summaryrefslogtreecommitdiffstats
path: root/src/core
diff options
context:
space:
mode:
Diffstat (limited to 'src/core')
-rw-r--r--src/core/CMakeLists.txt673
-rw-r--r--src/core/accessibility_activation_observer.cpp53
-rw-r--r--src/core/accessibility_activation_observer.h46
-rw-r--r--src/core/accessibility_tree_formatter_qt.cpp272
-rw-r--r--src/core/api/CMakeLists.txt222
-rw-r--r--src/core/api/Qt6WebEngineCoreDeploySupport.cmake173
-rw-r--r--src/core/api/Qt6WebEngineCoreMacros.cmake74
-rw-r--r--src/core/api/configure.cmake255
-rw-r--r--src/core/api/core_api.pro80
-rw-r--r--src/core/api/qt_cmdline.cmake34
-rw-r--r--src/core/api/qtwebenginecoreglobal.cpp189
-rw-r--r--src/core/api/qtwebenginecoreglobal.h49
-rw-r--r--src/core/api/qtwebenginecoreglobal_p.h55
-rw-r--r--src/core/api/qwebenginecallback.h101
-rw-r--r--src/core/api/qwebenginecallback_p.h253
-rw-r--r--src/core/api/qwebenginecertificateerror.cpp162
-rw-r--r--src/core/api/qwebenginecertificateerror.h78
-rw-r--r--src/core/api/qwebengineclientcertificateselection.cpp88
-rw-r--r--src/core/api/qwebengineclientcertificateselection.h44
-rw-r--r--src/core/api/qwebengineclientcertificatestore.cpp63
-rw-r--r--src/core/api/qwebengineclientcertificatestore.h54
-rw-r--r--src/core/api/qwebengineclienthints.cpp211
-rw-r--r--src/core/api/qwebengineclienthints.h72
-rw-r--r--src/core/api/qwebenginecontextmenurequest.cpp260
-rw-r--r--src/core/api/qwebenginecontextmenurequest.h136
-rw-r--r--src/core/api/qwebenginecontextmenurequest_p.h57
-rw-r--r--src/core/api/qwebenginecookiestore.cpp109
-rw-r--r--src/core/api/qwebenginecookiestore.h47
-rw-r--r--src/core/api/qwebenginecookiestore_p.h59
-rw-r--r--src/core/api/qwebenginedesktopmediarequest.cpp206
-rw-r--r--src/core/api/qwebenginedesktopmediarequest.h59
-rw-r--r--src/core/api/qwebenginedesktopmediarequest_p.h49
-rw-r--r--src/core/api/qwebenginedownloadrequest.cpp637
-rw-r--r--src/core/api/qwebenginedownloadrequest.h139
-rw-r--r--src/core/api/qwebenginedownloadrequest_p.h68
-rw-r--r--src/core/api/qwebenginefilesystemaccessrequest.cpp126
-rw-r--r--src/core/api/qwebenginefilesystemaccessrequest.h70
-rw-r--r--src/core/api/qwebenginefindtextresult.cpp40
-rw-r--r--src/core/api/qwebenginefindtextresult.h47
-rw-r--r--src/core/api/qwebengineframe.cpp118
-rw-r--r--src/core/api/qwebengineframe.h49
-rw-r--r--src/core/api/qwebenginefullscreenrequest.cpp113
-rw-r--r--src/core/api/qwebenginefullscreenrequest.h46
-rw-r--r--src/core/api/qwebengineglobalsettings.cpp125
-rw-r--r--src/core/api/qwebengineglobalsettings.h30
-rw-r--r--src/core/api/qwebengineglobalsettings_p.h44
-rw-r--r--src/core/api/qwebenginehistory.cpp389
-rw-r--r--src/core/api/qwebenginehistory.h136
-rw-r--r--src/core/api/qwebenginehistory_p.h99
-rw-r--r--src/core/api/qwebenginehttprequest.cpp60
-rw-r--r--src/core/api/qwebenginehttprequest.h52
-rw-r--r--src/core/api/qwebengineloadinginfo.cpp180
-rw-r--r--src/core/api/qwebengineloadinginfo.h82
-rw-r--r--src/core/api/qwebenginemessagepumpscheduler.cpp51
-rw-r--r--src/core/api/qwebenginemessagepumpscheduler_p.h46
-rw-r--r--src/core/api/qwebenginenavigationrequest.cpp206
-rw-r--r--src/core/api/qwebenginenavigationrequest.h78
-rw-r--r--src/core/api/qwebenginenewwindowrequest.cpp157
-rw-r--r--src/core/api/qwebenginenewwindowrequest.h62
-rw-r--r--src/core/api/qwebenginenewwindowrequest_p.h48
-rw-r--r--src/core/api/qwebenginenotification.cpp42
-rw-r--r--src/core/api/qwebenginenotification.h51
-rw-r--r--src/core/api/qwebenginepage.cpp2548
-rw-r--r--src/core/api/qwebenginepage.h405
-rw-r--r--src/core/api/qwebenginepage_p.h225
-rw-r--r--src/core/api/qwebengineprofile.cpp947
-rw-r--r--src/core/api/qwebengineprofile.h133
-rw-r--r--src/core/api/qwebengineprofile_p.h75
-rw-r--r--src/core/api/qwebenginequotarequest.cpp83
-rw-r--r--src/core/api/qwebenginequotarequest.h64
-rw-r--r--src/core/api/qwebengineregisterprotocolhandlerrequest.cpp46
-rw-r--r--src/core/api/qwebengineregisterprotocolhandlerrequest.h46
-rw-r--r--src/core/api/qwebenginescript.cpp283
-rw-r--r--src/core/api/qwebenginescript.h91
-rw-r--r--src/core/api/qwebenginescriptcollection.cpp179
-rw-r--r--src/core/api/qwebenginescriptcollection.h44
-rw-r--r--src/core/api/qwebenginescriptcollection_p.h51
-rw-r--r--src/core/api/qwebenginesettings.cpp121
-rw-r--r--src/core/api/qwebenginesettings.h127
-rw-r--r--src/core/api/qwebengineurlrequestinfo.cpp135
-rw-r--r--src/core/api/qwebengineurlrequestinfo.h61
-rw-r--r--src/core/api/qwebengineurlrequestinfo_p.h57
-rw-r--r--src/core/api/qwebengineurlrequestinterceptor.cpp11
-rw-r--r--src/core/api/qwebengineurlrequestinterceptor.h49
-rw-r--r--src/core/api/qwebengineurlrequestjob.cpp73
-rw-r--r--src/core/api/qwebengineurlrequestjob.h46
-rw-r--r--src/core/api/qwebengineurlscheme.cpp61
-rw-r--r--src/core/api/qwebengineurlscheme.h44
-rw-r--r--src/core/api/qwebengineurlschemehandler.cpp75
-rw-r--r--src/core/api/qwebengineurlschemehandler.h49
-rw-r--r--src/core/api/qwebenginewebauthuxrequest.cpp427
-rw-r--r--src/core/api/qwebenginewebauthuxrequest.h117
-rw-r--r--src/core/api/qwebenginewebauthuxrequest_p.h43
-rw-r--r--src/core/authentication_dialog_controller.cpp43
-rw-r--r--src/core/authentication_dialog_controller.h45
-rw-r--r--src/core/authentication_dialog_controller_p.h40
-rw-r--r--src/core/authenticator_request_client_delegate_qt.cpp247
-rw-r--r--src/core/authenticator_request_client_delegate_qt.h96
-rw-r--r--src/core/authenticator_request_dialog_controller.cpp302
-rw-r--r--src/core/authenticator_request_dialog_controller.h53
-rw-r--r--src/core/authenticator_request_dialog_controller_p.h78
-rw-r--r--src/core/autofill_client_qt.cpp147
-rw-r--r--src/core/autofill_client_qt.h76
-rw-r--r--src/core/autofill_popup_controller.cpp113
-rw-r--r--src/core/autofill_popup_controller.h62
-rw-r--r--src/core/autofill_popup_controller_p.h40
-rw-r--r--src/core/browser_accessibility_manager_qt.cpp133
-rw-r--r--src/core/browser_accessibility_manager_qt.h69
-rw-r--r--src/core/browser_accessibility_qt.cpp693
-rw-r--r--src/core/browser_accessibility_qt.h152
-rw-r--r--src/core/browser_main_parts_qt.cpp255
-rw-r--r--src/core/browser_main_parts_qt.h65
-rw-r--r--src/core/browser_message_filter_qt.cpp151
-rw-r--r--src/core/browser_message_filter_qt.h101
-rw-r--r--src/core/browsing_data_remover_delegate_qt.cpp60
-rw-r--r--src/core/browsing_data_remover_delegate_qt.h57
-rw-r--r--src/core/build_config_qt.h40
-rw-r--r--src/core/certificate_error_controller.cpp247
-rw-r--r--src/core/certificate_error_controller.h132
-rw-r--r--src/core/certificate_error_controller_p.h79
-rw-r--r--src/core/chromium_overrides.cpp255
-rw-r--r--src/core/client_cert_select_controller.cpp66
-rw-r--r--src/core/client_cert_select_controller.h58
-rw-r--r--src/core/client_hints.cpp177
-rw-r--r--src/core/client_hints.h102
-rw-r--r--src/core/clipboard_change_observer.h49
-rw-r--r--src/core/clipboard_qt.cpp363
-rw-r--r--src/core/clipboard_qt.h105
-rw-r--r--src/core/clipboard_util_win.cpp115
-rw-r--r--src/core/color_chooser_controller.cpp43
-rw-r--r--src/core/color_chooser_controller.h47
-rw-r--r--src/core/color_chooser_controller_p.h44
-rw-r--r--src/core/color_chooser_qt.cpp46
-rw-r--r--src/core/color_chooser_qt.h48
-rw-r--r--src/core/common/extensions/api/qtwebengine_extensions_features.gni25
-rw-r--r--src/core/common/extensions/extensions_api_provider_qt.cpp61
-rw-r--r--src/core/common/extensions/extensions_api_provider_qt.h44
-rw-r--r--src/core/common/extensions/extensions_client_qt.cpp60
-rw-r--r--src/core/common/extensions/extensions_client_qt.h57
-rw-r--r--src/core/common/qt_ipc_logging.cpp48
-rw-r--r--src/core/common/qt_messages.cpp3
-rw-r--r--src/core/common/qt_messages.h96
-rw-r--r--src/core/common/user_script_data.cpp49
-rw-r--r--src/core/common/user_script_data.h74
-rw-r--r--src/core/compositor/compositor.cpp75
-rw-r--r--src/core/compositor/compositor.h92
-rw-r--r--src/core/compositor/compositor_resource_fence.cpp51
-rw-r--r--src/core/compositor/compositor_resource_fence.h40
-rw-r--r--src/core/compositor/content_gpu_client_qt.cpp49
-rw-r--r--src/core/compositor/content_gpu_client_qt.h50
-rw-r--r--src/core/compositor/display_gl_output_surface.cpp341
-rw-r--r--src/core/compositor/display_gl_output_surface.h153
-rw-r--r--src/core/compositor/display_overrides.cpp153
-rw-r--r--src/core/compositor/display_skia_output_device.cpp240
-rw-r--r--src/core/compositor/display_skia_output_device.h89
-rw-r--r--src/core/compositor/display_software_output_surface.cpp105
-rw-r--r--src/core/compositor/display_software_output_surface.h46
-rw-r--r--src/core/compositor/native_skia_output_device.cpp422
-rw-r--r--src/core/compositor/native_skia_output_device.h183
-rw-r--r--src/core/compositor/native_skia_output_device_direct3d11.cpp88
-rw-r--r--src/core/compositor/native_skia_output_device_direct3d11.h28
-rw-r--r--src/core/compositor/native_skia_output_device_mac.mm97
-rw-r--r--src/core/compositor/native_skia_output_device_metal.cpp66
-rw-r--r--src/core/compositor/native_skia_output_device_metal.h31
-rw-r--r--src/core/compositor/native_skia_output_device_opengl.cpp86
-rw-r--r--src/core/compositor/native_skia_output_device_opengl.h28
-rw-r--r--src/core/compositor/native_skia_output_device_vulkan.cpp306
-rw-r--r--src/core/compositor/native_skia_output_device_vulkan.h28
-rw-r--r--src/core/compositor/vulkan_implementation_qt.cpp162
-rw-r--r--src/core/compositor/vulkan_implementation_qt.h46
-rw-r--r--src/core/config/common.pri50
-rw-r--r--src/core/config/linux.pri47
-rw-r--r--src/core/config/mac_osx.pri8
-rw-r--r--src/core/config/windows.pri8
-rw-r--r--src/core/configure.json313
-rw-r--r--src/core/configure/BUILD.root.gn.in779
-rw-r--r--src/core/content_browser_client_qt.cpp1166
-rw-r--r--src/core/content_browser_client_qt.h210
-rw-r--r--src/core/content_client_qt.cpp369
-rw-r--r--src/core/content_client_qt.h57
-rw-r--r--src/core/content_main_delegate_qt.cpp149
-rw-r--r--src/core/content_main_delegate_qt.h45
-rw-r--r--src/core/content_utility_client_qt.cpp65
-rw-r--r--src/core/content_utility_client_qt.h42
-rw-r--r--src/core/core.pro48
-rw-r--r--src/core/core_chromium.pri347
-rw-r--r--src/core/core_common.pri20
-rw-r--r--src/core/core_generator.pro7
-rw-r--r--src/core/core_gn_config.pri17
-rw-r--r--src/core/core_headers.pro6
-rw-r--r--src/core/core_module.pro163
-rw-r--r--src/core/core_project.pro28
-rw-r--r--src/core/custom_handlers/protocol_handler_registry_delegate_qt.cpp36
-rw-r--r--src/core/custom_handlers/protocol_handler_registry_delegate_qt.h35
-rw-r--r--src/core/custom_handlers/protocol_handler_registry_factory.cpp75
-rw-r--r--src/core/custom_handlers/protocol_handler_registry_factory.h57
-rw-r--r--src/core/custom_handlers/register_protocol_handler_request_controller.h26
-rw-r--r--src/core/custom_handlers/register_protocol_handler_request_controller_impl.cpp49
-rw-r--r--src/core/custom_handlers/register_protocol_handler_request_controller_impl.h38
-rw-r--r--src/core/delegated_frame_host_client_qt.cpp51
-rw-r--r--src/core/delegated_frame_host_client_qt.h46
-rw-r--r--src/core/desktop_media_controller.cpp244
-rw-r--r--src/core/desktop_media_controller.h65
-rw-r--r--src/core/desktop_media_controller_p.h28
-rw-r--r--src/core/desktop_screen_qt.cpp195
-rw-r--r--src/core/desktop_screen_qt.h72
-rw-r--r--src/core/devtools_frontend_qt.cpp542
-rw-r--r--src/core/devtools_frontend_qt.h138
-rw-r--r--src/core/devtools_manager_delegate_qt.cpp61
-rw-r--r--src/core/devtools_manager_delegate_qt.h40
-rw-r--r--src/core/doc/QtWebEngineDoc3
-rw-r--r--src/core/doc/about_credits.tmpl1
-rw-r--r--src/core/doc/about_credits_entry.tmpl13
-rw-r--r--src/core/doc/qtwebengine.qdocconf96
-rw-r--r--src/core/doc/snippets/qtwebengine_qwebenginepage_snippet.cpp14
-rw-r--r--src/core/doc/snippets/qtwebenginecore_build_snippet.qdoc36
-rw-r--r--src/core/doc/src/external-resources.qdoc138
-rw-r--r--src/core/doc/src/qt6-changes.qdoc131
-rw-r--r--src/core/doc/src/qt_webengine_add_convert_dictionary.qdoc54
-rw-r--r--src/core/doc/src/qtwebengine-debugging.qdoc112
-rw-r--r--src/core/doc/src/qtwebengine-deploying.qdoc199
-rw-r--r--src/core/doc/src/qtwebengine-features.qdoc777
-rw-r--r--src/core/doc/src/qtwebengine-global.qdoc56
-rw-r--r--src/core/doc/src/qtwebengine-index.qdoc47
-rw-r--r--src/core/doc/src/qtwebengine-modules.qdoc25
-rw-r--r--src/core/doc/src/qtwebengine-overview.qdoc307
-rw-r--r--src/core/doc/src/qtwebengine-platform-notes.qdoc223
-rw-r--r--src/core/doc/src/qtwebenginecore-index.qdoc43
-rw-r--r--src/core/doc/src/qtwebenginecore-module.qdoc49
-rw-r--r--src/core/doc/src/qwebengine-licensing.qdoc34
-rw-r--r--src/core/doc/src/qwebenginehistory_lgpl.qdoc272
-rw-r--r--src/core/doc/src/qwebenginepage_lgpl.qdoc838
-rw-r--r--src/core/doc/src/qwebenginesettings_lgpl.qdoc332
-rw-r--r--src/core/download_manager_delegate_qt.cpp202
-rw-r--r--src/core/download_manager_delegate_qt.h61
-rw-r--r--src/core/extensions/component_extension_resource_manager_qt.cpp83
-rw-r--r--src/core/extensions/component_extension_resource_manager_qt.h48
-rw-r--r--src/core/extensions/extension_host_delegate_qt.cpp116
-rw-r--r--src/core/extensions/extension_host_delegate_qt.h39
-rw-r--r--src/core/extensions/extension_system_factory_qt.cpp41
-rw-r--r--src/core/extensions/extension_system_factory_qt.h43
-rw-r--r--src/core/extensions/extension_system_qt.cpp240
-rw-r--r--src/core/extensions/extension_system_qt.h89
-rw-r--r--src/core/extensions/extension_web_contents_observer_qt.cpp54
-rw-r--r--src/core/extensions/extension_web_contents_observer_qt.h41
-rw-r--r--src/core/extensions/extensions_api_client_qt.cpp73
-rw-r--r--src/core/extensions/extensions_api_client_qt.h51
-rw-r--r--src/core/extensions/extensions_browser_client_qt.cpp258
-rw-r--r--src/core/extensions/extensions_browser_client_qt.h72
-rw-r--r--src/core/extensions/file_system_delegate_qt.cpp146
-rw-r--r--src/core/extensions/file_system_delegate_qt.h89
-rw-r--r--src/core/extensions/messaging_delegate_qt.cpp20
-rw-r--r--src/core/extensions/messaging_delegate_qt.h30
-rw-r--r--src/core/extensions/mime_handler_view_guest_delegate_qt.cpp76
-rw-r--r--src/core/extensions/mime_handler_view_guest_delegate_qt.h51
-rw-r--r--src/core/extensions/pdf_iframe_navigation_throttle_qt.cpp194
-rw-r--r--src/core/extensions/pdf_iframe_navigation_throttle_qt.h46
-rw-r--r--src/core/extensions/pdf_web_contents_helper_client_qt.h30
-rw-r--r--src/core/extensions/plugin_service_filter_qt.cpp64
-rw-r--r--src/core/extensions/plugin_service_filter_qt.h33
-rw-r--r--src/core/favicon_driver_qt.cpp422
-rw-r--r--src/core/favicon_driver_qt.h151
-rw-r--r--src/core/favicon_manager.cpp418
-rw-r--r--src/core/favicon_manager.h151
-rw-r--r--src/core/favicon_service_factory_qt.cpp163
-rw-r--r--src/core/favicon_service_factory_qt.h111
-rw-r--r--src/core/file_picker_controller.cpp173
-rw-r--r--src/core/file_picker_controller.h66
-rw-r--r--src/core/file_system_access/file_system_access_permission_context_factory_qt.cpp61
-rw-r--r--src/core/file_system_access/file_system_access_permission_context_factory_qt.h37
-rw-r--r--src/core/file_system_access/file_system_access_permission_context_qt.cpp479
-rw-r--r--src/core/file_system_access/file_system_access_permission_context_qt.h86
-rw-r--r--src/core/file_system_access/file_system_access_permission_grant_qt.cpp146
-rw-r--r--src/core/file_system_access/file_system_access_permission_grant_qt.h59
-rw-r--r--src/core/file_system_access/file_system_access_permission_request_controller.h39
-rw-r--r--src/core/file_system_access/file_system_access_permission_request_controller_impl.cpp48
-rw-r--r--src/core/file_system_access/file_system_access_permission_request_controller_impl.h32
-rw-r--r--src/core/file_system_access/file_system_access_permission_request_manager_qt.cpp195
-rw-r--r--src/core/file_system_access/file_system_access_permission_request_manager_qt.h79
-rw-r--r--src/core/find_text_helper.cpp71
-rw-r--r--src/core/find_text_helper.h57
-rw-r--r--src/core/global_descriptors_qt.h40
-rw-r--r--src/core/gn_run.pro68
-rw-r--r--src/core/javascript_dialog_controller.cpp42
-rw-r--r--src/core/javascript_dialog_controller.h42
-rw-r--r--src/core/javascript_dialog_controller_p.h45
-rw-r--r--src/core/javascript_dialog_manager_qt.cpp48
-rw-r--r--src/core/javascript_dialog_manager_qt.h45
-rw-r--r--src/core/location_provider_qt.cpp151
-rw-r--r--src/core/location_provider_qt.h55
-rw-r--r--src/core/login_delegate_qt.cpp60
-rw-r--r--src/core/login_delegate_qt.h40
-rw-r--r--src/core/media_capture_devices_dispatcher.cpp439
-rw-r--r--src/core/media_capture_devices_dispatcher.h88
-rw-r--r--src/core/native_web_keyboard_event_qt.cpp112
-rw-r--r--src/core/native_web_keyboard_event_qt.h20
-rw-r--r--src/core/native_web_keyboard_event_qt_mac.mm155
-rw-r--r--src/core/net/client_cert_override.cpp176
-rw-r--r--src/core/net/client_cert_override.h73
-rw-r--r--src/core/net/client_cert_qt.cpp148
-rw-r--r--src/core/net/client_cert_qt.h37
-rw-r--r--src/core/net/client_cert_store_data.cpp60
-rw-r--r--src/core/net/client_cert_store_data.h48
-rw-r--r--src/core/net/cookie_monster_delegate_qt.cpp144
-rw-r--r--src/core/net/cookie_monster_delegate_qt.h75
-rw-r--r--src/core/net/custom_url_loader_factory.cpp244
-rw-r--r--src/core/net/custom_url_loader_factory.h44
-rw-r--r--src/core/net/plugin_response_interceptor_url_loader_throttle.cpp248
-rw-r--r--src/core/net/plugin_response_interceptor_url_loader_throttle.h61
-rw-r--r--src/core/net/proxy_config_monitor.cpp52
-rw-r--r--src/core/net/proxy_config_monitor.h50
-rw-r--r--src/core/net/proxy_config_service_qt.cpp57
-rw-r--r--src/core/net/proxy_config_service_qt.h48
-rw-r--r--src/core/net/proxying_restricted_cookie_manager_qt.cpp151
-rw-r--r--src/core/net/proxying_restricted_cookie_manager_qt.h79
-rw-r--r--src/core/net/proxying_url_loader_factory_qt.cpp454
-rw-r--r--src/core/net/proxying_url_loader_factory_qt.h68
-rw-r--r--src/core/net/qrc_url_scheme_handler.cpp49
-rw-r--r--src/core/net/qrc_url_scheme_handler.h40
-rw-r--r--src/core/net/resource_request_body_qt.cpp181
-rw-r--r--src/core/net/resource_request_body_qt.h70
-rw-r--r--src/core/net/ssl_host_state_delegate_qt.cpp81
-rw-r--r--src/core/net/ssl_host_state_delegate_qt.h55
-rw-r--r--src/core/net/system_network_context_manager.cpp295
-rw-r--r--src/core/net/system_network_context_manager.h89
-rw-r--r--src/core/net/url_request_custom_job_delegate.cpp77
-rw-r--r--src/core/net/url_request_custom_job_delegate.h61
-rw-r--r--src/core/net/url_request_custom_job_proxy.cpp82
-rw-r--r--src/core/net/url_request_custom_job_proxy.h63
-rw-r--r--src/core/net/version_ui_qt.cpp56
-rw-r--r--src/core/net/version_ui_qt.h32
-rw-r--r--src/core/net/webui_controller_factory_qt.cpp110
-rw-r--r--src/core/net/webui_controller_factory_qt.h52
-rw-r--r--src/core/ozone/BUILD.gn17
-rw-r--r--src/core/ozone/gl_context_qt.cpp319
-rw-r--r--src/core/ozone/gl_context_qt.h89
-rw-r--r--src/core/ozone/gl_ozone_egl_qt.cpp163
-rw-r--r--src/core/ozone/gl_ozone_egl_qt.h63
-rw-r--r--src/core/ozone/gl_ozone_glx_qt.cpp83
-rw-r--r--src/core/ozone/gl_ozone_glx_qt.h67
-rw-r--r--src/core/ozone/gl_share_context_qt.cpp77
-rw-r--r--src/core/ozone/gl_share_context_qt.h63
-rw-r--r--src/core/ozone/gl_surface_egl_qt.cpp212
-rw-r--r--src/core/ozone/gl_surface_egl_qt.h58
-rw-r--r--src/core/ozone/gl_surface_glx_qt.cpp137
-rw-r--r--src/core/ozone/gl_surface_glx_qt.h49
-rw-r--r--src/core/ozone/gl_surface_qt.cpp188
-rw-r--r--src/core/ozone/gl_surface_qt.h59
-rw-r--r--src/core/ozone/gl_surface_wgl_qt.cpp56
-rw-r--r--src/core/ozone/gl_surface_wgl_qt.h49
-rw-r--r--src/core/ozone/ozone_extra.gni14
-rw-r--r--src/core/ozone/ozone_platform_qt.cpp223
-rw-r--r--src/core/ozone/ozone_platform_qt.h48
-rw-r--r--src/core/ozone/platform_window_qt.cpp70
-rw-r--r--src/core/ozone/platform_window_qt.h63
-rw-r--r--src/core/ozone/surface_factory_qt.cpp293
-rw-r--r--src/core/ozone/surface_factory_qt.h72
-rw-r--r--src/core/pdf_util_qt.cpp92
-rw-r--r--src/core/pdf_util_qt.h34
-rw-r--r--src/core/permission_manager_qt.cpp273
-rw-r--r--src/core/permission_manager_qt.h97
-rw-r--r--src/core/platform_notification_service_qt.cpp45
-rw-r--r--src/core/platform_notification_service_qt.h41
-rw-r--r--src/core/pointer_device_qt.cpp102
-rw-r--r--src/core/pref_service_adapter.cpp116
-rw-r--r--src/core/pref_service_adapter.h47
-rw-r--r--src/core/printing/pdf_document_helper_client_qt.cpp33
-rw-r--r--src/core/printing/pdf_document_helper_client_qt.h27
-rw-r--r--src/core/printing/pdf_stream_delegate_qt.cpp99
-rw-r--r--src/core/printing/pdf_stream_delegate_qt.h23
-rw-r--r--src/core/printing/pdfium_document_wrapper_qt.cpp40
-rw-r--r--src/core/printing/pdfium_document_wrapper_qt.h42
-rw-r--r--src/core/printing/print_view_manager_base_qt.cpp464
-rw-r--r--src/core/printing/print_view_manager_base_qt.h178
-rw-r--r--src/core/printing/print_view_manager_qt.cpp415
-rw-r--r--src/core/printing/print_view_manager_qt.h121
-rw-r--r--src/core/printing/printer_worker.cpp87
-rw-r--r--src/core/printing/printer_worker.h58
-rw-r--r--src/core/printing/printing_message_filter_qt.cpp234
-rw-r--r--src/core/printing/printing_message_filter_qt.h126
-rw-r--r--src/core/process_main.cpp67
-rw-r--r--src/core/process_main.h57
-rw-r--r--src/core/profile_adapter.cpp449
-rw-r--r--src/core/profile_adapter.h105
-rw-r--r--src/core/profile_adapter_client.cpp40
-rw-r--r--src/core/profile_adapter_client.h58
-rw-r--r--src/core/profile_io_data_qt.cpp174
-rw-r--r--src/core/profile_io_data_qt.h93
-rw-r--r--src/core/profile_qt.cpp167
-rw-r--r--src/core/profile_qt.h84
-rw-r--r--src/core/qtwebengine.gni75
-rw-r--r--src/core/qtwebengine_resources.gni140
-rw-r--r--src/core/qtwebengine_sources.gni194
-rw-r--r--src/core/quota_permission_context_qt.cpp110
-rw-r--r--src/core/quota_permission_context_qt.h61
-rw-r--r--src/core/quota_request_controller.h62
-rw-r--r--src/core/quota_request_controller_impl.cpp72
-rw-r--r--src/core/quota_request_controller_impl.h68
-rw-r--r--src/core/register_protocol_handler_request_controller.h62
-rw-r--r--src/core/register_protocol_handler_request_controller_impl.cpp83
-rw-r--r--src/core/register_protocol_handler_request_controller_impl.h73
-rw-r--r--src/core/render_view_context_menu_qt.cpp87
-rw-r--r--src/core/render_view_context_menu_qt.h50
-rw-r--r--src/core/render_widget_host_view_qt.cpp750
-rw-r--r--src/core/render_widget_host_view_qt.h171
-rw-r--r--src/core/render_widget_host_view_qt_delegate.h51
-rw-r--r--src/core/render_widget_host_view_qt_delegate_client.cpp380
-rw-r--r--src/core/render_widget_host_view_qt_delegate_client.h51
-rw-r--r--src/core/render_widget_host_view_qt_delegate_item.cpp455
-rw-r--r--src/core/render_widget_host_view_qt_delegate_item.h125
-rw-r--r--src/core/renderer/content_renderer_client_qt.cpp685
-rw-r--r--src/core/renderer/content_renderer_client_qt.h116
-rw-r--r--src/core/renderer/content_settings_observer_qt.cpp111
-rw-r--r--src/core/renderer/content_settings_observer_qt.h61
-rw-r--r--src/core/renderer/extensions/extensions_dispatcher_delegate_qt.cpp49
-rw-r--r--src/core/renderer/extensions/extensions_dispatcher_delegate_qt.h44
-rw-r--r--src/core/renderer/extensions/extensions_renderer_client_qt.cpp81
-rw-r--r--src/core/renderer/extensions/extensions_renderer_client_qt.h62
-rw-r--r--src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.cpp40
-rw-r--r--src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.h44
-rw-r--r--src/core/renderer/extensions/resource_request_policy_qt.cpp58
-rw-r--r--src/core/renderer/extensions/resource_request_policy_qt.h48
-rw-r--r--src/core/renderer/pepper/pepper_flash_renderer_host_qt.cpp432
-rw-r--r--src/core/renderer/pepper/pepper_flash_renderer_host_qt.h107
-rw-r--r--src/core/renderer/pepper/pepper_renderer_host_factory_qt.cpp97
-rw-r--r--src/core/renderer/pepper/pepper_renderer_host_factory_qt.h42
-rw-r--r--src/core/renderer/plugins/loadable_plugin_placeholder_qt.cpp55
-rw-r--r--src/core/renderer/plugins/loadable_plugin_placeholder_qt.h49
-rw-r--r--src/core/renderer/plugins/plugin_placeholder_qt.cpp75
-rw-r--r--src/core/renderer/plugins/plugin_placeholder_qt.h78
-rw-r--r--src/core/renderer/print_web_view_helper_delegate_qt.cpp72
-rw-r--r--src/core/renderer/print_web_view_helper_delegate_qt.h51
-rw-r--r--src/core/renderer/render_configuration.cpp41
-rw-r--r--src/core/renderer/render_configuration.h42
-rw-r--r--src/core/renderer/render_frame_observer_qt.cpp56
-rw-r--r--src/core/renderer/render_frame_observer_qt.h54
-rw-r--r--src/core/renderer/render_thread_observer_qt.cpp75
-rw-r--r--src/core/renderer/render_thread_observer_qt.h80
-rw-r--r--src/core/renderer/render_view_observer_qt.cpp94
-rw-r--r--src/core/renderer/render_view_observer_qt.h63
-rw-r--r--src/core/renderer/user_resource_controller.cpp325
-rw-r--r--src/core/renderer/user_resource_controller.h92
-rw-r--r--src/core/renderer/web_channel_ipc_transport.cpp162
-rw-r--r--src/core/renderer/web_channel_ipc_transport.h50
-rw-r--r--src/core/renderer/web_engine_page_render_frame.cpp66
-rw-r--r--src/core/renderer/web_engine_page_render_frame.h41
-rw-r--r--src/core/renderer_host/pepper/pepper_flash_browser_host_qt.cpp137
-rw-r--r--src/core/renderer_host/pepper/pepper_flash_browser_host_qt.h93
-rw-r--r--src/core/renderer_host/pepper/pepper_host_factory_qt.cpp113
-rw-r--r--src/core/renderer_host/pepper/pepper_host_factory_qt.h73
-rw-r--r--src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.cpp135
-rw-r--r--src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.h89
-rw-r--r--src/core/renderer_host/render_view_observer_host_qt.cpp95
-rw-r--r--src/core/renderer_host/render_view_observer_host_qt.h72
-rw-r--r--src/core/renderer_host/user_resource_controller_host.cpp125
-rw-r--r--src/core/renderer_host/user_resource_controller_host.h66
-rw-r--r--src/core/renderer_host/web_channel_ipc_transport_host.cpp118
-rw-r--r--src/core/renderer_host/web_channel_ipc_transport_host.h59
-rw-r--r--src/core/renderer_host/web_engine_page_host.cpp76
-rw-r--r--src/core/renderer_host/web_engine_page_host.h54
-rw-r--r--src/core/request_controller.h40
-rw-r--r--src/core/resource_bundle_qt.cpp76
-rw-r--r--src/core/resource_context_qt.cpp49
-rw-r--r--src/core/resource_context_qt.h76
-rw-r--r--src/core/sandbox_win.cpp46
-rw-r--r--src/core/select_file_dialog_factory_qt.cpp149
-rw-r--r--src/core/select_file_dialog_factory_qt.h46
-rw-r--r--src/core/tools/qwebengine_convert_dict/CMakeLists.txt37
-rw-r--r--src/core/tools/qwebengine_convert_dict/main.cpp254
-rw-r--r--src/core/tools/webenginedriver/CMakeLists.txt57
-rw-r--r--src/core/touch_handle_drawable_client.h46
-rw-r--r--src/core/touch_handle_drawable_qt.cpp123
-rw-r--r--src/core/touch_handle_drawable_qt.h51
-rw-r--r--src/core/touch_selection_controller_client_qt.cpp84
-rw-r--r--src/core/touch_selection_controller_client_qt.h52
-rw-r--r--src/core/touch_selection_menu_controller.cpp69
-rw-r--r--src/core/touch_selection_menu_controller.h57
-rw-r--r--src/core/type_conversion.cpp122
-rw-r--r--src/core/type_conversion.h162
-rw-r--r--src/core/user_notification_controller.cpp42
-rw-r--r--src/core/user_notification_controller.h48
-rw-r--r--src/core/user_script.cpp170
-rw-r--r--src/core/user_script.h63
-rw-r--r--src/core/visited_links_manager_qt.cpp64
-rw-r--r--src/core/visited_links_manager_qt.h46
-rw-r--r--src/core/web_contents_adapter.cpp738
-rw-r--r--src/core/web_contents_adapter.h103
-rw-r--r--src/core/web_contents_adapter_client.h367
-rw-r--r--src/core/web_contents_delegate_qt.cpp546
-rw-r--r--src/core/web_contents_delegate_qt.h149
-rw-r--r--src/core/web_contents_view_qt.cpp253
-rw-r--r--src/core/web_contents_view_qt.h87
-rw-r--r--src/core/web_engine_context.cpp940
-rw-r--r--src/core/web_engine_context.h76
-rw-r--r--src/core/web_engine_context_threads.cpp138
-rw-r--r--src/core/web_engine_error.cpp65
-rw-r--r--src/core/web_engine_error.h49
-rw-r--r--src/core/web_engine_library_info.cpp319
-rw-r--r--src/core/web_engine_library_info.h55
-rw-r--r--src/core/web_engine_settings.cpp393
-rw-r--r--src/core/web_engine_settings.h172
-rw-r--r--src/core/web_event_factory.cpp250
-rw-r--r--src/core/web_event_factory.h62
-rw-r--r--src/core/web_usb_detector_qt.cpp45
-rw-r--r--src/core/web_usb_detector_qt.h34
505 files changed, 38927 insertions, 25778 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
new file mode 100644
index 000000000..8ba77607b
--- /dev/null
+++ b/src/core/CMakeLists.txt
@@ -0,0 +1,673 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+cmake_minimum_required(VERSION 3.19)
+
+find_package(Ninja 1.7.2 REQUIRED)
+find_package(Nodejs 14.19 REQUIRED)
+find_package(Perl)
+find_package(PkgConfig)
+if(PkgConfig_FOUND)
+ create_pkg_config_host_wrapper(${CMAKE_CURRENT_BINARY_DIR})
+endif()
+
+set(buildDir "${CMAKE_CURRENT_BINARY_DIR}")
+
+add_subdirectory(api)
+add_subdirectory(tools/webenginedriver)
+add_subdirectory(tools/qwebengine_convert_dict)
+
+##
+# TOOLCHAIN SETUP
+##
+
+if(LINUX)
+ setup_toolchains()
+endif()
+
+##
+# GN BUILD SETUP
+##
+
+addSyncTargets(core)
+
+get_configs(configs)
+get_architectures(archs)
+
+foreach(arch ${archs})
+ foreach(config ${configs})
+
+ ##
+ # BUILD.gn SETUP
+ ##
+
+ set(buildGn core_${config}_${arch})
+ add_gn_target(${buildGn} ${config} ${arch}
+ SOURCES DEFINES CXX_COMPILE_OPTIONS C_COMPILE_OPTIONS INCLUDES MOC_PATH
+ )
+ resolve_target_includes(gnIncludes WebEngineCore)
+ get_forward_declaration_macro(forwardDeclarationMacro)
+ get_target_property(qtWebEngineProcessName WebEngineCore QTWEBENGINEPROCESS_NAME)
+
+ if("${config}" STREQUAL "Debug")
+ set(qtWebEngineProcessName "${qtWebEngineProcessName}${CMAKE_DEBUG_POSTFIX}")
+ endif()
+
+ set(gnCxxCompileOptions "")
+ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
+ # Silence warning in boringssl headers.
+ list(APPEND gnCxxCompileOptions -Wno-ignored-qualifiers)
+
+ if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL "11.0.0" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "11.2.0")
+ # GCC 11.1 has a regression in the integrated preprocessor, so disable it as a workaround (QTBUG-93360)
+ # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100796
+ list(APPEND gnCxxCompileOptions -no-integrated-cpp)
+ endif()
+ endif()
+
+ extend_gn_target(${buildGn}
+ INCLUDES
+ ${gnIncludes}
+ DEFINES
+ QT_NO_KEYWORDS
+ QT_USE_QSTRINGBUILDER
+ QTWEBENGINECORE_VERSION_STR=${QT_REPO_MODULE_VERSION}
+ QTWEBENGINEPROCESS_NAME=${qtWebEngineProcessName}
+ BUILDING_CHROMIUM
+ "${forwardDeclarationMacro}"
+ CXX_COMPILE_OPTIONS
+ ${gnCxxCompileOptions}
+ SOURCES
+ accessibility_tree_formatter_qt.cpp
+ browser_accessibility_qt.cpp browser_accessibility_qt.h
+ authentication_dialog_controller.cpp authentication_dialog_controller.h authentication_dialog_controller_p.h
+ autofill_client_qt.cpp autofill_client_qt.h
+ autofill_popup_controller.cpp autofill_popup_controller.h autofill_popup_controller_p.h
+ browser_accessibility_manager_qt.cpp browser_accessibility_manager_qt.h
+ browser_main_parts_qt.cpp browser_main_parts_qt.h
+ browser_message_filter_qt.cpp browser_message_filter_qt.h
+ browsing_data_remover_delegate_qt.cpp browsing_data_remover_delegate_qt.h
+ build_config_qt.h
+ certificate_error_controller.cpp certificate_error_controller.h
+ chromium_overrides.cpp
+ client_cert_select_controller.cpp client_cert_select_controller.h
+ client_hints.cpp client_hints.h
+ clipboard_change_observer.h
+ clipboard_qt.cpp clipboard_qt.h
+ color_chooser_controller.cpp color_chooser_controller.h color_chooser_controller_p.h
+ color_chooser_qt.cpp color_chooser_qt.h
+ common/qt_messages.cpp common/qt_messages.h
+ compositor/compositor.cpp compositor/compositor.h
+ compositor/content_gpu_client_qt.cpp compositor/content_gpu_client_qt.h
+ compositor/display_overrides.cpp
+ compositor/display_software_output_surface.cpp compositor/display_software_output_surface.h
+ compositor/native_skia_output_device.cpp compositor/native_skia_output_device.h
+ content_browser_client_qt.cpp content_browser_client_qt.h
+ content_client_qt.cpp content_client_qt.h
+ content_main_delegate_qt.cpp content_main_delegate_qt.h
+ content_utility_client_qt.cpp content_utility_client_qt.h
+ custom_handlers/protocol_handler_registry_delegate_qt.h custom_handlers/protocol_handler_registry_delegate_qt.cpp
+ custom_handlers/protocol_handler_registry_factory.h custom_handlers/protocol_handler_registry_factory.cpp
+ custom_handlers/register_protocol_handler_request_controller.h
+ custom_handlers/register_protocol_handler_request_controller_impl.cpp custom_handlers/register_protocol_handler_request_controller_impl.h
+ delegated_frame_host_client_qt.cpp delegated_frame_host_client_qt.h
+ desktop_media_controller.cpp desktop_media_controller.h desktop_media_controller_p.h
+ desktop_screen_qt.cpp desktop_screen_qt.h
+ devtools_frontend_qt.cpp devtools_frontend_qt.h
+ devtools_manager_delegate_qt.cpp devtools_manager_delegate_qt.h
+ download_manager_delegate_qt.cpp download_manager_delegate_qt.h
+ favicon_driver_qt.cpp favicon_driver_qt.h
+ favicon_service_factory_qt.cpp favicon_service_factory_qt.h
+ file_picker_controller.cpp file_picker_controller.h
+ file_system_access/file_system_access_permission_context_factory_qt.cpp file_system_access/file_system_access_permission_context_factory_qt.h
+ file_system_access/file_system_access_permission_context_qt.cpp file_system_access/file_system_access_permission_context_qt.h
+ file_system_access/file_system_access_permission_grant_qt.cpp file_system_access/file_system_access_permission_grant_qt.h
+ file_system_access/file_system_access_permission_request_controller.h
+ file_system_access/file_system_access_permission_request_controller_impl.cpp file_system_access/file_system_access_permission_request_controller_impl.h
+ file_system_access/file_system_access_permission_request_manager_qt.cpp file_system_access/file_system_access_permission_request_manager_qt.h
+ find_text_helper.cpp find_text_helper.h
+ global_descriptors_qt.h
+ javascript_dialog_controller.cpp javascript_dialog_controller.h javascript_dialog_controller_p.h
+ javascript_dialog_manager_qt.cpp javascript_dialog_manager_qt.h
+ login_delegate_qt.cpp login_delegate_qt.h
+ media_capture_devices_dispatcher.cpp media_capture_devices_dispatcher.h
+ native_web_keyboard_event_qt.cpp native_web_keyboard_event_qt.h
+ net/client_cert_qt.cpp net/client_cert_qt.h
+ net/client_cert_store_data.cpp net/client_cert_store_data.h
+ net/cookie_monster_delegate_qt.cpp net/cookie_monster_delegate_qt.h
+ net/custom_url_loader_factory.cpp net/custom_url_loader_factory.h
+ net/proxy_config_monitor.cpp net/proxy_config_monitor.h
+ net/proxy_config_service_qt.cpp net/proxy_config_service_qt.h
+ net/proxying_restricted_cookie_manager_qt.cpp net/proxying_restricted_cookie_manager_qt.h
+ net/proxying_url_loader_factory_qt.cpp net/proxying_url_loader_factory_qt.h
+ net/qrc_url_scheme_handler.cpp net/qrc_url_scheme_handler.h
+ net/resource_request_body_qt.cpp net/resource_request_body_qt.h
+ net/ssl_host_state_delegate_qt.cpp net/ssl_host_state_delegate_qt.h
+ net/system_network_context_manager.cpp net/system_network_context_manager.h
+ net/url_request_custom_job_delegate.cpp net/url_request_custom_job_delegate.h
+ net/url_request_custom_job_proxy.cpp net/url_request_custom_job_proxy.h
+ net/version_ui_qt.cpp net/version_ui_qt.h
+ net/webui_controller_factory_qt.cpp net/webui_controller_factory_qt.h
+ ozone/gl_context_qt.cpp ozone/gl_context_qt.h
+ ozone/gl_ozone_egl_qt.cpp ozone/gl_ozone_egl_qt.h
+ ozone/gl_share_context_qt.cpp ozone/gl_share_context_qt.h
+ ozone/gl_surface_egl_qt.cpp ozone/gl_surface_egl_qt.h
+ ozone/gl_surface_qt.cpp ozone/gl_surface_qt.h
+ ozone/gl_surface_wgl_qt.cpp ozone/gl_surface_wgl_qt.h
+ ozone/platform_window_qt.cpp ozone/platform_window_qt.h
+ ozone/surface_factory_qt.cpp ozone/surface_factory_qt.h
+ permission_manager_qt.cpp permission_manager_qt.h
+ pdf_util_qt.cpp pdf_util_qt.h
+ platform_notification_service_qt.cpp platform_notification_service_qt.h
+ pointer_device_qt.cpp
+ pref_service_adapter.cpp pref_service_adapter.h
+ process_main.cpp
+ profile_adapter.cpp profile_adapter.h
+ profile_adapter_client.cpp profile_adapter_client.h
+ profile_io_data_qt.cpp profile_io_data_qt.h
+ profile_qt.cpp profile_qt.h
+ render_view_context_menu_qt.cpp render_view_context_menu_qt.h
+ render_widget_host_view_qt.cpp render_widget_host_view_qt.h
+ render_widget_host_view_qt_delegate.h
+ render_widget_host_view_qt_delegate_client.cpp render_widget_host_view_qt_delegate_client.h
+ render_widget_host_view_qt_delegate_item.cpp render_widget_host_view_qt_delegate_item.h
+ renderer/content_renderer_client_qt.cpp renderer/content_renderer_client_qt.h
+ renderer/content_settings_observer_qt.cpp renderer/content_settings_observer_qt.h
+ renderer/render_configuration.cpp renderer/render_configuration.h
+ renderer/render_frame_observer_qt.cpp renderer/render_frame_observer_qt.h
+ renderer/user_resource_controller.cpp renderer/user_resource_controller.h
+ renderer/web_engine_page_render_frame.cpp renderer/web_engine_page_render_frame.h
+ renderer_host/user_resource_controller_host.cpp renderer_host/user_resource_controller_host.h
+ renderer_host/web_engine_page_host.cpp renderer_host/web_engine_page_host.h
+ request_controller.h
+ resource_bundle_qt.cpp
+ select_file_dialog_factory_qt.cpp select_file_dialog_factory_qt.h
+ touch_handle_drawable_client.h
+ touch_handle_drawable_qt.cpp touch_handle_drawable_qt.h
+ touch_selection_controller_client_qt.cpp touch_selection_controller_client_qt.h
+ touch_selection_menu_controller.cpp touch_selection_menu_controller.h
+ type_conversion.cpp type_conversion.h
+ user_notification_controller.cpp user_notification_controller.h
+ user_script.cpp user_script.h
+ visited_links_manager_qt.cpp visited_links_manager_qt.h
+ web_contents_adapter.cpp web_contents_adapter.h
+ web_contents_adapter_client.h
+ web_contents_delegate_qt.cpp web_contents_delegate_qt.h
+ web_contents_view_qt.cpp web_contents_view_qt.h
+ web_engine_context.cpp web_engine_context.h
+ web_engine_error.cpp web_engine_error.h
+ web_engine_library_info.cpp web_engine_library_info.h
+ web_engine_settings.cpp web_engine_settings.h
+ web_event_factory.cpp web_event_factory.h
+ web_usb_detector_qt.cpp web_usb_detector_qt.h
+ authenticator_request_client_delegate_qt.cpp authenticator_request_client_delegate_qt.h
+ authenticator_request_dialog_controller.cpp authenticator_request_dialog_controller.h authenticator_request_dialog_controller_p.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_accessibility
+ SOURCES
+ accessibility_activation_observer.cpp accessibility_activation_observer.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_ozone_x11
+ SOURCES
+ ozone/gl_ozone_glx_qt.cpp ozone/gl_ozone_glx_qt.h
+ ozone/gl_surface_glx_qt.cpp ozone/gl_surface_glx_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_vulkan
+ SOURCES
+ compositor/native_skia_output_device_vulkan.cpp compositor/native_skia_output_device_vulkan.h
+ compositor/vulkan_implementation_qt.cpp compositor/vulkan_implementation_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_opengl
+ SOURCES
+ compositor/compositor_resource_fence.cpp compositor/compositor_resource_fence.h
+ compositor/display_skia_output_device.cpp compositor/display_skia_output_device.h
+ compositor/native_skia_output_device_opengl.cpp compositor/native_skia_output_device_opengl.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION MACOS
+ SOURCES
+ native_web_keyboard_event_qt_mac.mm
+ compositor/native_skia_output_device_mac.mm
+ compositor/native_skia_output_device_metal.cpp compositor/native_skia_output_device_metal.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_pepper_plugins
+ SOURCES
+ renderer/pepper/pepper_renderer_host_factory_qt.cpp renderer/pepper/pepper_renderer_host_factory_qt.h
+ renderer/plugins/loadable_plugin_placeholder_qt.cpp renderer/plugins/loadable_plugin_placeholder_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_printing_and_pdf
+ SOURCES
+ printing/pdfium_document_wrapper_qt.cpp printing/pdfium_document_wrapper_qt.h
+ printing/print_view_manager_base_qt.cpp printing/print_view_manager_base_qt.h
+ printing/print_view_manager_qt.cpp printing/print_view_manager_qt.h
+ printing/printer_worker.cpp printing/printer_worker.h
+ renderer/print_web_view_helper_delegate_qt.cpp renderer/print_web_view_helper_delegate_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_geolocation
+ SOURCES
+ location_provider_qt.cpp location_provider_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_webchannel
+ SOURCES
+ renderer/web_channel_ipc_transport.cpp renderer/web_channel_ipc_transport.h
+ renderer_host/web_channel_ipc_transport_host.cpp renderer_host/web_channel_ipc_transport_host.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_extensions
+ SOURCES
+ common/extensions/extensions_api_provider_qt.cpp common/extensions/extensions_api_provider_qt.h
+ common/extensions/extensions_client_qt.cpp common/extensions/extensions_client_qt.h
+ extensions/component_extension_resource_manager_qt.cpp extensions/component_extension_resource_manager_qt.h
+ extensions/extension_host_delegate_qt.cpp extensions/extension_host_delegate_qt.h
+ extensions/extension_system_factory_qt.cpp extensions/extension_system_factory_qt.h
+ extensions/extension_system_qt.cpp extensions/extension_system_qt.h
+ extensions/extension_web_contents_observer_qt.cpp extensions/extension_web_contents_observer_qt.h
+ extensions/extensions_api_client_qt.cpp extensions/extensions_api_client_qt.h
+ extensions/extensions_browser_client_qt.cpp extensions/extensions_browser_client_qt.h
+ extensions/file_system_delegate_qt.cpp extensions/file_system_delegate_qt.h
+ extensions/messaging_delegate_qt.cpp extensions/messaging_delegate_qt.h
+ extensions/mime_handler_view_guest_delegate_qt.cpp extensions/mime_handler_view_guest_delegate_qt.h
+ extensions/plugin_service_filter_qt.cpp extensions/plugin_service_filter_qt.h
+ net/plugin_response_interceptor_url_loader_throttle.cpp net/plugin_response_interceptor_url_loader_throttle.h
+ renderer/extensions/extensions_dispatcher_delegate_qt.cpp renderer/extensions/extensions_dispatcher_delegate_qt.h
+ renderer/extensions/extensions_renderer_client_qt.cpp renderer/extensions/extensions_renderer_client_qt.h
+ renderer/extensions/renderer_permissions_policy_delegate_qt.cpp renderer/extensions/renderer_permissions_policy_delegate_qt.h
+ renderer/extensions/resource_request_policy_qt.cpp renderer/extensions/resource_request_policy_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION QT_FEATURE_webengine_extensions AND QT_FEATURE_webengine_printing_and_pdf
+ SOURCES
+ extensions/pdf_iframe_navigation_throttle_qt.cpp extensions/pdf_iframe_navigation_throttle_qt.h
+ printing/pdf_stream_delegate_qt.cpp printing/pdf_stream_delegate_qt.h
+ printing/pdf_document_helper_client_qt.cpp printing/pdf_document_helper_client_qt.h
+ )
+
+ extend_gn_target(${buildGn} CONDITION WIN32
+ SOURCES
+ clipboard_util_win.cpp
+ compositor/native_skia_output_device_direct3d11.cpp compositor/native_skia_output_device_direct3d11.h
+ )
+
+ ##
+ # GN PARAMETERS SETUP
+ ##
+
+ unset(gnArgArg)
+
+ append_build_type_setup(gnArgArg)
+ append_compiler_linker_sdk_setup(gnArgArg)
+ append_sanitizer_setup(gnArgArg)
+ append_toolchain_setup(gnArgArg)
+ append_pkg_config_setup(gnArgArg)
+
+ list(APPEND gnArgArg
+ qtwebengine_target="${buildDir}/${config}/${arch}:QtWebEngineCore"
+ build_dawn_tests=false
+ build_with_tflite_lib=false
+ enable_background_contents=false
+ enable_background_mode=false
+ enable_ipc_fuzzer=false
+ enable_ipc_logging=false
+ enable_java_templates=false
+ enable_media_remoting=false
+ enable_message_center=false
+ enable_nacl=false
+ enable_oop_printing=false
+ enable_remoting=false
+ enable_reporting=false
+ enable_resource_allowlist_generation=false
+ enable_screen_ai_service=false
+ enable_session_service=false
+ enable_supervised_users=false
+ enable_swiftshader=false
+ enable_swiftshader_vulkan=false
+ angle_enable_swiftshader=false
+ dawn_use_swiftshader=false
+ enable_vr=false
+ enable_web_speech=false
+ enable_widevine=true
+ enable_library_cdms=true
+ fatal_linker_warnings=false
+ has_native_accessibility=false
+ safe_browsing_mode=0
+ toolkit_views=false
+ chrome_pgo_phase=0
+ optimize_webui=false
+ strip_absolute_paths_from_debug_symbols=false
+ pdf_use_skia=true
+ use_dawn=false
+ skia_use_dawn=false
+ devtools_fast_bundle=false
+ devtools_skip_typecheck=false
+ use_static_angle=true
+ use_perfetto_client_library=false
+ trial_comparison_cert_verifier_supported=false
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_v8_context_snapshot v8_use_external_startup_data
+ CONDITION QT_FEATURE_webengine_v8_context_snapshot
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_printing enable_basic_printing enable_print_preview enable_pdf
+ CONDITION QT_FEATURE_webengine_printing_and_pdf
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_cups
+ CONDITION QT_FEATURE_webengine_printing_and_pdf AND NOT WIN32
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_plugins
+ CONDITION QT_FEATURE_webengine_printing_and_pdf OR
+ QT_FEATURE_webengine_pepper_plugins
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_ppapi
+ CONDITION QT_FEATURE_webengine_pepper_plugins
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_spellcheck
+ CONDITION QT_FEATURE_webengine_spellchecker
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_webrtc
+ CONDITION QT_FEATURE_webengine_webrtc
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_screen_capture
+ CONDITION QT_FEATURE_webengine_webrtc
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_hangout_services_extension
+ CONDITION QT_FEATURE_webengine_webrtc AND QT_FEATURE_webengine_extensions
+ )
+ extend_gn_list(gnArgArg
+ ARGS rtc_use_pipewire
+ CONDITION QT_FEATURE_webengine_webrtc_pipewire
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_extensions
+ CONDITION QT_FEATURE_webengine_extensions
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_vulkan
+ CONDITION QT_FEATURE_webengine_vulkan
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_kerberos
+ CONDITION QT_FEATURE_webengine_kerberos
+ )
+ extend_gn_list(gnArgArg
+ ARGS proprietary_codecs
+ CONDITION QT_FEATURE_webengine_proprietary_codecs
+ )
+ if(QT_FEATURE_webengine_proprietary_codecs)
+ list(APPEND gnArgArg ffmpeg_branding="Chrome")
+ endif()
+ extend_gn_list(gnArgArg
+ ARGS use_browser_spellchecker
+ CONDITION QT_FEATURE_webengine_native_spellchecker
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_embedded_config
+ CONDITION QT_FEATURE_webengine_embedded_build
+ )
+ extend_gn_list(gnArgArg
+ ARGS enable_webenginedriver
+ CONDITION QT_FEATURE_webenginedriver
+ )
+
+ if(LINUX)
+ list(APPEND gnArgArg
+ use_gtk=false # GTK toolkit bindings
+ use_qt=false # Qt5 toolkit bindings
+ use_cups=false
+ use_gio=false
+ use_bundled_fontconfig=false
+ use_glib=false
+ use_bluez=false
+ use_udev=true
+ is_cfi=false
+ use_ozone=true
+ ozone_auto_platforms=false
+ ozone_platform_headless=false
+ ozone_platform_external=true
+ ozone_platform="qt"
+ ozone_extra_path="${CMAKE_CURRENT_LIST_DIR}/ozone/ozone_extra.gni"
+ )
+ set(systemLibs libjpeg libpng freetype harfbuzz libevent libwebp libxml
+ opus snappy icu ffmpeg re2 lcms2 libopenjpeg2 libvpx
+ )
+ foreach(slib ${systemLibs})
+ extend_gn_list(gnArgArg
+ ARGS use_system_${slib}
+ CONDITION QT_FEATURE_webengine_system_${slib}
+ )
+ endforeach()
+ if(NOT QT_FEATURE_webengine_system_opus)
+ extend_gn_list(gnArgArg
+ ARGS has_perl
+ CONDITION Perl_FOUND
+ )
+ endif()
+ extend_gn_list(gnArgArg
+ ARGS use_system_libxslt
+ CONDITION QT_FEATURE_webengine_system_libxml
+ )
+ extend_gn_list(gnArgArg
+ ARGS icu_use_data_file
+ CONDITION NOT QT_FEATURE_webengine_system_icu
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_system_zlib use_system_minizip
+ CONDITION QT_FEATURE_webengine_system_zlib AND QT_FEATURE_webengine_system_minizip
+ )
+ extend_gn_list(gnArgArg
+ ARGS pdfium_use_system_zlib
+ CONDITION QT_FEATURE_webengine_system_zlib
+ )
+ extend_gn_list(gnArgArg
+ ARGS pdfium_use_system_libpng
+ CONDITION QT_FEATURE_webengine_system_libpng
+ )
+ extend_gn_list(gnArgArg
+ ARGS pdfium_use_system_libtiff
+ CONDITION QT_FEATURE_webengine_system_libtiff
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_libpci
+ CONDITION QT_FEATURE_webengine_system_libpci
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_alsa
+ CONDITION QT_FEATURE_webengine_system_alsa
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_pulseaudio
+ CONDITION QT_FEATURE_webengine_system_pulseaudio
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_system_minigbm
+ CONDITION QT_FEATURE_webengine_system_gbm
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_vaapi
+ CONDITION QT_FEATURE_webengine_vaapi
+ )
+ extend_gn_list(gnArgArg
+ ARGS ozone_platform_x11 use_xkbcommon
+ CONDITION QT_FEATURE_webengine_ozone_x11
+ )
+ extend_gn_list(gnArgArg
+ ARGS rtc_use_x11
+ CONDITION QT_FEATURE_webengine_ozone_x11 AND QT_FEATURE_webengine_webrtc
+ )
+ extend_gn_list(gnArgArg
+ ARGS use_vaapi_x11
+ CONDITION QT_FEATURE_webengine_ozone_x11 AND QT_FEATURE_webengine_vaapi
+ )
+
+ if(QT_FEATURE_webengine_kerberos)
+ list(APPEND gnArgArg
+ external_gssapi_include_dir="${GSSAPI_INCLUDE_DIRS}/gssapi"
+ )
+ endif()
+ get_gn_arch(cpu ${TEST_architecture_arch})
+ if(CMAKE_CROSSCOMPILING AND cpu STREQUAL "arm")
+ check_thumb(armThumb)
+ if(NOT armThumb AND NOT QT_FEATURE_webengine_system_ffmpeg)
+ list(APPEND gnArgArg media_use_ffmpeg=false use_webaudio_ffmpeg=false)
+ endif()
+ endif()
+
+ if(CMAKE_CROSSCOMPILING AND cpu STREQUAL "arm64")
+ # This is a workaround to avoid auto test timeouts on the QEMU arm64 CI.
+ if ("$ENV{TARGET_OSVERSION_COIN}" STREQUAL "qemu")
+ list(APPEND gnArgArg
+ v8_enable_sandbox=false
+ arm_control_flow_integrity="none"
+ )
+ endif()
+ endif()
+ unset(cpu)
+ endif()
+
+ if(MACOS)
+ list(APPEND gnArgArg
+ use_external_popup_menu=false
+ skia_use_metal=false
+ )
+ endif()
+
+ if(WIN32)
+ list(APPEND gnArgArg
+ ninja_use_custom_environment_files=false
+ com_init_check_hook_disabled=true
+ heterogeneous_executables=true
+ )
+ endif()
+
+ add_gn_command(
+ CMAKE_TARGET WebEngineCore
+ NINJA_TARGETS QtWebEngineCore convert_dict
+ GN_TARGET ${buildGn}
+ GN_ARGS ${gnArgArg}
+ BUILDDIR ${buildDir}/${config}/${arch}
+ MODULE core
+ )
+
+ endforeach()
+ create_cxx_configs(WebEngineCore ${arch})
+endforeach()
+
+
+##
+# WEBENGINECORE SETUP
+##
+
+list(GET archs 0 arch)
+target_include_directories(WebEngineCore PRIVATE
+ ${buildDir}/$<CONFIG>/${arch}/gen
+ ${buildDir}/$<CONFIG>/${arch}/gen/third_party/perfetto
+ ${buildDir}/$<CONFIG>/${arch}/gen/third_party/perfetto/build_config
+)
+
+set(stamps QtWebEngineCore.stamp)
+if(QT_FEATURE_webengine_v8_context_snapshot)
+ set(dataStamp obj/tools/v8_context_snapshot/v8_context_snapshot.stamp)
+endif()
+
+add_gn_build_artifacts_to_target(
+ CMAKE_TARGET WebEngineCore
+ NINJA_TARGET QtWebEngineCore
+ MODULE core
+ BUILDDIR ${buildDir}
+ COMPLETE_STATIC FALSE
+ NINJA_STAMP QtWebEngineCore.stamp
+ NINJA_DATA_STAMP ${dataStamp}
+)
+add_dependencies(WebEngineCore run_core_NinjaDone)
+if(COIN_BUG_699)
+ set_property(TARGET WebEngineCore PROPERTY CXX_LINKER_LAUNCHER ${PROJECT_BINARY_DIR}/linker_ulimit.sh)
+endif()
+
+##
+# SANDBOX
+##
+
+if(WIN32)
+ add_library(WebEngineCoreSandbox STATIC IMPORTED GLOBAL)
+ foreach(config ${configs})
+ string(TOUPPER ${config} cfg)
+ add_ninja_command(
+ TARGET QtWebEngineCoreSandbox
+ OUTPUT QtWebEngineCoreSandbox.lib
+ BUILDDIR ${buildDir}/${config}/${arch}
+ MODULE core
+ )
+ set(sandboxLibraryPath ${buildDir}/${config}/${arch}/QtWebEngineCoreSandbox.lib)
+ set_property(TARGET WebEngineCoreSandbox
+ PROPERTY IMPORTED_LOCATION_${cfg} ${sandboxLibraryPath}
+ )
+ add_custom_target(sandboxLibrary_${config}
+ DEPENDS ${buildDir}/${config}/${arch}/QtWebEngineCoreSandbox.lib)
+ add_dependencies(run_core_NinjaDone sandboxLibrary_${config})
+ add_dependencies(WebEngineCoreSandbox WebEngineCore)
+ endforeach()
+endif()
+
+##
+# WEBENGINECORE DICT TOOL SETUP
+##
+
+if(QT_FEATURE_webengine_spellchecker AND NOT CMAKE_CROSSCOMPILING)
+ qt_get_tool_target_name(dict_target_name qwebengine_convert_dict)
+ target_include_directories(${dict_target_name} PRIVATE
+ ../3rdparty/chromium
+ ../3rdparty/chromium/third_party/boringssl/src/include
+ ${buildDir}/$<CONFIG>/${arch}/gen
+ )
+ add_gn_build_artifacts_to_target(
+ CMAKE_TARGET ${dict_target_name}
+ NINJA_TARGET convert_dict
+ MODULE core
+ BUILDDIR ${buildDir}
+ COMPLETE_STATIC FALSE
+ NINJA_STAMP convert_dict.stamp
+ )
+ add_dependencies(${dict_target_name} run_core_NinjaDone)
+ add_dependencies(${dict_target_name} WebEngineCore)
+endif()
+
+##
+# WEBENGINEDRIVER
+##
+
+if(QT_FEATURE_webenginedriver)
+ add_ninja_command(
+ TARGET webenginedriver_group
+ OUTPUT ${WEBENGINEDRIVER_EXECUTABLE}
+ BUILDDIR ${buildDir}/$<CONFIG>/${arch}
+ MODULE core
+ )
+ add_custom_target(webenginedriver
+ DEPENDS
+ ${buildDir}/$<CONFIG>/${arch}/${WEBENGINEDRIVER_EXECUTABLE})
+ add_dependencies(run_core_NinjaDone webenginedriver)
+endif()
+
+##
+# CHROMIUM UPDATE
+##
+
+add_custom_target(update-chromium
+ COMMAND ${CMAKE_COMMAND} -P ${WEBENGINE_ROOT_SOURCE_DIR}/cmake/SubmoduleUpdate.cmake
+ DEPENDS ${WEBENGINE_ROOT_SOURCE_DIR}/cmake/SubmoduleUpdate.cmake
+)
diff --git a/src/core/accessibility_activation_observer.cpp b/src/core/accessibility_activation_observer.cpp
index 833190844..4f25a35ff 100644
--- a/src/core/accessibility_activation_observer.cpp
+++ b/src/core/accessibility_activation_observer.cpp
@@ -1,46 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "accessibility_activation_observer.h"
-#if QT_CONFIG(accessibility)
-
#include "content/browser/accessibility/browser_accessibility_state_impl.h"
namespace QtWebEngineCore {
@@ -48,12 +10,13 @@ namespace QtWebEngineCore {
namespace {
bool isAccessibilityEnabled() {
- // On Linux accessibility is disabled by default due to performance issues,
- // and can be re-enabled by setting the QTWEBENGINE_ENABLE_LINUX_ACCESSIBILITY environment
- // variable. For details, see QTBUG-59922.
+ // On Linux accessibility can be disabled due to performance issues by setting the
+ // QTWEBENGINE_ENABLE_LINUX_ACCESSIBILITY environment variable to 0. For details,
+ // see QTBUG-59922.
#ifdef Q_OS_LINUX
static bool accessibility_enabled
- = qEnvironmentVariableIsSet("QTWEBENGINE_ENABLE_LINUX_ACCESSIBILITY");
+ = qEnvironmentVariable("QTWEBENGINE_ENABLE_LINUX_ACCESSIBILITY", QLatin1String("1"))
+ == QLatin1String("1");
#else
const bool accessibility_enabled = true;
#endif
@@ -85,5 +48,3 @@ void AccessibilityActivationObserver::accessibilityActiveChanged(bool active)
}
} // namespace QtWebEngineCore
-
-#endif // QT_CONFIG(accessibility)
diff --git a/src/core/accessibility_activation_observer.h b/src/core/accessibility_activation_observer.h
index 23fd2101e..81d8b843c 100644
--- a/src/core/accessibility_activation_observer.h
+++ b/src/core/accessibility_activation_observer.h
@@ -1,53 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef ACCESSIBILITY_ACTIVATION_OBSERVER_H
#define ACCESSIBILITY_ACTIVATION_OBSERVER_H
#include <QtGui/qaccessible.h>
-#if QT_CONFIG(accessibility)
-
namespace QtWebEngineCore {
-class RenderWidgetHostViewQt;
-
class AccessibilityActivationObserver : public QAccessible::ActivationObserver
{
public:
@@ -59,6 +19,4 @@ public:
} // namespace QtWebEngineCore
-#endif // QT_CONFIG(accessibility)
-
#endif // ACCESSIBILITY_ACTIVATION_OBSERVER_H
diff --git a/src/core/accessibility_tree_formatter_qt.cpp b/src/core/accessibility_tree_formatter_qt.cpp
index 081856b37..3a3b30cb4 100644
--- a/src/core/accessibility_tree_formatter_qt.cpp
+++ b/src/core/accessibility_tree_formatter_qt.cpp
@@ -1,71 +1,46 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "content/browser/accessibility/accessibility_tree_formatter_browser.h"
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "content/browser/accessibility/browser_accessibility_manager.h"
+#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
+#include "content/public/browser/ax_inspect_factory.h"
+#include "ui/accessibility/platform/inspect/ax_event_recorder.h"
+
+#include <QtGui/qtguiglobal.h>
+
+#include <memory>
+#include <string>
#include <utility>
-#include "base/logging.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
+#if QT_CONFIG(accessibility)
+#include "browser_accessibility_qt.h"
+
#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
+#include "content/browser/accessibility/browser_accessibility.h"
+#include "ui/accessibility/platform/inspect/ax_tree_formatter_base.h"
-#include "browser_accessibility_qt.h"
+#include <QtGui/qaccessible.h>
+#endif
namespace content {
#if QT_CONFIG(accessibility)
-class AccessibilityTreeFormatterQt : public AccessibilityTreeFormatterBrowser {
+class AccessibilityTreeFormatterQt : public ui::AXTreeFormatterBase {
public:
explicit AccessibilityTreeFormatterQt();
~AccessibilityTreeFormatterQt() override;
+ base::Value::Dict BuildTree(ui::AXPlatformNodeDelegate *start) const override;
+ base::Value::Dict BuildTreeForSelector(const AXTreeSelector &selector) const override
+ {
+ return base::Value::Dict{};
+ }
+
private:
- base::FilePath::StringType GetExpectedFileSuffix() override;
- const std::string GetAllowEmptyString() override;
- const std::string GetAllowString() override;
- const std::string GetDenyString() override;
- const std::string GetDenyNodeString() override;
- void AddProperties(const BrowserAccessibility &node, base::DictionaryValue* dict) override;
- base::string16 ProcessTreeForOutput(const base::DictionaryValue &node, base::DictionaryValue * = nullptr) override;
+ void RecursiveBuildAccessibilityTree(const BrowserAccessibility &node, base::Value::Dict *dict) const;
+ void AddProperties(const BrowserAccessibility &node, base::Value::Dict *dict) const;
+ std::string ProcessTreeForOutput(const base::Value::Dict &node) const override;
};
AccessibilityTreeFormatterQt::AccessibilityTreeFormatterQt()
@@ -76,144 +51,177 @@ AccessibilityTreeFormatterQt::~AccessibilityTreeFormatterQt()
{
}
-void AccessibilityTreeFormatterQt::AddProperties(const BrowserAccessibility &node, base::DictionaryValue *dict)
+base::Value::Dict AccessibilityTreeFormatterQt::BuildTree(ui::AXPlatformNodeDelegate *start) const
{
- dict->SetInteger("id", node.GetId());
- const BrowserAccessibilityQt *acc_node = ToBrowserAccessibilityQt(&node);
+ BrowserAccessibility *root_internal =
+ BrowserAccessibility::FromAXPlatformNodeDelegate(start);
+ base::Value::Dict dict;
+ RecursiveBuildAccessibilityTree(*root_internal, &dict);
+ return dict;
+}
- dict->SetString("role", qAccessibleRoleString(acc_node->role()));
+void AccessibilityTreeFormatterQt::RecursiveBuildAccessibilityTree(const BrowserAccessibility &node, base::Value::Dict *dict) const
+{
+ AddProperties(node, dict);
- QAccessible::State state = acc_node->state();
+ base::Value::List children;
+ for (size_t i = 0; i < node.PlatformChildCount(); ++i) {
+ base::Value::Dict child_dict;
- std::vector<base::Value> states;
+ content::BrowserAccessibility *child_node = node.PlatformGetChild(i);
+
+ RecursiveBuildAccessibilityTree(*child_node, &child_dict);
+ children.Append(std::move(child_dict));
+ }
+ dict->Set(kChildrenDictAttr, std::move(children));
+}
+
+void AccessibilityTreeFormatterQt::AddProperties(const BrowserAccessibility &node, base::Value::Dict *dict) const
+{
+ dict->Set("id", node.GetId());
+ const QAccessibleInterface *iface = toQAccessibleInterface(&node);
+
+ dict->Set("role", qAccessibleRoleString(iface->role()));
+
+ QAccessible::State state = iface->state();
+
+ base::Value::List states;
if (state.busy)
- states.push_back(base::Value("busy"));
+ states.Append(base::Value("busy"));
if (state.checkable)
- states.push_back(base::Value("checkable"));
+ states.Append(base::Value("checkable"));
if (state.checked)
- states.push_back(base::Value("checked"));
- if (acc_node->IsClickable())
- states.push_back(base::Value("clickable"));
+ states.Append(base::Value("checked"));
+ if (node.IsClickable())
+ states.Append(base::Value("clickable"));
if (state.collapsed)
- states.push_back(base::Value("collapsed"));
+ states.Append(base::Value("collapsed"));
if (state.disabled)
- states.push_back(base::Value("disabled"));
+ states.Append(base::Value("disabled"));
if (state.editable)
- states.push_back(base::Value("editable"));
+ states.Append(base::Value("editable"));
if (state.expandable)
- states.push_back(base::Value("expandable"));
+ states.Append(base::Value("expandable"));
if (state.expanded)
- states.push_back(base::Value("expanded"));
+ states.Append(base::Value("expanded"));
if (state.focusable)
- states.push_back(base::Value("focusable"));
+ states.Append(base::Value("focusable"));
if (state.focused)
- states.push_back(base::Value("focused"));
+ states.Append(base::Value("focused"));
if (state.hasPopup)
- states.push_back(base::Value("hasPopup"));
+ states.Append(base::Value("hasPopup"));
if (state.hotTracked)
- states.push_back(base::Value("hotTracked"));
+ states.Append(base::Value("hotTracked"));
if (state.invisible)
- states.push_back(base::Value("invisible"));
+ states.Append(base::Value("invisible"));
if (state.linked)
- states.push_back(base::Value("linked"));
+ states.Append(base::Value("linked"));
if (state.multiLine)
- states.push_back(base::Value("multiLine"));
+ states.Append(base::Value("multiLine"));
if (state.multiSelectable)
- states.push_back(base::Value("multiSelectable"));
+ states.Append(base::Value("multiSelectable"));
if (state.modal)
- states.push_back(base::Value("modal"));
+ states.Append(base::Value("modal"));
if (state.offscreen)
- states.push_back(base::Value("offscreen"));
+ states.Append(base::Value("offscreen"));
if (state.passwordEdit)
- states.push_back(base::Value("password"));
+ states.Append(base::Value("password"));
if (state.pressed)
- states.push_back(base::Value("pressed"));
+ states.Append(base::Value("pressed"));
if (state.readOnly)
- states.push_back(base::Value("readOnly"));
+ states.Append(base::Value("readOnly"));
if (state.selectable)
- states.push_back(base::Value("selectable"));
+ states.Append(base::Value("selectable"));
if (state.selected)
- states.push_back(base::Value("selected"));
+ states.Append(base::Value("selected"));
if (state.traversed)
- states.push_back(base::Value("traversed"));
- dict->SetKey("states", base::Value(states));
+ states.Append(base::Value("traversed"));
+ dict->Set("states", std::move(states));
- dict->SetString("name", acc_node->text(QAccessible::Name).toStdString());
- dict->SetString("description", acc_node->text(QAccessible::Description).toStdString());
+ dict->Set("name", iface->text(QAccessible::Name).toStdString());
+ dict->Set("description", iface->text(QAccessible::Description).toStdString());
}
-base::string16 AccessibilityTreeFormatterQt::ProcessTreeForOutput(const base::DictionaryValue &node, base::DictionaryValue *)
+std::string AccessibilityTreeFormatterQt::ProcessTreeForOutput(const base::Value::Dict &node) const
{
- base::string16 error_value;
- if (node.GetString("error", &error_value))
- return error_value;
+ std::string error_value;
+ if (auto error_value = node.FindString("error"))
+ return *error_value;
- base::string16 line;
+ std::string line;
std::string role_value;
- node.GetString("role", &role_value);
- if (!role_value.empty())
- WriteAttribute(true, base::StringPrintf("%s", role_value.c_str()), &line);
+ if (auto role_value = node.FindString("role"))
+ WriteAttribute(true, base::StringPrintf("%s", role_value->c_str()), &line);
- const base::ListValue *states_value = nullptr;
- node.GetList("states", &states_value);
- if (states_value) {
+ if (const auto states_value = node.FindList("states")) {
for (const auto &state : *states_value) {
- std::string state_value;
- if (state.GetAsString(&state_value))
- WriteAttribute(true, state_value, &line);
+ if (auto *state_value = state.GetIfString())
+ WriteAttribute(false, *state_value, &line);
}
}
- std::string name_value;
- if (node.GetString("name", &name_value))
- WriteAttribute(true, base::StringPrintf("name='%s'", name_value.c_str()), &line);
+ if (auto name_value = node.FindString("name"))
+ WriteAttribute(true, base::StringPrintf("name='%s'", name_value->c_str()), &line);
- std::string description_value;
- if (node.GetString("description", &description_value))
- WriteAttribute(false, base::StringPrintf("description='%s'", description_value.c_str()), &line);
+ if (auto description_value = node.FindString("description"))
+ WriteAttribute(false, base::StringPrintf("description='%s'", description_value->c_str()), &line);
int id_value;
- node.GetInteger("id", &id_value);
+ if (auto maybe_id = node.FindInt("id"))
+ id_value = *maybe_id;
WriteAttribute(false, base::StringPrintf("id=%d", id_value), &line);
- return line + base::ASCIIToUTF16("\n");
-}
-
-base::FilePath::StringType AccessibilityTreeFormatterQt::GetExpectedFileSuffix()
-{
- return FILE_PATH_LITERAL("-expected-qt.txt");
+ return line + "\n";
}
-const std::string AccessibilityTreeFormatterQt::GetAllowEmptyString()
-{
- return "@QT-ALLOW-EMPTY:";
-}
+#endif // QT_CONFIG(accessibility)
-const std::string AccessibilityTreeFormatterQt::GetAllowString()
+// static
+std::unique_ptr<ui::AXTreeFormatter>
+AXInspectFactory::CreatePlatformFormatter()
{
- return "@QT-ALLOW:";
+ return AXInspectFactory::CreateFormatter(ui::AXApiType::kQt);
}
-const std::string AccessibilityTreeFormatterQt::GetDenyString()
+// static
+std::unique_ptr<ui::AXEventRecorder> AXInspectFactory::CreatePlatformRecorder(BrowserAccessibilityManager *manager,
+ base::ProcessId pid,
+ const ui::AXTreeSelector &selector)
{
- return "@QT-DENY:";
+ return AXInspectFactory::CreateRecorder(ui::AXApiType::kQt, manager, pid, selector);
}
-const std::string AccessibilityTreeFormatterQt::GetDenyNodeString()
+// static
+std::unique_ptr<ui::AXTreeFormatter> AXInspectFactory::CreateFormatter(ui::AXApiType::Type type)
{
- return "@QT-DENY-NODE:";
+ switch (type) {
+ case ui::AXApiType::kBlink:
+ return std::make_unique<AccessibilityTreeFormatterBlink>();
+ case ui::AXApiType::kQt:
+#if QT_CONFIG(accessibility)
+ return std::make_unique<AccessibilityTreeFormatterQt>();
+#else
+ return nullptr;
+#endif
+ default:
+ NOTREACHED() << "Unsupported inspect type " << type;
+ }
+ return nullptr;
}
-#endif // QT_CONFIG(accessibility)
-
// static
-std::unique_ptr<AccessibilityTreeFormatter> AccessibilityTreeFormatter::Create()
+std::unique_ptr<ui::AXEventRecorder> AXInspectFactory::CreateRecorder(ui::AXApiType::Type type,
+ BrowserAccessibilityManager *manager,
+ base::ProcessId pid,
+ const ui::AXTreeSelector &selector)
{
-#if QT_CONFIG(accessibility)
- return std::unique_ptr<AccessibilityTreeFormatter>(new AccessibilityTreeFormatterQt());
-#else
+ switch (type) {
+ case ui::AXApiType::kQt:
+ return std::make_unique<ui::AXEventRecorder>();
+ default:
+ NOTREACHED() << "Unsupported inspect type " << type;
+ }
return nullptr;
-#endif
}
} // namespace content
diff --git a/src/core/api/CMakeLists.txt b/src/core/api/CMakeLists.txt
new file mode 100644
index 000000000..c06f5e4ce
--- /dev/null
+++ b/src/core/api/CMakeLists.txt
@@ -0,0 +1,222 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+find_package(Qt6 ${PROJECT_VERSION} REQUIRED COMPONENTS Gui Network Quick)
+find_package(Qt6 ${PROJECT_VERSION} QUIET OPTIONAL_COMPONENTS WebChannel Positioning)
+
+set(qtWebEngineProcessName QtWebEngineProcess)
+
+qt_internal_add_module(WebEngineCore
+ SOURCES
+ qtwebenginecoreglobal.cpp qtwebenginecoreglobal.h qtwebenginecoreglobal_p.h
+ qwebenginecertificateerror.cpp qwebenginecertificateerror.h
+ qwebengineclientcertificateselection.cpp qwebengineclientcertificateselection.h
+ qwebengineclientcertificatestore.cpp qwebengineclientcertificatestore.h
+ qwebengineclienthints.cpp qwebengineclienthints.h
+ qwebenginecontextmenurequest.cpp qwebenginecontextmenurequest.h qwebenginecontextmenurequest_p.h
+ qwebenginecookiestore.cpp qwebenginecookiestore.h qwebenginecookiestore_p.h
+ qwebenginedesktopmediarequest.cpp qwebenginedesktopmediarequest.h qwebenginedesktopmediarequest_p.h
+ qwebenginedownloadrequest.cpp qwebenginedownloadrequest.h qwebenginedownloadrequest_p.h
+ qwebenginefilesystemaccessrequest.cpp qwebenginefilesystemaccessrequest.h
+ qwebenginefindtextresult.cpp qwebenginefindtextresult.h
+ qwebengineframe.cpp qwebengineframe.h
+ qwebenginefullscreenrequest.cpp qwebenginefullscreenrequest.h
+ qwebenginehistory.cpp qwebenginehistory.h qwebenginehistory_p.h
+ qwebenginehttprequest.cpp qwebenginehttprequest.h
+ qwebengineloadinginfo.cpp qwebengineloadinginfo.h
+ qwebenginemessagepumpscheduler.cpp qwebenginemessagepumpscheduler_p.h
+ qwebenginenavigationrequest.cpp qwebenginenavigationrequest.h
+ qwebenginenewwindowrequest.cpp qwebenginenewwindowrequest.h qwebenginenewwindowrequest_p.h
+ qwebenginenotification.cpp qwebenginenotification.h
+ qwebenginepage.cpp qwebenginepage.h qwebenginepage_p.h
+ qwebengineprofile.cpp qwebengineprofile.h qwebengineprofile_p.h
+ qwebenginequotarequest.cpp qwebenginequotarequest.h
+ qwebengineregisterprotocolhandlerrequest.cpp qwebengineregisterprotocolhandlerrequest.h
+ qwebenginescript.cpp qwebenginescript.h
+ qwebenginescriptcollection.cpp qwebenginescriptcollection.h qwebenginescriptcollection_p.h
+ qwebenginesettings.cpp qwebenginesettings.h
+ qwebengineurlrequestinfo.cpp qwebengineurlrequestinfo.h qwebengineurlrequestinfo_p.h
+ qwebengineurlrequestinterceptor.h qwebengineurlrequestinterceptor.cpp
+ qwebengineurlrequestjob.cpp qwebengineurlrequestjob.h
+ qwebengineurlscheme.cpp qwebengineurlscheme.h
+ qwebengineurlschemehandler.cpp qwebengineurlschemehandler.h
+ qwebengineglobalsettings.cpp qwebengineglobalsettings.h qwebengineglobalsettings_p.h
+ qwebenginewebauthuxrequest.cpp qwebenginewebauthuxrequest.h qwebenginewebauthuxrequest_p.h
+ DEFINES
+ BUILDING_CHROMIUM
+ INCLUDE_DIRECTORIES
+ ../
+ ../../3rdparty/chromium
+ ../../3rdparty/chromium/third_party/abseil-cpp
+ ../../3rdparty/chromium/third_party/perfetto/include
+ ../../3rdparty/chromium/third_party/boringssl/src/include
+ LIBRARIES
+ Qt::CorePrivate
+ Qt::GuiPrivate
+ Qt::QuickPrivate
+ PUBLIC_LIBRARIES
+ Qt::Core
+ Qt::Gui
+ Qt::Network
+ Qt::Quick
+ EXTRA_CMAKE_FILES
+ "${CMAKE_CURRENT_LIST_DIR}/${INSTALL_CMAKE_NAMESPACE}WebEngineCoreDeploySupport.cmake"
+ NO_GENERATE_CPP_EXPORTS
+)
+
+set_target_properties(WebEngineCore PROPERTIES QTWEBENGINEPROCESS_NAME ${qtWebEngineProcessName})
+set_target_properties(WebEngineCore PROPERTIES CXX_STANDARD 20)
+
+# Chromium included headers are not clean
+qt_skip_warnings_are_errors(WebEngineCore)
+
+if(CLANG OR GCC)
+ target_compile_options(WebEngineCore PRIVATE
+ "-Wno-unused-parameter"
+ "-Wno-expansion-to-defined"
+ )
+endif()
+
+if(GCC)
+ target_compile_options(WebEngineCore PRIVATE
+ "-Wno-packed-not-aligned"
+ )
+endif()
+
+qt_internal_extend_target(WebEngineCore CONDITION QT_FEATURE_webengine_webchannel
+ PUBLIC_LIBRARIES
+ Qt::WebChannel
+)
+qt_internal_extend_target(WebEngineCore CONDITION QT_FEATURE_webengine_geolocation
+ PUBLIC_LIBRARIES
+ Qt::Positioning
+)
+
+get_install_config(config)
+get_architectures(archs)
+get_configs(configs)
+list(GET archs 0 arch)
+
+##
+# DOCS
+##
+
+qt_internal_add_docs(WebEngineCore
+ ../doc/qtwebengine.qdocconf
+)
+
+add_code_attributions_target(
+ TARGET generate_chromium_attributions
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/chromium_attributions.qdoc
+ GN_TARGET :QtWebEngineCore
+ FILE_TEMPLATE ../doc/about_credits.tmpl
+ ENTRY_TEMPLATE ../doc/about_credits_entry.tmpl
+ BUILDDIR ${buildDir}/${config}/${arch}
+)
+add_dependencies(generate_chromium_attributions run_core_GnDone)
+add_dependencies(prepare_docs_WebEngineCore generate_chromium_attributions)
+
+##
+# WEBENGINECORE RESOURCES
+##
+
+#TODO: use simply filter / globbing-expressions
+set(localeList am ar bg bn ca cs da de el en-GB en-US es-419 es et fa fi fil fr
+ gu he hi hr hu id it ja kn ko lt lv ml mr ms nb nl pl pt-BR pt-PT ro ru sk
+ sl sr sv sw ta te th tr uk vi zh-CN zh-TW)
+
+set(resourceList qtwebengine_resources.pak
+ qtwebengine_resources_100p.pak
+ qtwebengine_resources_200p.pak
+ qtwebengine_devtools_resources.pak)
+
+set(stamps ${buildDir}/${config}/${arch}/QtWebEngineCore.stamp)
+
+qt_internal_get_filename_path_mode(path_mode)
+
+if(QT_FEATURE_webengine_v8_context_snapshot)
+ foreach(arch ${archs})
+ foreach(config ${configs})
+ if(MACOS)
+ set(ext_arch ".${arch}")
+ # QTBUG-118120 gn does not support x86_64h
+ if(ext_arch STREQUAL "x86_64h")
+ set(ext_arch "x86_64")
+ endif()
+ else()
+ unset(ext_arch)
+ endif()
+ if("${config}" STREQUAL "Debug")
+ set(ext_debug ".debug")
+ else()
+ unset(ext_debug)
+ endif()
+ get_filename_component(resSourcePath ${buildDir}/${config}/${arch}/v8_context_snapshot${ext_arch}${ext_debug}.bin ${path_mode})
+ list(APPEND resourceFiles ${resSourcePath})
+ if(MACOS)
+ set(stamps ${stamps} ${buildDir}/${config}/${arch}/obj/tools/v8_context_snapshot/v8_context_snapshot.stamp)
+ endif()
+ endforeach()
+ endforeach()
+endif()
+
+foreach(loc ${localeList})
+ get_filename_component(locSourcePath ${buildDir}/${config}/${arch}/qtwebengine_locales/${loc}.pak ${path_mode})
+ list(APPEND localeFiles ${locSourcePath})
+endforeach()
+
+foreach(res ${resourceList})
+ get_filename_component(resSourcePath ${buildDir}/${config}/${arch}/${res} ${path_mode})
+ list(APPEND resourceFiles ${resSourcePath})
+endforeach()
+
+
+if(NOT QT_FEATURE_webengine_system_icu)
+ get_filename_component(icuFile ${buildDir}/${config}/${arch}/icudtl.dat ${path_mode})
+ list(APPEND resourceFiles ${icuFile})
+ set_target_properties(WebEngineCore PROPERTIES ICUDTL_FILE ${icuFile})
+endif()
+
+if(QT_FEATURE_framework)
+ set(allResourceFiles ${localeFiles} ${resourceFiles})
+ target_sources(WebEngineCore PRIVATE ${allResourceFiles})
+
+ set_source_files_properties(${localeFiles}
+ TARGET_DIRECTORY WebEngineCore
+ PROPERTIES MACOSX_PACKAGE_LOCATION Resources/qtwebengine_locales
+ GENERATED TRUE
+ )
+ set_source_files_properties(${resourceFiles}
+ TARGET_DIRECTORY WebEngineCore
+ PROPERTIES MACOSX_PACKAGE_LOCATION Resources
+ GENERATED TRUE
+ )
+
+ add_custom_command(OUTPUT ${allResourceFiles} DEPENDS "${stamps}")
+ add_custom_target(generate_resources_${config} DEPENDS ${allResourceFiles})
+
+ addCopyCommand(WebEngineCore "${localeFiles}"
+ "${QT_BUILD_DIR}/${INSTALL_LIBDIR}/QtWebEngineCore.framework/Versions/A/Resources/qtwebengine_locales/"
+ )
+ addCopyCommand(WebEngineCore "${resourceFiles}"
+ "${QT_BUILD_DIR}/${INSTALL_LIBDIR}/QtWebEngineCore.framework/Versions/A/Resources/"
+ )
+
+else()
+ install(FILES ${localeFiles}
+ DESTINATION ${INSTALL_TRANSLATIONSDIR}/qtwebengine_locales
+ CONFIGURATIONS ${config}
+ )
+ install(FILES ${resourceFiles}
+ DESTINATION ${INSTALL_DATADIR}/resources
+ CONFIGURATIONS ${config}
+ )
+ if(QT_SUPERBUILD OR NOT QT_WILL_INSTALL)
+ addCopyCommand(WebEngineCore "${localeFiles}"
+ ${QT_BUILD_DIR}/${INSTALL_TRANSLATIONSDIR}/qtwebengine_locales
+ )
+ addCopyCommand(WebEngineCore "${resourceFiles}"
+ ${QT_BUILD_DIR}/${INSTALL_DATADIR}/resources
+ )
+ endif()
+endif()
diff --git a/src/core/api/Qt6WebEngineCoreDeploySupport.cmake b/src/core/api/Qt6WebEngineCoreDeploySupport.cmake
new file mode 100644
index 000000000..e67eb212b
--- /dev/null
+++ b/src/core/api/Qt6WebEngineCoreDeploySupport.cmake
@@ -0,0 +1,173 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+# NOTE: This code should only ever be executed in script mode. It expects to be
+# used either as part of an install(CODE) call or called by a script
+# invoked via cmake -P as a POST_BUILD step. It would not normally be
+# included directly, it should be pulled in automatically by the deploy
+# support set up by qtbase.
+
+cmake_minimum_required(VERSION 3.16...3.21)
+
+_qt_internal_add_deployment_hook(_qt_internal_webenginecore_deploy_hook)
+
+if(NOT QT_DEPLOY_WEBENGINECORE_RESOURCES_DIR)
+ set(QT_DEPLOY_WEBENGINECORE_RESOURCES_DIR "resources")
+endif()
+
+function(_qt_internal_webenginecore_status_message)
+ if(__QT_DEPLOY_VERBOSE)
+ message(STATUS ${ARGV})
+ endif()
+endfunction()
+
+function(_qt_internal_webenginecore_deploy_hook)
+ set(no_value_options "")
+ set(single_value_options "")
+ set(multi_value_options RESOLVED_DEPENDENCIES)
+ cmake_parse_arguments(PARSE_ARGV 0 arg
+ "${no_value_options}" "${single_value_options}" "${multi_value_options}"
+ )
+
+ set(webenginecore_dependency_found FALSE)
+ foreach(dependency IN LISTS arg_RESOLVED_DEPENDENCIES)
+ if(dependency MATCHES "/libQt[0-9]+WebEngineCore[^/]+")
+ set(webenginecore_dependency_found TRUE)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT webenginecore_dependency_found)
+ _qt_internal_webenginecore_status_message(
+ "No QtWebEngineCore dependency found. "
+ "Skipping deployment of QtWebEngine assets."
+ )
+ return()
+ endif()
+
+ _qt_internal_deploy_webenginecore()
+endfunction()
+
+function(_qt_internal_deploy_webenginecore)
+ _qt_internal_deploy_webenginecore_binary()
+ _qt_internal_deploy_webenginecore_data()
+ _qt_internal_deploy_webenginecore_translations()
+endfunction()
+
+function(_qt_internal_deploy_webenginecore_binary)
+ _qt_internal_webenginecore_status_message("Deploying the WebEngineCore process binary")
+
+ set(candidates "QtWebEngineProcess")
+ if(__QT_DEPLOY_ACTIVE_CONFIG STREQUAL "Debug" AND __QT_DEPLOY_SYSTEM_NAME STREQUAL "Windows")
+ list(PREPEND candidates "QtWebEngineProcessd")
+ endif()
+
+ list(TRANSFORM candidates
+ PREPEND "${__QT_DEPLOY_QT_INSTALL_PREFIX}/${__QT_DEPLOY_QT_INSTALL_LIBEXECS}/"
+ )
+
+ set(process_path "")
+ foreach(file_path IN LISTS candidates)
+ if(EXISTS "${file_path}")
+ set(process_path "${file_path}")
+ break()
+ endif()
+ endforeach()
+
+ set(install_destination "${QT_DEPLOY_PREFIX}/")
+ if(__QT_DEPLOY_SYSTEM_NAME STREQUAL "Windows")
+ string(APPEND install_destination "${QT_DEPLOY_BIN_DIR}")
+ else()
+ string(APPEND install_destination "${QT_DEPLOY_LIBEXEC_DIR}")
+ endif()
+ file(INSTALL "${process_path}" DESTINATION "${install_destination}")
+
+ get_filename_component(process_file_name "${process_path}" NAME)
+ if(CMAKE_VERSION GREATER_EQUAL "3.19")
+ file(CHMOD "${install_destination}/${process_file_name}"
+ PERMISSIONS OWNER_EXECUTE OWNER_READ OWNER_WRITE
+ GROUP_EXECUTE GROUP_READ
+ WORLD_EXECUTE WORLD_READ
+ )
+ else()
+ execute_process(
+ COMMAND chmod 0755 "${install_destination}/${process_file_name}"
+ )
+ endif()
+endfunction()
+
+function(_qt_internal_deploy_webenginecore_data)
+ _qt_internal_webenginecore_status_message("Deploying the WebEngineCore data files")
+ set(data_files
+ icudtl.dat
+ qtwebengine_devtools_resources.pak
+ qtwebengine_resources.pak
+ qtwebengine_resources_100p.pak
+ qtwebengine_resources_200p.pak
+ )
+ get_filename_component(resources_dir "resources" ABSOLUTE
+ BASE_DIR "${__QT_DEPLOY_QT_INSTALL_PREFIX}/${__QT_DEPLOY_QT_INSTALL_DATA}"
+ )
+
+ _qt_internal_webenginecore_find_v8_context_snapshot(
+ snapshot_file
+ RESOURCES_DIR "${resources_dir}"
+ )
+ if(NOT snapshot_file STREQUAL "")
+ list(APPEND data_files "${snapshot_file}")
+ endif()
+
+ get_filename_component(install_destination "${QT_DEPLOY_WEBENGINECORE_RESOURCES_DIR}" ABSOLUTE
+ BASE_DIR "${QT_DEPLOY_PREFIX}/${QT_DEPLOY_DATA_DIR}"
+ )
+ foreach(data_file IN LISTS data_files)
+ file(INSTALL "${resources_dir}/${data_file}" DESTINATION "${install_destination}")
+ endforeach()
+endfunction()
+
+# The V8 snapshot file comes as debug or release build. Multi-config builds have both, a self-built
+# Qt might only have the debug one.
+#
+# This function returns the file name of the V8 context snapshot file in ${out_var}.
+# If no snapshot could be found, ${out_var} is the empty string.
+function(_qt_internal_webenginecore_find_v8_context_snapshot out_var)
+ set(no_value_options "")
+ set(single_value_options RESOURCES_DIR)
+ set(multi_value_options "")
+ cmake_parse_arguments(PARSE_ARGV 1 arg
+ "${no_value_options}" "${single_value_options}" "${multi_value_options}"
+ )
+
+ set(result "")
+ set(candidates
+ v8_context_snapshot.bin
+ v8_context_snapshot.debug.bin
+ )
+ if(__QT_DEPLOY_QT_IS_MULTI_CONFIG_BUILD_WITH_DEBUG
+ AND __QT_DEPLOY_ACTIVE_CONFIG STREQUAL "Debug")
+ # Favor the debug version of the snapshot.
+ list(REVERSE candidates)
+ endif()
+ foreach(candidate IN LISTS candidates)
+ if(EXISTS "${arg_RESOURCES_DIR}/${candidate}")
+ set(result "${candidate}")
+ break()
+ endif()
+ endforeach()
+ set("${out_var}" "${result}" PARENT_SCOPE)
+endfunction()
+
+function(_qt_internal_deploy_webenginecore_translations)
+ _qt_internal_webenginecore_status_message("Deploying the WebEngineCore translations")
+
+ get_filename_component(locales_dir "qtwebengine_locales" ABSOLUTE
+ BASE_DIR "${__QT_DEPLOY_QT_INSTALL_PREFIX}/${__QT_DEPLOY_QT_INSTALL_TRANSLATIONS}"
+ )
+ get_filename_component(install_destination "qtwebengine_locales" ABSOLUTE
+ BASE_DIR "${QT_DEPLOY_PREFIX}/${QT_DEPLOY_TRANSLATIONS_DIR}"
+ )
+ file(GLOB locale_files "${locales_dir}/*.pak")
+ foreach(locale_file IN LISTS locale_files)
+ file(INSTALL "${locale_file}" DESTINATION "${install_destination}")
+ endforeach()
+endfunction()
diff --git a/src/core/api/Qt6WebEngineCoreMacros.cmake b/src/core/api/Qt6WebEngineCoreMacros.cmake
new file mode 100644
index 000000000..8bb731548
--- /dev/null
+++ b/src/core/api/Qt6WebEngineCoreMacros.cmake
@@ -0,0 +1,74 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+# Install support uses the CMAKE_INSTALL_xxxDIR variables. Include this here
+# so that it is more likely to get pulled in earlier at a higher level, and also
+# to avoid re-including it many times later
+include(GNUInstallDirs)
+_qt_internal_add_deploy_support("${CMAKE_CURRENT_LIST_DIR}/Qt6WebEngineCoreDeploySupport.cmake")
+
+function(qt6_add_webengine_dictionary)
+ set(options)
+ set(oneValueArgs TARGET SOURCE OUTPUT_DIRECTORY)
+ set(multiValueArgs)
+
+ cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if (NOT ARGS_SOURCE OR NOT EXISTS "${ARGS_SOURCE}" OR NOT IS_ABSOLUTE "${ARGS_SOURCE}")
+ message(FATAL_ERROR "Function qt_add_webengine_dictionary requires an absolute path to SOURCE dictionary.")
+ endif()
+
+ if (NOT ARGS_OUTPUT_DIRECTORY)
+ set(ARGS_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
+ endif()
+
+ get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+ get_target_property(isBundle ${ARGS_TARGET} MACOSX_BUNDLE)
+ if(isMultiConfig)
+ set(spellcheckerDir ${ARGS_OUTPUT_DIRECTORY}/dict/qtwebengine_dictionaries)
+ set(copyCommand COMMAND ${CMAKE_COMMAND} -E copy_directory ${ARGS_OUTPUT_DIRECTORY}/dict
+ ${ARGS_OUTPUT_DIRECTORY}/$<CONFIG>
+ )
+ elseif(APPLE AND isBundle)
+ get_target_property(outputName ${ARGS_TARGET} OUTPUT_NAME)
+ if(NOT outputName)
+ set(outputName ${ARGS_TARGET})
+ endif()
+ set(spellcheckerDir "${ARGS_OUTPUT_DIRECTORY}/${outputName}.app/Contents/Resources/qtwebengine_dictionaries")
+ else()
+ set(spellcheckerDir ${ARGS_OUTPUT_DIRECTORY}/qtwebengine_dictionaries)
+ endif()
+
+ get_filename_component(dictName ${ARGS_SOURCE} NAME_WE)
+ add_custom_command(
+ OUTPUT ${spellcheckerDir}/${dictName}.bdic
+ DEPENDS ${ARGS_SOURCE}
+ COMMENT "Running qwebengine_convert_dict for ${ARGS_SOURCE}"
+ COMMAND ${CMAKE_COMMAND} -E make_directory ${spellcheckerDir}
+ COMMAND ${CMAKE_COMMAND} -E env
+ $<TARGET_FILE:${QT_CMAKE_EXPORT_NAMESPACE}::qwebengine_convert_dict>
+ ${ARGS_SOURCE} ${spellcheckerDir}/${dictName}.bdic
+ ${copyCommand}
+ )
+ set(global_dict_target "qtwebengine_dictionaries")
+ if(NOT TARGET ${global_dict_target})
+ add_custom_target(${global_dict_target})
+ endif()
+
+ # in case of large project gen target should have unique name since it can collide, use TARGET
+ if (ARGS_TARGET)
+ add_custom_target(gen-${ARGS_TARGET}-${dictName} DEPENDS ${spellcheckerDir}/${dictName}.bdic)
+ add_dependencies(${ARGS_TARGET} gen-${ARGS_TARGET}-${dictName})
+ add_dependencies(${global_dict_target} gen-${ARGS_TARGET}-${dictName})
+ else()
+ add_custom_target(gen-${dictName} DEPENDS ${spellcheckerDir}/${dictName}.bdic)
+ add_dependencies(${global_dict_target} gen-${dictName})
+ endif()
+
+endfunction()
+
+if(NOT QT_NO_CREATE_VERSIONLESS_FUNCTIONS)
+ function(qt_add_webengine_dictionary)
+ qt6_add_webengine_dictionary(${ARGN})
+ endfunction()
+endif()
diff --git a/src/core/api/configure.cmake b/src/core/api/configure.cmake
new file mode 100644
index 000000000..f8488c057
--- /dev/null
+++ b/src/core/api/configure.cmake
@@ -0,0 +1,255 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+#### Libraries
+
+if(NOT QT_CONFIGURE_RUNNING)
+ find_package(GLIB2 COMPONENTS GIO)
+ find_package(GSSAPI)
+ find_package(PkgConfig)
+ if(PkgConfig_FOUND AND QT_FEATURE_pkg_config)
+ pkg_check_modules(ALSA alsa IMPORTED_TARGET)
+ pkg_check_modules(PULSEAUDIO libpulse>=0.9.10 libpulse-mainloop-glib)
+ pkg_check_modules(XDAMAGE xdamage)
+ pkg_check_modules(POPPLER_CPP poppler-cpp IMPORTED_TARGET)
+ pkg_check_modules(GBM gbm)
+ pkg_check_modules(LIBVA libva>=1.14)
+ if(NOT GIO_FOUND)
+ pkg_check_modules(GIO gio-2.0)
+ endif()
+ endif()
+ find_package(Cups)
+
+ find_package(Qt6 ${PROJECT_VERSION} CONFIG QUIET
+ OPTIONAL_COMPONENTS Positioning WebChannel PrintSupport)
+endif()
+
+#### Tests
+
+qt_config_compile_test(poppler
+ LABEL "poppler"
+ LIBRARIES
+ PkgConfig::POPPLER_CPP
+ CODE
+"
+#include <poppler-document.h>
+
+int main() {
+ auto *pdf = poppler::document::load_from_raw_data(\"file\",100,std::string(\"user\"));
+}"
+)
+
+qt_config_compile_test(alsa
+ LABEL "alsa"
+ LIBRARIES
+ PkgConfig::ALSA
+ CODE
+"
+#include \"alsa/asoundlib.h\"
+#if SND_LIB_VERSION < 0x1000a // 1.0.10
+#error Alsa version found too old, require >= 1.0.10
+#endif
+int main(){};
+")
+
+#### Features
+
+qt_feature("webengine-embedded-build" PRIVATE
+ LABEL "Embedded build"
+ PURPOSE "Enables the embedded build configuration."
+ AUTODETECT CMAKE_CROSSCOMPILING
+ CONDITION UNIX
+)
+qt_feature("webengine-system-alsa" PRIVATE
+ LABEL "Use ALSA"
+ CONDITION UNIX AND TEST_alsa
+)
+qt_feature("webengine-v8-context-snapshot" PRIVATE
+ LABEL "Use v8 context snapshot"
+ AUTODETECT NOT CMAKE_CROSSCOMPILING
+)
+qt_feature("webengine-geolocation" PUBLIC
+ LABEL "Geolocation"
+ CONDITION TARGET Qt::Positioning
+)
+qt_feature("webengine-system-pulseaudio" PRIVATE
+ LABEL "Use PulseAudio"
+ AUTODETECT UNIX
+ CONDITION PULSEAUDIO_FOUND
+)
+qt_feature("webengine-system-gbm" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Use system GBM"
+ AUTODETECT UNIX
+ CONDITION GBM_FOUND
+)
+qt_feature("webengine-printing-and-pdf" PRIVATE
+ LABEL "Printing and PDF"
+ PURPOSE "Provides printing and output to PDF."
+ AUTODETECT NOT QT_FEATURE_webengine_embedded_build
+ CONDITION TARGET Qt::PrintSupport AND QT_FEATURE_printer AND
+ (CUPS_FOUND OR WIN32)
+)
+qt_feature("webengine-pepper-plugins" PRIVATE
+ LABEL "Pepper Plugins"
+ PURPOSE "Enables use of Pepper plugins."
+ AUTODETECT QT_FEATURE_webengine_printing_and_pdf
+)
+qt_feature("webengine-webchannel" PUBLIC
+ SECTION "WebEngine"
+ LABEL "WebChannel support"
+ PURPOSE "Provides QtWebChannel integration."
+ CONDITION TARGET Qt::WebChannel
+)
+qt_feature("webengine-proprietary-codecs" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Proprietary Codecs"
+ PURPOSE "Enables the use of proprietary codecs such as h.264/h.265 and MP3."
+ AUTODETECT OFF
+)
+qt_feature("webengine-kerberos" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Kerberos Authentication"
+ PURPOSE "Enables Kerberos Authentication Support"
+ AUTODETECT WIN32
+ CONDITION NOT LINUX OR GSSAPI_FOUND
+)
+qt_feature("webengine-spellchecker" PUBLIC
+ LABEL "Spellchecker"
+ PURPOSE "Provides a spellchecker."
+)
+qt_feature("webengine-native-spellchecker" PUBLIC
+ LABEL "Native Spellchecker"
+ PURPOSE "Use the system's native spellchecking engine."
+ AUTODETECT OFF
+ CONDITION QT_FEATURE_webengine_spellchecker AND NOT LINUX
+)
+qt_feature("webengine-extensions" PUBLIC
+ SECTION "WebEngine"
+ LABEL "Extensions"
+ PURPOSE "Enables Chromium extensions within certain limits. Currently used by the pdf viewer and hangout webrtc extension."
+ AUTODETECT ON
+ CONDITION QT_FEATURE_webengine_printing_and_pdf OR QT_FEATURE_webengine_webrtc
+)
+qt_feature("webengine-webrtc" PRIVATE
+ LABEL "WebRTC"
+ PURPOSE "Provides WebRTC support."
+ AUTODETECT NOT QT_FEATURE_webengine_embedded_build
+ CONDITION XDAMAGE_FOUND OR NOT QT_FEATURE_webengine_ozone_x11
+)
+qt_feature("webengine-webrtc-pipewire" PRIVATE
+ LABEL "PipeWire over GIO"
+ PURPOSE "Provides PipeWire support in WebRTC using GIO."
+ AUTODETECT false
+ CONDITION QT_FEATURE_webengine_webrtc AND GIO_FOUND
+)
+qt_feature("webengine-full-debug-info" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Full debug information"
+ PURPOSE "Enables debug information for Blink and V8."
+ AUTODETECT OFF
+ CONDITION CMAKE_BUILD_TYPE STREQUAL Debug OR Debug IN_LIST CMAKE_CONFIGURATION_TYPES OR
+ CMAKE_BUILD_TYPE STREQUAL RelWithDebInfo OR RelWithDebInfo IN_LIST CMAKE_CONFIGURATION_TYPES
+)
+qt_feature("webengine-sanitizer" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Sanitizer support"
+ PURPOSE "Enables support for build with sanitizers"
+ AUTODETECT CLANG
+ CONDITION CLANG AND ECM_ENABLE_SANITIZERS
+)
+qt_feature("webengine-vulkan" PRIVATE
+ SECTION "WebEngine"
+ LABEL "Vulkan support"
+ PURPOSE "Enables support for Vulkan rendering"
+ CONDITION QT_FEATURE_vulkan
+)
+qt_feature("webengine-vaapi" PRIVATE
+ SECTION "WebEngine"
+ LABEL "VA-API support"
+ PURPOSE "Enables support for VA-API hardware acceleration"
+ AUTODETECT GBM_FOUND AND LIBVA_FOUND AND QT_FEATURE_vulkan
+ # hardware accelerated encoding requires bundled libvpx
+ CONDITION LINUX AND NOT QT_FEATURE_webengine_system_libvpx
+)
+list(LENGTH CMAKE_OSX_ARCHITECTURES osx_arch_count)
+qt_feature("webenginedriver" PUBLIC
+ SECTION "WebEngine"
+ LABEL "Build WebEngineDriver"
+ PURPOSE "Enables WebEngineDriver build"
+ CONDITION NOT CMAKE_CROSSCOMPILING
+ AND NOT (CMAKE_OSX_ARCHITECTURES AND osx_arch_count GREATER 1)
+ DISABLE CMAKE_BUILD_TYPE STREQUAL Debug
+)
+# internal testing feature
+qt_feature("webengine-system-poppler" PRIVATE
+ LABEL "poppler"
+ CONDITION UNIX AND TEST_poppler
+)
+qt_configure_add_summary_section(NAME "Qt WebEngineCore")
+qt_configure_add_summary_entry(ARGS "webengine-embedded-build")
+qt_configure_add_summary_entry(ARGS "webengine-full-debug-info")
+qt_configure_add_summary_entry(ARGS "webengine-sanitizer")
+qt_configure_add_summary_entry(ARGS "webengine-pepper-plugins")
+qt_configure_add_summary_entry(ARGS "webengine-printing-and-pdf")
+qt_configure_add_summary_entry(ARGS "webengine-proprietary-codecs")
+qt_configure_add_summary_entry(ARGS "webengine-spellchecker")
+qt_configure_add_summary_entry(
+ ARGS "webengine-native-spellchecker"
+ CONDITION NOT LINUX
+)
+qt_configure_add_summary_entry(ARGS "webengine-webrtc")
+qt_configure_add_summary_entry(ARGS "webengine-webrtc-pipewire")
+qt_configure_add_summary_entry(ARGS "webengine-geolocation")
+qt_configure_add_summary_entry(ARGS "webengine-webchannel")
+qt_configure_add_summary_entry(ARGS "webengine-kerberos")
+qt_configure_add_summary_entry(ARGS "webengine-extensions")
+qt_configure_add_summary_entry(
+ ARGS "webengine-ozone-x11"
+ CONDITION UNIX
+)
+qt_configure_add_summary_entry(
+ ARGS "webengine-vulkan"
+ CONDITION QT_FEATURE_vulkan
+)
+qt_configure_add_summary_entry(
+ ARGS "webengine-vaapi"
+ CONDITION LINUX
+)
+qt_configure_add_summary_entry(
+ ARGS "webengine-system-alsa"
+ CONDITION LINUX
+)
+qt_configure_add_summary_entry(
+ ARGS "webengine-system-pulseaudio"
+ CONDITION LINUX
+)
+qt_configure_add_summary_entry(ARGS "webengine-v8-context-snapshot")
+qt_configure_add_summary_entry(ARGS "webenginedriver")
+qt_configure_end_summary_section() # end of "Qt WebEngineCore" section
+if(CMAKE_CROSSCOMPILING)
+ check_thumb(armThumb)
+ qt_configure_add_report_entry(
+ TYPE WARNING
+ MESSAGE "Thumb instruction set is required to build ffmpeg for QtWebEngine."
+ CONDITION LINUX
+ AND NOT QT_FEATURE_webengine_system_ffmpeg
+ AND TEST_architecture_arch MATCHES arm
+ AND NOT armThumb
+ )
+endif()
+qt_configure_add_report_entry(
+ TYPE WARNING
+ MESSAGE "WebRTC requires XDamage with qpa_xcb."
+ CONDITION QT_FEATURE_webengine_ozone_x11 AND NOT XDAMAGE_FOUND
+)
+qt_configure_add_report_entry(
+ TYPE WARNING
+ MESSAGE "VA-API is incompatible with system libvpx."
+ CONDITION QT_FEATURE_webengine_system_libvpx AND QT_FEATURE_webengine_vaapi
+)
+qt_configure_add_report_entry(
+ TYPE WARNING
+ MESSAGE "System GBM is disabled. The bundled minigbm supports Intel only, you might need to install libgbm to avoid rendering issues."
+ CONDITION LINUX AND NOT QT_FEATURE_webengine_system_gbm
+)
diff --git a/src/core/api/core_api.pro b/src/core/api/core_api.pro
deleted file mode 100644
index c4ad5f643..000000000
--- a/src/core/api/core_api.pro
+++ /dev/null
@@ -1,80 +0,0 @@
-TARGET = qtwebenginecoreapi$$qtPlatformTargetSuffix()
-DESTDIR = $$OUT_PWD/$$getConfigDir()
-
-TEMPLATE = lib
-
-CONFIG += staticlib
-QT += network core-private webenginecoreheaders-private
-
-# Don't create .prl file for this intermediate library because
-# their contents get used when linking against them, breaking
-# "-Wl,-whole-archive -lqtwebenginecoreapi --Wl,-no-whole-archive"
-CONFIG -= create_prl
-
-# Copy this logic from qt_module.prf so that the intermediate library can be
-# created to the same rules as the final module linking in core_module.pro.
-!host_build:if(win32|mac):!macx-xcode {
- qtConfig(debug_and_release): CONFIG += debug_and_release
- qtConfig(build_all): CONFIG += build_all
-}
-
-DEFINES += \
- BUILDING_CHROMIUM \
- NOMINMAX
-
-CHROMIUM_SRC_DIR = $$QTWEBENGINE_ROOT/$$getChromiumSrcDir()
-CHROMIUM_GEN_DIR = $$OUT_PWD/../$$getConfigDir()/gen
-INCLUDEPATH += $$QTWEBENGINE_ROOT/src/core \
- $$CHROMIUM_GEN_DIR \
- $$CHROMIUM_SRC_DIR
-
-gcc: QMAKE_CXXFLAGS_WARN_ON = -Wno-unused-parameter
-
-HEADERS = \
- qwebenginecallback.h \
- qwebenginecallback_p.h \
- qwebengineclientcertificatestore.h \
- qtwebenginecoreglobal.h \
- qtwebenginecoreglobal_p.h \
- qwebenginecookiestore.h \
- qwebenginecookiestore_p.h \
- qwebenginefindtextresult.h \
- qwebenginehttprequest.h \
- qwebenginemessagepumpscheduler_p.h \
- qwebenginenotification.h \
- qwebenginequotarequest.h \
- qwebengineregisterprotocolhandlerrequest.h \
- qwebengineurlrequestinterceptor.h \
- qwebengineurlrequestinfo.h \
- qwebengineurlrequestinfo_p.h \
- qwebengineurlrequestjob.h \
- qwebengineurlscheme.h \
- qwebengineurlschemehandler.h
-
-SOURCES = \
- qtwebenginecoreglobal.cpp \
- qwebengineclientcertificatestore.cpp \
- qwebenginecookiestore.cpp \
- qwebenginefindtextresult.cpp \
- qwebenginehttprequest.cpp \
- qwebenginemessagepumpscheduler.cpp \
- qwebenginenotification.cpp \
- qwebenginequotarequest.cpp \
- qwebengineregisterprotocolhandlerrequest.cpp \
- qwebengineurlrequestinfo.cpp \
- qwebengineurlrequestjob.cpp \
- qwebengineurlscheme.cpp \
- qwebengineurlschemehandler.cpp
-
-# Chromium headers included are not remotely clean
-CONFIG -= warning_clean
-
-msvc {
- # Create a list of object files that can be used as response file for the linker.
- # This is done to simulate -whole-archive on MSVC.
- QMAKE_POST_LINK = \
- "if exist $(DESTDIR_TARGET).objects del $(DESTDIR_TARGET).objects$$escape_expand(\\n\\t)" \
- "for %%a in ($(OBJECTS)) do echo $$shell_quote($$shell_path($$OUT_PWD))\\%%a >> $(DESTDIR_TARGET).objects"
-}
-
-load(qt_common)
diff --git a/src/core/api/qt_cmdline.cmake b/src/core/api/qt_cmdline.cmake
new file mode 100644
index 000000000..fe7092b8c
--- /dev/null
+++ b/src/core/api/qt_cmdline.cmake
@@ -0,0 +1,34 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+qt_commandline_option(webengine-embedded-build TYPE boolean)
+qt_commandline_option(webengine-pepper-plugins TYPE boolean)
+qt_commandline_option(webengine-printing-and-pdf TYPE boolean)
+qt_commandline_option(webengine-proprietary-codecs TYPE boolean)
+qt_commandline_option(webengine-spellchecker TYPE boolean)
+qt_commandline_option(webengine-native-spellchecker TYPE boolean)
+qt_commandline_option(webengine-webrtc TYPE boolean)
+qt_commandline_option(webengine-full-debug-info TYPE boolean)
+qt_commandline_option(webengine-sanitizer TYPE boolean)
+
+qt_commandline_option(webengine-jumbo-build TYPE jumbo)
+function(qt_commandline_jumbo arg val nextok)
+ if ("${val}" STREQUAL "")
+ qtConfGetNextCommandlineArg(val)
+ endif()
+ if ("${val}" STREQUAL "no")
+ qtConfCommandlineSetInput(webengine_jumbo_file_merge_limit 0)
+ elseif("${val}" STREQUAL "")
+ qtConfCommandlineSetInput(webengine_jumbo_file_merge_limit 8)
+ elseif (val MATCHES "[0-9]+")
+ qtConfCommandlineSetInput(webengine_jumbo_file_merge_limit ${val})
+ else()
+ qtConfAddError("Invalid argument '${val}' to command line parameter '${arg}'")
+ endif()
+endfunction()
+
+set(systemLibs alsa ffmpeg freetype harfbuzz icu lcms2 libevent libjpeg
+ libpng libvpx libxml libwebp minizip opus pulseaudio re2 snappy zlib)
+foreach(slib ${systemLibs})
+ qt_commandline_option(webengine-${slib} TYPE enum NAME webengine-system-${slib} VALUES yes no system)
+endforeach()
diff --git a/src/core/api/qtwebenginecoreglobal.cpp b/src/core/api/qtwebenginecoreglobal.cpp
index ce4362741..d5112ccb3 100644
--- a/src/core/api/qtwebenginecoreglobal.cpp
+++ b/src/core/api/qtwebenginecoreglobal.cpp
@@ -1,81 +1,31 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qtwebenginecoreglobal_p.h"
#include <QGuiApplication>
#if QT_CONFIG(opengl)
# include <QOpenGLContext>
-#ifdef Q_OS_MACOS
-#include <sys/types.h>
-#include <sys/sysctl.h>
-#endif
#endif
#include <QThread>
+#include <QQuickWindow>
+#include "web_engine_context.h"
+#include "web_engine_library_info.h"
-#if QT_CONFIG(opengl)
+#include "base/base_paths.h"
+#include "base/i18n/icu_util.h"
+#include "base/path_service.h"
+#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
+
+#if QT_CONFIG(opengl) && !defined(Q_OS_MACOS)
QT_BEGIN_NAMESPACE
Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext *context);
Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
QT_END_NAMESPACE
#endif
-#if QT_CONFIG(opengl)
-#ifdef Q_OS_MACOS
-static bool needsOfflineRendererWorkaround()
-{
- size_t hwmodelsize = 0;
-
- if (sysctlbyname("hw.model", nullptr, &hwmodelsize, nullptr, 0) == -1)
- return false;
-
- char hwmodel[hwmodelsize];
- if (sysctlbyname("hw.model", &hwmodel, &hwmodelsize, nullptr, 0) == -1)
- return false;
-
- return QString::fromLatin1(hwmodel) == QLatin1String("MacPro6,1");
-}
-#endif
-#endif
-
namespace QtWebEngineCore {
-#if QT_CONFIG(opengl)
+#if QT_CONFIG(opengl) && !defined(Q_OS_MACOS)
static QOpenGLContext *shareContext;
static void deleteShareContext()
@@ -88,52 +38,105 @@ static void deleteShareContext()
#endif
// ### Qt 6: unify this logic and Qt::AA_ShareOpenGLContexts.
-// QtWebEngine::initialize was introduced first and meant to be called
+// QtWebEngineQuick::initialize was introduced first and meant to be called
// after the QGuiApplication creation, when AA_ShareOpenGLContexts fills
// the same need but the flag has to be set earlier.
-Q_WEBENGINECORE_PRIVATE_EXPORT void initialize()
+Q_WEBENGINECORE_EXPORT void initialize()
{
-#if QT_CONFIG(opengl)
+#if QT_CONFIG(opengl) && !defined(Q_OS_MACOS)
#ifdef Q_OS_WIN32
qputenv("QT_D3DCREATE_MULTITHREADED", "1");
#endif
-#ifdef Q_OS_MACOS
- if (needsOfflineRendererWorkaround())
- qputenv("QT_MAC_PRO_WEBENGINE_WORKAROUND", "1");
+ auto api = QQuickWindow::graphicsApi();
+ if (api != QSGRendererInterface::OpenGL
+#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
+ && api != QSGRendererInterface::Vulkan && api != QSGRendererInterface::Metal
+ && api != QSGRendererInterface::Direct3D11
#endif
+ )
+ QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
// No need to override the shared context if QApplication already set one (e.g with Qt::AA_ShareOpenGLContexts).
- if (qt_gl_global_share_context())
- return;
+ if (!qt_gl_global_share_context()) {
- QCoreApplication *app = QCoreApplication::instance();
- if (!app) {
- qFatal("QtWebEngine::initialize() but no core application instance.");
- return;
- }
+ QCoreApplication *app = QCoreApplication::instance();
+ if (!app) {
+ qFatal("QtWebEngineQuick::initialize() but no core application instance.");
+ return;
+ }
- // Bail out silently if the user did not construct a QGuiApplication.
- if (!qobject_cast<QGuiApplication *>(app))
- return;
+ // Bail out silently if the user did not construct a QGuiApplication.
+ if (!qobject_cast<QGuiApplication *>(app))
+ return;
- if (app->thread() != QThread::currentThread()) {
- qFatal("QtWebEngine::initialize() must be called from the Qt gui thread.");
- return;
+ if (app->thread() != QThread::currentThread()) {
+ qFatal("QtWebEngineQuick::initialize() must be called from the Qt gui thread.");
+ return;
+ }
+
+ if (shareContext)
+ return;
+
+ shareContext = new QOpenGLContext;
+ QSurfaceFormat format = QSurfaceFormat::defaultFormat();
+
+ shareContext->setFormat(format);
+ shareContext->create();
+ qAddPostRoutine(deleteShareContext);
+ qt_gl_set_global_share_context(shareContext);
+
+ // Classes like QOpenGLWidget check for the attribute
+ app->setAttribute(Qt::AA_ShareOpenGLContexts);
}
- if (shareContext)
- return;
+#endif // QT_CONFIG(opengl) && !defined(Q_OS_MACOS)
+}
- shareContext = new QOpenGLContext;
- QSurfaceFormat format = QSurfaceFormat::defaultFormat();
-// format.setOption(QSurfaceFormat::ResetNotification);
- shareContext->setFormat(format);
- shareContext->create();
- qAddPostRoutine(deleteShareContext);
- qt_gl_set_global_share_context(shareContext);
+bool closingDown()
+{
+ return WebEngineContext::closingDown();
+}
- // Classes like QOpenGLWidget check for the attribute
- app->setAttribute(Qt::AA_ShareOpenGLContexts);
+} // namespace QtWebEngineCore
+
+#if defined(Q_OS_WIN)
+namespace QtWebEngineSandbox {
+sandbox::SandboxInterfaceInfo *staticSandboxInterfaceInfo(sandbox::SandboxInterfaceInfo *info)
+{
+ static sandbox::SandboxInterfaceInfo *g_info = nullptr;
+ if (info) {
+ Q_ASSERT(g_info == nullptr);
+ g_info = info;
+ }
+ return g_info;
+}
+} //namespace
+#endif
+static void initialize()
+{
+#if QT_CONFIG(opengl) && !defined(Q_OS_MACOS)
+ // QCoreApplication is not yet instantiated, ensuring the call will be deferred
+ qAddPreRoutine(QtWebEngineCore::initialize);
#endif // QT_CONFIG(opengl)
}
-} // namespace QtWebEngineCore
+
+QT_BEGIN_NAMESPACE
+
+QString qWebEngineGetDomainAndRegistry(const QUrl &url) {
+ base::FilePath icuDataPath;
+ // Let's assume that ICU is already initialized if DIR_QT_LIBRARY_DATA is set.
+ if (!base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &icuDataPath)) {
+ icuDataPath = WebEngineLibraryInfo::getPath(base::DIR_QT_LIBRARY_DATA);
+ if (!base::PathService::OverrideAndCreateIfNeeded(base::DIR_QT_LIBRARY_DATA, icuDataPath, false, false))
+ qWarning("Failed to set ICU data path.");
+ base::i18n::InitializeICU();
+ }
+
+ const QString host = url.host();
+ const std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(host.toStdString(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
+ return QString::fromStdString(domain);
+}
+
+QT_END_NAMESPACE
+
+Q_CONSTRUCTOR_FUNCTION(initialize)
diff --git a/src/core/api/qtwebenginecoreglobal.h b/src/core/api/qtwebenginecoreglobal.h
index c425d1478..0041a72be 100644
--- a/src/core/api/qtwebenginecoreglobal.h
+++ b/src/core/api/qtwebenginecoreglobal.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTWEBENGINECOREGLOBAL_H
#define QTWEBENGINECOREGLOBAL_H
@@ -45,6 +9,8 @@
QT_BEGIN_NAMESPACE
+class QUrl;
+
#if defined(BUILDING_CHROMIUM)
# define Q_WEBENGINECORE_EXPORT Q_DECL_EXPORT
#else
@@ -53,6 +19,13 @@ QT_BEGIN_NAMESPACE
#define ASSERT_ENUMS_MATCH(A, B) Q_STATIC_ASSERT_X(static_cast<int>(A) == static_cast<int>(B), "The enum values must match");
+Q_WEBENGINECORE_EXPORT Q_DECL_CONST_FUNCTION const char *qWebEngineVersion() noexcept;
+Q_WEBENGINECORE_EXPORT Q_DECL_CONST_FUNCTION const char *qWebEngineProcessName() noexcept;
+Q_WEBENGINECORE_EXPORT Q_DECL_CONST_FUNCTION const char *qWebEngineChromiumVersion() noexcept;
+Q_WEBENGINECORE_EXPORT Q_DECL_CONST_FUNCTION const char *qWebEngineChromiumSecurityPatchVersion() noexcept;
+
+Q_WEBENGINECORE_EXPORT QString qWebEngineGetDomainAndRegistry(const QUrl &url);
+
QT_END_NAMESPACE
#endif // QTWEBENGINECOREGLOBAL_H
diff --git a/src/core/api/qtwebenginecoreglobal_p.h b/src/core/api/qtwebenginecoreglobal_p.h
index 655b2a814..a63568c8a 100644
--- a/src/core/api/qtwebenginecoreglobal_p.h
+++ b/src/core/api/qtwebenginecoreglobal_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTWEBENGINECOREGLOBAL_P_H
#define QTWEBENGINECOREGLOBAL_P_H
@@ -63,6 +27,17 @@
#define QT_NOT_USED Q_UNREACHABLE(); // This will assert in debug.
#endif
-#define Q_WEBENGINECORE_PRIVATE_EXPORT Q_WEBENGINECORE_EXPORT
-
+namespace QtWebEngineCore {
+Q_WEBENGINECORE_EXPORT int processMain(int argc, const char **argv);
+Q_WEBENGINECORE_EXPORT bool closingDown();
+} // namespace
+#if defined(Q_OS_WIN)
+namespace sandbox {
+struct SandboxInterfaceInfo;
+}
+namespace QtWebEngineSandbox {
+Q_WEBENGINECORE_EXPORT sandbox::SandboxInterfaceInfo *staticSandboxInterfaceInfo(sandbox::SandboxInterfaceInfo *info = nullptr);
+void initializeStaticCopy(int argc, const char **argv);
+}
+#endif
#endif // QTWEBENGINECOREGLOBAL_P_H
diff --git a/src/core/api/qwebenginecallback.h b/src/core/api/qwebenginecallback.h
deleted file mode 100644
index 49efc50b2..000000000
--- a/src/core/api/qwebenginecallback.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWEBENGINECALLBACK_H
-#define QWEBENGINECALLBACK_H
-
-#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-
-#include <QtCore/qshareddata.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qvariant.h>
-
-namespace QtWebEngineCore {
-class CallbackDirectory;
-}
-
-QT_BEGIN_NAMESPACE
-
-namespace QtWebEnginePrivate {
-
-template<typename T>
-class QWebEngineCallbackPrivateBase : public QSharedData {
-public:
- QWebEngineCallbackPrivateBase() {}
- virtual ~QWebEngineCallbackPrivateBase() {}
- virtual void operator()(T) = 0;
-};
-
-template<typename T, typename F>
-class QWebEngineCallbackPrivate : public QWebEngineCallbackPrivateBase<T> {
-public:
- QWebEngineCallbackPrivate(F callable) : m_callable(callable) {}
- void operator()(T value) override { m_callable(value); }
-
-private:
- F m_callable;
-};
-
-} // namespace QtWebEnginePrivate
-
-template<typename T>
-class QWebEngineCallback {
-public:
- template<typename F>
- QWebEngineCallback(F f)
- : d(new QtWebEnginePrivate::QWebEngineCallbackPrivate<T, F>(f))
- {}
- QWebEngineCallback() {}
- void swap(QWebEngineCallback &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
- operator bool() const { return d; }
-
-private:
- friend class QtWebEngineCore::CallbackDirectory;
- QExplicitlySharedDataPointer<QtWebEnginePrivate::QWebEngineCallbackPrivateBase<T>> d;
-};
-
-Q_DECLARE_SHARED(QWebEngineCallback<int>)
-Q_DECLARE_SHARED(QWebEngineCallback<const QByteArray &>)
-Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QWebEngineCallback<bool>)
-Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QWebEngineCallback<const QString &>)
-Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QWebEngineCallback<const QVariant &>)
-
-QT_END_NAMESPACE
-
-#endif // QWEBENGINECALLBACK_H
diff --git a/src/core/api/qwebenginecallback_p.h b/src/core/api/qwebenginecallback_p.h
deleted file mode 100644
index 133a86f6d..000000000
--- a/src/core/api/qwebenginecallback_p.h
+++ /dev/null
@@ -1,253 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWEBENGINECALLBACK_P_H
-#define QWEBENGINECALLBACK_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qtwebenginecoreglobal_p.h"
-#include "qwebenginecallback.h"
-
-#include <QByteArray>
-#include <QHash>
-#include <QSharedData>
-#include <QString>
-#include <QVariant>
-#include <type_traits>
-
-// keep in sync with Q_DECLARE_SHARED... in qwebenginecallback.h
-#define FOR_EACH_TYPE(F) \
- F(bool) \
- F(int) \
- F(const QString &) \
- F(const QByteArray &) \
- F(const QVariant &)
-
-namespace QtWebEngineCore {
-
-class CallbackDirectory {
- template<typename T>
- void invokeInternal(quint64 callbackId, T result);
- template<typename T>
- void invokeEmptyInternal(QtWebEnginePrivate::QWebEngineCallbackPrivateBase<T> *callback);
-
-public:
- ~CallbackDirectory()
- {
- // "Cancel" pending callbacks by calling them with an invalid value.
- // This guarantees that each callback is called exactly once.
- for (CallbackSharedDataPointerBase *const sharedPtrBase : m_callbackMap) {
- Q_ASSERT(sharedPtrBase);
- sharedPtrBase->invokeEmpty();
- delete sharedPtrBase;
- }
- }
-
- enum ReservedCallbackIds {
- NoCallbackId = 0,
- DeleteCookieCallbackId,
- DeleteSessionCookiesCallbackId,
- DeleteAllCookiesCallbackId,
- GetAllCookiesCallbackId,
-
- // Place reserved id's before this.
- ReservedCallbackIdsEnd
- };
-
- template<typename T>
- void registerCallback(quint64 callbackId, const QWebEngineCallback<T> &callback);
-
- template<typename T>
- void invokeEmpty(const QWebEngineCallback<T> &callback);
-
-#define DEFINE_INVOKE_FOR_TYPE(Type) \
- void invoke(quint64 callbackId, Type result) { invokeInternal<Type>(callbackId, std::forward<Type>(result)); }
- FOR_EACH_TYPE(DEFINE_INVOKE_FOR_TYPE)
-#undef DEFINE_INVOKE_FOR_TYPE
-
- template<typename A>
- void invokeDirectly(const QWebEngineCallback<typename std::remove_reference<A>::type &> &callback, A &argument)
- {
- return callback.d.data()->operator()(argument);
- }
-
- template<typename A>
- void invokeDirectly(const QWebEngineCallback<typename std::remove_reference<A>::type> &callback, const A &argument)
- {
- return callback.d.data()->operator()(std::forward<const A &>(argument));
- }
-
-private:
- struct CallbackSharedDataPointerBase {
- virtual ~CallbackSharedDataPointerBase() {}
- virtual void invokeEmpty() = 0;
- virtual void doRef() = 0;
- virtual void doDeref() = 0;
- virtual operator bool() const = 0;
- };
-
- template<typename T>
- struct CallbackSharedDataPointer : public CallbackSharedDataPointerBase {
- CallbackDirectory *parent;
- QtWebEnginePrivate::QWebEngineCallbackPrivateBase<T> *callback;
-
- ~CallbackSharedDataPointer() { doDeref(); }
- CallbackSharedDataPointer() : parent(0), callback(0) {}
- CallbackSharedDataPointer(const CallbackSharedDataPointer<T> &other)
- : parent(other.parent), callback(other.callback)
- {
- doRef();
- }
- CallbackSharedDataPointer(CallbackDirectory *p, QtWebEnginePrivate::QWebEngineCallbackPrivateBase<T> *c)
- : parent(p), callback(c)
- {
- Q_ASSERT(callback);
- doRef();
- }
-
- void invokeEmpty() override;
- operator bool() const override { return callback; }
-
- private:
- void doRef() override;
- void doDeref() override;
- };
-
- QHash<quint64, CallbackSharedDataPointerBase *> m_callbackMap;
-};
-
-template<typename T>
-inline void CallbackDirectory::registerCallback(quint64 callbackId, const QWebEngineCallback<T> &callback)
-{
- if (!callback.d)
- return;
- m_callbackMap.insert(callbackId, new CallbackSharedDataPointer<T>(this, callback.d.data()));
-}
-
-template<typename T>
-inline void CallbackDirectory::invokeInternal(quint64 callbackId, T result)
-{
- CallbackSharedDataPointerBase *const sharedPtrBase = m_callbackMap.take(callbackId);
- if (!sharedPtrBase)
- return;
-
- auto ptr = static_cast<CallbackSharedDataPointer<T> *>(sharedPtrBase);
- Q_ASSERT(ptr);
- (*ptr->callback)(std::forward<T>(result));
- delete ptr;
-}
-
-template<typename T>
-inline void CallbackDirectory::invokeEmptyInternal(QtWebEnginePrivate::QWebEngineCallbackPrivateBase<T> *callback)
-{
- Q_ASSERT(callback);
- using NoRefT = typename std::remove_reference<T>::type;
- using NoConstNoRefT = typename std::remove_const<NoRefT>::type;
- NoConstNoRefT t;
- (*callback)(t);
-}
-
-template<>
-inline void CallbackDirectory::invokeEmptyInternal(QtWebEnginePrivate::QWebEngineCallbackPrivateBase<bool> *callback)
-{
- Q_ASSERT(callback);
- (*callback)(false);
-}
-
-template<>
-inline void CallbackDirectory::invokeEmptyInternal(QtWebEnginePrivate::QWebEngineCallbackPrivateBase<int> *callback)
-{
- Q_ASSERT(callback);
- (*callback)(0);
-}
-
-template<typename T>
-inline void CallbackDirectory::invokeEmpty(const QWebEngineCallback<T> &callback)
-{
- if (!callback.d)
- return;
-
- invokeEmptyInternal(callback.d.data());
-}
-
-template<typename T>
-inline void CallbackDirectory::CallbackSharedDataPointer<T>::doRef()
-{
- if (!callback)
- return;
-
- callback->ref.ref();
-}
-
-template<typename T>
-inline void CallbackDirectory::CallbackSharedDataPointer<T>::doDeref()
-{
- if (!callback)
- return;
- if (!callback->ref.deref())
- delete callback;
-}
-
-template<typename T>
-inline void CallbackDirectory::CallbackSharedDataPointer<T>::invokeEmpty()
-{
- if (!callback)
- return;
-
- Q_ASSERT(parent);
- parent->invokeEmptyInternal(callback);
-}
-
-#define CHECK_RELOCATABLE(x) Q_STATIC_ASSERT((QTypeInfoQuery<QWebEngineCallback<x>>::isRelocatable));
-FOR_EACH_TYPE(CHECK_RELOCATABLE)
-#undef CHECK_RELOCATABLE
-
-} // namespace QtWebEngineCore
-
-#endif // QWEBENGINECALLBACK_P_H
diff --git a/src/core/api/qwebenginecertificateerror.cpp b/src/core/api/qwebenginecertificateerror.cpp
new file mode 100644
index 000000000..90d8a542d
--- /dev/null
+++ b/src/core/api/qwebenginecertificateerror.cpp
@@ -0,0 +1,162 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginecertificateerror.h"
+
+#include "certificate_error_controller.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineCertificateError
+ \brief The QWebEngineCertificateError class provides information about a certificate error.
+ \since 5.4
+ \inmodule QtWebEngineCore
+
+ Provides information about a certificate error. This class is used as a parameter of
+ QWebEnginePage::certificateError().
+*/
+
+/*! \internal
+*/
+QWebEngineCertificateError::QWebEngineCertificateError(
+ const QSharedPointer<QtWebEngineCore::CertificateErrorController> &controller)
+ : d(controller)
+{
+}
+
+QWebEngineCertificateError::QWebEngineCertificateError(const QWebEngineCertificateError &) = default;
+
+QWebEngineCertificateError& QWebEngineCertificateError::operator=(const QWebEngineCertificateError &) = default;
+
+/*! \internal
+*/
+QWebEngineCertificateError::~QWebEngineCertificateError() = default;
+
+/*!
+ \enum QWebEngineCertificateError::Type
+
+ This enum describes the type of certificate error encountered.
+
+ The values of this enum type match the SSL errors Chromium provides.
+ QSslError::SslError values are not used directly, because the Qt error
+ categories cannot be mapped to the Chromium error categories.
+
+ \value SslPinnedKeyNotInCertificateChain The certificate did not match the built-in public keys
+ pinned for the host name.
+ \value CertificateCommonNameInvalid The certificate's common name did not match the host name.
+ \value CertificateDateInvalid The certificate is not valid at the current date and time.
+ \value CertificateAuthorityInvalid The certificate is not signed by a trusted authority.
+ \value CertificateContainsErrors The certificate contains errors.
+ \value CertificateNoRevocationMechanism The certificate has no mechanism for determining if it has been revoked.
+ \value CertificateUnableToCheckRevocation Revocation information for the certificate is not available.
+ \value CertificateRevoked The certificate has been revoked.
+ \value CertificateInvalid The certificate is invalid.
+ \value CertificateWeakSignatureAlgorithm The certificate is signed using a weak signature algorithm.
+ \value CertificateNonUniqueName The host name specified in the certificate is not unique.
+ \value CertificateWeakKey The certificate contains a weak key.
+ \value CertificateNameConstraintViolation The certificate claimed DNS names that are in violation of name constraints.
+ \value CertificateValidityTooLong The certificate has a validity period that is too long. (Added in Qt 5.7)
+ \value CertificateTransparencyRequired Certificate Transparency was required for this connection, but the server
+ did not provide CT information that complied with the policy. (Added in Qt 5.8)
+ \value CertificateKnownInterceptionBlocked The certificate is known to be
+ used for interception by an entity other the device owner. (Added in
+ 5.15)
+ \value SslObsoleteVersion The connection uses an obsolete version of SSL/TLS. (Added in Qt 6.2, deprecated in Qt 6.4)
+ \value CertificateSymantecLegacy The certificate is a legacy Symantec one that's no longer valid. (Added in Qt 6.2)
+*/
+
+/*!
+ \property QWebEngineCertificateError::overridable
+ \brief Whether this error can be overridden and accepted.
+
+ \sa description()
+*/
+bool QWebEngineCertificateError::isOverridable() const
+{
+ return d->overridable();
+}
+
+/*!
+ Returns the URL that triggered the error.
+
+ \sa description()
+*/
+QUrl QWebEngineCertificateError::url() const
+{
+ return d->url();
+}
+
+/*!
+ Returns the type of the error.
+
+ \sa description(), isOverridable()
+*/
+QWebEngineCertificateError::Type QWebEngineCertificateError::type() const
+{
+ return d->error();
+}
+
+/*!
+ Returns a short localized human-readable description of the error.
+
+ \sa url(), isOverridable()
+*/
+QString QWebEngineCertificateError::description() const
+{
+ return d->errorString();
+}
+
+/*!
+ \since 5.14
+
+ Marks the certificate error for delayed handling.
+
+ This function should be called when there is a need to postpone the decision whether to accept a
+ certificate, for example, while waiting for user input. When called, the function pauses the
+ URL request until acceptCertificate() or rejectCertificate() is called.
+
+ \note It is only possible to defer overridable certificate errors.
+
+ \sa isOverridable()
+*/
+void QWebEngineCertificateError::defer()
+{
+ d->defer();
+}
+
+/*!
+ \since 5.14
+
+ Accepts the certificate and continues the loading of the requested URL.
+*/
+void QWebEngineCertificateError::acceptCertificate()
+{
+ d->ignoreCertificateError();
+}
+
+/*!
+ \since 5.14
+
+ Rejects the certificate and aborts the loading of the requested URL.
+*/
+void QWebEngineCertificateError::rejectCertificate()
+{
+ d->rejectCertificate();
+}
+
+/*!
+ \since 5.14
+
+ Returns the peer's chain of digital certificates.
+
+ Chain starts with the peer's immediate certificate and ending with the CA's certificate.
+*/
+QList<QSslCertificate> QWebEngineCertificateError::certificateChain() const
+{
+ return d->certificateChain();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginecertificateerror.cpp"
diff --git a/src/core/api/qwebenginecertificateerror.h b/src/core/api/qwebenginecertificateerror.h
new file mode 100644
index 000000000..c4a3585f4
--- /dev/null
+++ b/src/core/api/qwebenginecertificateerror.h
@@ -0,0 +1,78 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINECERTIFICATEERROR_H
+#define QWEBENGINECERTIFICATEERROR_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qsharedpointer.h>
+#include <QtCore/qurl.h>
+#include <QtNetwork/qsslcertificate.h>
+
+namespace QtWebEngineCore {
+class WebContentsDelegateQt;
+class CertificateErrorController;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineCertificateError
+{
+ Q_GADGET
+ Q_PROPERTY(QUrl url READ url CONSTANT FINAL)
+ Q_PROPERTY(Type type READ type CONSTANT FINAL)
+ Q_PROPERTY(QString description READ description CONSTANT FINAL)
+ Q_PROPERTY(bool overridable READ isOverridable CONSTANT FINAL)
+
+public:
+ QWebEngineCertificateError(const QWebEngineCertificateError &other);
+ QWebEngineCertificateError &operator=(const QWebEngineCertificateError &other);
+ ~QWebEngineCertificateError();
+
+ // Keep this identical to NET_ERROR in net_error_list.h, or add mapping layer.
+ enum Type {
+ SslPinnedKeyNotInCertificateChain = -150,
+ CertificateCommonNameInvalid = -200,
+ CertificateDateInvalid = -201,
+ CertificateAuthorityInvalid = -202,
+ CertificateContainsErrors = -203,
+ CertificateNoRevocationMechanism = -204,
+ CertificateUnableToCheckRevocation = -205,
+ CertificateRevoked = -206,
+ CertificateInvalid = -207,
+ CertificateWeakSignatureAlgorithm = -208,
+ CertificateNonUniqueName = -210,
+ CertificateWeakKey = -211,
+ CertificateNameConstraintViolation = -212,
+ CertificateValidityTooLong = -213,
+ CertificateTransparencyRequired = -214,
+ CertificateSymantecLegacy = -215,
+ CertificateKnownInterceptionBlocked = -217,
+ SslObsoleteVersion = -218,
+ };
+ Q_ENUM(Type)
+
+ Type type() const;
+ QUrl url() const;
+ bool isOverridable() const;
+ QString description() const;
+
+ Q_INVOKABLE void defer();
+ Q_INVOKABLE void rejectCertificate();
+ Q_INVOKABLE void acceptCertificate();
+
+ QList<QSslCertificate> certificateChain() const;
+
+private:
+ friend class QtWebEngineCore::WebContentsDelegateQt;
+ QWebEngineCertificateError(
+ const QSharedPointer<QtWebEngineCore::CertificateErrorController> &controller);
+ QSharedPointer<QtWebEngineCore::CertificateErrorController> d;
+};
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(QWebEngineCertificateError)
+
+#endif // QWEBENGINECERTIFICATEERROR_H
diff --git a/src/core/api/qwebengineclientcertificateselection.cpp b/src/core/api/qwebengineclientcertificateselection.cpp
new file mode 100644
index 000000000..d6402353c
--- /dev/null
+++ b/src/core/api/qwebengineclientcertificateselection.cpp
@@ -0,0 +1,88 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineclientcertificateselection.h"
+#include "client_cert_select_controller.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineClientCertificateSelection
+ \brief The QWebEngineClientCertSelection class wraps a client certificate selection.
+ \since 5.12
+ \inmodule QtWebEngineCore
+
+ When a web site requests an SSL client certificate, and one or more certificates
+ are found in the system's client certificate store, this class provides access to
+ the certificates to choose from, as well as a method for selecting one.
+
+ The selection is asynchronous. If no certificate is selected and no copy of the
+ object is kept alive, loading will continue without a certificate.
+
+ \sa QWebEnginePage::selectClientCertificate()
+*/
+
+/*! \internal
+*/
+QWebEngineClientCertificateSelection::QWebEngineClientCertificateSelection(
+ QSharedPointer<QtWebEngineCore::ClientCertSelectController> selectController)
+ : d_ptr(selectController)
+{}
+
+QWebEngineClientCertificateSelection::QWebEngineClientCertificateSelection(const QWebEngineClientCertificateSelection &other)
+ : d_ptr(other.d_ptr)
+{}
+
+QWebEngineClientCertificateSelection &QWebEngineClientCertificateSelection::operator=(const QWebEngineClientCertificateSelection &other)
+{
+ d_ptr = other.d_ptr;
+ return *this;
+}
+
+QWebEngineClientCertificateSelection::~QWebEngineClientCertificateSelection()
+{
+}
+
+/*!
+ Returns the client certificates available to choose from.
+
+ \sa select()
+*/
+QList<QSslCertificate> QWebEngineClientCertificateSelection::certificates() const
+{
+ return d_ptr->certificates();
+}
+
+/*!
+ Selects the client certificate \a certificate. The certificate must be one
+ of those offered in certificates().
+
+ \sa certificates(), selectNone()
+*/
+void QWebEngineClientCertificateSelection::select(const QSslCertificate &certificate)
+{
+ d_ptr->select(certificate);
+}
+
+/*!
+ Continue without using any of the offered certificates. This is the same
+ action as taken when destroying the last copy of this object if no
+ selection has been made.
+
+ \sa select()
+*/
+void QWebEngineClientCertificateSelection::selectNone()
+{
+ d_ptr->selectNone();
+}
+
+/*!
+ Returns the host and port of the server requesting the client certificate.
+*/
+QUrl QWebEngineClientCertificateSelection::host() const
+{
+ return d_ptr->hostAndPort();
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/core/api/qwebengineclientcertificateselection.h b/src/core/api/qwebengineclientcertificateselection.h
new file mode 100644
index 000000000..559d1753b
--- /dev/null
+++ b/src/core/api/qwebengineclientcertificateselection.h
@@ -0,0 +1,44 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINECLIENTCERTSELECTION_H
+#define QWEBENGINECLIENTCERTSELECTION_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtNetwork/qtnetwork-config.h>
+#include <QtCore/qlist.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtNetwork/qsslcertificate.h>
+
+namespace QtWebEngineCore {
+class ClientCertSelectController;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineClientCertificateSelection
+{
+public:
+ QWebEngineClientCertificateSelection(const QWebEngineClientCertificateSelection &);
+ ~QWebEngineClientCertificateSelection();
+
+ QWebEngineClientCertificateSelection &operator=(const QWebEngineClientCertificateSelection &);
+
+ QUrl host() const;
+
+ void select(const QSslCertificate &certificate);
+ void selectNone();
+ QList<QSslCertificate> certificates() const;
+
+private:
+ friend class QWebEnginePagePrivate;
+
+ QWebEngineClientCertificateSelection(
+ QSharedPointer<QtWebEngineCore::ClientCertSelectController>);
+
+ QSharedPointer<QtWebEngineCore::ClientCertSelectController> d_ptr;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINECLIENTCERTSELECTION_H
diff --git a/src/core/api/qwebengineclientcertificatestore.cpp b/src/core/api/qwebengineclientcertificatestore.cpp
index 84f273328..3d231c05f 100644
--- a/src/core/api/qwebengineclientcertificatestore.cpp
+++ b/src/core/api/qwebengineclientcertificatestore.cpp
@@ -1,47 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineclientcertificatestore.h"
#include "net/client_cert_store_data.h"
-#include <QByteArray>
#include <QList>
QT_BEGIN_NAMESPACE
@@ -57,7 +20,21 @@ QT_BEGIN_NAMESPACE
The class allows to store client certificates in an in-memory store.
When a web site requests an SSL client certificate, the QWebEnginePage::selectClientCertificate
signal is emitted with matching certificates from the native certificate store or the in-memory store.
- The getInstance() method can be used to access the single instance of the class.
+
+ The class instance can be obtained with the QWebEngineProfile::clientCertificateStore() method.
+
+ \code
+ QFile certFile(":/resouces/certificate.crt");
+ certFile.open(QIODevice::ReadOnly);
+ const QSslCertificate cert(certFile.readAll(), QSsl::Pem);
+
+ QFile keyFile(":/resources/privatekey.key");
+ keyFile.open(QIODevice::ReadOnly);
+ const QSslKey sslKey(keyFile.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, "");
+
+ QWebEngineProfile profile;
+ profile.clientCertificateStore()->add(cert, sslKey);
+ \endcode
*/
QWebEngineClientCertificateStore::QWebEngineClientCertificateStore(QtWebEngineCore::ClientCertificateStoreData *storeData)
@@ -88,10 +65,10 @@ void QWebEngineClientCertificateStore::add(const QSslCertificate &certificate, c
Returns an empty list if the store does not contain any certificates.
*/
-QVector<QSslCertificate> QWebEngineClientCertificateStore::certificates() const
+QList<QSslCertificate> QWebEngineClientCertificateStore::certificates() const
{
- QVector<QSslCertificate> certificateList;
- for (auto data : qAsConst(m_storeData->extraCerts))
+ QList<QSslCertificate> certificateList;
+ for (auto data : std::as_const(m_storeData->extraCerts))
certificateList.append(data->certificate);
return certificateList;
}
diff --git a/src/core/api/qwebengineclientcertificatestore.h b/src/core/api/qwebengineclientcertificatestore.h
index a4c83bb2e..fcebbe2b1 100644
--- a/src/core/api/qwebengineclientcertificatestore.h
+++ b/src/core/api/qwebengineclientcertificatestore.h
@@ -1,48 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINECLIENTCERTIFICATESTORE_H
#define QWEBENGINECLIENTCERTIFICATESTORE_H
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtNetwork/qtnetwork-config.h>
-#include <QtCore/qvector.h>
+#if QT_CONFIG(ssl)
+#include <QtCore/qlist.h>
#include <QtNetwork/qsslcertificate.h>
#include <QtNetwork/qsslkey.h>
@@ -53,13 +19,12 @@ class ProfileAdapter;
QT_BEGIN_NAMESPACE
-#if QT_CONFIG(ssl)
-
-class Q_WEBENGINECORE_EXPORT QWebEngineClientCertificateStore {
+class Q_WEBENGINECORE_EXPORT QWebEngineClientCertificateStore
+{
public:
void add(const QSslCertificate &certificate, const QSslKey &privateKey);
- QVector<QSslCertificate> certificates() const;
+ QList<QSslCertificate> certificates() const;
void remove(const QSslCertificate &certificate);
void clear();
@@ -72,8 +37,7 @@ private:
QtWebEngineCore::ClientCertificateStoreData *m_storeData;
};
-#endif // QT_CONFIG(ssl)
-
QT_END_NAMESPACE
+#endif // QT_CONFIG(ssl)
#endif // QWebEngineClientCertificateStore_H
diff --git a/src/core/api/qwebengineclienthints.cpp b/src/core/api/qwebengineclienthints.cpp
new file mode 100644
index 000000000..907d4ae76
--- /dev/null
+++ b/src/core/api/qwebengineclienthints.cpp
@@ -0,0 +1,211 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineclienthints.h"
+
+#include "profile_adapter.h"
+
+#include <QJsonObject>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineClientHints
+ \brief The QWebEngineClientHints class provides an object to customize User-Agent Client Hints used by a profile.
+
+ \since 6.8
+
+ \inmodule QtWebEngineCore
+
+ QWebEngineClientHints allows configuration of exposing browser and platform information via
+ User-Agent response and request headers, and a JavaScript API.
+
+ The information accessed via this API is split into two groups: low entropy and high entropy hints.
+ Low entropy hints (\l{QWebEngineClientHints::platform}{platform} and \l{QWebEngineClientHints::mobile}{mobile})
+ are those that do not give away much information; the API makes these accessible with every request and they can not
+ be disabled by QWebEngineClientHints::setAllClientHintsEnabled.
+
+ All the others are high entropy hints; they have the potential to give away more information, therefore they can be
+ disabled by QWebEngineClientHints::setAllClientHintsEnabled.
+
+ Each profile object has its own QWebEngineClientHints object, which configures the
+ Client Hint settings for that browsing context. If a Client Hint is not configured for a web engine
+ profile, its default value is deduced from the system.
+
+ \sa QWebEngineProfile::clientHints(), QQuickWebEngineProfile::clientHints()
+*/
+
+QWebEngineClientHints::QWebEngineClientHints(QtWebEngineCore::ProfileAdapter *profileAdapter)
+ : m_profileAdapter(profileAdapter)
+{
+}
+
+QWebEngineClientHints::~QWebEngineClientHints()
+{
+}
+
+/*!
+ \property QWebEngineClientHints::arch
+ The value of the \c{Sec-CH-UA-Arch} HTTP header and \c{architecture} member of NavigatorUAData in JavaScript.
+*/
+QString QWebEngineClientHints::arch() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAArchitecture).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::platform
+ The value of the \c{Sec-CH-UA-Platform} HTTP header and \c{platform} member of NavigatorUAData in JavaScript.
+
+ Can not be disabled.
+*/
+QString QWebEngineClientHints::platform() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAPlatform).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::model
+ The value of the \c{Sec-CH-UA-Model} HTTP header and \c{model} member of NavigatorUAData in JavaScript.
+*/
+QString QWebEngineClientHints::model() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAModel).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::mobile
+ The value of the \c{Sec-CH-UA-Mobile} HTTP header and \c{mobile} member of NavigatorUAData in JavaScript.
+
+ Can not be disabled.
+*/
+bool QWebEngineClientHints::isMobile() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAMobile).toBool();
+}
+
+/*!
+ \property QWebEngineClientHints::fullVersion
+ The value of the \c{Sec-CH-UA-Full-Version} HTTP header and \c{uaFullVersion} member of NavigatorUAData in JavaScript.
+*/
+QString QWebEngineClientHints::fullVersion() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAFullVersion).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::platformVersion
+ The value of the \c{Sec-CH-UA-Platform-Version} HTTP header and \c{platformVersion} member of NavigatorUAData in JavaScript.
+*/
+QString QWebEngineClientHints::platformVersion() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAPlatformVersion).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::bitness
+ The value of the \c{Sec-CH-UA-Bitness} HTTP header and \c{bitness} member of NavigatorUAData in JavaScript.
+*/
+QString QWebEngineClientHints::bitness() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UABitness).toString();
+}
+
+/*!
+ \property QWebEngineClientHints::fullVersionList
+ The value of the \c{Sec-CH-UA-Full-Version-List} HTTP header and \c{fullVersionList} member of NavigatorUAData in JavaScript.
+
+ It holds brand name and version number pairs in a QHash. The provided values will be automatically extended by the currently used version
+ of Chromium and a semi-random brand.
+*/
+QHash<QString,QString> QWebEngineClientHints::fullVersionList() const
+{
+ QHash<QString, QString> ret;
+ QJsonObject fullVersionList = m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAFullVersionList).toJsonObject();
+ for (const QString &key : fullVersionList.keys())
+ ret.insert(key, fullVersionList.value(key).toString());
+ return ret;
+}
+
+/*!
+ \property QWebEngineClientHints::wow64
+ The value of the \c{Sec-CH-UA-Wow64} HTTP header and \c{wow64} member of NavigatorUAData in JavaScript.
+*/
+bool QWebEngineClientHints::isWow64() const
+{
+ return m_profileAdapter->clientHint(QtWebEngineCore::ProfileAdapter::UAWOW64).toBool();
+}
+
+void QWebEngineClientHints::setArch(const QString &arch)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAArchitecture, QVariant(arch));
+}
+
+void QWebEngineClientHints::setPlatform(const QString &platform)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAPlatform, QVariant(platform));
+}
+
+void QWebEngineClientHints::setModel(const QString &model)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAModel, QVariant(model));
+}
+
+void QWebEngineClientHints::setIsMobile(const bool mobile)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAMobile, QVariant(mobile));
+}
+
+void QWebEngineClientHints::setFullVersion(const QString &fullVerson)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAFullVersion, QVariant(fullVerson));
+}
+
+void QWebEngineClientHints::setPlatformVersion(const QString &platformVersion)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAPlatformVersion, QVariant(platformVersion));
+}
+
+void QWebEngineClientHints::setBitness(const QString &bitness)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UABitness, QVariant(bitness));
+}
+
+void QWebEngineClientHints::setFullVersionList(const QHash<QString,QString> &fullVersionList)
+{
+ QJsonObject jsonObject;
+ for (auto i = fullVersionList.cbegin(), end = fullVersionList.cend(); i != end; ++i)
+ jsonObject.insert(i.key(), QJsonValue(i.value()));
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAFullVersionList, QVariant(jsonObject));
+}
+
+void QWebEngineClientHints::setIsWow64(const bool wow64)
+{
+ m_profileAdapter->setClientHint(QtWebEngineCore::ProfileAdapter::UAWOW64, QVariant(wow64));
+}
+
+/*!
+ \property QWebEngineClientHints::isAllClientHintsEnabled
+ This property controls whether the Client Hints HTTP headers are sent by WebEngine or not.
+
+ Enabled by default.
+*/
+bool QWebEngineClientHints::isAllClientHintsEnabled()
+{
+ return m_profileAdapter->clientHintsEnabled();
+}
+
+void QWebEngineClientHints::setAllClientHintsEnabled(bool enabled)
+{
+ m_profileAdapter->setClientHintsEnabled(enabled);
+}
+
+/*!
+ Resets all Client Hints settings to their default values.
+*/
+void QWebEngineClientHints::resetAll()
+{
+ m_profileAdapter->resetClientHints();
+}
+
+QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineclienthints.h b/src/core/api/qwebengineclienthints.h
new file mode 100644
index 000000000..8956b5cb6
--- /dev/null
+++ b/src/core/api/qwebengineclienthints.h
@@ -0,0 +1,72 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINECLIENTHINTS_H
+#define QWEBENGINECLIENTHINTS_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qhash.h>
+
+namespace QtWebEngineCore {
+class ProfileAdapter;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineClientHints
+{
+ Q_GADGET
+ Q_PROPERTY(QString arch READ arch WRITE setArch)
+ Q_PROPERTY(QString platform READ platform WRITE setPlatform)
+ Q_PROPERTY(QString model READ model WRITE setModel)
+ Q_PROPERTY(bool mobile READ isMobile WRITE setIsMobile)
+ Q_PROPERTY(QString fullVersion READ fullVersion WRITE setFullVersion)
+ Q_PROPERTY(QString platformVersion READ platformVersion WRITE setPlatformVersion)
+ Q_PROPERTY(QString bitness READ bitness WRITE setBitness)
+ Q_PROPERTY(QHash<QString,QString> fullVersionList READ fullVersionList WRITE setFullVersionList)
+ Q_PROPERTY(bool wow64 READ isWow64 WRITE setIsWow64)
+
+ Q_PROPERTY(bool isAllClientHintsEnabled READ isAllClientHintsEnabled WRITE setAllClientHintsEnabled)
+
+public:
+ ~QWebEngineClientHints();
+
+ QString arch() const;
+ QString platform() const;
+ QString model() const;
+ bool isMobile() const;
+ QString fullVersion() const;
+ QString platformVersion() const;
+ QString bitness() const;
+ QHash<QString,QString> fullVersionList() const;
+ bool isWow64() const;
+
+ void setArch(const QString &);
+ void setPlatform(const QString &);
+ void setModel(const QString &);
+ void setIsMobile(const bool);
+ void setFullVersion(const QString &);
+ void setPlatformVersion(const QString &);
+ void setBitness(const QString &);
+ void setFullVersionList(const QHash<QString,QString> &);
+ void setIsWow64(const bool);
+
+ bool isAllClientHintsEnabled();
+ void setAllClientHintsEnabled(bool enabled);
+
+ void resetAll();
+
+private:
+ explicit QWebEngineClientHints(QtWebEngineCore::ProfileAdapter *profileAdapter);
+ Q_DISABLE_COPY(QWebEngineClientHints)
+ friend class QWebEngineProfilePrivate;
+ friend class QQuickWebEngineProfilePrivate;
+
+ QtWebEngineCore::ProfileAdapter *m_profileAdapter;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINECLIENTHINTS_H
diff --git a/src/core/api/qwebenginecontextmenurequest.cpp b/src/core/api/qwebenginecontextmenurequest.cpp
new file mode 100644
index 000000000..25de1fe6b
--- /dev/null
+++ b/src/core/api/qwebenginecontextmenurequest.cpp
@@ -0,0 +1,260 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginecontextmenurequest.h"
+#include "qwebenginecontextmenurequest_p.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineContextMenuRequest
+ \since 6.2
+ \brief The QWebEngineContextMenuRequest class provides request for populating or extending a context menu with actions.
+
+ \inmodule QtWebEngineCore
+
+ QWebEngineContextMenuRequest is returned by QWebEngineView::lastContextMenuRequest() after a context menu event,
+ and contains information about where the context menu event took place. This is also in the context
+ in which any context specific QWebEnginePage::WebAction will be performed.
+*/
+
+/*!
+ \enum QWebEngineContextMenuRequest::MediaType
+ \readonly
+ \since 6.2
+
+ This enum describes the media type of the context menu request if any.
+
+ \value MediaTypeNone The context is not a media type.
+ \value MediaTypeImage The context is an image element.
+ \value MediaTypeVideo The context is a video element.
+ \value MediaTypeAudio The context is an audio element.
+ \value MediaTypeCanvas The context is a canvas element.
+ \value MediaTypeFile The context is a file.
+ \value MediaTypePlugin The context is a plugin element.
+*/
+
+/*!
+ \enum QWebEngineContextMenuRequest::EditFlag
+ \readonly
+ \since 6.2
+
+ The available edit operations in the current context menu request.
+
+ \value CanUndo Undo is available.
+ \value CanRedo Redo is available.
+ \value CanCut Cut is available.
+ \value CanCopy Copy is available.
+ \value CanPaste Paste is available.
+ \value CanDelete Delete is available.
+ \value CanSelectAll Select All is available.
+ \value CanTranslate Translate is available.
+ \value CanEditRichly Context is richly editable.
+*/
+
+/*!
+ \enum QWebEngineContextMenuRequest::MediaFlag
+ \readonly
+ \since 6.2
+
+ The current media element's status and its available operations.
+ \c MediaNone if the selected web page content is not a media element.
+
+ \value MediaInError An error occurred.
+ \value MediaPaused Media is paused.
+ \value MediaMuted Media is muted.
+ \value MediaLoop Media can be looped.
+ \value MediaCanSave Media can be saved.
+ \value MediaHasAudio Media has audio.
+ \value MediaCanToggleControls Media can show controls.
+ \value MediaControls Media controls are shown.
+ \value MediaCanPrint Media is printable.
+ \value MediaCanRotate Media is rotatable.
+*/
+
+/*!
+ \internal
+*/
+QWebEngineContextMenuRequest::QWebEngineContextMenuRequest(
+ QWebEngineContextMenuRequestPrivate *request)
+ : d(request)
+{
+}
+
+/*!
+ Destroys the context menu request.
+*/
+QWebEngineContextMenuRequest::~QWebEngineContextMenuRequest() = default;
+
+/*!
+ Returns the position of the context menu request, usually the mouse
+ position where the context menu event was triggered.
+*/
+QPoint QWebEngineContextMenuRequest::position() const
+{
+ return d->m_position;
+}
+
+/*!
+ Returns the selected text of the context menu request.
+*/
+QString QWebEngineContextMenuRequest::selectedText() const
+{
+ return d->m_selectedText;
+}
+
+/*!
+ Returns the text of a link if the context menu request was requested for a link.
+*/
+QString QWebEngineContextMenuRequest::linkText() const
+{
+ return d->m_linkText;
+}
+
+/*!
+ Returns the URL of a link if the menu context request is a link.
+ It is not guaranteed to be a valid URL.
+*/
+QUrl QWebEngineContextMenuRequest::linkUrl() const
+{
+ return d->m_unfilteredLinkUrl;
+}
+
+/*!
+ If the context menu request is a media element, returns the URL of that media.
+*/
+QUrl QWebEngineContextMenuRequest::mediaUrl() const
+{
+ return d->m_mediaUrl;
+}
+
+/*!
+ Returns the type of the media element or \c MediaTypeNone
+ if the context menu requestis not a media element.
+*/
+QWebEngineContextMenuRequest::MediaType QWebEngineContextMenuRequest::mediaType() const
+{
+ return static_cast<QWebEngineContextMenuRequest::MediaType>(d->m_mediaType);
+}
+
+/*!
+ Returns \c true if the context menu request is editable by the user;
+ otherwise returns \c false.
+*/
+bool QWebEngineContextMenuRequest::isContentEditable() const
+{
+ return d->m_isEditable;
+}
+
+/*!
+ If the menu context request is a word considered misspelled by the spell-checker,
+ returns the misspelled word.
+
+ For possible replacements of the word, see spellCheckerSuggestions().
+*/
+QString QWebEngineContextMenuRequest::misspelledWord() const
+{
+ return d->m_misspelledWord;
+}
+
+
+/*!
+ If the menu context request is a word considered misspelled by the spell-checker,
+ returns a list of suggested replacements for misspelledWord().
+*/
+QStringList QWebEngineContextMenuRequest::spellCheckerSuggestions() const
+{
+ return d->m_spellCheckerSuggestions;
+}
+
+/*!
+ \property QWebEngineContextMenuRequest::accepted
+ \brief Whether the request is accepted.
+*/
+bool QWebEngineContextMenuRequest::isAccepted() const
+{
+ return d->m_accepted;
+}
+
+void QWebEngineContextMenuRequest::setAccepted(bool accepted)
+{
+ d->m_accepted = accepted;
+}
+
+/*!
+ Returns the current media element's status and its available operations.
+ \c MediaNone if the selected web page content is not a media element.
+*/
+QWebEngineContextMenuRequest::MediaFlags QWebEngineContextMenuRequest::mediaFlags() const
+{
+ return static_cast<QWebEngineContextMenuRequest::MediaFlags>(d->m_mediaFlags);
+}
+
+/*!
+ Returns the available edit operations in the current context
+ or \c CanDoNone if no actions are available.
+*/
+QWebEngineContextMenuRequest::EditFlags QWebEngineContextMenuRequest::editFlags() const
+{
+ return static_cast<QWebEngineContextMenuRequest::EditFlags>(d->m_editFlags);
+}
+
+/*!
+ \internal
+*/
+QUrl QWebEngineContextMenuRequest::filteredLinkUrl() const
+{
+ return d->m_filteredLinkUrl;
+}
+
+/*!
+ \internal
+*/
+QString QWebEngineContextMenuRequest::altText() const
+{
+ return d->m_altText;
+}
+
+/*!
+ \internal
+*/
+QString QWebEngineContextMenuRequest::titleText() const
+{
+ return d->m_titleText;
+}
+
+/*!
+ \internal
+*/
+QUrl QWebEngineContextMenuRequest::referrerUrl() const
+{
+ return !d->m_frameUrl.isEmpty() ? d->m_frameUrl : d->m_pageUrl;
+}
+
+/*!
+ \internal
+*/
+QtWebEngineCore::ReferrerPolicy QWebEngineContextMenuRequest::referrerPolicy() const
+{
+ return d->m_referrerPolicy;
+}
+
+/*!
+ \internal
+*/
+QString QWebEngineContextMenuRequest::suggestedFileName() const
+{
+ return d->m_suggestedFileName;
+}
+
+/*!
+ \internal
+*/
+bool QWebEngineContextMenuRequest::hasImageContent() const
+{
+ return d->m_hasImageContent;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginecontextmenurequest.cpp"
diff --git a/src/core/api/qwebenginecontextmenurequest.h b/src/core/api/qwebenginecontextmenurequest.h
new file mode 100644
index 000000000..6e6f6338c
--- /dev/null
+++ b/src/core/api/qwebenginecontextmenurequest.h
@@ -0,0 +1,136 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINECONTEXTMENUREQUEST_H
+#define QWEBENGINECONTEXTMENUREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qurl.h>
+#include <QtCore/qpoint.h>
+#include <QtCore/qscopedpointer.h>
+
+namespace extensions {
+class MimeHandlerViewGuestDelegateQt;
+}
+
+namespace QtWebEngineCore {
+class RenderViewContextMenuQt;
+class WebContentsViewQt;
+
+// Must match blink::WebReferrerPolicy
+enum class ReferrerPolicy {
+ Always,
+ Default,
+ NoReferrerWhenDowngrade,
+ Never,
+ Origin,
+ OriginWhenCrossOrigin,
+ NoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ SameOrigin,
+ StrictOrigin,
+ Last = StrictOrigin,
+};
+}
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineContextMenuRequestPrivate;
+class Q_WEBENGINECORE_EXPORT QWebEngineContextMenuRequest : public QObject
+{
+ Q_OBJECT
+public:
+ // Must match blink::mojom::ContextMenuDataMediaType:
+ enum MediaType {
+ MediaTypeNone,
+ MediaTypeImage,
+ MediaTypeVideo,
+ MediaTypeAudio,
+ MediaTypeCanvas,
+ MediaTypeFile,
+ MediaTypePlugin
+ };
+ Q_ENUM(MediaType)
+
+ // Must match blink::ContextMenuData::MediaFlags:
+ enum MediaFlag {
+ MediaInError = 0x1,
+ MediaPaused = 0x2,
+ MediaMuted = 0x4,
+ MediaLoop = 0x8,
+ MediaCanSave = 0x10,
+ MediaHasAudio = 0x20,
+ MediaCanToggleControls = 0x40,
+ MediaControls = 0x80,
+ MediaCanPrint = 0x100,
+ MediaCanRotate = 0x200,
+ };
+ Q_DECLARE_FLAGS(MediaFlags, MediaFlag)
+ Q_FLAG(MediaFlags)
+
+ // Must match blink::ContextMenuDataEditFlags:
+ enum EditFlag {
+ CanUndo = 0x1,
+ CanRedo = 0x2,
+ CanCut = 0x4,
+ CanCopy = 0x8,
+ CanPaste = 0x10,
+ CanDelete = 0x20,
+ CanSelectAll = 0x40,
+ CanTranslate = 0x80,
+ CanEditRichly = 0x100,
+ };
+ Q_DECLARE_FLAGS(EditFlags, EditFlag)
+ Q_FLAG(EditFlags)
+
+ Q_PROPERTY(QPoint position READ position CONSTANT FINAL)
+ Q_PROPERTY(QString selectedText READ selectedText CONSTANT FINAL)
+ Q_PROPERTY(QString linkText READ linkText CONSTANT FINAL)
+ Q_PROPERTY(QUrl linkUrl READ linkUrl CONSTANT FINAL)
+ Q_PROPERTY(QUrl mediaUrl READ mediaUrl CONSTANT FINAL)
+ Q_PROPERTY(MediaType mediaType READ mediaType CONSTANT FINAL)
+ Q_PROPERTY(bool isContentEditable READ isContentEditable CONSTANT FINAL)
+ Q_PROPERTY(QString misspelledWord READ misspelledWord CONSTANT FINAL)
+ Q_PROPERTY(QStringList spellCheckerSuggestions READ spellCheckerSuggestions CONSTANT FINAL)
+ Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted FINAL)
+ Q_PROPERTY(MediaFlags mediaFlags READ mediaFlags CONSTANT FINAL REVISION(1, 1))
+ Q_PROPERTY(EditFlags editFlags READ editFlags CONSTANT FINAL REVISION(1, 1))
+
+ virtual ~QWebEngineContextMenuRequest();
+ QPoint position() const;
+ QString selectedText() const;
+ QString linkText() const;
+ QUrl linkUrl() const;
+ QUrl mediaUrl() const;
+ MediaType mediaType() const;
+ bool isContentEditable() const;
+ QString misspelledWord() const;
+ QStringList spellCheckerSuggestions() const;
+ bool isAccepted() const;
+ void setAccepted(bool accepted);
+ MediaFlags mediaFlags() const;
+ EditFlags editFlags() const;
+
+private:
+ QUrl filteredLinkUrl() const;
+ QString altText() const;
+ QString titleText() const;
+ QUrl referrerUrl() const;
+ QtWebEngineCore::ReferrerPolicy referrerPolicy() const;
+ bool hasImageContent() const;
+ QString suggestedFileName() const;
+
+private:
+ QWebEngineContextMenuRequest(QWebEngineContextMenuRequestPrivate *d);
+ QScopedPointer<QWebEngineContextMenuRequestPrivate> d;
+ friend class QtWebEngineCore::WebContentsViewQt;
+ friend class QtWebEngineCore::RenderViewContextMenuQt;
+ friend class extensions::MimeHandlerViewGuestDelegateQt;
+ friend class QQuickWebEngineViewPrivate;
+ friend class QQuickWebEngineView;
+ friend class QWebEnginePage;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINECONTEXTMENUREQUEST_H
diff --git a/src/core/api/qwebenginecontextmenurequest_p.h b/src/core/api/qwebenginecontextmenurequest_p.h
new file mode 100644
index 000000000..0e774f534
--- /dev/null
+++ b/src/core/api/qwebenginecontextmenurequest_p.h
@@ -0,0 +1,57 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINECONTEXTMENUREQUEST_P_H
+#define QWEBENGINECONTEXTMENUREQUEST_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qtwebenginecoreglobal_p.h"
+#include "qwebenginecontextmenurequest.h"
+#include <QPoint>
+#include <QUrl>
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineContextMenuRequestPrivate
+{
+public:
+ bool m_accepted = false;
+ bool m_hasImageContent = false;
+ bool m_isEditable = false;
+ bool m_isSpellCheckerEnabled = false;
+ uint m_mediaType = 0;
+ uint m_mediaFlags = 0;
+ uint m_editFlags = 0;
+ QPoint m_position;
+ QUrl m_filteredLinkUrl;
+ QUrl m_unfilteredLinkUrl;
+ QUrl m_mediaUrl;
+ QString m_altText;
+ QString m_linkText;
+ QString m_titleText;
+ QString m_selectedText;
+ QString m_suggestedFileName;
+ QString m_misspelledWord;
+ QStringList m_spellCheckerSuggestions;
+ QUrl m_pageUrl;
+ QUrl m_frameUrl;
+ QtWebEngineCore::ReferrerPolicy m_referrerPolicy = QtWebEngineCore::ReferrerPolicy::Default;
+ // Some likely candidates for future additions as we add support for the related actions:
+ // bool isImageBlocked;
+ // <enum tbd> mediaType;
+ // ...
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/core/api/qwebenginecookiestore.cpp b/src/core/api/qwebenginecookiestore.cpp
index 40594b9c0..6c4536a4a 100644
--- a/src/core/api/qwebenginecookiestore.cpp
+++ b/src/core/api/qwebenginecookiestore.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebenginecookiestore.h"
#include "qwebenginecookiestore_p.h"
@@ -62,11 +26,10 @@ using namespace QtWebEngineCore;
QWebEngineCookieStorePrivate::QWebEngineCookieStorePrivate(QWebEngineCookieStore *q)
: q_ptr(q)
- , m_nextCallbackId(CallbackDirectory::ReservedCallbackIdsEnd)
, m_deleteSessionCookiesPending(false)
, m_deleteAllCookiesPending(false)
, m_getAllCookiesPending(false)
- , delegate(0)
+ , delegate(nullptr)
{}
void QWebEngineCookieStorePrivate::processPendingUserCookies()
@@ -76,27 +39,30 @@ void QWebEngineCookieStorePrivate::processPendingUserCookies()
if (m_getAllCookiesPending) {
m_getAllCookiesPending = false;
- delegate->getAllCookies(CallbackDirectory::GetAllCookiesCallbackId);
+ delegate->getAllCookies();
}
if (m_deleteAllCookiesPending) {
m_deleteAllCookiesPending = false;
- delegate->deleteAllCookies(CallbackDirectory::DeleteAllCookiesCallbackId);
+ delegate->deleteAllCookies();
}
if (m_deleteSessionCookiesPending) {
m_deleteSessionCookiesPending = false;
- delegate->deleteSessionCookies(CallbackDirectory::DeleteSessionCookiesCallbackId);
+ delegate->deleteSessionCookies();
}
+ if (bool(filterCallback))
+ delegate->setHasFilter(true);
+
if (m_pendingUserCookies.isEmpty())
return;
- for (const CookieData &cookieData : qAsConst(m_pendingUserCookies)) {
- if (cookieData.callbackId == CallbackDirectory::DeleteCookieCallbackId)
+ for (const CookieData &cookieData : std::as_const(m_pendingUserCookies)) {
+ if (cookieData.wasDelete)
delegate->deleteCookie(cookieData.cookie, cookieData.origin);
else
- delegate->setCookie(cookieData.callbackId, cookieData.cookie, cookieData.origin);
+ delegate->setCookie(cookieData.cookie, cookieData.origin);
}
m_pendingUserCookies.clear();
@@ -110,26 +76,20 @@ void QWebEngineCookieStorePrivate::rejectPendingUserCookies()
m_pendingUserCookies.clear();
}
-void QWebEngineCookieStorePrivate::setCookie(const QWebEngineCallback<bool> &callback, const QNetworkCookie &cookie,
- const QUrl &origin)
+void QWebEngineCookieStorePrivate::setCookie(const QNetworkCookie &cookie, const QUrl &origin)
{
- const quint64 currentCallbackId = callback ? m_nextCallbackId++ : static_cast<quint64>(CallbackDirectory::NoCallbackId);
-
- if (currentCallbackId != CallbackDirectory::NoCallbackId)
- callbackDirectory.registerCallback(currentCallbackId, callback);
-
if (!delegate || !delegate->hasCookieMonster()) {
- m_pendingUserCookies.append(CookieData{ currentCallbackId, cookie, origin });
+ m_pendingUserCookies.append(CookieData{ false, cookie, origin });
return;
}
- delegate->setCookie(currentCallbackId, cookie, origin);
+ delegate->setCookie(cookie, origin);
}
void QWebEngineCookieStorePrivate::deleteCookie(const QNetworkCookie &cookie, const QUrl &url)
{
if (!delegate || !delegate->hasCookieMonster()) {
- m_pendingUserCookies.append(CookieData{ CallbackDirectory::DeleteCookieCallbackId, cookie, url });
+ m_pendingUserCookies.append(CookieData{ true, cookie, url });
return;
}
@@ -143,7 +103,7 @@ void QWebEngineCookieStorePrivate::deleteSessionCookies()
return;
}
- delegate->deleteSessionCookies(CallbackDirectory::DeleteSessionCookiesCallbackId);
+ delegate->deleteSessionCookies();
}
void QWebEngineCookieStorePrivate::deleteAllCookies()
@@ -154,7 +114,7 @@ void QWebEngineCookieStorePrivate::deleteAllCookies()
return;
}
- delegate->deleteAllCookies(CallbackDirectory::DeleteAllCookiesCallbackId);
+ delegate->deleteAllCookies();
}
void QWebEngineCookieStorePrivate::getAllCookies()
@@ -164,22 +124,9 @@ void QWebEngineCookieStorePrivate::getAllCookies()
return;
}
- delegate->getAllCookies(CallbackDirectory::GetAllCookiesCallbackId);
+ delegate->getAllCookies();
}
-void QWebEngineCookieStorePrivate::onGetAllCallbackResult(qint64 callbackId, const QByteArray &cookieList)
-{
- callbackDirectory.invoke(callbackId, cookieList);
-}
-void QWebEngineCookieStorePrivate::onSetCallbackResult(qint64 callbackId, bool success)
-{
- callbackDirectory.invoke(callbackId, success);
-}
-
-void QWebEngineCookieStorePrivate::onDeleteCallbackResult(qint64 callbackId, int numCookies)
-{
- callbackDirectory.invoke(callbackId, numCookies);
-}
void QWebEngineCookieStorePrivate::onCookieChanged(const QNetworkCookie &cookie, bool removed)
{
@@ -263,8 +210,7 @@ QWebEngineCookieStore::~QWebEngineCookieStore() {}
void QWebEngineCookieStore::setCookie(const QNetworkCookie &cookie, const QUrl &origin)
{
- //TODO: use callbacks or delete dummy ones
- d_ptr->setCookie(QWebEngineCallback<bool>(), cookie, origin);
+ d_ptr->setCookie(cookie, origin);
}
/*!
@@ -291,11 +237,8 @@ void QWebEngineCookieStore::deleteCookie(const QNetworkCookie &cookie, const QUr
void QWebEngineCookieStore::loadAllCookies()
{
- //TODO: use callbacks or delete dummy ones
if (d_ptr->m_getAllCookiesPending)
return;
- d_ptr->callbackDirectory.registerCallback(CallbackDirectory::GetAllCookiesCallbackId,
- QWebEngineCallback<const QByteArray &>());
//this will trigger cookieAdded signal
d_ptr->getAllCookies();
}
@@ -310,10 +253,8 @@ void QWebEngineCookieStore::loadAllCookies()
void QWebEngineCookieStore::deleteSessionCookies()
{
- //TODO: use callbacks or delete dummy ones
if (d_ptr->m_deleteAllCookiesPending || d_ptr->m_deleteSessionCookiesPending)
return;
- d_ptr->callbackDirectory.registerCallback(CallbackDirectory::DeleteSessionCookiesCallbackId, QWebEngineCallback<int>());
d_ptr->deleteSessionCookies();
}
@@ -325,10 +266,8 @@ void QWebEngineCookieStore::deleteSessionCookies()
void QWebEngineCookieStore::deleteAllCookies()
{
- //TODO: use callbacks or delete dummy ones
if (d_ptr->m_deleteAllCookiesPending)
return;
- d_ptr->callbackDirectory.registerCallback(CallbackDirectory::DeleteAllCookiesCallbackId, QWebEngineCallback<int>());
d_ptr->deleteAllCookies();
}
@@ -362,7 +301,10 @@ void QWebEngineCookieStore::deleteAllCookies()
*/
void QWebEngineCookieStore::setCookieFilter(const std::function<bool(const FilterRequest &)> &filterCallback)
{
+ bool changed = bool(d_ptr->filterCallback) != bool(filterCallback);
d_ptr->filterCallback = filterCallback;
+ if (changed && d_ptr->delegate)
+ d_ptr->delegate->setHasFilter(bool(d_ptr->filterCallback));
}
/*!
@@ -371,7 +313,10 @@ void QWebEngineCookieStore::setCookieFilter(const std::function<bool(const Filte
*/
void QWebEngineCookieStore::setCookieFilter(std::function<bool(const FilterRequest &)> &&filterCallback)
{
+ bool changed = bool(d_ptr->filterCallback) != bool(filterCallback);
d_ptr->filterCallback = std::move(filterCallback);
+ if (changed && d_ptr->delegate)
+ d_ptr->delegate->setHasFilter(bool(d_ptr->filterCallback));
}
/*!
@@ -429,3 +374,5 @@ void QWebEngineCookieStore::setCookieFilter(std::function<bool(const FilterReque
*/
QT_END_NAMESPACE
+
+#include "moc_qwebenginecookiestore.cpp"
diff --git a/src/core/api/qwebenginecookiestore.h b/src/core/api/qwebenginecookiestore.h
index ff8865406..347d0c45c 100644
--- a/src/core/api/qwebenginecookiestore.h
+++ b/src/core/api/qwebenginecookiestore.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINECOOKIESTORE_H
#define QWEBENGINECOOKIESTORE_H
@@ -53,13 +17,13 @@ namespace QtWebEngineCore {
class ContentBrowserClientQt;
class CookieMonsterDelegateQt;
class ProfileAdapter;
-class RestrictedCookieManagerQt;
} // namespace QtWebEngineCore
QT_BEGIN_NAMESPACE
class QWebEngineCookieStorePrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineCookieStore : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineCookieStore : public QObject
+{
Q_OBJECT
public:
@@ -85,11 +49,10 @@ Q_SIGNALS:
void cookieRemoved(const QNetworkCookie &cookie);
private:
- explicit QWebEngineCookieStore(QObject *parent = Q_NULLPTR);
+ explicit QWebEngineCookieStore(QObject *parent = nullptr);
friend class QtWebEngineCore::ContentBrowserClientQt;
friend class QtWebEngineCore::CookieMonsterDelegateQt;
friend class QtWebEngineCore::ProfileAdapter;
- friend class QtWebEngineCore::RestrictedCookieManagerQt;
Q_DISABLE_COPY(QWebEngineCookieStore)
Q_DECLARE_PRIVATE(QWebEngineCookieStore)
QScopedPointer<QWebEngineCookieStorePrivate> d_ptr;
diff --git a/src/core/api/qwebenginecookiestore_p.h b/src/core/api/qwebenginecookiestore_p.h
index a79e2b095..51200436d 100644
--- a/src/core/api/qwebenginecookiestore_p.h
+++ b/src/core/api/qwebenginecookiestore_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINECOOKIESTORE_P_H
#define QWEBENGINECOOKIESTORE_P_H
@@ -53,10 +17,9 @@
#include "qtwebenginecoreglobal_p.h"
-#include "qwebenginecallback_p.h"
#include "qwebenginecookiestore.h"
-#include <QVector>
+#include <QList>
#include <QNetworkCookie>
#include <QUrl>
@@ -66,10 +29,11 @@ class CookieMonsterDelegateQt;
QT_BEGIN_NAMESPACE
-class Q_WEBENGINECORE_PRIVATE_EXPORT QWebEngineCookieStorePrivate {
+class Q_WEBENGINECORE_EXPORT QWebEngineCookieStorePrivate
+{
Q_DECLARE_PUBLIC(QWebEngineCookieStore)
struct CookieData {
- quint64 callbackId;
+ bool wasDelete;
QNetworkCookie cookie;
QUrl origin;
};
@@ -77,10 +41,8 @@ class Q_WEBENGINECORE_PRIVATE_EXPORT QWebEngineCookieStorePrivate {
QWebEngineCookieStore *q_ptr;
public:
- QtWebEngineCore::CallbackDirectory callbackDirectory;
std::function<bool(const QWebEngineCookieStore::FilterRequest &)> filterCallback;
- QVector<CookieData> m_pendingUserCookies;
- quint64 m_nextCallbackId;
+ QList<CookieData> m_pendingUserCookies;
bool m_deleteSessionCookiesPending;
bool m_deleteAllCookiesPending;
bool m_getAllCookiesPending;
@@ -91,7 +53,7 @@ public:
void processPendingUserCookies();
void rejectPendingUserCookies();
- void setCookie(const QWebEngineCallback<bool> &callback, const QNetworkCookie &cookie, const QUrl &origin);
+ void setCookie(const QNetworkCookie &cookie, const QUrl &origin);
void deleteCookie(const QNetworkCookie &cookie, const QUrl &url);
void deleteSessionCookies();
void deleteAllCookies();
@@ -99,13 +61,10 @@ public:
bool canAccessCookies(const QUrl &firstPartyUrl, const QUrl &url) const;
- void onGetAllCallbackResult(qint64 callbackId, const QByteArray &cookieList);
- void onSetCallbackResult(qint64 callbackId, bool success);
- void onDeleteCallbackResult(qint64 callbackId, int numCookies);
void onCookieChanged(const QNetworkCookie &cookie, bool removed);
};
-Q_DECLARE_TYPEINFO(QWebEngineCookieStorePrivate::CookieData, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QWebEngineCookieStorePrivate::CookieData, Q_RELOCATABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/core/api/qwebenginedesktopmediarequest.cpp b/src/core/api/qwebenginedesktopmediarequest.cpp
new file mode 100644
index 000000000..dae69a68c
--- /dev/null
+++ b/src/core/api/qwebenginedesktopmediarequest.cpp
@@ -0,0 +1,206 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "desktop_media_controller.h"
+#include "qwebenginedesktopmediarequest.h"
+#include "qwebenginedesktopmediarequest_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QT_DEFINE_QESDP_SPECIALIZATION_DTOR(QWebEngineDesktopMediaRequestPrivate)
+
+/*!
+ \class QWebEngineDesktopMediaRequest
+ \brief A request for populating a dialog with available sources for screen capturing.
+
+ \since 6.7
+
+ \inmodule QtWebEngineCore
+
+ To allow web applications to capture contents of a display, applications must connect
+ to QWebEnginePage::desktopMediaRequested, which takes a QWebEngineDesktopMediaRequest
+ instance as an argument.
+
+ If a web application requests access to the contents of a display,
+ QWebEnginePage::desktopMediaRequested will be emitted with a
+ QWebEngineDesktopMediaRequest instance as an argument which holds references to
+ QAbstractListModels for available windows and screens that can be captured.
+
+ The data model's \e Qt::DisplayRole specifies the name of the source which is the title of a
+ window or the number of the display.
+ The model is dynamically updates if the available list of sources has changed e.g a window is
+ opened/closed.
+
+ The signal handler needs to then either call QWebEngineDesktopMediaRequest:selectScreen() or
+ QWebEngineDesktopMediaRequest::selectWindow() to accept the request and start screensharing.
+ \sa QWebEnginePage::desktopMediaRequested().
+*/
+
+class QWebEngineMediaSourceModel : public QAbstractListModel
+{
+public:
+ ~QWebEngineMediaSourceModel() override;
+
+ int rowCount(const QModelIndex &parent = QModelIndex()) const override;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
+
+private:
+ friend class QWebEngineDesktopMediaRequestPrivate;
+ explicit QWebEngineMediaSourceModel(QtWebEngineCore::DesktopMediaListQt *mediaList);
+ QtWebEngineCore::DesktopMediaListQt *m_mediaList;
+};
+
+QWebEngineMediaSourceModel::QWebEngineMediaSourceModel(QtWebEngineCore::DesktopMediaListQt *mediaList)
+ : m_mediaList(mediaList)
+{
+ QObject::connect(m_mediaList, &QtWebEngineCore::DesktopMediaListQt::sourceAdded, this,
+ [this](int index) {
+ beginInsertRows(QModelIndex(), index, index);
+ endInsertRows();
+ });
+ QObject::connect(m_mediaList, &QtWebEngineCore::DesktopMediaListQt::sourceRemoved, this,
+ [this](int index) {
+ beginRemoveRows(QModelIndex(), index, index);
+ endRemoveRows();
+ });
+ QObject::connect(m_mediaList, &QtWebEngineCore::DesktopMediaListQt::sourceMoved, this,
+ [this](int oldIndex, int newIndex) {
+ beginMoveRows(QModelIndex(), oldIndex, oldIndex, QModelIndex(), newIndex);
+ endMoveRows();
+ });
+ QObject::connect(m_mediaList, &QtWebEngineCore::DesktopMediaListQt::sourceNameChanged, this,
+ [this](int index) {
+ Q_EMIT dataChanged(QModelIndex(), QModelIndex(),
+ { Qt::DisplayRole });
+ });
+}
+
+QWebEngineMediaSourceModel::~QWebEngineMediaSourceModel() { }
+
+int QWebEngineMediaSourceModel::rowCount(const QModelIndex &) const
+{
+ return m_mediaList->getSourceCount();
+}
+
+QVariant QWebEngineMediaSourceModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid())
+ return QVariant();
+ switch (role) {
+ case Qt::DisplayRole:
+ case Qt::EditRole:
+ return m_mediaList->getSourceName(index.row());
+ default:
+ break;
+ }
+ return QVariant();
+}
+
+QWebEngineDesktopMediaRequestPrivate::QWebEngineDesktopMediaRequestPrivate(
+ QtWebEngineCore::DesktopMediaController *controller)
+ : controller(controller)
+ , m_screensModel(new QWebEngineMediaSourceModel(controller->screens()))
+ , m_windowsModel(new QWebEngineMediaSourceModel(controller->windows()))
+{
+}
+
+QWebEngineDesktopMediaRequestPrivate::~QWebEngineDesktopMediaRequestPrivate()
+{
+ // Keep old behavior, if there were no user action select the primary screen.
+ if (!didSelectOrCancel)
+ controller->selectScreen(0);
+}
+
+void QWebEngineDesktopMediaRequestPrivate::selectWindow(const QModelIndex &index)
+{
+ Q_ASSERT(index.model() == m_windowsModel.get());
+ if (!index.isValid())
+ return;
+ didSelectOrCancel = true;
+ controller->selectWindow(index.row());
+}
+
+void QWebEngineDesktopMediaRequestPrivate::selectScreen(const QModelIndex &index)
+{
+ Q_ASSERT(index.model() == m_screensModel.get());
+ if (!index.isValid())
+ return;
+ didSelectOrCancel = true;
+ controller->selectScreen(index.row());
+}
+
+void QWebEngineDesktopMediaRequestPrivate::cancel()
+{
+ // Notifies webrtc so it can free up it's resources.
+ didSelectOrCancel = true;
+ controller->cancel();
+}
+
+QWebEngineDesktopMediaRequest::QWebEngineDesktopMediaRequest(
+ QtWebEngineCore::DesktopMediaController *controller)
+ : d(new QWebEngineDesktopMediaRequestPrivate(controller))
+{
+}
+
+QWebEngineDesktopMediaRequest::~QWebEngineDesktopMediaRequest() = default;
+
+QWebEngineDesktopMediaRequest::QWebEngineDesktopMediaRequest(
+ const QWebEngineDesktopMediaRequest &other) noexcept = default;
+
+QWebEngineDesktopMediaRequest &QWebEngineDesktopMediaRequest::operator=(
+ const QWebEngineDesktopMediaRequest &other) noexcept = default;
+
+QWebEngineDesktopMediaRequest::QWebEngineDesktopMediaRequest(
+ QWebEngineDesktopMediaRequest &&other) noexcept = default;
+
+/*!
+ Returns a QAbstractListModel for the available screens.
+
+ \sa windowsModel()
+*/
+QAbstractListModel *QWebEngineDesktopMediaRequest::screensModel() const
+{
+ return d->m_screensModel.get();
+}
+
+/*!
+ Returns a QAbstractListModel for the available windows.
+
+ \sa screensModel()
+*/
+QAbstractListModel *QWebEngineDesktopMediaRequest::windowsModel() const
+{
+ return d->m_windowsModel.get();
+}
+
+/*!
+ Selects the window on the \a index to be captured.
+
+ \sa QWebEngineDesktopMediaRequest::selectScreen()
+*/
+void QWebEngineDesktopMediaRequest::selectWindow(const QModelIndex &index) const
+{
+ d->selectWindow(index);
+}
+
+/*!
+ Selects the screen on the \a index to be captured.
+
+ \sa QWebEngineDesktopMediaRequest::selectWindow()
+*/
+void QWebEngineDesktopMediaRequest::selectScreen(const QModelIndex &index) const
+{
+ d->selectScreen(index);
+}
+
+/*!
+ Rejects a request. Screen capturing will be aborted.
+*/
+void QWebEngineDesktopMediaRequest::cancel() const
+{
+ d->cancel();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginedesktopmediarequest.cpp"
diff --git a/src/core/api/qwebenginedesktopmediarequest.h b/src/core/api/qwebenginedesktopmediarequest.h
new file mode 100644
index 000000000..ebf66bce4
--- /dev/null
+++ b/src/core/api/qwebenginedesktopmediarequest.h
@@ -0,0 +1,59 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEDESKTOPMEDIAREQUEST_H
+#define QWEBENGINEDESKTOPMEDIAREQUEST_H
+
+#include <QtCore/qabstractitemmodel.h>
+#include <QtCore/qshareddata.h>
+#include <QtCore/qobject.h>
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+namespace QtWebEngineCore {
+class DesktopMediaController;
+}
+
+QT_BEGIN_NAMESPACE
+class QWebEnginePagePrivate;
+class QQuickWebEngineViewPrivate;
+class QWebEngineDesktopMediaRequestPrivate;
+QT_DECLARE_QESDP_SPECIALIZATION_DTOR_WITH_EXPORT(QWebEngineDesktopMediaRequestPrivate,
+ Q_WEBENGINECORE_EXPORT)
+
+class QWebEngineDesktopMediaRequest
+{
+ Q_GADGET_EXPORT(Q_WEBENGINECORE_EXPORT)
+ Q_PROPERTY(QAbstractListModel *screensModel READ screensModel FINAL)
+ Q_PROPERTY(QAbstractListModel *windowsModel READ windowsModel FINAL)
+
+public:
+ Q_WEBENGINECORE_EXPORT ~QWebEngineDesktopMediaRequest();
+
+ Q_WEBENGINECORE_EXPORT
+ QWebEngineDesktopMediaRequest(const QWebEngineDesktopMediaRequest &other) noexcept;
+ Q_WEBENGINECORE_EXPORT
+ QWebEngineDesktopMediaRequest(QWebEngineDesktopMediaRequest &&other) noexcept;
+ Q_WEBENGINECORE_EXPORT
+ QWebEngineDesktopMediaRequest &operator=(const QWebEngineDesktopMediaRequest &other) noexcept;
+ QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_PURE_SWAP(QWebEngineDesktopMediaRequest)
+ void swap(QWebEngineDesktopMediaRequest &other) noexcept { d.swap(other.d); }
+
+ Q_WEBENGINECORE_EXPORT QAbstractListModel *screensModel() const;
+ Q_WEBENGINECORE_EXPORT QAbstractListModel *windowsModel() const;
+
+ Q_WEBENGINECORE_EXPORT Q_INVOKABLE void selectScreen(const QModelIndex &index) const;
+ Q_WEBENGINECORE_EXPORT Q_INVOKABLE void selectWindow(const QModelIndex &index) const;
+ Q_WEBENGINECORE_EXPORT Q_INVOKABLE void cancel() const;
+
+private:
+ friend class QWebEnginePagePrivate;
+ friend class QQuickWebEngineViewPrivate;
+ Q_WEBENGINECORE_EXPORT explicit QWebEngineDesktopMediaRequest(
+ QtWebEngineCore::DesktopMediaController *controller);
+ QExplicitlySharedDataPointer<QWebEngineDesktopMediaRequestPrivate> d;
+};
+Q_DECLARE_SHARED(QWebEngineDesktopMediaRequest)
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEDESKTOPMEDIAREQUEST_H
diff --git a/src/core/api/qwebenginedesktopmediarequest_p.h b/src/core/api/qwebenginedesktopmediarequest_p.h
new file mode 100644
index 000000000..3add71bc0
--- /dev/null
+++ b/src/core/api/qwebenginedesktopmediarequest_p.h
@@ -0,0 +1,49 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef QWEBENGINEDESKTOPMEDIAREQUEST_P_H
+#define QWEBENGINEDESKTOPMEDIAREQUEST_P_H
+
+#include <QtCore/qabstractitemmodel.h>
+#include <QtCore/QSharedData>
+#include <QtCore/qobject.h>
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+namespace QtWebEngineCore {
+class DesktopMediaController;
+}
+
+QT_BEGIN_NAMESPACE
+class QWebEngineMediaSourceModel;
+
+class QWebEngineDesktopMediaRequestPrivate : public QSharedData
+{
+public:
+ ~QWebEngineDesktopMediaRequestPrivate();
+ explicit QWebEngineDesktopMediaRequestPrivate(
+ QtWebEngineCore::DesktopMediaController *controller);
+
+ void selectScreen(const QModelIndex &index);
+ void selectWindow(const QModelIndex &index);
+ void cancel();
+
+ bool didSelectOrCancel = false;
+ std::unique_ptr<QtWebEngineCore::DesktopMediaController> controller;
+ std::unique_ptr<QWebEngineMediaSourceModel> m_screensModel;
+ std::unique_ptr<QWebEngineMediaSourceModel> m_windowsModel;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEDESKTOPMEDIAREQUEST_P_H
diff --git a/src/core/api/qwebenginedownloadrequest.cpp b/src/core/api/qwebenginedownloadrequest.cpp
new file mode 100644
index 000000000..cbf46b448
--- /dev/null
+++ b/src/core/api/qwebenginedownloadrequest.cpp
@@ -0,0 +1,637 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginedownloadrequest.h"
+#include "qwebenginedownloadrequest_p.h"
+
+#include "qwebenginepage.h"
+
+#include "profile_adapter.h"
+#include "web_contents_adapter_client.h"
+
+#include <QFileInfo>
+
+QT_BEGIN_NAMESPACE
+
+using QtWebEngineCore::ProfileAdapterClient;
+
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NoReason, QWebEngineDownloadRequest::NoReason)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileFailed, QWebEngineDownloadRequest::FileFailed)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileAccessDenied, QWebEngineDownloadRequest::FileAccessDenied)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileNoSpace, QWebEngineDownloadRequest::FileNoSpace)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileNameTooLong, QWebEngineDownloadRequest::FileNameTooLong)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileTooLarge, QWebEngineDownloadRequest::FileTooLarge)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileVirusInfected, QWebEngineDownloadRequest::FileVirusInfected)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileTransientError, QWebEngineDownloadRequest::FileTransientError)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileBlocked, QWebEngineDownloadRequest::FileBlocked)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileSecurityCheckFailed, QWebEngineDownloadRequest::FileSecurityCheckFailed)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileTooShort, QWebEngineDownloadRequest::FileTooShort)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::FileHashMismatch, QWebEngineDownloadRequest::FileHashMismatch)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NetworkFailed, QWebEngineDownloadRequest::NetworkFailed)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NetworkTimeout, QWebEngineDownloadRequest::NetworkTimeout)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NetworkDisconnected, QWebEngineDownloadRequest::NetworkDisconnected)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NetworkServerDown, QWebEngineDownloadRequest::NetworkServerDown)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::NetworkInvalidRequest, QWebEngineDownloadRequest::NetworkInvalidRequest)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerFailed, QWebEngineDownloadRequest::ServerFailed)
+//ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerNoRange, QWebEngineDownloadRequest::ServerNoRange)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerBadContent, QWebEngineDownloadRequest::ServerBadContent)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerUnauthorized, QWebEngineDownloadRequest::ServerUnauthorized)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerCertProblem, QWebEngineDownloadRequest::ServerCertProblem)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerForbidden, QWebEngineDownloadRequest::ServerForbidden)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::ServerUnreachable, QWebEngineDownloadRequest::ServerUnreachable)
+ASSERT_ENUMS_MATCH(ProfileAdapterClient::UserCanceled, QWebEngineDownloadRequest::UserCanceled)
+//ASSERT_ENUMS_MATCH(ProfileAdapterClient::UserShutdown, QWebEngineDownloadRequest::UserShutdown)
+//ASSERT_ENUMS_MATCH(ProfileAdapterClient::Crash, QWebEngineDownloadRequest::Crash)
+
+static inline QWebEngineDownloadRequest::DownloadState toDownloadState(int state)
+{
+ switch (state) {
+ case ProfileAdapterClient::DownloadInProgress:
+ return QWebEngineDownloadRequest::DownloadInProgress;
+ case ProfileAdapterClient::DownloadCompleted:
+ return QWebEngineDownloadRequest::DownloadCompleted;
+ case ProfileAdapterClient::DownloadCancelled:
+ return QWebEngineDownloadRequest::DownloadCancelled;
+ case ProfileAdapterClient::DownloadInterrupted:
+ return QWebEngineDownloadRequest::DownloadInterrupted;
+ default:
+ Q_UNREACHABLE();
+ return QWebEngineDownloadRequest::DownloadCancelled;
+ }
+}
+
+static inline QWebEngineDownloadRequest::DownloadInterruptReason toDownloadInterruptReason(int reason)
+{
+ return static_cast<QWebEngineDownloadRequest::DownloadInterruptReason>(reason);
+}
+
+/*!
+ \class QWebEngineDownloadRequest
+ \brief The QWebEngineDownloadRequest class provides information about a download.
+
+ \inmodule QtWebEngineCore
+
+ QWebEngineDownloadRequest models a download throughout its life cycle, starting
+ with a pending download request and finishing with a completed download. It
+ can be used, for example, to get information about new downloads, to monitor
+ progress, and to pause, resume, and cancel downloads.
+
+ Downloads are usually triggered by user interaction on a web page. It is the
+ QWebEngineProfile's responsibility to notify the application of new download
+ requests, which it does by emitting the
+ \l{QWebEngineProfile::downloadRequested}{downloadRequested} signal together
+ with a newly created QWebEngineDownloadRequest. The application can then
+ examine this item and decide whether to accept it or not. A signal handler
+ must explicitly call accept() on the item for \QWE to actually start
+ downloading and writing data to disk. If no signal handler calls accept(),
+ then the download request will be automatically rejected and nothing will be
+ written to disk.
+
+ \note Some properties, such as setting the path and file name where the file
+ will be saved (see \l downloadDirectory() and \l downloadFileName()), can
+ only be changed before calling accept().
+
+ \section2 Object Life Cycle
+
+ All items are guaranteed to be valid during the emission of the
+ \l{QWebEngineProfile::downloadRequested}{downloadRequested} signal. If
+ accept() is \e not called by any signal handler, then the item will be
+ deleted \e immediately after signal emission. This means that the
+ application \b{must not} keep references to rejected download items. It also
+ means the application should not use a queued connection to this signal.
+
+ If accept() \e is called by a signal handler, then the QWebEngineProfile
+ will take ownership of the item. However, it is safe for the application to
+ delete the item at any time, except during the handling of the
+ \l{QWebEngineProfile::downloadRequested}{downloadRequested} signal. The
+ QWebEngineProfile being a long-lived object, it is in fact recommended that
+ the application delete any items it is no longer interested in.
+
+ \note Deleting an item will also automatically cancel a download since 5.12.2,
+ but it is recommended to cancel manually before deleting for portability.
+
+ \section2 Web Page Downloads
+
+ In addition to normal file downloads, which consist simply of retrieving
+ some raw bytes from the network and writing them to disk, \QWE also
+ supports saving complete web pages, which involves parsing the page's HTML,
+ downloading any dependent resources, and potentially packaging everything
+ into a special file format (\l savePageFormat). To check if a download is
+ for a file or a web page, use \l isSavePageDownload.
+
+ \sa QWebEngineProfile, QWebEngineProfile::downloadRequested,
+ QWebEnginePage::download, QWebEnginePage::save
+*/
+
+QWebEngineDownloadRequestPrivate::QWebEngineDownloadRequestPrivate(
+ QtWebEngineCore::ProfileAdapter *adapter)
+ : profileAdapter(adapter)
+{
+}
+
+QWebEngineDownloadRequestPrivate::~QWebEngineDownloadRequestPrivate()
+{
+}
+
+void QWebEngineDownloadRequestPrivate::update(const ProfileAdapterClient::DownloadItemInfo &info)
+{
+ Q_Q(QWebEngineDownloadRequest);
+
+ Q_ASSERT(downloadState != QWebEngineDownloadRequest::DownloadRequested);
+
+ if (toDownloadInterruptReason(info.downloadInterruptReason) != interruptReason) {
+ interruptReason = toDownloadInterruptReason(info.downloadInterruptReason);
+ Q_EMIT q->interruptReasonChanged();
+ }
+ if (toDownloadState(info.state) != downloadState) {
+ downloadState = toDownloadState(info.state);
+ Q_EMIT q->stateChanged(downloadState);
+ }
+
+ if (info.receivedBytes != receivedBytes || info.totalBytes != totalBytes) {
+
+ if (info.receivedBytes != receivedBytes) {
+ receivedBytes = info.receivedBytes;
+ Q_EMIT q->receivedBytesChanged();
+ }
+ if (info.totalBytes != totalBytes) {
+ totalBytes = info.totalBytes;
+ Q_EMIT q->totalBytesChanged();
+ }
+ }
+
+ if (info.done)
+ setFinished();
+
+ if (downloadPaused != info.paused) {
+ downloadPaused = info.paused;
+ Q_EMIT q->isPausedChanged();
+ }
+}
+
+void QWebEngineDownloadRequestPrivate::setFinished()
+{
+ if (downloadFinished)
+ return;
+
+ downloadFinished = true;
+ Q_EMIT q_ptr->isFinishedChanged();
+}
+
+/*!
+ Accepts the current download request, which will start the download.
+
+ If the item is in the \l DownloadRequested state, then it will transition
+ into the \l DownloadInProgress state and the downloading will begin. If the
+ item is in any other state, then nothing will happen.
+
+ \sa isFinished, stateChanged()
+*/
+
+void QWebEngineDownloadRequest::accept()
+{
+ Q_D(QWebEngineDownloadRequest);
+
+ if (d->downloadState != QWebEngineDownloadRequest::DownloadRequested)
+ return;
+
+ d->downloadState = QWebEngineDownloadRequest::DownloadInProgress;
+ Q_EMIT stateChanged(d->downloadState);
+}
+
+/*!
+ Cancels the current download.
+
+ If the item is in the \l DownloadInProgress state, then it will transition
+ into the \l DownloadCancelled state, the downloading will stop, and partially
+ downloaded files will be deleted from disk.
+
+ If the item is in the \l DownloadCompleted state, then nothing will happen.
+ If the item is in any other state, then it will transition into the \l
+ DownloadCancelled state without further effect.
+
+ \sa isFinished, stateChanged()
+*/
+
+void QWebEngineDownloadRequest::cancel()
+{
+ Q_D(QWebEngineDownloadRequest);
+
+ QWebEngineDownloadRequest::DownloadState state = d->downloadState;
+
+ if (state == QWebEngineDownloadRequest::DownloadCompleted)
+ return;
+
+ bool cancelled = state == QWebEngineDownloadRequest::DownloadCancelled;
+ if (cancelled)
+ return;
+
+ // Check if the download manager has a DownloadItem for this ID
+ // (network downloads or in progress page/resource saves)
+ if (state == QWebEngineDownloadRequest::DownloadInProgress) {
+ if (d->profileAdapter)
+ cancelled = d->profileAdapter->cancelDownload(d->downloadId);
+ }
+
+ // Not cancelled downloads are not even started yet at this point
+ if (!cancelled) {
+ d->downloadState = QWebEngineDownloadRequest::DownloadCancelled;
+ Q_EMIT stateChanged(d->downloadState);
+ d->setFinished();
+ }
+}
+
+/*!
+ Pauses the download.
+
+ Has no effect if the state is not \l DownloadInProgress. Does not change the
+ state.
+
+ \sa resume(), isPaused()
+*/
+
+void QWebEngineDownloadRequest::pause()
+{
+ Q_D(QWebEngineDownloadRequest);
+
+ QWebEngineDownloadRequest::DownloadState state = d->downloadState;
+
+ if (state != QWebEngineDownloadRequest::DownloadInProgress)
+ return;
+
+ if (d->profileAdapter)
+ d->profileAdapter->pauseDownload(d->downloadId);
+}
+
+/*!
+ Resumes the current download if it was paused or interrupted.
+
+ Has no effect if the state is not \l DownloadInProgress or \l
+ DownloadInterrupted. Does not change the state.
+
+ \sa pause(), isPaused(), state()
+*/
+void QWebEngineDownloadRequest::resume()
+{
+ Q_D(QWebEngineDownloadRequest);
+
+ QWebEngineDownloadRequest::DownloadState state = d->downloadState;
+
+ if (d->downloadFinished || (state != QWebEngineDownloadRequest::DownloadInProgress && state != QWebEngineDownloadRequest::DownloadInterrupted))
+ return;
+ if (d->profileAdapter)
+ d->profileAdapter->resumeDownload(d->downloadId);
+}
+
+/*!
+ Returns the download item's ID.
+*/
+
+quint32 QWebEngineDownloadRequest::id() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadId;
+}
+
+/*!
+ \fn void QWebEngineDownloadRequest::isPausedChanged()
+
+ This signal is emitted whenever isPaused changes.
+
+ \sa pause(), isPaused
+*/
+
+/*!
+ \fn void QWebEngineDownloadRequest::stateChanged(DownloadState state)
+
+ This signal is emitted whenever the download's \a state changes.
+
+ \sa state(), DownloadState
+*/
+
+/*!
+ \enum QWebEngineDownloadRequest::DownloadState
+
+ This enum describes the state of the download:
+
+ \value DownloadRequested Download has been requested, but has not been accepted yet.
+ \value DownloadInProgress Download is in progress.
+ \value DownloadCompleted Download completed successfully.
+ \value DownloadCancelled Download has been cancelled.
+ \value DownloadInterrupted Download has been interrupted (by the server or because of lost
+ connectivity).
+*/
+
+/*!
+ \enum QWebEngineDownloadRequest::SavePageFormat
+
+ This enum describes the format that is used to save a web page.
+
+ \value UnknownSaveFormat This is not a request for downloading a complete web page.
+ \value SingleHtmlSaveFormat The page is saved as a single HTML page. Resources such as images
+ are not saved.
+ \value CompleteHtmlSaveFormat The page is saved as a complete HTML page, for example a directory
+ containing the single HTML page and the resources.
+ \value MimeHtmlSaveFormat The page is saved as a complete web page in the MIME HTML format.
+*/
+
+/*!
+ \enum QWebEngineDownloadRequest::DownloadInterruptReason
+
+ Describes the reason why a download was interrupted:
+
+ \value NoReason Unknown reason or not interrupted.
+ \value FileFailed General file operation failure.
+ \value FileAccessDenied The file cannot be written locally, due to access restrictions.
+ \value FileNoSpace Insufficient space on the target drive.
+ \value FileNameTooLong The directory or file name is too long.
+ \value FileTooLarge The file size exceeds the file system limitation.
+ \value FileVirusInfected The file is infected with a virus.
+ \value FileTransientError Temporary problem (for example the file is in use,
+ out of memory, or too many files are opened at once).
+ \value FileBlocked The file was blocked due to local policy.
+ \value FileSecurityCheckFailed An attempt to check the safety of the download
+ failed due to unexpected reasons.
+ \value FileTooShort An attempt was made to seek past the end of a file when
+ opening a file (as part of resuming a previously interrupted download).
+ \value FileHashMismatch The partial file did not match the expected hash.
+
+ \value NetworkFailed General network failure.
+ \value NetworkTimeout The network operation has timed out.
+ \value NetworkDisconnected The network connection has been terminated.
+ \value NetworkServerDown The server has gone down.
+ \value NetworkInvalidRequest The network request was invalid (for example, the
+ original or redirected URL is invalid, has an unsupported scheme, or is disallowed by policy).
+
+ \value ServerFailed General server failure.
+ \value ServerBadContent The server does not have the requested data.
+ \value ServerUnauthorized The server did not authorize access to the resource.
+ \value ServerCertProblem A problem with the server certificate occurred.
+ \value ServerForbidden Access forbidden by the server.
+ \value ServerUnreachable Unexpected server response (might indicate that
+ the responding server may not be the intended server).
+ \value UserCanceled The user canceled the download.
+*/
+
+/*!
+ Returns the download item's current state.
+
+ \sa DownloadState
+*/
+
+QWebEngineDownloadRequest::DownloadState QWebEngineDownloadRequest::state() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadState;
+}
+
+/*!
+ Returns the total amount of data to download in bytes.
+
+ \c -1 means the size is unknown.
+*/
+
+qint64 QWebEngineDownloadRequest::totalBytes() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->totalBytes;
+}
+
+/*!
+ Returns the amount of data in bytes that has been downloaded so far.
+
+ \c -1 means the size is unknown.
+*/
+
+qint64 QWebEngineDownloadRequest::receivedBytes() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->receivedBytes;
+}
+
+/*!
+ Returns the download's origin URL.
+*/
+
+QUrl QWebEngineDownloadRequest::url() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadUrl;
+}
+
+/*!
+ Returns the MIME type of the download.
+*/
+
+QString QWebEngineDownloadRequest::mimeType() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->mimeType;
+}
+
+/*!
+ Returns the download directory path.
+*/
+
+QString QWebEngineDownloadRequest::downloadDirectory() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadDirectory;
+}
+
+/*!
+ Sets \a directory as the directory path to download the file to.
+
+ The download directory path can only be set in response to the QWebEngineProfile::downloadRequested()
+ signal before the download is accepted. Past that point, this function has no effect on the
+ download item's state.
+*/
+
+void QWebEngineDownloadRequest::setDownloadDirectory(const QString &directory)
+{
+ Q_D(QWebEngineDownloadRequest);
+ if (d->downloadState != QWebEngineDownloadRequest::DownloadRequested) {
+ qWarning("Setting the download directory is not allowed after the download has been accepted.");
+ return;
+ }
+
+ if (!directory.isEmpty() && d->downloadDirectory != directory) {
+ d->downloadDirectory = directory;
+ Q_EMIT downloadDirectoryChanged();
+ }
+
+ if (!d->isCustomFileName && d->profileAdapter) {
+ QString newFileName = QFileInfo(d->profileAdapter->determineDownloadPath(d->downloadDirectory,
+ d->suggestedFileName,
+ d->startTime)).fileName();
+ if (d->downloadFileName != newFileName) {
+ d->downloadFileName = newFileName;
+ Q_EMIT downloadFileNameChanged();
+ }
+ }
+}
+
+/*!
+ Returns the file name to download the file to.
+*/
+
+QString QWebEngineDownloadRequest::downloadFileName() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadFileName;
+}
+
+/*!
+ Sets \a fileName as the file name to download the file to.
+
+ The download file name can only be set in response to the QWebEngineProfile::downloadRequested()
+ signal before the download is accepted. Past that point, this function has no effect on the
+ download item's state.
+*/
+
+void QWebEngineDownloadRequest::setDownloadFileName(const QString &fileName)
+{
+ Q_D(QWebEngineDownloadRequest);
+ if (d->downloadState != QWebEngineDownloadRequest::DownloadRequested) {
+ qWarning("Setting the download file name is not allowed after the download has been accepted.");
+ return;
+ }
+
+ if (!fileName.isEmpty()) {
+ d->downloadFileName = fileName;
+ d->isCustomFileName = true;
+ Q_EMIT downloadFileNameChanged();
+ }
+}
+
+/*!
+ Returns the suggested file name.
+*/
+
+QString QWebEngineDownloadRequest::suggestedFileName() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->suggestedFileName;
+}
+
+/*!
+ \property QWebEngineDownloadRequest::isFinished
+ \brief Whether this download is finished (completed, cancelled,
+ or non-resumable interrupted state).
+
+ \sa state()
+*/
+
+bool QWebEngineDownloadRequest::isFinished() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadFinished;
+}
+
+/*!
+ \property QWebEngineDownloadRequest::isPaused
+ \brief Whether this download is paused.
+
+ \sa pause(), resume()
+*/
+
+bool QWebEngineDownloadRequest::isPaused() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->downloadPaused;
+}
+
+/*!
+ Returns the format the web page will be saved in if this is a download request for a web page.
+ \sa setSavePageFormat(), isSavePageDownload()
+*/
+QWebEngineDownloadRequest::SavePageFormat QWebEngineDownloadRequest::savePageFormat() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->savePageFormat;
+}
+
+/*!
+ Sets the \a format the web page will be saved in if this is a download request for a web page.
+
+ \sa savePageFormat(), isSavePageDownload()
+*/
+void QWebEngineDownloadRequest::setSavePageFormat(QWebEngineDownloadRequest::SavePageFormat format)
+{
+ Q_D(QWebEngineDownloadRequest);
+ if (d->savePageFormat != format) {
+ d->savePageFormat = format;
+ Q_EMIT savePageFormatChanged();
+ }
+}
+
+/*!
+ Returns \c true if this is a download request for saving a web page.
+
+ \sa savePageFormat(), setSavePageFormat()
+ */
+bool QWebEngineDownloadRequest::isSavePageDownload() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->isSavePageDownload;
+}
+
+/*!
+ Returns the reason why the download was interrupted.
+
+ \sa interruptReasonString()
+*/
+
+QWebEngineDownloadRequest::DownloadInterruptReason QWebEngineDownloadRequest::interruptReason() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ return d->interruptReason;
+}
+
+/*!
+ Returns a human-readable description of the reason for interrupting the download.
+
+ \sa interruptReason()
+*/
+
+QString QWebEngineDownloadRequest::interruptReasonString() const
+{
+ return ProfileAdapterClient::downloadInterruptReasonToString(
+ static_cast<ProfileAdapterClient::DownloadInterruptReason>(interruptReason()));
+}
+
+/*!
+ Returns the page the download was requested on. If the download was not triggered by content in a page,
+ \c nullptr is returned.
+*/
+QWebEnginePage *QWebEngineDownloadRequest::page() const
+{
+ Q_D(const QWebEngineDownloadRequest);
+ if (d->adapterClient && d->adapterClient->clientType() == QtWebEngineCore::WebContentsAdapterClient::WidgetsClient)
+ return const_cast<QWebEnginePage *>(static_cast<const QWebEnginePage *>(d->adapterClient->holdingQObject()));
+ return nullptr;
+}
+
+
+/*! \internal
+*/
+QWebEngineDownloadRequest::QWebEngineDownloadRequest(QWebEngineDownloadRequestPrivate *p, QObject *parent)
+ : QObject(parent)
+ , d_ptr(p)
+{
+ p->q_ptr = this;
+}
+
+/*! \internal
+*/
+QWebEngineDownloadRequest::~QWebEngineDownloadRequest()
+{
+ // MEMO Items are owned by profile by default and will be destroyed on profile's destruction
+ // It's not safe to access profile in that case, so we rely on profile to clean up items
+ if (!isFinished())
+ cancel();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginedownloadrequest.cpp"
diff --git a/src/core/api/qwebenginedownloadrequest.h b/src/core/api/qwebenginedownloadrequest.h
new file mode 100644
index 000000000..36604188e
--- /dev/null
+++ b/src/core/api/qwebenginedownloadrequest.h
@@ -0,0 +1,139 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEDOWNLOADREQUEST_H
+#define QWEBENGINEDOWNLOADREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qurl.h>
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineDownloadRequestPrivate;
+class QWebEnginePage;
+class QWebEngineProfilePrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineDownloadRequest : public QObject
+{
+ Q_OBJECT
+public:
+ Q_PROPERTY(quint32 id READ id CONSTANT FINAL)
+ Q_PROPERTY(DownloadState state READ state NOTIFY stateChanged FINAL)
+ Q_PROPERTY(SavePageFormat savePageFormat READ savePageFormat WRITE setSavePageFormat NOTIFY savePageFormatChanged FINAL)
+ Q_PROPERTY(qint64 totalBytes READ totalBytes NOTIFY totalBytesChanged FINAL)
+ Q_PROPERTY(qint64 receivedBytes READ receivedBytes NOTIFY receivedBytesChanged FINAL)
+ Q_PROPERTY(QString mimeType READ mimeType FINAL)
+ Q_PROPERTY(DownloadInterruptReason interruptReason READ interruptReason NOTIFY interruptReasonChanged FINAL)
+ Q_PROPERTY(QString interruptReasonString READ interruptReasonString NOTIFY interruptReasonChanged FINAL)
+ Q_PROPERTY(bool isFinished READ isFinished NOTIFY isFinishedChanged FINAL)
+ Q_PROPERTY(bool isPaused READ isPaused NOTIFY isPausedChanged FINAL)
+ Q_PROPERTY(bool isSavePageDownload READ isSavePageDownload CONSTANT FINAL)
+ Q_PROPERTY(QUrl url READ url CONSTANT FINAL)
+ Q_PROPERTY(QString suggestedFileName READ suggestedFileName CONSTANT FINAL)
+ Q_PROPERTY(QString downloadDirectory READ downloadDirectory WRITE setDownloadDirectory NOTIFY downloadDirectoryChanged FINAL)
+ Q_PROPERTY(QString downloadFileName READ downloadFileName WRITE setDownloadFileName NOTIFY downloadFileNameChanged FINAL)
+
+ ~QWebEngineDownloadRequest() override;
+
+ enum DownloadState {
+ DownloadRequested,
+ DownloadInProgress,
+ DownloadCompleted,
+ DownloadCancelled,
+ DownloadInterrupted
+ };
+ Q_ENUM(DownloadState)
+
+ enum SavePageFormat {
+ UnknownSaveFormat = -1,
+ SingleHtmlSaveFormat,
+ CompleteHtmlSaveFormat,
+ MimeHtmlSaveFormat
+ };
+ Q_ENUM(SavePageFormat)
+
+ enum DownloadInterruptReason {
+ NoReason = 0,
+ FileFailed = 1,
+ FileAccessDenied = 2,
+ FileNoSpace = 3,
+ FileNameTooLong = 5,
+ FileTooLarge = 6,
+ FileVirusInfected = 7,
+ FileTransientError = 10,
+ FileBlocked = 11,
+ FileSecurityCheckFailed = 12,
+ FileTooShort = 13,
+ FileHashMismatch = 14,
+ NetworkFailed = 20,
+ NetworkTimeout = 21,
+ NetworkDisconnected = 22,
+ NetworkServerDown = 23,
+ NetworkInvalidRequest = 24,
+ ServerFailed = 30,
+ //ServerNoRange = 31,
+ ServerBadContent = 33,
+ ServerUnauthorized = 34,
+ ServerCertProblem = 35,
+ ServerForbidden = 36,
+ ServerUnreachable = 37,
+ UserCanceled = 40,
+ //UserShutdown = 41,
+ //Crash = 50
+ };
+ Q_ENUM(DownloadInterruptReason)
+
+ quint32 id() const;
+ DownloadState state() const;
+ qint64 totalBytes() const;
+ qint64 receivedBytes() const;
+ QUrl url() const;
+ QString mimeType() const;
+ bool isFinished() const;
+ bool isPaused() const;
+ SavePageFormat savePageFormat() const;
+ void setSavePageFormat(SavePageFormat format);
+ DownloadInterruptReason interruptReason() const;
+ QString interruptReasonString() const;
+ bool isSavePageDownload() const;
+ QString suggestedFileName() const;
+ QString downloadDirectory() const;
+ void setDownloadDirectory(const QString &directory);
+ QString downloadFileName() const;
+ void setDownloadFileName(const QString &fileName);
+
+ QWebEnginePage *page() const;
+
+public Q_SLOTS:
+ void accept();
+ void cancel();
+ void pause();
+ void resume();
+
+Q_SIGNALS:
+ void stateChanged(QWebEngineDownloadRequest::DownloadState state);
+ void savePageFormatChanged();
+ void receivedBytesChanged();
+ void totalBytesChanged();
+ void interruptReasonChanged();
+ void isFinishedChanged();
+ void isPausedChanged();
+ void downloadDirectoryChanged();
+ void downloadFileNameChanged();
+
+private:
+ Q_DISABLE_COPY(QWebEngineDownloadRequest)
+ Q_DECLARE_PRIVATE(QWebEngineDownloadRequest)
+
+ friend class QWebEngineProfilePrivate;
+
+protected:
+ QWebEngineDownloadRequest(QWebEngineDownloadRequestPrivate *, QObject *parent = nullptr);
+ QScopedPointer<QWebEngineDownloadRequestPrivate> d_ptr;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEDOWNLOADREQUEST_H
diff --git a/src/core/api/qwebenginedownloadrequest_p.h b/src/core/api/qwebenginedownloadrequest_p.h
new file mode 100644
index 000000000..eef6c9bb5
--- /dev/null
+++ b/src/core/api/qwebenginedownloadrequest_p.h
@@ -0,0 +1,68 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEDOWNLOADREQUEST_P_H
+#define QWEBENGINEDOWNLOADREQUEST_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qtwebenginecoreglobal.h"
+#include "qwebenginedownloadrequest.h"
+#include "profile_adapter_client.h"
+#include <QString>
+#include <QPointer>
+
+namespace QtWebEngineCore {
+class ProfileAdapter;
+class WebContentsAdapterClient;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineDownloadRequestPrivate
+{
+public:
+ QWebEngineDownloadRequestPrivate(QtWebEngineCore::ProfileAdapter *adapter);
+ ~QWebEngineDownloadRequestPrivate();
+
+ void update(const QtWebEngineCore::ProfileAdapterClient::DownloadItemInfo &info);
+ void setFinished();
+
+ bool downloadFinished = false;
+ quint32 downloadId = -1;
+ qint64 startTime;
+ QWebEngineDownloadRequest::DownloadState downloadState =
+ QWebEngineDownloadRequest::DownloadCancelled;
+ QWebEngineDownloadRequest::SavePageFormat savePageFormat =
+ QWebEngineDownloadRequest::MimeHtmlSaveFormat;
+ QWebEngineDownloadRequest::DownloadInterruptReason interruptReason =
+ QWebEngineDownloadRequest::NoReason;
+ QString downloadPath;
+ QUrl downloadUrl;
+ QString mimeType;
+ bool downloadPaused = false;
+ QString suggestedFileName;
+ QString downloadDirectory;
+ QString downloadFileName;
+ bool isCustomFileName = false;
+ qint64 totalBytes = -1;
+ qint64 receivedBytes = 0;
+ bool isSavePageDownload = false;
+ QWebEngineDownloadRequest *q_ptr;
+ QPointer<QtWebEngineCore::ProfileAdapter> profileAdapter;
+ QtWebEngineCore::WebContentsAdapterClient *adapterClient = nullptr;
+ Q_DECLARE_PUBLIC(QWebEngineDownloadRequest)
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEDOWNLOADREQUEST_P_H
diff --git a/src/core/api/qwebenginefilesystemaccessrequest.cpp b/src/core/api/qwebenginefilesystemaccessrequest.cpp
new file mode 100644
index 000000000..3f901b671
--- /dev/null
+++ b/src/core/api/qwebenginefilesystemaccessrequest.cpp
@@ -0,0 +1,126 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginefilesystemaccessrequest.h"
+
+#include "file_system_access/file_system_access_permission_request_controller.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineFileSystemAccessRequest
+ \brief The QWebEngineFileSystemAccessRequest class enables accepting or rejecting
+ requests for local file system access from JavaScript applications.
+
+ \since 6.4
+
+ \inmodule QtWebEngineCore
+
+ To allow web applications to access local files of the computer,
+ applications must connect to QWebEnginePage::fileSystemAccessRequested, which takes a
+ QWebEngineFileSystemAccessRequest instance as an argument.
+
+ If a web applications requests access to local files or directories,
+ QWebEnginePage::fileSystemAccessRequested will be emitted with an
+ QWebEngineFileSystemAccessRequest instance as an argument where accessFlags() indicates
+ the type of the requested access: read, write or both. The signal handler needs to then
+ either call accept() or reject().
+*/
+
+/*!
+ \enum QWebEngineFileSystemAccessRequest::AccessFlag
+
+ This enum describes the type of the requested access: read, write or both. The options
+ can be OR-ed together from the following list:
+
+ \value Read
+ \value Write
+*/
+
+/*!
+ \enum QWebEngineFileSystemAccessRequest::HandleType
+
+ This enum describes the type of the requested file system entry.
+
+ \value File
+ \value Directory
+*/
+
+QWebEngineFileSystemAccessRequest::QWebEngineFileSystemAccessRequest(
+ const QWebEngineFileSystemAccessRequest &other) = default;
+QWebEngineFileSystemAccessRequest &QWebEngineFileSystemAccessRequest::operator=(
+ const QWebEngineFileSystemAccessRequest &other) = default;
+QWebEngineFileSystemAccessRequest::~QWebEngineFileSystemAccessRequest() = default;
+
+/*! \fn bool QWebEngineFileSystemAccessRequest::operator==(const QWebEngineFileSystemAccessRequest &lhs, const QWebEngineFileSystemAccessRequest &rhs)
+ Returns \c true if \a lhs and \a rhs both point to the same request.
+*/
+
+/*! \fn bool QWebEngineFileSystemAccessRequest::operator!=(const QWebEngineFileSystemAccessRequest &lhs, const QWebEngineFileSystemAccessRequest &rhs)
+ Returns \c true if \a lhs and \a rhs point to different requests.
+*/
+
+/*! \internal */
+QWebEngineFileSystemAccessRequest::QWebEngineFileSystemAccessRequest(
+ std::shared_ptr<QtWebEngineCore::FileSystemAccessPermissionRequestController> controller)
+ : d_ptr(std::move(controller))
+{
+}
+
+/*!
+ Rejects a request to access local files.
+*/
+void QWebEngineFileSystemAccessRequest::reject()
+{
+ d_ptr->reject();
+}
+
+/*!
+ Accepts the request to access local files.
+*/
+void QWebEngineFileSystemAccessRequest::accept()
+{
+ d_ptr->accept();
+}
+
+/*!
+ \property QWebEngineFileSystemAccessRequest::origin
+ \brief The URL of the web page that issued the file system access request.
+*/
+
+QUrl QWebEngineFileSystemAccessRequest::origin() const
+{
+ return d_ptr->origin();
+}
+
+/*!
+ \property QWebEngineFileSystemAccessRequest::filePath
+ \brief Returns the file path this file system access request is referring to.
+*/
+
+QUrl QWebEngineFileSystemAccessRequest::filePath() const
+{
+ return d_ptr->filePath();
+}
+
+/*!
+ \property QWebEngineFileSystemAccessRequest::handleType
+ \brief Returns the type of the requested file system entry. (File or directory)
+ */
+HandleType QWebEngineFileSystemAccessRequest::handleType() const
+{
+ return d_ptr->handleType();
+}
+
+/*!
+ \property QWebEngineFileSystemAccessRequest::accessFlags
+ \brief Contains the requested file access rights.
+ */
+AccessFlags QWebEngineFileSystemAccessRequest::accessFlags() const
+{
+ return d_ptr->accessFlags();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginefilesystemaccessrequest.cpp"
diff --git a/src/core/api/qwebenginefilesystemaccessrequest.h b/src/core/api/qwebenginefilesystemaccessrequest.h
new file mode 100644
index 000000000..37b1e1861
--- /dev/null
+++ b/src/core/api/qwebenginefilesystemaccessrequest.h
@@ -0,0 +1,70 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEFILESYSTEMACCESSREQUEST_H
+#define QWEBENGINEFILESYSTEMACCESSREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qurl.h>
+#include <memory>
+
+namespace QtWebEngineCore {
+class FileSystemAccessPermissionRequestController;
+class FileSystemAccessPermissionRequestManagerQt;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineFileSystemAccessRequest
+{
+ Q_GADGET
+ Q_PROPERTY(QUrl origin READ origin CONSTANT FINAL)
+ Q_PROPERTY(QUrl filePath READ filePath CONSTANT FINAL)
+ Q_PROPERTY(HandleType handleType READ handleType CONSTANT FINAL)
+ Q_PROPERTY(AccessFlags accessFlags READ accessFlags CONSTANT FINAL)
+
+public:
+ QWebEngineFileSystemAccessRequest(const QWebEngineFileSystemAccessRequest &other);
+ QWebEngineFileSystemAccessRequest &operator=(const QWebEngineFileSystemAccessRequest &other);
+ QWebEngineFileSystemAccessRequest(QWebEngineFileSystemAccessRequest &&other) noexcept = default;
+ QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_PURE_SWAP(QWebEngineFileSystemAccessRequest)
+ ~QWebEngineFileSystemAccessRequest();
+
+ void swap(QWebEngineFileSystemAccessRequest &other) noexcept { d_ptr.swap(other.d_ptr); }
+
+ enum HandleType { File, Directory };
+ Q_ENUM(HandleType)
+
+ enum AccessFlag { Read = 0x1, Write = 0x2 };
+ Q_DECLARE_FLAGS(AccessFlags, AccessFlag)
+ Q_FLAG(AccessFlags)
+
+ Q_INVOKABLE void accept();
+ Q_INVOKABLE void reject();
+ QUrl origin() const;
+ QUrl filePath() const;
+ HandleType handleType() const;
+ AccessFlags accessFlags() const;
+
+ inline friend bool operator==(const QWebEngineFileSystemAccessRequest &lhs,
+ const QWebEngineFileSystemAccessRequest &rhs) noexcept
+ { return lhs.d_ptr == rhs.d_ptr; }
+ inline friend bool operator!=(const QWebEngineFileSystemAccessRequest &lhs,
+ const QWebEngineFileSystemAccessRequest &rhs) noexcept
+ { return lhs.d_ptr != rhs.d_ptr; }
+
+private:
+ QWebEngineFileSystemAccessRequest(
+ std::shared_ptr<QtWebEngineCore::FileSystemAccessPermissionRequestController>);
+ friend QtWebEngineCore::FileSystemAccessPermissionRequestManagerQt;
+
+ std::shared_ptr<QtWebEngineCore::FileSystemAccessPermissionRequestController> d_ptr;
+};
+
+Q_DECLARE_SHARED(QWebEngineFileSystemAccessRequest)
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(QWebEngineFileSystemAccessRequest::AccessFlags)
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEFILESYSTEMACCESSREQUEST_H
diff --git a/src/core/api/qwebenginefindtextresult.cpp b/src/core/api/qwebenginefindtextresult.cpp
index c0adc6177..ce953ddff 100644
--- a/src/core/api/qwebenginefindtextresult.cpp
+++ b/src/core/api/qwebenginefindtextresult.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebenginefindtextresult.h"
diff --git a/src/core/api/qwebenginefindtextresult.h b/src/core/api/qwebenginefindtextresult.h
index 246e689c3..d506a50f5 100644
--- a/src/core/api/qwebenginefindtextresult.h
+++ b/src/core/api/qwebenginefindtextresult.h
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEFINDTEXTRESULT_H
#define QWEBENGINEFINDTEXTRESULT_H
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-#include <QtCore/QObject>
-#include <QtCore/QSharedData>
+#include <QtCore/qobject.h>
+#include <QtCore/qshareddata.h>
namespace QtWebEngineCore {
class FindTextHelper;
@@ -52,7 +16,8 @@ QT_BEGIN_NAMESPACE
class QWebEngineFindTextResultPrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineFindTextResult {
+class Q_WEBENGINECORE_EXPORT QWebEngineFindTextResult
+{
Q_GADGET
Q_PROPERTY(int numberOfMatches READ numberOfMatches CONSTANT FINAL)
Q_PROPERTY(int activeMatch READ activeMatch CONSTANT FINAL)
diff --git a/src/core/api/qwebengineframe.cpp b/src/core/api/qwebengineframe.cpp
new file mode 100644
index 000000000..edd89d663
--- /dev/null
+++ b/src/core/api/qwebengineframe.cpp
@@ -0,0 +1,118 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineframe.h"
+
+#include "web_contents_adapter_client.h"
+#include "web_contents_adapter.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineFrame
+ \brief The QWebEngineFrame class gives information about and control over a page frame.
+ \since 6.8
+
+ \inmodule QtWebEngineCore
+
+ A web engine frame represents a single frame within a web page, such as those created by
+ \c <frame> or \c <iframe> HTML elements.
+ An active QWebEnginePage has one or more frames arranged in a tree structure. The top-level
+ frame, the root of this tree, can be accessed through the mainFrame() method, and
+ children() provides a frame's direct descendants.
+
+ A frame's lifetime is, at most, as long as the QWebEnginePage object that produced it.
+ However, frames may be created and deleted spontaneously and dynamically, for example through
+ navigation and script execution. Because of this, many QWebEngineFrame methods return
+ optional values, which will be \c std::nullopt if the frame no longer exists.
+*/
+
+/*! \internal
+ */
+QWebEngineFrame::QWebEngineFrame(QtWebEngineCore::WebContentsAdapterClient *adapter, quint64 id)
+ : m_adapterClient(adapter), m_id(id)
+{
+}
+
+/*!
+ Returns \c{true} if this object represents an existing frame; \c{false} otherwise.
+
+ Once a frame is invalid, it never becomes valid again.
+*/
+bool QWebEngineFrame::isValid() const
+{
+ return m_adapterClient->webContentsAdapter()->hasFrame(m_id);
+}
+
+/*!
+ Returns the frame name; that is, what would be returned by \c window.name in JavaScript.
+
+ If the frame could not be found, returns a null QString.
+
+ \sa htmlName
+*/
+QString QWebEngineFrame::name() const
+{
+ return m_adapterClient->webContentsAdapter()->frameName(m_id);
+}
+
+/*!
+ Returns the value of the frame's \c name HTML attribute, or an empty string if it has none.
+
+ If the frame could not be found, returns a null QString.
+
+ \sa name
+*/
+QString QWebEngineFrame::htmlName() const
+{
+ return m_adapterClient->webContentsAdapter()->frameHtmlName(m_id);
+}
+
+/*!
+ Returns a list of the frame's children in an arbitrary order.
+
+ If the frame could not be found, returns an empty list.
+ */
+QList<QWebEngineFrame> QWebEngineFrame::children() const
+{
+ QList<QWebEngineFrame> result;
+ for (auto childId : m_adapterClient->webContentsAdapter()->frameChildren(m_id))
+ result.push_back(QWebEngineFrame{ m_adapterClient, childId });
+ return result;
+}
+
+/*!
+ Returns the URL of the content currently loaded in this frame.
+
+ If the frame could not be found, returns an empty QUrl.
+ */
+QUrl QWebEngineFrame::url() const
+{
+ return m_adapterClient->webContentsAdapter()->frameUrl(m_id);
+}
+
+/*!
+ Returns the size of the frame within the viewport.
+
+ If the frame could not be found, returns QSizeF().
+ */
+QSizeF QWebEngineFrame::size() const
+{
+ return m_adapterClient->webContentsAdapter()->frameSize(m_id);
+}
+
+/*! \fn bool QWebEngineFrame::operator==(const QWebEngineFrame &left, const QWebEngineFrame &right) noexcept
+
+ Returns \c{true} if \a left and \a right represent the same frame in the same web page,
+ otherwise \c{false}.
+ */
+
+/*! \fn bool QWebEngineFrame::operator!=(const QWebEngineFrame &left, const QWebEngineFrame &right) noexcept
+
+ Returns \c{true} if \a left and \a right represent different frames in the same web page,
+ otherwise \c{false}.
+ */
+
+QT_END_NAMESPACE
+
+#include "moc_qwebengineframe.cpp"
diff --git a/src/core/api/qwebengineframe.h b/src/core/api/qwebengineframe.h
new file mode 100644
index 000000000..1378a5cbc
--- /dev/null
+++ b/src/core/api/qwebengineframe.h
@@ -0,0 +1,49 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEFRAME_H
+#define QWEBENGINEFRAME_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qcompare.h>
+#include <QtCore/QList>
+#include <QtCore/QSizeF>
+#include <QtCore/QString>
+#include <QtCore/QUrl>
+
+namespace QtWebEngineCore {
+class WebContentsAdapterClient;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineFrame
+{
+public:
+ bool isValid() const;
+ QString name() const;
+ QString htmlName() const;
+ QList<QWebEngineFrame> children() const;
+ QUrl url() const;
+ QSizeF size() const;
+
+ friend inline bool comparesEqual(const QWebEngineFrame &lhs,
+ const QWebEngineFrame &rhs) noexcept
+ {
+ return lhs.m_adapterClient == rhs.m_adapterClient && lhs.m_id == rhs.m_id;
+ }
+
+ Q_DECLARE_EQUALITY_COMPARABLE(QWebEngineFrame);
+
+private:
+ friend class QWebEnginePage;
+
+ QWebEngineFrame(QtWebEngineCore::WebContentsAdapterClient *page, quint64 id);
+
+ QtWebEngineCore::WebContentsAdapterClient *m_adapterClient;
+ quint64 m_id;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEFRAME_H
diff --git a/src/core/api/qwebenginefullscreenrequest.cpp b/src/core/api/qwebenginefullscreenrequest.cpp
new file mode 100644
index 000000000..938aad19c
--- /dev/null
+++ b/src/core/api/qwebenginefullscreenrequest.cpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginefullscreenrequest.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineFullScreenRequest
+ \brief The QWebEngineFullScreenRequest class enables accepting or rejecting
+ requests for entering and exiting the fullscreen mode.
+
+ \since 5.6
+
+ \inmodule QtWebEngineCore
+
+ To allow elements such as videos to be shown in the fullscreen mode,
+ applications must set QWebEngineSettings::FullScreenSupportEnabled and
+ connect to QWebEnginePage::fullScreenRequested, which takes a
+ QWebEngineFullScreenRequest instance as an argument.
+
+ If an element of a web page requests to be shown in the fullscreen mode,
+ QWebEnginePage::fullScreenRequested will be emitted with an
+ QWebEngineFullScreenRequest instance as an argument where toggleOn() returns
+ \c true. The signal handler needs to then either call accept() or reject().
+
+ If the request to enter the fullscreen mode is accepted, the element
+ requesting fullscreen mode will fill the viewport, but it is up to the
+ application to make the view fullscreen or to move the page to a view that
+ is in the fullscreen mode.
+
+ Likewise, a QWebEnginePage::fullScreenRequested will be emitted when
+ the user wants to leave the full screen mode (that is, through the
+ QWebEnginePage::ExitFullScreen context menu action). In this case,
+ toggleOn() will return \c false, and the signal handler again needs to
+ accept() or reject() the request. If it is accepted, the applicaton needs to
+ make sure that the global window state is restored.
+*/
+
+/*!
+ \property QWebEngineFullScreenRequest::toggleOn
+ \brief Whether the web page has issued a request to enter fullscreen mode.
+*/
+
+/*!
+ \property QWebEngineFullScreenRequest::origin
+ \brief The URL to be opened in the fullscreen mode.
+*/
+
+/*
+ Creates a request for opening the \a page from the URL specified by
+ \a origin in the fullscreen mode if \a fullscreen is \c true.
+*/
+
+class QWebEngineFullScreenRequestPrivate : public QSharedData {
+public:
+ QWebEngineFullScreenRequestPrivate(const QUrl &origin, bool toggleOn, const std::function<void (bool)> &setFullScreenCallback)
+ : m_origin(origin)
+ , m_toggleOn(toggleOn)
+ , m_setFullScreenCallback(setFullScreenCallback) { }
+
+ const QUrl m_origin;
+ const bool m_toggleOn;
+ const std::function<void (bool)> m_setFullScreenCallback;
+};
+
+QWebEngineFullScreenRequest::QWebEngineFullScreenRequest(const QUrl &origin, bool toggleOn, const std::function<void (bool)> &setFullScreenCallback)
+ : d_ptr(new QWebEngineFullScreenRequestPrivate(origin, toggleOn, setFullScreenCallback)) { }
+
+QWebEngineFullScreenRequest::QWebEngineFullScreenRequest(const QWebEngineFullScreenRequest &other) = default;
+QWebEngineFullScreenRequest& QWebEngineFullScreenRequest::operator=(const QWebEngineFullScreenRequest &other) = default;
+QWebEngineFullScreenRequest::QWebEngineFullScreenRequest(QWebEngineFullScreenRequest &&other) = default;
+QWebEngineFullScreenRequest& QWebEngineFullScreenRequest::operator=(QWebEngineFullScreenRequest &&other) = default;
+QWebEngineFullScreenRequest::~QWebEngineFullScreenRequest() = default;
+
+/*!
+ Rejects a request to enter or exit the fullscreen mode.
+*/
+void QWebEngineFullScreenRequest::reject()
+{
+ d_ptr->m_setFullScreenCallback(!d_ptr->m_toggleOn);
+}
+
+/*!
+ Accepts the request to enter or exit the fullscreen mode.
+*/
+void QWebEngineFullScreenRequest::accept()
+{
+ d_ptr->m_setFullScreenCallback(d_ptr->m_toggleOn);
+}
+
+/*!
+ \fn QWebEngineFullScreenRequest::toggleOn() const
+ Returns \c true if the web page has issued a request to enter the fullscreen
+ mode, otherwise returns \c false.
+*/
+bool QWebEngineFullScreenRequest::toggleOn() const
+{
+ return d_ptr->m_toggleOn;
+}
+
+/*!
+ \fn QWebEngineFullScreenRequest::origin() const
+ Returns the URL to be opened in the fullscreen mode.
+*/
+QUrl QWebEngineFullScreenRequest::origin() const
+{
+ return d_ptr->m_origin;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginefullscreenrequest.cpp"
diff --git a/src/core/api/qwebenginefullscreenrequest.h b/src/core/api/qwebenginefullscreenrequest.h
new file mode 100644
index 000000000..8e25286b6
--- /dev/null
+++ b/src/core/api/qwebenginefullscreenrequest.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEFULLSCREENREQUEST_H
+#define QWEBENGINEFULLSCREENREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qglobal.h>
+#include <QtCore/qshareddata.h>
+#include <QtCore/qurl.h>
+
+#include <functional>
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineFullScreenRequestPrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineFullScreenRequest
+{
+ Q_GADGET
+ Q_PROPERTY(bool toggleOn READ toggleOn CONSTANT)
+ Q_PROPERTY(QUrl origin READ origin CONSTANT)
+
+public:
+ QWebEngineFullScreenRequest(const QWebEngineFullScreenRequest &other);
+ QWebEngineFullScreenRequest &operator=(const QWebEngineFullScreenRequest &other);
+ QWebEngineFullScreenRequest(QWebEngineFullScreenRequest &&other);
+ QWebEngineFullScreenRequest &operator=(QWebEngineFullScreenRequest &&other);
+ ~QWebEngineFullScreenRequest();
+
+ Q_INVOKABLE void reject();
+ Q_INVOKABLE void accept();
+ bool toggleOn() const;
+ QUrl origin() const;
+
+private:
+ friend class QWebEnginePagePrivate;
+ friend class QQuickWebEngineViewPrivate;
+ QWebEngineFullScreenRequest(const QUrl &origin, bool toggleOn, const std::function<void (bool)> &setFullScreenCallback);
+ QExplicitlySharedDataPointer<QWebEngineFullScreenRequestPrivate> d_ptr;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/core/api/qwebengineglobalsettings.cpp b/src/core/api/qwebengineglobalsettings.cpp
new file mode 100644
index 000000000..6aadd5517
--- /dev/null
+++ b/src/core/api/qwebengineglobalsettings.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineglobalsettings.h"
+#include "qwebengineglobalsettings_p.h"
+#include <QDebug>
+
+#ifdef signals
+#undef signals
+#endif
+
+namespace QtWebEngineCore {
+extern void configureStubHostResolver(QWebEngineGlobalSettings::SecureDnsMode dnsMode,
+ std::string dnsOverHttpsTemplates, bool insecureDnsClientEnabled,
+ bool additionalInsecureDnsTypesEnabled);
+extern bool isValidTemplates(std::string templates);
+
+} // namespace QtWebEngineCore
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \namespace QWebEngineGlobalSettings
+ \brief The QWebEngineGlobalSettings namespace holds global settings of the web engine.
+ \since 6.6
+ \inmodule QtWebEngineCore
+
+ The QWebEngineGlobalSettings namespace holds global properties of the web engine.
+
+ Invoke setDnsMode() to configure DNS-over-HTTPS.
+
+ \sa QWebEngineGlobalSettings::setDnsMode()
+*/
+
+/*!
+ \enum QWebEngineGlobalSettings::SecureDnsMode
+
+ This enum sets the DNS-over-HTTPS mode used by the DnsMode structure:
+
+ \value SystemOnly This is the default. Use the system DNS host resolution.
+ \value SecureWithFallback Enable DNS-over-HTTPS (DoH). DoH servers have to be
+ provided through \l {QWebEngineGlobalSettings::DnsMode::serverTemplates}{serverTemplates} in
+ the DnsMode structure. If a host cannot be resolved via the provided servers,
+ the system DNS host resolution is used.
+ \value SecureOnly Enable DNS-over-HTTPS and only allow hosts to be resolved
+ this way. DoH servers have to be provided through
+ \l {QWebEngineGlobalSettings::DnsMode::serverTemplates}{serverTemplates} in the DnsMode
+ structure. If the DNS-over-HTTPS resolution fails, there is no fallback and the DNS host
+ resolution fails completely.
+*/
+
+/*!
+ \class QWebEngineGlobalSettings::DnsMode
+ \brief The DnsMode struct provides means to specify the DNS host resolution mode.
+ \since 6.6
+ \inmodule QtWebEngineCore
+
+ The QWebEngineGlobalSettings::DnsMode structure describes the DNS mode and
+ the associated DNS server template used for the DNS host resolution.
+*/
+
+/*!
+ \variable QWebEngineGlobalSettings::DnsMode::secureMode
+ \brief The DNS mode used for the host resolution.
+
+ Set \a secureMode to SecureDnsMode::SecureOnly to only allow DNS-over-HTTPS host resolution
+ using servers from \a serverTemplates.
+
+ Set \a secureMode to SecureDnsMode::SecureWithFallback to enable DNS-over-HTTPS host resolution
+ using servers from \a serverTemplates, with a fallback to the system DNS.
+
+ \sa QWebEngineGlobalSettings::SecureDnsMode
+*/
+
+/*!
+ \variable QWebEngineGlobalSettings::DnsMode::serverTemplates
+ \brief A list of server URI templates used for secure DNS-over-HTTPS host resolution.
+
+ The \c serverTemplates structure member lists
+ \l{https://datatracker.ietf.org/d7oc/html/rfc6570}{URI templates}.
+ An example of a URI template is https://dns.google/dns-query{?dns}.
+*/
+
+/*!
+ \fn void QWebEngineGlobalSettings::setDnsMode(DnsMode dnsMode)
+
+ Sets \a dnsMode for DNS-over-HTTPS host resolution.
+
+ This function returns \c false if the \l {QWebEngineGlobalSettings::DnsMode::serverTemplates}
+ {serverTemplates} list in the \l {QWebEngineGlobalSettings::DnsMode}{DnsMode} structure is empty
+ or contains URI templates that cannot be parsed for SecureDnsMode::SecureOnly or
+ SecureDnsMode::SecureWithFallback. Otherwise, it returns \c true meaning that the DNS mode
+ change is triggered.
+*/
+
+bool QWebEngineGlobalSettings::setDnsMode(DnsMode dnsMode)
+{
+ QWebEngineGlobalSettingsPrivate *d = QWebEngineGlobalSettingsPrivate::instance();
+ if (dnsMode.secureMode != SecureDnsMode::SystemOnly) {
+ const QString servers = dnsMode.serverTemplates.join(QChar::Space);
+ const std::string templates = servers.toStdString();
+ if (!QtWebEngineCore::isValidTemplates(templates))
+ return false;
+ d->dnsOverHttpsTemplates = templates;
+ }
+ d->dnsMode = dnsMode.secureMode;
+ d->configureStubHostResolver();
+ return true;
+}
+
+/*!
+ \internal
+*/
+QWebEngineGlobalSettingsPrivate *QWebEngineGlobalSettingsPrivate::instance()
+{
+ static QWebEngineGlobalSettingsPrivate settings;
+ return &settings;
+}
+
+void QWebEngineGlobalSettingsPrivate::configureStubHostResolver()
+{
+ QtWebEngineCore::configureStubHostResolver(dnsMode, dnsOverHttpsTemplates, insecureDnsClientEnabled, additionalInsecureDnsTypesEnabled);
+}
+
+QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineglobalsettings.h b/src/core/api/qwebengineglobalsettings.h
new file mode 100644
index 000000000..a9eff6d12
--- /dev/null
+++ b/src/core/api/qwebengineglobalsettings.h
@@ -0,0 +1,30 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEGLOBALSETTINGS_H
+#define QWEBENGINEGLOBALSETTINGS_H
+
+#if 0
+#pragma qt_class(QWebEngineGlobalSettings)
+#endif
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/QObject>
+#include <QtCore/QScopedPointer>
+
+QT_BEGIN_NAMESPACE
+
+namespace QWebEngineGlobalSettings {
+// Mapping net::SecureDnsMode
+enum class SecureDnsMode : quint8 { SystemOnly = 0, SecureWithFallback = 1, SecureOnly = 2 };
+struct DnsMode
+{
+ SecureDnsMode secureMode = SecureDnsMode::SystemOnly;
+ QStringList serverTemplates;
+};
+Q_WEBENGINECORE_EXPORT bool setDnsMode(DnsMode dnsMode);
+}
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEGLOBALSETTINGS_H
diff --git a/src/core/api/qwebengineglobalsettings_p.h b/src/core/api/qwebengineglobalsettings_p.h
new file mode 100644
index 000000000..8e35ad68c
--- /dev/null
+++ b/src/core/api/qwebengineglobalsettings_p.h
@@ -0,0 +1,44 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEGLOBALSETTINGS_P_H
+#define QWEBENGINEGLOBALSETTINGS_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qtwebenginecoreglobal_p.h"
+#include "qwebengineglobalsettings.h"
+#include <string>
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineGlobalSettingsPrivate
+{
+public:
+ QWebEngineGlobalSettingsPrivate()
+ : dnsMode(QWebEngineGlobalSettings::SecureDnsMode::SystemOnly)
+ , dnsOverHttpsTemplates("")
+ , insecureDnsClientEnabled(false)
+ , additionalInsecureDnsTypesEnabled(false){};
+
+ static QWebEngineGlobalSettingsPrivate *instance();
+ QWebEngineGlobalSettings::SecureDnsMode dnsMode;
+ std::string dnsOverHttpsTemplates;
+ const bool insecureDnsClientEnabled;
+ const bool additionalInsecureDnsTypesEnabled;
+
+ void configureStubHostResolver();
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEGLOBALSETTINGS_P_H
diff --git a/src/core/api/qwebenginehistory.cpp b/src/core/api/qwebenginehistory.cpp
new file mode 100644
index 000000000..5d2fc8e9e
--- /dev/null
+++ b/src/core/api/qwebenginehistory.cpp
@@ -0,0 +1,389 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginehistory.h"
+#include "qwebenginehistory_p.h"
+
+#include "web_contents_adapter.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \fn QWebEngineHistoryItem::swap(QWebEngineHistoryItem &other)
+ Swaps the history item with the \a other item.
+*/
+
+QWebEngineHistoryItemPrivate::QWebEngineHistoryItemPrivate(
+ QtWebEngineCore::WebContentsAdapterClient *client, int index)
+ : client(client), index(index)
+{
+}
+
+QtWebEngineCore::WebContentsAdapter *QWebEngineHistoryItemPrivate::adapter() const
+{
+ return client ? client->webContentsAdapter() : nullptr;
+}
+
+QWebEngineHistoryItem::QWebEngineHistoryItem(QWebEngineHistoryItemPrivate *d) : d(d) { }
+QWebEngineHistoryItem::QWebEngineHistoryItem(const QWebEngineHistoryItem &other) = default;
+QWebEngineHistoryItem::QWebEngineHistoryItem(QWebEngineHistoryItem &&other) = default;
+QWebEngineHistoryItem &QWebEngineHistoryItem::operator=(const QWebEngineHistoryItem &other) = default;
+QWebEngineHistoryItem &QWebEngineHistoryItem::operator=(QWebEngineHistoryItem &&other) = default;
+QWebEngineHistoryItem::~QWebEngineHistoryItem() = default;
+
+QUrl QWebEngineHistoryItem::originalUrl() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ return d->adapter() ? d->adapter()->getNavigationEntryOriginalUrl(d->index) : QUrl();
+}
+
+QUrl QWebEngineHistoryItem::url() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ return d->adapter() ? d->adapter()->getNavigationEntryUrl(d->index) : QUrl();
+}
+
+QString QWebEngineHistoryItem::title() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ return d->adapter() ? d->adapter()->getNavigationEntryTitle(d->index) : QString();
+}
+
+QDateTime QWebEngineHistoryItem::lastVisited() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ return d->adapter() ? d->adapter()->getNavigationEntryTimestamp(d->index) : QDateTime();
+}
+
+/*!
+ Returns the URL of the icon associated with the history item.
+
+ \sa url(), originalUrl(), title()
+*/
+QUrl QWebEngineHistoryItem::iconUrl() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ return d->adapter() ? d->adapter()->getNavigationEntryIconUrl(d->index) : QUrl();
+}
+
+bool QWebEngineHistoryItem::isValid() const
+{
+ Q_D(const QWebEngineHistoryItem);
+ if (!d->client)
+ return false;
+ return d->index >= 0 && d->index < d->adapter()->navigationEntryCount();
+}
+
+QWebEngineHistoryPrivate::QWebEngineHistoryPrivate(QtWebEngineCore::WebContentsAdapterClient *client,
+ const ImageProviderUrl &imageProviderUrl)
+ : client(client), imageProviderUrl(imageProviderUrl)
+{
+ Q_ASSERT(client);
+}
+
+QWebEngineHistoryPrivate::~QWebEngineHistoryPrivate()
+{
+ // Invalidate shared item references possibly still out there.
+ QList<QWebEngineHistoryItem>::iterator it, end;
+ for (it = items.begin(), end = items.end(); it != end; ++it)
+ it->d->client = nullptr;
+}
+
+void QWebEngineHistoryPrivate::updateItems() const
+{
+ // Keep track of items we return to be able to invalidate them
+ // and avoid dangling references to our client.
+ int entryCount = adapter()->navigationEntryCount();
+ while (items.size() > entryCount) {
+ items.last().d->client = nullptr;
+ items.removeLast();
+ }
+ while (items.size() < entryCount) {
+ int nextIndex = items.size();
+ items.append(QWebEngineHistoryItem(new QWebEngineHistoryItemPrivate(client, nextIndex)));
+ }
+}
+
+QtWebEngineCore::WebContentsAdapter *QWebEngineHistoryPrivate::adapter() const
+{
+ Q_ASSERT(client->webContentsAdapter());
+ return client->webContentsAdapter();
+}
+
+QWebEngineHistoryModelPrivate::QWebEngineHistoryModelPrivate(const QWebEngineHistoryPrivate *history)
+ : history(history)
+{
+ Q_ASSERT(history);
+}
+
+QWebEngineHistoryModelPrivate::~QWebEngineHistoryModelPrivate()
+{
+}
+
+QtWebEngineCore::WebContentsAdapter *QWebEngineHistoryModelPrivate::adapter() const
+{
+ Q_ASSERT(history->adapter());
+ return history->adapter();
+}
+
+int QWebEngineHistoryModelPrivate::count() const
+{
+ return adapter()->navigationEntryCount();
+}
+
+int QWebEngineHistoryModelPrivate::index(int index) const
+{
+ return index;
+}
+
+int QWebEngineHistoryModelPrivate::offsetForIndex(int index) const
+{
+ return index - adapter()->currentNavigationEntryIndex();
+}
+
+int QWebEngineBackHistoryModelPrivate::count() const
+{
+ return adapter()->currentNavigationEntryIndex();
+}
+
+int QWebEngineBackHistoryModelPrivate::index(int i) const
+{
+ Q_ASSERT(i >= 0 && i < count());
+ return count() - 1 - i;
+}
+
+int QWebEngineBackHistoryModelPrivate::offsetForIndex(int index) const
+{
+ return - index - 1;
+}
+
+int QWebEngineForwardHistoryModelPrivate::count() const
+{
+ if (!adapter()->isInitialized())
+ return 0;
+ return adapter()->navigationEntryCount() - adapter()->currentNavigationEntryIndex() - 1;
+}
+
+int QWebEngineForwardHistoryModelPrivate::index(int i) const
+{
+ return adapter()->currentNavigationEntryIndex() + i + 1;
+}
+
+int QWebEngineForwardHistoryModelPrivate::offsetForIndex(int index) const
+{
+ return index + 1;
+}
+
+QWebEngineHistoryModel::QWebEngineHistoryModel(QWebEngineHistoryModelPrivate *d)
+ : d_ptr(d)
+{
+}
+
+QWebEngineHistoryModel::~QWebEngineHistoryModel()
+{
+}
+
+QHash<int, QByteArray> QWebEngineHistoryModel::roleNames() const
+{
+ QHash<int, QByteArray> roles;
+ roles[Qt::DisplayRole] = "display";
+ roles[Qt::ToolTipRole] = "toolTip";
+ roles[UrlRole] = "url";
+ roles[TitleRole] = "title";
+ roles[OffsetRole] = "offset";
+ roles[IconUrlRole] = "icon";
+ return roles;
+}
+
+int QWebEngineHistoryModel::rowCount(const QModelIndex &index) const
+{
+ Q_UNUSED(index);
+ Q_D(const QWebEngineHistoryModel);
+ return d->count();
+}
+
+QVariant QWebEngineHistoryModel::data(const QModelIndex &index, int role) const
+{
+ Q_D(const QWebEngineHistoryModel);
+
+ if (!index.isValid())
+ return QVariant();
+
+ switch (role) {
+ case Qt::DisplayRole:
+ case TitleRole:
+ return d->adapter()->getNavigationEntryTitle(d->index(index.row()));
+
+ case Qt::ToolTipRole:
+ case UrlRole:
+ return d->adapter()->getNavigationEntryUrl(d->index(index.row()));
+
+ case OffsetRole:
+ return d->offsetForIndex(index.row());
+
+ case IconUrlRole: {
+ QUrl url = QUrl(d->adapter()->getNavigationEntryIconUrl(d->index(index.row())));
+ return d->history->urlOrImageProviderUrl(url);
+ }
+ default:
+ break;
+ }
+
+ return QVariant();
+}
+
+void QWebEngineHistoryModel::reset()
+{
+ beginResetModel();
+ endResetModel();
+}
+
+QWebEngineHistory::QWebEngineHistory(QWebEngineHistoryPrivate *d) : d_ptr(d) { }
+
+QWebEngineHistory::~QWebEngineHistory() { }
+
+void QWebEngineHistory::clear()
+{
+ Q_D(const QWebEngineHistory);
+ d->adapter()->clearNavigationHistory();
+ d->client->updateNavigationActions();
+ reset();
+}
+
+QList<QWebEngineHistoryItem> QWebEngineHistory::items() const
+{
+ Q_D(const QWebEngineHistory);
+ d->updateItems();
+ return d->items;
+}
+
+QList<QWebEngineHistoryItem> QWebEngineHistory::backItems(int maxItems) const
+{
+ Q_D(const QWebEngineHistory);
+ d->updateItems();
+ const int end = currentItemIndex();
+ const int start = std::max(0, end - maxItems);
+ return d->items.mid(start, end - start);
+}
+
+QList<QWebEngineHistoryItem> QWebEngineHistory::forwardItems(int maxItems) const
+{
+ Q_D(const QWebEngineHistory);
+ d->updateItems();
+ const int start = currentItemIndex() + 1;
+ const int end = std::min(count(), start + maxItems);
+ return d->items.mid(start, end - start);
+}
+
+bool QWebEngineHistory::canGoBack() const
+{
+ Q_D(const QWebEngineHistory);
+ return d->adapter()->canGoToOffset(-1);
+}
+
+bool QWebEngineHistory::canGoForward() const
+{
+ Q_D(const QWebEngineHistory);
+ return d->adapter()->canGoToOffset(1);
+}
+
+void QWebEngineHistory::back()
+{
+ Q_D(const QWebEngineHistory);
+ d->adapter()->navigateToOffset(-1);
+}
+
+void QWebEngineHistory::forward()
+{
+ Q_D(const QWebEngineHistory);
+ d->adapter()->navigateToOffset(1);
+}
+
+void QWebEngineHistory::goToItem(const QWebEngineHistoryItem &item)
+{
+ Q_D(const QWebEngineHistory);
+ Q_ASSERT(item.d->client == d->client);
+ d->adapter()->navigateToIndex(item.d->index);
+}
+
+QWebEngineHistoryItem QWebEngineHistory::backItem() const
+{
+ return itemAt(currentItemIndex() - 1);
+}
+
+QWebEngineHistoryItem QWebEngineHistory::currentItem() const
+{
+ return itemAt(currentItemIndex());
+}
+
+QWebEngineHistoryItem QWebEngineHistory::forwardItem() const
+{
+ return itemAt(currentItemIndex() + 1);
+}
+
+QWebEngineHistoryItem QWebEngineHistory::itemAt(int i) const
+{
+ Q_D(const QWebEngineHistory);
+ if (i >= 0 && i < count()) {
+ d->updateItems();
+ return d->items[i];
+ } else {
+ // Return an invalid item right away.
+ QWebEngineHistoryItem item(new QWebEngineHistoryItemPrivate(0, i));
+ Q_ASSERT(!item.isValid());
+ return item;
+ }
+}
+
+int QWebEngineHistory::currentItemIndex() const
+{
+ Q_D(const QWebEngineHistory);
+ return d->adapter()->currentNavigationEntryIndex();
+}
+
+int QWebEngineHistory::count() const
+{
+ Q_D(const QWebEngineHistory);
+ if (!d->adapter()->isInitialized())
+ return 0;
+ return d->adapter()->navigationEntryCount();
+}
+
+QWebEngineHistoryModel *QWebEngineHistory::itemsModel() const
+{
+ Q_D(const QWebEngineHistory);
+ if (!d->navigationModel)
+ d->navigationModel.reset(new QWebEngineHistoryModel(new QWebEngineHistoryModelPrivate(d)));
+ return d->navigationModel.data();
+}
+
+QWebEngineHistoryModel *QWebEngineHistory::backItemsModel() const
+{
+ Q_D(const QWebEngineHistory);
+ if (!d->backNavigationModel)
+ d->backNavigationModel.reset(new QWebEngineHistoryModel(new QWebEngineBackHistoryModelPrivate(d)));
+ return d->backNavigationModel.data();
+}
+
+QWebEngineHistoryModel *QWebEngineHistory::forwardItemsModel() const
+{
+ Q_D(const QWebEngineHistory);
+ if (!d->forwardNavigationModel)
+ d->forwardNavigationModel.reset(new QWebEngineHistoryModel(new QWebEngineForwardHistoryModelPrivate(d)));
+ return d->forwardNavigationModel.data();
+}
+
+void QWebEngineHistory::reset()
+{
+ Q_D(QWebEngineHistory);
+ if (d->navigationModel)
+ d->navigationModel->reset();
+ if (d->backNavigationModel)
+ d->backNavigationModel->reset();
+ if (d->forwardNavigationModel)
+ d->forwardNavigationModel->reset();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginehistory.cpp"
diff --git a/src/core/api/qwebenginehistory.h b/src/core/api/qwebenginehistory.h
new file mode 100644
index 000000000..fd54e62a5
--- /dev/null
+++ b/src/core/api/qwebenginehistory.h
@@ -0,0 +1,136 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEHISTORY_H
+#define QWEBENGINEHISTORY_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qabstractitemmodel.h>
+#include <QtCore/qurl.h>
+#include <QtCore/qstring.h>
+#include <QtCore/qdatetime.h>
+#include <QtCore/qshareddata.h>
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineHistory;
+class QWebEngineHistoryPrivate;
+class QWebEngineHistoryItemPrivate;
+class QWebEngineHistoryModelPrivate;
+class QWebEnginePagePrivate;
+class QQuickWebEngineViewPrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineHistoryItem
+{
+public:
+ QWebEngineHistoryItem(const QWebEngineHistoryItem &other);
+ QWebEngineHistoryItem(QWebEngineHistoryItem &&other);
+ QWebEngineHistoryItem &operator=(const QWebEngineHistoryItem &other);
+ QWebEngineHistoryItem &operator=(QWebEngineHistoryItem &&other);
+ ~QWebEngineHistoryItem();
+
+ QUrl originalUrl() const;
+ QUrl url() const;
+
+ QString title() const;
+ QDateTime lastVisited() const;
+ QUrl iconUrl() const;
+
+ bool isValid() const;
+
+ void swap(QWebEngineHistoryItem &other) noexcept { d.swap(other.d); }
+
+private:
+ QWebEngineHistoryItem(QWebEngineHistoryItemPrivate *priv);
+ Q_DECLARE_PRIVATE_D(d.data(), QWebEngineHistoryItem)
+ QExplicitlySharedDataPointer<QWebEngineHistoryItemPrivate> d;
+ friend class QWebEngineHistory;
+ friend class QWebEngineHistoryPrivate;
+};
+
+Q_DECLARE_SHARED(QWebEngineHistoryItem)
+
+class Q_WEBENGINECORE_EXPORT QWebEngineHistoryModel : public QAbstractListModel
+{
+ Q_OBJECT
+
+public:
+ enum Roles {
+ UrlRole = Qt::UserRole,
+ TitleRole,
+ OffsetRole,
+ IconUrlRole,
+ };
+
+ int rowCount(const QModelIndex &parent = QModelIndex()) const override;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
+ QHash<int, QByteArray> roleNames() const override;
+ void reset();
+
+private:
+ QWebEngineHistoryModel(QWebEngineHistoryModelPrivate *);
+ virtual ~QWebEngineHistoryModel();
+
+ Q_DISABLE_COPY(QWebEngineHistoryModel)
+ Q_DECLARE_PRIVATE(QWebEngineHistoryModel)
+ QScopedPointer<QWebEngineHistoryModelPrivate> d_ptr;
+
+ friend class QWebEngineHistory;
+ friend class QWebEngineHistoryPrivate;
+ friend void QScopedPointerDeleter<QWebEngineHistoryModel>::cleanup(QWebEngineHistoryModel *) noexcept;
+};
+
+class Q_WEBENGINECORE_EXPORT QWebEngineHistory : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QWebEngineHistoryModel *items READ itemsModel CONSTANT FINAL)
+ Q_PROPERTY(QWebEngineHistoryModel *backItems READ backItemsModel CONSTANT FINAL)
+ Q_PROPERTY(QWebEngineHistoryModel *forwardItems READ forwardItemsModel CONSTANT FINAL)
+
+public:
+ Q_REVISION(1) Q_INVOKABLE void clear();
+
+ QList<QWebEngineHistoryItem> items() const;
+ QList<QWebEngineHistoryItem> backItems(int maxItems) const;
+ QList<QWebEngineHistoryItem> forwardItems(int maxItems) const;
+
+ bool canGoBack() const;
+ bool canGoForward() const;
+
+ void back();
+ void forward();
+ void goToItem(const QWebEngineHistoryItem &item);
+
+ QWebEngineHistoryItem backItem() const;
+ QWebEngineHistoryItem currentItem() const;
+ QWebEngineHistoryItem forwardItem() const;
+ QWebEngineHistoryItem itemAt(int i) const;
+
+ int currentItemIndex() const;
+
+ int count() const;
+
+ QWebEngineHistoryModel *itemsModel() const;
+ QWebEngineHistoryModel *backItemsModel() const;
+ QWebEngineHistoryModel *forwardItemsModel() const;
+
+private:
+ QWebEngineHistory(QWebEngineHistoryPrivate *d);
+ ~QWebEngineHistory();
+
+ Q_DISABLE_COPY(QWebEngineHistory)
+ Q_DECLARE_PRIVATE(QWebEngineHistory)
+ QScopedPointer<QWebEngineHistoryPrivate> d_ptr;
+
+ void reset();
+
+ friend Q_WEBENGINECORE_EXPORT QDataStream &operator>>(QDataStream &, QWebEngineHistory &);
+ friend Q_WEBENGINECORE_EXPORT QDataStream &operator<<(QDataStream &, const QWebEngineHistory &);
+ friend class QWebEnginePagePrivate;
+ friend class QQuickWebEngineViewPrivate;
+ friend void QScopedPointerDeleter<QWebEngineHistory>::cleanup(QWebEngineHistory *) noexcept;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEHISTORY_H
diff --git a/src/core/api/qwebenginehistory_p.h b/src/core/api/qwebenginehistory_p.h
new file mode 100644
index 000000000..fe28f4a0e
--- /dev/null
+++ b/src/core/api/qwebenginehistory_p.h
@@ -0,0 +1,99 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEHISTORY_P_H
+#define QWEBENGINEHISTORY_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+#include "qtwebenginecoreglobal_p.h"
+#include "qwebenginehistory.h"
+#include <QtCore/qshareddata.h>
+
+namespace QtWebEngineCore {
+class WebContentsAdapter;
+class WebContentsAdapterClient;
+}
+
+QT_BEGIN_NAMESPACE
+
+class QWebEnginePagePrivate;
+
+class QWebEngineHistoryItemPrivate : public QSharedData
+{
+public:
+ QWebEngineHistoryItemPrivate(QtWebEngineCore::WebContentsAdapterClient *client = nullptr, int index = 0);
+ QtWebEngineCore::WebContentsAdapter *adapter() const;
+ QtWebEngineCore::WebContentsAdapterClient *client;
+ int index;
+};
+
+class QWebEngineHistoryModelPrivate
+{
+public:
+ QWebEngineHistoryModelPrivate(const QWebEngineHistoryPrivate *history);
+ virtual ~QWebEngineHistoryModelPrivate();
+
+ virtual int count() const;
+ virtual int index(int) const;
+ virtual int offsetForIndex(int) const;
+
+ QtWebEngineCore::WebContentsAdapter *adapter() const;
+ const QWebEngineHistoryPrivate *history;
+};
+
+class QWebEngineBackHistoryModelPrivate : public QWebEngineHistoryModelPrivate
+{
+public:
+ QWebEngineBackHistoryModelPrivate(const QWebEngineHistoryPrivate *history)
+ : QWebEngineHistoryModelPrivate(history) { }
+
+ int count() const override;
+ int index(int) const override;
+ int offsetForIndex(int) const override;
+};
+
+class QWebEngineForwardHistoryModelPrivate : public QWebEngineHistoryModelPrivate
+{
+public:
+ QWebEngineForwardHistoryModelPrivate(const QWebEngineHistoryPrivate *history)
+ : QWebEngineHistoryModelPrivate(history) { }
+
+ int count() const override;
+ int index(int) const override;
+ int offsetForIndex(int) const override;
+};
+
+class Q_WEBENGINECORE_EXPORT QWebEngineHistoryPrivate
+{
+public:
+ typedef std::function<QUrl (const QUrl &)> ImageProviderUrl;
+ QWebEngineHistoryPrivate(QtWebEngineCore::WebContentsAdapterClient *client,
+ const ImageProviderUrl &imageProviderUrl = ImageProviderUrl());
+ ~QWebEngineHistoryPrivate();
+
+ void updateItems() const;
+ QtWebEngineCore::WebContentsAdapter *adapter() const;
+
+ QtWebEngineCore::WebContentsAdapterClient *client;
+
+ ImageProviderUrl imageProviderUrl;
+ QUrl urlOrImageProviderUrl(const QUrl &url) const { return imageProviderUrl ? imageProviderUrl(url) : url; }
+
+ mutable QList<QWebEngineHistoryItem> items;
+ mutable QScopedPointer<QWebEngineHistoryModel> navigationModel;
+ mutable QScopedPointer<QWebEngineHistoryModel> backNavigationModel;
+ mutable QScopedPointer<QWebEngineHistoryModel> forwardNavigationModel;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEHISTORY_P_H
diff --git a/src/core/api/qwebenginehttprequest.cpp b/src/core/api/qwebenginehttprequest.cpp
index 3395cc99f..050213d1e 100644
--- a/src/core/api/qwebenginehttprequest.cpp
+++ b/src/core/api/qwebenginehttprequest.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qplatformdefs.h"
#include <QtCore/qshareddata.h>
@@ -72,7 +36,7 @@ public:
QUrl url;
QWebEngineHttpRequest::Method method;
typedef QPair<QByteArray, QByteArray> HeaderPair;
- typedef QVector<HeaderPair> Headers;
+ typedef QList<HeaderPair> Headers;
Headers headers;
QByteArray postData;
@@ -96,7 +60,7 @@ public:
Headers::ConstIterator findHeader(const QByteArray &key) const;
Headers allHeaders() const;
- QVector<QByteArray> headersKeys() const;
+ QList<QByteArray> headersKeys() const;
void setHeader(const QByteArray &key, const QByteArray &value);
void unsetHeader(const QByteArray &key);
void setAllHeaders(const Headers &list);
@@ -182,16 +146,16 @@ QWebEngineHttpRequest QWebEngineHttpRequest::postRequest(const QUrl &url,
QWebEngineHttpRequest result(url);
result.setMethod(QWebEngineHttpRequest::Post);
- QString buffer;
+ QByteArray buffer;
for (QMap<QString, QString>::const_iterator it = postData.begin(); it != postData.end(); it++) {
QByteArray key = QUrl::toPercentEncoding(it.key());
QByteArray value = QUrl::toPercentEncoding(it.value());
- if (buffer.length() > 0)
- buffer += QLatin1Char('&');
- buffer += key + QLatin1Char('=') + value;
+ if (buffer.size() > 0)
+ buffer += '&';
+ buffer.append(key).append('=').append(value);
}
- result.setPostData(buffer.toLatin1());
+ result.setPostData(buffer);
result.setHeader(QByteArrayLiteral("Content-Type"),
QByteArrayLiteral("application/x-www-form-urlencoded"));
@@ -293,7 +257,7 @@ QByteArray QWebEngineHttpRequest::header(const QByteArray &headerName) const
\sa setHeader(), header(), hasHeader(), unsetHeader()
*/
-QVector<QByteArray> QWebEngineHttpRequest::headers() const
+QList<QByteArray> QWebEngineHttpRequest::headers() const
{
return d->headersKeys();
}
@@ -339,9 +303,9 @@ QWebEngineHttpRequestPrivate::Headers QWebEngineHttpRequestPrivate::allHeaders()
return headers;
}
-QVector<QByteArray> QWebEngineHttpRequestPrivate::headersKeys() const
+QList<QByteArray> QWebEngineHttpRequestPrivate::headersKeys() const
{
- QVector<QByteArray> result;
+ QList<QByteArray> result;
result.reserve(headers.size());
Headers::ConstIterator it = headers.constBegin(), end = headers.constEnd();
for (; it != end; ++it)
diff --git a/src/core/api/qwebenginehttprequest.h b/src/core/api/qwebenginehttprequest.h
index 1c4d7837b..6c0298f86 100644
--- a/src/core/api/qwebenginehttprequest.h
+++ b/src/core/api/qwebenginehttprequest.h
@@ -1,49 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEHTTPREQUEST_H
#define QWEBENGINEHTTPREQUEST_H
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-#include <QtCore/qshareddata.h>
-#include <QtCore/qvector.h>
+#include <QtCore/qlist.h>
#include <QtCore/qmap.h>
+#include <QtCore/qshareddata.h>
#include <QtCore/qstring.h>
#include <QtCore/qurl.h>
@@ -51,7 +15,8 @@ QT_BEGIN_NAMESPACE
class QWebEngineHttpRequestPrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineHttpRequest {
+class Q_WEBENGINECORE_EXPORT QWebEngineHttpRequest
+{
public:
enum Method {
Get,
@@ -72,7 +37,7 @@ public:
QWebEngineHttpRequest &operator=(const QWebEngineHttpRequest &other);
static QWebEngineHttpRequest postRequest(const QUrl &url, const QMap<QString, QString> &postData);
- void swap(QWebEngineHttpRequest &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
+ void swap(QWebEngineHttpRequest &other) noexcept { d.swap(other.d); }
bool operator==(const QWebEngineHttpRequest &other) const;
inline bool operator!=(const QWebEngineHttpRequest &other) const { return !operator==(other); }
@@ -87,14 +52,13 @@ public:
void setPostData(const QByteArray &postData);
bool hasHeader(const QByteArray &headerName) const;
- QVector<QByteArray> headers() const;
+ QList<QByteArray> headers() const;
QByteArray header(const QByteArray &headerName) const;
void setHeader(const QByteArray &headerName, const QByteArray &value);
void unsetHeader(const QByteArray &headerName);
private:
QSharedDataPointer<QWebEngineHttpRequestPrivate> d;
- friend class QWebEngineHttpRequestPrivate;
};
Q_DECLARE_SHARED(QWebEngineHttpRequest)
diff --git a/src/core/api/qwebengineloadinginfo.cpp b/src/core/api/qwebengineloadinginfo.cpp
new file mode 100644
index 000000000..a72117e9d
--- /dev/null
+++ b/src/core/api/qwebengineloadinginfo.cpp
@@ -0,0 +1,180 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include <qwebengineloadinginfo.h>
+
+#include <web_engine_error.h>
+
+QT_BEGIN_NAMESPACE
+
+using LoadStatus = QWebEngineLoadingInfo::LoadStatus;
+using ErrorDomain = QWebEngineLoadingInfo::ErrorDomain;
+
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::NoErrorDomain) == static_cast<int>(ErrorDomain::NoErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::InternalErrorDomain) == static_cast<int>(ErrorDomain::InternalErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::ConnectionErrorDomain) == static_cast<int>(ErrorDomain::ConnectionErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::CertificateErrorDomain) == static_cast<int>(ErrorDomain::CertificateErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::HttpErrorDomain) == static_cast<int>(ErrorDomain::HttpErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::FtpErrorDomain) == static_cast<int>(ErrorDomain::FtpErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::DnsErrorDomain) == static_cast<int>(ErrorDomain::DnsErrorDomain));
+Q_STATIC_ASSERT(static_cast<int>(WebEngineError::HttpStatusCodeDomain) == static_cast<int>(ErrorDomain::HttpStatusCodeDomain));
+
+class QWebEngineLoadingInfo::QWebEngineLoadingInfoPrivate : public QSharedData {
+public:
+ QWebEngineLoadingInfoPrivate(const QUrl& url, LoadStatus status, bool isErrorPage,
+ const QString& errorString, int errorCode, ErrorDomain errorDomain,
+ const QMultiMap<QByteArray,QByteArray>& responseHeaders)
+ : url(url)
+ , status(status)
+ , isErrorPage(isErrorPage)
+ , errorString(errorString)
+ , errorCode(errorCode)
+ , errorDomain(errorDomain)
+ , responseHeaders(responseHeaders)
+ {
+ }
+
+ QUrl url;
+ LoadStatus status;
+ bool isErrorPage;
+ QString errorString;
+ int errorCode;
+ ErrorDomain errorDomain;
+ QMultiMap<QByteArray,QByteArray> responseHeaders;
+};
+
+/*!
+ \class QWebEngineLoadingInfo
+ \brief A utility type for the WebEngineView::loadingChanged signal.
+ \inmodule QtWebEngineCore
+ \since 6.2
+
+ Contains information about a web page loading status change, such as the URL and
+ current loading status (started, succeeded, stopped, failed).
+
+ \sa QWebEnginePage::loadStarted, QWebEnginePage::loadFinished, WebEngineView::loadingChanged
+*/
+QWebEngineLoadingInfo::QWebEngineLoadingInfo(const QUrl& url, LoadStatus status, bool isErrorPage,
+ const QString& errorString, int errorCode, ErrorDomain errorDomain,
+ const QMultiMap<QByteArray,QByteArray>& responseHeaders)
+ : d_ptr(new QWebEngineLoadingInfoPrivate(url, status, isErrorPage, errorString, errorCode, errorDomain,
+ responseHeaders))
+{
+}
+
+QWebEngineLoadingInfo::QWebEngineLoadingInfo(const QWebEngineLoadingInfo &other) = default;
+QWebEngineLoadingInfo& QWebEngineLoadingInfo::operator=(const QWebEngineLoadingInfo &other) = default;
+QWebEngineLoadingInfo::QWebEngineLoadingInfo(QWebEngineLoadingInfo &&other) = default;
+QWebEngineLoadingInfo& QWebEngineLoadingInfo::operator=(QWebEngineLoadingInfo &&other) = default;
+
+QWebEngineLoadingInfo::~QWebEngineLoadingInfo()
+{
+}
+/*!
+ \property QWebEngineLoadingInfo::url
+ \brief Holds the URL of the load request.
+*/
+/*!
+ Returns the URL of the load request.
+*/
+QUrl QWebEngineLoadingInfo::url() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->url;
+}
+/*!
+ \enum QWebEngineLoadingInfo::LoadStatus
+
+ This enumeration represents the load status of a web page load request:
+
+ \value LoadStartedStatus Page is currently loading.
+ \value LoadStoppedStatus
+ Loading the page was stopped by the stop() method or by the loader
+ code or network stack in Chromium.
+ \value LoadSucceededStatus Page has been loaded with success.
+ \value LoadFailedStatus Page could not be loaded.
+*/
+/*!
+ \property QWebEngineLoadingInfo::status
+ \brief The load status of the page.
+*/
+LoadStatus QWebEngineLoadingInfo::status() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->status;
+}
+/*!
+ \property QWebEngineLoadingInfo::isErrorPage
+ \brief Indicates if the load resulted in an error page.
+*/
+bool QWebEngineLoadingInfo::isErrorPage() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->isErrorPage;
+}
+/*!
+ \property QWebEngineLoadingInfo::errorString
+ \brief Holds the error message.
+*/
+QString QWebEngineLoadingInfo::errorString() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->errorString;
+}
+/*!
+ \enum QWebEngineLoadingInfo::ErrorDomain
+ This enumeration holds the type of a load error:
+
+ \value NoErrorDomain
+ Error type is not known.
+ \value InternalErrorDomain
+ Content cannot be interpreted by \QWE.
+ \value ConnectionErrorDomain
+ Error results from a faulty network connection.
+ \value CertificateErrorDomain
+ Error is related to the SSL/TLS certificate.
+ \value HttpErrorDomain
+ Error is related to the HTTP connection.
+ \value FtpErrorDomain
+ Error is related to the FTP connection.
+ \value DnsErrorDomain
+ Error is related to the DNS connection.
+ \value HttpStatusCodeDomain
+ Error is the HTTP response status code, even in case of success e.g. the server replied with status 200.
+*/
+/*
+ \property QWebEngineLoadingInfo::errorDomain
+ \brief Holds the error domain.
+*/
+ErrorDomain QWebEngineLoadingInfo::errorDomain() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->errorDomain;
+}
+
+/*!
+ \property QWebEngineLoadingInfo::errorCode
+ \brief Holds the error code.
+*/
+int QWebEngineLoadingInfo::errorCode() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->errorCode;
+}
+
+/*!
+ \property QWebEngineLoadingInfo::responseHeaders
+ \since 6.6
+ \brief Holds the response headers when \c QWebEngineLoadingInfo::status()
+ is equal to \c QWebEngineLoadingInfo::LoadSucceededStatus or
+ \c QWebEngineLoadingInfo::LoadFailedStatus.
+*/
+QMultiMap<QByteArray,QByteArray> QWebEngineLoadingInfo::responseHeaders() const
+{
+ Q_D(const QWebEngineLoadingInfo);
+ return d->responseHeaders;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebengineloadinginfo.cpp"
diff --git a/src/core/api/qwebengineloadinginfo.h b/src/core/api/qwebengineloadinginfo.h
new file mode 100644
index 000000000..48d14601a
--- /dev/null
+++ b/src/core/api/qwebengineloadinginfo.h
@@ -0,0 +1,82 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINELOADINGINFO_H
+#define QWEBENGINELOADINGINFO_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qmap.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qshareddata.h>
+#include <QtCore/qurl.h>
+
+namespace QtWebEngineCore {
+class WebContentsAdapter;
+class WebContentsDelegateQt;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineLoadingInfo
+{
+ Q_GADGET
+ Q_PROPERTY(QUrl url READ url CONSTANT FINAL)
+ Q_PROPERTY(bool isErrorPage READ isErrorPage CONSTANT FINAL)
+ Q_PROPERTY(LoadStatus status READ status CONSTANT FINAL)
+ Q_PROPERTY(QString errorString READ errorString CONSTANT FINAL)
+ Q_PROPERTY(ErrorDomain errorDomain READ errorDomain CONSTANT FINAL)
+ Q_PROPERTY(int errorCode READ errorCode CONSTANT FINAL)
+ Q_PROPERTY(QMultiMap<QByteArray,QByteArray> responseHeaders READ responseHeaders CONSTANT REVISION(6,6) FINAL)
+
+public:
+ enum LoadStatus {
+ LoadStartedStatus,
+ LoadStoppedStatus,
+ LoadSucceededStatus,
+ LoadFailedStatus
+ };
+ Q_ENUM(LoadStatus)
+
+ enum ErrorDomain {
+ NoErrorDomain,
+ InternalErrorDomain,
+ ConnectionErrorDomain,
+ CertificateErrorDomain,
+ HttpErrorDomain,
+ FtpErrorDomain,
+ DnsErrorDomain,
+ HttpStatusCodeDomain
+ };
+ Q_ENUM(ErrorDomain)
+
+ QWebEngineLoadingInfo(const QWebEngineLoadingInfo &other);
+ QWebEngineLoadingInfo &operator=(const QWebEngineLoadingInfo &other);
+ QWebEngineLoadingInfo(QWebEngineLoadingInfo &&other);
+ QWebEngineLoadingInfo &operator=(QWebEngineLoadingInfo &&other);
+ ~QWebEngineLoadingInfo();
+
+ QUrl url() const;
+ bool isErrorPage() const;
+ LoadStatus status() const;
+ QString errorString() const;
+ ErrorDomain errorDomain() const;
+ int errorCode() const;
+ QMultiMap<QByteArray,QByteArray> responseHeaders() const;
+
+private:
+ QWebEngineLoadingInfo(const QUrl &url, LoadStatus status, bool isErrorPage = false,
+ const QString &errorString = QString(), int errorCode = 0,
+ ErrorDomain errorDomain = NoErrorDomain,
+ const QMultiMap<QByteArray,QByteArray> &responseHeaders = {});
+ class QWebEngineLoadingInfoPrivate;
+ Q_DECLARE_PRIVATE(QWebEngineLoadingInfo)
+ QExplicitlySharedDataPointer<QWebEngineLoadingInfoPrivate> d_ptr;
+ friend class QQuickWebEngineViewPrivate;
+ friend class QtWebEngineCore::WebContentsAdapter;
+ friend class QtWebEngineCore::WebContentsDelegateQt;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINELOADINGINFO_H
diff --git a/src/core/api/qwebenginemessagepumpscheduler.cpp b/src/core/api/qwebenginemessagepumpscheduler.cpp
index 34cbc49bf..a435e2c0c 100644
--- a/src/core/api/qwebenginemessagepumpscheduler.cpp
+++ b/src/core/api/qwebenginemessagepumpscheduler.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebenginemessagepumpscheduler_p.h"
@@ -47,9 +11,14 @@ QWebEngineMessagePumpScheduler::QWebEngineMessagePumpScheduler(std::function<voi
: m_callback(std::move(callback))
{}
-void QWebEngineMessagePumpScheduler::scheduleWork()
+void QWebEngineMessagePumpScheduler::scheduleImmediateWork()
{
- QCoreApplication::postEvent(this, new QTimerEvent(0));
+ QCoreApplication::postEvent(this, new QTimerEvent(0), Qt::NormalEventPriority);
+}
+
+void QWebEngineMessagePumpScheduler::scheduleIdleWork()
+{
+ QCoreApplication::postEvent(this, new QTimerEvent(0), Qt::LowEventPriority);
}
void QWebEngineMessagePumpScheduler::scheduleDelayedWork(int delay)
@@ -70,3 +39,5 @@ void QWebEngineMessagePumpScheduler::timerEvent(QTimerEvent *ev)
m_timerId = 0;
m_callback();
}
+
+#include "moc_qwebenginemessagepumpscheduler_p.cpp"
diff --git a/src/core/api/qwebenginemessagepumpscheduler_p.h b/src/core/api/qwebenginemessagepumpscheduler_p.h
index 07b2ca203..37f7dd9a6 100644
--- a/src/core/api/qwebenginemessagepumpscheduler_p.h
+++ b/src/core/api/qwebenginemessagepumpscheduler_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEMESSAGEPUMPSCHEDULER_P_H
#define QWEBENGINEMESSAGEPUMPSCHEDULER_P_H
@@ -59,11 +23,13 @@
QT_BEGIN_NAMESPACE
-class Q_WEBENGINECORE_PRIVATE_EXPORT QWebEngineMessagePumpScheduler : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineMessagePumpScheduler : public QObject
+{
Q_OBJECT
public:
QWebEngineMessagePumpScheduler(std::function<void()> callback);
- void scheduleWork();
+ void scheduleImmediateWork();
+ void scheduleIdleWork();
void scheduleDelayedWork(int delay);
protected:
diff --git a/src/core/api/qwebenginenavigationrequest.cpp b/src/core/api/qwebenginenavigationrequest.cpp
new file mode 100644
index 000000000..dc7447b88
--- /dev/null
+++ b/src/core/api/qwebenginenavigationrequest.cpp
@@ -0,0 +1,206 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginenavigationrequest.h"
+
+#include "qwebenginepage.h"
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineNavigationRequestPrivate {
+public:
+ QWebEngineNavigationRequestPrivate(const QUrl& url, QWebEngineNavigationRequest::NavigationType navigationType, bool mainFrame, bool formData)
+ : url(url)
+ , navigationType(navigationType)
+ , isMainFrame(mainFrame)
+ , hasFormData(formData)
+ {}
+
+ QUrl url;
+ QWebEngineNavigationRequest::NavigationType navigationType;
+ bool isMainFrame;
+ bool hasFormData;
+ bool isAccepted = true;
+};
+
+/*!
+ \class QWebEngineNavigationRequest
+ \brief A utility type for the QWebEnginePage::navigationRequested signal.
+ \since 6.2
+
+ \inmodule QtWebEngineCore
+
+ Contains information about a navigation request.
+
+ To accept or reject a request, call accept() or reject().
+
+ The default if not handled is to accept the navigation.
+
+ \sa QWebEnginePage::navigationRequested
+*/
+
+/*!
+ \qmltype WebEngineNavigationRequest
+ \instantiates QWebEngineNavigationRequest
+ \inqmlmodule QtWebEngine
+ \since QtWebEngine 1.0
+
+ \brief Represents a request for navigating to a web page as part of
+ \l{WebEngineView::navigationRequested()}.
+
+ To accept or reject a request, call accept() or reject().
+*/
+
+/*! \internal
+*/
+QWebEngineNavigationRequest::QWebEngineNavigationRequest(const QUrl& url, QWebEngineNavigationRequest::NavigationType navigationType, bool mainFrame, bool formData, QObject* parent)
+ : QObject(parent)
+ , d_ptr(new QWebEngineNavigationRequestPrivate(url, navigationType, mainFrame, formData))
+{
+}
+
+QWebEngineNavigationRequest::~QWebEngineNavigationRequest()
+{
+}
+
+#if QT_DEPRECATED_SINCE(6, 2)
+/*!
+ \qmlproperty enumeration WebEngineNavigationRequest::action
+
+ Whether to accept or ignore the navigation request.
+
+ \value WebEngineNavigationRequest.AcceptRequest
+ Accepts a navigation request.
+ \value WebEngineNavigationRequest.IgnoreRequest
+ Ignores a navigation request.
+*/
+QWebEngineNavigationRequest::NavigationRequestAction QWebEngineNavigationRequest::action() const
+{
+ qWarning("Navigation request: action/setAction are deprecated. Please, use accept/reject methods instead.");
+ Q_D(const QWebEngineNavigationRequest);
+ return d->isAccepted ? AcceptRequest : IgnoreRequest;
+}
+
+/*! \internal */
+void QWebEngineNavigationRequest::setAction(QWebEngineNavigationRequest::NavigationRequestAction action)
+{
+ qWarning("Navigation request: action/setAction are deprecated. Please, use accept/reject methods instead.");
+ Q_D(QWebEngineNavigationRequest);
+ bool acceptRequest = action == AcceptRequest;
+ if (d->isAccepted == acceptRequest)
+ return;
+
+ acceptRequest ? accept() : reject();
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
+ emit actionChanged();
+QT_WARNING_POP
+}
+#endif
+/*!
+ Accepts a navigation request.
+*/
+void QWebEngineNavigationRequest::accept()
+{
+ d_ptr->isAccepted = true;
+}
+/*!
+ Rejects a navigation request.
+*/
+void QWebEngineNavigationRequest::reject()
+{
+ d_ptr->isAccepted = false;
+}
+/*!
+ \property QWebEngineNavigationRequest::url
+ \brief The URL of the web page to go to.
+*/
+/*!
+ \qmlproperty url WebEngineNavigationRequest::url
+ \readonly
+
+ The URL of the web page to go to.
+*/
+
+QUrl QWebEngineNavigationRequest::url() const
+{
+ Q_D(const QWebEngineNavigationRequest);
+ return d->url;
+}
+/*!
+ \property QWebEngineNavigationRequest::navigationType
+ \brief The method used to navigate to a web page.
+*/
+/*!
+ \qmlproperty enumeration WebEngineNavigationRequest::navigationType
+ \readonly
+
+ The method used to navigate to a web page.
+
+ \value WebEngineNavigationRequest.LinkClickedNavigation
+ Clicking a link.
+ \value WebEngineNavigationRequest.TypedNavigation
+ Entering an URL on the address bar.
+ \value WebEngineNavigationRequest.FormSubmittedNavigation
+ Submitting a form.
+ \value WebEngineNavigationRequest.BackForwardNavigation
+ Using navigation history to go to the previous or next page.
+ \value WebEngineNavigationRequest.ReloadNavigation
+ Reloading the page.
+ \value WebEngineNavigationRequest.RedirectNavigation
+ Page content or server triggered a redirection or page refresh.
+ \value WebEngineNavigationRequest.OtherNavigation
+ Using some other method to go to a page.
+*/
+
+QWebEngineNavigationRequest::NavigationType QWebEngineNavigationRequest::navigationType() const
+{
+ Q_D(const QWebEngineNavigationRequest);
+ return d->navigationType;
+}
+
+/*!
+ \property QWebEngineNavigationRequest::isMainFrame
+ \brief Whether the navigation issue is requested for a top level page.
+*/
+/*!
+ \qmlproperty bool WebEngineNavigationRequest::isMainFrame
+ \readonly
+
+ Whether the navigation issue is requested for a top level page.
+*/
+
+bool QWebEngineNavigationRequest::isMainFrame() const
+{
+ Q_D(const QWebEngineNavigationRequest);
+ return d->isMainFrame;
+}
+
+/*!
+ \property QWebEngineNavigationRequest::hasFormData
+ \brief Whether the navigation request contains form data
+ \since 6.8
+*/
+/*!
+ \qmlproperty bool WebEngineNavigationRequest::hasFormData
+ \since 6.8
+ \readonly
+
+ Whether the navigation request contains form data
+*/
+
+bool QWebEngineNavigationRequest::hasFormData() const
+{
+ Q_D(const QWebEngineNavigationRequest);
+ return d->hasFormData;
+}
+
+/*! \internal */
+bool QWebEngineNavigationRequest::isAccepted() const
+{
+ return d_ptr->isAccepted;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginenavigationrequest.cpp"
diff --git a/src/core/api/qwebenginenavigationrequest.h b/src/core/api/qwebenginenavigationrequest.h
new file mode 100644
index 000000000..a810a59fe
--- /dev/null
+++ b/src/core/api/qwebenginenavigationrequest.h
@@ -0,0 +1,78 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINENAVIGATIONREQUEST_H
+#define QWEBENGINENAVIGATIONREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qurl.h>
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineNavigationRequestPrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineNavigationRequest : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QUrl url READ url CONSTANT FINAL)
+ Q_PROPERTY(bool isMainFrame READ isMainFrame CONSTANT FINAL)
+ Q_PROPERTY(bool hasFormData READ hasFormData CONSTANT REVISION(6, 8) FINAL)
+ Q_PROPERTY(NavigationType navigationType READ navigationType CONSTANT FINAL)
+
+public:
+ ~QWebEngineNavigationRequest();
+
+ // must match WebContentsAdapterClient::NavigationType
+ enum NavigationType {
+ LinkClickedNavigation,
+ TypedNavigation,
+ FormSubmittedNavigation,
+ BackForwardNavigation,
+ ReloadNavigation,
+ OtherNavigation,
+ RedirectNavigation,
+ };
+ Q_ENUM(NavigationType)
+
+ QUrl url() const;
+ bool isMainFrame() const;
+ bool hasFormData() const;
+ NavigationType navigationType() const;
+
+ Q_INVOKABLE void accept();
+ Q_INVOKABLE void reject();
+
+#if QT_DEPRECATED_SINCE(6, 2)
+ enum NavigationRequestAction {
+ AcceptRequest,
+ IgnoreRequest = 0xFF
+ };
+ Q_ENUM(NavigationRequestAction)
+
+private:
+ Q_PROPERTY(NavigationRequestAction action READ action WRITE setAction NOTIFY actionChanged FINAL)
+
+ QT_DEPRECATED NavigationRequestAction action() const;
+ QT_DEPRECATED_X("Use accept/reject methods to handle the request")
+ void setAction(NavigationRequestAction action);
+
+Q_SIGNALS:
+ QT_DEPRECATED void actionChanged();
+#endif
+
+private:
+ QWebEngineNavigationRequest(const QUrl &url, NavigationType navigationType, bool mainFrame, bool formData,
+ QObject *parent = nullptr);
+
+ friend class QWebEnginePagePrivate;
+ friend class QQuickWebEngineViewPrivate;
+ bool isAccepted() const;
+
+ Q_DECLARE_PRIVATE(QWebEngineNavigationRequest)
+ QScopedPointer<QWebEngineNavigationRequestPrivate> d_ptr;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINENAVIGATIONREQUEST_H
diff --git a/src/core/api/qwebenginenewwindowrequest.cpp b/src/core/api/qwebenginenewwindowrequest.cpp
new file mode 100644
index 000000000..895033fd1
--- /dev/null
+++ b/src/core/api/qwebenginenewwindowrequest.cpp
@@ -0,0 +1,157 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginenewwindowrequest.h"
+#include "qwebenginenewwindowrequest_p.h"
+
+#include "qwebenginepage.h"
+
+#include "web_contents_adapter.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineNewWindowRequest
+ \brief A utility type for the QWebEnginePage::newWindowRequested() signal.
+ \since 6.2
+
+ \inmodule QtWebEngineCore
+
+ Contains information about a request to load a page in a separate web engine view.
+
+ \sa QWebEnginePage::newWindowRequested()
+*/
+
+/*!
+ \qmltype WebEngineNewWindowRequest
+ \instantiates QWebEngineNewWindowRequest
+ \inqmlmodule QtWebEngine
+ \since QtWebEngine 1.12
+
+ \brief A utility type for the WebEngineView::newWindowRequested signal.
+
+ Contains information about a request to load a page in a separate web engine view.
+
+ \sa WebEngineView::newWindowRequested
+*/
+
+/*!
+ \enum QWebEngineNewWindowRequest::DestinationType
+
+ This enum describes the type of window requested:
+
+ \value InNewWindow
+ In a separate window.
+ \value InNewTab
+ In a tab of the same window.
+ \value InNewDialog
+ In a window without a tab bar, toolbar, or URL bar.
+ \value InNewBackgroundTab
+ In a tab of the same window, without hiding the currently visible web engine view.
+*/
+
+/*!
+ \qmlproperty enumeration WebEngineNewWindowRequest::DestinationType
+
+ Describes how to open a new view:
+
+ \value WebEngineNewWindowRequest.InNewWindow
+ In a separate window.
+ \value WebEngineNewWindowRequest.InNewTab
+ In a tab of the same window.
+ \value WebEngineNewWindowRequest.InNewDialog
+ In a window without a tab bar, toolbar, or URL bar.
+ \value WebEngineNewWindowRequest.InNewBackgroundTab
+ In a tab of the same window, without hiding the currently visible web engine view.
+*/
+
+QWebEngineNewWindowRequest::QWebEngineNewWindowRequest(QWebEngineNewWindowRequest::DestinationType destination,
+ const QRect &geometry,
+ const QUrl &url,
+ bool userInitiated,
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter> adapter,
+ QObject *parent)
+ : QObject(parent)
+ , d_ptr(new QWebEngineNewWindowRequestPrivate{destination, geometry, url, adapter, userInitiated})
+{
+}
+
+QWebEngineNewWindowRequest::~QWebEngineNewWindowRequest()
+{
+}
+
+/*!
+ \property QWebEngineNewWindowRequest::destination
+ \brief The type of window that is requested.
+*/
+/*!
+ \qmlproperty WebEngineNewWindowRequest::DestinationType WebEngineNewWindowRequest::destination
+ \brief The type of window that is requested.
+*/
+QWebEngineNewWindowRequest::DestinationType QWebEngineNewWindowRequest::destination() const
+{
+ return d_ptr->destination;
+}
+
+/*!
+ \property QWebEngineNewWindowRequest::requestedUrl
+ \brief The URL that is requested for the new page.
+*/
+/*!
+ \qmlproperty QUrl WebEngineNewWindowRequest::requestedUrl
+ \brief The URL that is requested for the new page.
+ \since QtWebEngine 1.5
+ */
+QUrl QWebEngineNewWindowRequest::requestedUrl() const
+{
+ return d_ptr->requestedUrl;
+}
+
+/*!
+ \property QWebEngineNewWindowRequest::requestedGeometry
+ \brief The size that is requested for the new page.
+*/
+/*!
+ \qmlproperty QRect WebEngineNewWindowRequest::requestedGeometry
+ \brief The size that is requested for the new page.
+ \since QtWebEngine 2.0
+ */
+QRect QWebEngineNewWindowRequest::requestedGeometry() const
+{
+ return d_ptr->requestedGeometry;
+}
+
+/*!
+ \property QWebEngineNewWindowRequest::userInitiated
+ Whether this page request was directly triggered as the result of a keyboard or mouse event.
+
+ You can use this property to block automatic \e popups.
+*/
+/*!
+ \qmlproperty bool WebEngineNewWindowRequest::userInitiated
+ Whether this window request was directly triggered as the result of a keyboard or mouse event.
+
+ You can use this property to block automatic \e popups.
+ */
+bool QWebEngineNewWindowRequest::isUserInitiated() const
+{
+ return d_ptr->isUserInitiated;
+}
+
+/*!
+ Opens the requested window in the view represented by \a page.
+
+ \sa QWebEnginePage::newWindowRequested
+*/
+void QWebEngineNewWindowRequest::openIn(QWebEnginePage *page)
+{
+ if (!page) {
+ qWarning("Trying to open a QWebEngineNewWindowRequest in an invalid QWebEnginePage.");
+ return;
+ }
+ page->acceptAsNewWindow(*this);
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginenewwindowrequest.cpp"
diff --git a/src/core/api/qwebenginenewwindowrequest.h b/src/core/api/qwebenginenewwindowrequest.h
new file mode 100644
index 000000000..86d182581
--- /dev/null
+++ b/src/core/api/qwebenginenewwindowrequest.h
@@ -0,0 +1,62 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINENEWWINDOWREQUEST_H
+#define QWEBENGINENEWWINDOWREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qrect.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtCore/qsharedpointer.h>
+#include <QtCore/qurl.h>
+
+namespace QtWebEngineCore {
+class WebContentsAdapter;
+}
+
+QT_BEGIN_NAMESPACE
+
+class QWebEnginePage;
+struct QWebEngineNewWindowRequestPrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineNewWindowRequest : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(DestinationType destination READ destination CONSTANT FINAL)
+ Q_PROPERTY(QUrl requestedUrl READ requestedUrl CONSTANT FINAL)
+ Q_PROPERTY(QRect requestedGeometry READ requestedGeometry CONSTANT FINAL)
+ Q_PROPERTY(bool userInitiated READ isUserInitiated CONSTANT FINAL)
+public:
+ ~QWebEngineNewWindowRequest();
+
+ enum DestinationType {
+ InNewWindow,
+ InNewTab,
+ InNewDialog,
+ InNewBackgroundTab
+ };
+ Q_ENUM(DestinationType)
+
+ DestinationType destination() const;
+ QUrl requestedUrl() const;
+ QRect requestedGeometry() const;
+ bool isUserInitiated() const;
+
+ void openIn(QWebEnginePage *);
+
+protected:
+ QWebEngineNewWindowRequest(DestinationType, const QRect &, const QUrl &, bool,
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter>,
+ QObject * = nullptr);
+
+ QScopedPointer<QWebEngineNewWindowRequestPrivate> d_ptr;
+ friend class QWebEnginePage;
+ friend class QWebEnginePagePrivate;
+ friend class QQuickWebEngineView;
+ friend class QQuickWebEngineViewPrivate;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINENEWWINDOWREQUEST_H
diff --git a/src/core/api/qwebenginenewwindowrequest_p.h b/src/core/api/qwebenginenewwindowrequest_p.h
new file mode 100644
index 000000000..979d3fe2d
--- /dev/null
+++ b/src/core/api/qwebenginenewwindowrequest_p.h
@@ -0,0 +1,48 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINENEWWINDOWREQUEST_P_H
+#define QWEBENGINENEWWINDOWREQUEST_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qwebenginenewwindowrequest.h"
+
+#include <QtCore/QRect>
+#include <QtCore/QSharedPointer>
+#include <QtCore/QUrl>
+
+namespace QtWebEngineCore {
+class WebContentsAdapter;
+}
+
+QT_BEGIN_NAMESPACE
+
+struct QWebEngineNewWindowRequestPrivate
+{
+ void setHandled()
+ {
+ isRequestHandled = true;
+ adapter.reset();
+ }
+
+ QWebEngineNewWindowRequest::DestinationType destination;
+ QRect requestedGeometry;
+ QUrl requestedUrl;
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter> adapter;
+ bool isUserInitiated;
+ bool isRequestHandled = false;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINENEWWINDOWREQUEST_P_H
diff --git a/src/core/api/qwebenginenotification.cpp b/src/core/api/qwebenginenotification.cpp
index 0505b825a..136047042 100644
--- a/src/core/api/qwebenginenotification.cpp
+++ b/src/core/api/qwebenginenotification.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebenginenotification.h"
@@ -90,7 +54,7 @@ public:
~QWebEngineNotificationPrivate() override
{
if (controller->client() == this)
- controller->setClient(0);
+ controller->setClient(nullptr);
}
// UserNotificationController::Client:
diff --git a/src/core/api/qwebenginenotification.h b/src/core/api/qwebenginenotification.h
index 08fd629be..646413d39 100644
--- a/src/core/api/qwebenginenotification.h
+++ b/src/core/api/qwebenginenotification.h
@@ -1,51 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINENOTIFICATION_H
#define QWEBENGINENOTIFICATION_H
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-#include <QtCore/QObject>
-#include <QtCore/QScopedPointer>
-#include <QtCore/QSharedPointer>
-#include <QtCore/QUrl>
+#include <QtCore/qobject.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtCore/qsharedpointer.h>
+#include <QtCore/qurl.h>
namespace QtWebEngineCore {
class UserNotificationController;
@@ -55,7 +19,8 @@ QT_BEGIN_NAMESPACE
class QWebEngineNotificationPrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineNotification : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineNotification : public QObject
+{
Q_OBJECT
Q_PROPERTY(QUrl origin READ origin CONSTANT FINAL)
Q_PROPERTY(QString title READ title CONSTANT FINAL)
diff --git a/src/core/api/qwebenginepage.cpp b/src/core/api/qwebenginepage.cpp
new file mode 100644
index 000000000..c2a737d72
--- /dev/null
+++ b/src/core/api/qwebenginepage.cpp
@@ -0,0 +1,2548 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginepage.h"
+#include "authenticator_request_dialog_controller.h"
+#include "qwebenginepage_p.h"
+
+#include "qwebenginecertificateerror.h"
+#include "qwebenginedesktopmediarequest.h"
+#include "qwebenginefilesystemaccessrequest.h"
+#include "qwebenginefindtextresult.h"
+#include "qwebenginefullscreenrequest.h"
+#include "qwebenginehistory.h"
+#include "qwebenginehistory_p.h"
+#include "qwebenginehttprequest.h"
+#include "qwebengineloadinginfo.h"
+#include "qwebenginenavigationrequest.h"
+#include "qwebenginenewwindowrequest.h"
+#include "qwebenginenewwindowrequest_p.h"
+#include "qwebengineprofile.h"
+#include "qwebengineprofile_p.h"
+#include "qwebengineregisterprotocolhandlerrequest.h"
+#include "qwebenginescript.h"
+#include "qwebenginescriptcollection_p.h"
+#include "qwebenginesettings.h"
+#include "qwebenginewebauthuxrequest.h"
+
+#include "authentication_dialog_controller.h"
+#include "autofill_popup_controller.h"
+#include "color_chooser_controller.h"
+#include "find_text_helper.h"
+#include "file_picker_controller.h"
+#include "javascript_dialog_controller.h"
+#include "profile_adapter.h"
+#include "render_view_context_menu_qt.h"
+#include "render_widget_host_view_qt_delegate.h"
+#include "render_widget_host_view_qt_delegate_client.h"
+#include "render_widget_host_view_qt_delegate_item.h"
+#include "touch_selection_menu_controller.h"
+#include "web_contents_adapter.h"
+
+#include <QAction>
+#include <QGuiApplication>
+#include <QAuthenticator>
+#include <QClipboard>
+#include <QKeyEvent>
+#include <QIcon>
+
+#include <QLoggingCategory>
+#include <QMimeData>
+#include <QtCore/QPointer>
+#include <QRect>
+#include <QTimer>
+#include <QUrl>
+#include <QVariant>
+
+QT_BEGIN_NAMESPACE
+
+using namespace QtWebEngineCore;
+
+static QWebEnginePage::WebWindowType toWindowType(WebContentsAdapterClient::WindowOpenDisposition disposition)
+{
+ switch (disposition) {
+ case WebContentsAdapterClient::NewForegroundTabDisposition:
+ return QWebEnginePage::WebBrowserTab;
+ case WebContentsAdapterClient::NewBackgroundTabDisposition:
+ return QWebEnginePage::WebBrowserBackgroundTab;
+ case WebContentsAdapterClient::NewPopupDisposition:
+ return QWebEnginePage::WebDialog;
+ case WebContentsAdapterClient::NewWindowDisposition:
+ return QWebEnginePage::WebBrowserWindow;
+ default:
+ Q_UNREACHABLE();
+ }
+}
+
+static QWebEngineNewWindowRequest::DestinationType toDestinationType(WebContentsAdapterClient::WindowOpenDisposition disposition)
+{
+ switch (disposition) {
+ case WebContentsAdapterClient::NewForegroundTabDisposition:
+ return QWebEngineNewWindowRequest::InNewTab;
+ case WebContentsAdapterClient::NewBackgroundTabDisposition:
+ return QWebEngineNewWindowRequest::InNewBackgroundTab;
+ case WebContentsAdapterClient::NewPopupDisposition:
+ return QWebEngineNewWindowRequest::InNewDialog;
+ case WebContentsAdapterClient::NewWindowDisposition:
+ return QWebEngineNewWindowRequest::InNewWindow;
+ default:
+ Q_UNREACHABLE();
+ }
+}
+
+QWebEnginePagePrivate::QWebEnginePagePrivate(QWebEngineProfile *_profile)
+ : adapter(QSharedPointer<WebContentsAdapter>::create())
+ , history(new QWebEngineHistory(new QWebEngineHistoryPrivate(this)))
+ , profile(_profile ? _profile : QWebEngineProfile::defaultProfile())
+ , settings(new QWebEngineSettings(profile->settings()))
+ , view(nullptr)
+ , isLoading(false)
+ , scriptCollection(new QWebEngineScriptCollectionPrivate(profileAdapter()->userResourceController(), adapter))
+ , m_isBeingAdopted(false)
+ , m_backgroundColor(Qt::white)
+ , fullscreenMode(false)
+ , webChannel(nullptr)
+ , webChannelWorldId(QWebEngineScript::MainWorld)
+ , defaultAudioMuted(false)
+ , defaultZoomFactor(1.0)
+{
+ memset(actions, 0, sizeof(actions));
+
+#if QT_DEPRECATED_SINCE(6, 5)
+ qRegisterMetaType<QWebEngineQuotaRequest>();
+#endif
+ qRegisterMetaType<QWebEngineRegisterProtocolHandlerRequest>();
+ qRegisterMetaType<QWebEngineFileSystemAccessRequest>();
+ qRegisterMetaType<QWebEngineFindTextResult>();
+
+ // See setVisible().
+ wasShownTimer.setSingleShot(true);
+ QObject::connect(&wasShownTimer, &QTimer::timeout, [this](){
+ ensureInitialized();
+ });
+
+ profile->d_ptr->addWebContentsAdapterClient(this);
+}
+
+QWebEnginePagePrivate::~QWebEnginePagePrivate()
+{
+ delete history;
+ delete settings;
+ profile->d_ptr->removeWebContentsAdapterClient(this);
+}
+
+RenderWidgetHostViewQtDelegate *QWebEnginePagePrivate::CreateRenderWidgetHostViewQtDelegate(RenderWidgetHostViewQtDelegateClient *client)
+{
+ if (view)
+ return view->CreateRenderWidgetHostViewQtDelegate(client);
+ delegateItem = new QtWebEngineCore::RenderWidgetHostViewQtDelegateItem(client, false);
+ return delegateItem;
+}
+
+RenderWidgetHostViewQtDelegate *QWebEnginePagePrivate::CreateRenderWidgetHostViewQtDelegateForPopup(RenderWidgetHostViewQtDelegateClient *client)
+{
+ // Set the QWebEngineView as the parent for a popup delegate, so that the new popup window
+ // responds properly to clicks in case the QWebEngineView is inside a modal QDialog. Setting the
+ // parent essentially notifies the OS that the popup window is part of the modal session, and
+ // should allow interaction.
+ // The new delegate will not be deleted by the parent view though, because we unset the parent
+ // when the parent is destroyed. The delegate will be destroyed by Chromium when the popup is
+ // dismissed.
+ return view
+ ? view->CreateRenderWidgetHostViewQtDelegateForPopup(client)
+ : new QtWebEngineCore::RenderWidgetHostViewQtDelegateItem(client, true);
+}
+
+void QWebEnginePagePrivate::initializationFinished()
+{
+ if (m_backgroundColor != Qt::white)
+ adapter->setBackgroundColor(m_backgroundColor);
+#if QT_CONFIG(webengine_webchannel)
+ if (webChannel)
+ adapter->setWebChannel(webChannel, webChannelWorldId);
+#endif
+ if (defaultAudioMuted != adapter->isAudioMuted())
+ adapter->setAudioMuted(defaultAudioMuted);
+ if (!qFuzzyCompare(adapter->currentZoomFactor(), defaultZoomFactor))
+ adapter->setZoomFactor(defaultZoomFactor);
+ if (view)
+ adapter->setVisible(view->isVisible());
+
+ scriptCollection.d->initializationFinished(adapter);
+
+ m_isBeingAdopted = false;
+}
+
+void QWebEnginePagePrivate::titleChanged(const QString &title)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->titleChanged(title);
+}
+
+void QWebEnginePagePrivate::urlChanged()
+{
+ Q_Q(QWebEnginePage);
+ QUrl qurl = adapter->activeUrl();
+ if (url != qurl) {
+ url = qurl;
+ Q_EMIT q->urlChanged(qurl);
+ }
+}
+
+void QWebEnginePagePrivate::iconChanged(const QUrl &url)
+{
+ Q_Q(QWebEnginePage);
+ if (iconUrl == url)
+ return;
+ iconUrl = url;
+ Q_EMIT q->iconUrlChanged(iconUrl);
+ Q_EMIT q->iconChanged(iconUrl.isEmpty() ? QIcon() : adapter->icon());
+}
+
+void QWebEnginePagePrivate::loadProgressChanged(int progress)
+{
+ Q_Q(QWebEnginePage);
+ QTimer::singleShot(0, q, [q, progress] () { Q_EMIT q->loadProgress(progress); });
+}
+
+void QWebEnginePagePrivate::didUpdateTargetURL(const QUrl &hoveredUrl)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->linkHovered(hoveredUrl.toString());
+}
+
+void QWebEnginePagePrivate::selectionChanged()
+{
+ Q_Q(QWebEnginePage);
+ QTimer::singleShot(0, q, [this, q]() {
+ updateEditActions();
+ Q_EMIT q->selectionChanged();
+ });
+}
+
+void QWebEnginePagePrivate::zoomUpdateIsNeeded()
+{
+ Q_Q(QWebEnginePage);
+ q->setZoomFactor(defaultZoomFactor);
+}
+
+void QWebEnginePagePrivate::recentlyAudibleChanged(bool recentlyAudible)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->recentlyAudibleChanged(recentlyAudible);
+}
+
+void QWebEnginePagePrivate::renderProcessPidChanged(qint64 pid)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->renderProcessPidChanged(pid);
+}
+
+QRectF QWebEnginePagePrivate::viewportRect() const
+{
+ return view ? view->viewportRect() : QRectF();
+}
+
+QColor QWebEnginePagePrivate::backgroundColor() const
+{
+ return m_backgroundColor;
+}
+
+void QWebEnginePagePrivate::loadStarted(QWebEngineLoadingInfo info)
+{
+ Q_Q(QWebEnginePage);
+ isLoading = true;
+ QTimer::singleShot(0, q, [q, info = std::move(info)] () {
+ Q_EMIT q->loadStarted();
+ Q_EMIT q->loadingChanged(info);
+ });
+}
+
+void QWebEnginePagePrivate::loadFinished(QWebEngineLoadingInfo info)
+{
+ Q_Q(QWebEnginePage);
+ isLoading = false;
+ QTimer::singleShot(0, q, [q, info = std::move(info)] () {
+ Q_EMIT q->loadFinished(info.status() == QWebEngineLoadingInfo::LoadSucceededStatus);
+ Q_EMIT q->loadingChanged(info);
+ });
+}
+
+void QWebEnginePagePrivate::didPrintPageToPdf(const QString &filePath, bool success)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->pdfPrintingFinished(filePath, success);
+ if (view)
+ view->didPrintPageToPdf(filePath, success);
+}
+
+void QWebEnginePagePrivate::focusContainer()
+{
+ if (view) {
+ view->focusContainer();
+ }
+}
+
+void QWebEnginePagePrivate::unhandledKeyEvent(QKeyEvent *event)
+{
+ if (view) {
+ view->unhandledKeyEvent(event);
+ }
+}
+
+QSharedPointer<WebContentsAdapter>
+QWebEnginePagePrivate::adoptNewWindow(QSharedPointer<WebContentsAdapter> newWebContents,
+ WindowOpenDisposition disposition, bool userGesture,
+ const QRect &initialGeometry, const QUrl &targetUrl)
+{
+ Q_Q(QWebEnginePage);
+ Q_ASSERT(newWebContents);
+ QWebEnginePage *newPage = q->createWindow(toWindowType(disposition));
+ if (newPage) {
+ if (!newWebContents->webContents())
+ return newPage->d_func()->adapter; // Reuse existing adapter
+
+ if (!newPage->d_func()->adoptWebContents(newWebContents.get()))
+ return nullptr;
+
+ if (!initialGeometry.isEmpty())
+ emit newPage->geometryChangeRequested(initialGeometry);
+
+ return newWebContents;
+ }
+
+ QWebEngineNewWindowRequest request(toDestinationType(disposition), initialGeometry,
+ targetUrl, userGesture, newWebContents);
+
+ Q_EMIT q->newWindowRequested(request);
+
+ if (request.d_ptr->isRequestHandled)
+ return newWebContents;
+ return nullptr;
+}
+
+void QWebEnginePagePrivate::createNewWindow(WindowOpenDisposition disposition, bool userGesture, const QUrl &targetUrl)
+{
+ Q_Q(QWebEnginePage);
+ QWebEnginePage *newPage = q->createWindow(toWindowType(disposition));
+ if (newPage) {
+ newPage->setUrl(targetUrl);
+ return;
+ }
+
+ QWebEngineNewWindowRequest request(toDestinationType(disposition), QRect(),
+ targetUrl, userGesture, nullptr);
+
+ Q_EMIT q->newWindowRequested(request);
+}
+
+QString QWebEnginePagePrivate::actionText(int action)
+{
+ switch (action) {
+ case QWebEnginePage::Back:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Back);
+ case QWebEnginePage::Forward:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Forward);
+ case QWebEnginePage::Stop:
+ return QWebEnginePage::tr("Stop");
+ case QWebEnginePage::Reload:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Reload);
+ case QWebEnginePage::ReloadAndBypassCache:
+ return QWebEnginePage::tr("Reload and Bypass Cache");
+ case QWebEnginePage::Cut:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Cut);
+ case QWebEnginePage::Copy:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Copy);
+ case QWebEnginePage::Paste:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Paste);
+ case QWebEnginePage::Undo:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Undo);
+ case QWebEnginePage::Redo:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::Redo);
+ case QWebEnginePage::SelectAll:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::SelectAll);
+ case QWebEnginePage::PasteAndMatchStyle:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::PasteAndMatchStyle);
+ case QWebEnginePage::OpenLinkInThisWindow:
+ return QWebEnginePage::tr("Open link in this window");
+ case QWebEnginePage::OpenLinkInNewWindow:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::OpenLinkInNewWindow);
+ case QWebEnginePage::OpenLinkInNewTab:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::OpenLinkInNewTab);
+ case QWebEnginePage::OpenLinkInNewBackgroundTab:
+ return QWebEnginePage::tr("Open link in new background tab");
+ case QWebEnginePage::CopyLinkToClipboard:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::CopyLinkToClipboard);
+ case QWebEnginePage::DownloadLinkToDisk:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::DownloadLinkToDisk);
+ case QWebEnginePage::CopyImageToClipboard:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::CopyImageToClipboard);
+ case QWebEnginePage::CopyImageUrlToClipboard:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::CopyImageUrlToClipboard);
+ case QWebEnginePage::DownloadImageToDisk:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::DownloadImageToDisk);
+ case QWebEnginePage::CopyMediaUrlToClipboard:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::CopyMediaUrlToClipboard);
+ case QWebEnginePage::ToggleMediaControls:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::ToggleMediaControls);
+ case QWebEnginePage::ToggleMediaLoop:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::ToggleMediaLoop);
+ case QWebEnginePage::ToggleMediaPlayPause:
+ return QWebEnginePage::tr("Toggle Play/Pause");
+ case QWebEnginePage::ToggleMediaMute:
+ return QWebEnginePage::tr("Toggle Mute");
+ case QWebEnginePage::DownloadMediaToDisk:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::DownloadMediaToDisk);
+ case QWebEnginePage::InspectElement:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::InspectElement);
+ case QWebEnginePage::ExitFullScreen:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::ExitFullScreen);
+ case QWebEnginePage::RequestClose:
+ return QWebEnginePage::tr("Close Page");
+ case QWebEnginePage::Unselect:
+ return QWebEnginePage::tr("Unselect");
+ case QWebEnginePage::SavePage:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::SavePage);
+ case QWebEnginePage::ViewSource:
+ return RenderViewContextMenuQt::getMenuItemName(RenderViewContextMenuQt::ContextMenuItem::ViewSource);
+ case QWebEnginePage::ToggleBold:
+ return QWebEnginePage::tr("&Bold");
+ case QWebEnginePage::ToggleItalic:
+ return QWebEnginePage::tr("&Italic");
+ case QWebEnginePage::ToggleUnderline:
+ return QWebEnginePage::tr("&Underline");
+ case QWebEnginePage::ToggleStrikethrough:
+ return QWebEnginePage::tr("&Strikethrough");
+ case QWebEnginePage::AlignLeft:
+ return QWebEnginePage::tr("Align &Left");
+ case QWebEnginePage::AlignCenter:
+ return QWebEnginePage::tr("Align &Center");
+ case QWebEnginePage::AlignRight:
+ return QWebEnginePage::tr("Align &Right");
+ case QWebEnginePage::AlignJustified:
+ return QWebEnginePage::tr("Align &Justified");
+ case QWebEnginePage::Indent:
+ return QWebEnginePage::tr("&Indent");
+ case QWebEnginePage::Outdent:
+ return QWebEnginePage::tr("&Outdent");
+ case QWebEnginePage::InsertOrderedList:
+ return QWebEnginePage::tr("Insert &Ordered List");
+ case QWebEnginePage::InsertUnorderedList:
+ return QWebEnginePage::tr("Insert &Unordered List");
+ case QWebEnginePage::ChangeTextDirectionLTR:
+ return QWebEnginePage::tr("Change text direction left to right");
+ case QWebEnginePage::ChangeTextDirectionRTL:
+ return QWebEnginePage::tr("Change text direction right to left");
+ default:
+ break;
+ }
+ return {};
+}
+
+class WebContentsAdapterOwner : public QObject
+{
+public:
+ typedef QSharedPointer<QtWebEngineCore::WebContentsAdapter> AdapterPtr;
+ WebContentsAdapterOwner(const AdapterPtr &ptr)
+ : adapter(ptr)
+ {}
+
+private:
+ AdapterPtr adapter;
+};
+
+bool QWebEnginePagePrivate::adoptWebContents(WebContentsAdapter *webContents)
+{
+ Q_ASSERT(webContents);
+ if (webContents->profileAdapter() && profileAdapter() != webContents->profileAdapter()) {
+ qWarning("Can not adopt content from a different WebEngineProfile.");
+ return false;
+ }
+
+ m_isBeingAdopted = true;
+
+ webContents->setRequestInterceptor(adapter->requestInterceptor());
+
+ // This throws away the WebContentsAdapter that has been used until now.
+ // All its states, particularly the loading URL, are replaced by the adopted WebContentsAdapter.
+ WebContentsAdapterOwner *adapterOwner = new WebContentsAdapterOwner(adapter->sharedFromThis());
+ adapterOwner->deleteLater();
+
+ adapter = webContents->sharedFromThis();
+ adapter->setClient(this);
+ return true;
+}
+
+bool QWebEnginePagePrivate::isBeingAdopted()
+{
+ return m_isBeingAdopted;
+}
+
+void QWebEnginePagePrivate::close()
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->windowCloseRequested();
+}
+
+void QWebEnginePagePrivate::windowCloseRejected()
+{
+ // Do nothing for now.
+}
+
+void QWebEnginePagePrivate::didRunJavaScript(quint64 requestId, const QVariant& result)
+{
+ if (auto callback = m_variantCallbacks.take(requestId))
+ callback(result);
+}
+
+void QWebEnginePagePrivate::didFetchDocumentMarkup(quint64 requestId, const QString& result)
+{
+ if (auto callback = m_stringCallbacks.take(requestId))
+ callback(result);
+}
+
+void QWebEnginePagePrivate::didFetchDocumentInnerText(quint64 requestId, const QString& result)
+{
+ if (auto callback = m_stringCallbacks.take(requestId))
+ callback(result);
+}
+
+void QWebEnginePagePrivate::didPrintPage(quint64 requestId, QSharedPointer<QByteArray> result)
+{
+#if QT_CONFIG(webengine_printing_and_pdf)
+ // If no currentPrinter is set that means that were printing to PDF only.
+ if (!currentPrinter) {
+ if (!result.data())
+ return;
+ if (auto callback = m_pdfResultCallbacks.take(requestId))
+ callback(*(result.data()));
+ return;
+ }
+
+ if (view)
+ view->didPrintPage(currentPrinter, result);
+ else
+ currentPrinter = nullptr;
+#else
+ // we should never enter this branch, but just for safe-keeping...
+ Q_UNUSED(result);
+ if (auto callback = m_pdfResultCallbacks.take(requestId))
+ callback(QByteArray());
+#endif
+}
+
+bool QWebEnginePagePrivate::passOnFocus(bool reverse)
+{
+ return view ? view->passOnFocus(reverse) : false;
+}
+
+void QWebEnginePagePrivate::authenticationRequired(QSharedPointer<AuthenticationDialogController> controller)
+{
+ Q_Q(QWebEnginePage);
+ QAuthenticator networkAuth;
+ networkAuth.setRealm(controller->realm());
+
+ if (controller->isProxy())
+ Q_EMIT q->proxyAuthenticationRequired(controller->url(), &networkAuth, controller->host());
+ else
+ Q_EMIT q->authenticationRequired(controller->url(), &networkAuth);
+
+ // Authentication has been cancelled
+ if (networkAuth.isNull()) {
+ controller->reject();
+ return;
+ }
+
+ controller->accept(networkAuth.user(), networkAuth.password());
+}
+
+void QWebEnginePagePrivate::releaseProfile()
+{
+ qWarning("Release of profile requested but WebEnginePage still not deleted. Expect troubles !");
+ // this is not the way to go, but might avoid the crash if user code does not make any calls to page.
+ q_ptr->d_ptr.reset();
+}
+
+void QWebEnginePagePrivate::showColorDialog(QSharedPointer<ColorChooserController> controller)
+{
+ if (view)
+ view->showColorDialog(controller);
+}
+
+void QWebEnginePagePrivate::runMediaAccessPermissionRequest(const QUrl &securityOrigin, WebContentsAdapterClient::MediaRequestFlags requestFlags)
+{
+ Q_Q(QWebEnginePage);
+ QWebEnginePage::Feature feature;
+ if (requestFlags.testFlag(WebContentsAdapterClient::MediaAudioCapture) &&
+ requestFlags.testFlag(WebContentsAdapterClient::MediaVideoCapture))
+ feature = QWebEnginePage::MediaAudioVideoCapture;
+ else if (requestFlags.testFlag(WebContentsAdapterClient::MediaAudioCapture))
+ feature = QWebEnginePage::MediaAudioCapture;
+ else if (requestFlags.testFlag(WebContentsAdapterClient::MediaVideoCapture))
+ feature = QWebEnginePage::MediaVideoCapture;
+ else if (requestFlags.testFlag(WebContentsAdapterClient::MediaDesktopAudioCapture) &&
+ requestFlags.testFlag(WebContentsAdapterClient::MediaDesktopVideoCapture))
+ feature = QWebEnginePage::DesktopAudioVideoCapture;
+ else // if (requestFlags.testFlag(WebContentsAdapterClient::MediaDesktopVideoCapture))
+ feature = QWebEnginePage::DesktopVideoCapture;
+ Q_EMIT q->featurePermissionRequested(securityOrigin, feature);
+}
+
+static QWebEnginePage::Feature toFeature(QtWebEngineCore::ProfileAdapter::PermissionType type)
+{
+ switch (type) {
+ case QtWebEngineCore::ProfileAdapter::NotificationPermission:
+ return QWebEnginePage::Notifications;
+ case QtWebEngineCore::ProfileAdapter::GeolocationPermission:
+ return QWebEnginePage::Geolocation;
+ case QtWebEngineCore::ProfileAdapter::ClipboardReadWrite:
+ return QWebEnginePage::ClipboardReadWrite;
+ case QtWebEngineCore::ProfileAdapter::LocalFontsPermission:
+ return QWebEnginePage::LocalFontsAccess;
+ default:
+ break;
+ }
+ Q_UNREACHABLE();
+ return QWebEnginePage::Feature(-1);
+}
+
+void QWebEnginePagePrivate::runFeaturePermissionRequest(QtWebEngineCore::ProfileAdapter::PermissionType permission, const QUrl &securityOrigin)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->featurePermissionRequested(securityOrigin, toFeature(permission));
+}
+
+void QWebEnginePagePrivate::runMouseLockPermissionRequest(const QUrl &securityOrigin)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->featurePermissionRequested(securityOrigin, QWebEnginePage::MouseLock);
+}
+
+void QWebEnginePagePrivate::runRegisterProtocolHandlerRequest(QWebEngineRegisterProtocolHandlerRequest request)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->registerProtocolHandlerRequested(request);
+}
+
+/*!
+ \fn void QWebEnginePage::fileSystemAccessRequested(QWebEngineFileSystemAccessRequest request)
+ \since 6.4
+
+ This signal is emitted when the web page requests access to local files or directories.
+
+ The request object \a request can be used to accept or reject the request.
+*/
+
+void QWebEnginePagePrivate::runFileSystemAccessRequest(QWebEngineFileSystemAccessRequest request)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->fileSystemAccessRequested(request);
+}
+
+QObject *QWebEnginePagePrivate::accessibilityParentObject()
+{
+ return view ? view->accessibilityParentObject() : nullptr;
+}
+
+void QWebEnginePagePrivate::updateAction(QWebEnginePage::WebAction action) const
+{
+#if !QT_CONFIG(action)
+ Q_UNUSED(action);
+#else
+ QAction *a = actions[action];
+ if (!a)
+ return;
+
+ bool enabled = true;
+
+ switch (action) {
+ case QWebEnginePage::Back:
+ enabled = adapter->canGoToOffset(-1);
+ break;
+ case QWebEnginePage::Forward:
+ enabled = adapter->canGoToOffset(1);
+ break;
+ case QWebEnginePage::Stop:
+ enabled = isLoading;
+ break;
+ case QWebEnginePage::Reload:
+ case QWebEnginePage::ReloadAndBypassCache:
+ enabled = !isLoading;
+ break;
+ case QWebEnginePage::ViewSource:
+ enabled = adapter->canViewSource();
+ break;
+ case QWebEnginePage::Cut:
+ case QWebEnginePage::Copy:
+ case QWebEnginePage::Unselect:
+ enabled = adapter->hasFocusedFrame() && !adapter->selectedText().isEmpty();
+ break;
+ case QWebEnginePage::Paste:
+ case QWebEnginePage::Undo:
+ case QWebEnginePage::Redo:
+ case QWebEnginePage::SelectAll:
+ case QWebEnginePage::PasteAndMatchStyle:
+ enabled = adapter->hasFocusedFrame();
+ break;
+ default:
+ break;
+ }
+
+ a->setEnabled(enabled);
+#endif // QT_CONFIG(action)
+}
+
+void QWebEnginePagePrivate::updateNavigationActions()
+{
+ updateAction(QWebEnginePage::Back);
+ updateAction(QWebEnginePage::Forward);
+ updateAction(QWebEnginePage::Stop);
+ updateAction(QWebEnginePage::Reload);
+ updateAction(QWebEnginePage::ReloadAndBypassCache);
+ updateAction(QWebEnginePage::ViewSource);
+}
+
+void QWebEnginePagePrivate::updateEditActions()
+{
+ updateAction(QWebEnginePage::Cut);
+ updateAction(QWebEnginePage::Copy);
+ updateAction(QWebEnginePage::Paste);
+ updateAction(QWebEnginePage::Undo);
+ updateAction(QWebEnginePage::Redo);
+ updateAction(QWebEnginePage::SelectAll);
+ updateAction(QWebEnginePage::PasteAndMatchStyle);
+ updateAction(QWebEnginePage::Unselect);
+}
+
+#if QT_CONFIG(action)
+void QWebEnginePagePrivate::_q_webActionTriggered(bool checked)
+{
+ Q_Q(QWebEnginePage);
+ QAction *a = qobject_cast<QAction *>(q->sender());
+ if (!a)
+ return;
+ QWebEnginePage::WebAction action = static_cast<QWebEnginePage::WebAction>(a->data().toInt());
+ q->triggerAction(action, checked);
+}
+#endif // QT_CONFIG(action)
+
+void QWebEnginePagePrivate::recreateFromSerializedHistory(QDataStream &input)
+{
+ QSharedPointer<WebContentsAdapter> newWebContents = WebContentsAdapter::createFromSerializedNavigationHistory(input, this);
+ if (newWebContents) {
+ adapter = std::move(newWebContents);
+ adapter->setClient(this);
+ adapter->loadDefault();
+ }
+}
+
+void QWebEnginePagePrivate::updateScrollPosition(const QPointF &position)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->scrollPositionChanged(position);
+}
+
+void QWebEnginePagePrivate::updateContentsSize(const QSizeF &size)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->contentsSizeChanged(size);
+}
+
+void QWebEnginePagePrivate::setFullScreenMode(bool fullscreen)
+{
+ if (fullscreenMode != fullscreen) {
+ fullscreenMode = fullscreen;
+ adapter->changedFullScreen();
+ }
+}
+
+ProfileAdapter* QWebEnginePagePrivate::profileAdapter()
+{
+ return profile->d_ptr->profileAdapter();
+}
+
+WebContentsAdapter *QWebEnginePagePrivate::webContentsAdapter()
+{
+ ensureInitialized();
+ return adapter.data();
+}
+
+const QObject *QWebEnginePagePrivate::holdingQObject() const
+{
+ Q_Q(const QWebEnginePage);
+ return q;
+}
+
+void QWebEnginePagePrivate::findTextFinished(const QWebEngineFindTextResult &result)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->findTextFinished(result);
+}
+
+void QWebEnginePagePrivate::showAutofillPopup(QtWebEngineCore::AutofillPopupController *controller,
+ const QRect &bounds, bool autoselectFirstSuggestion)
+{
+ if (view)
+ view->showAutofillPopup(controller, bounds, autoselectFirstSuggestion);
+}
+
+void QWebEnginePagePrivate::hideAutofillPopup()
+{
+ if (view)
+ view->hideAutofillPopup();
+}
+
+void QWebEnginePagePrivate::ensureInitialized() const
+{
+ if (!adapter->isInitialized())
+ adapter->loadDefault();
+}
+
+void QWebEnginePagePrivate::showWebAuthDialog(QWebEngineWebAuthUxRequest *request)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->webAuthUxRequested(request);
+}
+
+QWebEnginePage::QWebEnginePage(QObject* parent)
+ : QObject(parent)
+ , d_ptr(new QWebEnginePagePrivate())
+{
+ Q_D(QWebEnginePage);
+ d->q_ptr = this;
+ d->adapter->setClient(d);
+}
+
+/*!
+ \fn void QWebEnginePage::findTextFinished(const QWebEngineFindTextResult &result)
+ \since 5.14
+
+ This signal is emitted when a search string search on a page is completed. \a result is
+ the result of the string search.
+
+ \sa findText()
+*/
+
+
+/*!
+ \enum QWebEnginePage::RenderProcessTerminationStatus
+ \since 5.6
+
+ This enum describes the status with which the render process terminated:
+
+ \value NormalTerminationStatus
+ The render process terminated normally.
+ \value AbnormalTerminationStatus
+ The render process terminated with with a non-zero exit status.
+ \value CrashedTerminationStatus
+ The render process crashed, for example because of a segmentation fault.
+ \value KilledTerminationStatus
+ The render process was killed, for example by \c SIGKILL or task manager kill.
+*/
+
+/*!
+ \fn QWebEnginePage::renderProcessTerminated(RenderProcessTerminationStatus terminationStatus, int exitCode)
+ \since 5.6
+
+ This signal is emitted when the render process is terminated with a non-zero exit status.
+ \a terminationStatus is the termination status of the process and \a exitCode is the status code
+ with which the process terminated.
+*/
+
+/*!
+ \fn QWebEnginePage::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest)
+
+ This signal is emitted when the web page issues the request to enter fullscreen mode for
+ a web-element, usually a video element.
+
+ The request object \a fullScreenRequest can be used to accept or reject the request.
+
+ If the request is accepted the element requesting fullscreen will fill the viewport,
+ but it is up to the application to make the view fullscreen or move the page to a view
+ that is fullscreen.
+
+ \sa QWebEngineSettings::FullScreenSupportEnabled
+*/
+
+/*!
+ \fn QWebEnginePage::quotaRequested(QWebEngineQuotaRequest quotaRequest)
+ \since 5.11
+ \deprecated [6.5] This signal is no longer emitted.
+
+ Requesting host quota is no longer supported by Chromium.
+ The behavior of navigator.webkitPersistentStorage
+ is identical to navigator.webkitTemporaryStorage.
+
+ For further details, see https://crbug.com/1233525
+*/
+
+/*!
+ \fn QWebEnginePage::registerProtocolHandlerRequested(QWebEngineRegisterProtocolHandlerRequest request)
+ \since 5.11
+
+ This signal is emitted when the web page tries to register a custom protocol
+ using the \l registerProtocolHandler API.
+
+ The request object \a request can be used to accept or reject the request:
+
+ \snippet webenginewidgets/simplebrowser/webview.cpp registerProtocolHandlerRequested
+*/
+
+/*!
+ \property QWebEnginePage::scrollPosition
+ \since 5.7
+
+ \brief The scroll position of the page contents.
+*/
+
+/*!
+ \property QWebEnginePage::contentsSize
+ \since 5.7
+
+ \brief The size of the page contents.
+*/
+
+/*!
+ \fn void QWebEnginePage::audioMutedChanged(bool muted)
+ \since 5.7
+
+ This signal is emitted when the page's \a muted state changes.
+ \note Not to be confused with a specific HTML5 audio or video element being muted.
+*/
+
+/*!
+ \fn void QWebEnginePage::recentlyAudibleChanged(bool recentlyAudible);
+ \since 5.7
+
+ This signal is emitted when the page's audible state, \a recentlyAudible, changes, because
+ the audio is played or stopped.
+
+ \note The signal is also emitted when calling the setAudioMuted() method.
+*/
+
+/*!
+ \fn void QWebEnginePage::renderProcessPidChanged(qint64 pid);
+ \since 5.15
+
+ This signal is emitted when the underlying render process PID, \a pid, changes.
+*/
+
+/*!
+ \fn void QWebEnginePage::iconUrlChanged(const QUrl &url)
+
+ This signal is emitted when the URL of the icon ("favicon") associated with the
+ page is changed. The new URL is specified by \a url.
+
+ \sa iconUrl(), icon(), iconChanged()
+*/
+
+/*!
+ \fn void QWebEnginePage::iconChanged(const QIcon &icon)
+ \since 5.7
+
+ This signal is emitted when the icon ("favicon") associated with the
+ page is changed. The new icon is specified by \a icon.
+
+ \sa icon(), iconUrl(), iconUrlChanged()
+*/
+
+/*!
+ Constructs an empty web engine page in the web engine profile \a profile with the parent
+ \a parent.
+
+ If the profile is not the default profile, the caller must ensure that the profile stays alive
+ for as long as the page does.
+
+ \since 5.5
+*/
+QWebEnginePage::QWebEnginePage(QWebEngineProfile *profile, QObject* parent)
+ : QObject(parent)
+ , d_ptr(new QWebEnginePagePrivate(profile))
+{
+ Q_D(QWebEnginePage);
+ d->q_ptr = this;
+ d->adapter->setClient(d);
+}
+
+QWebEnginePage::~QWebEnginePage()
+{
+ if (d_ptr) {
+ // d_ptr might be exceptionally null if profile adapter got deleted first
+ setDevToolsPage(nullptr);
+ emit _q_aboutToDelete();
+
+ for (auto varFun : std::as_const(d_ptr->m_variantCallbacks))
+ varFun(QVariant());
+ for (auto strFun : std::as_const(d_ptr->m_stringCallbacks))
+ strFun(QString());
+ d_ptr->m_variantCallbacks.clear();
+ d_ptr->m_stringCallbacks.clear();
+ }
+}
+
+QWebEngineHistory *QWebEnginePage::history() const
+{
+ Q_D(const QWebEnginePage);
+ return d->history;
+}
+
+QWebEngineSettings *QWebEnginePage::settings() const
+{
+ Q_D(const QWebEnginePage);
+ return d->settings;
+}
+
+/*!
+ * Returns a pointer to the web channel instance used by this page or a null pointer if none was set.
+ * This channel automatically uses the internal web engine transport mechanism over Chromium IPC
+ * that is exposed in the JavaScript context of this page as \c qt.webChannelTransport.
+ *
+ * \since 5.5
+ * \sa setWebChannel()
+ */
+QWebChannel *QWebEnginePage::webChannel() const
+{
+#if QT_CONFIG(webengine_webchannel)
+ Q_D(const QWebEnginePage);
+ return d->webChannel;
+#endif
+ qWarning("WebEngine compiled without webchannel support");
+ return nullptr;
+}
+
+/*!
+ * Sets the web channel instance to be used by this page to \a channel and connects it to
+ * web engine's transport using Chromium IPC messages. The transport is exposed in the JavaScript
+ * world \a worldId as
+ * \c qt.webChannelTransport, which should be used when using the \l{Qt WebChannel JavaScript API}.
+ *
+ * \note The page does not take ownership of the channel object.
+ * \note Only one web channel can be installed per page, setting one even in another JavaScript
+ * world uninstalls any already installed web channel.
+ *
+ * \since 5.7
+ * \sa QWebEngineScript::ScriptWorldId
+ */
+void QWebEnginePage::setWebChannel(QWebChannel *channel, quint32 worldId)
+{
+#if QT_CONFIG(webengine_webchannel)
+ Q_D(QWebEnginePage);
+ if (d->webChannel != channel || d->webChannelWorldId != worldId) {
+ d->webChannel = channel;
+ d->webChannelWorldId = worldId;
+ d->adapter->setWebChannel(channel, worldId);
+ }
+#else
+ Q_UNUSED(channel);
+ Q_UNUSED(worldId);
+ qWarning("WebEngine compiled without webchannel support");
+#endif
+}
+
+/*!
+ \property QWebEnginePage::backgroundColor
+ \brief The page's background color behind the document's body.
+ \since 5.6
+
+ You can set the background color to Qt::transparent or to a translucent
+ color to see through the document, or you can set it to match your
+ web content in a hybrid application to prevent the white flashes that may appear
+ during loading.
+
+ The default value is white.
+*/
+QColor QWebEnginePage::backgroundColor() const
+{
+ Q_D(const QWebEnginePage);
+ return d->m_backgroundColor;
+}
+
+void QWebEnginePage::setBackgroundColor(const QColor &color)
+{
+ Q_D(QWebEnginePage);
+ if (d->m_backgroundColor == color)
+ return;
+ d->m_backgroundColor = color;
+ d->adapter->setBackgroundColor(color);
+}
+
+/*!
+ * Save the currently loaded web page to disk.
+ *
+ * The web page is saved to \a filePath in the specified \a{format}.
+ *
+ * This is a short cut for the following actions:
+ * \list
+ * \li Trigger the Save web action.
+ * \li Accept the next download item and set the specified file path and save format.
+ * \endlist
+ *
+ * This function issues an asynchronous download request for the web page and returns immediately.
+ *
+ * \sa QWebEngineDownloadRequest::SavePageFormat
+ * \since 5.8
+ */
+void QWebEnginePage::save(const QString &filePath,
+ QWebEngineDownloadRequest::SavePageFormat format) const
+{
+ Q_D(const QWebEnginePage);
+ d->ensureInitialized();
+ d->adapter->save(filePath, format);
+}
+
+/*!
+ \property QWebEnginePage::audioMuted
+ \brief Whether the current page audio is muted.
+ \since 5.7
+
+ The default value is \c false.
+ \sa recentlyAudible
+*/
+bool QWebEnginePage::isAudioMuted() const {
+ Q_D(const QWebEnginePage);
+ if (d->adapter->isInitialized())
+ return d->adapter->isAudioMuted();
+ return d->defaultAudioMuted;
+}
+
+void QWebEnginePage::setAudioMuted(bool muted) {
+ Q_D(QWebEnginePage);
+ bool wasAudioMuted = isAudioMuted();
+ d->defaultAudioMuted = muted;
+ d->adapter->setAudioMuted(muted);
+ if (wasAudioMuted != isAudioMuted())
+ Q_EMIT audioMutedChanged(muted);
+}
+
+/*!
+ \property QWebEnginePage::recentlyAudible
+ \brief The current page's \e {audible state}, that is, whether audio was recently played
+ or not.
+ \since 5.7
+
+ The default value is \c false.
+ \sa audioMuted
+*/
+bool QWebEnginePage::recentlyAudible() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->isInitialized() && d->adapter->recentlyAudible();
+}
+
+/*!
+ \property QWebEnginePage::renderProcessPid
+ \brief The process ID (PID) of the render process assigned to the current
+ page's main frame.
+ \since 5.15
+
+ If no render process is available yet, \c 0 is returned.
+*/
+qint64 QWebEnginePage::renderProcessPid() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->renderProcessPid();
+}
+
+/*!
+ Returns the web engine profile the page belongs to.
+ \since 5.5
+*/
+QWebEngineProfile *QWebEnginePage::profile() const
+{
+ Q_D(const QWebEnginePage);
+ return d->profile;
+}
+
+bool QWebEnginePage::hasSelection() const
+{
+ return !selectedText().isEmpty();
+}
+
+QString QWebEnginePage::selectedText() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->selectedText();
+}
+
+#if QT_CONFIG(action)
+QAction *QWebEnginePage::action(WebAction action) const
+{
+ Q_D(const QWebEnginePage);
+ if (action == QWebEnginePage::NoWebAction)
+ return nullptr;
+ if (d->actions[action])
+ return d->actions[action];
+
+ const QString text = QWebEnginePagePrivate::actionText(action);
+
+ QAction *a = new QAction(const_cast<QWebEnginePage*>(this));
+ a->setText(text);
+ a->setData(action);
+
+ connect(a, SIGNAL(triggered(bool)), this, SLOT(_q_webActionTriggered(bool)));
+
+ d->actions[action] = a;
+ d->updateAction(action);
+ return a;
+}
+#endif // QT_CONFIG(action)
+
+void QWebEnginePage::triggerAction(WebAction action, bool)
+{
+ Q_D(QWebEnginePage);
+ d->ensureInitialized();
+ switch (action) {
+ case Back:
+ d->adapter->navigateBack();
+ break;
+ case Forward:
+ d->adapter->navigateForward();
+ break;
+ case Stop:
+ d->adapter->stop();
+ break;
+ case Reload:
+ d->adapter->reload();
+ break;
+ case ReloadAndBypassCache:
+ d->adapter->reloadAndBypassCache();
+ break;
+ case Cut:
+ d->adapter->cut();
+ break;
+ case Copy:
+ d->adapter->copy();
+ break;
+ case Paste:
+ d->adapter->paste();
+ break;
+ case Undo:
+ d->adapter->undo();
+ break;
+ case Redo:
+ d->adapter->redo();
+ break;
+ case SelectAll:
+ d->adapter->selectAll();
+ break;
+ case PasteAndMatchStyle:
+ d->adapter->pasteAndMatchStyle();
+ break;
+ case Unselect:
+ d->adapter->unselect();
+ break;
+ case OpenLinkInThisWindow:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->filteredLinkUrl().isValid())
+ setUrl(d->view->lastContextMenuRequest()->filteredLinkUrl());
+ break;
+ case OpenLinkInNewWindow:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->filteredLinkUrl().isValid())
+ d->createNewWindow(WebContentsAdapterClient::NewWindowDisposition, true,
+ d->view->lastContextMenuRequest()->filteredLinkUrl());
+ break;
+ case OpenLinkInNewTab:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->filteredLinkUrl().isValid())
+ d->createNewWindow(WebContentsAdapterClient::NewForegroundTabDisposition, true,
+ d->view->lastContextMenuRequest()->filteredLinkUrl());
+ break;
+ case OpenLinkInNewBackgroundTab:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->filteredLinkUrl().isValid())
+ d->createNewWindow(WebContentsAdapterClient::NewBackgroundTabDisposition, true,
+ d->view->lastContextMenuRequest()->filteredLinkUrl());
+ break;
+ case CopyLinkToClipboard:
+ if (d->view && d->view->lastContextMenuRequest() && !d->view->lastContextMenuRequest()->linkUrl().isEmpty()) {
+ QString urlString = d->view->lastContextMenuRequest()->linkUrl().toString(
+ QUrl::FullyEncoded);
+ QString linkText = d->view->lastContextMenuRequest()->linkText().toHtmlEscaped();
+ QString title = d->view->lastContextMenuRequest()->titleText();
+ if (!title.isEmpty())
+ title = QStringLiteral(" title=\"%1\"").arg(title.toHtmlEscaped());
+ QMimeData *data = new QMimeData();
+ data->setText(urlString);
+ QString html = QStringLiteral("<a href=\"") + urlString + QStringLiteral("\"") + title + QStringLiteral(">")
+ + linkText + QStringLiteral("</a>");
+ data->setHtml(html);
+ data->setUrls(QList<QUrl>() << d->view->lastContextMenuRequest()->linkUrl());
+ QGuiApplication::clipboard()->setMimeData(data);
+ }
+ break;
+ case DownloadLinkToDisk:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->filteredLinkUrl().isValid())
+ d->adapter->download(d->view->lastContextMenuRequest()->filteredLinkUrl(),
+ d->view->lastContextMenuRequest()->suggestedFileName(),
+ d->view->lastContextMenuRequest()->referrerUrl(),
+ d->view->lastContextMenuRequest()->referrerPolicy());
+
+ break;
+ case CopyImageToClipboard:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->hasImageContent()
+ && (d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeImage
+ || d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeCanvas)) {
+ d->adapter->copyImageAt(d->view->lastContextMenuRequest()->position());
+ }
+ break;
+ case CopyImageUrlToClipboard:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeImage) {
+ QString urlString =
+ d->view->lastContextMenuRequest()->mediaUrl().toString(QUrl::FullyEncoded);
+ QString alt = d->view->lastContextMenuRequest()->altText();
+ if (!alt.isEmpty())
+ alt = QStringLiteral(" alt=\"%1\"").arg(alt.toHtmlEscaped());
+ QString title = d->view->lastContextMenuRequest()->titleText();
+ if (!title.isEmpty())
+ title = QStringLiteral(" title=\"%1\"").arg(title.toHtmlEscaped());
+ QMimeData *data = new QMimeData();
+ data->setText(urlString);
+ QString html = QStringLiteral("<img src=\"") + urlString + QStringLiteral("\"") + title + alt + QStringLiteral("></img>");
+ data->setHtml(html);
+ data->setUrls(QList<QUrl>() << d->view->lastContextMenuRequest()->mediaUrl());
+ QGuiApplication::clipboard()->setMimeData(data);
+ }
+ break;
+ case DownloadImageToDisk:
+ case DownloadMediaToDisk:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid())
+ d->adapter->download(d->view->lastContextMenuRequest()->mediaUrl(),
+ d->view->lastContextMenuRequest()->suggestedFileName(),
+ d->view->lastContextMenuRequest()->referrerUrl(),
+ d->view->lastContextMenuRequest()->referrerPolicy());
+ break;
+ case CopyMediaUrlToClipboard:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && (d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeAudio
+ || d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeVideo)) {
+ QString urlString =
+ d->view->lastContextMenuRequest()->mediaUrl().toString(QUrl::FullyEncoded);
+ QString title = d->view->lastContextMenuRequest()->titleText();
+ if (!title.isEmpty())
+ title = QStringLiteral(" title=\"%1\"").arg(title.toHtmlEscaped());
+ QMimeData *data = new QMimeData();
+ data->setText(urlString);
+ if (d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeAudio)
+ data->setHtml(QStringLiteral("<audio src=\"") + urlString + QStringLiteral("\"") + title +
+ QStringLiteral("></audio>"));
+ else
+ data->setHtml(QStringLiteral("<video src=\"") + urlString + QStringLiteral("\"") + title +
+ QStringLiteral("></video>"));
+ data->setUrls(QList<QUrl>() << d->view->lastContextMenuRequest()->mediaUrl());
+ QGuiApplication::clipboard()->setMimeData(data);
+ }
+ break;
+ case ToggleMediaControls:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaCanToggleControls) {
+ bool enable = !(d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaControls);
+ d->adapter->executeMediaPlayerActionAt(d->view->lastContextMenuRequest()->position(),
+ WebContentsAdapter::MediaPlayerControls, enable);
+ }
+ break;
+ case ToggleMediaLoop:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && (d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeAudio
+ || d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeVideo)) {
+ bool enable = !(d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaLoop);
+ d->adapter->executeMediaPlayerActionAt(d->view->lastContextMenuRequest()->position(),
+ WebContentsAdapter::MediaPlayerLoop, enable);
+ }
+ break;
+ case ToggleMediaPlayPause:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && (d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeAudio
+ || d->view->lastContextMenuRequest()->mediaType()
+ == QWebEngineContextMenuRequest::MediaTypeVideo)) {
+ bool enable = (d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaPaused);
+ d->adapter->executeMediaPlayerActionAt(d->view->lastContextMenuRequest()->position(),
+ WebContentsAdapter::MediaPlayerPlay, enable);
+ }
+ break;
+ case ToggleMediaMute:
+ if (d->view && d->view->lastContextMenuRequest() && d->view->lastContextMenuRequest()->mediaUrl().isValid()
+ && d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaHasAudio) {
+ // Make sure to negate the value, so that toggling actually works.
+ bool enable = !(d->view->lastContextMenuRequest()->mediaFlags()
+ & QWebEngineContextMenuRequest::MediaMuted);
+ d->adapter->executeMediaPlayerActionAt(d->view->lastContextMenuRequest()->position(),
+ WebContentsAdapter::MediaPlayerMute, enable);
+ }
+ break;
+ case InspectElement:
+ if (d->view && d->view->lastContextMenuRequest())
+ d->adapter->inspectElementAt(d->view->lastContextMenuRequest()->position());
+ break;
+ case ExitFullScreen:
+ // See under ViewSource, anything that can trigger a delete of the current view is dangerous to call directly here.
+ QTimer::singleShot(0, this, [d](){ d->adapter->exitFullScreen(); });
+ break;
+ case RequestClose:
+ d->adapter->requestClose();
+ break;
+ case SavePage:
+ d->adapter->save();
+ break;
+ case ViewSource:
+ // This is a workaround to make the ViewSource action working in a context menu.
+ // The WebContentsAdapter::viewSource() method deletes a
+ // RenderWidgetHostViewQtDelegateWidget instance which passes the control to the event
+ // loop. If the QMenu::aboutToHide() signal is connected to the QObject::deleteLater()
+ // slot the QMenu is deleted by the event handler while the ViewSource action is still not
+ // completed. This may lead to a crash. To avoid this the WebContentsAdapter::viewSource()
+ // method is called indirectly via the QTimer::singleShot() function which schedules the
+ // the viewSource() call after the QMenu's destruction.
+ QTimer::singleShot(0, this, [d](){ d->adapter->viewSource(); });
+ break;
+ case ToggleBold:
+ runJavaScript(QStringLiteral("document.execCommand('bold');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case ToggleItalic:
+ runJavaScript(QStringLiteral("document.execCommand('italic');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case ToggleUnderline:
+ runJavaScript(QStringLiteral("document.execCommand('underline');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case ToggleStrikethrough:
+ runJavaScript(QStringLiteral("document.execCommand('strikethrough');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case AlignLeft:
+ runJavaScript(QStringLiteral("document.execCommand('justifyLeft');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case AlignCenter:
+ runJavaScript(QStringLiteral("document.execCommand('justifyCenter');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case AlignRight:
+ runJavaScript(QStringLiteral("document.execCommand('justifyRight');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case AlignJustified:
+ runJavaScript(QStringLiteral("document.execCommand('justifyFull');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case Indent:
+ runJavaScript(QStringLiteral("document.execCommand('indent');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case Outdent:
+ runJavaScript(QStringLiteral("document.execCommand('outdent');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case InsertOrderedList:
+ runJavaScript(QStringLiteral("document.execCommand('insertOrderedList');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case InsertUnorderedList:
+ runJavaScript(QStringLiteral("document.execCommand('insertUnorderedList');"), QWebEngineScript::ApplicationWorld);
+ break;
+ case ChangeTextDirectionLTR:
+ d->adapter->changeTextDirection(true /*left to right*/);
+ break;
+ case ChangeTextDirectionRTL:
+ d->adapter->changeTextDirection(false /*left to right*/);
+ break;
+ case NoWebAction:
+ break;
+ case WebActionCount:
+ Q_UNREACHABLE();
+ break;
+ }
+}
+
+/*!
+ * \since 5.8
+ * Replace the current misspelled word with \a replacement.
+ *
+ * The current misspelled word can be found in QWebEngineContextMenuRequest::misspelledWord(),
+ * and suggested replacements in QWebEngineContextMenuRequest::spellCheckerSuggestions().
+ *
+ */
+
+void QWebEnginePage::replaceMisspelledWord(const QString &replacement)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->replaceMisspelling(replacement);
+}
+
+void QWebEnginePage::findText(const QString &subString, FindFlags options, const std::function<void(const QWebEngineFindTextResult &)> &resultCallback)
+{
+ Q_D(QWebEnginePage);
+ if (!d->adapter->isInitialized()) {
+ if (resultCallback)
+ resultCallback(QWebEngineFindTextResult());
+ return;
+ }
+
+ d->adapter->findTextHelper()->startFinding(subString, options & FindCaseSensitively, options & FindBackward, resultCallback);
+}
+
+/*!
+ * \reimp
+ */
+bool QWebEnginePage::event(QEvent *e)
+{
+ return QObject::event(e);
+}
+
+void QWebEnginePagePrivate::desktopMediaRequested(
+ QtWebEngineCore::DesktopMediaController *controller)
+{
+ Q_Q(QWebEnginePage);
+ QTimer::singleShot(0, q, [q, controller]() {
+ Q_EMIT q->desktopMediaRequested(QWebEngineDesktopMediaRequest(controller));
+ });
+}
+
+void QWebEnginePagePrivate::contextMenuRequested(QWebEngineContextMenuRequest *data)
+{
+ if (view)
+ view->contextMenuRequested(data);
+}
+
+/*!
+ \fn void QWebEnginePage::navigationRequested(QWebEngineNavigationRequest &request)
+ \since 6.2
+
+ This signal is emitted on navigation together with the call the acceptNavigationRequest().
+ It can be used to accept or ignore the \a request. The default is to accept.
+
+ \sa acceptNavigationRequest()
+*/
+
+void QWebEnginePagePrivate::navigationRequested(int navigationType, const QUrl &url, bool &accepted, bool isMainFrame, bool hasFormData)
+{
+ Q_Q(QWebEnginePage);
+
+ accepted = q->acceptNavigationRequest(url, static_cast<QWebEnginePage::NavigationType>(navigationType), isMainFrame);
+ if (accepted) {
+ QWebEngineNavigationRequest navigationRequest(url, static_cast<QWebEngineNavigationRequest::NavigationType>(navigationType), isMainFrame, hasFormData);
+ Q_EMIT q->navigationRequested(navigationRequest);
+ accepted = navigationRequest.isAccepted();
+ }
+
+ if (accepted && adapter->findTextHelper()->isFindTextInProgress())
+ adapter->findTextHelper()->stopFinding();
+}
+
+void QWebEnginePagePrivate::requestFullScreenMode(const QUrl &origin, bool fullscreen)
+{
+ Q_Q(QWebEnginePage);
+ QWebEngineFullScreenRequest request(origin, fullscreen, [q = QPointer(q)] (bool toggleOn) { if (q) q->d_ptr->setFullScreenMode(toggleOn); });
+ Q_EMIT q->fullScreenRequested(std::move(request));
+}
+
+bool QWebEnginePagePrivate::isFullScreenMode() const
+{
+ return fullscreenMode;
+}
+
+void QWebEnginePagePrivate::javascriptDialog(QSharedPointer<JavaScriptDialogController> controller)
+{
+ Q_Q(QWebEnginePage);
+ bool accepted = false;
+ QString promptResult;
+ switch (controller->type()) {
+ case AlertDialog:
+ q->javaScriptAlert(controller->securityOrigin(), controller->message());
+ accepted = true;
+ break;
+ case ConfirmDialog:
+ accepted = q->javaScriptConfirm(controller->securityOrigin(), controller->message());
+ break;
+ case PromptDialog:
+ accepted = q->javaScriptPrompt(controller->securityOrigin(), controller->message(), controller->defaultPrompt(), &promptResult);
+ if (accepted)
+ controller->textProvided(promptResult);
+ break;
+ case UnloadDialog:
+ accepted = q->javaScriptConfirm(controller->securityOrigin(), QCoreApplication::translate("QWebEnginePage", "Are you sure you want to leave this page? Changes that you made may not be saved."));
+ break;
+ case InternalAuthorizationDialog:
+ accepted = view ? view->showAuthorizationDialog(controller->title(), controller->message())
+ : false;
+ break;
+ }
+ if (accepted)
+ controller->accept();
+ else
+ controller->reject();
+}
+
+void QWebEnginePagePrivate::allowCertificateError(const QWebEngineCertificateError &error)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->certificateError(error);
+}
+
+void QWebEnginePagePrivate::selectClientCert(const QSharedPointer<ClientCertSelectController> &controller)
+{
+ Q_Q(QWebEnginePage);
+ QWebEngineClientCertificateSelection certSelection(controller);
+
+ Q_EMIT q->selectClientCertificate(certSelection);
+}
+
+/*!
+ \fn void QWebEnginePage::selectClientCertificate(QWebEngineClientCertificateSelection clientCertificateSelection)
+ \since 5.12
+
+ This signal is emitted when a web site requests an SSL client certificate, and one or more were
+ found in system's client certificate store.
+
+ Handling the signal is asynchronous, and loading will be waiting until a certificate is selected,
+ or the last copy of \a clientCertificateSelection is destroyed.
+
+ If the signal is not handled, \a clientCertificateSelection is automatically destroyed, and loading
+ will continue without a client certificate.
+
+ \sa QWebEngineClientCertificateSelection
+*/
+
+void QWebEnginePagePrivate::javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString &message, int lineNumber, const QString &sourceID)
+{
+ Q_Q(QWebEnginePage);
+ q->javaScriptConsoleMessage(static_cast<QWebEnginePage::JavaScriptConsoleMessageLevel>(level), message, lineNumber, sourceID);
+}
+
+void QWebEnginePagePrivate::renderProcessTerminated(RenderProcessTerminationStatus terminationStatus,
+ int exitCode)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->renderProcessTerminated(static_cast<QWebEnginePage::RenderProcessTerminationStatus>(
+ terminationStatus), exitCode);
+}
+
+void QWebEnginePagePrivate::requestGeometryChange(const QRect &geometry, const QRect &frameGeometry)
+{
+ Q_UNUSED(geometry);
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->geometryChangeRequested(frameGeometry);
+}
+
+QObject *QWebEnginePagePrivate::dragSource() const
+{
+#if QT_CONFIG(draganddrop)
+ return view->accessibilityParentObject();
+#else
+ return nullptr;
+#endif // QT_CONFIG(draganddrop)
+}
+
+bool QWebEnginePagePrivate::isEnabled() const
+{
+ if (view)
+ return view->isEnabled();
+ return true;
+}
+
+void QWebEnginePagePrivate::setToolTip(const QString &toolTipText)
+{
+ if (view)
+ view->setToolTip(toolTipText);
+}
+
+/*!
+ \fn void QWebEnginePage::printRequested()
+ \since 5.12
+
+ This signal is emitted when the JavaScript \c{window.print()} method is called or the user pressed the print
+ button of PDF viewer plugin.
+ Typically, the signal handler can simply call printToPdf().
+
+ \sa printToPdf()
+*/
+
+void QWebEnginePagePrivate::printRequested()
+{
+ Q_Q(QWebEnginePage);
+ QTimer::singleShot(0, q, [q]() {
+ Q_EMIT q->printRequested();
+ });
+ if (view)
+ view->printRequested();
+}
+
+QtWebEngineCore::TouchHandleDrawableDelegate *
+QWebEnginePagePrivate::createTouchHandleDelegate(const QMap<int, QImage> &images)
+{
+ return view->createTouchHandleDelegate(images);
+}
+
+void QWebEnginePagePrivate::showTouchSelectionMenu(
+ QtWebEngineCore::TouchSelectionMenuController *controller, const QRect &selectionBounds,
+ const QSize &handleSize)
+{
+ Q_UNUSED(handleSize);
+
+ if (controller->buttonCount() == 1) {
+ controller->runContextMenu();
+ return;
+ }
+
+ view->showTouchSelectionMenu(controller, selectionBounds);
+}
+
+void QWebEnginePagePrivate::hideTouchSelectionMenu()
+{
+ view->hideTouchSelectionMenu();
+}
+
+void QWebEnginePagePrivate::lifecycleStateChanged(LifecycleState state)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->lifecycleStateChanged(static_cast<QWebEnginePage::LifecycleState>(state));
+}
+
+void QWebEnginePagePrivate::recommendedStateChanged(LifecycleState state)
+{
+ Q_Q(QWebEnginePage);
+ QTimer::singleShot(0, q, [q, state]() {
+ Q_EMIT q->recommendedStateChanged(static_cast<QWebEnginePage::LifecycleState>(state));
+ });
+}
+
+void QWebEnginePagePrivate::visibleChanged(bool visible)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->visibleChanged(visible);
+}
+
+/*!
+ \since 5.13
+
+ Registers the request interceptor \a interceptor to intercept URL requests.
+
+ The page does not take ownership of the pointer. This interceptor is called
+ after any interceptors on the profile, and unlike profile interceptors, only
+ URL requests from this page are intercepted. If the original request was
+ already blocked or redirected by the profile interceptor, it will not be
+ intercepted by this.
+
+ To unset the request interceptor, set a \c nullptr.
+
+ \sa QWebEngineUrlRequestInfo, QWebEngineProfile::setUrlRequestInterceptor()
+*/
+
+void QWebEnginePage::setUrlRequestInterceptor(QWebEngineUrlRequestInterceptor *interceptor)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->setRequestInterceptor(interceptor);
+}
+
+void QWebEnginePage::setFeaturePermission(const QUrl &securityOrigin, QWebEnginePage::Feature feature, QWebEnginePage::PermissionPolicy policy)
+{
+ Q_D(QWebEnginePage);
+ if (policy == PermissionUnknown) {
+ switch (feature) {
+ case MediaAudioVideoCapture:
+ case MediaAudioCapture:
+ case MediaVideoCapture:
+ case DesktopAudioVideoCapture:
+ case DesktopVideoCapture:
+ case MouseLock:
+ break;
+ case Geolocation:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::GeolocationPermission, ProfileAdapter::AskPermission);
+ break;
+ case Notifications:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::NotificationPermission, ProfileAdapter::AskPermission);
+ break;
+ case ClipboardReadWrite:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::ClipboardReadWrite,
+ ProfileAdapter::AskPermission);
+ break;
+ case LocalFontsAccess:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::LocalFontsPermission, ProfileAdapter::AskPermission);
+ break;
+ }
+ return;
+ }
+
+ const WebContentsAdapterClient::MediaRequestFlags audioVideoCaptureFlags(
+ WebContentsAdapterClient::MediaVideoCapture |
+ WebContentsAdapterClient::MediaAudioCapture);
+ const WebContentsAdapterClient::MediaRequestFlags desktopAudioVideoCaptureFlags(
+ WebContentsAdapterClient::MediaDesktopVideoCapture |
+ WebContentsAdapterClient::MediaDesktopAudioCapture);
+
+ if (policy == PermissionGrantedByUser) {
+ switch (feature) {
+ case MediaAudioVideoCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, audioVideoCaptureFlags);
+ break;
+ case MediaAudioCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, WebContentsAdapterClient::MediaAudioCapture);
+ break;
+ case MediaVideoCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, WebContentsAdapterClient::MediaVideoCapture);
+ break;
+ case DesktopAudioVideoCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, desktopAudioVideoCaptureFlags);
+ break;
+ case DesktopVideoCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, WebContentsAdapterClient::MediaDesktopVideoCapture);
+ break;
+ case MouseLock:
+ d->adapter->grantMouseLockPermission(securityOrigin, true);
+ break;
+ case Geolocation:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::GeolocationPermission, ProfileAdapter::AllowedPermission);
+ break;
+ case Notifications:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::NotificationPermission, ProfileAdapter::AllowedPermission);
+ break;
+ case ClipboardReadWrite:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::ClipboardReadWrite,
+ ProfileAdapter::AllowedPermission);
+ break;
+ case LocalFontsAccess:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::LocalFontsPermission, ProfileAdapter::AllowedPermission);
+ break;
+ }
+ } else { // if (policy == PermissionDeniedByUser)
+ switch (feature) {
+ case MediaAudioVideoCapture:
+ case MediaAudioCapture:
+ case MediaVideoCapture:
+ case DesktopAudioVideoCapture:
+ case DesktopVideoCapture:
+ d->adapter->grantMediaAccessPermission(securityOrigin, WebContentsAdapterClient::MediaNone);
+ break;
+ case Geolocation:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::GeolocationPermission, ProfileAdapter::DeniedPermission);
+ break;
+ case MouseLock:
+ d->adapter->grantMouseLockPermission(securityOrigin, false);
+ break;
+ case Notifications:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::NotificationPermission, ProfileAdapter::DeniedPermission);
+ break;
+ case ClipboardReadWrite:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::ClipboardReadWrite,
+ ProfileAdapter::DeniedPermission);
+ break;
+ case LocalFontsAccess:
+ d->adapter->grantFeaturePermission(securityOrigin, ProfileAdapter::LocalFontsPermission, ProfileAdapter::DeniedPermission);
+ break;
+ }
+ }
+}
+
+static inline QWebEnginePage::FileSelectionMode toPublic(FilePickerController::FileChooserMode mode)
+{
+ // Should the underlying values change, we'll need a switch here.
+ return static_cast<QWebEnginePage::FileSelectionMode>(mode);
+}
+
+void QWebEnginePagePrivate::runFileChooser(QSharedPointer<FilePickerController> controller)
+{
+ Q_Q(QWebEnginePage);
+
+ QStringList selectedFileNames = q->chooseFiles(toPublic(controller->mode()), (QStringList() << controller->defaultFileName()), controller->acceptedMimeTypes());
+
+ if (!selectedFileNames.empty())
+ controller->accepted(selectedFileNames);
+ else
+ controller->rejected();
+}
+
+QWebEngineSettings *QWebEnginePagePrivate::webEngineSettings() const
+{
+ return settings;
+}
+
+/*!
+ \since 5.10
+ Downloads the resource from the location given by \a url to a local file.
+
+ If \a filename is given, it is used as the suggested file name.
+ If it is relative, the file is saved in the standard download location with
+ the given name.
+ If it is a null or empty QString, the default file name is used.
+
+ This will emit QWebEngineProfile::downloadRequested() after the download
+ has started.
+*/
+
+void QWebEnginePage::download(const QUrl& url, const QString& filename)
+{
+ Q_D(QWebEnginePage);
+ d->ensureInitialized();
+ d->adapter->download(url, filename);
+}
+
+/*!
+ \fn void QWebEnginePage::loadingChanged(const QWebEngineLoadingInfo &loadingInfo)
+ \since 6.2
+ This signal is emitted when loading the page specified by \a loadingInfo begins,
+ ends, or fails.
+*/
+
+/*!
+ \property QWebEnginePage::loading
+ \since 6.2
+
+ \brief Whether the page is currently loading.
+
+ \sa QWebEngineLoadingInfo, loadStarted, loadFinished
+*/
+bool QWebEnginePage::isLoading() const
+{
+ return d_ptr->isLoading;
+}
+
+void QWebEnginePage::load(const QUrl& url)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->load(url);
+}
+
+/*!
+ \since 5.9
+ Issues the specified \a request and loads the response.
+
+ \sa load(), setUrl(), url(), urlChanged(), QUrl::fromUserInput()
+*/
+void QWebEnginePage::load(const QWebEngineHttpRequest& request)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->load(request);
+}
+
+void QWebEnginePage::toHtml(const std::function<void(const QString &)> &resultCallback) const
+{
+ Q_D(const QWebEnginePage);
+ d->ensureInitialized();
+ quint64 requestId = d->adapter->fetchDocumentMarkup();
+ d->m_stringCallbacks.insert(requestId, resultCallback);
+}
+
+void QWebEnginePage::toPlainText(const std::function<void(const QString &)> &resultCallback) const
+{
+ Q_D(const QWebEnginePage);
+ d->ensureInitialized();
+ quint64 requestId = d->adapter->fetchDocumentInnerText();
+ d->m_stringCallbacks.insert(requestId, resultCallback);
+}
+
+void QWebEnginePage::setHtml(const QString &html, const QUrl &baseUrl)
+{
+ setContent(html.toUtf8(), QStringLiteral("text/html;charset=UTF-8"), baseUrl);
+}
+
+void QWebEnginePage::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->setContent(data, mimeType, baseUrl);
+}
+
+QString QWebEnginePage::title() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->pageTitle();
+}
+
+void QWebEnginePage::setUrl(const QUrl &url)
+{
+ Q_D(QWebEnginePage);
+ if (d->url != url) {
+ d->url = url;
+ emit urlChanged(url);
+ }
+ load(url);
+}
+
+QUrl QWebEnginePage::url() const
+{
+ Q_D(const QWebEnginePage);
+ return d->url;
+}
+
+QUrl QWebEnginePage::requestedUrl() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->requestedUrl();
+}
+
+/*!
+ \property QWebEnginePage::iconUrl
+ \brief The URL of the icon associated with the page currently viewed.
+
+ By default, this property contains an empty URL.
+
+ \sa iconUrlChanged(), icon(), iconChanged()
+*/
+QUrl QWebEnginePage::iconUrl() const
+{
+ Q_D(const QWebEnginePage);
+ return d->iconUrl;
+}
+
+/*!
+ \property QWebEnginePage::icon
+ \brief The icon associated with the page currently viewed.
+ \since 5.7
+
+ By default, this property contains a null icon. If touch icons are disabled
+ (see \c QWebEngineSettings::TouchIconsEnabled), the favicon is provided in two sizes
+ (16x16 and 32x32 pixels) encapsulated in \c{QIcon}. Otherwise, single icon is provided
+ with the largest available size.
+
+ \sa iconChanged(), iconUrl(), iconUrlChanged(), QWebEngineSettings::TouchIconsEnabled
+*/
+QIcon QWebEnginePage::icon() const
+{
+ Q_D(const QWebEnginePage);
+
+ if (d->iconUrl.isEmpty() || !d->adapter->isInitialized())
+ return QIcon();
+
+ return d->adapter->icon();
+}
+
+qreal QWebEnginePage::zoomFactor() const
+{
+ Q_D(const QWebEnginePage);
+ if (d->adapter->isInitialized())
+ return d->adapter->currentZoomFactor();
+ return d->defaultZoomFactor;
+}
+
+void QWebEnginePage::setZoomFactor(qreal factor)
+{
+ Q_D(QWebEnginePage);
+ d->defaultZoomFactor = factor;
+
+ if (d->adapter->isInitialized()) {
+ d->adapter->setZoomFactor(factor);
+ // MEMO: should reset if factor was not applied due to being invalid
+ d->defaultZoomFactor = zoomFactor();
+ }
+}
+
+void QWebEnginePage::runJavaScript(const QString& scriptSource, const std::function<void(const QVariant &)> &resultCallback)
+{
+ Q_D(QWebEnginePage);
+ d->ensureInitialized();
+ if (d->adapter->lifecycleState() == WebContentsAdapter::LifecycleState::Discarded) {
+ qWarning("runJavaScript: disabled in Discarded state");
+ if (resultCallback)
+ resultCallback(QVariant());
+ return;
+ }
+ quint64 requestId = d->adapter->runJavaScriptCallbackResult(scriptSource, QWebEngineScript::MainWorld);
+ if (requestId)
+ d->m_variantCallbacks.insert(requestId, resultCallback);
+ else if (resultCallback)
+ resultCallback(QVariant());
+}
+
+void QWebEnginePage::runJavaScript(const QString& scriptSource, quint32 worldId, const std::function<void(const QVariant &)> &resultCallback)
+{
+ Q_D(QWebEnginePage);
+ d->ensureInitialized();
+ if (d->adapter->lifecycleState() == WebContentsAdapter::LifecycleState::Discarded) {
+ qWarning("runJavaScript: disabled in Discarded state");
+ if (resultCallback)
+ resultCallback(QVariant());
+ return;
+ }
+ if (resultCallback) {
+ quint64 requestId = d->adapter->runJavaScriptCallbackResult(scriptSource, worldId);
+ if (requestId)
+ d->m_variantCallbacks.insert(requestId, resultCallback);
+ else
+ resultCallback(QVariant());
+ } else {
+ d->adapter->runJavaScript(scriptSource, worldId);
+ }
+}
+
+/*!
+ Returns the collection of scripts that are injected into the page.
+
+ In addition, a page might also execute scripts
+ added through QWebEngineProfile::scripts().
+
+ \sa QWebEngineScriptCollection, QWebEngineScript, {Script Injection}
+*/
+
+QWebEngineScriptCollection &QWebEnginePage::scripts()
+{
+ Q_D(QWebEnginePage);
+ return d->scriptCollection;
+}
+
+QWebEnginePage *QWebEnginePage::createWindow(WebWindowType type)
+{
+ Q_D(QWebEnginePage);
+ return d->view ? d->view->createPageForWindow(type) : nullptr;
+}
+
+/*!
+ \since 5.11
+ Returns the page this page is inspecting, if any.
+
+ Returns \c nullptr if this page is not a developer tools page.
+
+ \sa setInspectedPage(), devToolsPage()
+*/
+
+QWebEnginePage *QWebEnginePage::inspectedPage() const
+{
+ Q_D(const QWebEnginePage);
+ return d->inspectedPage;
+}
+
+/*!
+ \since 5.11
+ Navigates this page to an internal URL that is the developer
+ tools of \a page.
+
+ This is the same as calling setDevToolsPage() on \a page
+ with \c this as argument.
+
+ \sa inspectedPage(), setDevToolsPage()
+*/
+
+void QWebEnginePage::setInspectedPage(QWebEnginePage *page)
+{
+ Q_D(QWebEnginePage);
+ if (d->inspectedPage == page)
+ return;
+ QWebEnginePage *oldPage = d->inspectedPage;
+ d->inspectedPage = nullptr;
+ if (oldPage)
+ oldPage->setDevToolsPage(nullptr);
+ d->inspectedPage = page;
+ if (page)
+ page->setDevToolsPage(this);
+}
+
+/*!
+ \since 5.11
+ Returns the page that is hosting the developer tools
+ of this page, if any.
+
+ Returns \c nullptr if no developer tools page is set.
+
+ \sa setDevToolsPage(), inspectedPage()
+*/
+
+QWebEnginePage *QWebEnginePage::devToolsPage() const
+{
+ Q_D(const QWebEnginePage);
+ return d->devToolsPage;
+}
+
+/*!
+ \since 5.11
+ Binds \a devToolsPage to be the developer tools of this page.
+ Triggers \a devToolsPage to navigate to an internal URL
+ with the developer tools.
+
+ This is the same as calling setInspectedPage() on \a devToolsPage
+ with \c this as argument.
+
+ \sa devToolsPage(), setInspectedPage()
+*/
+
+void QWebEnginePage::setDevToolsPage(QWebEnginePage *devToolsPage)
+{
+ Q_D(QWebEnginePage);
+ if (d->devToolsPage == devToolsPage)
+ return;
+ d->ensureInitialized();
+ QWebEnginePage *oldDevTools = d->devToolsPage;
+ d->devToolsPage = nullptr;
+ if (oldDevTools)
+ oldDevTools->setInspectedPage(nullptr);
+ d->devToolsPage = devToolsPage;
+ if (devToolsPage)
+ devToolsPage->setInspectedPage(this);
+ if (d->adapter) {
+ if (devToolsPage)
+ d->adapter->openDevToolsFrontend(devToolsPage->d_ptr->adapter);
+ else
+ d->adapter->closeDevToolsFrontend();
+ }
+}
+
+/*!
+ \since 6.6
+ Returns the id of the developer tools host associated with this page.
+
+ If remote debugging is enabled (see \l{Qt WebEngine Developer Tools}), the id can be used to
+ build the URL to connect to the developer tool websocket:
+ \c{ws://localhost:<debugggin-port>/devtools/page/<id>)}. The websocket can be used to to interact
+ with the page using the \l{https://chromedevtools.github.io/devtools-protocol/}{DevTools
+ Protocol}.
+*/
+
+QString QWebEnginePage::devToolsId() const
+{
+ Q_D(const QWebEnginePage);
+ d->ensureInitialized();
+ return d->adapter->devToolsId();
+}
+
+ASSERT_ENUMS_MATCH(FilePickerController::Open, QWebEnginePage::FileSelectOpen)
+ASSERT_ENUMS_MATCH(FilePickerController::OpenMultiple, QWebEnginePage::FileSelectOpenMultiple)
+ASSERT_ENUMS_MATCH(FilePickerController::UploadFolder, QWebEnginePage::FileSelectUploadFolder)
+ASSERT_ENUMS_MATCH(FilePickerController::Save, QWebEnginePage::FileSelectSave)
+
+// TODO: remove virtuals
+QStringList QWebEnginePage::chooseFiles(FileSelectionMode mode, const QStringList &oldFiles, const QStringList &acceptedMimeTypes)
+{
+ Q_D(const QWebEnginePage);
+ return d->view ? d->view->chooseFiles(mode, oldFiles, acceptedMimeTypes) : QStringList();
+}
+
+void QWebEnginePage::javaScriptAlert(const QUrl &securityOrigin, const QString &msg)
+{
+ Q_UNUSED(securityOrigin);
+ Q_D(const QWebEnginePage);
+ if (d->view)
+ d->view->javaScriptAlert(url(), msg);
+}
+
+bool QWebEnginePage::javaScriptConfirm(const QUrl &securityOrigin, const QString &msg)
+{
+ Q_UNUSED(securityOrigin);
+ Q_D(const QWebEnginePage);
+ return d->view ? d->view->javaScriptConfirm(url(), msg) : false;
+}
+
+bool QWebEnginePage::javaScriptPrompt(const QUrl &securityOrigin, const QString &msg, const QString &defaultValue, QString *result)
+{
+ Q_UNUSED(securityOrigin);
+ Q_D(const QWebEnginePage);
+ return d->view ? d->view->javaScriptPrompt(url(), msg, defaultValue, result) : false;
+}
+
+void QWebEnginePage::javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString &message, int lineNumber, const QString &sourceID)
+{
+ static QLoggingCategory loggingCategory("js", QtWarningMsg);
+ static QByteArray file = sourceID.toUtf8();
+ QMessageLogger logger(file.constData(), lineNumber, nullptr, loggingCategory.categoryName());
+
+ switch (level) {
+ case JavaScriptConsoleMessageLevel::InfoMessageLevel:
+ if (loggingCategory.isInfoEnabled())
+ logger.info().noquote() << message;
+ break;
+ case JavaScriptConsoleMessageLevel::WarningMessageLevel:
+ if (loggingCategory.isWarningEnabled())
+ logger.warning().noquote() << message;
+ break;
+ case JavaScriptConsoleMessageLevel::ErrorMessageLevel:
+ if (loggingCategory.isCriticalEnabled())
+ logger.critical().noquote() << message;
+ break;
+ }
+}
+
+bool QWebEnginePage::acceptNavigationRequest(const QUrl &url, NavigationType type, bool isMainFrame)
+{
+ Q_UNUSED(url);
+ Q_UNUSED(type);
+ Q_UNUSED(isMainFrame);
+ return true;
+}
+
+QPointF QWebEnginePage::scrollPosition() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->lastScrollOffset();
+}
+
+QSizeF QWebEnginePage::contentsSize() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->lastContentsSize();
+}
+
+/*!
+ \fn void QWebEnginePage::newWindowRequested(QWebEngineNewWindowRequest &request)
+ \since 6.2
+
+ This signal is emitted when \a request is issued to load a page in a separate
+ web engine window. This can either be because the current page requested it explicitly
+ through a JavaScript call to \c window.open, or because the user clicked on a link
+ while holding Shift, Ctrl, or a built-in combination that triggers the page to open
+ in a new window.
+
+ The signal is handled by calling openIn() with the new page on the request.
+ If this signal is not handled, the requested load will fail.
+
+ \note This signal is not emitted if \l createWindow() handled the request first.
+
+ \sa createWindow(), QWebEngineNewWindowRequest::openIn()
+*/
+
+/*!
+ \fn void QWebEnginePage::pdfPrintingFinished(const QString &filePath, bool success)
+
+ This signal is emitted when printing the web page into a PDF file has
+ finished.
+ \a filePath will contain the path the file was requested to be created
+ at, and \a success will be \c true if the file was successfully created and
+ \c false otherwise.
+
+ \sa printToPdf()
+*/
+
+/*!
+ Renders the current content of the page into a PDF document and saves it
+ in the location specified in \a filePath.
+ The page size and orientation of the produced PDF document are taken from
+ the values specified in \a layout, while the range of pages printed is
+ taken from \a ranges with the default being printing all pages.
+
+ This method issues an asynchronous request for printing the web page into
+ a PDF and returns immediately.
+ To be informed about the result of the request, connect to the signal
+ pdfPrintingFinished().
+
+ \note The \l QWebEnginePage::Stop web action can be used to interrupt
+ this asynchronous operation.
+
+ If a file already exists at the provided file path, it will be overwritten.
+ \sa pdfPrintingFinished()
+*/
+void QWebEnginePage::printToPdf(const QString &filePath, const QPageLayout &layout, const QPageRanges &ranges)
+{
+#if QT_CONFIG(webengine_printing_and_pdf)
+ Q_D(QWebEnginePage);
+ d->ensureInitialized();
+ d->adapter->printToPDF(layout, ranges, filePath);
+#else
+ Q_UNUSED(filePath);
+ Q_UNUSED(layout);
+ Q_UNUSED(ranges);
+#endif
+}
+
+/*!
+ Renders the current content of the page into a PDF document and returns a byte array containing the PDF data
+ as parameter to \a resultCallback.
+ The page size and orientation of the produced PDF document are taken from the values specified in \a layout,
+ while the range of pages printed is taken from \a ranges with the default being printing all pages.
+
+ The \a resultCallback must take a const reference to a QByteArray as parameter. If printing was successful, this byte array
+ will contain the PDF data, otherwise, the byte array will be empty.
+
+ \note The \l QWebEnginePage::Stop web action can be used to interrupt this operation.
+
+ \warning We guarantee that the callback (\a resultCallback) is always called, but it might be done
+ during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid
+ value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.
+*/
+void QWebEnginePage::printToPdf(const std::function<void(const QByteArray&)> &resultCallback, const QPageLayout &layout, const QPageRanges &ranges)
+{
+ Q_D(QWebEnginePage);
+#if QT_CONFIG(webengine_printing_and_pdf)
+ d->ensureInitialized();
+ quint64 requestId = d->adapter->printToPDFCallbackResult(layout, ranges);
+ d->m_pdfResultCallbacks.insert(requestId, resultCallback);
+#else
+ Q_UNUSED(layout);
+ Q_UNUSED(ranges);
+ if (resultCallback)
+ resultCallback(QByteArray());
+#endif
+}
+
+/*!
+ \internal
+*/
+void QWebEnginePage::acceptAsNewWindow(QWebEngineNewWindowRequest &request)
+{
+ Q_D(QWebEnginePage);
+ auto adapter = request.d_ptr->adapter;
+ QUrl url = request.requestedUrl();
+ if ((!adapter && !url.isValid()) || request.d_ptr->isRequestHandled) {
+ qWarning("Trying to open an empty request, it was either already used or was invalidated."
+ "\nYou must complete the request synchronously within the newWindowRequested signal handler."
+ " If a view hasn't been adopted before returning, the request will be invalidated.");
+ return;
+ }
+
+ if (!adapter)
+ setUrl(url);
+ else if (!d->adoptWebContents(adapter.data()))
+ return;
+
+ QRect geometry = request.requestedGeometry();
+ if (!geometry.isEmpty())
+ emit geometryChangeRequested(geometry);
+
+ request.d_ptr->setHandled();
+}
+
+/*!
+ \enum QWebEnginePage::LifecycleState
+ \since 5.14
+
+ This enum describes the lifecycle state of the page:
+
+ \value Active
+ Normal state.
+ \value Frozen
+ Low CPU usage state where most HTML task sources are suspended.
+ \value Discarded
+ Very low resource usage state where the entire browsing context is discarded.
+
+ \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example}
+*/
+
+/*!
+ \property QWebEnginePage::lifecycleState
+ \since 5.14
+
+ \brief The current lifecycle state of the page.
+
+ The following restrictions are enforced by the setter:
+
+ \list
+ \li A \l{visible} page must remain in the \c{Active} state.
+ \li If the page is being inspected by a \l{devToolsPage} then both pages must
+ remain in the \c{Active} states.
+ \li A page in the \c{Discarded} state can only transition to the \c{Active}
+ state. This will cause a reload of the page.
+ \endlist
+
+ These are the only hard limits on the lifecycle state, but see also
+ \l{recommendedState} for the recommended soft limits.
+
+ \sa recommendedState, {Page Lifecycle API}, {WebEngine Lifecycle Example}
+*/
+
+QWebEnginePage::LifecycleState QWebEnginePage::lifecycleState() const
+{
+ Q_D(const QWebEnginePage);
+ return static_cast<LifecycleState>(d->adapter->lifecycleState());
+}
+
+void QWebEnginePage::setLifecycleState(LifecycleState state)
+{
+ Q_D(QWebEnginePage);
+ d->adapter->setLifecycleState(static_cast<WebContentsAdapterClient::LifecycleState>(state));
+}
+
+/*!
+ \property QWebEnginePage::recommendedState
+ \since 5.14
+
+ \brief The recommended limit for the lifecycle state of the page.
+
+ Setting the lifecycle state to a lower resource usage state than the
+ recommended state may cause side-effects such as stopping background audio
+ playback or loss of HTML form input. Setting the lifecycle state to a higher
+ resource state is however completely safe.
+
+ \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example}
+*/
+
+QWebEnginePage::LifecycleState QWebEnginePage::recommendedState() const
+{
+ Q_D(const QWebEnginePage);
+ return static_cast<LifecycleState>(d->adapter->recommendedState());
+}
+
+/*!
+ \property QWebEnginePage::visible
+ \since 5.14
+
+ \brief Whether the page is considered visible in the Page Visibility API.
+
+ Setting this property changes the \c{Document.hidden} and the
+ \c{Document.visibilityState} properties in JavaScript which web sites can use
+ to voluntarily reduce their resource usage if they are not visible to the
+ user.
+
+ If the page is connected to a \e {view} then this property will be managed
+ automatically by the view according to it's own visibility.
+
+ \sa lifecycleState
+*/
+
+bool QWebEnginePage::isVisible() const
+{
+ Q_D(const QWebEnginePage);
+ return d->adapter->isVisible();
+}
+
+void QWebEnginePage::setVisible(bool visible)
+{
+ Q_D(QWebEnginePage);
+
+ if (!d->adapter->isInitialized()) {
+ // On the one hand, it is too early to initialize here. The application
+ // may call show() before load(), or it may call show() from
+ // createWindow(), and then we would create an unnecessary blank
+ // WebContents here. On the other hand, if the application calls show()
+ // then it expects something to be shown, so we have to initialize.
+ // Therefore we have to delay the initialization via the event loop.
+ if (visible)
+ d->wasShownTimer.start();
+ else
+ d->wasShownTimer.stop();
+ return;
+ }
+
+ d->adapter->setVisible(visible);
+}
+
+/*!
+ \since 6.8
+
+ The main, top-level frame of the page. All other frames on this page are accessible
+ as children of the main frame.
+*/
+QWebEngineFrame QWebEnginePage::mainFrame()
+{
+ Q_D(QWebEnginePage);
+ return QWebEngineFrame(d, d->adapter->mainFrameId());
+}
+
+/*!
+ \since 6.8
+
+ Returns the frame with the given \a name. If there are multiple frames with the same
+ name, which one is returned is arbitrary. If no frame was found, returns \c std::nullopt.
+*/
+std::optional<QWebEngineFrame> QWebEnginePage::findFrameByName(const QString &name)
+{
+ Q_D(QWebEnginePage);
+ if (auto maybeId = d->adapter->findFrameIdByName(name)) {
+ return QWebEngineFrame(d, *maybeId);
+ }
+ return {};
+}
+
+QDataStream &operator<<(QDataStream &stream, const QWebEngineHistory &history)
+{
+ auto adapter = history.d_func()->adapter();
+ if (!adapter->isInitialized())
+ adapter->loadDefault();
+ adapter->serializeNavigationHistory(stream);
+ return stream;
+}
+
+QDataStream &operator>>(QDataStream &stream, QWebEngineHistory &history)
+{
+ static_cast<QWebEnginePagePrivate *>(history.d_func()->client)->recreateFromSerializedHistory(stream);
+ return stream;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginepage.cpp"
diff --git a/src/core/api/qwebenginepage.h b/src/core/api/qwebenginepage.h
new file mode 100644
index 000000000..e5a4e9551
--- /dev/null
+++ b/src/core/api/qwebenginepage.h
@@ -0,0 +1,405 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEPAGE_H
+#define QWEBENGINEPAGE_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtWebEngineCore/qwebengineclientcertificateselection.h>
+#include <QtWebEngineCore/qwebenginedownloadrequest.h>
+#include <QtWebEngineCore/qwebenginequotarequest.h>
+#include <QtWebEngineCore/qwebengineframe.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qurl.h>
+#include <QtGui/qpagelayout.h>
+#include <QtGui/qpageranges.h>
+#include <QtGui/qtgui-config.h>
+
+#include <functional>
+#include <optional>
+
+QT_BEGIN_NAMESPACE
+
+class QAction;
+class QAuthenticator;
+class QContextMenuBuilder;
+class QRect;
+class QVariant;
+class QWebChannel;
+class QWebEngineCertificateError;
+class QWebEngineDesktopMediaRequest;
+class QWebEngineFileSystemAccessRequest;
+class QWebEngineFindTextResult;
+class QWebEngineFullScreenRequest;
+class QWebEngineHistory;
+class QWebEngineHttpRequest;
+class QWebEngineLoadingInfo;
+class QWebEngineNavigationRequest;
+class QWebEngineNewWindowRequest;
+class QWebEnginePagePrivate;
+class QWebEngineProfile;
+class QWebEngineRegisterProtocolHandlerRequest;
+class QWebEngineScriptCollection;
+class QWebEngineSettings;
+class QWebEngineUrlRequestInterceptor;
+class QWebEngineWebAuthUxRequest;
+
+class Q_WEBENGINECORE_EXPORT QWebEnginePage : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QString selectedText READ selectedText)
+ Q_PROPERTY(bool hasSelection READ hasSelection)
+ Q_PROPERTY(QUrl requestedUrl READ requestedUrl)
+ Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor)
+ Q_PROPERTY(QString title READ title NOTIFY titleChanged)
+ Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)
+ Q_PROPERTY(QUrl iconUrl READ iconUrl NOTIFY iconUrlChanged)
+ Q_PROPERTY(QIcon icon READ icon NOTIFY iconChanged)
+ Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor)
+ Q_PROPERTY(QSizeF contentsSize READ contentsSize NOTIFY contentsSizeChanged)
+ Q_PROPERTY(QPointF scrollPosition READ scrollPosition NOTIFY scrollPositionChanged)
+ Q_PROPERTY(bool audioMuted READ isAudioMuted WRITE setAudioMuted NOTIFY audioMutedChanged)
+ Q_PROPERTY(bool recentlyAudible READ recentlyAudible NOTIFY recentlyAudibleChanged)
+ Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged)
+ Q_PROPERTY(LifecycleState lifecycleState READ lifecycleState WRITE setLifecycleState NOTIFY lifecycleStateChanged)
+ Q_PROPERTY(LifecycleState recommendedState READ recommendedState NOTIFY recommendedStateChanged)
+ Q_PROPERTY(qint64 renderProcessPid READ renderProcessPid NOTIFY renderProcessPidChanged)
+ Q_PROPERTY(bool loading READ isLoading NOTIFY loadingChanged FINAL)
+
+public:
+ enum WebAction {
+ NoWebAction = - 1,
+ Back,
+ Forward,
+ Stop,
+ Reload,
+
+ Cut,
+ Copy,
+ Paste,
+
+ Undo,
+ Redo,
+ SelectAll,
+ ReloadAndBypassCache,
+
+ PasteAndMatchStyle,
+
+ OpenLinkInThisWindow,
+ OpenLinkInNewWindow,
+ OpenLinkInNewTab,
+ CopyLinkToClipboard,
+ DownloadLinkToDisk,
+
+ CopyImageToClipboard,
+ CopyImageUrlToClipboard,
+ DownloadImageToDisk,
+
+ CopyMediaUrlToClipboard,
+ ToggleMediaControls,
+ ToggleMediaLoop,
+ ToggleMediaPlayPause,
+ ToggleMediaMute,
+ DownloadMediaToDisk,
+
+ InspectElement,
+ ExitFullScreen,
+ RequestClose,
+ Unselect,
+ SavePage,
+ OpenLinkInNewBackgroundTab,
+ ViewSource,
+
+ ToggleBold,
+ ToggleItalic,
+ ToggleUnderline,
+ ToggleStrikethrough,
+
+ AlignLeft,
+ AlignCenter,
+ AlignRight,
+ AlignJustified,
+ Indent,
+ Outdent,
+
+ InsertOrderedList,
+ InsertUnorderedList,
+
+ ChangeTextDirectionLTR,
+ ChangeTextDirectionRTL,
+
+ WebActionCount
+ };
+ Q_ENUM(WebAction)
+
+ enum FindFlag {
+ FindBackward = 1,
+ FindCaseSensitively = 2,
+ };
+ Q_DECLARE_FLAGS(FindFlags, FindFlag)
+
+ enum WebWindowType {
+ WebBrowserWindow,
+ WebBrowserTab,
+ WebDialog,
+ WebBrowserBackgroundTab
+ };
+ Q_ENUM(WebWindowType)
+
+ enum PermissionPolicy {
+ PermissionUnknown,
+ PermissionGrantedByUser,
+ PermissionDeniedByUser
+ };
+ Q_ENUM(PermissionPolicy)
+
+ // must match WebContentsAdapterClient::NavigationType
+ enum NavigationType {
+ NavigationTypeLinkClicked,
+ NavigationTypeTyped,
+ NavigationTypeFormSubmitted,
+ NavigationTypeBackForward,
+ NavigationTypeReload,
+ NavigationTypeOther,
+ NavigationTypeRedirect,
+ };
+ Q_ENUM(NavigationType)
+
+ enum Feature {
+ Notifications = 0,
+ Geolocation = 1,
+ MediaAudioCapture = 2,
+ MediaVideoCapture,
+ MediaAudioVideoCapture,
+ MouseLock,
+ DesktopVideoCapture,
+ DesktopAudioVideoCapture,
+ ClipboardReadWrite,
+ LocalFontsAccess,
+ };
+ Q_ENUM(Feature)
+
+ // Ex-QWebFrame enum
+
+ enum FileSelectionMode {
+ FileSelectOpen,
+ FileSelectOpenMultiple,
+ FileSelectUploadFolder,
+ FileSelectSave
+ };
+ Q_ENUM(FileSelectionMode)
+
+ // must match WebContentsAdapterClient::JavaScriptConsoleMessageLevel
+ enum JavaScriptConsoleMessageLevel {
+ InfoMessageLevel = 0,
+ WarningMessageLevel,
+ ErrorMessageLevel
+ };
+ Q_ENUM(JavaScriptConsoleMessageLevel)
+
+ // must match WebContentsAdapterClient::RenderProcessTerminationStatus
+ enum RenderProcessTerminationStatus {
+ NormalTerminationStatus = 0,
+ AbnormalTerminationStatus,
+ CrashedTerminationStatus,
+ KilledTerminationStatus
+ };
+ Q_ENUM(RenderProcessTerminationStatus)
+
+ // must match WebContentsAdapterClient::LifecycleState
+ enum class LifecycleState {
+ Active,
+ Frozen,
+ Discarded,
+ };
+ Q_ENUM(LifecycleState)
+
+ explicit QWebEnginePage(QObject *parent = nullptr);
+ QWebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr);
+ ~QWebEnginePage();
+ QWebEngineHistory *history() const;
+
+ bool hasSelection() const;
+ QString selectedText() const;
+
+ QWebEngineProfile *profile() const;
+
+#if QT_CONFIG(action)
+ QAction *action(WebAction action) const;
+#endif
+ virtual void triggerAction(WebAction action, bool checked = false);
+
+ void replaceMisspelledWord(const QString &replacement);
+
+ bool event(QEvent*) override;
+
+ void findText(const QString &subString, FindFlags options = {}, const std::function<void(const QWebEngineFindTextResult &)> &resultCallback = std::function<void(const QWebEngineFindTextResult &)>());
+
+ void setFeaturePermission(const QUrl &securityOrigin, Feature feature, PermissionPolicy policy);
+
+ bool isLoading() const;
+
+ void load(const QUrl &url);
+ void load(const QWebEngineHttpRequest &request);
+ void download(const QUrl &url, const QString &filename = QString());
+ void setHtml(const QString &html, const QUrl &baseUrl = QUrl());
+ void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl());
+
+ void toHtml(const std::function<void(const QString &)> &resultCallback) const;
+ void toPlainText(const std::function<void(const QString &)> &resultCallback) const;
+
+ QString title() const;
+ void setUrl(const QUrl &url);
+ QUrl url() const;
+ QUrl requestedUrl() const;
+ QUrl iconUrl() const;
+ QIcon icon() const;
+
+ qreal zoomFactor() const;
+ void setZoomFactor(qreal factor);
+
+ QPointF scrollPosition() const;
+ QSizeF contentsSize() const;
+
+ void runJavaScript(const QString &scriptSource, const std::function<void(const QVariant &)> &resultCallback);
+ void runJavaScript(const QString &scriptSource, quint32 worldId = 0, const std::function<void(const QVariant &)> &resultCallback = {});
+ QWebEngineScriptCollection &scripts();
+ QWebEngineSettings *settings() const;
+
+ QWebChannel *webChannel() const;
+ void setWebChannel(QWebChannel *, quint32 worldId = 0);
+ QColor backgroundColor() const;
+ void setBackgroundColor(const QColor &color);
+
+ void save(const QString &filePath, QWebEngineDownloadRequest::SavePageFormat format
+ = QWebEngineDownloadRequest::MimeHtmlSaveFormat) const;
+
+ bool isAudioMuted() const;
+ void setAudioMuted(bool muted);
+ bool recentlyAudible() const;
+ qint64 renderProcessPid() const;
+
+ void printToPdf(const QString &filePath,
+ const QPageLayout &layout = QPageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF()),
+ const QPageRanges &ranges = {});
+ void printToPdf(const std::function<void(const QByteArray&)> &resultCallback,
+ const QPageLayout &layout = QPageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF()),
+ const QPageRanges &ranges = {});
+
+ void setInspectedPage(QWebEnginePage *page);
+ QWebEnginePage *inspectedPage() const;
+ void setDevToolsPage(QWebEnginePage *page);
+ QWebEnginePage *devToolsPage() const;
+ QString devToolsId() const;
+
+ void setUrlRequestInterceptor(QWebEngineUrlRequestInterceptor *interceptor);
+
+ LifecycleState lifecycleState() const;
+ void setLifecycleState(LifecycleState state);
+
+ LifecycleState recommendedState() const;
+
+ bool isVisible() const;
+ void setVisible(bool visible);
+
+ QWebEngineFrame mainFrame();
+ std::optional<QWebEngineFrame> findFrameByName(const QString &name);
+
+ void acceptAsNewWindow(QWebEngineNewWindowRequest &request);
+
+Q_SIGNALS:
+ void loadStarted();
+ void loadProgress(int progress);
+ void loadFinished(bool ok);
+ void loadingChanged(const QWebEngineLoadingInfo &loadingInfo);
+
+ void linkHovered(const QString &url);
+ void selectionChanged();
+ void geometryChangeRequested(const QRect &geom);
+ void windowCloseRequested();
+
+ void featurePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature);
+ void featurePermissionRequestCanceled(const QUrl &securityOrigin, QWebEnginePage::Feature feature);
+ void fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest);
+#if QT_DEPRECATED_SINCE(6, 5)
+ QT_DEPRECATED_VERSION_X_6_5("Requesting host quota is no longer supported.")
+ void quotaRequested(QWebEngineQuotaRequest quotaRequest);
+#endif
+ void registerProtocolHandlerRequested(QWebEngineRegisterProtocolHandlerRequest request);
+ void fileSystemAccessRequested(QWebEngineFileSystemAccessRequest request);
+ void selectClientCertificate(QWebEngineClientCertificateSelection clientCertSelection);
+ void authenticationRequired(const QUrl &requestUrl, QAuthenticator *authenticator);
+ void proxyAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *authenticator, const QString &proxyHost);
+
+ void renderProcessTerminated(RenderProcessTerminationStatus terminationStatus, int exitCode);
+ void desktopMediaRequested(const QWebEngineDesktopMediaRequest &request);
+ void certificateError(const QWebEngineCertificateError &certificateError);
+ void navigationRequested(QWebEngineNavigationRequest &request);
+ void newWindowRequested(QWebEngineNewWindowRequest &request);
+
+ // Ex-QWebFrame signals
+ void titleChanged(const QString &title);
+ void urlChanged(const QUrl &url);
+ void iconUrlChanged(const QUrl &url);
+ void iconChanged(const QIcon &icon);
+
+ void scrollPositionChanged(const QPointF &position);
+ void contentsSizeChanged(const QSizeF &size);
+ void audioMutedChanged(bool muted);
+ void recentlyAudibleChanged(bool recentlyAudible);
+ void renderProcessPidChanged(qint64 pid);
+
+ void pdfPrintingFinished(const QString &filePath, bool success);
+ void printRequested();
+
+ void visibleChanged(bool visible);
+
+ void lifecycleStateChanged(LifecycleState state);
+ void recommendedStateChanged(LifecycleState state);
+
+ void findTextFinished(const QWebEngineFindTextResult &result);
+
+ // TODO: fixme / rewrite bindPageToView
+ void _q_aboutToDelete();
+
+ void webAuthUxRequested(QWebEngineWebAuthUxRequest *request);
+
+protected:
+ virtual QWebEnginePage *createWindow(WebWindowType type);
+ virtual QStringList chooseFiles(FileSelectionMode mode, const QStringList &oldFiles,
+ const QStringList &acceptedMimeTypes);
+ virtual void javaScriptAlert(const QUrl &securityOrigin, const QString &msg);
+ virtual bool javaScriptConfirm(const QUrl &securityOrigin, const QString &msg);
+ virtual bool javaScriptPrompt(const QUrl &securityOrigin, const QString &msg,
+ const QString &defaultValue, QString *result);
+ virtual void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level,
+ const QString &message, int lineNumber,
+ const QString &sourceID);
+ virtual bool acceptNavigationRequest(const QUrl &url, NavigationType type, bool isMainFrame);
+
+private:
+ Q_DISABLE_COPY(QWebEnginePage)
+ Q_DECLARE_PRIVATE(QWebEnginePage)
+ QScopedPointer<QWebEnginePagePrivate> d_ptr;
+#if QT_CONFIG(action)
+ Q_PRIVATE_SLOT(d_func(), void _q_webActionTriggered(bool checked))
+#endif
+
+ friend class QContextMenuBuilder;
+ friend class QWebEngineView;
+ friend class QWebEngineViewPrivate;
+#if QT_CONFIG(accessibility)
+ friend class QWebEngineViewAccessible;
+#endif // QT_CONFIG(accessibility)
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(QWebEnginePage::FindFlags)
+
+Q_WEBENGINECORE_EXPORT QDataStream &operator<<(QDataStream &stream,
+ const QWebEngineHistory &history);
+Q_WEBENGINECORE_EXPORT QDataStream &operator>>(QDataStream &stream, QWebEngineHistory &history);
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEPAGE_H
diff --git a/src/core/api/qwebenginepage_p.h b/src/core/api/qwebenginepage_p.h
new file mode 100644
index 000000000..31ace7e9d
--- /dev/null
+++ b/src/core/api/qwebenginepage_p.h
@@ -0,0 +1,225 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEPAGE_P_H
+#define QWEBENGINEPAGE_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qwebenginepage.h"
+
+#include "qwebenginescriptcollection.h"
+#include "web_contents_adapter_client.h"
+
+#include <QtCore/qcompilerdetection.h>
+#include <QtCore/QPointer>
+#include <QtCore/QTimer>
+#include <QtGui/QColor>
+
+namespace QtWebEngineCore {
+class AutofillPopupController;
+class RenderWidgetHostViewQtDelegate;
+class RenderWidgetHostViewQtDelegateClient;
+class RenderWidgetHostViewQtDelegateItem;
+class TouchHandleDrawableDelegate;
+class TouchSelectionMenuController;
+class WebContentsAdapter;
+}
+
+QT_BEGIN_NAMESPACE
+class QPrinter;
+class QWebEngineFindTextResult;
+class QWebEngineHistory;
+class QWebEnginePage;
+class QWebEngineProfile;
+class QWebEngineSettings;
+
+class PageView
+{
+public:
+ virtual void contextMenuRequested(QWebEngineContextMenuRequest *request) = 0;
+ virtual QStringList chooseFiles(QWebEnginePage::FileSelectionMode mode,
+ const QStringList &oldFiles,
+ const QStringList &acceptedMimeTypes) = 0;
+ virtual void
+ showColorDialog(QSharedPointer<QtWebEngineCore::ColorChooserController> controller) = 0;
+ virtual bool showAuthorizationDialog(const QString &title, const QString &message) = 0;
+ virtual void javaScriptAlert(const QUrl &url, const QString &msg) = 0;
+ virtual bool javaScriptConfirm(const QUrl &url, const QString &msg) = 0;
+ virtual bool javaScriptPrompt(const QUrl &url, const QString &msg, const QString &defaultValue,
+ QString *result) = 0;
+ virtual void setToolTip(const QString &toolTipText) = 0;
+ virtual QtWebEngineCore::RenderWidgetHostViewQtDelegate *CreateRenderWidgetHostViewQtDelegate(
+ QtWebEngineCore::RenderWidgetHostViewQtDelegateClient *client) = 0;
+ virtual QtWebEngineCore::RenderWidgetHostViewQtDelegate *CreateRenderWidgetHostViewQtDelegateForPopup(
+ QtWebEngineCore::RenderWidgetHostViewQtDelegateClient *client) = 0;
+ virtual QWebEngineContextMenuRequest *lastContextMenuRequest() const = 0;
+ virtual QWebEnginePage *createPageForWindow(QWebEnginePage::WebWindowType type) = 0;
+ virtual bool isEnabled() const = 0;
+ virtual bool isVisible() const = 0;
+ virtual QRect viewportRect() const = 0;
+ virtual void focusContainer() = 0;
+ virtual void unhandledKeyEvent(QKeyEvent *event) = 0;
+ virtual bool passOnFocus(bool reverse) = 0;
+ virtual QObject *accessibilityParentObject() = 0;
+ virtual void didPrintPage(QPrinter *&printer, QSharedPointer<QByteArray> result) = 0;
+ virtual void didPrintPageToPdf(const QString &filePath, bool success) = 0;
+ virtual void printRequested() = 0;
+ virtual void showAutofillPopup(QtWebEngineCore::AutofillPopupController *controller,
+ const QRect &bounds, bool autoselectFirstSuggestion) = 0;
+ virtual void hideAutofillPopup() = 0;
+ virtual QtWebEngineCore::TouchHandleDrawableDelegate *
+ createTouchHandleDelegate(const QMap<int, QImage> &) = 0;
+ virtual void showTouchSelectionMenu(QtWebEngineCore::TouchSelectionMenuController *,
+ const QRect &) = 0;
+ virtual void hideTouchSelectionMenu() = 0;
+};
+
+class Q_WEBENGINECORE_EXPORT QWebEnginePagePrivate : public QtWebEngineCore::WebContentsAdapterClient
+{
+public:
+ Q_DECLARE_PUBLIC(QWebEnginePage)
+ QWebEnginePage *q_ptr;
+
+ QWebEnginePagePrivate(QWebEngineProfile *profile = nullptr);
+ ~QWebEnginePagePrivate();
+
+ QtWebEngineCore::RenderWidgetHostViewQtDelegate* CreateRenderWidgetHostViewQtDelegate(QtWebEngineCore::RenderWidgetHostViewQtDelegateClient *client) override;
+ QtWebEngineCore::RenderWidgetHostViewQtDelegate* CreateRenderWidgetHostViewQtDelegateForPopup(QtWebEngineCore::RenderWidgetHostViewQtDelegateClient *client) override;
+ void initializationFinished() override;
+ void lifecycleStateChanged(LifecycleState state) override;
+ void recommendedStateChanged(LifecycleState state) override;
+ void visibleChanged(bool visible) override;
+ void titleChanged(const QString &) override;
+ void urlChanged() override;
+ void iconChanged(const QUrl &) override;
+ void loadProgressChanged(int progress) override;
+ void didUpdateTargetURL(const QUrl &) override;
+ void selectionChanged() override;
+ void zoomUpdateIsNeeded() override;
+ void recentlyAudibleChanged(bool recentlyAudible) override;
+ void renderProcessPidChanged(qint64 pid) override;
+ QRectF viewportRect() const override;
+ QColor backgroundColor() const override;
+ void loadStarted(QWebEngineLoadingInfo info) override;
+ void loadCommitted() override { }
+ void loadFinished(QWebEngineLoadingInfo info) override;
+ void focusContainer() override;
+ void unhandledKeyEvent(QKeyEvent *event) override;
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter>
+ adoptNewWindow(QSharedPointer<QtWebEngineCore::WebContentsAdapter> newWebContents,
+ WindowOpenDisposition disposition, bool userGesture,
+ const QRect &initialGeometry, const QUrl &targetUrl) override;
+ bool isBeingAdopted() override;
+ void close() override;
+ void windowCloseRejected() override;
+ void desktopMediaRequested(QtWebEngineCore::DesktopMediaController *) override;
+ void contextMenuRequested(QWebEngineContextMenuRequest *request) override;
+ void navigationRequested(int navigationType, const QUrl &url, bool &accepted, bool isMainFrame, bool hasFormData) override;
+ void requestFullScreenMode(const QUrl &origin, bool fullscreen) override;
+ bool isFullScreenMode() const override;
+ void javascriptDialog(QSharedPointer<QtWebEngineCore::JavaScriptDialogController>) override;
+ void runFileChooser(QSharedPointer<QtWebEngineCore::FilePickerController>) override;
+ void showColorDialog(QSharedPointer<QtWebEngineCore::ColorChooserController>) override;
+ void didRunJavaScript(quint64 requestId, const QVariant &result) override;
+ void didFetchDocumentMarkup(quint64 requestId, const QString &result) override;
+ void didFetchDocumentInnerText(quint64 requestId, const QString &result) override;
+ void didPrintPage(quint64 requestId, QSharedPointer<QByteArray> result) override;
+ void didPrintPageToPdf(const QString &filePath, bool success) override;
+ bool passOnFocus(bool reverse) override;
+ void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString &message,
+ int lineNumber, const QString &sourceID) override;
+ void authenticationRequired(
+ QSharedPointer<QtWebEngineCore::AuthenticationDialogController>) override;
+ void releaseProfile() override;
+ void runMediaAccessPermissionRequest(const QUrl &securityOrigin, MediaRequestFlags requestFlags) override;
+ void runFeaturePermissionRequest(QtWebEngineCore::ProfileAdapter::PermissionType permission, const QUrl &securityOrigin) override;
+ void runMouseLockPermissionRequest(const QUrl &securityOrigin) override;
+ void runRegisterProtocolHandlerRequest(QWebEngineRegisterProtocolHandlerRequest) override;
+ void runFileSystemAccessRequest(QWebEngineFileSystemAccessRequest) override;
+ QObject *accessibilityParentObject() override;
+ QWebEngineSettings *webEngineSettings() const override;
+ void allowCertificateError(const QWebEngineCertificateError &error) override;
+ void selectClientCert(
+ const QSharedPointer<QtWebEngineCore::ClientCertSelectController> &controller) override;
+ void renderProcessTerminated(RenderProcessTerminationStatus terminationStatus, int exitCode) override;
+ void requestGeometryChange(const QRect &geometry, const QRect &frameGeometry) override;
+ void updateScrollPosition(const QPointF &position) override;
+ void updateContentsSize(const QSizeF &size) override;
+ void updateNavigationActions() override;
+ void updateEditActions() override;
+ QObject *dragSource() const override;
+ bool isEnabled() const override;
+ void setToolTip(const QString &toolTipText) override;
+ void printRequested() override;
+ QtWebEngineCore::TouchHandleDrawableDelegate *
+ createTouchHandleDelegate(const QMap<int, QImage> &) override;
+ void showTouchSelectionMenu(QtWebEngineCore::TouchSelectionMenuController *, const QRect &,
+ const QSize &) override;
+ void hideTouchSelectionMenu() override;
+ const QObject *holdingQObject() const override;
+ ClientType clientType() override { return QtWebEngineCore::WebContentsAdapterClient::WidgetsClient; }
+ void findTextFinished(const QWebEngineFindTextResult &result) override;
+ void showAutofillPopup(QtWebEngineCore::AutofillPopupController *controller,
+ const QRect &bounds, bool autoselectFirstSuggestion) override;
+ void hideAutofillPopup() override;
+ void showWebAuthDialog(QWebEngineWebAuthUxRequest *controller) override;
+
+ QtWebEngineCore::ProfileAdapter *profileAdapter() override;
+ QtWebEngineCore::WebContentsAdapter *webContentsAdapter() override;
+
+ void updateAction(QWebEnginePage::WebAction) const;
+ void _q_webActionTriggered(bool checked);
+
+ void createNewWindow(WindowOpenDisposition disposition, bool userGesture, const QUrl &targetUrl);
+ bool adoptWebContents(QtWebEngineCore::WebContentsAdapter *webContents);
+ QtWebEngineCore::WebContentsAdapter *webContents() { return adapter.data(); }
+ void recreateFromSerializedHistory(QDataStream &input);
+
+ void setFullScreenMode(bool);
+ void ensureInitialized() const;
+
+ static QString actionText(int action);
+
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter> adapter;
+ QWebEngineHistory *history;
+ QWebEngineProfile *profile;
+ QWebEngineSettings *settings;
+ PageView *view;
+ QUrl url;
+ bool isLoading;
+ QWebEngineScriptCollection scriptCollection;
+ bool m_isBeingAdopted;
+ QColor m_backgroundColor;
+ bool fullscreenMode;
+ QWebChannel *webChannel;
+ unsigned int webChannelWorldId;
+ QUrl iconUrl;
+ QPointer<QWebEnginePage> inspectedPage;
+ QPointer<QWebEnginePage> devToolsPage;
+ bool defaultAudioMuted;
+ qreal defaultZoomFactor;
+ QTimer wasShownTimer;
+ QtWebEngineCore::RenderWidgetHostViewQtDelegateItem *delegateItem = nullptr;
+#if QT_CONFIG(webengine_printing_and_pdf)
+ QPrinter *currentPrinter = nullptr;
+#endif
+
+ mutable QMap<quint64, std::function<void(const QVariant &)>> m_variantCallbacks;
+ mutable QMap<quint64, std::function<void(const QString &)>> m_stringCallbacks;
+ QMap<quint64, std::function<void(const QByteArray &)>> m_pdfResultCallbacks;
+ mutable QAction *actions[QWebEnginePage::WebActionCount];
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEPAGE_P_H
diff --git a/src/core/api/qwebengineprofile.cpp b/src/core/api/qwebengineprofile.cpp
new file mode 100644
index 000000000..dbb98102c
--- /dev/null
+++ b/src/core/api/qwebengineprofile.cpp
@@ -0,0 +1,947 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineprofile.h"
+#include "qwebengineprofile_p.h"
+#include "qwebengineclienthints.h"
+#include "qwebenginecookiestore.h"
+#include "qwebenginedownloadrequest.h"
+#include "qwebenginedownloadrequest_p.h"
+#include "qwebenginenotification.h"
+#include "qwebenginesettings.h"
+#include "qwebenginescriptcollection.h"
+#include "qwebenginescriptcollection_p.h"
+#include "qtwebenginecoreglobal.h"
+#include "profile_adapter.h"
+#include "visited_links_manager_qt.h"
+#include "web_engine_settings.h"
+
+#include <QDir>
+#include <QtWebEngineCore/qwebengineurlscheme.h>
+
+QT_BEGIN_NAMESPACE
+
+ASSERT_ENUMS_MATCH(QWebEngineDownloadRequest::UnknownSaveFormat, QtWebEngineCore::ProfileAdapterClient::UnknownSavePageFormat)
+ASSERT_ENUMS_MATCH(QWebEngineDownloadRequest::SingleHtmlSaveFormat, QtWebEngineCore::ProfileAdapterClient::SingleHtmlSaveFormat)
+ASSERT_ENUMS_MATCH(QWebEngineDownloadRequest::CompleteHtmlSaveFormat, QtWebEngineCore::ProfileAdapterClient::CompleteHtmlSaveFormat)
+ASSERT_ENUMS_MATCH(QWebEngineDownloadRequest::MimeHtmlSaveFormat, QtWebEngineCore::ProfileAdapterClient::MimeHtmlSaveFormat)
+
+using QtWebEngineCore::ProfileAdapter;
+
+/*!
+ \class QWebEngineProfile
+ \brief The QWebEngineProfile class provides a web engine profile shared by multiple pages.
+ \since 5.5
+
+ \inmodule QtWebEngineCore
+
+ A web engine profile contains settings, scripts, persistent cookie policy, and the list of
+ visited links shared by all web engine pages that belong to the profile.
+
+ All pages that belong to the profile share a common QWebEngineSettings instance, which can
+ be accessed with the settings() method. Likewise, the scripts() method provides access
+ to a common QWebEngineScriptCollection instance.
+
+ Information about visited links is stored together with persistent cookies and other persistent
+ data in a storage returned by storageName(). Persistent data is stored in a subdirectory set by
+ calling setPersistentStoragePath(), and the cache is located in a subdirectory set by calling
+ setCachePath(). The cache type can be set to \e in-memory or \e on-disk by calling
+ setHttpCacheType(). If only the storage name is set, the subdirectories are created and named
+ automatically. If you set any of the values manually, you should do it before creating any
+ pages that belong to the profile.
+
+ The cache can be cleared of links by calling
+ clearVisitedLinks() or clearAllVisitedLinks(). PersistentCookiesPolicy describes whether
+ session and persistent cookies are saved to and restored from memory or disk.
+
+ Profiles can be used to isolate pages from each other. A typical use case is a dedicated
+ \e {off-the-record profile} for a \e {private browsing} mode. Using QWebEngineProfile() without
+ defining a storage name constructs a new off-the-record profile that leaves no record on the
+ local machine, and has no persistent data or cache. The isOffTheRecord() method can be used
+ to check whether a profile is off-the-record.
+
+ The default profile can be accessed by defaultProfile(). It is a built-in profile that all
+ web pages not specifically created with another profile belong to.
+
+ Implementing the QWebEngineUrlRequestInterceptor interface and registering the interceptor on a
+ profile by setUrlRequestInterceptor() enables intercepting, blocking, and modifying URL
+ requests (QWebEngineUrlRequestInfo) before they reach the networking stack of Chromium.
+
+ A QWebEngineUrlSchemeHandler can be registered for a profile by installUrlSchemeHandler()
+ to add support for custom URL schemes. Requests for the scheme are then issued to
+ QWebEngineUrlSchemeHandler::requestStarted() as QWebEngineUrlRequestJob objects.
+
+ Spellchecking HTML form fields can be enabled per profile by using the setSpellCheckEnabled()
+ method and the current languages used for spellchecking can be set by using the
+ setSpellCheckLanguages() method.
+
+*/
+
+/*!
+ \enum QWebEngineProfile::HttpCacheType
+
+ This enum describes the HTTP cache type:
+
+ \value MemoryHttpCache Use an in-memory cache. This is the default if
+ \c off-the-record is set.
+ \value DiskHttpCache Use a disk cache. This is the default if the profile
+ is not \c off-the-record. If set on an \c off-the-record profile will instead
+ set \c MemoryHttpCache.
+ \value NoCache Disable both in-memory and disk caching. (Added in Qt 5.7)
+*/
+
+/*!
+ \enum QWebEngineProfile::PersistentCookiesPolicy
+
+ This enum describes policy for cookie persistency:
+
+ \value NoPersistentCookies
+ Both session and persistent cookies are stored in memory. This is the only setting
+ possible if \c off-the-record is set or no persistent data path is available.
+ \value AllowPersistentCookies
+ Cookies marked persistent are saved to and restored from disk, whereas session cookies
+ are only stored to disk for crash recovery. This is the default setting.
+ \value ForcePersistentCookies
+ Both session and persistent cookies are saved to and restored from disk.
+*/
+
+void QWebEngineProfilePrivate::showNotification(QSharedPointer<QtWebEngineCore::UserNotificationController> &controller)
+{
+ if (m_notificationPresenter) {
+ std::unique_ptr<QWebEngineNotification> notification(new QWebEngineNotification(controller));
+ m_notificationPresenter(std::move(notification));
+ }
+}
+
+/*!
+ \fn QWebEngineProfile::downloadRequested(QWebEngineDownloadRequest *download)
+
+ \since 5.5
+
+ This signal is emitted whenever a download has been triggered.
+ The \a download argument holds the state of the download.
+ The download has to be explicitly accepted with QWebEngineDownloadRequest::accept() or it will be
+ cancelled by default.
+ The download item is parented by the profile. If it is not accepted, it
+ will be deleted immediately after the signal emission.
+ This signal cannot be used with a queued connection.
+
+ \sa QWebEngineDownloadRequest, QWebEnginePage::download()
+*/
+
+/*!
+ \fn QWebEngineProfile::clearHttpCacheCompleted()
+
+ \since 6.7
+
+ This signal is emitted when the clearHttpCache() operation is completed.
+
+ \sa QWebEngineProfile::clearHttpCache()
+*/
+
+QWebEngineProfilePrivate::QWebEngineProfilePrivate(ProfileAdapter* profileAdapter)
+ : m_settings(new QWebEngineSettings())
+ , m_profileAdapter(profileAdapter)
+ , m_scriptCollection(new QWebEngineScriptCollection(
+ new QWebEngineScriptCollectionPrivate(profileAdapter->userResourceController())))
+ , m_clientHints(new QWebEngineClientHints(profileAdapter))
+{
+ m_profileAdapter->addClient(this);
+}
+
+QWebEngineProfilePrivate::~QWebEngineProfilePrivate()
+{
+ if (m_profileAdapter) {
+ // In the case the user sets this profile as the parent of the interceptor
+ // it can be deleted before the browser-context still referencing it is.
+ m_profileAdapter->setRequestInterceptor(nullptr);
+ m_profileAdapter->removeClient(this);
+ }
+
+ if (m_profileAdapter != QtWebEngineCore::ProfileAdapter::defaultProfileAdapter())
+ delete m_profileAdapter;
+ else if (m_profileAdapter)
+ m_profileAdapter->releaseAllWebContentsAdapterClients();
+
+ delete m_settings;
+}
+
+ProfileAdapter* QWebEngineProfilePrivate::profileAdapter() const
+{
+ return m_profileAdapter;
+}
+
+void QWebEngineProfilePrivate::downloadDestroyed(quint32 downloadId)
+{
+ m_ongoingDownloads.remove(downloadId);
+ if (m_profileAdapter)
+ m_profileAdapter->removeDownload(downloadId);
+}
+
+void QWebEngineProfilePrivate::cleanDownloads()
+{
+ for (auto download : m_ongoingDownloads.values()) {
+ if (!download)
+ continue;
+
+ if (!download->isFinished())
+ download->cancel();
+
+ if (m_profileAdapter)
+ m_profileAdapter->removeDownload(download->id());
+ }
+ m_ongoingDownloads.clear();
+}
+
+void QWebEngineProfilePrivate::downloadRequested(DownloadItemInfo &info)
+{
+ Q_Q(QWebEngineProfile);
+
+ Q_ASSERT(!m_ongoingDownloads.contains(info.id));
+ QWebEngineDownloadRequestPrivate *itemPrivate =
+ new QWebEngineDownloadRequestPrivate(m_profileAdapter);
+ itemPrivate->downloadId = info.id;
+ itemPrivate->downloadState = info.accepted ? QWebEngineDownloadRequest::DownloadInProgress
+ : QWebEngineDownloadRequest::DownloadRequested;
+ itemPrivate->startTime = info.startTime;
+ itemPrivate->downloadUrl = info.url;
+ itemPrivate->totalBytes = info.totalBytes;
+ itemPrivate->downloadDirectory = QFileInfo(info.path).path();
+ itemPrivate->downloadFileName = QFileInfo(info.path).fileName();
+ itemPrivate->suggestedFileName = info.suggestedFileName;
+ itemPrivate->mimeType = info.mimeType;
+ itemPrivate->savePageFormat = static_cast<QWebEngineDownloadRequest::SavePageFormat>(info.savePageFormat);
+ itemPrivate->isSavePageDownload = info.isSavePageDownload;
+ if (info.page && info.page->clientType() == QtWebEngineCore::WebContentsAdapterClient::WidgetsClient)
+ itemPrivate->adapterClient = info.page;
+ else
+ itemPrivate->adapterClient = nullptr;
+
+ QWebEngineDownloadRequest *download = new QWebEngineDownloadRequest(itemPrivate, q);
+
+ m_ongoingDownloads.insert(info.id, download);
+ QObject::connect(download, &QWebEngineDownloadRequest::destroyed, q, [id = info.id, this] () { downloadDestroyed(id); });
+
+ Q_EMIT q->downloadRequested(download);
+
+ QWebEngineDownloadRequest::DownloadState state = download->state();
+
+ info.path = QDir(download->downloadDirectory()).filePath(download->downloadFileName());
+ info.savePageFormat = static_cast<QtWebEngineCore::ProfileAdapterClient::SavePageFormat>(
+ download->savePageFormat());
+ info.accepted = state != QWebEngineDownloadRequest::DownloadCancelled;
+
+ if (state == QWebEngineDownloadRequest::DownloadRequested) {
+ // Delete unaccepted downloads.
+ info.accepted = false;
+ delete download;
+ }
+}
+
+void QWebEngineProfilePrivate::downloadUpdated(const DownloadItemInfo &info)
+{
+ if (!m_ongoingDownloads.contains(info.id))
+ return;
+
+ QWebEngineDownloadRequest* download = m_ongoingDownloads.value(info.id).data();
+
+ if (!download) {
+ downloadDestroyed(info.id);
+ return;
+ }
+
+ download->d_func()->update(info);
+}
+
+void QWebEngineProfilePrivate::clearHttpCacheCompleted()
+{
+ Q_Q(QWebEngineProfile);
+ Q_EMIT q->clearHttpCacheCompleted();
+}
+
+void QWebEngineProfilePrivate::addWebContentsAdapterClient(QtWebEngineCore::WebContentsAdapterClient *adapter)
+{
+ Q_ASSERT(m_profileAdapter);
+ m_profileAdapter->addWebContentsAdapterClient(adapter);
+}
+
+void QWebEngineProfilePrivate::removeWebContentsAdapterClient(QtWebEngineCore::WebContentsAdapterClient *adapter)
+{
+ Q_ASSERT(m_profileAdapter);
+ m_profileAdapter->removeWebContentsAdapterClient(adapter);
+}
+
+QtWebEngineCore::WebEngineSettings *QWebEngineProfilePrivate::coreSettings() const
+{
+ return QtWebEngineCore::WebEngineSettings::get(settings());
+}
+
+/*!
+ Constructs a new off-the-record profile with the parent \a parent.
+
+ An off-the-record profile leaves no record on the local machine, and has no persistent data or cache.
+ Thus, the HTTP cache can only be in memory and the cookies can only be non-persistent. Trying to change
+ these settings will have no effect.
+
+ \sa isOffTheRecord()
+*/
+QWebEngineProfile::QWebEngineProfile(QObject *parent)
+ : QObject(parent)
+ , d_ptr(new QWebEngineProfilePrivate(new QtWebEngineCore::ProfileAdapter()))
+{
+ d_ptr->q_ptr = this;
+}
+
+/*!
+ Constructs a new profile with the storage name \a storageName and parent \a parent.
+
+ The storage name must be unique.
+
+ A disk-based QWebEngineProfile should be destroyed on or before application exit, otherwise the cache
+ and persistent data may not be fully flushed to disk.
+
+ \sa storageName()
+*/
+QWebEngineProfile::QWebEngineProfile(const QString &storageName, QObject *parent)
+ : QObject(parent)
+ , d_ptr(new QWebEngineProfilePrivate(new QtWebEngineCore::ProfileAdapter(storageName)))
+{
+ d_ptr->q_ptr = this;
+}
+
+/*! \internal
+*/
+QWebEngineProfile::QWebEngineProfile(QWebEngineProfilePrivate *privatePtr, QObject *parent)
+ : QObject(parent)
+ , d_ptr(privatePtr)
+{
+ d_ptr->q_ptr = this;
+}
+
+/*! \internal
+*/
+QWebEngineProfile::~QWebEngineProfile()
+{
+ d_ptr->cleanDownloads();
+}
+
+/*!
+ Returns the storage name for the profile.
+
+ The storage name is used to give each profile that uses the disk separate subdirectories for persistent data and cache.
+*/
+QString QWebEngineProfile::storageName() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->storageName();
+}
+
+/*!
+ Returns \c true if this is an off-the-record profile that leaves no record on the computer.
+
+ This will force cookies and HTTP cache to be in memory, but also force all other normally
+ persistent data to be stored in memory.
+*/
+bool QWebEngineProfile::isOffTheRecord() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->isOffTheRecord();
+}
+
+/*!
+ Returns the path used to store persistent data for the browser and web content.
+
+ Persistent data includes persistent cookies, HTML5 local storage, and visited links.
+
+ By default, this is below QStandardPaths::DataLocation in a QtWebengine/StorageName specific
+ subdirectory.
+
+ \note Use QStandardPaths::writableLocation(QStandardPaths::DataLocation)
+ to obtain the QStandardPaths::DataLocation path.
+
+ \sa setPersistentStoragePath(), storageName(), QStandardPaths::writableLocation()
+*/
+QString QWebEngineProfile::persistentStoragePath() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->dataPath();
+}
+
+/*!
+ Overrides the default path used to store persistent web engine data.
+
+ If \a path is set to the null string, the default path is restored.
+
+ \sa persistentStoragePath()
+*/
+void QWebEngineProfile::setPersistentStoragePath(const QString &path)
+{
+ const Q_D(QWebEngineProfile);
+ d->profileAdapter()->setDataPath(path);
+}
+
+/*!
+ \since 5.13
+
+ The path to the location where the downloaded files are stored.
+
+ \note By default, the download path is QStandardPaths::DownloadLocation.
+
+ \sa setDownloadPath(), QStandardPaths::writableLocation()
+*/
+QString QWebEngineProfile::downloadPath() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->downloadPath();
+}
+
+/*!
+ \since 5.13
+
+ Overrides the default path used for download location, setting it to \a path.
+
+ If set to the null string, the default path is restored.
+
+ \sa downloadPath()
+*/
+void QWebEngineProfile::setDownloadPath(const QString &path)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setDownloadPath(path);
+}
+
+/*!
+ \since 6.5
+
+ Returns \c true if the push messaging service is enabled.
+ \note By default the push messaging service is disabled.
+
+ \sa setPushServiceEnabled()
+*/
+bool QWebEngineProfile::isPushServiceEnabled() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->pushServiceEnabled();
+}
+
+/*!
+ \since 6.5
+
+ Enables the push messaging service if \a enable is \c true, otherwise disables it.
+
+ \note \QWE uses \l {https://firebase.google.com}{Firebase Cloud Messaging (FCM)}
+ as a browser push service. Therefore, all push messages will go through the
+ Google push service and its respective servers.
+
+ \sa isPushServiceEnabled()
+*/
+void QWebEngineProfile::setPushServiceEnabled(bool enable)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setPushServiceEnabled(enable);
+}
+
+/*!
+ Returns the path used for caches.
+
+ By default, this is below StandardPaths::CacheLocation in a QtWebengine/StorageName specific
+ subdirectory.
+
+ \note Use QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
+ to obtain the QStandardPaths::CacheLocation path.
+
+ \sa setCachePath(), storageName(), QStandardPaths::writableLocation()
+*/
+QString QWebEngineProfile::cachePath() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->cachePath();
+}
+
+/*!
+ Overrides the default path used for disk caches, setting it to \a path.
+
+ If set to the null string, the default path is restored.
+
+ \sa cachePath()
+*/
+void QWebEngineProfile::setCachePath(const QString &path)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setCachePath(path);
+}
+
+/*!
+ Returns the user-agent string sent with HTTP to identify the browser.
+
+ \note On Windows 8.1 and newer, the default user agent will always report
+ "Windows NT 6.2" (Windows 8), unless the application does contain a manifest
+ that declares newer Windows versions as supported.
+
+ \sa setHttpUserAgent(), {windows_manifest} {Windows Application Manifest}
+*/
+QString QWebEngineProfile::httpUserAgent() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->httpUserAgent();
+}
+
+/*!
+ Overrides the default user-agent string, setting it to \a userAgent.
+
+ \sa httpUserAgent()
+*/
+void QWebEngineProfile::setHttpUserAgent(const QString &userAgent)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setHttpUserAgent(userAgent);
+}
+
+/*!
+ Returns the type of HTTP cache used.
+
+ If the profile is off-the-record, MemoryHttpCache is returned.
+
+ \sa setHttpCacheType(), cachePath()
+*/
+QWebEngineProfile::HttpCacheType QWebEngineProfile::httpCacheType() const
+{
+ const Q_D(QWebEngineProfile);
+ return QWebEngineProfile::HttpCacheType(d->profileAdapter()->httpCacheType());
+}
+
+/*!
+ Sets the HTTP cache type to \a httpCacheType.
+
+ \note Setting the \a httpCacheType to NoCache on the profile, which has already some cache
+ entries does not trigger the removal of those entries.
+
+ \sa httpCacheType(), setCachePath(), clearHttpCache()
+*/
+void QWebEngineProfile::setHttpCacheType(QWebEngineProfile::HttpCacheType httpCacheType)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setHttpCacheType(ProfileAdapter::HttpCacheType(httpCacheType));
+}
+
+/*!
+ Sets the value of the Accept-Language HTTP request-header field to \a httpAcceptLanguage.
+
+ \since 5.6
+ */
+void QWebEngineProfile::setHttpAcceptLanguage(const QString &httpAcceptLanguage)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setHttpAcceptLanguage(httpAcceptLanguage);
+}
+
+/*!
+ Returns the value of the Accept-Language HTTP request-header field.
+
+ \since 5.6
+ */
+QString QWebEngineProfile::httpAcceptLanguage() const
+{
+ Q_D(const QWebEngineProfile);
+ return d->profileAdapter()->httpAcceptLanguage();
+}
+
+/*!
+ Returns the current policy for persistent cookies.
+
+ If the profile is off-the-record, NoPersistentCookies is returned.
+
+ \sa setPersistentCookiesPolicy()
+*/
+QWebEngineProfile::PersistentCookiesPolicy QWebEngineProfile::persistentCookiesPolicy() const
+{
+ const Q_D(QWebEngineProfile);
+ return QWebEngineProfile::PersistentCookiesPolicy(d->profileAdapter()->persistentCookiesPolicy());
+}
+
+/*!
+ Sets the policy for persistent cookies to \a newPersistentCookiesPolicy.
+
+ \sa persistentCookiesPolicy()
+*/
+void QWebEngineProfile::setPersistentCookiesPolicy(QWebEngineProfile::PersistentCookiesPolicy newPersistentCookiesPolicy)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setPersistentCookiesPolicy(ProfileAdapter::PersistentCookiesPolicy(newPersistentCookiesPolicy));
+}
+
+/*!
+ Returns the maximum size of the HTTP cache in bytes.
+
+ Will return \c 0 if the size is automatically controlled by QtWebEngine.
+
+ \sa setHttpCacheMaximumSize(), httpCacheType()
+*/
+int QWebEngineProfile::httpCacheMaximumSize() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->httpCacheMaxSize();
+}
+
+/*!
+ Sets the maximum size of the HTTP cache to \a maxSize bytes.
+
+ Setting it to \c 0 means the size will be controlled automatically by QtWebEngine.
+
+ \sa httpCacheMaximumSize(), setHttpCacheType()
+*/
+void QWebEngineProfile::setHttpCacheMaximumSize(int maxSize)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setHttpCacheMaxSize(maxSize);
+}
+
+/*!
+ Returns the cookie store for this profile.
+
+ \since 5.6
+*/
+
+QWebEngineCookieStore* QWebEngineProfile::cookieStore()
+{
+ Q_D(QWebEngineProfile);
+ return d->profileAdapter()->cookieStore();
+}
+
+/*!
+ Registers a request interceptor singleton \a interceptor to intercept URL requests.
+
+ The profile does not take ownership of the pointer.
+
+ \since 5.13
+ \sa QWebEngineUrlRequestInfo QWebEngineUrlRequestInterceptor
+*/
+
+void QWebEngineProfile::setUrlRequestInterceptor(QWebEngineUrlRequestInterceptor *interceptor)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setRequestInterceptor(interceptor);
+}
+
+/*!
+ Clears all links from the visited links database.
+
+ \sa clearVisitedLinks()
+*/
+void QWebEngineProfile::clearAllVisitedLinks()
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->visitedLinksManager()->deleteAllVisitedLinkData();
+}
+
+/*!
+ Clears the links in \a urls from the visited links database.
+
+ \sa clearAllVisitedLinks()
+*/
+void QWebEngineProfile::clearVisitedLinks(const QList<QUrl> &urls)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->visitedLinksManager()->deleteVisitedLinkDataForUrls(urls);
+}
+
+/*!
+ Returns \c true if \a url is considered a visited link by this profile.
+*/
+bool QWebEngineProfile::visitedLinksContainsUrl(const QUrl &url) const
+{
+ Q_D(const QWebEngineProfile);
+ return d->profileAdapter()->visitedLinksManager()->containsUrl(url);
+}
+
+/*!
+ Returns the collection of scripts that are injected into all pages that share
+ this profile.
+
+ \sa QWebEngineScriptCollection, QWebEngineScript, QWebEnginePage::scripts(),
+ {Script Injection}
+*/
+QWebEngineScriptCollection *QWebEngineProfile::scripts() const
+{
+ Q_D(const QWebEngineProfile);
+ return d->m_scriptCollection.data();
+}
+
+/*!
+ Sets the function \a notificationPresenter as responsible for presenting sent notifications.
+
+ \since 5.13
+ \sa QWebEngineNotification
+*/
+void QWebEngineProfile::setNotificationPresenter(std::function<void(std::unique_ptr<QWebEngineNotification>)> notificationPresenter)
+{
+ Q_D(QWebEngineProfile);
+ d->m_notificationPresenter = std::move(notificationPresenter);
+}
+
+/*!
+ \fn QWebEngineProfile::notificationPresenter()
+ Returns the presenter responsible for presenting sent notifications.
+ \since 6.2
+ */
+std::function<void(std::unique_ptr<QWebEngineNotification>)> QWebEngineProfile::notificationPresenter()
+{
+ Q_D(QWebEngineProfile);
+ return d->m_notificationPresenter;
+}
+
+/*!
+ Returns the default profile.
+
+ The default profile is off-the-record.
+
+ \sa storageName()
+*/
+QWebEngineProfile *QWebEngineProfile::defaultProfile()
+{
+ static QWebEngineProfile* profile = new QWebEngineProfile(
+ new QWebEngineProfilePrivate(ProfileAdapter::createDefaultProfileAdapter()),
+ ProfileAdapter::globalQObjectRoot());
+ return profile;
+}
+
+/*!
+ \since 5.8
+
+ Sets the current list of \a languages for the spell checker.
+ Each language should match the name of the \c .bdic dictionary.
+ For example, the language \c en-US will load the \c en-US.bdic
+ dictionary file.
+
+ See the \l {Spellchecker}{Spellchecker feature documentation} for how
+ dictionary files are searched.
+
+ For more information about how to compile \c .bdic dictionaries, see the
+ \l{WebEngine Widgets Spellchecker Example}{Spellchecker Example}.
+
+*/
+void QWebEngineProfile::setSpellCheckLanguages(const QStringList &languages)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setSpellCheckLanguages(languages);
+}
+
+/*!
+ \since 5.8
+
+ Returns the list of languages used by the spell checker.
+*/
+QStringList QWebEngineProfile::spellCheckLanguages() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->spellCheckLanguages();
+}
+
+/*!
+ \since 5.8
+
+ Enables spell checker if \a enable is \c true, otherwise disables it.
+ \sa isSpellCheckEnabled()
+ */
+void QWebEngineProfile::setSpellCheckEnabled(bool enable)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->setSpellCheckEnabled(enable);
+}
+/*!
+ \since 5.8
+
+ Returns \c true if the spell checker is enabled; otherwise returns \c false.
+ \sa setSpellCheckEnabled()
+ */
+bool QWebEngineProfile::isSpellCheckEnabled() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->isSpellCheckEnabled();
+}
+
+/*!
+ Returns the default settings for all pages in this profile.
+*/
+QWebEngineSettings *QWebEngineProfile::settings() const
+{
+ const Q_D(QWebEngineProfile);
+ return d->settings();
+}
+
+/*!
+ \since 5.6
+
+ Returns the custom URL scheme handler register for the URL scheme \a scheme.
+*/
+const QWebEngineUrlSchemeHandler *QWebEngineProfile::urlSchemeHandler(const QByteArray &scheme) const
+{
+ const Q_D(QWebEngineProfile);
+ return d->profileAdapter()->urlSchemeHandler(scheme);
+}
+
+/*!
+ \since 5.6
+
+ Registers a handler \a handler for custom URL scheme \a scheme in the profile.
+
+ It is necessary to first register the scheme with \l
+ QWebEngineUrlScheme::registerScheme at application startup.
+*/
+void QWebEngineProfile::installUrlSchemeHandler(const QByteArray &scheme, QWebEngineUrlSchemeHandler *handler)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->installUrlSchemeHandler(scheme, handler);
+}
+
+/*!
+ \since 5.6
+
+ Removes the custom URL scheme handler \a handler from the profile.
+
+ \sa removeUrlScheme()
+*/
+void QWebEngineProfile::removeUrlSchemeHandler(QWebEngineUrlSchemeHandler *handler)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->removeUrlSchemeHandler(handler);
+}
+
+/*!
+ \since 5.6
+
+ Removes the custom URL scheme \a scheme from the profile.
+
+ \sa removeUrlSchemeHandler()
+*/
+void QWebEngineProfile::removeUrlScheme(const QByteArray &scheme)
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->removeUrlScheme(scheme);
+}
+
+/*!
+ \since 5.6
+
+ Removes all custom URL scheme handlers installed in the profile.
+*/
+void QWebEngineProfile::removeAllUrlSchemeHandlers()
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->removeAllUrlSchemeHandlers();
+}
+
+/*!
+ \since 5.7
+
+ Removes the profile's cache entries.
+
+ \note Make sure that you do not start new navigation or any operation on the profile while
+ the clear operation is in progress. The clearHttpCacheCompleted() signal notifies about the
+ completion.
+
+ \sa QWebEngineProfile::clearHttpCacheCompleted()
+*/
+void QWebEngineProfile::clearHttpCache()
+{
+ Q_D(QWebEngineProfile);
+ d->profileAdapter()->clearHttpCache();
+}
+
+/*!
+ \since 5.13
+
+ Returns the profile's client certificate store.
+*/
+QWebEngineClientCertificateStore *QWebEngineProfile::clientCertificateStore()
+{
+#if QT_CONFIG(ssl)
+ Q_D(QWebEngineProfile);
+ return d->profileAdapter()->clientCertificateStore();
+#else
+ return nullptr;
+#endif
+}
+
+/*!
+ * Requests an icon for a previously loaded page with this profile from the database. Each profile
+ * has its own icon database and it is stored in the persistent storage thus the stored icons
+ * can be accessed without network connection too. The icon must be previously loaded to be
+ * stored in the database.
+ *
+ * \a url specifies the URL of the page what the icon is requested for. In case of more than one
+ * available icons the one with the size closest to \a desiredSizeInPixel will be returned.
+ * The result icon is resized to \a desiredSizeInPixel. If desiredSizeInPixel is 0 the largest
+ * available icon is returned.
+ *
+ * This function is asynchronous and the result is returned by \a iconAvailableCallback.
+ * The callback is called if a request for an icon is performed. If the requested icon is
+ * available, the first parameter (with type QIcon) is the result. Otherwise, it is null.
+ *
+ * The second parameter stores the URL of the requested icon. It is empty if the icon can't be
+ * fetched.
+ *
+ * The third parameter stores the URL of the page which the icon is assigned.
+ *
+ * \note Icons can't be requested with an off-the-record profile.
+ *
+ * \since 6.2
+ * \sa requestIconForIconURL()
+ */
+void QWebEngineProfile::requestIconForPageURL(const QUrl &url, int desiredSizeInPixel,
+ std::function<void(const QIcon &, const QUrl &, const QUrl &)> iconAvailableCallback) const
+{
+ Q_D(const QWebEngineProfile);
+ d->profileAdapter()->requestIconForPageURL(url, desiredSizeInPixel,
+ settings()->testAttribute(QWebEngineSettings::TouchIconsEnabled),
+ iconAvailableCallback);
+}
+
+/*!
+ * Requests an icon with the specified \a url from the database. Each profile has its
+ * own icon database and it is stored in the persistent storage thus the stored icons
+ * can be accessed without network connection too. The icon must be previously loaded to be
+ * stored in the database.
+ *
+ * \a url specifies the URL of the icon. In case of more than one
+ * available icons the one with the size closest to \a desiredSizeInPixel will be returned.
+ * The result icon is resized to \a desiredSizeInPixel. If desiredSizeInPixel is 0 the largest
+ * available icon is returned.
+ *
+ * This function is asynchronous and the result is returned by \a iconAvailableCallback.
+ * The callback is called if a request for an icon is performed. If the requested icon is
+ * available, the first parameter (with type QIcon) is the result. Otherwise, it is null.
+ *
+ * The second parameter stores the URL of the requested icon. It is empty if the icon can't be
+ * fetched.
+ *
+ * \note Icons can't be requested with an off-the-record profile.
+ *
+ * \since 6.2
+ * \sa requestIconForPageURL()
+ */
+void QWebEngineProfile::requestIconForIconURL(const QUrl &url, int desiredSizeInPixel,
+ std::function<void(const QIcon &, const QUrl &)> iconAvailableCallback) const
+{
+ Q_D(const QWebEngineProfile);
+ d->profileAdapter()->requestIconForIconURL(url, desiredSizeInPixel,
+ settings()->testAttribute(QWebEngineSettings::TouchIconsEnabled),
+ iconAvailableCallback);
+}
+
+/*!
+ Return the Client Hints settings associated with this browsing context.
+
+ \since 6.8
+ \sa QWebEngineClientHints
+*/
+QWebEngineClientHints *QWebEngineProfile::clientHints() const
+{
+ Q_D(const QWebEngineProfile);
+ return d->m_clientHints.data();
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qwebengineprofile.cpp"
+#include "moc_qwebengineurlrequestinterceptor.cpp"
diff --git a/src/core/api/qwebengineprofile.h b/src/core/api/qwebengineprofile.h
new file mode 100644
index 000000000..a0027cb81
--- /dev/null
+++ b/src/core/api/qwebengineprofile.h
@@ -0,0 +1,133 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEPROFILE_H
+#define QWEBENGINEPROFILE_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtCore/qstring.h>
+
+#include <functional>
+#include <memory>
+
+QT_BEGIN_NAMESPACE
+
+class QUrl;
+class QWebEngineClientCertificateStore;
+class QWebEngineClientHints;
+class QWebEngineCookieStore;
+class QWebEngineDownloadRequest;
+class QWebEngineNotification;
+class QWebEngineProfilePrivate;
+class QWebEngineSettings;
+class QWebEngineScriptCollection;
+class QWebEngineUrlRequestInterceptor;
+class QWebEngineUrlSchemeHandler;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineProfile : public QObject
+{
+ Q_OBJECT
+public:
+ explicit QWebEngineProfile(QObject *parent = nullptr);
+ explicit QWebEngineProfile(const QString &name, QObject *parent = nullptr);
+ virtual ~QWebEngineProfile();
+
+ enum HttpCacheType {
+ MemoryHttpCache,
+ DiskHttpCache,
+ NoCache
+ };
+ Q_ENUM(HttpCacheType)
+
+ enum PersistentCookiesPolicy {
+ NoPersistentCookies,
+ AllowPersistentCookies,
+ ForcePersistentCookies
+ };
+ Q_ENUM(PersistentCookiesPolicy)
+
+ QString storageName() const;
+ bool isOffTheRecord() const;
+
+ QString persistentStoragePath() const;
+ void setPersistentStoragePath(const QString &path);
+
+ QString cachePath() const;
+ void setCachePath(const QString &path);
+
+ QString httpUserAgent() const;
+ void setHttpUserAgent(const QString &userAgent);
+
+ HttpCacheType httpCacheType() const;
+ void setHttpCacheType(QWebEngineProfile::HttpCacheType);
+
+ void setHttpAcceptLanguage(const QString &httpAcceptLanguage);
+ QString httpAcceptLanguage() const;
+
+ PersistentCookiesPolicy persistentCookiesPolicy() const;
+ void setPersistentCookiesPolicy(QWebEngineProfile::PersistentCookiesPolicy);
+
+ int httpCacheMaximumSize() const;
+ void setHttpCacheMaximumSize(int maxSize);
+
+ QWebEngineCookieStore *cookieStore();
+ void setUrlRequestInterceptor(QWebEngineUrlRequestInterceptor *interceptor);
+
+ void clearAllVisitedLinks();
+ void clearVisitedLinks(const QList<QUrl> &urls);
+ bool visitedLinksContainsUrl(const QUrl &url) const;
+
+ QWebEngineSettings *settings() const;
+ QWebEngineScriptCollection *scripts() const;
+ QWebEngineClientHints *clientHints() const;
+
+ const QWebEngineUrlSchemeHandler *urlSchemeHandler(const QByteArray &) const;
+ void installUrlSchemeHandler(const QByteArray &scheme, QWebEngineUrlSchemeHandler *);
+ void removeUrlScheme(const QByteArray &scheme);
+ void removeUrlSchemeHandler(QWebEngineUrlSchemeHandler *);
+ void removeAllUrlSchemeHandlers();
+
+ void clearHttpCache();
+
+ void setSpellCheckLanguages(const QStringList &languages);
+ QStringList spellCheckLanguages() const;
+ void setSpellCheckEnabled(bool enabled);
+ bool isSpellCheckEnabled() const;
+
+ QString downloadPath() const;
+ void setDownloadPath(const QString &path);
+
+ bool isPushServiceEnabled() const;
+ void setPushServiceEnabled(bool enabled);
+
+ void setNotificationPresenter(std::function<void(std::unique_ptr<QWebEngineNotification>)> notificationPresenter);
+
+ QWebEngineClientCertificateStore *clientCertificateStore();
+
+ void requestIconForPageURL(const QUrl &url, int desiredSizeInPixel, std::function<void(const QIcon &, const QUrl &, const QUrl &)> iconAvailableCallback) const;
+ void requestIconForIconURL(const QUrl &url, int desiredSizeInPixel, std::function<void(const QIcon &, const QUrl &)> iconAvailableCallback) const;
+
+ static QWebEngineProfile *defaultProfile();
+
+Q_SIGNALS:
+ void downloadRequested(QWebEngineDownloadRequest *download);
+ void clearHttpCacheCompleted();
+
+private:
+ Q_DISABLE_COPY(QWebEngineProfile)
+ Q_DECLARE_PRIVATE(QWebEngineProfile)
+ QWebEngineProfile(QWebEngineProfilePrivate *, QObject *parent = nullptr);
+
+ friend class QWebEngineView;
+ std::function<void(std::unique_ptr<QWebEngineNotification>)> notificationPresenter();
+
+ friend class QWebEnginePagePrivate;
+ QScopedPointer<QWebEngineProfilePrivate> d_ptr;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEPROFILE_H
diff --git a/src/core/api/qwebengineprofile_p.h b/src/core/api/qwebengineprofile_p.h
new file mode 100644
index 000000000..0ccc27037
--- /dev/null
+++ b/src/core/api/qwebengineprofile_p.h
@@ -0,0 +1,75 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEPROFILE_P_H
+#define QWEBENGINEPROFILE_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "profile_adapter_client.h"
+
+#include <QMap>
+#include <QPointer>
+#include <QScopedPointer>
+#include <QSharedPointer>
+
+#include <functional>
+
+namespace QtWebEngineCore {
+class ProfileAdapter;
+class WebEngineSettings;
+}
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineClientHints;
+class QWebEngineNotification;
+class QWebEngineProfile;
+class QWebEngineScriptCollection;
+class QWebEngineSettings;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineProfilePrivate : public QtWebEngineCore::ProfileAdapterClient {
+public:
+ Q_DECLARE_PUBLIC(QWebEngineProfile)
+ QWebEngineProfilePrivate(QtWebEngineCore::ProfileAdapter *profileAdapter);
+ ~QWebEngineProfilePrivate();
+
+ QtWebEngineCore::ProfileAdapter *profileAdapter() const;
+ QWebEngineSettings *settings() const { return m_settings; }
+ QtWebEngineCore::WebEngineSettings *coreSettings() const override;
+
+ void downloadDestroyed(quint32 downloadId);
+
+ void cleanDownloads();
+
+ void downloadRequested(DownloadItemInfo &info) override;
+ void downloadUpdated(const DownloadItemInfo &info) override;
+
+ void showNotification(QSharedPointer<QtWebEngineCore::UserNotificationController> &) override;
+ void clearHttpCacheCompleted() override;
+
+ void addWebContentsAdapterClient(QtWebEngineCore::WebContentsAdapterClient *adapter) override;
+ void removeWebContentsAdapterClient(QtWebEngineCore::WebContentsAdapterClient *adapter) override;
+
+private:
+ QWebEngineProfile *q_ptr;
+ QWebEngineSettings *m_settings;
+ QPointer<QtWebEngineCore::ProfileAdapter> m_profileAdapter;
+ QScopedPointer<QWebEngineScriptCollection> m_scriptCollection;
+ QScopedPointer<QWebEngineClientHints> m_clientHints;
+ QMap<quint32, QPointer<QWebEngineDownloadRequest>> m_ongoingDownloads;
+ std::function<void(std::unique_ptr<QWebEngineNotification>)> m_notificationPresenter;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEPROFILE_P_H
diff --git a/src/core/api/qwebenginequotarequest.cpp b/src/core/api/qwebenginequotarequest.cpp
index 7686d0806..3c312216d 100644
--- a/src/core/api/qwebenginequotarequest.cpp
+++ b/src/core/api/qwebenginequotarequest.cpp
@@ -1,113 +1,56 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebenginequotarequest.h"
-#include "quota_request_controller.h"
+#if QT_DEPRECATED_SINCE(6, 5)
QT_BEGIN_NAMESPACE
/*!
\class QWebEngineQuotaRequest
- \brief The QWebEngineQuotaRequest class enables accepting or rejecting
- requests for larger persistent storage than the application's current
- allocation in File System API.
-
\since 5.11
\inmodule QtWebEngineCore
+ \deprecated [6.5] Requesting host quota is no longer supported by Chromium.
+
+ The behavior of navigator.webkitPersistentStorage
+ is identical to navigator.webkitTemporaryStorage.
- This class is used by the QWebEnginePage::quotaRequested() signal to \l
- accept() or \l reject() a request for an increase in the persistent storage
- allocated to the application. The default quota is 0 bytes.
+ For further details, see https://crbug.com/1233525
*/
/*! \fn QWebEngineQuotaRequest::QWebEngineQuotaRequest()
\internal
*/
-/*! \internal */
-QWebEngineQuotaRequest::QWebEngineQuotaRequest(QSharedPointer<QtWebEngineCore::QuotaRequestController> controller)
- : d_ptr(controller)
-{}
-
-/*!
- Rejects a request for larger persistent storage.
-*/
void QWebEngineQuotaRequest::reject()
{
- d_ptr->reject();
}
-/*!
- Accepts a request for larger persistent storage.
-*/
void QWebEngineQuotaRequest::accept()
{
- d_ptr->accept();
}
/*!
\property QWebEngineQuotaRequest::origin
- \brief The URL of the web page that issued the quota request.
*/
QUrl QWebEngineQuotaRequest::origin() const
{
- return d_ptr->origin();
+ return QUrl();
}
/*!
\property QWebEngineQuotaRequest::requestedSize
- \brief Contains the size of the requested disk space in bytes.
*/
qint64 QWebEngineQuotaRequest::requestedSize() const
{
- return d_ptr->requestedSize();
+ return 0;
}
-/*! \fn bool QWebEngineQuotaRequest::operator==(const QWebEngineQuotaRequest &that) const
- Returns \c true if \a that points to the same object as this quota request.
-*/
+QT_END_NAMESPACE
-/*! \fn bool QWebEngineQuotaRequest::operator!=(const QWebEngineQuotaRequest &that) const
- Returns \c true if \a that points to a different object than this request.
-*/
+#endif // QT_DEPRECATED_SINCE(6, 5)
-QT_END_NAMESPACE
+#include "moc_qwebenginequotarequest.cpp"
diff --git a/src/core/api/qwebenginequotarequest.h b/src/core/api/qwebenginequotarequest.h
index da72116c8..f542f5576 100644
--- a/src/core/api/qwebenginequotarequest.h
+++ b/src/core/api/qwebenginequotarequest.h
@@ -1,75 +1,35 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEQUOTAREQUEST_H
#define QWEBENGINEQUOTAREQUEST_H
-#include <QtCore/qsharedpointer.h>
-#include <QtCore/qurl.h>
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-namespace QtWebEngineCore {
-class QuotaPermissionContextQt;
-class QuotaRequestController;
-} // namespace QtWebEngineCore
+#include <QtCore/qurl.h>
+
+#if QT_DEPRECATED_SINCE(6, 5)
QT_BEGIN_NAMESPACE
-class Q_WEBENGINECORE_EXPORT QWebEngineQuotaRequest {
+class Q_WEBENGINECORE_EXPORT QWebEngineQuotaRequest
+{
Q_GADGET
Q_PROPERTY(QUrl origin READ origin CONSTANT FINAL)
Q_PROPERTY(qint64 requestedSize READ requestedSize CONSTANT FINAL)
public:
+ QT_DEPRECATED_VERSION_X_6_5("Requesting host quota is no longer supported.")
QWebEngineQuotaRequest() {}
Q_INVOKABLE void accept();
Q_INVOKABLE void reject();
QUrl origin() const;
qint64 requestedSize() const;
- bool operator==(const QWebEngineQuotaRequest &that) const { return d_ptr == that.d_ptr; }
- bool operator!=(const QWebEngineQuotaRequest &that) const { return d_ptr != that.d_ptr; }
-
-private:
- QWebEngineQuotaRequest(QSharedPointer<QtWebEngineCore::QuotaRequestController>);
- friend QtWebEngineCore::QuotaPermissionContextQt;
- QSharedPointer<QtWebEngineCore::QuotaRequestController> d_ptr;
+ bool operator==(const QWebEngineQuotaRequest &) const { Q_UNREACHABLE(); }
+ bool operator!=(const QWebEngineQuotaRequest &) const { Q_UNREACHABLE(); }
};
QT_END_NAMESPACE
+#endif // QT_DEPRECATED_SINCE(6, 5)
+
#endif // QWEBENGINEQUOTAREQUEST_H
diff --git a/src/core/api/qwebengineregisterprotocolhandlerrequest.cpp b/src/core/api/qwebengineregisterprotocolhandlerrequest.cpp
index a3960327d..3e52302e4 100644
--- a/src/core/api/qwebengineregisterprotocolhandlerrequest.cpp
+++ b/src/core/api/qwebengineregisterprotocolhandlerrequest.cpp
@@ -1,45 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineregisterprotocolhandlerrequest.h"
-#include "register_protocol_handler_request_controller.h"
+#include "custom_handlers/register_protocol_handler_request_controller.h"
QT_BEGIN_NAMESPACE
@@ -50,7 +14,7 @@ QT_BEGIN_NAMESPACE
\brief The QWebEngineRegisterProtocolHandlerRequest class enables
accepting or rejecting requests from the \l registerProtocolHandler API.
- \sa QWebEnginePage::registerProtocolHandlerRequested
+ \sa QWebEnginePage::registerProtocolHandlerRequested()
*/
/*! \fn QWebEngineRegisterProtocolHandlerRequest::QWebEngineRegisterProtocolHandlerRequest()
@@ -114,3 +78,5 @@ QString QWebEngineRegisterProtocolHandlerRequest::scheme() const
*/
QT_END_NAMESPACE
+
+#include "moc_qwebengineregisterprotocolhandlerrequest.cpp"
diff --git a/src/core/api/qwebengineregisterprotocolhandlerrequest.h b/src/core/api/qwebengineregisterprotocolhandlerrequest.h
index 67caf1590..d6e51695e 100644
--- a/src/core/api/qwebengineregisterprotocolhandlerrequest.h
+++ b/src/core/api/qwebengineregisterprotocolhandlerrequest.h
@@ -1,48 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEREGISTERPROTOCOLHANDLERREQUEST_H
#define QWEBENGINEREGISTERPROTOCOLHANDLERREQUEST_H
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+
#include <QtCore/qsharedpointer.h>
#include <QtCore/qurl.h>
-#include <QtWebEngineCore/qtwebenginecoreglobal.h>
namespace QtWebEngineCore {
class RegisterProtocolHandlerRequestController;
@@ -51,7 +16,8 @@ class WebContentsDelegateQt;
QT_BEGIN_NAMESPACE
-class Q_WEBENGINECORE_EXPORT QWebEngineRegisterProtocolHandlerRequest {
+class Q_WEBENGINECORE_EXPORT QWebEngineRegisterProtocolHandlerRequest
+{
Q_GADGET
Q_PROPERTY(QUrl origin READ origin CONSTANT FINAL)
Q_PROPERTY(QString scheme READ scheme CONSTANT FINAL)
diff --git a/src/core/api/qwebenginescript.cpp b/src/core/api/qwebenginescript.cpp
new file mode 100644
index 000000000..29b92a396
--- /dev/null
+++ b/src/core/api/qwebenginescript.cpp
@@ -0,0 +1,283 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginescript.h"
+
+#include "user_script.h"
+#include <QtCore/QDebug>
+#include <QtCore/QFile>
+
+using QtWebEngineCore::UserScript;
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QWebEngineScript
+ \inmodule QtWebEngineCore
+ \since 5.5
+ \brief The QWebEngineScript class encapsulates a JavaScript program.
+
+
+ QWebEngineScript enables the programmatic injection of so called \e {user scripts} in the
+ JavaScript engine at different points, determined by injectionPoint(), during the loading of web
+ contents.
+
+ Scripts can be executed either in the main JavaScript \e world, along with the rest of the
+ JavaScript coming from the web contents, or in their own isolated world. While the DOM of the
+ page can be accessed from any world, JavaScript variables of a function defined in one world are
+ not accessible from a different one. ScriptWorldId provides some predefined IDs for this
+ purpose.
+
+ The following \l Greasemonkey attributes are supported since Qt 5.8:
+ \c @exclude, \c @include, \c @name, \c @match, and \c @run-at.
+
+ Use QWebEnginePage::scripts() and QWebEngineProfile::scripts() to access
+ the collection of scripts associated with a single page or a
+ number of pages sharing the same profile.
+
+ \sa {Script Injection}
+*/
+/*!
+ \enum QWebEngineScript::InjectionPoint
+
+ This enum describes the timing of the script injection:
+
+ \value DocumentCreation The script will be executed as soon as the document is created. This is not suitable for
+ any DOM operation.
+ \value DocumentReady The script will run as soon as the DOM is ready. This is equivalent to the
+ \c DOMContentLoaded event firing in JavaScript.
+ \value Deferred The script will run when the page load finishes, or 500ms after the document is ready, whichever
+ comes first.
+
+*/
+/*!
+ \enum QWebEngineScript::ScriptWorldId
+
+ This enum provides pre-defined world IDs for isolating user scripts into different worlds:
+
+ \value MainWorld The world used by the page's web contents. It can be useful in order to expose custom functionality
+ to web contents in certain scenarios.
+ \value ApplicationWorld The default isolated world used for application level functionality implemented in JavaScript.
+ \value UserWorld The first isolated world to be used by scripts set by users if the application is not making use
+ of more worlds. As a rule of thumb, if that functionality is exposed to the application users, each individual script
+ should probably get its own isolated world.
+
+*/
+
+/*!
+ \fn QWebEngineScript::operator!=(const QWebEngineScript &other) const
+
+ Returns \c true if the script is not equal to \a other, otherwise returns \c false.
+*/
+
+/*!
+ \fn QWebEngineScript::swap(QWebEngineScript &other)
+
+ Swaps the contents of the script with the contents of \a other.
+*/
+
+/*!
+ * Constructs a null script.
+ */
+
+QWebEngineScript::QWebEngineScript()
+ : d(new UserScript)
+{
+}
+
+/*!
+ * Constructs a user script using the contents of \a other.
+ */
+QWebEngineScript::QWebEngineScript(const QWebEngineScript &other)
+ : d(other.d)
+{
+}
+
+/*!
+ Destroys a script.
+*/
+QWebEngineScript::~QWebEngineScript()
+{
+}
+
+/*!
+ Assigns \a other to the script.
+*/
+QWebEngineScript &QWebEngineScript::operator=(const QWebEngineScript &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ * Returns the name of the script. Can be useful to retrieve a particular script from a
+ * QWebEngineScriptCollection.
+ *
+ * \sa QWebEngineScriptCollection::find()
+ */
+
+QString QWebEngineScript::name() const
+{
+ return d->name();
+}
+
+/*!
+ * Sets the script name to \a scriptName.
+ */
+void QWebEngineScript::setName(const QString &scriptName)
+{
+ if (scriptName == name())
+ return;
+ d->setName(scriptName);
+}
+
+
+QUrl QWebEngineScript::sourceUrl() const
+{
+ return d->sourceUrl();
+}
+
+void QWebEngineScript::setSourceUrl(const QUrl &url)
+{
+ if (url == sourceUrl())
+ return;
+
+ d->setSourceUrl(url);
+
+ QFile file;
+ if (url.isLocalFile()) {
+ file.setFileName(url.toLocalFile());
+ } else if (url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) == 0) {
+ if (url.authority().isEmpty())
+ file.setFileName(QLatin1Char(':') + url.path());
+ }
+
+ if (!file.open(QIODevice::ReadOnly)) {
+ qWarning() << "Can't open user script " << url;
+ return;
+ }
+
+ QString source = QString::fromUtf8(file.readAll());
+ setSourceCode(source);
+}
+
+/*!
+ Returns the source of the script.
+ */
+QString QWebEngineScript::sourceCode() const
+{
+ return d->sourceCode();
+}
+
+/*!
+ * Sets the script source to \a scriptSource.
+ */
+void QWebEngineScript::setSourceCode(const QString &scriptSource)
+{
+ if (scriptSource == sourceCode())
+ return;
+ d->setSourceCode(scriptSource);
+}
+
+ASSERT_ENUMS_MATCH(QWebEngineScript::Deferred, UserScript::AfterLoad)
+ASSERT_ENUMS_MATCH(QWebEngineScript::DocumentReady, UserScript::DocumentLoadFinished)
+ASSERT_ENUMS_MATCH(QWebEngineScript::DocumentCreation, UserScript::DocumentElementCreation)
+
+/*!
+ * Returns the point in the loading process at which the script will be executed.
+ * The default value is QWebEngineScript::Deferred.
+ *
+ * \sa setInjectionPoint()
+ */
+QWebEngineScript::InjectionPoint QWebEngineScript::injectionPoint() const
+{
+ return static_cast<QWebEngineScript::InjectionPoint>(d->injectionPoint());
+}
+/*!
+ * Sets the point at which to execute the script to be \a p.
+ *
+ * \sa InjectionPoint
+ */
+void QWebEngineScript::setInjectionPoint(QWebEngineScript::InjectionPoint p)
+{
+ if (p == injectionPoint())
+ return;
+ d->setInjectionPoint(static_cast<UserScript::InjectionPoint>(p));
+}
+
+/*!
+ Returns the world ID defining which world the script is executed in.
+ */
+quint32 QWebEngineScript::worldId() const
+{
+ return d->worldId();
+}
+
+/*!
+ Sets the world ID of the isolated world to \a id when running this script.
+
+ Must be between \c 0 and \c 256.
+ */
+void QWebEngineScript::setWorldId(quint32 id)
+{
+ if (id == d->worldId())
+ return;
+ d->setWorldId(id);
+}
+
+/*!
+ Returns \c true if the script is executed on every frame in the page, or \c false if it is only
+ ran for the main frame.
+ */
+bool QWebEngineScript::runsOnSubFrames() const
+{
+ return d->runsOnSubFrames();
+}
+
+/*!
+ * Executes the script on sub frames in addition to the main frame if \a on returns \c true.
+ */
+void QWebEngineScript::setRunsOnSubFrames(bool on)
+{
+ if (runsOnSubFrames() == on)
+ return;
+ d->setRunsOnSubFrames(on);
+}
+
+/*!
+ Returns \c true if the script is equal to \a other, otherwise returns \c false.
+ */
+bool QWebEngineScript::operator==(const QWebEngineScript &other) const
+{
+ return d == other.d || *d == *(other.d);
+}
+
+QWebEngineScript::QWebEngineScript(const UserScript &coreScript)
+ : d(new UserScript(coreScript))
+{
+}
+
+#ifndef QT_NO_DEBUG_STREAM
+QDebug operator<<(QDebug d, const QWebEngineScript &script)
+{
+ d.nospace() << "QWebEngineScript(" << script.name() << ", ";
+ switch (script.injectionPoint()) {
+ case QWebEngineScript::DocumentCreation:
+ d << "QWebEngineScript::DocumentCreation" << ", ";
+ break;
+ case QWebEngineScript::DocumentReady:
+ d << "QWebEngineScript::DocumentReady" << ", ";
+ break;
+ case QWebEngineScript::Deferred:
+ d << "QWebEngineScript::Deferred" << ", ";
+ break;
+ }
+ d << script.worldId() << ", "
+ << script.runsOnSubFrames() << ", " << script.sourceCode() << ")";
+ return d.space();
+}
+#endif
+
+QT_END_NAMESPACE
+
+#include "moc_qwebenginescript.cpp"
diff --git a/src/core/api/qwebenginescript.h b/src/core/api/qwebenginescript.h
new file mode 100644
index 000000000..9827c4879
--- /dev/null
+++ b/src/core/api/qwebenginescript.h
@@ -0,0 +1,91 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINESCRIPT_H
+#define QWEBENGINESCRIPT_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qurl.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qshareddata.h>
+
+namespace QtWebEngineCore {
+class UserScript;
+} // namespace
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineScript
+{
+
+ Q_GADGET
+ Q_PROPERTY(QString name READ name WRITE setName FINAL)
+ Q_PROPERTY(QUrl sourceUrl READ sourceUrl WRITE setSourceUrl FINAL)
+ Q_PROPERTY(QString sourceCode READ sourceCode WRITE setSourceCode FINAL)
+ Q_PROPERTY(InjectionPoint injectionPoint READ injectionPoint WRITE setInjectionPoint FINAL)
+ Q_PROPERTY(quint32 worldId READ worldId WRITE setWorldId FINAL)
+ Q_PROPERTY(bool runsOnSubFrames READ runsOnSubFrames WRITE setRunsOnSubFrames FINAL)
+
+public:
+
+ enum InjectionPoint {
+ Deferred,
+ DocumentReady,
+ DocumentCreation
+ };
+
+ Q_ENUM(InjectionPoint)
+
+ enum ScriptWorldId {
+ MainWorld = 0,
+ ApplicationWorld,
+ UserWorld
+ };
+
+ Q_ENUM(ScriptWorldId)
+
+ QWebEngineScript();
+ QWebEngineScript(const QWebEngineScript &other);
+ ~QWebEngineScript();
+
+ QWebEngineScript &operator=(const QWebEngineScript &other);
+
+ QString name() const;
+ void setName(const QString &);
+
+ QUrl sourceUrl() const;
+ void setSourceUrl(const QUrl &url);
+
+ QString sourceCode() const;
+ void setSourceCode(const QString &);
+
+ InjectionPoint injectionPoint() const;
+ void setInjectionPoint(InjectionPoint);
+
+ quint32 worldId() const;
+ void setWorldId(quint32);
+
+ bool runsOnSubFrames() const;
+ void setRunsOnSubFrames(bool on);
+
+ bool operator==(const QWebEngineScript &other) const;
+ inline bool operator!=(const QWebEngineScript &other) const
+ { return !operator==(other); }
+ void swap(QWebEngineScript &other) noexcept { d.swap(other.d); }
+
+private:
+ friend class QWebEngineScriptCollectionPrivate;
+ QWebEngineScript(const QtWebEngineCore::UserScript &);
+
+ QSharedDataPointer<QtWebEngineCore::UserScript> d;
+};
+
+Q_DECLARE_TYPEINFO(QWebEngineScript, Q_RELOCATABLE_TYPE);
+
+#ifndef QT_NO_DEBUG_STREAM
+Q_WEBENGINECORE_EXPORT QDebug operator<<(QDebug, const QWebEngineScript &);
+#endif
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINESCRIPT_H
diff --git a/src/core/api/qwebenginescriptcollection.cpp b/src/core/api/qwebenginescriptcollection.cpp
new file mode 100644
index 000000000..7867192b6
--- /dev/null
+++ b/src/core/api/qwebenginescriptcollection.cpp
@@ -0,0 +1,179 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginescriptcollection.h"
+#include "qwebenginescriptcollection_p.h"
+
+#include "renderer_host/user_resource_controller_host.h"
+
+/*!
+ \class QWebEngineScriptCollection
+ \inmodule QtWebEngineCore
+ \since 5.5
+ \brief The QWebEngineScriptCollection class represents a collection of user scripts.
+
+ QWebEngineScriptCollection manages a set of user scripts.
+
+ Use QWebEnginePage::scripts() and QWebEngineProfile::scripts() to access
+ the collection of scripts associated with a single page or a
+ number of pages sharing the same profile.
+
+ \sa {Script Injection}
+*/
+
+/*!
+ \fn QWebEngineScriptCollection::isEmpty() const
+
+ Returns \c true if the collection is empty; otherwise returns \c false.
+*/
+
+QWebEngineScriptCollection::QWebEngineScriptCollection(QWebEngineScriptCollectionPrivate *collectionPrivate)
+ :d(collectionPrivate)
+{
+}
+
+/*!
+ Destroys the collection.
+*/
+QWebEngineScriptCollection::~QWebEngineScriptCollection()
+{
+}
+
+/*!
+ Returns the number of elements in the collection.
+ */
+
+int QWebEngineScriptCollection::count() const
+{
+ return d->count();
+}
+
+/*!
+ Returns \c true if the collection contains an occurrence of \a value; otherwise returns
+ \c false.
+ */
+
+bool QWebEngineScriptCollection::contains(const QWebEngineScript &value) const
+{
+ return d->contains(value);
+}
+
+/*!
+ Returns the list of scripts in the collection with the name \a name, or an empty list if none
+ was found.
+ */
+
+QList<QWebEngineScript> QWebEngineScriptCollection::find(const QString &name) const
+{
+ return d->toList(name);
+}
+/*!
+ Inserts the script \a s into the collection.
+ */
+void QWebEngineScriptCollection::insert(const QWebEngineScript &s)
+{
+ d->insert(s);
+}
+/*!
+ Inserts scripts from the list \a list into the collection.
+ */
+void QWebEngineScriptCollection::insert(const QList<QWebEngineScript> &list)
+{
+ d->reserve(list.size());
+ for (const QWebEngineScript &s : list)
+ d->insert(s);
+}
+
+/*!
+ Removes \a script from the collection.
+
+ Returns \c true if the script was found and successfully removed from the collection; otherwise
+ returns \c false.
+ */
+bool QWebEngineScriptCollection::remove(const QWebEngineScript &script)
+{
+ return d->remove(script);
+}
+
+/*!
+ * Removes all scripts from this collection.
+ */
+void QWebEngineScriptCollection::clear()
+{
+ d->clear();
+}
+
+/*!
+ Returns a list with the values of the scripts used in this collection.
+ */
+QList<QWebEngineScript> QWebEngineScriptCollection::toList() const
+{
+ return d->toList();
+}
+
+
+QWebEngineScriptCollectionPrivate::QWebEngineScriptCollectionPrivate(QtWebEngineCore::UserResourceControllerHost *controller, QSharedPointer<QtWebEngineCore::WebContentsAdapter> webContents)
+ : m_scriptController(controller)
+ , m_contents(webContents)
+{
+}
+
+int QWebEngineScriptCollectionPrivate::count() const
+{
+ return m_scripts.size();
+}
+
+bool QWebEngineScriptCollectionPrivate::contains(const QWebEngineScript &s) const
+{
+ return m_scripts.contains(s);
+}
+
+void QWebEngineScriptCollectionPrivate::insert(const QWebEngineScript &script)
+{
+ m_scripts.append(script);
+ if (!m_contents || m_contents->isInitialized())
+ m_scriptController->addUserScript(*script.d, m_contents.data());
+}
+
+bool QWebEngineScriptCollectionPrivate::remove(const QWebEngineScript &script)
+{
+ if (!m_contents || m_contents->isInitialized())
+ m_scriptController->removeUserScript(*script.d, m_contents.data());
+ return m_scripts.removeAll(script);
+}
+
+QList<QWebEngineScript> QWebEngineScriptCollectionPrivate::toList(const QString &scriptName) const
+{
+ if (scriptName.isNull())
+ return m_scripts;
+
+ QList<QWebEngineScript> ret;
+ for (const QWebEngineScript &script : std::as_const(m_scripts))
+ if (scriptName == script.name())
+ ret.append(script);
+ return ret;
+}
+
+void QWebEngineScriptCollectionPrivate::clear()
+{
+ m_scripts.clear();
+ if (!m_contents || m_contents->isInitialized())
+ m_scriptController->clearAllScripts(m_contents.data());
+}
+
+void QWebEngineScriptCollectionPrivate::reserve(int capacity)
+{
+ m_scripts.reserve(capacity);
+ if (!m_contents || m_contents->isInitialized())
+ m_scriptController->reserve(m_contents.data(), capacity);
+}
+
+void QWebEngineScriptCollectionPrivate::initializationFinished(QSharedPointer<QtWebEngineCore::WebContentsAdapter> contents)
+{
+ Q_ASSERT(m_contents);
+ Q_ASSERT(contents);
+
+ for (const QWebEngineScript &script : std::as_const(m_scripts))
+ m_scriptController->addUserScript(*script.d, contents.data());
+ m_contents = contents;
+}
diff --git a/src/core/api/qwebenginescriptcollection.h b/src/core/api/qwebenginescriptcollection.h
new file mode 100644
index 000000000..a3b3c1c08
--- /dev/null
+++ b/src/core/api/qwebenginescriptcollection.h
@@ -0,0 +1,44 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINESCRIPTCOLLECTION_H
+#define QWEBENGINESCRIPTCOLLECTION_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtWebEngineCore/qwebenginescript.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtCore/qlist.h>
+
+QT_BEGIN_NAMESPACE
+class QWebEngineScriptCollectionPrivate;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineScriptCollection
+{
+public:
+ ~QWebEngineScriptCollection();
+
+ bool isEmpty() const { return !count(); }
+ int count() const;
+ bool contains(const QWebEngineScript &value) const;
+ QList<QWebEngineScript> find(const QString &name) const;
+ void insert(const QWebEngineScript &);
+ void insert(const QList<QWebEngineScript> &list);
+ bool remove(const QWebEngineScript &);
+ void clear();
+
+ QList<QWebEngineScript> toList() const;
+
+private:
+ Q_DISABLE_COPY(QWebEngineScriptCollection)
+ friend class QWebEnginePagePrivate;
+ friend class QWebEngineProfilePrivate;
+ friend class QQuickWebEngineProfilePrivate;
+ friend class QQuickWebEngineViewPrivate;
+ friend class QQuickWebEngineScriptCollectionPrivate;
+ QWebEngineScriptCollection(QWebEngineScriptCollectionPrivate *);
+
+ QScopedPointer<QWebEngineScriptCollectionPrivate> d;
+};
+
+QT_END_NAMESPACE
+#endif // QWEBENGINESCRIPTCOLLECTION_H
diff --git a/src/core/api/qwebenginescriptcollection_p.h b/src/core/api/qwebenginescriptcollection_p.h
new file mode 100644
index 000000000..67b3aa4a7
--- /dev/null
+++ b/src/core/api/qwebenginescriptcollection_p.h
@@ -0,0 +1,51 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINESCRIPTCOLLECTION_P_H
+#define QWEBENGINESCRIPTCOLLECTION_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qtwebenginecoreglobal.h"
+#include "qwebenginescript.h"
+#include "web_contents_adapter.h"
+
+#include <QtCore/QList>
+#include <QtCore/QSharedPointer>
+
+namespace QtWebEngineCore {
+class UserResourceControllerHost;
+} // namespace
+
+QT_BEGIN_NAMESPACE
+class Q_WEBENGINECORE_EXPORT QWebEngineScriptCollectionPrivate
+{
+public:
+ QWebEngineScriptCollectionPrivate(QtWebEngineCore::UserResourceControllerHost *, QSharedPointer<QtWebEngineCore::WebContentsAdapter> = QSharedPointer<QtWebEngineCore::WebContentsAdapter>());
+ int count() const;
+ bool contains(const QWebEngineScript &) const;
+ QList<QWebEngineScript> toList(const QString &scriptName = QString()) const;
+ void initializationFinished(QSharedPointer<QtWebEngineCore::WebContentsAdapter> contents);
+ void insert(const QWebEngineScript &);
+ bool remove(const QWebEngineScript &);
+ void clear();
+ void reserve(int);
+
+private:
+ QtWebEngineCore::UserResourceControllerHost *m_scriptController;
+ QSharedPointer<QtWebEngineCore::WebContentsAdapter> m_contents;
+ QList<QWebEngineScript> m_scripts;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINESCRIPTCOLLECTION__PH
diff --git a/src/core/api/qwebenginesettings.cpp b/src/core/api/qwebenginesettings.cpp
new file mode 100644
index 000000000..f19d8efe5
--- /dev/null
+++ b/src/core/api/qwebenginesettings.cpp
@@ -0,0 +1,121 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginesettings.h"
+#include "web_engine_settings.h"
+
+QT_BEGIN_NAMESPACE
+
+using QtWebEngineCore::WebEngineSettings;
+
+QWebEngineSettings::QWebEngineSettings(QWebEngineSettings *parentSettings)
+ : d_ptr(new WebEngineSettings(parentSettings ? parentSettings->d_ptr.data() : nullptr))
+{
+ d_ptr->scheduleApplyRecursively();
+}
+
+QWebEngineSettings::~QWebEngineSettings() { }
+
+/*
+ Returns the settings for a web engine page that belongs to the default
+ profile. All web pages not specifically created with another profile belong
+ to the default profile.
+
+QWebEngineSettings *QWebEngineSettings::defaultSettings()
+{
+ return QWebEngineProfile::defaultProfile()->settings();
+}
+*/
+
+void QWebEngineSettings::setFontFamily(QWebEngineSettings::FontFamily which, const QString &family)
+{
+ d_ptr->setFontFamily(which, family);
+}
+
+QString QWebEngineSettings::fontFamily(QWebEngineSettings::FontFamily which) const
+{
+ return d_ptr->fontFamily(which);
+}
+
+void QWebEngineSettings::resetFontFamily(QWebEngineSettings::FontFamily which)
+{
+ d_ptr->resetFontFamily(which);
+}
+
+void QWebEngineSettings::setFontSize(QWebEngineSettings::FontSize type, int size)
+{
+ d_ptr->setFontSize(type, size);
+}
+
+int QWebEngineSettings::fontSize(QWebEngineSettings::FontSize type) const
+{
+ return d_ptr->fontSize(type);
+}
+
+void QWebEngineSettings::resetFontSize(QWebEngineSettings::FontSize type)
+{
+ d_ptr->resetFontSize(type);
+}
+
+QString QWebEngineSettings::defaultTextEncoding() const
+{
+ return d_ptr->defaultTextEncoding();
+}
+
+QWebEngineSettings::UnknownUrlSchemePolicy QWebEngineSettings::unknownUrlSchemePolicy() const
+{
+ return d_ptr->unknownUrlSchemePolicy();
+}
+
+void QWebEngineSettings::resetUnknownUrlSchemePolicy()
+{
+ d_ptr->setUnknownUrlSchemePolicy(QWebEngineSettings::InheritedUnknownUrlSchemePolicy);
+}
+
+void QWebEngineSettings::setAttribute(QWebEngineSettings::WebAttribute attr, bool on)
+{
+ d_ptr->setAttribute(attr, on);
+}
+
+bool QWebEngineSettings::testAttribute(QWebEngineSettings::WebAttribute attr) const
+{
+ return d_ptr->testAttribute(attr);
+}
+
+void QWebEngineSettings::resetAttribute(QWebEngineSettings::WebAttribute attr)
+{
+ d_ptr->resetAttribute(attr);
+}
+
+void QWebEngineSettings::setDefaultTextEncoding(const QString &encoding)
+{
+ d_ptr->setDefaultTextEncoding(encoding);
+}
+
+void QWebEngineSettings::setUnknownUrlSchemePolicy(
+ QWebEngineSettings::UnknownUrlSchemePolicy policy)
+{
+ d_ptr->setUnknownUrlSchemePolicy(policy);
+}
+
+void QWebEngineSettings::setParentSettings(QWebEngineSettings *parentSettings)
+{
+ d_ptr->setParentSettings(parentSettings->d_ptr.data());
+}
+
+void QWebEngineSettings::setImageAnimationPolicy(QWebEngineSettings::ImageAnimationPolicy policy)
+{
+ d_ptr->setImageAnimationPolicy(policy);
+}
+
+QWebEngineSettings::ImageAnimationPolicy QWebEngineSettings::imageAnimationPolicy() const
+{
+ return d_ptr->imageAnimationPolicy();
+}
+
+void QWebEngineSettings::resetImageAnimationPolicy()
+{
+ d_ptr->setImageAnimationPolicy(QWebEngineSettings::InheritedImageAnimationPolicy);
+}
+
+QT_END_NAMESPACE
diff --git a/src/core/api/qwebenginesettings.h b/src/core/api/qwebenginesettings.h
new file mode 100644
index 000000000..7f89f1ea6
--- /dev/null
+++ b/src/core/api/qwebenginesettings.h
@@ -0,0 +1,127 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINESETTINGS_H
+#define QWEBENGINESETTINGS_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qscopedpointer.h>
+#include <QtCore/qstring.h>
+
+namespace QtWebEngineCore {
+class WebEngineSettings;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineSettings
+{
+public:
+ enum FontFamily {
+ StandardFont,
+ FixedFont,
+ SerifFont,
+ SansSerifFont,
+ CursiveFont,
+ FantasyFont,
+ PictographFont
+ };
+
+ enum WebAttribute {
+ AutoLoadImages,
+ JavascriptEnabled,
+ JavascriptCanOpenWindows,
+ JavascriptCanAccessClipboard,
+ LinksIncludedInFocusChain,
+ LocalStorageEnabled,
+ LocalContentCanAccessRemoteUrls,
+ XSSAuditingEnabled,
+ SpatialNavigationEnabled,
+ LocalContentCanAccessFileUrls,
+ HyperlinkAuditingEnabled,
+ ScrollAnimatorEnabled,
+ ErrorPageEnabled,
+ PluginsEnabled,
+ FullScreenSupportEnabled,
+ ScreenCaptureEnabled,
+ WebGLEnabled,
+ Accelerated2dCanvasEnabled,
+ AutoLoadIconsForPage,
+ TouchIconsEnabled,
+ FocusOnNavigationEnabled,
+ PrintElementBackgrounds,
+ AllowRunningInsecureContent,
+ AllowGeolocationOnInsecureOrigins,
+ AllowWindowActivationFromJavaScript,
+ ShowScrollBars,
+ PlaybackRequiresUserGesture,
+ WebRTCPublicInterfacesOnly,
+ JavascriptCanPaste,
+ DnsPrefetchEnabled,
+ PdfViewerEnabled,
+ NavigateOnDropEnabled,
+ ReadingFromCanvasEnabled,
+ ForceDarkMode,
+ };
+
+ enum FontSize {
+ MinimumFontSize,
+ MinimumLogicalFontSize,
+ DefaultFontSize,
+ DefaultFixedFontSize
+ };
+
+ enum UnknownUrlSchemePolicy {
+ InheritedUnknownUrlSchemePolicy = 0, // TODO: hide
+ DisallowUnknownUrlSchemes = 1,
+ AllowUnknownUrlSchemesFromUserInteraction,
+ AllowAllUnknownUrlSchemes
+ };
+
+ enum ImageAnimationPolicy {
+ InheritedImageAnimationPolicy = 0,
+ AllowImageAnimation,
+ AnimateImageOnce,
+ DisallowImageAnimation
+ };
+
+public:
+ ~QWebEngineSettings();
+ void setFontFamily(FontFamily which, const QString &family);
+ QString fontFamily(FontFamily which) const;
+ void resetFontFamily(FontFamily which);
+
+ void setFontSize(FontSize type, int size);
+ int fontSize(FontSize type) const;
+ void resetFontSize(FontSize type);
+
+ void setAttribute(WebAttribute attr, bool on);
+ bool testAttribute(WebAttribute attr) const;
+ void resetAttribute(WebAttribute attr);
+
+ void setDefaultTextEncoding(const QString &encoding);
+ QString defaultTextEncoding() const;
+
+ UnknownUrlSchemePolicy unknownUrlSchemePolicy() const;
+ void setUnknownUrlSchemePolicy(UnknownUrlSchemePolicy policy);
+ void resetUnknownUrlSchemePolicy();
+
+ void setImageAnimationPolicy(ImageAnimationPolicy policy);
+ ImageAnimationPolicy imageAnimationPolicy() const;
+ void resetImageAnimationPolicy();
+
+private:
+ explicit QWebEngineSettings(QWebEngineSettings *parentSettings = nullptr);
+ void setParentSettings(QWebEngineSettings *parentSettings);
+ Q_DISABLE_COPY(QWebEngineSettings)
+ typedef ::QtWebEngineCore::WebEngineSettings QWebEngineSettingsPrivate;
+ QScopedPointer<QWebEngineSettingsPrivate> d_ptr;
+ friend class QWebEnginePagePrivate;
+ friend class QWebEngineProfilePrivate;
+ friend class QQuickWebEngineSettings;
+ friend class QtWebEngineCore::WebEngineSettings;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINESETTINGS_H
diff --git a/src/core/api/qwebengineurlrequestinfo.cpp b/src/core/api/qwebengineurlrequestinfo.cpp
index 5ed729f5e..152cf4dd0 100644
--- a/src/core/api/qwebengineurlrequestinfo.cpp
+++ b/src/core/api/qwebengineurlrequestinfo.cpp
@@ -1,72 +1,20 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineurlrequestinfo.h"
#include "qwebengineurlrequestinfo_p.h"
-#include "content/public/common/resource_type.h"
-
#include "web_contents_adapter_client.h"
+#include "net/resource_request_body_qt.h"
+
+#include <memory>
+#include <utility>
QT_BEGIN_NAMESPACE
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeMainFrame, content::ResourceType::kMainFrame)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSubFrame, content::ResourceType::kSubFrame)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeStylesheet, content::ResourceType::kStylesheet)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeScript, content::ResourceType::kScript)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeImage, content::ResourceType::kImage)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeFontResource, content::ResourceType::kFontResource)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSubResource, content::ResourceType::kSubResource)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeObject, content::ResourceType::kObject)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeMedia, content::ResourceType::kMedia)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeWorker, content::ResourceType::kWorker)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSharedWorker, content::ResourceType::kSharedWorker)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePrefetch, content::ResourceType::kPrefetch)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeFavicon, content::ResourceType::kFavicon)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeXhr, content::ResourceType::kXhr)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePing, content::ResourceType::kPing)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeServiceWorker, content::ResourceType::kServiceWorker)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeCspReport, content::ResourceType::kCspReport)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePluginResource, content::ResourceType::kPluginResource)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadMainFrame, content::ResourceType::kNavigationPreloadMainFrame)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadSubFrame, content::ResourceType::kNavigationPreloadSubFrame)
-ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeLast, content::ResourceType::kMaxValue)
+// We changed the type from QScopedPointer to unique_ptr, make sure it's binary compatible:
+static_assert(sizeof(QScopedPointer<QWebEngineUrlRequestInfoPrivate>)
+ == sizeof(std::unique_ptr<QWebEngineUrlRequestInfoPrivate>));
ASSERT_ENUMS_MATCH(QtWebEngineCore::WebContentsAdapterClient::LinkNavigation, QWebEngineUrlRequestInfo::NavigationTypeLink)
ASSERT_ENUMS_MATCH(QtWebEngineCore::WebContentsAdapterClient::TypedNavigation, QWebEngineUrlRequestInfo::NavigationTypeTyped)
@@ -111,7 +59,7 @@ ASSERT_ENUMS_MATCH(QtWebEngineCore::WebContentsAdapterClient::RedirectNavigation
*/
/*!
- \fn QWebEngineUrlRequestInterceptor::QWebEngineUrlRequestInterceptor(QObject * p = 0)
+ \fn QWebEngineUrlRequestInterceptor::QWebEngineUrlRequestInterceptor(QObject *p = nullptr)
Creates a new QWebEngineUrlRequestInterceptor object with \a p as parent.
*/
@@ -129,10 +77,11 @@ ASSERT_ENUMS_MATCH(QtWebEngineCore::WebContentsAdapterClient::RedirectNavigation
execution of this function is finished.
*/
-QWebEngineUrlRequestInfoPrivate::QWebEngineUrlRequestInfoPrivate(QWebEngineUrlRequestInfo::ResourceType resource,
- QWebEngineUrlRequestInfo::NavigationType navigation,
- const QUrl &u, const QUrl &fpu, const QUrl &i,
- const QByteArray &m)
+QWebEngineUrlRequestInfoPrivate::QWebEngineUrlRequestInfoPrivate(
+ QWebEngineUrlRequestInfo::ResourceType resource,
+ QWebEngineUrlRequestInfo::NavigationType navigation, const QUrl &u, const QUrl &fpu,
+ const QUrl &i, const QByteArray &m, QtWebEngineCore::ResourceRequestBody *const rb,
+ const QHash<QByteArray, QByteArray> &h)
: resourceType(resource)
, navigationType(navigation)
, shouldBlockRequest(false)
@@ -142,6 +91,8 @@ QWebEngineUrlRequestInfoPrivate::QWebEngineUrlRequestInfoPrivate(QWebEngineUrlRe
, initiator(i)
, method(m)
, changed(false)
+ , extraHeaders(h)
+ , resourceRequestBody(rb)
{}
/*!
@@ -152,14 +103,17 @@ QWebEngineUrlRequestInfo::QWebEngineUrlRequestInfo() {}
/*!
\internal
*/
-QWebEngineUrlRequestInfo::QWebEngineUrlRequestInfo(QWebEngineUrlRequestInfo &&p) : d_ptr(p.d_ptr.take()) {}
+QWebEngineUrlRequestInfo::QWebEngineUrlRequestInfo(QWebEngineUrlRequestInfo &&p)
+ : d_ptr(std::move(p.d_ptr))
+{
+}
/*!
\internal
*/
QWebEngineUrlRequestInfo &QWebEngineUrlRequestInfo::operator=(QWebEngineUrlRequestInfo &&p)
{
- d_ptr.reset(p.d_ptr.take());
+ d_ptr = std::move(p.d_ptr);
return *this;
}
@@ -205,6 +159,7 @@ QWebEngineUrlRequestInfo::QWebEngineUrlRequestInfo(QWebEngineUrlRequestInfoPriva
\value ResourceTypePluginResource A resource requested by a plugin. (Added in Qt 5.7)
\value ResourceTypeNavigationPreloadMainFrame A main-frame service worker navigation preload request. (Added in Qt 5.14)
\value ResourceTypeNavigationPreloadSubFrame A sub-frame service worker navigation preload request. (Added in Qt 5.14)
+ \value ResourceTypeWebSocket A WebSocket request. (Added in Qt 6.4)
\value ResourceTypeUnknown Unknown request type.
\note For forward compatibility all values not matched should be treated as unknown,
@@ -288,6 +243,20 @@ QByteArray QWebEngineUrlRequestInfo::requestMethod() const
}
/*!
+ Returns a pointer to a QIODevice that gives access to the request body.
+ The request body can contain data for example when the request is
+ a POST request. If the request body is empty the QIODevice reflects this
+ and does not return any data when performing read operations on it.
+
+ \since 6.7
+*/
+
+QIODevice *QWebEngineUrlRequestInfo::requestBody() const
+{
+ return d_ptr->resourceRequestBody;
+}
+
+/*!
\internal
*/
bool QWebEngineUrlRequestInfo::changed() const
@@ -333,8 +302,36 @@ void QWebEngineUrlRequestInfo::block(bool shouldBlock)
void QWebEngineUrlRequestInfo::setHttpHeader(const QByteArray &name, const QByteArray &value)
{
- d_ptr->changed = true;
+ // Headers are case insentive, so we need to compare manually
+ for (auto it = d_ptr->extraHeaders.begin(); it != d_ptr->extraHeaders.end(); ++it) {
+ if (it.key().compare(name, Qt::CaseInsensitive) == 0) {
+ d_ptr->extraHeaders.erase(it);
+ break;
+ }
+ }
+
d_ptr->extraHeaders.insert(name, value);
}
+/*!
+ Returns the request headers.
+ \since 6.5
+ \note Not all headers are visible at this stage as Chromium will add
+ security and proxy headers at a later stage.
+*/
+
+QHash<QByteArray, QByteArray> QWebEngineUrlRequestInfo::httpHeaders() const
+{
+ return d_ptr->extraHeaders;
+}
+
+/*!
+ \internal
+*/
+void QWebEngineUrlRequestInfoPrivate::appendFileToResourceRequestBodyForTest(const QString &path)
+{
+ if (resourceRequestBody)
+ resourceRequestBody->appendFilesForTest(path);
+}
+
QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineurlrequestinfo.h b/src/core/api/qwebengineurlrequestinfo.h
index 21e44d2f1..33efcbeda 100644
--- a/src/core/api/qwebengineurlrequestinfo.h
+++ b/src/core/api/qwebengineurlrequestinfo.h
@@ -1,61 +1,29 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEURLREQUESTINFO_H
#define QWEBENGINEURLREQUESTINFO_H
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-#include <QtCore/qscopedpointer.h>
#include <QtCore/qurl.h>
+#include <QtCore/qiodevice.h>
+
+#include <memory>
namespace QtWebEngineCore {
+class ContentBrowserClientQt;
class InterceptedRequest;
-class NetworkDelegateQt;
-class URLRequestNotification;
} // namespace QtWebEngineCore
+class TestPostRequestInterceptor;
+
QT_BEGIN_NAMESPACE
class QWebEngineUrlRequestInfoPrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestInfo {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestInfo
+{
public:
enum ResourceType {
ResourceTypeMainFrame = 0, // top level page
@@ -82,6 +50,7 @@ public:
#ifndef Q_QDOC
ResourceTypeLast = ResourceTypeNavigationPreloadSubFrame,
#endif
+ ResourceTypeWebSocket = 254,
ResourceTypeUnknown = 255
};
@@ -102,16 +71,18 @@ public:
QUrl firstPartyUrl() const;
QUrl initiator() const;
QByteArray requestMethod() const;
+ QIODevice *requestBody() const;
bool changed() const;
void block(bool shouldBlock);
void redirect(const QUrl &url);
void setHttpHeader(const QByteArray &name, const QByteArray &value);
+ QHash<QByteArray, QByteArray> httpHeaders() const;
private:
- friend class QtWebEngineCore::NetworkDelegateQt;
- friend class QtWebEngineCore::URLRequestNotification;
+ friend class QtWebEngineCore::ContentBrowserClientQt;
friend class QtWebEngineCore::InterceptedRequest;
+ friend class ::TestPostRequestInterceptor;
Q_DISABLE_COPY(QWebEngineUrlRequestInfo)
Q_DECLARE_PRIVATE(QWebEngineUrlRequestInfo)
@@ -122,7 +93,7 @@ private:
QWebEngineUrlRequestInfo(QWebEngineUrlRequestInfo &&p);
QWebEngineUrlRequestInfo &operator=(QWebEngineUrlRequestInfo &&p);
~QWebEngineUrlRequestInfo();
- QScopedPointer<QWebEngineUrlRequestInfoPrivate> d_ptr;
+ std::unique_ptr<QWebEngineUrlRequestInfoPrivate> d_ptr;
};
QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineurlrequestinfo_p.h b/src/core/api/qwebengineurlrequestinfo_p.h
index 206104ec9..95cc72362 100644
--- a/src/core/api/qwebengineurlrequestinfo_p.h
+++ b/src/core/api/qwebengineurlrequestinfo_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEURLREQUESTINFO_P_H
#define QWEBENGINEURLREQUESTINFO_P_H
@@ -63,14 +27,22 @@ namespace net {
class URLRequest;
}
+namespace QtWebEngineCore {
+class ResourceRequestBody;
+}
+
QT_BEGIN_NAMESPACE
-class QWebEngineUrlRequestInfoPrivate {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestInfoPrivate
+{
Q_DECLARE_PUBLIC(QWebEngineUrlRequestInfo)
public:
QWebEngineUrlRequestInfoPrivate(QWebEngineUrlRequestInfo::ResourceType resource,
- QWebEngineUrlRequestInfo::NavigationType navigation, const QUrl &u, const QUrl &fpu,
- const QUrl &i, const QByteArray &m);
+ QWebEngineUrlRequestInfo::NavigationType navigation,
+ const QUrl &u, const QUrl &fpu, const QUrl &i,
+ const QByteArray &m,
+ QtWebEngineCore::ResourceRequestBody *const rb = nullptr,
+ const QHash<QByteArray, QByteArray> &h = {});
QWebEngineUrlRequestInfo::ResourceType resourceType;
QWebEngineUrlRequestInfo::NavigationType navigationType;
@@ -82,8 +54,11 @@ public:
const QByteArray method;
bool changed;
QHash<QByteArray, QByteArray> extraHeaders;
+ QtWebEngineCore::ResourceRequestBody *const resourceRequestBody;
QWebEngineUrlRequestInfo *q_ptr;
+
+ void appendFileToResourceRequestBodyForTest(const QString &path);
};
QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineurlrequestinterceptor.cpp b/src/core/api/qwebengineurlrequestinterceptor.cpp
new file mode 100644
index 000000000..c3cd49a5b
--- /dev/null
+++ b/src/core/api/qwebengineurlrequestinterceptor.cpp
@@ -0,0 +1,11 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebengineurlrequestinterceptor.h"
+
+QT_BEGIN_NAMESPACE
+
+// Has to stay empty till Qt7
+QWebEngineUrlRequestInterceptor::~QWebEngineUrlRequestInterceptor() = default;
+
+QT_END_NAMESPACE
diff --git a/src/core/api/qwebengineurlrequestinterceptor.h b/src/core/api/qwebengineurlrequestinterceptor.h
index 4d3020306..2ca8ee914 100644
--- a/src/core/api/qwebengineurlrequestinterceptor.h
+++ b/src/core/api/qwebengineurlrequestinterceptor.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENINGEURLREQUESTINTERCEPTOR_H
#define QWEBENINGEURLREQUESTINTERCEPTOR_H
@@ -43,19 +7,16 @@
#include <QtWebEngineCore/qtwebenginecoreglobal.h>
#include <QtWebEngineCore/qwebengineurlrequestinfo.h>
-#include <QtCore/qbytearray.h>
-#include <QtCore/qhash.h>
#include <QtCore/qobject.h>
-#include <QtCore/qurl.h>
QT_BEGIN_NAMESPACE
-class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestInterceptor : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestInterceptor : public QObject
+{
Q_OBJECT
- Q_DISABLE_COPY(QWebEngineUrlRequestInterceptor)
public:
explicit QWebEngineUrlRequestInterceptor(QObject *p = nullptr) : QObject(p) {}
-
+ ~QWebEngineUrlRequestInterceptor() override;
virtual void interceptRequest(QWebEngineUrlRequestInfo &info) = 0;
};
diff --git a/src/core/api/qwebengineurlrequestjob.cpp b/src/core/api/qwebengineurlrequestjob.cpp
index 3bb9d1732..b3997a49d 100644
--- a/src/core/api/qwebengineurlrequestjob.cpp
+++ b/src/core/api/qwebengineurlrequestjob.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineurlrequestjob.h"
@@ -148,7 +112,36 @@ QMap<QByteArray, QByteArray> QWebEngineUrlRequestJob::requestHeaders() const
}
/*!
- Replies to the request with \a device and the MIME type \a contentType.
+ Returns a pointer to a QIODevice that gives access to the request body.
+ The request body can contain data for example when the request is
+ a POST request. If the request body is empty the QIODevice reflects this
+ and does not return any data when performing read operations on it.
+
+ \since 6.7
+ \sa QIODevice
+*/
+QIODevice *QWebEngineUrlRequestJob::requestBody() const
+{
+ return d_ptr->requestBody();
+}
+
+/*!
+ \since 6.6
+ Set \a additionalResponseHeaders. These additional headers of the response
+ are only used when QWebEngineUrlRequestJob::reply(const QByteArray&, QIODevice*)
+ is called.
+*/
+void QWebEngineUrlRequestJob::setAdditionalResponseHeaders(
+ const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders) const
+{
+ d_ptr->setAdditionalResponseHeaders(additionalResponseHeaders);
+}
+
+/*!
+ Replies to the request with \a device and the content type \a contentType.
+ Content type is similar to the HTTP Content-Type header, and can either be
+ a MIME type, or a MIME type and charset encoding combined like this:
+ "text/html; charset=utf-8".
The user has to be aware that \a device will be used on another thread
until the job is deleted. In case simultaneous access from the main thread
@@ -189,3 +182,5 @@ void QWebEngineUrlRequestJob::redirect(const QUrl &url)
}
QT_END_NAMESPACE
+
+#include "moc_qwebengineurlrequestjob.cpp"
diff --git a/src/core/api/qwebengineurlrequestjob.h b/src/core/api/qwebengineurlrequestjob.h
index 6d4a9e734..a0cb48b8b 100644
--- a/src/core/api/qwebengineurlrequestjob.h
+++ b/src/core/api/qwebengineurlrequestjob.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEURLREQUESTJOB_H
#define QWEBENGINEURLREQUESTJOB_H
@@ -55,7 +19,8 @@ QT_BEGIN_NAMESPACE
class QIODevice;
-class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestJob : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlRequestJob : public QObject
+{
Q_OBJECT
public:
~QWebEngineUrlRequestJob();
@@ -74,10 +39,13 @@ public:
QByteArray requestMethod() const;
QUrl initiator() const;
QMap<QByteArray, QByteArray> requestHeaders() const;
+ QIODevice *requestBody() const;
void reply(const QByteArray &contentType, QIODevice *device);
void fail(Error error);
void redirect(const QUrl &url);
+ void setAdditionalResponseHeaders(
+ const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders) const;
private:
QWebEngineUrlRequestJob(QtWebEngineCore::URLRequestCustomJobDelegate *);
diff --git a/src/core/api/qwebengineurlscheme.cpp b/src/core/api/qwebengineurlscheme.cpp
index f73992c6b..3093c2b8e 100644
--- a/src/core/api/qwebengineurlscheme.cpp
+++ b/src/core/api/qwebengineurlscheme.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineurlscheme.h"
@@ -171,12 +135,12 @@ public:
Indicates that the URL scheme provides access to local resources. The purpose
of this flag is to prevent network content from accessing local resources.
Only schemes with the \c LocalAccessAllowed flag may load resources from a
- scheme with the \c Local flag. The only builtin schemes with this flag are \c
- file and \c qrc.
+ scheme with the \c LocalScheme flag. The only builtin scheme with this flag is \c
+ file.
\value LocalAccessAllowed
Indicates that content from this scheme should be allowed to load resources
- from schemes with the \c Local flag.
+ from schemes with the \c LocalScheme flag.
\value NoAccessAllowed
Indicates that all content from this scheme should be forced to have unique
@@ -194,10 +158,15 @@ public:
\value CorsEnabled
Enables cross-origin resource sharing (CORS) for this scheme. This flag is
- required in order to, for example, use the scheme with the \l
- {https://fetch.spec.whatwg.org/}{Fetch API}, or to deliver CSS fonts to a
- different origin. The appropriate CORS headers are generated automatically by
- the QWebEngineUrlRequestJob class. (Added in Qt 5.14)
+ required in order for content to be loaded by documents of a different origin,
+ this includes access from other schemes. The appropriate CORS headers are
+ generated automatically by the QWebEngineUrlRequestJob class. By default only
+ \c http and \c https are CORS enabled. (Added in Qt 5.14)
+
+ \value [since 6.6] FetchApiAllowed
+ Enables a URL scheme to be used by the HTML5 fetch API and \c XMLHttpRequest.send with
+ a body. By default only \c http and \c https can be send to using the Fetch API or with
+ an XMLHttpRequest with a body.
*/
QWebEngineUrlScheme::QWebEngineUrlScheme(QWebEngineUrlSchemePrivate *d) : d(d) {}
@@ -415,3 +384,5 @@ void QWebEngineUrlScheme::lockSchemes()
}
QT_END_NAMESPACE
+
+#include "moc_qwebengineurlscheme.cpp"
diff --git a/src/core/api/qwebengineurlscheme.h b/src/core/api/qwebengineurlscheme.h
index ecac44184..35498a68e 100644
--- a/src/core/api/qwebengineurlscheme.h
+++ b/src/core/api/qwebengineurlscheme.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEURLSCHEME_H
#define QWEBENGINEURLSCHEME_H
@@ -54,7 +18,8 @@ QT_BEGIN_NAMESPACE
class QWebEngineUrlSchemePrivate;
-class Q_WEBENGINECORE_EXPORT QWebEngineUrlScheme {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlScheme
+{
Q_GADGET
public:
enum class Syntax {
@@ -77,6 +42,7 @@ public:
ViewSourceAllowed = 0x20,
ContentSecurityPolicyIgnored = 0x40,
CorsEnabled = 0x80,
+ FetchApiAllowed = 0x100,
};
Q_DECLARE_FLAGS(Flags, Flag)
Q_FLAG(Flags)
diff --git a/src/core/api/qwebengineurlschemehandler.cpp b/src/core/api/qwebengineurlschemehandler.cpp
index aecee5044..e01ecef49 100644
--- a/src/core/api/qwebengineurlschemehandler.cpp
+++ b/src/core/api/qwebengineurlschemehandler.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwebengineurlschemehandler.h"
@@ -48,9 +12,23 @@ QT_BEGIN_NAMESPACE
\brief The QWebEngineUrlSchemeHandler class is a base class for handling custom URL schemes.
\since 5.6
+ A custom scheme handler is, broadly speaking, similar to a web application
+ served over HTTP. However, because custom schemes are integrated directly
+ into the web engine, they have the advantage in terms of efficiency and security:
+ There is no need for generating and parsing HTTP messages or for transferring data
+ over sockets, nor any way to intercept or monitor the traffic.
+
To implement a custom URL scheme for QtWebEngine, you first have to create an instance of
QWebEngineUrlScheme and register it using QWebEngineUrlScheme::registerScheme().
+ As custom schemes are integrated directly into the web engine, they do not
+ necessarily need to follow the standard security rules which apply to
+ ordinary web content. Depending on the chosen configuration, content served
+ over a custom scheme may be given access to local resources, be set to
+ ignore Content-Security-Policy rules, or conversely, be denied access to any
+ other content entirely. If it is to be accessed by normal content, ensure cross-origin
+ access is enabled, and if accessed from HTTPS that it is marked as secure.
+
\note Make sure that you create and register the scheme object \e before the QGuiApplication
or QApplication object is instantiated.
@@ -66,10 +44,23 @@ QT_BEGIN_NAMESPACE
{
public:
MySchemeHandler(QObject *parent = nullptr);
- void requestStarted(QWebEngineUrlRequestJob *request)
+ void requestStarted(QWebEngineUrlRequestJob *job)
{
- // ....
+ const QByteArray method = job->requestMethod();
+ const QUrl url = job->requestUrl();
+
+ if (isValidUrl(url)) {
+ if (method == QByteArrayLiteral("GET")) {
+ job->reply(QByteArrayLiteral("text/html"), makeReply(url));
+ else // Unsupported method
+ job->fail(QWebEngineUrlRequestJob::RequestDenied);
+ } else {
+ // Invalid URL
+ job->fail(QWebEngineUrlRequestJob::UrlNotFound);
+ }
}
+ bool isValidUrl(const QUrl &url) const // ....
+ QIODevice *makeReply(const QUrl &url) // ....
};
int main(int argc, char **argv)
@@ -92,7 +83,7 @@ QT_BEGIN_NAMESPACE
\inmodule QtWebEngineCore
- \sa {QWebEngineUrlScheme}, {WebEngine Widgets WebUI Example}
+ \sa {QWebEngineUrlScheme}
*/
/*!
@@ -125,3 +116,5 @@ QWebEngineUrlSchemeHandler::~QWebEngineUrlSchemeHandler()
*/
QT_END_NAMESPACE
+
+#include "moc_qwebengineurlschemehandler.cpp"
diff --git a/src/core/api/qwebengineurlschemehandler.h b/src/core/api/qwebengineurlschemehandler.h
index 09c5b08cb..848904719 100644
--- a/src/core/api/qwebengineurlschemehandler.h
+++ b/src/core/api/qwebengineurlschemehandler.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QWEBENGINEURLSCHEMEHANDLER_H
#define QWEBENGINEURLSCHEMEHANDLER_H
@@ -44,18 +8,15 @@
#include <QtCore/qobject.h>
-namespace QtWebEngineCore {
-class URLRequestContextGetterQt;
-}
-
QT_BEGIN_NAMESPACE
class QWebEngineUrlRequestJob;
-class Q_WEBENGINECORE_EXPORT QWebEngineUrlSchemeHandler : public QObject {
+class Q_WEBENGINECORE_EXPORT QWebEngineUrlSchemeHandler : public QObject
+{
Q_OBJECT
public:
- QWebEngineUrlSchemeHandler(QObject *parent = Q_NULLPTR);
+ QWebEngineUrlSchemeHandler(QObject *parent = nullptr);
~QWebEngineUrlSchemeHandler();
virtual void requestStarted(QWebEngineUrlRequestJob *) = 0;
diff --git a/src/core/api/qwebenginewebauthuxrequest.cpp b/src/core/api/qwebenginewebauthuxrequest.cpp
new file mode 100644
index 000000000..6a79daec9
--- /dev/null
+++ b/src/core/api/qwebenginewebauthuxrequest.cpp
@@ -0,0 +1,427 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qwebenginewebauthuxrequest.h"
+#include "qwebenginewebauthuxrequest_p.h"
+#include "authenticator_request_dialog_controller.h"
+
+/*!
+ \qmltype WebEngineWebAuthUxRequest
+ \instantiates QWebEngineWebAuthUxRequest
+ \inqmlmodule QtWebEngine
+ \since QtWebEngine 6.7
+ \brief Encapsulates the data of a WebAuth UX request.
+
+ Web engine's WebAuth UX requests are passed to the user in the
+ \l WebEngineView::webAuthUxRequested() signal.
+
+ For more information about how to handle web engine authenticator requests, see the
+ \l{WebEngine Quick Nano Browser}{Nano Browser}.
+*/
+
+/*!
+ \class QWebEngineWebAuthUxRequest
+ \brief The QWebEngineWebAuthUxRequest class encapsulates the data of a WebAuth UX request.
+ \since 6.7
+
+ \inmodule QtWebEngineCore
+
+ This class contains the information and API for WebAuth UX. WebAuth may require user
+ interaction during the authentication process. These requests are handled by displaying a
+ dialog to users. QtWebEngine currently supports user verification, resident credentials,
+ and display request failure UX requests.
+
+ QWebEngineWebAuthUxRequest models a WebAuth UX request throughout its life cycle,
+ starting with showing a UX dialog, updating it's content through state changes, and
+ finally closing the dialog.
+
+ WebAuth UX requests are normally triggered when the authenticator requires user interaction.
+ It is the QWebEnginePage's responsibility to notify the application of the new WebAuth UX
+ requests, which it does by emitting the
+ \l{QWebEnginePage::webAuthUxRequested}{webAuthUxRequested} signal together with a newly
+ created QWebEngineWebAuthUxRequest. The application can then examine this request and
+ display a WebAuth UX dialog.
+
+ The QWebEngineWebAuthUxRequest object periodically emits the \l
+ {QWebEngineWebAuthUxRequest::}{stateChanged} signal to notify potential
+ observers of the current WebAuth UX states. The observers update the WebAuth dialog
+ accordingly.
+
+ For more information about how to handle web engine authenticator requests, see the
+ \l{WebEngine Widgets Simple Browser Example}{Simple Browser}.
+*/
+
+/*!
+ \struct QWebEngineWebAuthPinRequest
+ \brief The QWebEngineWebAuthPinRequest class encapsulates the data of a PIN WebAuth UX request.
+ \since 6.7
+
+ \inmodule QtWebEngineCore
+
+ This encapsulates the following information related to a PIN request made by an authenticator.
+ \list
+ \li The reason for the PIN prompt.
+ \li The error details for the PIN prompt.
+ \li The number of attempts remaining before a hard lock. Should be ignored unless
+ \l{QWebEngineWebAuthPinRequest::reason} is
+ \l{QWebEngineWebAuthUxRequest::PinEntryReason::Challenge}.
+ \li The minimum PIN length the authenticator will accept for the PIN.
+ \endlist
+ Use this structure to update the WebAuth UX dialog when the WebAuth UX state is \l
+ QWebEngineWebAuthUxRequest::WebAuthUxState::CollectPin.
+*/
+
+/*!
+ \property QWebEngineWebAuthPinRequest::reason
+ \brief The reason for the PIN prompt.
+*/
+
+/*!
+ \property QWebEngineWebAuthPinRequest::error
+ \brief The error details for the PIN prompt.
+*/
+
+/*!
+ \property QWebEngineWebAuthPinRequest::remainingAttempts
+ \brief The number of attempts remaining before a hard lock. Should be ignored unless
+ \l{QWebEngineWebAuthPinRequest::reason} is
+ \l{QWebEngineWebAuthUxRequest::PinEntryReason::Challenge}.
+*/
+
+/*!
+ \property QWebEngineWebAuthPinRequest::minPinLength
+ \brief The minimum PIN length the authenticator will accept for the PIN.
+*/
+
+/*!
+ \enum QWebEngineWebAuthUxRequest::WebAuthUxState
+
+ This enum describes the state of the current WebAuth UX request.
+
+ \value NotStarted WebAuth UX request not started yet.
+ \value SelectAccount The authenticator requires resident credential details.
+ The application needs to display an account details dialog, and
+ the user needs to select an account to proceed.
+ \value CollectPin The authenticator requires user verification.
+ The application needs to display a PIN request dialog.
+ \value FinishTokenCollection The authenticator requires token/user verification (like tap on
+ the FIDO key) to complete the process.
+ \value RequestFailed WebAuth request failed. Display error details.
+ \value Cancelled WebAuth request is cancelled. Close the WebAuth dialog.
+ \value Completed WebAuth request is completed. Close the WebAuth dialog.
+*/
+
+/*!
+ \enum QWebEngineWebAuthUxRequest::PinEntryReason
+
+ This enum describes the reasons that may prompt the authenticator to ask for a PIN.
+
+ \value Set A new PIN is being set.
+ \value Change The existing PIN must be changed before using this authenticator.
+ \value Challenge The existing PIN is being collected to prove user verification.
+*/
+
+/*!
+ \enum QWebEngineWebAuthUxRequest::PinEntryError
+
+ This enum describes the errors that may prompt the authenticator to ask for a PIN.
+
+ \value NoError No error has occurred.
+ \value InternalUvLocked Internal UV is locked, so we are falling back to PIN.
+ \value WrongPin The PIN the user entered does not match the authenticator PIN.
+ \value TooShort The new PIN the user entered is too short.
+ \value InvalidCharacters The new PIN the user entered contains invalid characters.
+ \value SameAsCurrentPin The new PIN the user entered is the same as the currently set PIN.
+*/
+
+/*!
+ \enum QWebEngineWebAuthUxRequest::RequestFailureReason
+
+ This enum describes the reason for WebAuth request failure.
+
+ \value Timeout The authentication session has timed out.
+ \value KeyNotRegistered Key is not registered with the authenticator.
+ \value KeyAlreadyRegistered Key is already registered with the authenticator.
+ Try to register with another Key or use another authenticator.
+ \value SoftPinBlock The authenticator is blocked as the user entered the wrong key many times.
+ \value HardPinBlock The authenticator is blocked as the user entered the wrong key many times
+ and reset the PIN to use the specific authenticator again.
+ \value AuthenticatorRemovedDuringPinEntry Authenticator removed during PIN entry.
+ \value AuthenticatorMissingResidentKeys Authenticator doesn't have resident key support.
+ \value AuthenticatorMissingUserVerification Authenticator doesn't
+ have user verification support.
+ \value AuthenticatorMissingLargeBlob Authenticator doesn't have large blob support.
+ \value NoCommonAlgorithms No common algorithm.
+ \value StorageFull The resident credential could not be created because the
+ authenticator has insufficient storage.
+ \value UserConsentDenied User consent denied.
+ \value WinUserCancelled The user clicked \uicontrol Cancel in the native windows UI.
+*/
+
+/*!
+ \fn void QWebEngineWebAuthUxRequest::stateChanged(WebAuthUxState state)
+
+ This signal is emitted whenever the WebAuth UX's \a state changes.
+
+ \sa state, WebAuthUxState
+*/
+
+/*!
+ \qmlsignal void WebEngineWebAuthUxRequest::stateChanged(WebAuthUxState state)
+ This signal is emitted whenever the WebAuth UX's \a state changes.
+
+ \sa state, QWebEngineWebAuthUxRequest::WebAuthUxState
+*/
+
+/*! \internal
+ */
+QWebEngineWebAuthUxRequestPrivate::QWebEngineWebAuthUxRequestPrivate(
+ QtWebEngineCore::AuthenticatorRequestDialogController *controller)
+ : webAuthDialogController(controller)
+{
+ m_currentState = controller->state();
+}
+
+/*! \internal
+ */
+QWebEngineWebAuthUxRequestPrivate::~QWebEngineWebAuthUxRequestPrivate() { }
+
+/*! \internal
+ */
+QWebEngineWebAuthUxRequest::QWebEngineWebAuthUxRequest(QWebEngineWebAuthUxRequestPrivate *p)
+ : d_ptr(p)
+{
+ connect(d_ptr->webAuthDialogController,
+ &QtWebEngineCore::AuthenticatorRequestDialogController::stateChanged,
+ [this](WebAuthUxState currentState) {
+ Q_D(QWebEngineWebAuthUxRequest);
+ d->m_currentState = currentState;
+ Q_EMIT stateChanged(d->m_currentState);
+ });
+}
+
+/*! \internal
+ */
+QWebEngineWebAuthUxRequest::~QWebEngineWebAuthUxRequest() { }
+
+/*!
+ \qmlproperty stringlist WebEngineWebAuthUxRequest::userNames
+ \brief The available user names for the resident credential support.
+
+ This is needed when the current WebAuth request's UX state is
+ WebEngineWebAuthUxRequest.WebAuthUxState.SelectAccount. The
+ WebAuth dialog displays user names. The user needs to select an
+ account to proceed.
+
+ \sa state setSelectedAccount() QWebEngineWebAuthUxRequest::userNames
+*/
+/*!
+ \property QWebEngineWebAuthUxRequest::userNames
+ \brief The available user names for the resident credential support.
+ This is needed when the current WebAuth request's UX state is \l SelectAccount.
+ The WebAuth dialog displays user names. The user needs to select an account to proceed.
+
+ \sa SelectAccount setSelectedAccount()
+*/
+QStringList QWebEngineWebAuthUxRequest::userNames() const
+{
+ const Q_D(QWebEngineWebAuthUxRequest);
+
+ return d->webAuthDialogController->userNames();
+}
+
+/*!
+ \qmlproperty string WebEngineWebAuthUxRequest::relyingPartyId
+ \brief The WebAuth request's relying party id.
+*/
+/*!
+ \property QWebEngineWebAuthUxRequest::relyingPartyId
+ \brief The WebAuth request's relying party id.
+*/
+QString QWebEngineWebAuthUxRequest::relyingPartyId() const
+{
+ const Q_D(QWebEngineWebAuthUxRequest);
+
+ return d->webAuthDialogController->relyingPartyId();
+}
+
+/*!
+ \qmlproperty QWebEngineWebAuthPinRequest WebEngineWebAuthUxRequest::pinRequest
+ \brief The WebAuth request's PIN request information.
+
+ \sa QWebEngineWebAuthPinRequest
+*/
+/*!
+ \property QWebEngineWebAuthUxRequest::pinRequest
+ \brief The WebAuth request's PIN request information.
+
+ This is needed when the current WebAuth request state is \l CollectPin.
+ WebAuth Dialog displays a PIN request dialog. The user needs to enter a PIN and
+ invoke \l setPin() to proceed.
+
+ \sa QWebEngineWebAuthPinRequest CollectPin setPin()
+*/
+QWebEngineWebAuthPinRequest QWebEngineWebAuthUxRequest::pinRequest() const
+{
+ const Q_D(QWebEngineWebAuthUxRequest);
+
+ return d->webAuthDialogController->pinRequest();
+}
+
+/*!
+ \qmlproperty enumeration WebEngineWebAuthUxRequest::state
+ \brief The WebAuth request's current UX state.
+
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.NotStarted WebAuth UX request not started yet.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.SelectAccount The authenticator requires
+ resident credential details. The application needs to display an account details dialog,
+ and the user needs to select an account to proceed.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.CollectPin The authenticator requires user verification.
+ The application needs to display a PIN request dialog.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.FinishTokenCollection The authenticator requires
+ token/user verification (like tap on the FIDO key) to complete the process.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.RequestFailed WebAuth request failed. Display error details.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.Cancelled WebAuth request is cancelled.
+ Close the WebAuth dialog.
+ \value WebEngineWebAuthUxRequest.WebAuthUxState.Completed WebAuth request is completed.
+ Close the WebAuth dialog.
+*/
+/*!
+ \property QWebEngineWebAuthUxRequest::state
+ \brief The WebAuth request's current UX state.
+
+ \l stateChanged() is emitted when the current state changes.
+ Update the WebAuth dialog in reponse to the changes in state.
+*/
+QWebEngineWebAuthUxRequest::WebAuthUxState QWebEngineWebAuthUxRequest::state() const
+{
+ return d_ptr->m_currentState;
+}
+
+/*!
+ \qmlmethod void WebEngineWebAuthUxRequest::setSelectedAccount(const QString &selectedAccount)
+
+ Sends the \a selectedAccount name to the authenticator.
+ This is needed when the current WebAuth request's UX state is
+ WebEngineWebAuthUxRequest.WebAuthUxState.SelectAccount. The
+ WebAuth request is blocked until the user selects an account and
+ invokes this method.
+
+ \sa WebEngineWebAuthUxRequest::userNames state
+*/
+/*!
+ Sends the \a selectedAccount name to the authenticator.
+ This is needed when the current WebAuth request's UX state is \l SelectAccount.
+ The WebAuth request is blocked until the user selects an account and invokes this method.
+
+ \sa userNames SelectAccount
+*/
+void QWebEngineWebAuthUxRequest::setSelectedAccount(const QString &selectedAccount)
+{
+ Q_D(QWebEngineWebAuthUxRequest);
+
+ d->webAuthDialogController->sendSelectAccountResponse(selectedAccount);
+}
+
+/*!
+ \qmlmethod void WebEngineWebAuthUxRequest::setPin(const QString &pin)
+ Sends the \a pin to the authenticator that prompts for a PIN.
+ This is needed when the current WebAuth request's UX state is
+ WebEngineWebAuthUxRequest.WebAuthUxState.CollectPin. The WebAuth
+ request is blocked until the user responds with a PIN.
+
+ \sa QWebEngineWebAuthPinRequest state
+*/
+/*!
+ Sends the \a pin to the authenticator that prompts for a PIN.
+ This is needed when the current WebAuth request's UX state is \l CollectPin.
+ The WebAuth request is blocked until the user responds with a PIN.
+
+ \sa QWebEngineWebAuthPinRequest CollectPin
+*/
+void QWebEngineWebAuthUxRequest::setPin(const QString &pin)
+{
+ Q_D(QWebEngineWebAuthUxRequest);
+ d->webAuthDialogController->sendCollectPinResponse(pin);
+}
+
+/*!
+ \qmlmethod void WebEngineWebAuthUxRequest::cancel()
+ Cancels the current WebAuth request.
+
+ \sa QWebEngineWebAuthUxRequest::Cancelled, WebEngineWebAuthUxRequest::stateChanged()
+*/
+/*!
+ Cancels the current WebAuth request.
+
+ \sa QWebEngineWebAuthUxRequest::Cancelled, stateChanged()
+*/
+void QWebEngineWebAuthUxRequest::cancel()
+{
+ Q_D(QWebEngineWebAuthUxRequest);
+
+ d->webAuthDialogController->reject();
+}
+
+/*!
+ \qmlmethod void WebEngineWebAuthUxRequest::retry()
+ Retries the current WebAuth request.
+
+ \sa stateChanged()
+*/
+/*!
+ Retries the current WebAuth request.
+
+ \sa stateChanged()
+*/
+void QWebEngineWebAuthUxRequest::retry()
+{
+ const Q_D(QWebEngineWebAuthUxRequest);
+
+ d->webAuthDialogController->retryRequest();
+}
+
+/*!
+ \qmlproperty enumeration WebEngineWebAuthUxRequest::requestFailureReason
+ \brief The WebAuth request's failure reason.
+
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.Timeout The authentication session has timed out.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.KeyNotRegistered Key is not registered with the authenticator.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.KeyAlreadyRegistered Key is already registered with
+ the authenticator. Try to register with another key or use another authenticator.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.SoftPinBlock The authenticator is blocked as the user
+ entered the wrong key many times.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.HardPinBlock The authenticator is blocked as the user entered
+ the wrong key many times and reset the PIN to use the specific authenticator again.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.AuthenticatorRemovedDuringPinEntry Authenticator
+ removed during PIN entry.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.AuthenticatorMissingResidentKeys Authenticator doesn't
+ have resident key support.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.AuthenticatorMissingUserVerification Authenticator doesn't
+ have user verification support.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.AuthenticatorMissingLargeBlob Authenticator doesn't have
+ large blob support.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.NoCommonAlgorithms No common algorithm.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.StorageFull The resident credential could not be created
+ because the authenticator has insufficient storage.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.UserConsentDenied User consent denied.
+ \value WebEngineWebAuthUxRequest.RequestFailureReason.WinUserCancelled The user clicked \uicontrol Cancel
+ in the native windows UI.
+
+ \sa stateChanged()
+*/
+/*!
+ \property QWebEngineWebAuthUxRequest::requestFailureReason
+ \brief The WebAuth request's failure reason.
+
+ \sa stateChanged() QWebEngineWebAuthUxRequest::RequestFailureReason
+*/
+QWebEngineWebAuthUxRequest::RequestFailureReason
+QWebEngineWebAuthUxRequest::requestFailureReason() const
+{
+ const Q_D(QWebEngineWebAuthUxRequest);
+
+ return d->webAuthDialogController->requestFailureReason();
+}
+
+#include "moc_qwebenginewebauthuxrequest.cpp"
diff --git a/src/core/api/qwebenginewebauthuxrequest.h b/src/core/api/qwebenginewebauthuxrequest.h
new file mode 100644
index 000000000..111f52847
--- /dev/null
+++ b/src/core/api/qwebenginewebauthuxrequest.h
@@ -0,0 +1,117 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEWEBAUTHUXREQUEST_H
+#define QWEBENGINEWEBAUTHUXREQUEST_H
+
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtCore/qobject.h>
+
+namespace QtWebEngineCore {
+class AuthenticatorRequestDialogControllerPrivate;
+}
+
+QT_BEGIN_NAMESPACE
+
+class QWebEngineWebAuthUxRequestPrivate;
+struct QWebEngineWebAuthPinRequest;
+
+class Q_WEBENGINECORE_EXPORT QWebEngineWebAuthUxRequest : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QStringList userNames READ userNames CONSTANT FINAL)
+ Q_PROPERTY(WebAuthUxState state READ state NOTIFY stateChanged FINAL)
+ Q_PROPERTY(QString relyingPartyId READ relyingPartyId CONSTANT FINAL)
+ Q_PROPERTY(QWebEngineWebAuthPinRequest pinRequest READ pinRequest CONSTANT FINAL)
+ Q_PROPERTY(RequestFailureReason requestFailureReason READ requestFailureReason CONSTANT FINAL)
+ Q_CLASSINFO("RegisterEnumClassesUnscoped", "false")
+public:
+ enum class WebAuthUxState {
+ NotStarted,
+ SelectAccount,
+ CollectPin,
+ FinishTokenCollection,
+ RequestFailed,
+ Cancelled,
+ Completed,
+ };
+ Q_ENUM(WebAuthUxState)
+
+ enum class PinEntryReason {
+ Set,
+ Change,
+ Challenge,
+ };
+ Q_ENUM(PinEntryReason)
+
+ enum class PinEntryError {
+ NoError,
+ InternalUvLocked,
+ WrongPin,
+ TooShort,
+ InvalidCharacters,
+ SameAsCurrentPin,
+ };
+ Q_ENUM(PinEntryError)
+
+ enum class RequestFailureReason {
+ Timeout,
+ KeyNotRegistered,
+ KeyAlreadyRegistered,
+ SoftPinBlock,
+ HardPinBlock,
+ AuthenticatorRemovedDuringPinEntry,
+ AuthenticatorMissingResidentKeys,
+ AuthenticatorMissingUserVerification,
+ AuthenticatorMissingLargeBlob,
+ NoCommonAlgorithms,
+ StorageFull,
+ UserConsentDenied,
+ WinUserCancelled,
+ };
+ Q_ENUM(RequestFailureReason)
+
+ ~QWebEngineWebAuthUxRequest() override;
+
+ QStringList userNames() const;
+ QString relyingPartyId() const;
+ QWebEngineWebAuthPinRequest pinRequest() const;
+ WebAuthUxState state() const;
+ RequestFailureReason requestFailureReason() const;
+
+Q_SIGNALS:
+ void stateChanged(QWebEngineWebAuthUxRequest::WebAuthUxState state);
+
+public Q_SLOTS:
+ void cancel();
+ void retry();
+ void setSelectedAccount(const QString &selectedAccount);
+ void setPin(const QString &pin);
+
+protected:
+ explicit QWebEngineWebAuthUxRequest(QWebEngineWebAuthUxRequestPrivate *);
+
+ std::unique_ptr<QWebEngineWebAuthUxRequestPrivate> d_ptr;
+ friend class QtWebEngineCore::AuthenticatorRequestDialogControllerPrivate;
+ Q_DECLARE_PRIVATE(QWebEngineWebAuthUxRequest)
+};
+
+struct QWebEngineWebAuthPinRequest
+{
+ Q_GADGET_EXPORT(Q_WEBENGINECORE_EXPORT)
+
+ Q_PROPERTY(QWebEngineWebAuthUxRequest::PinEntryReason reason MEMBER reason CONSTANT FINAL)
+ Q_PROPERTY(QWebEngineWebAuthUxRequest::PinEntryError error MEMBER error CONSTANT FINAL)
+ Q_PROPERTY(qint32 minPinLength MEMBER minPinLength CONSTANT FINAL)
+ Q_PROPERTY(int remainingAttempts MEMBER remainingAttempts CONSTANT FINAL)
+public:
+ QWebEngineWebAuthUxRequest::PinEntryReason reason;
+ QWebEngineWebAuthUxRequest::PinEntryError error;
+ qint32 minPinLength;
+ int remainingAttempts;
+};
+
+QT_END_NAMESPACE
+
+#endif // QWEBENGINEWEBAUTHUXREQUEST_H
diff --git a/src/core/api/qwebenginewebauthuxrequest_p.h b/src/core/api/qwebenginewebauthuxrequest_p.h
new file mode 100644
index 000000000..4c685bac7
--- /dev/null
+++ b/src/core/api/qwebenginewebauthuxrequest_p.h
@@ -0,0 +1,43 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QWEBENGINEWEBAUTHUXREQUEST_P_H
+#define QWEBENGINEWEBAUTHUXREQUEST_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qtwebenginecoreglobal_p.h"
+#include "qwebenginewebauthuxrequest.h"
+#include <QtCore/QSharedPointer>
+
+namespace QtWebEngineCore {
+class WebContentsAdapterClient;
+class AuthenticatorRequestDialogController;
+}
+
+QT_BEGIN_NAMESPACE
+
+class Q_WEBENGINECORE_EXPORT QWebEngineWebAuthUxRequestPrivate
+{
+
+public:
+ QWebEngineWebAuthUxRequestPrivate(
+ QtWebEngineCore::AuthenticatorRequestDialogController *controller);
+ ~QWebEngineWebAuthUxRequestPrivate();
+
+ QWebEngineWebAuthUxRequest::WebAuthUxState m_currentState =
+ QWebEngineWebAuthUxRequest::WebAuthUxState::NotStarted;
+ QtWebEngineCore::AuthenticatorRequestDialogController *webAuthDialogController;
+};
+
+QT_END_NAMESPACE
+#endif // QWEBENGINEWEBAUTHUXREQUEST_P_H
diff --git a/src/core/authentication_dialog_controller.cpp b/src/core/authentication_dialog_controller.cpp
index e37ffab44..4efd5dad3 100644
--- a/src/core/authentication_dialog_controller.cpp
+++ b/src/core/authentication_dialog_controller.cpp
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "authentication_dialog_controller.h"
#include "authentication_dialog_controller_p.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browser_task_traits.h"
@@ -53,7 +16,7 @@ AuthenticationDialogControllerPrivate::AuthenticationDialogControllerPrivate(bas
void AuthenticationDialogControllerPrivate::dialogFinished(bool accepted, const QString &user, const QString &password)
{
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&LoginDelegateQt::sendAuthToRequester,
loginDelegate, accepted, user, password));
}
diff --git a/src/core/authentication_dialog_controller.h b/src/core/authentication_dialog_controller.h
index 631a95c34..944ec4d15 100644
--- a/src/core/authentication_dialog_controller.h
+++ b/src/core/authentication_dialog_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,15 +15,14 @@
#ifndef AUTHENTICATION_DIALOG_CONTROLLER_H
#define AUTHENTICATION_DIALOG_CONTROLLER_H
-#include "qtwebenginecoreglobal_p.h"
-
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QObject>
namespace QtWebEngineCore {
class AuthenticationDialogControllerPrivate;
-class Q_WEBENGINECORE_PRIVATE_EXPORT AuthenticationDialogController : public QObject {
+class Q_WEBENGINECORE_EXPORT AuthenticationDialogController : public QObject {
Q_OBJECT
public:
~AuthenticationDialogController();
diff --git a/src/core/authentication_dialog_controller_p.h b/src/core/authentication_dialog_controller_p.h
index 1abff576d..6c35a60dc 100644
--- a/src/core/authentication_dialog_controller_p.h
+++ b/src/core/authentication_dialog_controller_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef AUTHENTICATION_DIALOG_CONTROLLER_P_H
#define AUTHENTICATION_DIALOG_CONTROLLER_P_H
diff --git a/src/core/authenticator_request_client_delegate_qt.cpp b/src/core/authenticator_request_client_delegate_qt.cpp
new file mode 100644
index 000000000..5f9fd9ca3
--- /dev/null
+++ b/src/core/authenticator_request_client_delegate_qt.cpp
@@ -0,0 +1,247 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "authenticator_request_client_delegate_qt.h"
+#include "authenticator_request_dialog_controller.h"
+#include "authenticator_request_dialog_controller_p.h"
+#include "base/base64.h"
+#include "profile_adapter_client.h"
+#include "profile_qt.h"
+#include "content/public/browser/web_contents.h"
+#include "web_contents_delegate_qt.h"
+#include "type_conversion.h"
+
+namespace QtWebEngineCore {
+
+using RequestFailureReason = QWebEngineWebAuthUxRequest::RequestFailureReason;
+
+WebAuthenticationDelegateQt::WebAuthenticationDelegateQt() = default;
+
+WebAuthenticationDelegateQt::~WebAuthenticationDelegateQt() = default;
+
+bool WebAuthenticationDelegateQt::SupportsResidentKeys(content::RenderFrameHost *render_frame_host)
+{
+ return true;
+}
+
+AuthenticatorRequestClientDelegateQt::AuthenticatorRequestClientDelegateQt(
+ content::RenderFrameHost *render_frame_host)
+ : m_renderFrameHost(render_frame_host), m_weakFactory(this)
+{
+ m_dialogController.reset(new AuthenticatorRequestDialogController(
+ new AuthenticatorRequestDialogControllerPrivate(m_renderFrameHost,
+ m_weakFactory.GetWeakPtr())));
+}
+
+AuthenticatorRequestClientDelegateQt::~AuthenticatorRequestClientDelegateQt()
+{
+ // Currently WebAuth request is completed. Now it is possible to delete the dialog if displayed
+ m_dialogController->finishRequest();
+}
+
+void AuthenticatorRequestClientDelegateQt::SetRelyingPartyId(const std::string &rp_id)
+{
+ m_dialogController->setRelyingPartyId(rp_id);
+}
+
+bool AuthenticatorRequestClientDelegateQt::DoesBlockRequestOnFailure(
+ InterestingFailureReason reason)
+{
+ if (!IsWebAuthnUIEnabled())
+ return false;
+
+ switch (reason) {
+ case InterestingFailureReason::kTimeout:
+ m_dialogController->handleRequestFailure(RequestFailureReason::Timeout);
+ break;
+ case InterestingFailureReason::kAuthenticatorMissingResidentKeys:
+ m_dialogController->handleRequestFailure(
+ RequestFailureReason::AuthenticatorMissingResidentKeys);
+ break;
+ case InterestingFailureReason::kAuthenticatorMissingUserVerification:
+ m_dialogController->handleRequestFailure(
+ RequestFailureReason::AuthenticatorMissingUserVerification);
+ break;
+ case InterestingFailureReason::kAuthenticatorMissingLargeBlob:
+ m_dialogController->handleRequestFailure(
+ RequestFailureReason::AuthenticatorMissingLargeBlob);
+ break;
+ case InterestingFailureReason::kAuthenticatorRemovedDuringPINEntry:
+ m_dialogController->handleRequestFailure(
+ RequestFailureReason::AuthenticatorRemovedDuringPinEntry);
+ break;
+ case InterestingFailureReason::kHardPINBlock:
+ m_dialogController->handleRequestFailure(RequestFailureReason::HardPinBlock);
+ break;
+ case InterestingFailureReason::kSoftPINBlock:
+ m_dialogController->handleRequestFailure(RequestFailureReason::SoftPinBlock);
+ break;
+ case InterestingFailureReason::kKeyAlreadyRegistered:
+ m_dialogController->handleRequestFailure(RequestFailureReason::KeyAlreadyRegistered);
+ break;
+ case InterestingFailureReason::kKeyNotRegistered:
+ m_dialogController->handleRequestFailure(RequestFailureReason::KeyNotRegistered);
+ break;
+ case InterestingFailureReason::kNoCommonAlgorithms:
+ m_dialogController->handleRequestFailure(RequestFailureReason::NoCommonAlgorithms);
+ break;
+ case InterestingFailureReason::kStorageFull:
+ m_dialogController->handleRequestFailure(RequestFailureReason::StorageFull);
+ break;
+ case InterestingFailureReason::kUserConsentDenied:
+ m_dialogController->handleRequestFailure(RequestFailureReason::UserConsentDenied);
+ break;
+ case InterestingFailureReason::kWinUserCancelled:
+#if BUILDFLAG(IS_WIN)
+ m_dialogController->handleRequestFailure(RequestFailureReason::WinUserCancelled);
+#else
+ return false;
+#endif
+ break;
+ default:
+ return false;
+ }
+ return true;
+}
+void AuthenticatorRequestClientDelegateQt::RegisterActionCallbacks(
+ base::OnceClosure cancel_callback, base::RepeatingClosure start_over_callback,
+ AccountPreselectedCallback account_preselected_callback,
+ device::FidoRequestHandlerBase::RequestCallback request_callback,
+ base::RepeatingClosure bluetooth_adapter_power_on_callback)
+{
+ m_cancelCallback = std::move(cancel_callback);
+ m_startOverCallback = std::move(start_over_callback);
+ m_accountPreselectedCallback = std::move(account_preselected_callback);
+ m_requestCallback = std::move(request_callback);
+ m_bluetoothAdapterPowerOnCallback = std::move(bluetooth_adapter_power_on_callback);
+}
+
+void AuthenticatorRequestClientDelegateQt::ShouldReturnAttestation(
+ const std::string &relying_party_id, const device::FidoAuthenticator *authenticator,
+ bool is_enterprise_attestation, base::OnceCallback<void(bool)> callback)
+{
+ std::move(callback).Run(!is_enterprise_attestation);
+}
+
+void AuthenticatorRequestClientDelegateQt::SelectAccount(
+ std::vector<device::AuthenticatorGetAssertionResponse> responses,
+ base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)> callback)
+{
+ if (m_isUiDisabled) {
+ // Requests with UI disabled should never reach account selection.
+ DCHECK(IsVirtualEnvironmentEnabled());
+ std::move(callback).Run(std::move(responses.at(0)));
+ return;
+ }
+
+ if (m_isConditionalRequest) {
+ return;
+ }
+
+ m_authenticatorGetAssertionResponse = std::move(responses);
+ m_selectAccountCallback = std::move(callback);
+
+ QStringList userList;
+ int nIndex = -1;
+ for (const auto &response : m_authenticatorGetAssertionResponse) {
+ nIndex++;
+ const auto &user_entity = response.user_entity;
+ const bool has_user_identifying_info = user_entity && user_entity->name;
+ if (has_user_identifying_info) {
+ QString userName = toQt(*response.user_entity->name);
+ m_userMap[userName] = nIndex;
+ userList.append(userName);
+ }
+ }
+ m_dialogController->selectAccount(userList);
+}
+
+void AuthenticatorRequestClientDelegateQt::DisableUI()
+{
+ m_isUiDisabled = true;
+}
+
+bool AuthenticatorRequestClientDelegateQt::IsWebAuthnUIEnabled()
+{
+ return !m_isUiDisabled;
+}
+
+void AuthenticatorRequestClientDelegateQt::SetConditionalRequest(bool is_conditional)
+{
+ m_isConditionalRequest = is_conditional;
+}
+
+// This method will not be invoked until the observer is set.
+void AuthenticatorRequestClientDelegateQt::OnTransportAvailabilityEnumerated(
+ device::FidoRequestHandlerBase::TransportAvailabilityInfo data)
+{
+ // Show dialog only after this step;
+ // If m_isUiDisabled is set or another UI request in progress return
+ if (m_isUiDisabled
+ || m_dialogController->state() != QWebEngineWebAuthUxRequest::WebAuthUxState::NotStarted)
+ return;
+
+ // Start WebAuth UX
+ // we may need to pass data as well. for SelectAccount and SupportPin it is not required,
+ // skipping that for the timebeing.
+ m_dialogController->startRequest(m_isConditionalRequest);
+}
+
+bool AuthenticatorRequestClientDelegateQt::SupportsPIN() const
+{
+ return true;
+}
+
+void AuthenticatorRequestClientDelegateQt::CollectPIN(
+ CollectPINOptions options, base::OnceCallback<void(std::u16string)> provide_pin_cb)
+{
+
+ m_providePinCallback = std::move(provide_pin_cb);
+ QWebEngineWebAuthPinRequest pinRequestInfo;
+
+ pinRequestInfo.reason = static_cast<QWebEngineWebAuthUxRequest::PinEntryReason>(options.reason);
+ pinRequestInfo.error = static_cast<QWebEngineWebAuthUxRequest::PinEntryError>(options.error);
+ pinRequestInfo.remainingAttempts = options.attempts;
+ pinRequestInfo.minPinLength = options.min_pin_length;
+ m_dialogController->collectPin(pinRequestInfo);
+}
+
+void AuthenticatorRequestClientDelegateQt::FinishCollectToken()
+{
+ m_dialogController->finishCollectToken();
+}
+
+void AuthenticatorRequestClientDelegateQt::onCancelRequest()
+{
+ if (!m_cancelCallback)
+ return;
+
+ std::move(m_cancelCallback).Run();
+}
+
+void AuthenticatorRequestClientDelegateQt::onSelectAccount(const QString &selectedAccount)
+{
+ if (!m_selectAccountCallback)
+ return;
+
+ if (m_userMap.find(selectedAccount) != m_userMap.end()) {
+ std::move(m_selectAccountCallback)
+ .Run(std::move(m_authenticatorGetAssertionResponse.at(m_userMap[selectedAccount])));
+ } else {
+ onCancelRequest();
+ }
+}
+
+void AuthenticatorRequestClientDelegateQt::onCollectPin(const QString &pin)
+{
+ if (!m_providePinCallback)
+ return;
+ std::move(m_providePinCallback).Run(pin.toStdU16String());
+}
+
+void AuthenticatorRequestClientDelegateQt::onRetryRequest()
+{
+ DCHECK(m_startOverCallback);
+ m_startOverCallback.Run();
+}
+}
diff --git a/src/core/authenticator_request_client_delegate_qt.h b/src/core/authenticator_request_client_delegate_qt.h
new file mode 100644
index 000000000..05c6136bd
--- /dev/null
+++ b/src/core/authenticator_request_client_delegate_qt.h
@@ -0,0 +1,96 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef AUTHENTICATOR_REQUEST_CLIENT_DELEGATE_QT_H
+#define AUTHENTICATOR_REQUEST_CLIENT_DELEGATE_QT_H
+
+#include "qtwebenginecoreglobal_p.h"
+#include "content/public/browser/authenticator_request_client_delegate.h"
+#include <unordered_map>
+#include <QSharedPointer>
+
+namespace QtWebEngineCore {
+
+class AuthenticatorRequestDialogController;
+
+class WebAuthenticationDelegateQt : public content::WebAuthenticationDelegate
+{
+public:
+ WebAuthenticationDelegateQt();
+ virtual ~WebAuthenticationDelegateQt();
+
+ bool SupportsResidentKeys(content::RenderFrameHost *render_frame_host) override;
+};
+
+class AuthenticatorRequestClientDelegateQt : public content::AuthenticatorRequestClientDelegate
+{
+public:
+ explicit AuthenticatorRequestClientDelegateQt(content::RenderFrameHost *render_frame_host);
+ AuthenticatorRequestClientDelegateQt(const AuthenticatorRequestClientDelegateQt &) = delete;
+ AuthenticatorRequestClientDelegateQt &
+ operator=(const AuthenticatorRequestClientDelegateQt &) = delete;
+ ~AuthenticatorRequestClientDelegateQt();
+
+ // content::AuthenticatorRequestClientDelegate ovverrides
+ void SetRelyingPartyId(const std::string &rp_id) override;
+ bool DoesBlockRequestOnFailure(InterestingFailureReason reason) override;
+ void RegisterActionCallbacks(base::OnceClosure cancel_callback,
+ base::RepeatingClosure start_over_callback,
+ AccountPreselectedCallback account_preselected_callback,
+ device::FidoRequestHandlerBase::RequestCallback request_callback,
+ base::RepeatingClosure bluetooth_adapter_power_on_callback) override;
+ void ShouldReturnAttestation(const std::string &relying_party_id,
+ const device::FidoAuthenticator *authenticator,
+ bool is_enterprise_attestation,
+ base::OnceCallback<void(bool)> callback) override;
+ void SelectAccount(
+ std::vector<device::AuthenticatorGetAssertionResponse> responses,
+ base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)> callback) override;
+ void DisableUI() override;
+ bool IsWebAuthnUIEnabled() override;
+ void SetConditionalRequest(bool is_conditional) override;
+
+ // device::FidoRequestHandlerBase::Observer overrides:
+ // This method will not be invoked until the observer is set.
+ void OnTransportAvailabilityEnumerated(
+ device::FidoRequestHandlerBase::TransportAvailabilityInfo data) override;
+
+ bool SupportsPIN() const override;
+ void CollectPIN(CollectPINOptions options,
+ base::OnceCallback<void(std::u16string)> provide_pin_cb) override;
+ void FinishCollectToken() override;
+
+ // Dialog helper
+ void onCancelRequest();
+ void onSelectAccount(const QString &selectedAccount);
+ void onCollectPin(const QString &pin);
+ void onRetryRequest();
+
+private:
+ content::RenderFrameHost *m_renderFrameHost;
+ bool m_isUiDisabled = false;
+ bool m_isConditionalRequest = false;
+
+ base::OnceClosure m_cancelCallback;
+ base::RepeatingClosure m_startOverCallback;
+ AccountPreselectedCallback m_accountPreselectedCallback;
+ device::FidoRequestHandlerBase::RequestCallback m_requestCallback;
+ base::RepeatingClosure m_bluetoothAdapterPowerOnCallback;
+
+ // Select account details;
+ std::vector<device::AuthenticatorGetAssertionResponse> m_authenticatorGetAssertionResponse;
+ std::unordered_map<QString, int> m_userMap;
+ base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)> m_selectAccountCallback;
+
+ // collect pin
+ base::OnceCallback<void(std::u16string)> m_providePinCallback;
+
+ // This member is used to keep authenticator request dialog controller alive until
+ // authenticator request is completed or cancelled.
+ QSharedPointer<AuthenticatorRequestDialogController> m_dialogController;
+ base::WeakPtrFactory<AuthenticatorRequestClientDelegateQt> m_weakFactory;
+};
+
+}
+
+#endif // AUTHENTICATOR_REQUEST_CLIENT_DELEGATE_QT_H
diff --git a/src/core/authenticator_request_dialog_controller.cpp b/src/core/authenticator_request_dialog_controller.cpp
new file mode 100644
index 000000000..73fb4e7f3
--- /dev/null
+++ b/src/core/authenticator_request_dialog_controller.cpp
@@ -0,0 +1,302 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "authenticator_request_dialog_controller.h"
+#include "authenticator_request_dialog_controller_p.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "web_contents_delegate_qt.h"
+#include "qwebenginewebauthuxrequest_p.h"
+#include "qwebenginewebauthuxrequest.h"
+
+using PinEntryError = QWebEngineWebAuthUxRequest::PinEntryError;
+using PinEntryReason = QWebEngineWebAuthUxRequest::PinEntryReason;
+using WebAuthUxState = QWebEngineWebAuthUxRequest::WebAuthUxState;
+
+namespace QtWebEngineCore {
+
+ASSERT_ENUMS_MATCH(PinEntryReason::Set, device::pin::PINEntryReason::kSet)
+ASSERT_ENUMS_MATCH(PinEntryReason::Change, device::pin::PINEntryReason::kChange)
+ASSERT_ENUMS_MATCH(PinEntryReason::Challenge, device::pin::PINEntryReason::kChallenge)
+ASSERT_ENUMS_MATCH(PinEntryError::WrongPin, device::pin::PINEntryError::kWrongPIN)
+ASSERT_ENUMS_MATCH(PinEntryError::TooShort, device::pin::PINEntryError::kTooShort)
+ASSERT_ENUMS_MATCH(PinEntryError::SameAsCurrentPin, device::pin::PINEntryError::kSameAsCurrentPIN)
+ASSERT_ENUMS_MATCH(PinEntryError::NoError, device::pin::PINEntryError::kNoError)
+ASSERT_ENUMS_MATCH(PinEntryError::InvalidCharacters, device::pin::PINEntryError::kInvalidCharacters)
+ASSERT_ENUMS_MATCH(PinEntryError::InternalUvLocked, device::pin::PINEntryError::kInternalUvLocked)
+
+AuthenticatorRequestDialogControllerPrivate::AuthenticatorRequestDialogControllerPrivate(
+ content::RenderFrameHost *renderFrameHost,
+ base::WeakPtr<AuthenticatorRequestClientDelegateQt> authenticatorRequestDelegate)
+ : m_renderFrameHost(renderFrameHost)
+ , m_authenticatorRequestDelegate(authenticatorRequestDelegate)
+{
+}
+
+AuthenticatorRequestDialogControllerPrivate::~AuthenticatorRequestDialogControllerPrivate()
+{
+ if (m_request) {
+ delete m_request;
+ m_request = nullptr;
+ }
+}
+
+void AuthenticatorRequestDialogControllerPrivate::showWebAuthDialog()
+{
+ Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
+
+ content::WebContents *webContent = content::WebContents::FromRenderFrameHost(m_renderFrameHost);
+
+ if (!webContent)
+ return;
+
+ WebContentsAdapterClient *adapterClient = nullptr;
+ if (webContent)
+ adapterClient =
+ static_cast<WebContentsDelegateQt *>(webContent->GetDelegate())->adapterClient();
+
+ if (adapterClient) {
+
+ QWebEngineWebAuthUxRequestPrivate *itemPrivate =
+ new QWebEngineWebAuthUxRequestPrivate(q_ptr);
+
+ m_request = new QWebEngineWebAuthUxRequest(itemPrivate);
+
+ adapterClient->showWebAuthDialog(m_request);
+ m_isDialogCreated = true;
+ } else {
+ cancelRequest();
+ }
+}
+
+void AuthenticatorRequestDialogControllerPrivate::selectAccount(const QStringList &userList)
+{
+ m_userList.clear();
+ m_userList = userList;
+ setCurrentState(WebAuthUxState::SelectAccount);
+}
+
+void AuthenticatorRequestDialogControllerPrivate::collectPin(QWebEngineWebAuthPinRequest pinRequest)
+{
+ m_pinRequest = pinRequest;
+ setCurrentState(WebAuthUxState::CollectPin);
+}
+
+void AuthenticatorRequestDialogControllerPrivate::finishCollectToken()
+{
+ setCurrentState(WebAuthUxState::FinishTokenCollection);
+}
+
+QStringList AuthenticatorRequestDialogControllerPrivate::userNames() const
+{
+ return m_userList;
+}
+
+void AuthenticatorRequestDialogControllerPrivate::finishRequest()
+{
+ if (!m_isDialogCreated)
+ return;
+ setCurrentState(WebAuthUxState::Completed);
+}
+
+void AuthenticatorRequestDialogControllerPrivate::setCurrentState(
+ QWebEngineWebAuthUxRequest::WebAuthUxState uxState)
+{
+ if (!m_isStarted) {
+ // Dialog isn't showing yet. Remember to show this step when it appears.
+ m_pendingState = uxState;
+ return;
+ }
+
+ m_currentState = uxState;
+
+ if (m_isConditionalRequest)
+ return;
+
+ if (!m_isDialogCreated) {
+ showWebAuthDialog();
+ } else {
+ Q_EMIT q_ptr->stateChanged(m_currentState);
+
+ if (m_currentState == QWebEngineWebAuthUxRequest::WebAuthUxState::Cancelled
+ || m_currentState == QWebEngineWebAuthUxRequest::WebAuthUxState::Completed) {
+ m_isDialogCreated = false;
+ }
+ }
+}
+
+void AuthenticatorRequestDialogControllerPrivate::cancelRequest()
+{
+ setCurrentState(WebAuthUxState::Cancelled);
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&AuthenticatorRequestClientDelegateQt::onCancelRequest,
+ m_authenticatorRequestDelegate));
+}
+
+void AuthenticatorRequestDialogControllerPrivate::retryRequest()
+{
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&AuthenticatorRequestClientDelegateQt::onRetryRequest,
+ m_authenticatorRequestDelegate));
+}
+
+void AuthenticatorRequestDialogControllerPrivate::sendSelectAccountResponse(
+ const QString &selectedAccount)
+{
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&AuthenticatorRequestClientDelegateQt::onSelectAccount,
+ m_authenticatorRequestDelegate, selectedAccount));
+}
+
+QWebEngineWebAuthUxRequest::WebAuthUxState
+AuthenticatorRequestDialogControllerPrivate::state() const
+{
+ return m_currentState;
+}
+
+void AuthenticatorRequestDialogControllerPrivate::startRequest(bool isConditionalRequest)
+{
+ DCHECK(!m_isStarted);
+
+ m_isStarted = true;
+ m_isConditionalRequest = isConditionalRequest;
+
+ if (m_pendingState) {
+ setCurrentState(*m_pendingState);
+ m_pendingState.reset();
+ }
+}
+
+void AuthenticatorRequestDialogControllerPrivate::setRelyingPartyId(const QString &rpId)
+{
+ m_relyingPartyId = rpId;
+}
+
+QString AuthenticatorRequestDialogControllerPrivate::relyingPartyId() const
+{
+ return m_relyingPartyId;
+}
+
+QWebEngineWebAuthPinRequest AuthenticatorRequestDialogControllerPrivate::pinRequest()
+{
+ return m_pinRequest;
+}
+
+void AuthenticatorRequestDialogControllerPrivate::handleRequestFailure(
+ QWebEngineWebAuthUxRequest::RequestFailureReason reason)
+{
+ m_requestFailureReason = reason;
+ setCurrentState(WebAuthUxState::RequestFailed);
+}
+
+void AuthenticatorRequestDialogControllerPrivate::sendCollectPinResponse(const QString &pin)
+{
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&AuthenticatorRequestClientDelegateQt::onCollectPin,
+ m_authenticatorRequestDelegate, pin));
+}
+
+QWebEngineWebAuthUxRequest::RequestFailureReason
+AuthenticatorRequestDialogControllerPrivate::requestFailureReason() const
+{
+ return m_requestFailureReason;
+}
+
+AuthenticatorRequestDialogController::AuthenticatorRequestDialogController(
+ AuthenticatorRequestDialogControllerPrivate *dd)
+{
+ Q_ASSERT(dd);
+ d_ptr.reset(dd);
+ d_ptr->q_ptr = this;
+}
+
+AuthenticatorRequestDialogController::~AuthenticatorRequestDialogController() { }
+
+void AuthenticatorRequestDialogController::selectAccount(const QStringList &userList)
+{
+ d_ptr->selectAccount(userList);
+}
+
+void AuthenticatorRequestDialogController::collectPin(QWebEngineWebAuthPinRequest pinRequest)
+{
+ d_ptr->collectPin(pinRequest);
+}
+
+QStringList AuthenticatorRequestDialogController::userNames() const
+{
+ return d_ptr->userNames();
+}
+
+QWebEngineWebAuthPinRequest AuthenticatorRequestDialogController::pinRequest()
+{
+ return d_ptr->pinRequest();
+}
+
+void AuthenticatorRequestDialogController::reject()
+{
+ d_ptr->cancelRequest();
+}
+
+void AuthenticatorRequestDialogController::sendSelectAccountResponse(const QString &account)
+{
+ d_ptr->sendSelectAccountResponse(account);
+}
+
+void AuthenticatorRequestDialogController::finishCollectToken()
+{
+ d_ptr->finishCollectToken();
+}
+
+void AuthenticatorRequestDialogController::finishRequest()
+{
+ d_ptr->finishRequest();
+}
+
+QWebEngineWebAuthUxRequest::WebAuthUxState AuthenticatorRequestDialogController::state() const
+{
+ return d_ptr->state();
+}
+
+void AuthenticatorRequestDialogController::startRequest(bool bIsConditionalRequest)
+{
+ d_ptr->startRequest(bIsConditionalRequest);
+}
+
+void AuthenticatorRequestDialogController::setRelyingPartyId(const std::string &rpId)
+{
+ d_ptr->setRelyingPartyId(QString::fromStdString(rpId));
+}
+
+QString AuthenticatorRequestDialogController::relyingPartyId() const
+{
+ return d_ptr->relyingPartyId();
+}
+
+void AuthenticatorRequestDialogController::handleRequestFailure(
+ QWebEngineWebAuthUxRequest::RequestFailureReason reason)
+{
+ d_ptr->handleRequestFailure(reason);
+}
+
+void AuthenticatorRequestDialogController::retryRequest()
+{
+ d_ptr->retryRequest();
+}
+
+void AuthenticatorRequestDialogController::sendCollectPinResponse(const QString &pin)
+{
+ d_ptr->sendCollectPinResponse(pin);
+}
+
+QWebEngineWebAuthUxRequest::RequestFailureReason
+AuthenticatorRequestDialogController::requestFailureReason() const
+{
+ return d_ptr->requestFailureReason();
+}
+}
diff --git a/src/core/authenticator_request_dialog_controller.h b/src/core/authenticator_request_dialog_controller.h
new file mode 100644
index 000000000..98e8dcf90
--- /dev/null
+++ b/src/core/authenticator_request_dialog_controller.h
@@ -0,0 +1,53 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_H
+#define AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_H
+
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+#include <QtCore/qobject.h>
+#include "qwebenginewebauthuxrequest.h"
+
+namespace content {
+class WebContents;
+class RenderFrameHost;
+}
+namespace QtWebEngineCore {
+
+class AuthenticatorRequestDialogControllerPrivate;
+
+class Q_WEBENGINECORE_EXPORT AuthenticatorRequestDialogController : public QObject
+{
+ Q_OBJECT
+public:
+ ~AuthenticatorRequestDialogController();
+ void sendSelectAccountResponse(const QString &account);
+ void sendCollectPinResponse(const QString &pin);
+ QStringList userNames() const;
+ QWebEngineWebAuthPinRequest pinRequest();
+ void reject();
+ AuthenticatorRequestDialogController(AuthenticatorRequestDialogControllerPrivate *);
+
+ QWebEngineWebAuthUxRequest::WebAuthUxState state() const;
+ QString relyingPartyId() const;
+ void retryRequest();
+ QWebEngineWebAuthUxRequest::RequestFailureReason requestFailureReason() const;
+
+Q_SIGNALS:
+ void stateChanged(QWebEngineWebAuthUxRequest::WebAuthUxState state);
+
+private:
+ void selectAccount(const QStringList &userList);
+ void collectPin(QWebEngineWebAuthPinRequest pinRequest);
+ void finishCollectToken();
+ void startRequest(bool bIsConditionalRequest);
+ void finishRequest();
+ void setRelyingPartyId(const std::string &rpId);
+ void handleRequestFailure(QWebEngineWebAuthUxRequest::RequestFailureReason reason);
+
+ QScopedPointer<AuthenticatorRequestDialogControllerPrivate> d_ptr;
+ friend class AuthenticatorRequestClientDelegateQt;
+};
+}
+
+#endif // AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_H
diff --git a/src/core/authenticator_request_dialog_controller_p.h b/src/core/authenticator_request_dialog_controller_p.h
new file mode 100644
index 000000000..5e7333d56
--- /dev/null
+++ b/src/core/authenticator_request_dialog_controller_p.h
@@ -0,0 +1,78 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_P_H
+#define AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_P_H
+#include <QStringList>
+#include <QSharedPointer>
+#include "authenticator_request_client_delegate_qt.h"
+#include "authenticator_request_dialog_controller.h"
+
+namespace content {
+class WebContents;
+class RenderFrameHost;
+}
+
+namespace QtWebEngineCore {
+
+class AuthenticatorRequestDialogControllerPrivate
+{
+
+public:
+ AuthenticatorRequestDialogControllerPrivate(
+ content::RenderFrameHost *renderFrameHost,
+ base::WeakPtr<AuthenticatorRequestClientDelegateQt> authenticatorRequestDelegate);
+ ~AuthenticatorRequestDialogControllerPrivate();
+ void showWebAuthDialog();
+ void selectAccount(const QStringList &userList);
+ QStringList userNames() const;
+ QString relyingPartyId() const;
+ QWebEngineWebAuthUxRequest::WebAuthUxState state() const;
+ QWebEngineWebAuthPinRequest pinRequest();
+ QWebEngineWebAuthUxRequest::RequestFailureReason requestFailureReason() const;
+ void sendSelectAccountResponse(const QString &selectedAccount);
+ void setCurrentState(QWebEngineWebAuthUxRequest::WebAuthUxState uxState);
+ void setRelyingPartyId(const QString &rpId);
+
+ // Support pin functionality
+ void collectPin(QWebEngineWebAuthPinRequest pinRequestInfo);
+ void finishCollectToken();
+ void handleRequestFailure(QWebEngineWebAuthUxRequest::RequestFailureReason reason);
+ void sendCollectPinResponse(const QString &pin);
+
+ // Deleting dialog;
+ void finishRequest();
+
+ // cancel request
+ void cancelRequest();
+ void retryRequest();
+ void startRequest(bool isConditionalRequest);
+
+ AuthenticatorRequestDialogController *q_ptr;
+
+private:
+ content::RenderFrameHost *m_renderFrameHost;
+ QStringList m_userList;
+ QString m_pin;
+ QString m_relyingPartyId;
+
+ bool m_isStarted = false;
+ bool m_isConditionalRequest = false;
+ QWebEngineWebAuthUxRequest::WebAuthUxState m_currentState =
+ QWebEngineWebAuthUxRequest::WebAuthUxState::NotStarted;
+ base::WeakPtr<AuthenticatorRequestClientDelegateQt> m_authenticatorRequestDelegate;
+ bool m_isDialogCreated = false;
+ QWebEngineWebAuthPinRequest m_pinRequest;
+
+ QWebEngineWebAuthUxRequest *m_request = nullptr;
+ QWebEngineWebAuthUxRequest::RequestFailureReason m_requestFailureReason;
+
+ // m_pendingState holds requested steps until the UI is shown. The UI is only
+ // shown once the TransportAvailabilityInfo is available, but authenticators
+ // may request, e.g., PIN entry prior to that.
+ absl::optional<QWebEngineWebAuthUxRequest::WebAuthUxState> m_pendingState;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // AUTHENTICATOR_REQUEST_DIALOG_CONTROLLER_P_H
diff --git a/src/core/autofill_client_qt.cpp b/src/core/autofill_client_qt.cpp
new file mode 100644
index 000000000..3bdc62e19
--- /dev/null
+++ b/src/core/autofill_client_qt.cpp
@@ -0,0 +1,147 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "autofill_client_qt.h"
+
+#include "autofill_popup_controller.h"
+#include "autofill_popup_controller_p.h"
+#include "render_widget_host_view_qt.h"
+#include "type_conversion.h"
+#include "web_contents_adapter_client.h"
+#include "web_contents_view_qt.h"
+
+#include "chrome/browser/profiles/profile.h"
+#include "components/autofill/core/common/autofill_prefs.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+
+namespace QtWebEngineCore {
+
+void AutofillClientQt::CreateForWebContents(content::WebContents *contents)
+{
+ DCHECK(contents);
+ if (!FromWebContents(contents))
+ contents->SetUserData(UserDataKey(), base::WrapUnique(new AutofillClientQt(contents)));
+}
+
+AutofillClientQt::AutofillClientQt(content::WebContents *webContents)
+ : autofill::ContentAutofillClient(
+ webContents, base::BindRepeating(&autofill::BrowserDriverInitHook, this, ""))
+ , content::WebContentsObserver(webContents)
+ , m_popupController(new AutofillPopupController(new AutofillPopupControllerPrivate))
+{
+}
+
+AutofillClientQt::~AutofillClientQt() { }
+
+autofill::PersonalDataManager *AutofillClientQt::GetPersonalDataManager()
+{
+ return nullptr;
+}
+
+autofill::AutocompleteHistoryManager *AutofillClientQt::GetAutocompleteHistoryManager()
+{
+ return nullptr;
+}
+
+PrefService *AutofillClientQt::GetPrefs()
+{
+ return const_cast<PrefService *>(std::as_const(*this).GetPrefs());
+}
+
+const PrefService *AutofillClientQt::GetPrefs() const
+{
+ Profile *profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext());
+ return profile->GetPrefs();
+}
+
+void AutofillClientQt::ShowAutofillPopup(const autofill::AutofillClient::PopupOpenArgs &open_args,
+ base::WeakPtr<autofill::AutofillPopupDelegate> delegate)
+{
+ m_popupController->d->delegate = delegate;
+ m_popupController->d->suggestions = open_args.suggestions;
+ m_popupController->updateModel();
+
+ bool autoSelectFirstSuggestion =
+ open_args.trigger_source == autofill::AutofillSuggestionTriggerSource::kTextFieldDidReceiveKeyDown;
+
+ adapterClient()->showAutofillPopup(m_popupController.data(),
+ QRect(toQt(gfx::ToEnclosingRect(open_args.element_bounds))),
+ autoSelectFirstSuggestion);
+}
+
+void AutofillClientQt::UpdateAutofillPopupDataListValues(const std::vector<std::u16string> &values,
+ const std::vector<std::u16string> &labels)
+{
+ Q_UNUSED(labels);
+
+ if (values.empty())
+ HideAutofillPopup(autofill::PopupHidingReason::kNoSuggestions);
+}
+
+void AutofillClientQt::PinPopupView()
+{
+ // Called by password_manager component only.
+ NOTIMPLEMENTED();
+}
+
+autofill::AutofillClient::PopupOpenArgs AutofillClientQt::GetReopenPopupArgs(autofill::AutofillSuggestionTriggerSource trigger_source) const
+{
+ // Called by password_manager component only.
+ NOTIMPLEMENTED();
+ return autofill::AutofillClient::PopupOpenArgs();
+}
+
+std::vector<autofill::Suggestion> AutofillClientQt::GetPopupSuggestions() const
+{
+ // Called by password_manager component only.
+ NOTIMPLEMENTED();
+ return {};
+}
+
+void AutofillClientQt::UpdatePopup(const std::vector<autofill::Suggestion> &, autofill::PopupType, autofill::AutofillSuggestionTriggerSource)
+{
+ // Called by password_manager component only.
+ NOTIMPLEMENTED();
+}
+
+void AutofillClientQt::HideAutofillPopup(autofill::PopupHidingReason)
+{
+ adapterClient()->hideAutofillPopup();
+}
+
+bool AutofillClientQt::IsAutocompleteEnabled() const
+{
+ return autofill::prefs::IsAutocompleteEnabled(GetPrefs());
+}
+
+bool AutofillClientQt::IsPasswordManagerEnabled()
+{
+ return false;
+}
+
+bool AutofillClientQt::IsOffTheRecord()
+{
+ return web_contents()->GetBrowserContext()->IsOffTheRecord();
+}
+
+scoped_refptr<network::SharedURLLoaderFactory> AutofillClientQt::GetURLLoaderFactory()
+{
+ return nullptr;
+}
+
+void AutofillClientQt::PropagateAutofillPredictionsDeprecated(autofill::AutofillDriver *,
+ const std::vector<autofill::FormStructure *> &)
+{
+ // For testing purposes only.
+ NOTIMPLEMENTED();
+}
+
+WebContentsAdapterClient *AutofillClientQt::adapterClient()
+{
+ return WebContentsViewQt::from(
+ static_cast<content::WebContentsImpl *>(web_contents())->GetView())
+ ->client();
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/autofill_client_qt.h b/src/core/autofill_client_qt.h
new file mode 100644
index 000000000..cd38de462
--- /dev/null
+++ b/src/core/autofill_client_qt.h
@@ -0,0 +1,76 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef AUTOFILL_CLIENT_QT_H
+#define AUTOFILL_CLIENT_QT_H
+
+#include <string>
+#include <vector>
+
+#include "base/memory/weak_ptr.h"
+#include "components/autofill/content/browser/content_autofill_client.h"
+#include "content/public/browser/web_contents_observer.h"
+#include "content/public/browser/web_contents_user_data.h"
+
+#include <QScopedPointer>
+
+namespace QtWebEngineCore {
+
+class AutofillPopupController;
+class WebContentsAdapterClient;
+
+class AutofillClientQt : public autofill::ContentAutofillClient,
+ public content::WebContentsObserver
+{
+public:
+ ~AutofillClientQt() override;
+
+ static void CreateForWebContents(content::WebContents *contents);
+
+ // autofill::AutofillClient overrides:
+ autofill::PersonalDataManager *GetPersonalDataManager() override;
+ autofill::AutocompleteHistoryManager *GetAutocompleteHistoryManager() override;
+ PrefService *GetPrefs() override;
+ const PrefService *GetPrefs() const override;
+
+ void ShowAutofillPopup(const autofill::AutofillClient::PopupOpenArgs &open_args,
+ base::WeakPtr<autofill::AutofillPopupDelegate> delegate) override;
+ void UpdateAutofillPopupDataListValues(const std::vector<std::u16string> &values,
+ const std::vector<std::u16string> &labels) override;
+ void PinPopupView() override;
+ PopupOpenArgs GetReopenPopupArgs(
+ autofill::AutofillSuggestionTriggerSource trigger_source) const override;
+ std::vector<autofill::Suggestion> GetPopupSuggestions() const override;
+ void UpdatePopup(const std::vector<autofill::Suggestion>& suggestions,
+ autofill::PopupType popup_type,
+ autofill::AutofillSuggestionTriggerSource trigger_source) override;
+ void HideAutofillPopup(autofill::PopupHidingReason reason) override;
+ bool IsAutocompleteEnabled() const override;
+ bool IsPasswordManagerEnabled() override;
+ void PropagateAutofillPredictionsDeprecated(autofill::AutofillDriver *,
+ const std::vector<autofill::FormStructure *> &) override;
+ bool IsOffTheRecord() override;
+ scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
+
+private:
+ explicit AutofillClientQt(content::WebContents *webContents);
+
+ WebContentsAdapterClient *adapterClient();
+
+ QScopedPointer<AutofillPopupController> m_popupController;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // AUTOFILL_CLIENT_QT_H
diff --git a/src/core/autofill_popup_controller.cpp b/src/core/autofill_popup_controller.cpp
new file mode 100644
index 000000000..a6baf5fc2
--- /dev/null
+++ b/src/core/autofill_popup_controller.cpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "autofill_popup_controller.h"
+#include "autofill_popup_controller_p.h"
+
+#include "components/autofill/core/browser/ui/autofill_popup_delegate.h"
+#include "components/autofill/core/browser/ui/suggestion.h"
+
+namespace QtWebEngineCore {
+
+AutofillPopupController::AutofillPopupController(AutofillPopupControllerPrivate *dd)
+{
+ Q_ASSERT(dd);
+ d.reset(dd);
+}
+
+AutofillPopupController::~AutofillPopupController() { }
+
+void AutofillPopupController::setCurrentIndex(const QModelIndex &index)
+{
+ if (m_currentIndex == index)
+ return;
+
+ m_currentIndex = index;
+
+ if (m_currentIndex.isValid()) {
+ const autofill::Suggestion &suggestion = d->suggestions[m_currentIndex.row()];
+ d->delegate->DidSelectSuggestion(suggestion, autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked);
+ }
+
+ Q_EMIT currentIndexChanged(index);
+}
+
+void AutofillPopupController::selectPreviousSuggestion()
+{
+ if (!m_currentIndex.isValid()) {
+ setCurrentIndex(m_model.index(m_model.rowCount() - 1, 0));
+ return;
+ }
+
+ if (m_currentIndex.row() == 0) {
+ selectLastSuggestion();
+ return;
+ }
+
+ setCurrentIndex(m_model.index(m_currentIndex.row() - 1, 0));
+}
+
+void AutofillPopupController::selectNextSuggestion()
+{
+ if (!m_currentIndex.isValid()) {
+ setCurrentIndex(m_model.index(0, 0));
+ return;
+ }
+
+ if (m_currentIndex.row() == m_model.rowCount() - 1) {
+ selectFirstSuggestion();
+ return;
+ }
+
+ setCurrentIndex(m_model.index(m_currentIndex.row() + 1, 0));
+}
+
+void AutofillPopupController::selectFirstSuggestion()
+{
+ setCurrentIndex(m_model.index(0, 0));
+}
+
+void AutofillPopupController::selectLastSuggestion()
+{
+ setCurrentIndex(m_model.index(m_model.rowCount() - 1, 0));
+}
+
+void AutofillPopupController::acceptSuggestion()
+{
+ if (!m_currentIndex.isValid())
+ return;
+
+ const int index = m_currentIndex.row();
+ const autofill::Suggestion &suggestion = d->suggestions[index];
+ d->delegate->DidAcceptSuggestion(suggestion, index, autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked);
+}
+
+void AutofillPopupController::notifyPopupShown()
+{
+ d->delegate->OnPopupShown();
+}
+
+void AutofillPopupController::notifyPopupHidden()
+{
+ d->delegate->OnPopupHidden();
+}
+
+void AutofillPopupController::selectSuggestion(int index)
+{
+ if (index < 0)
+ setCurrentIndex(QModelIndex());
+ else
+ setCurrentIndex(m_model.index(index, 0));
+}
+
+void AutofillPopupController::updateModel()
+{
+ QStringList values;
+ for (size_t i = 0; i < d->suggestions.size(); ++i) {
+ values.append(QString::fromStdU16String(d->suggestions[i].main_text.value));
+ }
+ m_model.setStringList(values);
+ setCurrentIndex(QModelIndex());
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/autofill_popup_controller.h b/src/core/autofill_popup_controller.h
new file mode 100644
index 000000000..1b4d8d7e8
--- /dev/null
+++ b/src/core/autofill_popup_controller.h
@@ -0,0 +1,62 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef AUTOFILL_POPUP_CONTROLLER_H
+#define AUTOFILL_POPUP_CONTROLLER_H
+
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+
+#include <QModelIndex>
+#include <QObject>
+#include <QScopedPointer>
+#include <QStringListModel>
+
+namespace QtWebEngineCore {
+
+class AutofillPopupControllerPrivate;
+
+class Q_WEBENGINECORE_EXPORT AutofillPopupController : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QStringListModel *model READ model CONSTANT FINAL)
+
+public:
+ ~AutofillPopupController();
+
+ QStringListModel *model() { return &m_model; }
+
+ void selectPreviousSuggestion();
+ void selectNextSuggestion();
+ void selectFirstSuggestion();
+ void selectLastSuggestion();
+
+ void notifyPopupShown();
+ void notifyPopupHidden();
+
+public Q_SLOTS:
+ void selectSuggestion(int index);
+ void acceptSuggestion();
+
+Q_SIGNALS:
+ void currentIndexChanged(const QModelIndex &index);
+
+private:
+ AutofillPopupController(AutofillPopupControllerPrivate *);
+ QScopedPointer<AutofillPopupControllerPrivate> d;
+
+ void setCurrentIndex(const QModelIndex &index);
+
+ // Only called by AutofillClientQt:
+ void updateModel();
+
+ QStringListModel m_model;
+ QModelIndex m_currentIndex;
+
+ friend class AutofillClientQt;
+};
+
+} // namespace QtWebEngineCore
+
+Q_DECLARE_METATYPE(QtWebEngineCore::AutofillPopupController *)
+
+#endif // AUTOFILL_POPUP_CONTROLLER_H
diff --git a/src/core/autofill_popup_controller_p.h b/src/core/autofill_popup_controller_p.h
new file mode 100644
index 000000000..886fe4dcd
--- /dev/null
+++ b/src/core/autofill_popup_controller_p.h
@@ -0,0 +1,40 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef AUTOFILL_POPUP_CONTROLLER_P_H
+#define AUTOFILL_POPUP_CONTROLLER_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <vector>
+
+#include "base/memory/weak_ptr.h"
+#include "components/autofill/core/browser/ui/suggestion.h"
+
+namespace autofill {
+class AutofillPopupDelegate;
+}
+
+namespace QtWebEngineCore {
+
+class AutofillPopupControllerPrivate
+{
+public:
+ AutofillPopupControllerPrivate() = default;
+
+ base::WeakPtr<autofill::AutofillPopupDelegate> delegate = nullptr;
+ std::vector<autofill::Suggestion> suggestions;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // AUTOFILL_POPUP_CONTROLLER_P_H
diff --git a/src/core/browser_accessibility_manager_qt.cpp b/src/core/browser_accessibility_manager_qt.cpp
index 5968bfd30..077856266 100644
--- a/src/core/browser_accessibility_manager_qt.cpp
+++ b/src/core/browser_accessibility_manager_qt.cpp
@@ -1,79 +1,67 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "qtwebenginecoreglobal.h"
+
+#include "content/browser/accessibility/browser_accessibility_manager.h"
+
+#include <QtGui/qtguiglobal.h>
+
+#if QT_CONFIG(accessibility)
+#include "browser_accessibility_qt.h"
#include "browser_accessibility_manager_qt.h"
+#include "render_widget_host_view_qt.h" // WebContentsAccessibilityQt
+#include "content/browser/accessibility/browser_accessibility.h"
#include "ui/accessibility/ax_enums.mojom.h"
-#include "browser_accessibility_qt.h"
-using namespace blink;
+#include <QtGui/qaccessible.h>
+#endif // QT_CONFIG(accessibility)
namespace content {
-BrowserAccessibilityManager* BrowserAccessibilityManager::Create(
- const ui::AXTreeUpdate& initialTree,
- BrowserAccessibilityDelegate* delegate,
- BrowserAccessibilityFactory* factory)
+// static
+BrowserAccessibilityManager *BrowserAccessibilityManager::Create(
+ const ui::AXTreeUpdate &initialTree,
+ WebAXPlatformTreeManagerDelegate *delegate)
{
#if QT_CONFIG(accessibility)
- return new BrowserAccessibilityManagerQt(nullptr, initialTree, delegate, factory);
+ Q_ASSERT(delegate);
+ QtWebEngineCore::WebContentsAccessibilityQt *access = nullptr;
+ access = static_cast<QtWebEngineCore::WebContentsAccessibilityQt *>(delegate->AccessibilityGetWebContentsAccessibility());
+
+ // Accessibility is not supported for guest views and child frames.
+ if (!access) {
+ return nullptr;
+ }
+
+ return new BrowserAccessibilityManagerQt(access, initialTree, delegate);
#else
- delete factory;
+ Q_UNUSED(initialTree);
+ Q_UNUSED(delegate);
return nullptr;
#endif // QT_CONFIG(accessibility)
}
-BrowserAccessibility *BrowserAccessibility::Create()
+// static
+BrowserAccessibilityManager *BrowserAccessibilityManager::Create(
+ WebAXPlatformTreeManagerDelegate *delegate)
{
#if QT_CONFIG(accessibility)
- return new BrowserAccessibilityQt();
+ return BrowserAccessibilityManager::Create(BrowserAccessibilityManagerQt::GetEmptyDocument(), delegate);
#else
+ Q_UNUSED(delegate);
return nullptr;
-#endif // QT_CONFIG(accessibility)
+#endif
}
#if QT_CONFIG(accessibility)
BrowserAccessibilityManagerQt::BrowserAccessibilityManagerQt(
- QObject *parentObject, const ui::AXTreeUpdate &initialTree,
- BrowserAccessibilityDelegate* delegate, BrowserAccessibilityFactory* factory)
- : BrowserAccessibilityManager(delegate, factory)
- , m_parentObject(parentObject)
+ QtWebEngineCore::WebContentsAccessibilityQt *webContentsAccessibility,
+ const ui::AXTreeUpdate &initialTree,
+ WebAXPlatformTreeManagerDelegate* delegate)
+ : BrowserAccessibilityManager(delegate)
+ , m_webContentsAccessibility(webContentsAccessibility)
{
Initialize(initialTree);
m_valid = true; // BrowserAccessibilityQt can start using the AXTree
@@ -86,17 +74,28 @@ BrowserAccessibilityManagerQt::~BrowserAccessibilityManagerQt()
QAccessibleInterface *BrowserAccessibilityManagerQt::rootParentAccessible()
{
- return QAccessible::queryAccessibleInterface(m_parentObject);
+ content::BrowserAccessibility *parent_node = GetParentNodeFromParentTreeAsBrowserAccessibility();
+ if (!parent_node) {
+ Q_ASSERT(m_webContentsAccessibility);
+ return QAccessible::queryAccessibleInterface(m_webContentsAccessibility->accessibilityParentObject());
+ }
+
+ auto *parent_manager =
+ static_cast<BrowserAccessibilityManagerQt *>(parent_node->manager());
+ return parent_manager->rootParentAccessible();
}
void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
- BrowserAccessibility* node)
+ BrowserAccessibility *node,
+ int action_request_id)
{
- BrowserAccessibilityQt *iface = static_cast<BrowserAccessibilityQt*>(node);
+ auto *iface = toQAccessibleInterface(node);
switch (event_type) {
case ax::mojom::Event::kFocus: {
QAccessibleEvent event(iface, QAccessible::Focus);
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
break;
}
@@ -104,6 +103,8 @@ void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
QAccessible::State change;
change.checked = true;
QAccessibleStateChangeEvent event(iface, change);
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
break;
}
@@ -112,6 +113,8 @@ void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
if (QAccessibleValueInterface *valueIface = iface->valueInterface())
value = valueIface->currentValue();
QAccessibleValueChangeEvent event(iface, value);
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
break;
}
@@ -123,6 +126,8 @@ void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
break;
case ax::mojom::Event::kTextChanged: {
QAccessibleTextUpdateEvent event(iface, -1, QString(), QString());
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
break;
}
@@ -134,9 +139,13 @@ void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
textIface->selection(0, &start, &end);
if (start == end) {
QAccessibleTextCursorEvent event(iface, start);
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
} else {
QAccessibleTextSelectionEvent event(iface, start, end);
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
}
}
@@ -148,14 +157,20 @@ void BrowserAccessibilityManagerQt::FireBlinkEvent(ax::mojom::Event event_type,
}
void BrowserAccessibilityManagerQt::FireGeneratedEvent(ui::AXEventGenerator::Event event_type,
- BrowserAccessibility* node)
+ const ui::AXNode *node)
{
- BrowserAccessibilityQt *iface = static_cast<BrowserAccessibilityQt*>(node);
+ BrowserAccessibilityManager::FireGeneratedEvent(event_type, node);
+
+ BrowserAccessibility *wrapper = GetFromAXNode(node);
+ DCHECK(wrapper);
+ auto *iface = toQAccessibleInterface(wrapper);
switch (event_type) {
- case ui::AXEventGenerator::Event::VALUE_CHANGED:
+ case ui::AXEventGenerator::Event::VALUE_IN_TEXT_FIELD_CHANGED:
if (iface->role() == QAccessible::EditableText) {
QAccessibleTextUpdateEvent event(iface, -1, QString(), QString());
+ if (event.object())
+ event.setChild(-1);
QAccessible::updateAccessibility(&event);
}
break;
diff --git a/src/core/browser_accessibility_manager_qt.h b/src/core/browser_accessibility_manager_qt.h
index 6d6086811..e36edd979 100644
--- a/src/core/browser_accessibility_manager_qt.h
+++ b/src/core/browser_accessibility_manager_qt.h
@@ -1,81 +1,44 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BROWSER_ACCESSIBILITY_MANAGER_QT_H
#define BROWSER_ACCESSIBILITY_MANAGER_QT_H
#include "content/browser/accessibility/browser_accessibility_manager.h"
-#include <QtCore/qobject.h>
-#include <QtGui/qtgui-config.h>
+#include <QtCore/qtclasshelpermacros.h>
+#include <QtCore/qtconfigmacros.h>
-#if QT_CONFIG(accessibility)
+QT_FORWARD_DECLARE_CLASS(QAccessibleInterface)
-QT_BEGIN_NAMESPACE
-class QAccessibleInterface;
-QT_END_NAMESPACE
+namespace QtWebEngineCore {
+class WebContentsAccessibilityQt;
+}
namespace content {
class BrowserAccessibilityManagerQt : public BrowserAccessibilityManager
{
public:
- BrowserAccessibilityManagerQt(QObject* parentObject,
- const ui::AXTreeUpdate& initialTree,
- BrowserAccessibilityDelegate* delegate,
- BrowserAccessibilityFactory* factory = new BrowserAccessibilityFactory());
+ BrowserAccessibilityManagerQt(QtWebEngineCore::WebContentsAccessibilityQt *webContentsAccessibility,
+ const ui::AXTreeUpdate &initialTree,
+ WebAXPlatformTreeManagerDelegate *delegate);
~BrowserAccessibilityManagerQt() override;
void FireBlinkEvent(ax::mojom::Event event_type,
- BrowserAccessibility* node) override;
+ BrowserAccessibility *node,
+ int action_request_id) override;
void FireGeneratedEvent(ui::AXEventGenerator::Event event_type,
- BrowserAccessibility* node) override;
+ const ui::AXNode *node) override;
QAccessibleInterface *rootParentAccessible();
bool isValid() const { return m_valid; }
private:
Q_DISABLE_COPY(BrowserAccessibilityManagerQt)
- QObject *m_parentObject;
+ QtWebEngineCore::WebContentsAccessibilityQt *m_webContentsAccessibility;
bool m_valid = false;
};
}
-#endif // QT_CONFIG(accessibility)
-#endif
+#endif // BROWSER_ACCESSIBILITY_MANAGER_QT_H
diff --git a/src/core/browser_accessibility_qt.cpp b/src/core/browser_accessibility_qt.cpp
index de78eb85d..de3347df3 100644
--- a/src/core/browser_accessibility_qt.cpp
+++ b/src/core/browser_accessibility_qt.cpp
@@ -1,88 +1,197 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
#include "browser_accessibility_qt.h"
-
-#if QT_CONFIG(accessibility)
-
-#include "ui/accessibility/ax_enums.mojom.h"
-
#include "browser_accessibility_manager_qt.h"
#include "qtwebenginecoreglobal_p.h"
#include "type_conversion.h"
-using namespace blink;
-using QtWebEngineCore::toQt;
+#if QT_CONFIG(accessibility)
+#include "content/browser/accessibility/browser_accessibility.h"
+#include "ui/accessibility/ax_enums.mojom.h"
-namespace content {
+#include <QtGui/qaccessible.h>
+
+namespace QtWebEngineCore {
+class BrowserAccessibilityInterface;
+
+class BrowserAccessibilityQt
+ : public content::BrowserAccessibility
+{
+public:
+ BrowserAccessibilityQt(content::BrowserAccessibilityManager *manager, ui::AXNode *node);
+ ~BrowserAccessibilityQt();
+
+ bool isReady() const;
+
+ QtWebEngineCore::BrowserAccessibilityInterface *interface = nullptr;
+};
+
+class BrowserAccessibilityInterface
+ : public QAccessibleInterface
+ , public QAccessibleActionInterface
+ , public QAccessibleTextInterface
+ , public QAccessibleValueInterface
+ , public QAccessibleTableInterface
+ , public QAccessibleTableCellInterface
+{
+public:
+ BrowserAccessibilityInterface(BrowserAccessibilityQt *chromiumInterface);
+ ~BrowserAccessibilityInterface() override;
+
+ void destroy();
+
+ // QAccessibleInterface
+ bool isValid() const override;
+ QObject *object() const override;
+ QAccessibleInterface *childAt(int x, int y) const override;
+ void *interface_cast(QAccessible::InterfaceType type) override;
+
+ // navigation, hierarchy
+ QAccessibleInterface *parent() const override;
+ QAccessibleInterface *child(int index) const override;
+ QAccessibleInterface *focusChild() const override;
+ int childCount() const override;
+ int indexOfChild(const QAccessibleInterface *) const override;
+
+ // properties and state
+ QString text(QAccessible::Text t) const override;
+ void setText(QAccessible::Text t, const QString &text) override;
+ QRect rect() const override;
+ QAccessible::Role role() const override;
+ QAccessible::State state() const override;
+
+ // QAccessibleActionInterface
+ QStringList actionNames() const override;
+ void doAction(const QString &actionName) override;
+ QStringList keyBindingsForAction(const QString &actionName) const override;
+
+ // QAccessibleTextInterface
+ void addSelection(int startOffset, int endOffset) override;
+ QString attributes(int offset, int *startOffset, int *endOffset) const override;
+ int cursorPosition() const override;
+ QRect characterRect(int offset) const override;
+ int selectionCount() const override;
+ int offsetAtPoint(const QPoint &point) const override;
+ void selection(int selectionIndex, int *startOffset, int *endOffset) const override;
+ QString text(int startOffset, int endOffset) const override;
+ void removeSelection(int selectionIndex) override;
+ void setCursorPosition(int position) override;
+ void setSelection(int selectionIndex, int startOffset, int endOffset) override;
+ int characterCount() const override;
+ void scrollToSubstring(int startIndex, int endIndex) override;
+
+ // QAccessibleValueInterface
+ QVariant currentValue() const override;
+ void setCurrentValue(const QVariant &value) override;
+ QVariant maximumValue() const override;
+ QVariant minimumValue() const override;
+ QVariant minimumStepSize() const override;
+
+ // QAccessibleTableInterface
+ QAccessibleInterface *cellAt(int row, int column) const override;
+ QAccessibleInterface *caption() const override;
+ QAccessibleInterface *summary() const override;
+ QString columnDescription(int column) const override;
+ QString rowDescription(int row) const override;
+ int columnCount() const override;
+ int rowCount() const override;
+ // selection
+ int selectedCellCount() const override;
+ int selectedColumnCount() const override;
+ int selectedRowCount() const override;
+ QList<QAccessibleInterface *> selectedCells() const override;
+ QList<int> selectedColumns() const override;
+ QList<int> selectedRows() const override;
+ bool isColumnSelected(int column) const override;
+ bool isRowSelected(int row) const override;
+ bool selectRow(int row) override;
+ bool selectColumn(int column) override;
+ bool unselectRow(int row) override;
+ bool unselectColumn(int column) override;
+
+ // QAccessibleTableCellInterface
+ int columnExtent() const override;
+ QList<QAccessibleInterface *> columnHeaderCells() const override;
+ int columnIndex() const override;
+ int rowExtent() const override;
+ QList<QAccessibleInterface *> rowHeaderCells() const override;
+ int rowIndex() const override;
+ bool isSelected() const override;
+ QAccessibleInterface *table() const override;
+
+ void modelChange(QAccessibleTableModelChangeEvent *event) override;
+
+private:
+ content::BrowserAccessibility *findTable() const;
+
+ QObject *m_object = nullptr;
+ QAccessible::Id m_id = 0;
+ BrowserAccessibilityQt *q;
+};
+
+BrowserAccessibilityQt::BrowserAccessibilityQt(content::BrowserAccessibilityManager *manager,
+ ui::AXNode *node)
+ : content::BrowserAccessibility(manager, node)
+ , interface(new BrowserAccessibilityInterface(this))
+{
+}
+
+BrowserAccessibilityQt::~BrowserAccessibilityQt()
+{
+ if (interface)
+ interface->destroy();
+}
+
+bool BrowserAccessibilityQt::isReady() const
+{
+ // FIXME: This is just a workaround, remove this when the commented out assert in
+ // BrowserAccessibilityManager::GetFromID(int32_t id) gets fixed.
+ return manager()->GetFromID(node()->id()) != nullptr;
+}
+
+BrowserAccessibilityInterface::BrowserAccessibilityInterface(BrowserAccessibilityQt *chromiumInterface)
+ : q(chromiumInterface)
+{
+ if (parent() && parent()->object()) {
+ m_object = new QObject(parent()->object());
+ QString name = toQt(q->GetAuthorUniqueId());
+ if (!name.isEmpty())
+ m_object->setObjectName(name);
+ }
-const BrowserAccessibilityQt *ToBrowserAccessibilityQt(const BrowserAccessibility *obj)
-{
- return static_cast<const BrowserAccessibilityQt *>(obj);
+ m_id = QAccessible::registerAccessibleInterface(this);
}
-QAccessibleInterface *toQAccessibleInterface(BrowserAccessibility *obj)
+BrowserAccessibilityInterface::~BrowserAccessibilityInterface()
{
- return static_cast<BrowserAccessibilityQt *>(obj);
+ q->interface = nullptr;
}
-BrowserAccessibilityQt::BrowserAccessibilityQt()
+void BrowserAccessibilityInterface::destroy()
{
- QAccessible::registerAccessibleInterface(this);
+ QAccessible::deleteAccessibleInterface(m_id);
}
-bool BrowserAccessibilityQt::isValid() const
+bool BrowserAccessibilityInterface::isValid() const
{
- auto managerQt = static_cast<BrowserAccessibilityManagerQt *>(manager_);
+ if (!q->isReady())
+ return false;
+
+ auto managerQt = static_cast<content::BrowserAccessibilityManagerQt *>(q->manager());
return managerQt && managerQt->isValid();
}
-QObject *BrowserAccessibilityQt::object() const
+QObject *BrowserAccessibilityInterface::object() const
{
- return 0;
+ return m_object;
}
-QAccessibleInterface *BrowserAccessibilityQt::childAt(int x, int y) const
+QAccessibleInterface *BrowserAccessibilityInterface::childAt(int x, int y) const
{
for (int i = 0; i < childCount(); ++i) {
QAccessibleInterface *childIface = child(i);
@@ -90,10 +199,10 @@ QAccessibleInterface *BrowserAccessibilityQt::childAt(int x, int y) const
if (childIface->rect().contains(x,y))
return childIface;
}
- return 0;
+ return nullptr;
}
-void *BrowserAccessibilityQt::interface_cast(QAccessible::InterfaceType type)
+void *BrowserAccessibilityInterface::interface_cast(QAccessible::InterfaceType type)
{
switch (type) {
case QAccessible::ActionInterface:
@@ -101,7 +210,7 @@ void *BrowserAccessibilityQt::interface_cast(QAccessible::InterfaceType type)
return static_cast<QAccessibleActionInterface*>(this);
break;
case QAccessible::TextInterface:
- if (HasState(ax::mojom::State::kEditable))
+ if (q->HasState(ax::mojom::State::kEditable))
return static_cast<QAccessibleTextInterface*>(this);
break;
case QAccessible::ValueInterface: {
@@ -123,35 +232,36 @@ void *BrowserAccessibilityQt::interface_cast(QAccessible::InterfaceType type)
}
case QAccessible::TableCellInterface: {
QAccessible::Role r = role();
- if (r == QAccessible::Cell ||
- r == QAccessible::ListItem ||
- r == QAccessible::TreeItem)
- return static_cast<QAccessibleTableCellInterface*>(this);
+ if (r == QAccessible::Cell || r == QAccessible::ListItem || r == QAccessible::TreeItem) {
+ if (findTable())
+ return static_cast<QAccessibleTableCellInterface *>(this);
+ }
break;
}
default:
break;
}
- return 0;
+ return nullptr;
}
-QAccessibleInterface *BrowserAccessibilityQt::parent() const
+QAccessibleInterface *BrowserAccessibilityInterface::parent() const
{
- BrowserAccessibility *p = PlatformGetParent();
- if (p)
- return static_cast<BrowserAccessibilityQt*>(p);
- return static_cast<BrowserAccessibilityManagerQt*>(manager())->rootParentAccessible();
+ content::BrowserAccessibility *chromiumParent = q->PlatformGetParent();
+ if (chromiumParent)
+ return toQAccessibleInterface(chromiumParent);
+ return static_cast<content::BrowserAccessibilityManagerQt*>(q->manager())->rootParentAccessible();
}
-QAccessibleInterface *BrowserAccessibilityQt::child(int index) const
+QAccessibleInterface *BrowserAccessibilityInterface::child(int index) const
{
- return static_cast<BrowserAccessibilityQt*>(BrowserAccessibility::PlatformGetChild(index));
+ content::BrowserAccessibility *chromiumChild = q->PlatformGetChild(index);
+ return chromiumChild ? toQAccessibleInterface(chromiumChild) : nullptr;
}
-QAccessibleInterface *BrowserAccessibilityQt::focusChild() const
+QAccessibleInterface *BrowserAccessibilityInterface::focusChild() const
{
if (state().focused)
- return const_cast<BrowserAccessibilityQt *>(this);
+ return const_cast<BrowserAccessibilityInterface *>(this);
for (int i = 0; i < childCount(); ++i) {
if (QAccessibleInterface *iface = child(i)->focusChild())
@@ -161,57 +271,65 @@ QAccessibleInterface *BrowserAccessibilityQt::focusChild() const
return nullptr;
}
-int BrowserAccessibilityQt::childCount() const
+int BrowserAccessibilityInterface::childCount() const
{
- return PlatformChildCount();
+ return q->PlatformChildCount();
}
-int BrowserAccessibilityQt::indexOfChild(const QAccessibleInterface *iface) const
+int BrowserAccessibilityInterface::indexOfChild(const QAccessibleInterface *iface) const
{
- const BrowserAccessibilityQt *child = static_cast<const BrowserAccessibilityQt*>(iface);
- return const_cast<BrowserAccessibilityQt *>(child)->GetIndexInParent();
+ const BrowserAccessibilityInterface *child = static_cast<const BrowserAccessibilityInterface *>(iface);
+ return const_cast<BrowserAccessibilityInterface *>(child)->q->GetIndexInParent().value();
}
-QString BrowserAccessibilityQt::text(QAccessible::Text t) const
+QString BrowserAccessibilityInterface::text(QAccessible::Text t) const
{
+ if (!q->isReady())
+ return QString();
+
switch (t) {
case QAccessible::Name:
- return toQt(GetStringAttribute(ax::mojom::StringAttribute::kName));
+ return toQt(q->GetStringAttribute(ax::mojom::StringAttribute::kName));
case QAccessible::Description:
- return toQt(GetStringAttribute(ax::mojom::StringAttribute::kDescription));
+ return toQt(q->GetStringAttribute(ax::mojom::StringAttribute::kDescription));
case QAccessible::Value:
- return toQt(GetStringAttribute(ax::mojom::StringAttribute::kValue));
+ return toQt(q->GetStringAttribute(ax::mojom::StringAttribute::kValue));
case QAccessible::Accelerator:
- return toQt(GetStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts));
+ return toQt(q->GetStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts));
default:
break;
}
return QString();
}
-void BrowserAccessibilityQt::setText(QAccessible::Text t, const QString &text)
+void BrowserAccessibilityInterface::setText(QAccessible::Text t, const QString &text)
{
}
-QRect BrowserAccessibilityQt::rect() const
+QRect BrowserAccessibilityInterface::rect() const
{
- if (!manager()) // needed implicitly by GetScreenBoundsRect()
+ if (!q->manager() || !q->isReady()) // needed implicitly by GetScreenBoundsRect()
return QRect();
- gfx::Rect bounds = GetUnclippedScreenBoundsRect();
+ gfx::Rect bounds = q->GetUnclippedScreenBoundsRect();
+ bounds = gfx::ScaleToRoundedRect(bounds, 1.f / q->manager()->device_scale_factor()); // FIXME: check
return QRect(bounds.x(), bounds.y(), bounds.width(), bounds.height());
}
-QAccessible::Role BrowserAccessibilityQt::role() const
+QAccessible::Role BrowserAccessibilityInterface::role() const
{
- switch (GetRole()) {
+ switch (q->GetRole()) {
case ax::mojom::Role::kNone:
case ax::mojom::Role::kUnknown:
return QAccessible::NoRole;
+ // Internal roles (matching auralinux and win)
+ case ax::mojom::Role::kKeyboard:
+ case ax::mojom::Role::kImeCandidate:
+ return QAccessible::NoRole;
+
// Used by Chromium to distinguish between the root of the tree
// for this page, and a web area for a frame within this page.
- case ax::mojom::Role::kWebArea:
case ax::mojom::Role::kWebView:
case ax::mojom::Role::kRootWebArea: // not sure if we need to make a diff here, but this seems common
return QAccessible::WebDocument;
@@ -223,8 +341,6 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kAlert:
case ax::mojom::Role::kAlertDialog:
return QAccessible::AlertMessage;
- case ax::mojom::Role::kAnchor:
- return QAccessible::Link;
case ax::mojom::Role::kApplication:
return QAccessible::Document; // returning Application here makes Qt return the top level app object
case ax::mojom::Role::kArticle:
@@ -261,10 +377,11 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kTextFieldWithComboBox:
return QAccessible::ComboBox;
+ case ax::mojom::Role::kComboBoxSelect:
+ return QAccessible::PopupMenu;
case ax::mojom::Role::kComplementary:
return QAccessible::ComplementaryContent;
case ax::mojom::Role::kComment:
- case ax::mojom::Role::kCommentSection:
return QAccessible::Section;
case ax::mojom::Role::kContentDeletion:
case ax::mojom::Role::kContentInsertion:
@@ -328,6 +445,11 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kDocIndex:
case ax::mojom::Role::kDocIntroduction:
case ax::mojom::Role::kDocNotice:
+ return QAccessible::Section;
+ case ax::mojom::Role::kDocPageFooter:
+ return QAccessible::Footer;
+ case ax::mojom::Role::kDocPageHeader:
+ return QAccessible::Heading;
case ax::mojom::Role::kDocPageList:
case ax::mojom::Role::kDocPart:
case ax::mojom::Role::kDocPreface:
@@ -353,7 +475,8 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kFigure:
return QAccessible::Section;
case ax::mojom::Role::kFooter:
- return QAccessible::Footer;
+ // CORE-AAM recommends LANDMARK instead of FOOTER.
+ return QAccessible::Section;
case ax::mojom::Role::kFooterAsNonLandmark:
return QAccessible::Section;
case ax::mojom::Role::kForm:
@@ -377,23 +500,16 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::WebDocument;
case ax::mojom::Role::kIframePresentational:
return QAccessible::Grouping;
- case ax::mojom::Role::kIgnored:
- return QAccessible::NoRole;
case ax::mojom::Role::kImage:
return QAccessible::Graphic;
- case ax::mojom::Role::kImageMap:
- return QAccessible::Document;
case ax::mojom::Role::kInlineTextBox:
return QAccessible::StaticText;
case ax::mojom::Role::kInputTime:
return QAccessible::SpinBox;
- case ax::mojom::Role::kKeyboard:
- return QAccessible::NoRole; // FIXME
case ax::mojom::Role::kLabelText:
return QAccessible::StaticText;
case ax::mojom::Role::kLayoutTable:
case ax::mojom::Role::kLayoutTableCell:
- case ax::mojom::Role::kLayoutTableColumn:
case ax::mojom::Role::kLayoutTableRow:
return QAccessible::Section;
case ax::mojom::Role::kLegend:
@@ -423,7 +539,50 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kMarquee:
return QAccessible::Section;
case ax::mojom::Role::kMath:
+ case ax::mojom::Role::kMathMLMath:
return QAccessible::Equation;
+ case ax::mojom::Role::kMathMLFraction:
+ return QAccessible::Grouping;
+ case ax::mojom::Role::kMathMLIdentifier:
+ return QAccessible::StaticText;
+ case ax::mojom::Role::kMathMLMultiscripts:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLNoneScript:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLNumber:
+ return QAccessible::StaticText;
+ case ax::mojom::Role::kMathMLOperator:
+ return QAccessible::StaticText;
+ case ax::mojom::Role::kMathMLOver:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLPrescriptDelimiter:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLRoot:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLRow:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLSquareRoot:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLStringLiteral:
+ return QAccessible::StaticText;
+ case ax::mojom::Role::kMathMLSub:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLSubSup:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLSup:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLTable:
+ return QAccessible::Table;
+ case ax::mojom::Role::kMathMLTableCell:
+ return QAccessible::Cell;
+ case ax::mojom::Role::kMathMLTableRow:
+ return QAccessible::Row;
+ case ax::mojom::Role::kMathMLText:
+ return QAccessible::StaticText;
+ case ax::mojom::Role::kMathMLUnder:
+ return QAccessible::Section;
+ case ax::mojom::Role::kMathMLUnderOver:
+ return QAccessible::Section;
case ax::mojom::Role::kMenu:
return QAccessible::PopupMenu;
case ax::mojom::Role::kMenuBar:
@@ -434,8 +593,6 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::CheckBox;
case ax::mojom::Role::kMenuItemRadio:
return QAccessible::RadioButton;
- case ax::mojom::Role::kMenuButton:
- return QAccessible::MenuItem;
case ax::mojom::Role::kMenuListOption:
return QAccessible::MenuItem;
case ax::mojom::Role::kMenuListPopup:
@@ -450,12 +607,18 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::Pane;
case ax::mojom::Role::kParagraph:
return QAccessible::Paragraph;
+ case ax::mojom::Role::kPdfActionableHighlight:
+ return QAccessible::Button;
+ case ax::mojom::Role::kPdfRoot:
+ return QAccessible::Document;
+ case ax::mojom::Role::kPluginObject:
+ return QAccessible::Grouping;
case ax::mojom::Role::kPopUpButton:
return QAccessible::ComboBox;
+ case ax::mojom::Role::kPortal:
+ return QAccessible::Button;
case ax::mojom::Role::kPre:
return QAccessible::Section;
- case ax::mojom::Role::kPresentational:
- return QAccessible::NoRole; // FIXME
case ax::mojom::Role::kProgressIndicator:
return QAccessible::ProgressBar;
case ax::mojom::Role::kRadioButton:
@@ -464,8 +627,6 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::Grouping;
case ax::mojom::Role::kRegion:
return QAccessible::Section;
- case ax::mojom::Role::kRevision:
- return QAccessible::Section;
case ax::mojom::Role::kRow:
return QAccessible::Row;
case ax::mojom::Role::kRowGroup:
@@ -473,7 +634,7 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kRowHeader:
return QAccessible::RowHeader;
case ax::mojom::Role::kRuby:
- return QAccessible::StaticText;
+ return QAccessible::Grouping;
case ax::mojom::Role::kRubyAnnotation:
return QAccessible::StaticText;
case ax::mojom::Role::kScrollBar:
@@ -487,7 +648,6 @@ QAccessible::Role BrowserAccessibilityQt::role() const
case ax::mojom::Role::kSection:
return QAccessible::Section;
case ax::mojom::Role::kSlider:
- case ax::mojom::Role::kSliderThumb:
return QAccessible::Slider;
case ax::mojom::Role::kSpinButton:
return QAccessible::SpinBox;
@@ -499,10 +659,14 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::Indicator;
case ax::mojom::Role::kStrong:
return QAccessible::StaticText;
+ case ax::mojom::Role::kSubscript:
+ return QAccessible::Grouping;
case ax::mojom::Role::kSuggestion:
return QAccessible::Section;
+ case ax::mojom::Role::kSuperscript:
+ return QAccessible::Grouping;
case ax::mojom::Role::kSvgRoot:
- return QAccessible::Graphic;
+ return QAccessible::WebDocument;
case ax::mojom::Role::kSwitch:
return QAccessible::Button;
case ax::mojom::Role::kTable:
@@ -544,63 +708,68 @@ QAccessible::Role BrowserAccessibilityQt::role() const
return QAccessible::NoRole;
}
-QAccessible::State BrowserAccessibilityQt::state() const
+QAccessible::State BrowserAccessibilityInterface::state() const
{
QAccessible::State state = QAccessible::State();
- if (HasState(ax::mojom::State::kCollapsed))
+ if (!q->isReady()) {
+ state.invalid = true;
+ return state;
+ }
+
+ if (q->HasState(ax::mojom::State::kCollapsed))
state.collapsed = true;
- if (HasState(ax::mojom::State::kDefault))
+ if (q->HasState(ax::mojom::State::kDefault))
state.defaultButton = true;
- if (HasState(ax::mojom::State::kEditable))
+ if (q->HasState(ax::mojom::State::kEditable))
state.editable = true;
- if (HasState(ax::mojom::State::kExpanded))
+ if (q->HasState(ax::mojom::State::kExpanded))
state.expanded = true;
- if (HasState(ax::mojom::State::kFocusable))
+ if (q->HasState(ax::mojom::State::kFocusable))
state.focusable = true;
- if (HasState(ax::mojom::State::kHorizontal))
+ if (q->HasState(ax::mojom::State::kHorizontal))
{} // FIXME
- if (HasState(ax::mojom::State::kHovered))
+ if (q->HasState(ax::mojom::State::kHovered))
state.hotTracked = true;
- if (HasState(ax::mojom::State::kIgnored))
+ if (q->HasState(ax::mojom::State::kIgnored))
{} // FIXME
- if (HasState(ax::mojom::State::kInvisible))
+ if (q->HasState(ax::mojom::State::kInvisible))
state.invisible = true;
- if (HasState(ax::mojom::State::kLinked))
+ if (q->HasState(ax::mojom::State::kLinked))
state.linked = true;
- if (HasState(ax::mojom::State::kMultiline))
+ if (q->HasState(ax::mojom::State::kMultiline))
state.multiLine = true;
- if (HasState(ax::mojom::State::kMultiselectable))
+ if (q->HasState(ax::mojom::State::kMultiselectable))
state.multiSelectable = true;
- if (HasState(ax::mojom::State::kProtected))
+ if (q->HasState(ax::mojom::State::kProtected))
state.passwordEdit = true;
- if (HasState(ax::mojom::State::kRequired))
+ if (q->HasState(ax::mojom::State::kRequired))
{} // FIXME
- if (HasState(ax::mojom::State::kRichlyEditable))
+ if (q->HasState(ax::mojom::State::kRichlyEditable))
{} // FIXME
- if (HasState(ax::mojom::State::kVertical))
+ if (q->HasState(ax::mojom::State::kVertical))
{} // FIXME
- if (HasState(ax::mojom::State::kVisited))
+ if (q->HasState(ax::mojom::State::kVisited))
state.traversed = true;
- if (IsOffscreen())
+ if (q->IsOffscreen())
state.offscreen = true;
- if (manager()->GetFocus() == this)
+ if (q->manager()->GetFocus() == q)
state.focused = true;
- if (GetBoolAttribute(ax::mojom::BoolAttribute::kBusy))
+ if (q->GetBoolAttribute(ax::mojom::BoolAttribute::kBusy))
state.busy = true;
- if (GetBoolAttribute(ax::mojom::BoolAttribute::kModal))
+ if (q->GetBoolAttribute(ax::mojom::BoolAttribute::kModal))
state.modal = true;
- if (HasBoolAttribute(ax::mojom::BoolAttribute::kSelected)) {
+ if (q->HasBoolAttribute(ax::mojom::BoolAttribute::kSelected)) {
state.selectable = true;
- state.selected = GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
+ state.selected = q->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
}
- if (HasIntAttribute(ax::mojom::IntAttribute::kCheckedState)) {
+ if (q->HasIntAttribute(ax::mojom::IntAttribute::kCheckedState)) {
state.checkable = true;
const ax::mojom::CheckedState checkedState =
- static_cast<ax::mojom::CheckedState>(GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
+ static_cast<ax::mojom::CheckedState>(q->GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
switch (checkedState) {
case ax::mojom::CheckedState::kTrue:
- if (GetRole() == ax::mojom::Role::kToggleButton)
+ if (q->GetRole() == ax::mojom::Role::kToggleButton)
state.pressed = true;
else
state.checked = true;
@@ -613,8 +782,8 @@ QAccessible::State BrowserAccessibilityQt::state() const
break;
}
}
- if (HasIntAttribute(ax::mojom::IntAttribute::kRestriction)) {
- const ax::mojom::Restriction restriction = static_cast<ax::mojom::Restriction>(GetIntAttribute(ax::mojom::IntAttribute::kRestriction));
+ if (q->HasIntAttribute(ax::mojom::IntAttribute::kRestriction)) {
+ const ax::mojom::Restriction restriction = static_cast<ax::mojom::Restriction>(q->GetIntAttribute(ax::mojom::IntAttribute::kRestriction));
switch (restriction) {
case ax::mojom::Restriction::kReadOnly:
state.readOnly = true;
@@ -626,8 +795,8 @@ QAccessible::State BrowserAccessibilityQt::state() const
break;
}
}
- if (HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) {
- const ax::mojom::HasPopup hasPopup = static_cast<ax::mojom::HasPopup>(GetIntAttribute(ax::mojom::IntAttribute::kHasPopup));
+ if (q->HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) {
+ const ax::mojom::HasPopup hasPopup = static_cast<ax::mojom::HasPopup>(q->GetIntAttribute(ax::mojom::IntAttribute::kHasPopup));
switch (hasPopup) {
case ax::mojom::HasPopup::kFalse:
break;
@@ -644,356 +813,370 @@ QAccessible::State BrowserAccessibilityQt::state() const
return state;
}
-// Qt does not reference count accessibles
-void BrowserAccessibilityQt::NativeAddReference()
-{
-}
-
-// there is no reference counting, but BrowserAccessibility::Destroy
-// calls this (and that is the only place in the chromium sources,
-// so we can safely use it to dispose of ourselves here
-// (the default implementation of this function just contains a "delete this")
-void BrowserAccessibilityQt::NativeReleaseReference()
-{
- // delete this
- QAccessible::Id interfaceId = QAccessible::uniqueId(this);
- QAccessible::deleteAccessibleInterface(interfaceId);
-}
-
-QStringList BrowserAccessibilityQt::actionNames() const
+QStringList BrowserAccessibilityInterface::actionNames() const
{
QStringList actions;
- if (HasState(ax::mojom::State::kFocusable))
+ if (q->HasState(ax::mojom::State::kFocusable))
actions << QAccessibleActionInterface::setFocusAction();
return actions;
}
-void BrowserAccessibilityQt::doAction(const QString &actionName)
+void BrowserAccessibilityInterface::doAction(const QString &actionName)
{
if (actionName == QAccessibleActionInterface::setFocusAction())
- manager()->SetFocus(*this);
+ q->manager()->SetFocus(*q);
}
-QStringList BrowserAccessibilityQt::keyBindingsForAction(const QString &actionName) const
+QStringList
+BrowserAccessibilityInterface::keyBindingsForAction(const QString & /*actionName*/) const
{
QT_NOT_YET_IMPLEMENTED
return QStringList();
}
-void BrowserAccessibilityQt::addSelection(int startOffset, int endOffset)
+void BrowserAccessibilityInterface::addSelection(int startOffset, int endOffset)
{
- manager()->SetSelection(AXPlatformRange(CreatePositionAt(startOffset), CreatePositionAt(endOffset)));
+ q->manager()->SetSelection(content::BrowserAccessibility::AXRange(q->CreatePositionAt(startOffset), q->CreatePositionAt(endOffset)));
}
-QString BrowserAccessibilityQt::attributes(int offset, int *startOffset, int *endOffset) const
+QString BrowserAccessibilityInterface::attributes(int offset, int *startOffset, int *endOffset) const
{
*startOffset = offset;
*endOffset = offset;
return QString();
}
-int BrowserAccessibilityQt::cursorPosition() const
+int BrowserAccessibilityInterface::cursorPosition() const
{
int pos = 0;
- GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &pos);
+ q->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &pos);
return pos;
}
-QRect BrowserAccessibilityQt::characterRect(int /*offset*/) const
+QRect BrowserAccessibilityInterface::characterRect(int /*offset*/) const
{
QT_NOT_YET_IMPLEMENTED
return QRect();
}
-int BrowserAccessibilityQt::selectionCount() const
+int BrowserAccessibilityInterface::selectionCount() const
{
int start = 0;
int end = 0;
- GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &start);
- GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, &end);
+ q->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &start);
+ q->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, &end);
if (start != end)
return 1;
return 0;
}
-int BrowserAccessibilityQt::offsetAtPoint(const QPoint &/*point*/) const
+int BrowserAccessibilityInterface::offsetAtPoint(const QPoint &/*point*/) const
{
QT_NOT_YET_IMPLEMENTED
return 0;
}
-void BrowserAccessibilityQt::selection(int selectionIndex, int *startOffset, int *endOffset) const
+void BrowserAccessibilityInterface::selection(int selectionIndex, int *startOffset, int *endOffset) const
{
Q_ASSERT(startOffset && endOffset);
*startOffset = 0;
*endOffset = 0;
if (selectionIndex != 0)
return;
- GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, startOffset);
- GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, endOffset);
+ q->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, startOffset);
+ q->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, endOffset);
}
-QString BrowserAccessibilityQt::text(int startOffset, int endOffset) const
+QString BrowserAccessibilityInterface::text(int startOffset, int endOffset) const
{
return text(QAccessible::Value).mid(startOffset, endOffset - startOffset);
}
-void BrowserAccessibilityQt::removeSelection(int selectionIndex)
+void BrowserAccessibilityInterface::removeSelection(int selectionIndex)
{
- manager()->SetSelection(AXPlatformRange(CreatePositionAt(0), CreatePositionAt(0)));
+ q->manager()->SetSelection(content::BrowserAccessibility::AXRange(q->CreatePositionAt(0), q->CreatePositionAt(0)));
}
-void BrowserAccessibilityQt::setCursorPosition(int position)
+void BrowserAccessibilityInterface::setCursorPosition(int position)
{
- manager()->SetSelection(AXPlatformRange(CreatePositionAt(position), CreatePositionAt(position)));
+ q->manager()->SetSelection(content::BrowserAccessibility::AXRange(q->CreatePositionAt(position), q->CreatePositionAt(position)));
}
-void BrowserAccessibilityQt::setSelection(int selectionIndex, int startOffset, int endOffset)
+void BrowserAccessibilityInterface::setSelection(int selectionIndex, int startOffset, int endOffset)
{
if (selectionIndex != 0)
return;
- manager()->SetSelection(AXPlatformRange(CreatePositionAt(startOffset), CreatePositionAt(endOffset)));
+ q->manager()->SetSelection(content::BrowserAccessibility::AXRange(q->CreatePositionAt(startOffset), q->CreatePositionAt(endOffset)));
}
-int BrowserAccessibilityQt::characterCount() const
+int BrowserAccessibilityInterface::characterCount() const
{
return text(QAccessible::Value).length();
}
-void BrowserAccessibilityQt::scrollToSubstring(int startIndex, int endIndex)
+void BrowserAccessibilityInterface::scrollToSubstring(int startIndex, int endIndex)
{
int count = characterCount();
if (startIndex < endIndex && endIndex < count)
- manager()->ScrollToMakeVisible(*this,
- GetRootFrameHypertextRangeBoundsRect(
- startIndex,
- endIndex - startIndex,
- ui::AXClippingBehavior::kUnclipped));
+ q->manager()->ScrollToMakeVisible(*q,
+ q->GetRootFrameHypertextRangeBoundsRect(
+ startIndex,
+ endIndex - startIndex,
+ ui::AXClippingBehavior::kUnclipped));
}
-QVariant BrowserAccessibilityQt::currentValue() const
+QVariant BrowserAccessibilityInterface::currentValue() const
{
QVariant result;
float value;
- if (GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &value)) {
+ if (q->GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &value)) {
result = (double) value;
}
return result;
}
-void BrowserAccessibilityQt::setCurrentValue(const QVariant &value)
+void BrowserAccessibilityInterface::setCurrentValue(const QVariant &value)
{
// not yet implemented anywhere in blink
QT_NOT_YET_IMPLEMENTED
}
-QVariant BrowserAccessibilityQt::maximumValue() const
+QVariant BrowserAccessibilityInterface::maximumValue() const
{
QVariant result;
float value;
- if (GetFloatAttribute(ax::mojom::FloatAttribute::kMaxValueForRange, &value)) {
+ if (q->GetFloatAttribute(ax::mojom::FloatAttribute::kMaxValueForRange, &value)) {
result = (double) value;
}
return result;
}
-QVariant BrowserAccessibilityQt::minimumValue() const
+QVariant BrowserAccessibilityInterface::minimumValue() const
{
QVariant result;
float value;
- if (GetFloatAttribute(ax::mojom::FloatAttribute::kMinValueForRange, &value)) {
+ if (q->GetFloatAttribute(ax::mojom::FloatAttribute::kMinValueForRange, &value)) {
result = (double) value;
}
return result;
}
-QVariant BrowserAccessibilityQt::minimumStepSize() const
+QVariant BrowserAccessibilityInterface::minimumStepSize() const
{
QVariant result;
float value;
- if (GetFloatAttribute(ax::mojom::FloatAttribute::kStepValueForRange, &value)) {
+ if (q->GetFloatAttribute(ax::mojom::FloatAttribute::kStepValueForRange, &value)) {
result = (double) value;
}
return result;
}
-QAccessibleInterface *BrowserAccessibilityQt::cellAt(int row, int column) const
+QAccessibleInterface *BrowserAccessibilityInterface::cellAt(int row, int column) const
{
int columns = 0;
int rows = 0;
- if (!GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, &columns) ||
- !GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount, &rows) ||
- columns <= 0 ||
- rows <= 0) {
- return 0;
+ if (!q->GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, &columns)
+ || !q->GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount, &rows)
+ || columns <= 0
+ || rows <= 0) {
+ return nullptr;
}
if (row < 0 || row >= rows || column < 0 || column >= columns)
- return 0;
+ return nullptr;
- base::Optional<int> cell_id = GetCellId(row, column);
- BrowserAccessibility* cell = cell_id ? manager()->GetFromID(*cell_id) : nullptr;
- if (cell) {
- QAccessibleInterface *iface = static_cast<BrowserAccessibilityQt*>(cell);
- return iface;
- }
+ absl::optional<int> cell_id = q->GetCellId(row, column);
+ content::BrowserAccessibility *cell = cell_id ? q->manager()->GetFromID(*cell_id) : nullptr;
+ if (cell)
+ return content::toQAccessibleInterface(cell);
return nullptr;
}
-QAccessibleInterface *BrowserAccessibilityQt::caption() const
+QAccessibleInterface *BrowserAccessibilityInterface::caption() const
{
return nullptr;
}
-QAccessibleInterface *BrowserAccessibilityQt::summary() const
+QAccessibleInterface *BrowserAccessibilityInterface::summary() const
{
return nullptr;
}
-QString BrowserAccessibilityQt::columnDescription(int column) const
+QString BrowserAccessibilityInterface::columnDescription(int column) const
{
return QString();
}
-QString BrowserAccessibilityQt::rowDescription(int row) const
+QString BrowserAccessibilityInterface::rowDescription(int row) const
{
return QString();
}
-int BrowserAccessibilityQt::columnCount() const
+int BrowserAccessibilityInterface::columnCount() const
{
int columns = 0;
- if (GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, &columns))
+ if (q->GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, &columns))
return columns;
-
return 0;
}
-int BrowserAccessibilityQt::rowCount() const
+int BrowserAccessibilityInterface::rowCount() const
{
int rows = 0;
- if (GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount, &rows))
- return rows;
+ if (q->GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount, &rows))
+ return rows;
return 0;
}
-int BrowserAccessibilityQt::selectedCellCount() const
+int BrowserAccessibilityInterface::selectedCellCount() const
{
return 0;
}
-int BrowserAccessibilityQt::selectedColumnCount() const
+int BrowserAccessibilityInterface::selectedColumnCount() const
{
return 0;
}
-int BrowserAccessibilityQt::selectedRowCount() const
+int BrowserAccessibilityInterface::selectedRowCount() const
{
return 0;
}
-QList<QAccessibleInterface *> BrowserAccessibilityQt::selectedCells() const
+QList<QAccessibleInterface *> BrowserAccessibilityInterface::selectedCells() const
{
return QList<QAccessibleInterface *>();
}
-QList<int> BrowserAccessibilityQt::selectedColumns() const
+QList<int> BrowserAccessibilityInterface::selectedColumns() const
{
return QList<int>();
}
-QList<int> BrowserAccessibilityQt::selectedRows() const
+QList<int> BrowserAccessibilityInterface::selectedRows() const
{
return QList<int>();
}
-bool BrowserAccessibilityQt::isColumnSelected(int /*column*/) const
+bool BrowserAccessibilityInterface::isColumnSelected(int /*column*/) const
{
return false;
}
-bool BrowserAccessibilityQt::isRowSelected(int /*row*/) const
+bool BrowserAccessibilityInterface::isRowSelected(int /*row*/) const
{
return false;
}
-bool BrowserAccessibilityQt::selectRow(int /*row*/)
+bool BrowserAccessibilityInterface::selectRow(int /*row*/)
{
return false;
}
-bool BrowserAccessibilityQt::selectColumn(int /*column*/)
+bool BrowserAccessibilityInterface::selectColumn(int /*column*/)
{
return false;
}
-bool BrowserAccessibilityQt::unselectRow(int /*row*/)
+bool BrowserAccessibilityInterface::unselectRow(int /*row*/)
{
return false;
}
-bool BrowserAccessibilityQt::unselectColumn(int /*column*/)
+bool BrowserAccessibilityInterface::unselectColumn(int /*column*/)
{
return false;
}
-int BrowserAccessibilityQt::columnExtent() const
+int BrowserAccessibilityInterface::columnExtent() const
{
return 1;
}
-QList<QAccessibleInterface *> BrowserAccessibilityQt::columnHeaderCells() const
+QList<QAccessibleInterface *> BrowserAccessibilityInterface::columnHeaderCells() const
{
return QList<QAccessibleInterface*>();
}
-int BrowserAccessibilityQt::columnIndex() const
+int BrowserAccessibilityInterface::columnIndex() const
{
int column = 0;
- if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, &column))
- return column;
+ if (q->GetIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, &column))
+ return column;
return 0;
}
-int BrowserAccessibilityQt::rowExtent() const
+int BrowserAccessibilityInterface::rowExtent() const
{
return 1;
}
-QList<QAccessibleInterface *> BrowserAccessibilityQt::rowHeaderCells() const
+QList<QAccessibleInterface *> BrowserAccessibilityInterface::rowHeaderCells() const
{
return QList<QAccessibleInterface*>();
}
-int BrowserAccessibilityQt::rowIndex() const
+int BrowserAccessibilityInterface::rowIndex() const
{
int row = 0;
- if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, &row))
- return row;
+ if (q->GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, &row))
+ return row;
return 0;
}
-bool BrowserAccessibilityQt::isSelected() const
+bool BrowserAccessibilityInterface::isSelected() const
{
return false;
}
-QAccessibleInterface *BrowserAccessibilityQt::table() const
+content::BrowserAccessibility *BrowserAccessibilityInterface::findTable() const
{
- BrowserAccessibility* find_table = PlatformGetParent();
- while (find_table && find_table->GetRole() != ax::mojom::Role::kTable)
- find_table = find_table->PlatformGetParent();
- if (!find_table)
- return 0;
- return static_cast<BrowserAccessibilityQt*>(find_table);
+ content::BrowserAccessibility *parent = q->PlatformGetParent();
+ while (parent && parent->GetRole() != ax::mojom::Role::kTable)
+ parent = parent->PlatformGetParent();
+
+ return parent;
}
-void BrowserAccessibilityQt::modelChange(QAccessibleTableModelChangeEvent *)
+QAccessibleInterface *BrowserAccessibilityInterface::table() const
{
+ content::BrowserAccessibility *table = findTable();
+ Q_ASSERT(table);
+ return content::toQAccessibleInterface(table);
+}
+void BrowserAccessibilityInterface::modelChange(QAccessibleTableModelChangeEvent *)
+{
}
-} // namespace content
+} // namespace QtWebEngineCore
#endif // QT_CONFIG(accessibility)
+namespace content {
+
+// static
+std::unique_ptr<BrowserAccessibility> BrowserAccessibility::Create(BrowserAccessibilityManager *man, ui::AXNode *node)
+{
+#if QT_CONFIG(accessibility)
+ return std::unique_ptr<BrowserAccessibility>(new QtWebEngineCore::BrowserAccessibilityQt(man, node));
+#else
+ Q_UNUSED(man);
+ Q_UNUSED(node);
+ return nullptr;
+#endif // #if QT_CONFIG(accessibility)
+}
+
+#if QT_CONFIG(accessibility)
+QAccessibleInterface *toQAccessibleInterface(BrowserAccessibility *obj)
+{
+ return static_cast<QtWebEngineCore::BrowserAccessibilityQt *>(obj)->interface;
+}
+
+const QAccessibleInterface *toQAccessibleInterface(const BrowserAccessibility *obj)
+{
+ return static_cast<const QtWebEngineCore::BrowserAccessibilityQt *>(obj)->interface;
+}
+#endif // #if QT_CONFIG(accessibility)
+
+} // namespace content
diff --git a/src/core/browser_accessibility_qt.h b/src/core/browser_accessibility_qt.h
index 19c7a1e54..598aa3ef5 100644
--- a/src/core/browser_accessibility_qt.h
+++ b/src/core/browser_accessibility_qt.h
@@ -1,155 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BROWSER_ACCESSIBILITY_QT_H
#define BROWSER_ACCESSIBILITY_QT_H
-#include <QtGui/qaccessible.h>
-#include "content/browser/accessibility/browser_accessibility.h"
+#include <QtGui/qtguiglobal.h>
#if QT_CONFIG(accessibility)
+QT_FORWARD_DECLARE_CLASS(QAccessibleInterface)
namespace content {
+class BrowserAccessibility;
-class BrowserAccessibilityQt
- : public BrowserAccessibility
- , public QAccessibleInterface
- , public QAccessibleActionInterface
- , public QAccessibleTextInterface
- , public QAccessibleValueInterface
- , public QAccessibleTableInterface
- , public QAccessibleTableCellInterface
-{
-public:
- BrowserAccessibilityQt();
-
- // QAccessibleInterface
- bool isValid() const override;
- QObject *object() const override;
- QAccessibleInterface *childAt(int x, int y) const override;
- void *interface_cast(QAccessible::InterfaceType type) override;
-
- // navigation, hierarchy
- QAccessibleInterface *parent() const override;
- QAccessibleInterface *child(int index) const override;
- QAccessibleInterface *focusChild() const override;
- int childCount() const override;
- int indexOfChild(const QAccessibleInterface *) const override;
-
- // properties and state
- QString text(QAccessible::Text t) const override;
- void setText(QAccessible::Text t, const QString &text) override;
- QRect rect() const override;
- QAccessible::Role role() const override;
- QAccessible::State state() const override;
-
- // BrowserAccessible
- void NativeAddReference() override;
- void NativeReleaseReference() override;
- bool IsNative() const override { return true; }
-
- // QAccessibleActionInterface
- QStringList actionNames() const override;
- void doAction(const QString &actionName) override;
- QStringList keyBindingsForAction(const QString &actionName) const override;
-
- // QAccessibleTextInterface
- void addSelection(int startOffset, int endOffset) override;
- QString attributes(int offset, int *startOffset, int *endOffset) const override;
- int cursorPosition() const override;
- QRect characterRect(int offset) const override;
- int selectionCount() const override;
- int offsetAtPoint(const QPoint &point) const override;
- void selection(int selectionIndex, int *startOffset, int *endOffset) const override;
- QString text(int startOffset, int endOffset) const override;
- void removeSelection(int selectionIndex) override;
- void setCursorPosition(int position) override;
- void setSelection(int selectionIndex, int startOffset, int endOffset) override;
- int characterCount() const override;
- void scrollToSubstring(int startIndex, int endIndex) override;
-
- // QAccessibleValueInterface
- QVariant currentValue() const override;
- void setCurrentValue(const QVariant &value) override;
- QVariant maximumValue() const override;
- QVariant minimumValue() const override;
- QVariant minimumStepSize() const override;
-
- // QAccessibleTableInterface
- QAccessibleInterface *cellAt(int row, int column) const override;
- QAccessibleInterface *caption() const override;
- QAccessibleInterface *summary() const override;
- QString columnDescription(int column) const override;
- QString rowDescription(int row) const override;
- int columnCount() const override;
- int rowCount() const override;
- // selection
- int selectedCellCount() const override;
- int selectedColumnCount() const override;
- int selectedRowCount() const override;
- QList<QAccessibleInterface*> selectedCells() const override;
- QList<int> selectedColumns() const override;
- QList<int> selectedRows() const override;
- bool isColumnSelected(int column) const override;
- bool isRowSelected(int row) const override;
- bool selectRow(int row) override;
- bool selectColumn(int column) override;
- bool unselectRow(int row) override;
- bool unselectColumn(int column) override;
-
- // QAccessibleTableCellInterface
- int columnExtent() const override;
- QList<QAccessibleInterface*> columnHeaderCells() const override;
- int columnIndex() const override;
- int rowExtent() const override;
- QList<QAccessibleInterface*> rowHeaderCells() const override;
- int rowIndex() const override;
- bool isSelected() const override;
- QAccessibleInterface* table() const override;
-
- void modelChange(QAccessibleTableModelChangeEvent *event) override;
-};
-
-const BrowserAccessibilityQt *ToBrowserAccessibilityQt(const BrowserAccessibility *obj);
-QAccessibleInterface *toQAccessibleInterface(BrowserAccessibility *acc);
+QAccessibleInterface *toQAccessibleInterface(BrowserAccessibility *obj);
+const QAccessibleInterface *toQAccessibleInterface(const BrowserAccessibility *obj);
} // namespace content
-
#endif // QT_CONFIG(accessibility)
-#endif
+
+#endif // BROWSER_ACCESSIBILITY_QT_H
diff --git a/src/core/browser_main_parts_qt.cpp b/src/core/browser_main_parts_qt.cpp
index 925c18664..9021dbb98 100644
--- a/src/core/browser_main_parts_qt.cpp
+++ b/src/core/browser_main_parts_qt.cpp
@@ -1,81 +1,68 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "browser_main_parts_qt.h"
#include "api/qwebenginemessagepumpscheduler_p.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_loop_current.h"
+#include "base/message_loop/message_pump.h"
#include "base/message_loop/message_pump_for_ui.h"
#include "base/process/process.h"
+#include "base/task/current_thread.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/thread_controller_with_message_pump_impl.h"
+#include "base/task/task_traits.h"
+#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
+#include "chrome/browser/tab_contents/form_interaction_tab_helper.h"
+#include "components/device_event_log/device_event_log.h"
+#include "components/performance_manager/embedder/graph_features.h"
+#include "components/performance_manager/embedder/performance_manager_lifetime.h"
+#include "components/performance_manager/public/graph/graph.h"
+#include "components/performance_manager/public/performance_manager.h"
#include "content/public/browser/browser_main_parts.h"
+#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
-#include "content/public/browser/system_connector.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/common/content_features.h"
+#include "content/public/common/result_codes.h"
#include "extensions/buildflags/buildflags.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "select_file_dialog_factory_qt.h"
+#include "services/service_manager/public/cpp/connector.h"
+#include "services/service_manager/public/cpp/service.h"
+#include "type_conversion.h"
+#include "ui/display/screen.h"
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/common/constants.h"
#include "extensions/common/extensions_client.h"
#include "extensions/extensions_browser_client_qt.h"
#include "extensions/extension_system_factory_qt.h"
#include "common/extensions/extensions_client_qt.h"
-#endif //BUILDFLAG(ENABLE_EXTENSIONS)
-#include "services/service_manager/public/cpp/connector.h"
-#include "services/service_manager/public/cpp/service.h"
-#include "ui/display/screen.h"
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+#include "content/public/browser/plugin_service.h"
+#include "extensions/plugin_service_filter_qt.h"
+#endif // BUILDFLAG(ENABLE_PLUGINS)
#include "web_engine_context.h"
+#include "web_usb_detector_qt.h"
+#include <QDeadlineTimer>
#include <QtGui/qtgui-config.h>
+#include <QStandardPaths>
#if QT_CONFIG(opengl)
#include "ui/gl/gl_context.h"
#include <QOpenGLContext>
#endif
-#if defined(OS_MACOSX)
-#include "base/message_loop/message_pump_mac.h"
+#if BUILDFLAG(IS_MAC)
+#include "base/message_loop/message_pump_apple.h"
+#include "services/device/public/cpp/geolocation/geolocation_manager.h"
+#include "services/device/public/cpp/geolocation/system_geolocation_source.h"
#include "ui/base/idle/idle.h"
#endif
@@ -85,6 +72,10 @@
#include "desktop_screen_qt.h"
#endif
+#if defined(Q_OS_LINUX)
+#include "components/os_crypt/sync/key_storage_config_linux.h"
+#include "components/os_crypt/sync/os_crypt.h"
+#endif
namespace QtWebEngineCore {
@@ -131,12 +122,17 @@ public:
{
// NOTE: This method may called from any thread at any time.
ensureDelegate();
- m_scheduler.scheduleWork();
+ m_scheduler.scheduleImmediateWork();
}
- void ScheduleDelayedWork(const base::TimeTicks &delayed_work_time) override
+ void ScheduleDelayedWork(const Delegate::NextWorkInfo &next_work_info) override
{
// NOTE: This method may called from any thread at any time.
+ ScheduleDelayedWork(next_work_info.delayed_run_time);
+ }
+
+ void ScheduleDelayedWork(const base::TimeTicks &delayed_work_time)
+ {
ensureDelegate();
m_scheduler.scheduleDelayedWork(GetTimeIntervalMilliseconds(delayed_work_time));
}
@@ -145,79 +141,51 @@ private:
void ensureDelegate()
{
if (!m_delegate) {
- auto seqMan = base::MessageLoopCurrent::GetCurrentSequenceManagerImpl();
+ auto seqMan = base::CurrentThread::Get()->GetCurrentSequenceManagerImpl();
m_delegate = static_cast<base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl *>(
seqMan->controller_.get());
}
}
- // Both Qt and Chromium keep track of the current GL context by using
- // thread-local variables, and naturally they are completely unaware of each
- // other. As a result, when a QOpenGLContext is made current, the previous
- // gl::GLContext is not released, and vice-versa. This is fine as long as
- // each thread uses exclusively either Qt or Chromium GL bindings, which is
- // usually the case.
- //
- // The only exception is when the GL driver is considered thread-unsafe
- // (QOpenGLContext::supportsThreadedOpenGL() is false), in which case we
- // have to run all GL operations, including Chromium's GPU service, on the
- // UI thread. Now the bindings are being mixed and both Qt and Chromium get
- // quite confused regarding the current state of the surface.
- //
- // To get this to work we have to release the current QOpenGLContext before
- // executing any tasks from Chromium's GPU service and the gl::GLContext
- // afterwards. Since GPU service just posts tasks to the UI thread task
- // runner, we'll have to instrument the entire UI thread message pump.
- class ScopedGLContextChecker
- {
-#if QT_CONFIG(opengl)
- public:
- ScopedGLContextChecker()
- {
- if (!m_enabled)
- return;
-
- if (QOpenGLContext *context = QOpenGLContext::currentContext())
- context->doneCurrent();
- }
-
- ~ScopedGLContextChecker()
- {
- if (!m_enabled)
- return;
-
- if (gl::GLContext *context = gl::GLContext::GetCurrent())
- context->ReleaseCurrent(nullptr);
- }
-
- private:
- bool m_enabled = !QOpenGLContext::supportsThreadedOpenGL();
-#endif // QT_CONFIG(opengl)
- };
-
void handleScheduledWork()
{
- ScopedGLContextChecker glContextChecker;
-
- bool more_work_is_plausible = m_delegate->DoWork();
+ QDeadlineTimer timer(std::chrono::milliseconds(2));
+ base::MessagePump::Delegate::NextWorkInfo more_work_info = m_delegate->DoWork();
+ while (more_work_info.is_immediate() && !timer.hasExpired())
+ more_work_info = m_delegate->DoWork();
- base::TimeTicks delayed_work_time;
- more_work_is_plausible |= m_delegate->DoDelayedWork(&delayed_work_time);
+ if (more_work_info.is_immediate())
+ return m_scheduler.scheduleImmediateWork();
- if (more_work_is_plausible)
- return ScheduleWork();
+ if (m_delegate->DoIdleWork())
+ return m_scheduler.scheduleIdleWork();
- more_work_is_plausible |= m_delegate->DoIdleWork();
- if (more_work_is_plausible)
- return ScheduleWork();
-
- ScheduleDelayedWork(delayed_work_time);
+ ScheduleDelayedWork(more_work_info.delayed_run_time);
}
Delegate *m_delegate = nullptr;
QWebEngineMessagePumpScheduler m_scheduler;
};
+#if BUILDFLAG(IS_MAC)
+class FakeGeolocationSource : public device::SystemGeolocationSource
+{
+public:
+ FakeGeolocationSource() = default;
+ ~FakeGeolocationSource() override = default;
+
+ // SystemGeolocationSource implementation:
+ void StartWatchingPosition(bool) override {}
+ void StopWatchingPosition() override {}
+ void RegisterPermissionUpdateCallback(PermissionUpdateCallback callback)
+ {
+ callback.Run(device::LocationSystemPermissionStatus::kDenied);
+ }
+ void RegisterPositionUpdateCallback(PositionUpdateCallback callback) {}
+ void RequestPermission() override {}
+};
+#endif // BUILDFLAG(IS_MAC)
+
std::unique_ptr<base::MessagePump> messagePumpFactory()
{
static bool madePrimaryPump = false;
@@ -225,8 +193,8 @@ std::unique_ptr<base::MessagePump> messagePumpFactory()
madePrimaryPump = true;
return std::make_unique<MessagePumpForUIQt>();
}
-#if defined(OS_MACOSX)
- return base::MessagePumpMac::Create();
+#if BUILDFLAG(IS_MAC)
+ return base::message_pump_apple::Create();
#else
return std::make_unique<base::MessagePumpForUI>();
#endif
@@ -237,24 +205,61 @@ int BrowserMainPartsQt::PreEarlyInitialization()
#if BUILDFLAG(ENABLE_EXTENSIONS)
content::ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(extensions::kExtensionScheme);
#endif //ENABLE_EXTENSIONS
- return 0;
+ return content::RESULT_CODE_NORMAL_EXIT;
+}
+
+void BrowserMainPartsQt::PreCreateMainMessageLoop()
+{
+#if BUILDFLAG(IS_MAC)
+ m_geolocationManager = std::make_unique<device::GeolocationManager>(std::make_unique<FakeGeolocationSource>());
+#endif
}
-void BrowserMainPartsQt::PreMainMessageLoopStart()
+void BrowserMainPartsQt::PostCreateMainMessageLoop()
{
+ if (!device_event_log::IsInitialized())
+ device_event_log::Initialize(0 /* default max entries */);
+
+#if defined(Q_OS_LINUX)
+ auto config = std::make_unique<os_crypt::Config>();
+ config->product_name = "Qt WebEngine";
+ config->should_use_preference = false;
+ config->user_data_path = toFilePath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
+ OSCrypt::SetConfig(std::move(config));
+#endif
}
-void BrowserMainPartsQt::PreMainMessageLoopRun()
+int BrowserMainPartsQt::PreMainMessageLoopRun()
{
+ ui::SelectFileDialog::SetFactory(std::make_unique<SelectFileDialogFactoryQt>());
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::ExtensionsClient::Set(new extensions::ExtensionsClientQt());
extensions::ExtensionsBrowserClient::Set(new extensions::ExtensionsBrowserClientQt());
extensions::ExtensionSystemFactoryQt::GetInstance();
-#endif //ENABLE_EXTENSIONS
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+ content::PluginService *plugin_service = content::PluginService::GetInstance();
+ plugin_service->SetFilter(extensions::PluginServiceFilterQt::GetInstance());
+#endif // BUILDFLAG(ENABLE_PLUGINS)
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+ if (base::FeatureList::IsEnabled(features::kWebUsb)) {
+ m_webUsbDetector.reset(new WebUsbDetectorQt());
+ content::GetUIThreadTaskRunner({ base::TaskPriority::BEST_EFFORT })
+ ->PostTask(FROM_HERE,
+ base::BindOnce(&WebUsbDetectorQt::Initialize,
+ base::Unretained(m_webUsbDetector.get())));
+ }
+ return content::RESULT_CODE_NORMAL_EXIT;
}
void BrowserMainPartsQt::PostMainMessageLoopRun()
{
+ performance_manager_lifetime_.reset();
+
+ m_webUsbDetector.reset();
+
// The ProfileQt's destructor uses the MessageLoop so it should be deleted
// right before the RenderProcessHostImpl's destructor destroys it.
WebEngineContext::current()->destroyProfileAdapter();
@@ -262,23 +267,39 @@ void BrowserMainPartsQt::PostMainMessageLoopRun()
int BrowserMainPartsQt::PreCreateThreads()
{
- base::ThreadRestrictions::SetIOAllowed(true);
-
-#if defined(OS_MACOSX)
+#if BUILDFLAG(IS_MAC)
ui::InitIdleMonitor();
#endif
// Like ChromeBrowserMainExtraPartsViews::PreCreateThreads does.
#if defined(Q_OS_WIN)
display::Screen::SetScreenInstance(new display::win::ScreenWin);
+#elif defined(Q_OS_DARWIN)
+ display::Screen::SetScreenInstance(display::CreateNativeScreen());
#else
display::Screen::SetScreenInstance(new DesktopScreenQt);
#endif
- return 0;
+ return content::RESULT_CODE_NORMAL_EXIT;
+}
+
+static void CreatePoliciesAndDecorators(performance_manager::Graph *graph)
+{
+ graph->PassToGraph(FormInteractionTabHelper::CreateGraphObserver());
}
void BrowserMainPartsQt::PostCreateThreads()
{
+ performance_manager_lifetime_ =
+ std::make_unique<performance_manager::PerformanceManagerLifetime>(
+ performance_manager::GraphFeatures::WithDefault(),
+ base::BindOnce(&QtWebEngineCore::CreatePoliciesAndDecorators));
+}
+
+#if BUILDFLAG(IS_MAC)
+device::GeolocationManager *BrowserMainPartsQt::GetGeolocationManager()
+{
+ return m_geolocationManager.get();
}
+#endif
} // namespace QtWebEngineCore
diff --git a/src/core/browser_main_parts_qt.h b/src/core/browser_main_parts_qt.h
index f287c2e44..6828552b7 100644
--- a/src/core/browser_main_parts_qt.h
+++ b/src/core/browser_main_parts_qt.h
@@ -1,47 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BROWSER_MAIN_PARTS_QT_H
#define BROWSER_MAIN_PARTS_QT_H
#include "content/public/browser/browser_main_parts.h"
+#include "web_usb_detector_qt.h"
+
namespace base {
class MessagePump;
}
@@ -50,6 +16,14 @@ namespace content {
class ServiceManagerConnection;
}
+namespace device {
+class GeolocationManager;
+}
+
+namespace performance_manager {
+class PerformanceManagerLifetime;
+}
+
namespace QtWebEngineCore {
std::unique_ptr<base::MessagePump> messagePumpFactory();
@@ -61,14 +35,23 @@ public:
~BrowserMainPartsQt() override = default;
int PreEarlyInitialization() override;
- void PreMainMessageLoopStart() override;
- void PreMainMessageLoopRun() override;
+ void PreCreateMainMessageLoop() override;
+ void PostCreateMainMessageLoop() override;
+ int PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
int PreCreateThreads() override;
void PostCreateThreads() override;
+#if BUILDFLAG(IS_MAC)
+ device::GeolocationManager *GetGeolocationManager();
+#endif
+
private:
- DISALLOW_COPY_AND_ASSIGN(BrowserMainPartsQt);
+ std::unique_ptr<performance_manager::PerformanceManagerLifetime> performance_manager_lifetime_;
+ std::unique_ptr<WebUsbDetectorQt> m_webUsbDetector;
+#if BUILDFLAG(IS_MAC)
+ std::unique_ptr<device::GeolocationManager> m_geolocationManager;
+#endif
};
} // namespace QtWebEngineCore
diff --git a/src/core/browser_message_filter_qt.cpp b/src/core/browser_message_filter_qt.cpp
index a4b75f075..e8fcb994a 100644
--- a/src/core/browser_message_filter_qt.cpp
+++ b/src/core/browser_message_filter_qt.cpp
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "browser_message_filter_qt.h"
#include "chrome/browser/profiles/profile.h"
-#include "content/public/browser/plugin_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
@@ -56,103 +19,85 @@ BrowserMessageFilterQt::BrowserMessageFilterQt(int /*render_process_id*/, Profil
{
}
-// The following is based on chrome/browser/plugins/plugin_info_message_filter.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
bool BrowserMessageFilterQt::OnMessageReceived(const IPC::Message& message)
{
IPC_BEGIN_MESSAGE_MAP(BrowserMessageFilterQt, message)
- IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_AllowDatabase, OnAllowDatabase)
- IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_AllowDOMStorage, OnAllowDOMStorage)
- IPC_MESSAGE_HANDLER_DELAY_REPLY(QtWebEngineHostMsg_RequestFileSystemAccessSync,
- OnRequestFileSystemAccessSync)
- IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_RequestFileSystemAccessAsync,
- OnRequestFileSystemAccessAsync)
- IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_AllowIndexedDB, OnAllowIndexedDB)
+ IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_AllowStorageAccess, OnAllowStorageAccess)
+ IPC_MESSAGE_HANDLER_DELAY_REPLY(QtWebEngineHostMsg_RequestStorageAccessSync,
+ OnRequestStorageAccessSync)
+ IPC_MESSAGE_HANDLER(QtWebEngineHostMsg_RequestStorageAccessAsync,
+ OnRequestStorageAccessAsync)
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
-void BrowserMessageFilterQt::OnAllowDatabase(int /*render_frame_id*/,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool* allowed)
-{
- *allowed = m_profileData->canGetCookies(toQt(top_origin_url), toQt(origin_url));
-}
-
-void BrowserMessageFilterQt::OnAllowDOMStorage(int /*render_frame_id*/,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool /*local*/,
- bool *allowed)
-{
- *allowed = m_profileData->canGetCookies(toQt(top_origin_url), toQt(origin_url));
-}
-
-void BrowserMessageFilterQt::OnAllowIndexedDB(int /*render_frame_id*/,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool *allowed)
+void BrowserMessageFilterQt::OnAllowStorageAccess(int /*render_frame_id*/,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int /*storage_type*/,
+ bool *allowed)
{
*allowed = m_profileData->canGetCookies(toQt(top_origin_url), toQt(origin_url));
}
-void BrowserMessageFilterQt::OnRequestFileSystemAccessSync(int render_frame_id,
- const GURL& origin_url,
- const GURL& top_origin_url,
- IPC::Message* reply_msg)
+void BrowserMessageFilterQt::OnRequestStorageAccessSync(int render_frame_id,
+ const GURL& origin_url,
+ const GURL& top_origin_url,
+ int storage_type,
+ IPC::Message* reply_msg)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- base::Callback<void(bool)> callback = base::Bind(
- &BrowserMessageFilterQt::OnRequestFileSystemAccessSyncResponse,
+ auto callback = base::BindOnce(
+ &BrowserMessageFilterQt::OnRequestStorageAccessSyncResponse,
base::WrapRefCounted(this), reply_msg);
- OnRequestFileSystemAccess(render_frame_id,
- origin_url,
- top_origin_url,
- callback);
+ OnRequestStorageAccess(render_frame_id,
+ origin_url,
+ top_origin_url,
+ storage_type,
+ std::move(callback));
}
-void BrowserMessageFilterQt::OnRequestFileSystemAccessSyncResponse(IPC::Message *reply_msg, bool allowed)
+void BrowserMessageFilterQt::OnRequestStorageAccessSyncResponse(IPC::Message *reply_msg, bool allowed)
{
- QtWebEngineHostMsg_RequestFileSystemAccessSync::WriteReplyParams(reply_msg, allowed);
+ QtWebEngineHostMsg_RequestStorageAccessSync::WriteReplyParams(reply_msg, allowed);
Send(reply_msg);
}
-void BrowserMessageFilterQt::OnRequestFileSystemAccessAsync(int render_frame_id,
- int request_id,
- const GURL& origin_url,
- const GURL& top_origin_url)
+void BrowserMessageFilterQt::OnRequestStorageAccessAsync(int render_frame_id,
+ int request_id,
+ const GURL& origin_url,
+ const GURL& top_origin_url,
+ int storage_type)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- base::Callback<void(bool)> callback = base::Bind(
- &BrowserMessageFilterQt::OnRequestFileSystemAccessAsyncResponse,
+ auto callback = base::BindOnce(
+ &BrowserMessageFilterQt::OnRequestStorageAccessAsyncResponse,
base::WrapRefCounted(this), render_frame_id, request_id);
- OnRequestFileSystemAccess(render_frame_id,
- origin_url,
- top_origin_url,
- callback);
+ OnRequestStorageAccess(render_frame_id,
+ origin_url,
+ top_origin_url,
+ storage_type,
+ std::move(callback));
}
-void BrowserMessageFilterQt::OnRequestFileSystemAccessAsyncResponse(int render_frame_id,
- int request_id,
- bool allowed)
+void BrowserMessageFilterQt::OnRequestStorageAccessAsyncResponse(int render_frame_id,
+ int request_id,
+ bool allowed)
{
- Send(new QtWebEngineMsg_RequestFileSystemAccessAsyncResponse(render_frame_id, request_id, allowed));
+ Send(new QtWebEngineMsg_RequestStorageAccessAsyncResponse(render_frame_id, request_id, allowed));
}
-void BrowserMessageFilterQt::OnRequestFileSystemAccess(int /*render_frame_id*/,
- const GURL &origin_url,
- const GURL &top_origin_url,
- base::Callback<void(bool)> callback)
+void BrowserMessageFilterQt::OnRequestStorageAccess(int /*render_frame_id*/,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int /*storage_type*/,
+ base::OnceCallback<void(bool)> callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
bool allowed = m_profileData->canGetCookies(toQt(top_origin_url), toQt(origin_url));
- callback.Run(allowed);
+ std::move(callback).Run(allowed);
}
} // namespace QtWebEngineCore
diff --git a/src/core/browser_message_filter_qt.h b/src/core/browser_message_filter_qt.h
index 4abc612f8..0f5721c82 100644
--- a/src/core/browser_message_filter_qt.h
+++ b/src/core/browser_message_filter_qt.h
@@ -1,48 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BROWSER_MESSAGE_FILTER_QT_H
#define BROWSER_MESSAGE_FILTER_QT_H
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "content/public/browser/browser_message_filter.h"
-#include "content/public/common/webplugininfo.h"
class GURL;
class Profile;
@@ -59,39 +22,33 @@ public:
private:
bool OnMessageReceived(const IPC::Message& message) override;
- void OnAllowDatabase(int render_frame_id,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool *allowed);
- void OnAllowDOMStorage(int render_frame_id,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool local,
- bool *allowed);
-
- void OnAllowIndexedDB(int render_frame_id,
- const GURL &origin_url,
- const GURL &top_origin_url,
- bool *allowed);
-
- void OnRequestFileSystemAccessSync(int render_frame_id,
- const GURL &origin_url,
- const GURL &top_origin_url,
- IPC::Message *message);
- void OnRequestFileSystemAccessAsync(int render_frame_id,
- int request_id,
- const GURL &origin_url,
- const GURL &top_origin_url);
- void OnRequestFileSystemAccessSyncResponse(IPC::Message *reply_msg,
- bool allowed);
- void OnRequestFileSystemAccessAsyncResponse(int render_frame_id,
- int request_id,
- bool allowed);
- void OnRequestFileSystemAccess(int render_frame_id,
- const GURL &origin_url,
- const GURL &top_origin_url,
- base::Callback<void(bool)> callback);
+ void OnAllowStorageAccess(int render_frame_id,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int storage_type,
+ bool *allowed);
+
+ void OnRequestStorageAccessSync(int render_frame_id,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int storage_type,
+ IPC::Message *message);
+ void OnRequestStorageAccessAsync(int render_frame_id,
+ int request_id,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int storage_type);
+ void OnRequestStorageAccessSyncResponse(IPC::Message *reply_msg,
+ bool allowed);
+ void OnRequestStorageAccessAsyncResponse(int render_frame_id,
+ int request_id,
+ bool allowed);
+ void OnRequestStorageAccess(int render_frame_id,
+ const GURL &origin_url,
+ const GURL &top_origin_url,
+ int storage_type,
+ base::OnceCallback<void(bool)> callback);
ProfileIODataQt *m_profileData;
};
diff --git a/src/core/browsing_data_remover_delegate_qt.cpp b/src/core/browsing_data_remover_delegate_qt.cpp
index 344ba817f..eb33fb992 100644
--- a/src/core/browsing_data_remover_delegate_qt.cpp
+++ b/src/core/browsing_data_remover_delegate_qt.cpp
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "browsing_data_remover_delegate_qt.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "components/web_cache/browser/web_cache_manager.h"
#include "content/public/browser/browsing_data_remover.h"
@@ -48,7 +12,7 @@
namespace QtWebEngineCore {
-bool DoesOriginMatchEmbedderMask(int origin_type_mask,
+bool DoesOriginMatchEmbedderMask(uint64_t origin_type_mask,
const url::Origin &origin,
storage::SpecialStoragePolicy *policy)
{
@@ -70,10 +34,10 @@ bool BrowsingDataRemoverDelegateQt::MayRemoveDownloadHistory()
void BrowsingDataRemoverDelegateQt::RemoveEmbedderData(const base::Time &delete_begin,
const base::Time &delete_end,
- int remove_mask,
+ uint64_t remove_mask,
content::BrowsingDataFilterBuilder *filter_builder,
- int origin_type_mask,
- base::OnceClosure callback)
+ uint64_t origin_type_mask,
+ base::OnceCallback<void(/*failed_data_types=*/uint64_t)> callback)
{
Q_UNUSED(delete_begin);
Q_UNUSED(delete_end);
@@ -83,7 +47,13 @@ void BrowsingDataRemoverDelegateQt::RemoveEmbedderData(const base::Time &delete_
if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE)
web_cache::WebCacheManager::GetInstance()->ClearCache();
- std::move(callback).Run();
+ std::move(callback).Run(0);
+}
+
+std::vector<std::string> BrowsingDataRemoverDelegateQt::GetDomainsForDeferredCookieDeletion(
+ content::StoragePartition *, uint64_t)
+{
+ return {};
}
} // namespace QtWebEngineCore
diff --git a/src/core/browsing_data_remover_delegate_qt.h b/src/core/browsing_data_remover_delegate_qt.h
index dc2761ffc..d33af4acb 100644
--- a/src/core/browsing_data_remover_delegate_qt.h
+++ b/src/core/browsing_data_remover_delegate_qt.h
@@ -1,45 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BROWSING_DATA_REMOVER_DELEGATE_QT_H
#define BROWSING_DATA_REMOVER_DELEGATE_QT_H
+#include <cstdint>
+
#include "content/public/browser/browsing_data_remover_delegate.h"
namespace QtWebEngineCore {
@@ -53,12 +19,15 @@ public:
content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher GetOriginTypeMatcher() override;
bool MayRemoveDownloadHistory() override;
void RemoveEmbedderData(
- const base::Time &delete_begin,
- const base::Time &delete_end,
- int remove_mask,
- content::BrowsingDataFilterBuilder *filter_builder,
- int origin_type_mask,
- base::OnceClosure callback) override;
+ const base::Time &delete_begin,
+ const base::Time &delete_end,
+ uint64_t remove_mask,
+ content::BrowsingDataFilterBuilder *filter_builder,
+ uint64_t origin_type_mask,
+ base::OnceCallback<void(/*failed_data_types=*/uint64_t)> callback) override;
+ std::vector<std::string> GetDomainsForDeferredCookieDeletion(
+ content::StoragePartition *storage_partition,
+ uint64_t remove_mask) override;
};
} // namespace QtWebEngineCore
diff --git a/src/core/build_config_qt.h b/src/core/build_config_qt.h
index 9c7a77d65..5f6978e13 100644
--- a/src/core/build_config_qt.h
+++ b/src/core/build_config_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BUILD_CONFIG_QT
#define BUILD_CONFIG_QT
diff --git a/src/core/certificate_error_controller.cpp b/src/core/certificate_error_controller.cpp
index 353228c2d..014d74500 100644
--- a/src/core/certificate_error_controller.cpp
+++ b/src/core/certificate_error_controller.cpp
@@ -1,44 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "certificate_error_controller.h"
-#include "certificate_error_controller_p.h"
#include <net/base/net_errors.h>
#include <net/cert/x509_certificate.h>
@@ -48,98 +11,142 @@
#include "components/strings/grit/components_strings.h"
#include "type_conversion.h"
-QT_BEGIN_NAMESPACE
-
-using namespace QtWebEngineCore;
-
-ASSERT_ENUMS_MATCH(CertificateErrorController::SslPinnedKeyNotInCertificateChain, net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateCommonNameInvalid, net::ERR_CERT_BEGIN)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateCommonNameInvalid, net::ERR_CERT_COMMON_NAME_INVALID)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateDateInvalid, net::ERR_CERT_DATE_INVALID)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateAuthorityInvalid, net::ERR_CERT_AUTHORITY_INVALID)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateContainsErrors, net::ERR_CERT_CONTAINS_ERRORS)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateUnableToCheckRevocation, net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateRevoked, net::ERR_CERT_REVOKED)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateInvalid, net::ERR_CERT_INVALID)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateWeakSignatureAlgorithm, net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateNonUniqueName, net::ERR_CERT_NON_UNIQUE_NAME)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateWeakKey, net::ERR_CERT_WEAK_KEY)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateNameConstraintViolation, net::ERR_CERT_NAME_CONSTRAINT_VIOLATION)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateValidityTooLong, net::ERR_CERT_VALIDITY_TOO_LONG)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateTransparencyRequired, net::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateSymantecLegacy, net::ERR_CERT_SYMANTEC_LEGACY)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateKnownInterceptionBlocked, net::ERR_CERT_KNOWN_INTERCEPTION_BLOCKED)
-ASSERT_ENUMS_MATCH(CertificateErrorController::CertificateErrorEnd, net::ERR_CERT_END)
-
-void CertificateErrorControllerPrivate::accept(bool accepted)
+namespace QtWebEngineCore {
+
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::SslPinnedKeyNotInCertificateChain,
+ net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateCommonNameInvalid, net::ERR_CERT_BEGIN)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateCommonNameInvalid,
+ net::ERR_CERT_COMMON_NAME_INVALID)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateDateInvalid, net::ERR_CERT_DATE_INVALID)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateAuthorityInvalid,
+ net::ERR_CERT_AUTHORITY_INVALID)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateContainsErrors,
+ net::ERR_CERT_CONTAINS_ERRORS)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateUnableToCheckRevocation,
+ net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateRevoked, net::ERR_CERT_REVOKED)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateInvalid, net::ERR_CERT_INVALID)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateWeakSignatureAlgorithm,
+ net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateNonUniqueName,
+ net::ERR_CERT_NON_UNIQUE_NAME)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateWeakKey, net::ERR_CERT_WEAK_KEY)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateNameConstraintViolation,
+ net::ERR_CERT_NAME_CONSTRAINT_VIOLATION)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateValidityTooLong,
+ net::ERR_CERT_VALIDITY_TOO_LONG)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateTransparencyRequired,
+ net::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateSymantecLegacy,
+ net::ERR_CERT_SYMANTEC_LEGACY)
+ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateKnownInterceptionBlocked,
+ net::ERR_CERT_KNOWN_INTERCEPTION_BLOCKED)
+// net::ERR_SSL_OBSOLETE_VERSION was removed again in Chromium 98
+//ASSERT_ENUMS_MATCH(QWebEngineCertificateError::SslObsoleteVersion,
+// net::ERR_SSL_OBSOLETE_VERSION)
+//ASSERT_ENUMS_MATCH(QWebEngineCertificateError::CertificateErrorEnd, net::ERR_CERT_END)
+
+// Copied from chrome/browser/ssl/ssl_error_handler.cc:
+static int IsCertErrorFatal(int cert_error)
{
- std::move(callback).Run(accepted ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE : content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
+ switch (cert_error) {
+ case net::ERR_CERT_COMMON_NAME_INVALID:
+ case net::ERR_CERT_DATE_INVALID:
+ case net::ERR_CERT_AUTHORITY_INVALID:
+ case net::ERR_CERT_NO_REVOCATION_MECHANISM:
+ case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION:
+ case net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM:
+ case net::ERR_CERT_WEAK_KEY:
+ case net::ERR_CERT_NAME_CONSTRAINT_VIOLATION:
+ case net::ERR_CERT_VALIDITY_TOO_LONG:
+ case net::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED:
+ case net::ERR_CERT_SYMANTEC_LEGACY:
+ case net::ERR_CERT_KNOWN_INTERCEPTION_BLOCKED:
+ return false;
+ case net::ERR_CERT_CONTAINS_ERRORS:
+ case net::ERR_CERT_REVOKED:
+ case net::ERR_CERT_INVALID:
+ case net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN:
+ return true;
+ default:
+ NOTREACHED();
+ }
+ return true;
}
-CertificateErrorControllerPrivate::CertificateErrorControllerPrivate(int cert_error,
- const net::SSLInfo& ssl_info,
- const GURL &request_url,
- bool main_frame,
- bool fatal_error,
- bool strict_enforcement,
- base::OnceCallback<void(content::CertificateRequestResultType)> cb
- )
- : certError(CertificateErrorController::CertificateError(cert_error))
- , requestUrl(toQt(request_url))
- , resourceType(main_frame ? CertificateErrorController::ResourceTypeMainFrame : CertificateErrorController::ResourceTypeOther)
- , fatalError(fatal_error)
- , strictEnforcement(strict_enforcement)
- , callback(std::move(cb))
+CertificateErrorController::CertificateErrorController(
+ int cert_error, const net::SSLInfo &ssl_info, const GURL &request_url,
+ bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> cb)
+ : m_certError(QWebEngineCertificateError::Type(cert_error))
+ , m_requestUrl(toQt(request_url))
+ , m_overridable(!IsCertErrorFatal(cert_error) && !strict_enforcement)
{
+ // MEMO set callback anyway even for non overridable error since chromium halts load until it's called
+ // callback will be executed either explicitly by use code or implicitly when error goes out of scope
+ m_callback = std::move(cb);
+
if (auto cert = ssl_info.cert.get()) {
- validStart = toQt(cert->valid_start());
- validExpiry = toQt(cert->valid_expiry());
- certificateChain = toCertificateChain(cert);
+ m_validExpiry = toQt(cert->valid_expiry());
+ m_certificateChain = toCertificateChain(cert);
}
}
-CertificateErrorController::CertificateErrorController(CertificateErrorControllerPrivate *p) : d(p)
-{
-}
-
CertificateErrorController::~CertificateErrorController()
{
- delete d;
- d = 0;
+ if (!answered())
+ rejectCertificate();
}
-CertificateErrorController::CertificateError CertificateErrorController::error() const
+QWebEngineCertificateError::Type CertificateErrorController::error() const
{
- return d->certError;
+ return m_certError;
}
QUrl CertificateErrorController::url() const
{
- return d->requestUrl;
+ return m_requestUrl;
}
bool CertificateErrorController::overridable() const
{
- return !d->fatalError && !d->strictEnforcement;
+ return m_overridable;
}
-bool CertificateErrorController::strictEnforcement() const
+bool CertificateErrorController::deferred() const
{
- return d->strictEnforcement;
+ return m_deferred;
+}
+
+void CertificateErrorController::defer()
+{
+ m_deferred = true;
+}
+
+bool CertificateErrorController::answered() const
+{
+ return m_answered;
}
void CertificateErrorController::accept(bool accepted)
{
- d->accept(accepted);
+ if (answered())
+ return;
+
+ m_answered = true;
+ if (m_callback)
+ std::move(m_callback)
+ .Run(accepted ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE
+ : content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
}
-CertificateErrorController::ResourceType CertificateErrorController::resourceType() const
+void CertificateErrorController::deactivate()
{
- return d->resourceType;
+ m_callback.Reset();
}
static QString getQStringForMessageId(int message_id) {
- base::string16 string = l10n_util::GetStringUTF16(message_id);
+ std::u16string string = l10n_util::GetStringUTF16(message_id);
return toQt(string);
}
@@ -148,41 +155,43 @@ QString CertificateErrorController::errorString() const
// Try to use chromiums translation of the error strings, though not all are
// consistently described and we need to use versions that does not contain HTML
// formatted text.
- switch (d->certError) {
- case SslPinnedKeyNotInCertificateChain:
+ switch (m_certError) {
+ case QWebEngineCertificateError::SslPinnedKeyNotInCertificateChain:
return getQStringForMessageId(IDS_CERT_ERROR_SUMMARY_PINNING_FAILURE_DETAILS);
- case CertificateCommonNameInvalid:
+ case QWebEngineCertificateError::CertificateCommonNameInvalid:
return getQStringForMessageId(IDS_CERT_ERROR_COMMON_NAME_INVALID_DESCRIPTION);
- case CertificateDateInvalid:
- if (QDateTime::currentDateTime() > d->validExpiry)
+ case QWebEngineCertificateError::CertificateDateInvalid:
+ if (QDateTime::currentDateTime() > m_validExpiry)
return getQStringForMessageId(IDS_CERT_ERROR_EXPIRED_DESCRIPTION);
else
return getQStringForMessageId(IDS_CERT_ERROR_NOT_YET_VALID_DESCRIPTION);
- case CertificateAuthorityInvalid:
- case CertificateKnownInterceptionBlocked:
- case CertificateSymantecLegacy:
+ case QWebEngineCertificateError::CertificateAuthorityInvalid:
+ case QWebEngineCertificateError::CertificateKnownInterceptionBlocked:
+ case QWebEngineCertificateError::CertificateSymantecLegacy:
return getQStringForMessageId(IDS_CERT_ERROR_AUTHORITY_INVALID_DESCRIPTION);
- case CertificateContainsErrors:
+ case QWebEngineCertificateError::CertificateContainsErrors:
return getQStringForMessageId(IDS_CERT_ERROR_CONTAINS_ERRORS_DESCRIPTION);
- case CertificateNoRevocationMechanism:
- return getQStringForMessageId(IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DETAILS);
- case CertificateRevoked:
+ case QWebEngineCertificateError::CertificateNoRevocationMechanism:
+ return getQStringForMessageId(IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DESCRIPTION);
+ case QWebEngineCertificateError::CertificateRevoked:
return getQStringForMessageId(IDS_CERT_ERROR_REVOKED_CERT_DESCRIPTION);
- case CertificateInvalid:
+ case QWebEngineCertificateError::CertificateInvalid:
return getQStringForMessageId(IDS_CERT_ERROR_INVALID_CERT_DESCRIPTION);
- case CertificateWeakSignatureAlgorithm:
+ case QWebEngineCertificateError::CertificateWeakSignatureAlgorithm:
return getQStringForMessageId(IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DESCRIPTION);
- case CertificateNonUniqueName:
+ case QWebEngineCertificateError::CertificateNonUniqueName:
return getQStringForMessageId(IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
- case CertificateWeakKey:
+ case QWebEngineCertificateError::CertificateWeakKey:
return getQStringForMessageId(IDS_CERT_ERROR_WEAK_KEY_DESCRIPTION);
- case CertificateNameConstraintViolation:
+ case QWebEngineCertificateError::CertificateNameConstraintViolation:
return getQStringForMessageId(IDS_CERT_ERROR_NAME_CONSTRAINT_VIOLATION_DESCRIPTION);
- case CertificateValidityTooLong:
+ case QWebEngineCertificateError::CertificateValidityTooLong:
return getQStringForMessageId(IDS_CERT_ERROR_VALIDITY_TOO_LONG_DESCRIPTION);
- case CertificateTransparencyRequired:
+ case QWebEngineCertificateError::CertificateTransparencyRequired:
return getQStringForMessageId(IDS_CERT_ERROR_CERTIFICATE_TRANSPARENCY_REQUIRED_DESCRIPTION);
- case CertificateUnableToCheckRevocation: // Deprecated in Chromium.
+ case QWebEngineCertificateError::SslObsoleteVersion:
+ return getQStringForMessageId(IDS_SSL_ERROR_OBSOLETE_VERSION_DESCRIPTION);
+ case QWebEngineCertificateError::CertificateUnableToCheckRevocation: // Deprecated in Chromium.
default:
break;
}
@@ -192,7 +201,7 @@ QString CertificateErrorController::errorString() const
QList<QSslCertificate> CertificateErrorController::certificateChain() const
{
- return d->certificateChain;
+ return m_certificateChain;
}
-QT_END_NAMESPACE
+}
diff --git a/src/core/certificate_error_controller.h b/src/core/certificate_error_controller.h
index dc1c3cf54..cbcb60f8a 100644
--- a/src/core/certificate_error_controller.h
+++ b/src/core/certificate_error_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,82 +17,60 @@
#include "qtwebenginecoreglobal_p.h"
+#include "base/functional/callback.h"
+#include "content/public/browser/certificate_request_result_type.h"
+
+#include "qwebenginecertificateerror.h"
#include <QtCore/QDateTime>
+#include <QtCore/QScopedPointer>
#include <QtCore/QUrl>
#include <QtNetwork/QSslCertificate>
-QT_BEGIN_NAMESPACE
+namespace net {
+class SSLInfo;
+}
+class GURL;
-class CertificateErrorControllerPrivate;
+namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT CertificateErrorController {
+class Q_WEBENGINECORE_EXPORT CertificateErrorController {
public:
- CertificateErrorController(CertificateErrorControllerPrivate *p);
+ CertificateErrorController(
+ int cert_error, const net::SSLInfo &ssl_info, const GURL &request_url,
+ bool strict_enforcement,
+ base::OnceCallback<void(content::CertificateRequestResultType)> callback);
~CertificateErrorController();
- // We can't use QSslError::SslErrors, because the error categories doesn't map.
- // Keep up to date with net/base/net_errors.h and net::IsCertificateError():
- enum CertificateError {
- SslPinnedKeyNotInCertificateChain = -150,
- CertificateCommonNameInvalid = -200,
- CertificateDateInvalid = -201,
- CertificateAuthorityInvalid = -202,
- CertificateContainsErrors = -203,
- CertificateNoRevocationMechanism = -204,
- CertificateUnableToCheckRevocation = -205,
- CertificateRevoked = -206,
- CertificateInvalid = -207,
- CertificateWeakSignatureAlgorithm = -208,
- CertificateNonUniqueName = -210,
- CertificateWeakKey = -211,
- CertificateNameConstraintViolation = -212,
- CertificateValidityTooLong = -213,
- CertificateTransparencyRequired = -214,
- CertificateSymantecLegacy = -215,
- CertificateKnownInterceptionBlocked = -217,
- CertificateErrorEnd = -218 // not an error, just an enum boundary
- };
-
- CertificateError error() const;
+ QWebEngineCertificateError::Type error() const;
QUrl url() const;
bool overridable() const;
- bool strictEnforcement() const;
QString errorString() const;
- QDateTime validStart() const;
QDateTime validExpiry() const;
QList<QSslCertificate> certificateChain() const;
+ bool deferred() const;
+ void defer();
+
+ bool answered() const;
void accept(bool);
- // Note: The resource type should probably not be exported, since once accepted the certificate exception
- // counts for all resource types.
- // Keep up to date with webkit/common/resource_type.h
- enum ResourceType {
- ResourceTypeMainFrame = 0, // top level page
- ResourceTypeSubFrame, // frame or iframe
- ResourceTypeStylesheet, // a CSS stylesheet
- ResourceTypeScript, // an external script
- ResourceTypeImage, // an image (jpg/gif/png/etc)
- ResourceTypeFont, // a font
- ResourceTypeOther, // an "other" subresource.
- ResourceTypeObject, // an object (or embed) tag for a plugin,
- // or a resource that a plugin requested.
- ResourceTypeMedia, // a media resource.
- ResourceTypeWorker, // the main resource of a dedicated worker.
- ResourceTypeSharedWorker, // the main resource of a shared worker.
- ResourceTypePrefetch, // an explicitly requested prefetch
- ResourceTypeFavicon, // a favicon
- ResourceTypeXHR, // a XMLHttpRequest
- ResourceTypePing, // a ping request for <a ping>
- ResourceTypeServiceWorker, // the main resource of a service worker.
- };
-
- ResourceType resourceType() const;
+ void ignoreCertificateError() { accept(true); }
+ void rejectCertificate() { accept(false); }
+
+ void deactivate();
+
+ QWebEngineCertificateError::Type m_certError;
+ const QUrl m_requestUrl;
+ QDateTime m_validExpiry;
+ bool m_overridable;
+ base::OnceCallback<void(content::CertificateRequestResultType)> m_callback;
+ QList<QSslCertificate> m_certificateChain;
+
+ bool m_answered = false, m_deferred = false;
private:
- CertificateErrorControllerPrivate* d;
+ Q_DISABLE_COPY(CertificateErrorController)
};
-QT_END_NAMESPACE
-
+}
#endif // CERTIFICATE_ERROR_CONTROLLER_H
diff --git a/src/core/certificate_error_controller_p.h b/src/core/certificate_error_controller_p.h
deleted file mode 100644
index b0b0bc658..000000000
--- a/src/core/certificate_error_controller_p.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CERTIFICATE_ERROR_CONTROLLER_P_H
-#define CERTIFICATE_ERROR_CONTROLLER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "content/public/browser/content_browser_client.h"
-
-#include "certificate_error_controller.h"
-
-QT_BEGIN_NAMESPACE
-
-class CertificateErrorControllerPrivate {
-public:
- CertificateErrorControllerPrivate(int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool main_frame, bool fatal_error, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback);
-
- void accept(bool accepted);
-
- CertificateErrorController::CertificateError certError;
- const QUrl requestUrl;
- QDateTime validStart;
- QDateTime validExpiry;
- CertificateErrorController::ResourceType resourceType;
- bool fatalError;
- bool strictEnforcement;
- base::OnceCallback<void(content::CertificateRequestResultType)> callback;
- QList<QSslCertificate> certificateChain;
-};
-
-QT_END_NAMESPACE
-
-#endif // CERTIFICATE_ERROR_CONTROLLER_P_H
diff --git a/src/core/chromium_overrides.cpp b/src/core/chromium_overrides.cpp
index 01937d3e7..28917e6c5 100644
--- a/src/core/chromium_overrides.cpp
+++ b/src/core/chromium_overrides.cpp
@@ -1,76 +1,41 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "type_conversion.h"
#include "ozone/gl_context_qt.h"
#include "qtwebenginecoreglobal_p.h"
#include "web_contents_view_qt.h"
+#include "web_engine_library_info.h"
#include "base/values.h"
-#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
-#include "content/browser/accessibility/accessibility_tree_formatter_browser.h"
-#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/browser/web_contents/web_contents_view.h"
#include "content/common/font_list.h"
+#include "content/public/browser/web_contents_view_delegate.h"
+#include "extensions/buildflags/buildflags.h"
+#include "extensions/common/constants.h"
+#include "gpu/vulkan/buildflags.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_factory.h"
-#include "ui/events/devices/device_data_manager.h"
-#include "ui/events/platform/platform_event_source.h"
-#include "ui/snapshot/snapshot.h"
-#include "ppapi/buildflags/buildflags.h"
#include <QGuiApplication>
-#include <QScreen>
-#include <QWindow>
#include <QFontDatabase>
-#include <QStringList>
#include <QLibraryInfo>
-#if defined(USE_AURA) && !defined(USE_OZONE)
-#include "ui/base/dragdrop/os_exchange_data.h"
-#include "ui/base/dragdrop/os_exchange_data_provider_aura.h"
-#include "ui/gfx/render_text.h"
-#include "ui/gfx/platform_font.h"
+#if !QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+#include "chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h"
#endif
-#if defined(USE_OPENSSL_CERTS)
-#include "net/ssl/openssl_client_key_store.h"
-#endif
+#if BUILDFLAG(ENABLE_VULKAN)
+#include "compositor/vulkan_implementation_qt.h"
+
+#include "gpu/vulkan/init/vulkan_factory.h"
+
+#if defined(USE_OZONE)
+#include "ui/ozone/public/ozone_platform.h"
+#include "ui/ozone/public/surface_factory_ozone.h"
+#endif // defined(USE_OZONE)
+#endif // defined(ENABLE_VULKAN)
void *GetQtXDisplay()
{
@@ -78,124 +43,166 @@ void *GetQtXDisplay()
}
namespace content {
-class WebContentsImpl;
-class WebContentsView;
-class WebContentsViewDelegate;
class RenderViewHostDelegateView;
-WebContentsView* CreateWebContentsView(WebContentsImpl *web_contents,
- WebContentsViewDelegate *,
- RenderViewHostDelegateView **render_view_host_delegate_view)
+std::unique_ptr<WebContentsView> CreateWebContentsView(
+ WebContentsImpl *web_contents,
+ std::unique_ptr<WebContentsViewDelegate> delegate,
+ raw_ptr<RenderViewHostDelegateView>* render_view_host_delegate_view)
{
- QtWebEngineCore::WebContentsViewQt* rv = new QtWebEngineCore::WebContentsViewQt(web_contents);
+ QtWebEngineCore::WebContentsViewQt *rv = new QtWebEngineCore::WebContentsViewQt(web_contents);
*render_view_host_delegate_view = rv;
- return rv;
+ return std::unique_ptr<WebContentsView>(rv);
}
-#if defined(Q_OS_MACOS)
-std::string getQtPrefix()
+#if defined(Q_OS_DARWIN)
+#if defined(QT_MAC_FRAMEWORK_BUILD)
+base::FilePath getSandboxPath()
+{
+ return WebEngineLibraryInfo::getPath(QT_FRAMEWORK_BUNDLE);
+}
+#else
+base::FilePath getSandboxPath()
{
const QString prefix = QLibraryInfo::location(QLibraryInfo::PrefixPath);
- return prefix.toStdString();
+ return QtWebEngineCore::toFilePath(prefix);
}
#endif
-
+#endif
} // namespace content
#if defined(USE_AURA) || defined(USE_OZONE)
namespace content {
// content/common/font_list.h
-std::unique_ptr<base::ListValue> GetFontList_SlowBlocking()
+base::Value::List GetFontList_SlowBlocking()
{
- std::unique_ptr<base::ListValue> font_list(new base::ListValue);
+ base::Value::List font_list;
- QFontDatabase database;
- for (auto family : database.families()){
- std::unique_ptr<base::ListValue> font_item(new base::ListValue());
- font_item->AppendString(family.toStdString());
- font_item->AppendString(family.toStdString()); // localized name.
+ for (auto family : QFontDatabase::families()){
+ base::Value::List font_item;
+ font_item.Append(family.toStdString());
+ font_item.Append(family.toStdString()); // localized name.
// TODO(yusukes): Support localized family names.
- font_list->Append(std::move(font_item));
+ font_list.Append(std::move(font_item));
}
return font_list;
}
} // namespace content
+#endif // defined(USE_AURA) || defined(USE_OZONE)
-namespace aura {
-class Window;
-}
+#if BUILDFLAG(ENABLE_VULKAN)
+namespace gpu {
+std::unique_ptr<VulkanImplementation> CreateVulkanImplementation(bool use_swiftshader,
+ bool allow_protected_memory)
+{
+#if QT_CONFIG(webengine_vulkan)
+#if BUILDFLAG(IS_APPLE)
+ // TODO: Investigate if we can support MoltenVK.
+ NOTIMPLEMENTED();
+ return nullptr;
+#else
+#if defined(USE_OZONE)
+ return ui::OzonePlatform::GetInstance()->GetSurfaceFactoryOzone()->CreateVulkanImplementation(
+ use_swiftshader, allow_protected_memory);
+#endif
+
+#if !BUILDFLAG(IS_WIN)
+ // TODO(samans): Support Swiftshader on more platforms.
+ // https://crbug.com/963988
+ DCHECK(!use_swiftshader) << "Vulkan Swiftshader is not supported on this platform.";
+#endif // !BUILDFLAG(IS_WIN)
-namespace wm {
-class ActivationClient;
+ // Protected memory is supported only on Fuchsia, which uses Ozone, i.e.
+ // VulkanImplementation is initialized above.
+ DCHECK(!allow_protected_memory) << "Protected memory is not supported on this platform.";
+
+ return std::make_unique<VulkanImplementationQt>();
+#endif // BUILDFLAG(IS_APPLE)
+#else
+ NOTREACHED();
+ return nullptr;
+#endif // QT_CONFIG(webengine_vulkan)
+}
+} // namespace gpu
+#endif // BUILDFLAG(ENABLE_VULKAN)
-ActivationClient *GetActivationClient(aura::Window *)
+std::unique_ptr<ui::OSExchangeDataProvider> ui::OSExchangeDataProviderFactory::CreateProvider()
{
return nullptr;
}
-} // namespace wm
-#endif // defined(USE_AURA) || defined(USE_OZONE)
+#if !QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+namespace extensions {
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateSetMetaDataFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
-namespace content {
-std::vector<AccessibilityTreeFormatter::TestPass> AccessibilityTreeFormatter::GetTestPasses()
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartFunction::Run()
{
- return {
- {"blink", &AccessibilityTreeFormatterBlink::CreateBlink, nullptr},
- {"native", &AccessibilityTreeFormatter::Create, nullptr},
- };
+ return RespondNow(NoArguments());
}
-} // namespace content
-#if defined(USE_AURA)
-namespace ui {
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
-bool GrabWindowSnapshot(gfx::NativeWindow window,
- const gfx::Rect& snapshot_bounds,
- gfx::Image* image)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopFunction::Run()
{
- NOTIMPLEMENTED();
- return false;
+ return RespondNow(NoArguments());
}
-bool GrabViewSnapshot(gfx::NativeView view,
- const gfx::Rect& snapshot_bounds,
- gfx::Image* image)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStoreFunction::Run()
{
- NOTIMPLEMENTED();
- return false;
+ return RespondNow(NoArguments());
}
-void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window,
- const gfx::Rect& source_rect,
- const gfx::Size& target_size,
- GrabWindowSnapshotAsyncCallback callback)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateUploadStoredFunction::Run()
{
- NOTIMPLEMENTED();
- std::move(callback).Run(gfx::Image());
+ return RespondNow(NoArguments());
}
-void GrabWindowSnapshotAsync(gfx::NativeWindow window,
- const gfx::Rect& source_rect,
- GrabWindowSnapshotAsyncCallback callback)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateUploadFunction::Run()
{
- NOTIMPLEMENTED();
- std::move(callback).Run(gfx::Image());
+ return RespondNow(NoArguments());
}
-void GrabViewSnapshotAsync(gfx::NativeView view,
- const gfx::Rect& source_rect,
- GrabWindowSnapshotAsyncCallback callback)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateDiscardFunction::Run()
{
- NOTIMPLEMENTED();
- std::move(callback).Run(gfx::Image());
+ return RespondNow(NoArguments());
}
-} // namespace ui
-#endif // defined(USE_AURA)
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartRtpDumpFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
-std::unique_ptr<ui::OSExchangeData::Provider>
-ui::OSExchangeDataProviderFactory::CreateProvider() {
- return nullptr;
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopRtpDumpFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartAudioDebugRecordingsFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopAudioDebugRecordingsFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartEventLoggingFunction::Run()
+{
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction WebrtcLoggingPrivateGetLogsDirectoryFunction::Run()
+{
+ return RespondNow(NoArguments());
}
+} // namespace extensions
+#endif // !QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
diff --git a/src/core/client_cert_select_controller.cpp b/src/core/client_cert_select_controller.cpp
index 0baaf2bc5..d6af984c1 100644
--- a/src/core/client_cert_select_controller.cpp
+++ b/src/core/client_cert_select_controller.cpp
@@ -1,58 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "client_cert_select_controller.h"
-#include <base/bind.h>
+#include <base/functional/bind.h>
#include <content/public/browser/client_certificate_delegate.h>
#include <net/cert/x509_certificate.h>
#include <net/ssl/client_cert_identity.h>
#include <net/ssl/ssl_cert_request_info.h>
#include <net/ssl/ssl_info.h>
+#include "net/ssl/ssl_private_key.h"
#include "type_conversion.h"
#include <QDebug>
-QT_BEGIN_NAMESPACE
-
-using namespace QtWebEngineCore;
+namespace QtWebEngineCore {
ClientCertSelectController::ClientCertSelectController(net::SSLCertRequestInfo *certRequestInfo,
std::vector<std::unique_ptr<net::ClientCertIdentity>> clientCerts,
@@ -73,8 +36,6 @@ ClientCertSelectController::~ClientCertSelectController()
m_delegate->ContinueWithCertificate(nullptr, nullptr);
}
-#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
-
void ClientCertSelectController::selectNone()
{
if (m_selected) {
@@ -97,8 +58,8 @@ void ClientCertSelectController::select(int index)
scoped_refptr<net::X509Certificate> cert = certInfo->certificate();
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move(certInfo),
- base::Bind(&content::ClientCertificateDelegate::ContinueWithCertificate,
- base::Passed(std::move(m_delegate)), std::move(cert)));
+ base::BindOnce(&content::ClientCertificateDelegate::ContinueWithCertificate,
+ std::move(m_delegate), std::move(cert)));
return;
}
std::vector<std::string> pem_encoded;
@@ -116,15 +77,16 @@ void ClientCertSelectController::select(const QSslCertificate &certificate)
}
QByteArray derCertificate = certificate.toDer();
scoped_refptr<net::X509Certificate> selectedCert =
- net::X509Certificate::CreateFromBytes(derCertificate.constData(), derCertificate.length());
+ net::X509Certificate::CreateFromBytes(base::make_span((const unsigned char *)derCertificate.constData(),
+ (long unsigned)derCertificate.length()));
for (auto &certInfo : m_clientCerts) {
scoped_refptr<net::X509Certificate> cert = certInfo->certificate();
if (cert->EqualsExcludingChain(selectedCert.get())) {
m_selected = true;
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move(certInfo),
- base::Bind(&content::ClientCertificateDelegate::ContinueWithCertificate,
- base::Passed(std::move(m_delegate)), std::move(cert)));
+ base::BindOnce(&content::ClientCertificateDelegate::ContinueWithCertificate,
+ std::move(m_delegate), std::move(cert)));
return;
}
}
@@ -132,7 +94,7 @@ void ClientCertSelectController::select(const QSslCertificate &certificate)
<< " Selected certificate needs to be one of the offered";
}
-QVector<QSslCertificate> ClientCertSelectController::certificates() const
+QList<QSslCertificate> ClientCertSelectController::certificates() const
{
if (!m_certificates.isEmpty())
return m_certificates;
@@ -144,6 +106,4 @@ QVector<QSslCertificate> ClientCertSelectController::certificates() const
return m_certificates;
}
-#endif // !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
-
-QT_END_NAMESPACE
+}
diff --git a/src/core/client_cert_select_controller.h b/src/core/client_cert_select_controller.h
index f121c1155..8380a7845 100644
--- a/src/core/client_cert_select_controller.h
+++ b/src/core/client_cert_select_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,14 +15,12 @@
#ifndef CLIENT_CERT_SELECT_CONTROLLER_H
#define CLIENT_CERT_SELECT_CONTROLLER_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QtNetwork/qtnetwork-config.h>
#include <QtCore/QUrl>
-#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
-#include <QtCore/QVector>
+#include <QtCore/QList>
#include <QtNetwork/QSslCertificate>
-#endif
#include <memory>
namespace content {
@@ -70,9 +32,9 @@ class ClientCertIdentity;
class SSLCertRequestInfo;
}
-QT_BEGIN_NAMESPACE
+namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT ClientCertSelectController {
+class Q_WEBENGINECORE_EXPORT ClientCertSelectController {
public:
ClientCertSelectController(net::SSLCertRequestInfo *certRequestInfo,
std::vector<std::unique_ptr<net::ClientCertIdentity>> clientCerts,
@@ -80,22 +42,20 @@ public:
~ClientCertSelectController();
QUrl hostAndPort() const { return m_hostAndPort; }
-#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
void selectNone();
void select(const QSslCertificate &certificate);
void select(int index);
- QVector<QSslCertificate> certificates() const;
-#endif
+ QList<QSslCertificate> certificates() const;
private:
QUrl m_hostAndPort;
std::vector<std::unique_ptr<net::ClientCertIdentity>> m_clientCerts;
std::unique_ptr<content::ClientCertificateDelegate> m_delegate;
- mutable QVector<QSslCertificate> m_certificates;
+ mutable QList<QSslCertificate> m_certificates;
bool m_selected;
};
-QT_END_NAMESPACE
+}
#endif // CLIENT_CERT_SELECT_CONTROLLER_H
diff --git a/src/core/client_hints.cpp b/src/core/client_hints.cpp
new file mode 100644
index 000000000..9fa7531da
--- /dev/null
+++ b/src/core/client_hints.cpp
@@ -0,0 +1,177 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "client_hints.h"
+
+#include "profile_qt.h"
+#include "web_contents_delegate_qt.h"
+#include "web_engine_settings.h"
+
+#include "components/embedder_support/user_agent_utils.h"
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "content/public/browser/network_service_instance.h"
+#include "extensions/buildflags/buildflags.h"
+#include "services/network/public/cpp/is_potentially_trustworthy.h"
+#include "services/network/public/cpp/network_quality_tracker.h"
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+#include "components/guest_view/browser/guest_view_base.h"
+#endif
+
+namespace QtWebEngineCore {
+
+// based on weblayer/browser/client_hints_factory.cc:
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// static
+ClientHints *ClientHintsFactory::GetForBrowserContext(content::BrowserContext *browser_context)
+{
+ return static_cast<ClientHints*>(GetInstance()->GetServiceForBrowserContext(browser_context, true));
+}
+
+// static
+ClientHintsFactory *ClientHintsFactory::GetInstance()
+{
+ static base::NoDestructor<ClientHintsFactory> factory;
+ return factory.get();
+}
+
+ClientHintsFactory::ClientHintsFactory()
+ : BrowserContextKeyedServiceFactory("ClientHints", BrowserContextDependencyManager::GetInstance())
+{
+}
+
+ClientHintsFactory::~ClientHintsFactory() = default;
+
+KeyedService *ClientHintsFactory::BuildServiceInstanceFor(content::BrowserContext *context) const
+{
+ return new ClientHints(context);
+}
+
+content::BrowserContext *ClientHintsFactory::GetBrowserContextToUse(content::BrowserContext *context) const
+{
+ return context;
+}
+
+// based on components/client_hints/browser/in_memory_client_hints_controller_delegate.cc:
+// Copyright 2022 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+ClientHints::ClientHints(content::BrowserContext *context)
+ : context_(context)
+{
+}
+
+ClientHints::~ClientHints() = default;
+
+// Enabled Client Hints are only cached and not persisted in this
+// implementation.
+void ClientHints::PersistClientHints(const url::Origin &primary_origin,
+ content::RenderFrameHost *parent_rfh,
+ const std::vector<network::mojom::WebClientHintsType> &client_hints)
+{
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ const GURL primary_url = primary_origin.GetURL();
+ DCHECK(primary_url.is_valid());
+ if (!network::IsUrlPotentiallyTrustworthy(primary_url))
+ return;
+
+ // Client hints should only be enabled when JavaScript is enabled.
+ if (!IsJavaScriptAllowed(primary_url, parent_rfh))
+ return;
+
+ blink::EnabledClientHints enabled_hints;
+ ProfileAdapter *profileAdapter = static_cast<ProfileQt *>(context_)->profileAdapter();
+ for (auto hint : client_hints) {
+ enabled_hints.SetIsEnabled(hint, profileAdapter->clientHintsEnabled());
+ }
+ accept_ch_cache_[primary_origin] = enabled_hints;
+}
+
+// Looks up enabled Client Hints for the URL origin, and adds additional Client
+// Hints if set.
+void ClientHints::GetAllowedClientHintsFromSource(const url::Origin &origin,
+ blink::EnabledClientHints *client_hints)
+{
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ DCHECK(client_hints);
+ // Can not assert this, as we get here for unregistered custom schemes:
+ if (!network::IsOriginPotentiallyTrustworthy(origin))
+ return;
+
+ const auto &it = accept_ch_cache_.find(origin);
+ if (it != accept_ch_cache_.end()) {
+ *client_hints = it->second;
+ }
+
+ ProfileAdapter *profileAdapter = static_cast<ProfileQt *>(context_)->profileAdapter();
+ for (auto hint : additional_hints_)
+ client_hints->SetIsEnabled(hint, profileAdapter->clientHintsEnabled());
+}
+
+void ClientHints::SetAdditionalClientHints(const std::vector<network::mojom::WebClientHintsType> &hints)
+{
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ additional_hints_ = hints;
+}
+
+void ClientHints::ClearAdditionalClientHints()
+{
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ additional_hints_.clear();
+}
+
+network::NetworkQualityTracker *ClientHints::GetNetworkQualityTracker()
+{
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ if (!network_quality_tracker_) {
+ network_quality_tracker_ =
+ std::make_unique<network::NetworkQualityTracker>(
+ base::BindRepeating(&content::GetNetworkService));
+ }
+ return network_quality_tracker_.get();
+}
+
+bool ClientHints::IsJavaScriptAllowed(const GURL &url, content::RenderFrameHost *parent_rfh)
+{
+ content::WebContents *webContents = content::WebContents::FromRenderFrameHost(parent_rfh);
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ if (webContents && guest_view::GuestViewBase::IsGuest(webContents))
+ webContents = guest_view::GuestViewBase::GetTopLevelWebContents(webContents);
+#endif
+
+ if (webContents) {
+ WebContentsDelegateQt* delegate =
+ static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
+ if (delegate) {
+ WebEngineSettings *settings = delegate->webEngineSettings();
+ if (settings)
+ return settings->testAttribute(QWebEngineSettings::JavascriptEnabled);
+ }
+ }
+ return true;
+}
+
+bool ClientHints::AreThirdPartyCookiesBlocked(const GURL &url, content::RenderFrameHost *rfh)
+{
+ return false; // we probably can not report anything more specific
+}
+
+blink::UserAgentMetadata ClientHints::GetUserAgentMetadata()
+{
+ return static_cast<ProfileQt *>(context_)->userAgentMetadata();
+}
+
+void ClientHints::SetMostRecentMainFrameViewportSize(
+ const gfx::Size& viewport_size) {
+ viewport_size_ = viewport_size;
+}
+
+gfx::Size
+ClientHints::GetMostRecentMainFrameViewportSize() {
+ return viewport_size_;
+}
+} // namespace
diff --git a/src/core/client_hints.h b/src/core/client_hints.h
new file mode 100644
index 000000000..193982d16
--- /dev/null
+++ b/src/core/client_hints.h
@@ -0,0 +1,102 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef CLIENT_HINTS_H_
+#define CLIENT_HINTS_H_
+
+// based on components/client_hints/browser/client_hints.h:
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/memory/raw_ptr.h"
+#include "base/no_destructor.h"
+#include "base/sequence_checker.h"
+#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
+#include "components/keyed_service/core/keyed_service.h"
+#include "content/public/browser/client_hints_controller_delegate.h"
+#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
+
+namespace QtWebEngineCore {
+
+class ClientHints;
+
+class ClientHintsFactory : public BrowserContextKeyedServiceFactory
+{
+public:
+ ClientHintsFactory(const ClientHintsFactory &) = delete;
+ ClientHintsFactory &operator=(const ClientHintsFactory &) = delete;
+
+ static ClientHints *GetForBrowserContext(content::BrowserContext *browser_context);
+ static ClientHintsFactory *GetInstance();
+
+private:
+ friend class base::NoDestructor<ClientHintsFactory>;
+
+ ClientHintsFactory();
+ ~ClientHintsFactory() override;
+
+ // BrowserContextKeyedServiceFactory methods:
+ KeyedService *BuildServiceInstanceFor(content::BrowserContext *profile) const override;
+ content::BrowserContext *GetBrowserContextToUse(content::BrowserContext *context) const override;
+};
+
+class ClientHints : public KeyedService, public content::ClientHintsControllerDelegate
+{
+public:
+ ClientHints(content::BrowserContext *context);
+
+ ClientHints(const ClientHints &) = delete;
+ ClientHints &operator=(const ClientHints &) = delete;
+
+ ~ClientHints() override;
+
+ // content::ClientHintsControllerDelegate:
+ network::NetworkQualityTracker *GetNetworkQualityTracker() override;
+
+ void GetAllowedClientHintsFromSource(const url::Origin &origin, blink::EnabledClientHints *client_hints) override;
+
+ bool IsJavaScriptAllowed(const GURL &url, content::RenderFrameHost *parent_rfh) override;
+
+ bool AreThirdPartyCookiesBlocked(const GURL &url, content::RenderFrameHost *rfh) override;
+
+ blink::UserAgentMetadata GetUserAgentMetadata() override;
+
+ void PersistClientHints(const url::Origin &primary_origin,
+ content::RenderFrameHost *parent_rfh,
+ const std::vector<network::mojom::WebClientHintsType> &client_hints) override;
+
+ void SetAdditionalClientHints(const std::vector<network::mojom::WebClientHintsType> &) override;
+
+ void ClearAdditionalClientHints() override;
+
+ void SetMostRecentMainFrameViewportSize(const gfx::Size&) override;
+ gfx::Size GetMostRecentMainFrameViewportSize() override;
+
+private:
+ SEQUENCE_CHECKER(sequence_checker_);
+
+ raw_ptr<content::BrowserContext> context_ = nullptr;
+
+ // Stores enabled Client Hint types for an origin.
+ std::map<url::Origin, blink::EnabledClientHints> accept_ch_cache_
+ GUARDED_BY_CONTEXT(sequence_checker_);
+
+ // Additional Client Hint types for Client Hints Reliability. If additional
+ // hints are set, they would be included by subsequent calls to
+ // GetAllowedClientHintsFromSource.
+ std::vector<network::mojom::WebClientHintsType> additional_hints_
+ GUARDED_BY_CONTEXT(sequence_checker_);
+
+ std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_
+ GUARDED_BY_CONTEXT(sequence_checker_);
+
+ // This stores the viewport size of the most recent visible main frame tree
+ // node. This value is only used when the viewport size cannot be directly
+ // queried such as for prefetch requests and for tab restores.
+ gfx::Size viewport_size_;
+};
+
+} // namespace QtWebEngineCore
+
+#endif
diff --git a/src/core/clipboard_change_observer.h b/src/core/clipboard_change_observer.h
index f9b33fc93..33a382fbe 100644
--- a/src/core/clipboard_change_observer.h
+++ b/src/core/clipboard_change_observer.h
@@ -1,62 +1,29 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CLIPBOARD_CHANGE_OBSERVER_H
#define CLIPBOARD_CHANGE_OBSERVER_H
#include <QClipboard>
-#include <QMap>
#include <QObject>
+#include "ui/base/clipboard/clipboard_sequence_number_token.h"
+
namespace QtWebEngineCore {
class ClipboardChangeObserver : public QObject {
Q_OBJECT
public:
ClipboardChangeObserver();
- quint64 getSequenceNumber(QClipboard::Mode mode) { return sequenceNumber.value(mode); }
+ const ui::ClipboardSequenceNumberToken &getPrimarySequenceNumber() { return m_primarySequenceNumber; }
+ const ui::ClipboardSequenceNumberToken &getSelectionSequenceNumber() { return m_selectionSequenceNumber; }
private Q_SLOTS:
void trackChange(QClipboard::Mode mode);
private:
- QMap<QClipboard::Mode, quint64> sequenceNumber;
+ ui::ClipboardSequenceNumberToken m_primarySequenceNumber;
+ ui::ClipboardSequenceNumberToken m_selectionSequenceNumber;
};
} // namespace QtWebEngineCore
diff --git a/src/core/clipboard_qt.cpp b/src/core/clipboard_qt.cpp
index ef7a05299..3f49c6e3c 100644
--- a/src/core/clipboard_qt.cpp
+++ b/src/core/clipboard_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -46,16 +10,26 @@
#include "type_conversion.h"
#include "base/logging.h"
+#include "base/strings/utf_offset_string_conversions.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/types/variant_util.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/custom_data_helper.h"
#include "ui/base/clipboard/clipboard.h"
+#include "ui/base/clipboard/clipboard_monitor.h"
#include "ui/base/clipboard/clipboard_constants.h"
#include "ui/base/clipboard/clipboard_format_type.h"
+#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
+#include "ui/base/ui_base_features.h"
+#include <QBuffer>
#include <QGuiApplication>
#include <QImage>
+#include <QImageWriter>
#include <QMimeData>
+#include <memory>
+
namespace QtWebEngineCore {
static void registerMetaTypes()
@@ -74,7 +48,13 @@ ClipboardChangeObserver::ClipboardChangeObserver()
void ClipboardChangeObserver::trackChange(QClipboard::Mode mode)
{
- ++sequenceNumber[mode];
+ if (mode == QClipboard::Clipboard)
+ m_primarySequenceNumber = ui::ClipboardSequenceNumberToken();
+ else if (mode == QClipboard::Selection)
+ m_selectionSequenceNumber = ui::ClipboardSequenceNumberToken();
+ else
+ return;
+ ui::ClipboardMonitor::GetInstance()->NotifyClipboardDataChanged();
}
} // namespace QtWebEngineCore
@@ -83,12 +63,12 @@ using namespace QtWebEngineCore;
namespace {
-QScopedPointer<QMimeData> uncommittedData;
+std::unique_ptr<QMimeData> uncommittedData;
QMimeData *getUncommittedData()
{
if (!uncommittedData)
uncommittedData.reset(new QMimeData);
- return uncommittedData.data();
+ return uncommittedData.get();
}
} // namespace
@@ -105,50 +85,83 @@ Clipboard *Clipboard::Create()
namespace QtWebEngineCore {
-void ClipboardQt::WritePortableRepresentations(ui::ClipboardBuffer type, const ObjectMap &objects)
+#if defined(Q_OS_WIN)
+extern std::string HtmlToCFHtml(const std::string &html, const std::string &base_url);
+extern void CFHtmlExtractMetadata(const std::string &cf_html, std::string *base_url,
+ size_t *html_start, size_t *fragment_start, size_t *fragment_end);
+#endif // defined(Q_OS_WIN)
+
+void ClipboardQt::WritePortableAndPlatformRepresentations(ui::ClipboardBuffer type,
+ const ObjectMap &objects,
+ std::vector<ui::Clipboard::PlatformRepresentation> platform_representations,
+ std::unique_ptr<ui::DataTransferEndpoint> data_src)
{
DCHECK(CalledOnValidThread());
DCHECK(IsSupportedClipboardBuffer(type));
+ if (!platform_representations.empty())
+ DispatchPlatformRepresentations(std::move(platform_representations));
for (const auto &object : objects)
- DispatchPortableRepresentation(object.first, object.second);
+ DispatchPortableRepresentation(object.second);
// Commit the accumulated data.
if (uncommittedData)
- QGuiApplication::clipboard()->setMimeData(uncommittedData.take(),
+ QGuiApplication::clipboard()->setMimeData(uncommittedData.release(),
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard
: QClipboard::Selection);
if (type == ui::ClipboardBuffer::kCopyPaste && IsSupportedClipboardBuffer(ui::ClipboardBuffer::kSelection)) {
- ObjectMap::const_iterator text_iter = objects.find(PortableFormat::kText);
+ auto text_iter = objects.find(base::VariantIndexOfType<Data, TextData>());
if (text_iter != objects.end()) {
// Copy text and SourceTag to the selection clipboard.
- WritePortableRepresentations(ui::ClipboardBuffer::kSelection,
- ObjectMap(text_iter, text_iter + 1));
+ WritePortableAndPlatformRepresentations(ui::ClipboardBuffer::kSelection,
+ ObjectMap(text_iter, ++text_iter),
+ {},
+ nullptr);
}
}
+ m_dataSrc[type] = std::move(data_src);
}
-void ClipboardQt::WritePlatformRepresentations(ui::ClipboardBuffer buffer, std::vector<ui::Clipboard::PlatformRepresentation> platform_representations)
-{
- DCHECK(CalledOnValidThread());
- DCHECK(IsSupportedClipboardBuffer(buffer));
- DispatchPlatformRepresentations(std::move(platform_representations));
-}
-
-void ClipboardQt::WriteText(const char *text_data, size_t text_len)
+void ClipboardQt::WriteText(base::StringPiece text)
{
- getUncommittedData()->setText(QString::fromUtf8(text_data, text_len));
+ getUncommittedData()->setText(toQString(text));
}
-void ClipboardQt::WriteHTML(const char *markup_data, size_t markup_len, const char *url_data, size_t url_len)
+void ClipboardQt::WriteHTML(base::StringPiece markup, absl::optional<base::StringPiece> source_url)
{
- getUncommittedData()->setHtml(QString::fromUtf8(markup_data, markup_len));
+ QString markup_string = toQString(markup);
+#if defined (Q_OS_MACOS)
+ // We need to prepend the charset on macOS to prevent garbled Unicode characters
+ // when pasting to certain applications (e.g. Notes, TextEdit)
+ // Mirrors the behavior in ui/base/clipboard/clipboard_mac.mm in Chromium.
+ markup_string.prepend(QLatin1String("<meta charset='utf-8'>"));
+#endif
+
+#if !defined(Q_OS_WIN)
+ getUncommittedData()->setHtml(markup_string);
+#else
+ QString url;
+ if (source_url)
+ url = toQString(*source_url);
+
+ std::string cf_html = HtmlToCFHtml(markup_string.toStdString(), url.toStdString());
+ size_t html_start = std::string::npos;
+ size_t fragment_start = std::string::npos;
+ size_t fragment_end = std::string::npos;
+ CFHtmlExtractMetadata(cf_html, nullptr, &html_start, &fragment_start, &fragment_end);
+
+ DCHECK(fragment_start != std::string::npos && fragment_end != std::string::npos
+ && html_start != std::string::npos);
+ DCHECK(fragment_start >= html_start && fragment_end >= fragment_start);
+
+ getUncommittedData()->setHtml(QString::fromStdString(cf_html.substr(html_start)));
+#endif // !defined(Q_OS_WIN)
}
-void ClipboardQt::WriteRTF(const char *rtf_data, size_t data_len)
+void ClipboardQt::WriteRTF(base::StringPiece rtf)
{
- getUncommittedData()->setData(QString::fromLatin1(ui::kMimeTypeRTF), QByteArray(rtf_data, data_len));
+ getUncommittedData()->setData(QString::fromLatin1(ui::kMimeTypeRTF), toQByteArray(rtf));
}
void ClipboardQt::WriteWebSmartPaste()
@@ -161,12 +174,12 @@ void ClipboardQt::WriteBitmap(const SkBitmap &bitmap)
getUncommittedData()->setImageData(toQImage(bitmap).copy());
}
-void ClipboardQt::WriteBookmark(const char *title_data, size_t title_len, const char *url_data, size_t url_len)
+void ClipboardQt::WriteBookmark(base::StringPiece title_in, base::StringPiece url_in)
{
// FIXME: Untested, seems to be used only for drag-n-drop.
// Write as a mozilla url (UTF16: URL, newline, title).
- QString url = QString::fromUtf8(url_data, url_len);
- QString title = QString::fromUtf8(title_data, title_len);
+ QString url = toQString(url_in);
+ QString title = toQString(title_in);
QByteArray data;
data.append(reinterpret_cast<const char *>(url.utf16()), url.size() * 2);
@@ -175,28 +188,37 @@ void ClipboardQt::WriteBookmark(const char *title_data, size_t title_len, const
getUncommittedData()->setData(QString::fromLatin1(ui::kMimeTypeMozillaURL), data);
}
-void ClipboardQt::WriteData(const ui::ClipboardFormatType &format, const char *data_data, size_t data_len)
+void ClipboardQt::WriteData(const ui::ClipboardFormatType &format, base::span<const uint8_t> data)
{
- getUncommittedData()->setData(QString::fromStdString(format.ToString()), QByteArray(data_data, data_len));
+ getUncommittedData()->setData(QString::fromStdString(format.GetName()), QByteArray((const char *)data.data(), data.size()));
}
-bool ClipboardQt::IsFormatAvailable(const ui::ClipboardFormatType &format, ui::ClipboardBuffer type) const
+bool ClipboardQt::IsFormatAvailable(const ui::ClipboardFormatType &format,
+ ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
- return mimeData && mimeData->hasFormat(QString::fromStdString(format.ToString()));
+
+ if (!mimeData)
+ return false;
+ if (format == ui::ClipboardFormatType::PngType())
+ return mimeData->hasImage();
+ return mimeData->hasFormat(QString::fromStdString(format.GetName()));
}
void ClipboardQt::Clear(ui::ClipboardBuffer type)
{
QGuiApplication::clipboard()->clear(type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard
- : QClipboard::Selection);
+ : QClipboard::Selection);
+ m_dataSrc[type].reset();
}
-void ClipboardQt::ReadAvailableTypes(ui::ClipboardBuffer type, std::vector<base::string16> *types,
- bool *contains_filenames) const
+void ClipboardQt::ReadAvailableTypes(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::vector<std::u16string> *types) const
{
- if (!types || !contains_filenames) {
+ if (!types) {
NOTREACHED();
return;
}
@@ -206,18 +228,19 @@ void ClipboardQt::ReadAvailableTypes(ui::ClipboardBuffer type, std::vector<base:
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
if (!mimeData)
return;
- if (mimeData->hasImage() && !mimeData->formats().contains(QStringLiteral("image/png")))
- types->push_back(toString16(QStringLiteral("image/png")));
- const QStringList formats = mimeData->formats();
- for (const QString &mimeType : formats)
- types->push_back(toString16(mimeType));
- *contains_filenames = false;
- const QByteArray customData = mimeData->data(QString::fromLatin1(ui::kMimeTypeWebCustomData));
- ui::ReadCustomDataTypes(customData.constData(), customData.size(), types);
+ for (const auto& mime_type : GetStandardFormats(type, data_dst))
+ types->push_back(mime_type);
+
+ if (mimeData->hasFormat(QString::fromLatin1(ui::kMimeTypeWebCustomData))) {
+ const QByteArray customData = mimeData->data(QString::fromLatin1(ui::kMimeTypeWebCustomData));
+ ui::ReadCustomDataTypes(customData.constData(), customData.size(), types);
+ }
}
-void ClipboardQt::ReadText(ui::ClipboardBuffer type, base::string16 *result) const
+void ClipboardQt::ReadText(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::u16string *result) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
@@ -225,7 +248,9 @@ void ClipboardQt::ReadText(ui::ClipboardBuffer type, base::string16 *result) con
*result = toString16(mimeData->text());
}
-void ClipboardQt::ReadAsciiText(ui::ClipboardBuffer type, std::string *result) const
+void ClipboardQt::ReadAsciiText(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::string *result) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
@@ -233,7 +258,9 @@ void ClipboardQt::ReadAsciiText(ui::ClipboardBuffer type, std::string *result) c
*result = mimeData->text().toStdString();
}
-void ClipboardQt::ReadHTML(ui::ClipboardBuffer type, base::string16 *markup, std::string *src_url,
+void ClipboardQt::ReadHTML(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::u16string *markup, std::string *src_url,
uint32_t *fragment_start, uint32_t *fragment_end) const
{
markup->clear();
@@ -246,11 +273,40 @@ void ClipboardQt::ReadHTML(ui::ClipboardBuffer type, base::string16 *markup, std
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
if (!mimeData)
return;
+
+#if !defined(Q_OS_WIN)
*markup = toString16(mimeData->html());
*fragment_end = static_cast<uint32_t>(markup->length());
+#else
+ const std::string cf_html = mimeData->html().toStdString();
+ size_t html_start = std::string::npos;
+ size_t start_index = std::string::npos;
+ size_t end_index = std::string::npos;
+ CFHtmlExtractMetadata(cf_html, src_url, &html_start, &start_index, &end_index);
+
+ // This might happen if the contents of the clipboard changed and CF_HTML is
+ // no longer available.
+ if (start_index == std::string::npos || end_index == std::string::npos
+ || html_start == std::string::npos)
+ return;
+
+ if (start_index < html_start || end_index < start_index)
+ return;
+
+ std::vector<size_t> offsets;
+ offsets.push_back(start_index - html_start);
+ offsets.push_back(end_index - html_start);
+ markup->assign(base::UTF8ToUTF16AndAdjustOffsets(cf_html.data() + html_start, &offsets));
+ // Ensure the Fragment points within the string; see https://crbug.com/607181.
+ size_t end = std::min(offsets[1], markup->length());
+ *fragment_start = base::checked_cast<uint32_t>(std::min(offsets[0], end));
+ *fragment_end = base::checked_cast<uint32_t>(end);
+#endif // !defined(Q_OS_WIN)
}
-void ClipboardQt::ReadRTF(ui::ClipboardBuffer type, std::string *result) const
+void ClipboardQt::ReadRTF(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::string *result) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
@@ -260,33 +316,26 @@ void ClipboardQt::ReadRTF(ui::ClipboardBuffer type, std::string *result) const
*result = std::string(byteArray.constData(), byteArray.length());
}
-SkBitmap ClipboardQt::ReadImage(ui::ClipboardBuffer type) const
+void ClipboardQt::ReadPng(ui::ClipboardBuffer type, const ui::DataTransferEndpoint *, ui::Clipboard::ReadPngCallback callback) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
if (!mimeData)
- return SkBitmap();
+ return std::move(callback).Run({});
QImage image = qvariant_cast<QImage>(mimeData->imageData());
- image = image.convertToFormat(QImage::Format_ARGB32);
- SkBitmap bitmap;
-
- bitmap.allocN32Pixels(image.width(), image.height(), true);
- const size_t bytesPerRowDst = bitmap.rowBytes();
- const size_t bytesPerLineSrc = static_cast<size_t>(image.bytesPerLine());
- const size_t dataBytes = std::min(bytesPerRowDst, bytesPerLineSrc);
- uchar *dst = static_cast<uchar *>(bitmap.getPixels());
- const uchar *src = image.constBits();
- for (int y = 0; y < image.height(); ++y) {
- memcpy(dst, src, dataBytes);
- dst += bytesPerRowDst;
- src += bytesPerLineSrc;
- }
-
- return bitmap;
+ QBuffer buffer;
+ QImageWriter writer(&buffer, "png");
+ writer.write(image);
+ std::vector<uint8_t> pngData;
+ pngData.resize(buffer.size());
+ memcpy(pngData.data(), buffer.data().data(), buffer.size());
+ return std::move(callback).Run(std::move(pngData));
}
-void ClipboardQt::ReadCustomData(ui::ClipboardBuffer clipboard_type, const base::string16 &type, base::string16 *result) const
+void ClipboardQt::ReadCustomData(ui::ClipboardBuffer clipboard_type, const std::u16string &type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::u16string *result) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
clipboard_type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
@@ -296,24 +345,122 @@ void ClipboardQt::ReadCustomData(ui::ClipboardBuffer clipboard_type, const base:
ui::ReadCustomDataForType(customData.constData(), customData.size(), type, result);
}
-void ClipboardQt::ReadBookmark(base::string16 *title, std::string *url) const
+void ClipboardQt::ReadBookmark(const ui::DataTransferEndpoint *data_dst, std::u16string *title, std::string *url) const
{
NOTIMPLEMENTED();
}
-void ClipboardQt::ReadData(const ui::ClipboardFormatType &format, std::string *result) const
+void ClipboardQt::ReadSvg(ui::ClipboardBuffer clipboard_type,
+ const ui::DataTransferEndpoint *,
+ std::u16string *result) const
+{
+ const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
+ clipboard_type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
+ if (!mimeData)
+ return;
+ const QByteArray svgData = mimeData->data(QString::fromLatin1(ui::kMimeTypeSvg));
+ if (!svgData.isEmpty())
+ *result = toString16(QString::fromUtf8(svgData));
+}
+
+void ClipboardQt::WriteSvg(base::StringPiece markup)
+{
+ getUncommittedData()->setData(QString::fromLatin1(ui::kMimeTypeSvg),
+ toQByteArray(markup));
+}
+
+void ClipboardQt::ReadData(const ui::ClipboardFormatType &format,
+ const ui::DataTransferEndpoint *data_dst,
+ std::string *result) const
{
const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData();
if (!mimeData)
return;
- const QByteArray byteArray = mimeData->data(QString::fromStdString(format.ToString()));
+ const QByteArray byteArray = mimeData->data(QString::fromStdString(format.GetName()));
*result = std::string(byteArray.constData(), byteArray.length());
}
-uint64_t ClipboardQt::GetSequenceNumber(ui::ClipboardBuffer type) const
+const ui::ClipboardSequenceNumberToken &ClipboardQt::GetSequenceNumber(ui::ClipboardBuffer type) const
{
- return clipboardChangeObserver()->getSequenceNumber(type == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard
- : QClipboard::Selection);
+ return type == ui::ClipboardBuffer::kCopyPaste
+ ? clipboardChangeObserver()->getPrimarySequenceNumber()
+ : clipboardChangeObserver()->getSelectionSequenceNumber();
+}
+
+const ui::DataTransferEndpoint *ClipboardQt::GetSource(ui::ClipboardBuffer buffer) const
+{
+ auto it = m_dataSrc.find(buffer);
+ return it == m_dataSrc.end() ? nullptr : it->second.get();
+}
+
+void ClipboardQt::ReadFilenames(ui::ClipboardBuffer buffer,
+ const ui::DataTransferEndpoint *data_dst,
+ std::vector<ui::FileInfo> *result) const
+{
+ const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
+ buffer == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
+ if (!mimeData)
+ return;
+ const QList<QUrl> urls = mimeData->urls();
+ for (const QUrl &url : urls) {
+ if (url.isLocalFile()) {
+ base::FilePath filepath = toFilePath(url.toLocalFile());
+ result->push_back(ui::FileInfo(filepath, base::FilePath()));
+ }
+ }
+}
+
+void ClipboardQt::WriteFilenames(std::vector<ui::FileInfo> filenames)
+{
+ QList<QUrl> urls;
+ for (const ui::FileInfo &file : filenames) {
+ QUrl url = QUrl::fromLocalFile(QString::fromStdString(file.path.AsUTF8Unsafe()));
+ urls.append(url);
+ }
+ getUncommittedData()->setUrls(urls);
+}
+
+void ClipboardQt::WriteUnsanitizedHTML(base::StringPiece markup, absl::optional<base::StringPiece> source_url)
+{
+ WriteHTML(std::move(markup), std::move(source_url));
+}
+
+#if defined(USE_OZONE)
+bool ClipboardQt::IsSelectionBufferAvailable() const
+{
+ return QGuiApplication::clipboard()->supportsSelection();
+}
+#endif
+
+// This is the same as ReadAvailableTypes minus dealing with custom-data
+std::vector<std::u16string> ClipboardQt::GetStandardFormats(ui::ClipboardBuffer buffer, const ui::DataTransferEndpoint *data_dst) const
+{
+ Q_UNUSED(data_dst);
+ const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData(
+ buffer == ui::ClipboardBuffer::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection);
+ if (!mimeData)
+ return {};
+
+ std::vector<std::u16string> types;
+ if (mimeData->hasImage())
+ types.push_back(base::UTF8ToUTF16(ui::kMimeTypePNG));
+ if (mimeData->hasHtml())
+ types.push_back(base::UTF8ToUTF16(ui::kMimeTypeHTML));
+ if (mimeData->hasText())
+ types.push_back(base::UTF8ToUTF16(ui::kMimeTypeText));
+ if (mimeData->hasUrls())
+ types.push_back(base::UTF8ToUTF16(ui::kMimeTypeURIList));
+ const QStringList formats = mimeData->formats();
+ for (const QString &mimeType : formats) {
+ auto mime_type = mimeType.toStdString();
+ // Only add white-listed formats here
+ if (mime_type == ui::ClipboardFormatType::SvgType().GetName() ||
+ mime_type == ui::ClipboardFormatType::RtfType().GetName()) {
+ types.push_back(base::UTF8ToUTF16(mime_type));
+ continue;
+ }
+ }
+ return types;
}
} // namespace QtWebEngineCore
diff --git a/src/core/clipboard_qt.h b/src/core/clipboard_qt.h
index 6d86e8f6c..22f24cfe5 100644
--- a/src/core/clipboard_qt.h
+++ b/src/core/clipboard_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CLIPBOARD_QT_H
#define CLIPBOARD_QT_H
@@ -44,36 +8,57 @@
namespace QtWebEngineCore {
-class ClipboardQt : public ui::Clipboard {
+class ClipboardQt : public ui::Clipboard
+{
public:
- uint64_t GetSequenceNumber(ui::ClipboardBuffer type) const override;
- bool IsFormatAvailable(const ui::ClipboardFormatType &format, ui::ClipboardBuffer type) const override;
+ const ui::ClipboardSequenceNumberToken &GetSequenceNumber(ui::ClipboardBuffer type) const override;
+ bool IsFormatAvailable(const ui::ClipboardFormatType &format,
+ ui::ClipboardBuffer buffer,
+ const ui::DataTransferEndpoint *data_dst) const override;
void Clear(ui::ClipboardBuffer type) override;
- void ReadAvailableTypes(ui::ClipboardBuffer type, std::vector<base::string16> *types,
- bool *contains_filenames) const override;
- void ReadText(ui::ClipboardBuffer type, base::string16 *result) const override;
- void ReadAsciiText(ui::ClipboardBuffer type, std::string *result) const override;
- void ReadHTML(ui::ClipboardBuffer type, base::string16 *markup, std::string *src_url, uint32_t *fragment_start,
+ void ReadAvailableTypes(ui::ClipboardBuffer type,
+ const ui::DataTransferEndpoint *data_dst,
+ std::vector<std::u16string> *types) const override;
+ void ReadText(ui::ClipboardBuffer type, const ui::DataTransferEndpoint *data_dst, std::u16string *result) const override;
+ void ReadAsciiText(ui::ClipboardBuffer type, const ui::DataTransferEndpoint *data_dst, std::string *result) const override;
+ void ReadHTML(ui::ClipboardBuffer type, const ui::DataTransferEndpoint *data_dst, std::u16string *markup, std::string *src_url, uint32_t *fragment_start,
uint32_t *fragment_end) const override;
- void ReadRTF(ui::ClipboardBuffer type, std::string *result) const override;
- SkBitmap ReadImage(ui::ClipboardBuffer type) const override;
- void ReadCustomData(ui::ClipboardBuffer clipboard_type, const base::string16 &type, base::string16 *result) const override;
- void ReadBookmark(base::string16 *title, std::string *url) const override;
- void ReadData(const ui::ClipboardFormatType &format, std::string *result) const override;
-
+ void ReadRTF(ui::ClipboardBuffer type, const ui::DataTransferEndpoint *data_dst, std::string *result) const override;
+ void ReadCustomData(ui::ClipboardBuffer clipboard_type, const std::u16string &type, const ui::DataTransferEndpoint *data_dst, std::u16string *result) const override;
+ void ReadBookmark(const ui::DataTransferEndpoint *data_dst, std::u16string *title, std::string *url) const override;
+ void ReadData(const ui::ClipboardFormatType &format, const ui::DataTransferEndpoint *data_dst, std::string *result) const override;
+#if defined(USE_OZONE)
+ bool IsSelectionBufferAvailable() const override;
+#endif
void OnPreShutdown() override {}
+ void ReadSvg(ui::ClipboardBuffer, const ui::DataTransferEndpoint *, std::u16string *) const override;
+ void ReadPng(ui::ClipboardBuffer, const ui::DataTransferEndpoint *, ui::Clipboard::ReadPngCallback) const override;
+
+ std::vector<std::u16string> GetStandardFormats(ui::ClipboardBuffer buffer, const ui::DataTransferEndpoint *data_dst) const override;
+
+ const ui::DataTransferEndpoint *GetSource(ui::ClipboardBuffer buffer) const override;
+ void ReadFilenames(ui::ClipboardBuffer buffer,
+ const ui::DataTransferEndpoint *data_dst,
+ std::vector<ui::FileInfo> *result) const override;
protected:
- void WritePortableRepresentations(ui::ClipboardBuffer type, const ObjectMap &objects) override;
- void WritePlatformRepresentations(ui::ClipboardBuffer type,
- std::vector<ui::Clipboard::PlatformRepresentation> platform_representations) override;
- void WriteText(const char *text_data, size_t text_len) override;
- void WriteHTML(const char *markup_data, size_t markup_len, const char *url_data, size_t url_len) override;
- void WriteRTF(const char *rtf_data, size_t data_len) override;
- void WriteBookmark(const char *title_data, size_t title_len, const char *url_data, size_t url_len) override;
+ void WritePortableAndPlatformRepresentations(ui::ClipboardBuffer buffer,
+ const ObjectMap &objects,
+ std::vector<Clipboard::PlatformRepresentation> platform_representations,
+ std::unique_ptr<ui::DataTransferEndpoint> data_src) override;
+
+ void WriteText(base::StringPiece text) override;
+ void WriteHTML(base::StringPiece markup, absl::optional<base::StringPiece> source_url) override;
+ void WriteRTF(base::StringPiece rtf) override;
+ void WriteBookmark(base::StringPiece title, base::StringPiece url) override;
void WriteWebSmartPaste() override;
void WriteBitmap(const SkBitmap &bitmap) override;
- void WriteData(const ui::ClipboardFormatType &format, const char *data_data, size_t data_len) override;
+ void WriteData(const ui::ClipboardFormatType &format, base::span<const uint8_t> data) override;
+ void WriteSvg(base::StringPiece markup) override;
+ void WriteFilenames(std::vector<ui::FileInfo> filenames) override;
+ void WriteUnsanitizedHTML(base::StringPiece markup, absl::optional<base::StringPiece> source_url) override;
+
+ base::flat_map<ui::ClipboardBuffer, std::unique_ptr<ui::DataTransferEndpoint>> m_dataSrc;
};
} // namespace QtWebEngineCore
diff --git a/src/core/clipboard_util_win.cpp b/src/core/clipboard_util_win.cpp
new file mode 100644
index 000000000..601e44180
--- /dev/null
+++ b/src/core/clipboard_util_win.cpp
@@ -0,0 +1,115 @@
+// Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <string>
+
+#include "base/strings/stringprintf.h"
+#include "base/strings/string_util.h"
+
+// These functions are copied from ui/base/clipboard/clipboard_util_win.cc
+
+namespace QtWebEngineCore {
+
+// Helper method for converting from text/html to MS CF_HTML.
+// Documentation for the CF_HTML format is available at
+// http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx
+// HtmlToCFHtml is based on similar method in
+// WebCore/platform/win/ClipboardUtilitiesWin.cpp.
+std::string HtmlToCFHtml(const std::string &html, const std::string &base_url)
+{
+ if (html.empty())
+ return std::string();
+
+#define MAX_DIGITS 10
+#define MAKE_NUMBER_FORMAT_1(digits) MAKE_NUMBER_FORMAT_2(digits)
+#define MAKE_NUMBER_FORMAT_2(digits) "%0" #digits "u"
+#define NUMBER_FORMAT MAKE_NUMBER_FORMAT_1(MAX_DIGITS)
+
+ static const char *header = "Version:0.9\r\n"
+ "StartHTML:" NUMBER_FORMAT "\r\n"
+ "EndHTML:" NUMBER_FORMAT "\r\n"
+ "StartFragment:" NUMBER_FORMAT "\r\n"
+ "EndFragment:" NUMBER_FORMAT "\r\n";
+ static const char *source_url_prefix = "SourceURL:";
+
+ static const char *start_markup = "<html>\r\n<body>\r\n<!--StartFragment-->";
+ static const char *end_markup = "<!--EndFragment-->\r\n</body>\r\n</html>";
+
+ // Calculate offsets
+ size_t start_html_offset = strlen(header) - strlen(NUMBER_FORMAT) * 4 + MAX_DIGITS * 4;
+ if (!base_url.empty()) {
+ start_html_offset += strlen(source_url_prefix) + base_url.length() + 2; // Add 2 for \r\n.
+ }
+ size_t start_fragment_offset = start_html_offset + strlen(start_markup);
+ size_t end_fragment_offset = start_fragment_offset + html.length();
+ size_t end_html_offset = end_fragment_offset + strlen(end_markup);
+
+ std::string result = base::StringPrintf(header, start_html_offset, end_html_offset,
+ start_fragment_offset, end_fragment_offset);
+ if (!base_url.empty()) {
+ result += source_url_prefix;
+ result += base_url;
+ result += "\r\n";
+ }
+ result += start_markup;
+ result += html;
+ result += end_markup;
+
+#undef MAX_DIGITS
+#undef MAKE_NUMBER_FORMAT_1
+#undef MAKE_NUMBER_FORMAT_2
+#undef NUMBER_FORMAT
+
+ return result;
+}
+
+void CFHtmlExtractMetadata(const std::string &cf_html, std::string *base_url, size_t *html_start,
+ size_t *fragment_start, size_t *fragment_end)
+{
+ // Obtain base_url if present.
+ if (base_url) {
+ static constexpr char kSrcUrlStr[] = "SourceURL:";
+ size_t line_start = cf_html.find(kSrcUrlStr);
+ if (line_start != std::string::npos) {
+ size_t src_end = cf_html.find("\n", line_start);
+ size_t src_start = line_start + strlen(kSrcUrlStr);
+ if (src_end != std::string::npos && src_start != std::string::npos) {
+ *base_url = cf_html.substr(src_start, src_end - src_start);
+ base::TrimWhitespaceASCII(*base_url, base::TRIM_ALL, base_url);
+ }
+ }
+ }
+
+ // Find the markup between "<!--StartFragment-->" and "<!--EndFragment-->".
+ // If the comments cannot be found, like copying from OpenOffice Writer,
+ // we simply fall back to using StartFragment/EndFragment bytecount values
+ // to determine the fragment indexes.
+ std::string cf_html_lower = base::ToLowerASCII(cf_html);
+ size_t markup_start = cf_html_lower.find("<html", 0);
+ if (html_start) {
+ *html_start = markup_start;
+ }
+ size_t tag_start = cf_html.find("<!--StartFragment", markup_start);
+ if (tag_start == std::string::npos) {
+ static constexpr char kStartFragmentStr[] = "StartFragment:";
+ size_t start_fragment_start = cf_html.find(kStartFragmentStr);
+ if (start_fragment_start != std::string::npos) {
+ *fragment_start = static_cast<size_t>(
+ atoi(cf_html.c_str() + start_fragment_start + strlen(kStartFragmentStr)));
+ }
+
+ static constexpr char kEndFragmentStr[] = "EndFragment:";
+ size_t end_fragment_start = cf_html.find(kEndFragmentStr);
+ if (end_fragment_start != std::string::npos) {
+ *fragment_end = static_cast<size_t>(
+ atoi(cf_html.c_str() + end_fragment_start + strlen(kEndFragmentStr)));
+ }
+ } else {
+ *fragment_start = cf_html.find('>', tag_start) + 1;
+ size_t tag_end = cf_html.rfind("<!--EndFragment", std::string::npos);
+ *fragment_end = cf_html.rfind('<', tag_end);
+ }
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/color_chooser_controller.cpp b/src/core/color_chooser_controller.cpp
index 361ff93ba..fcaef2eba 100644
--- a/src/core/color_chooser_controller.cpp
+++ b/src/core/color_chooser_controller.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content/browser/web_contents/web_contents_impl.h"
@@ -101,5 +65,4 @@ void ColorChooserController::reject()
didEndColorDialog();
}
-
-} // namespace
+} // namespace QtWebEngineCore
diff --git a/src/core/color_chooser_controller.h b/src/core/color_chooser_controller.h
index 66222bb77..a97ebfbff 100644
--- a/src/core/color_chooser_controller.h
+++ b/src/core/color_chooser_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,8 +15,7 @@
#ifndef COLOR_CHOOSER_CONTROLLER_H
#define COLOR_CHOOSER_CONTROLLER_H
-#include "qtwebenginecoreglobal_p.h"
-
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QObject>
QT_FORWARD_DECLARE_CLASS(QColor)
@@ -62,7 +25,7 @@ namespace QtWebEngineCore {
class ColorChooserControllerPrivate;
-class Q_WEBENGINECORE_PRIVATE_EXPORT ColorChooserController : public QObject {
+class Q_WEBENGINECORE_EXPORT ColorChooserController : public QObject {
Q_OBJECT
public:
~ColorChooserController();
@@ -84,6 +47,6 @@ private:
friend class ColorChooserQt;
};
-} // namespace
+} // namespace QtWebEngineCore
#endif // COLOR_CHOOSER_CONTROLLER_H
diff --git a/src/core/color_chooser_controller_p.h b/src/core/color_chooser_controller_p.h
index a03167f21..45eeb9471 100644
--- a/src/core/color_chooser_controller_p.h
+++ b/src/core/color_chooser_controller_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef COLOR_CHOOSER_CONTROLLER_P_H
#define COLOR_CHOOSER_CONTROLLER_P_H
@@ -54,7 +18,7 @@
#include <QColor>
namespace content {
- class WebContents;
+class WebContents;
}
namespace QtWebEngineCore {
@@ -67,7 +31,7 @@ public:
QColor m_initialColor;
};
-} // namespace
+} // namespace QtWebEngineCore
#endif // COLOR_CHOOSER_CONTROLLER_P_H
diff --git a/src/core/color_chooser_qt.cpp b/src/core/color_chooser_qt.cpp
index 749d04148..de2e833a0 100644
--- a/src/core/color_chooser_qt.cpp
+++ b/src/core/color_chooser_qt.cpp
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "color_chooser_qt.h"
#include "color_chooser_controller.h"
#include "color_chooser_controller_p.h"
-namespace content {
- class WebContents;
-}
+#include <QColor>
namespace QtWebEngineCore {
@@ -57,4 +19,4 @@ QSharedPointer<ColorChooserController> ColorChooserQt::controller()
return m_controller;
}
-} // namespace
+} // namespace QtWebEngineCore
diff --git a/src/core/color_chooser_qt.h b/src/core/color_chooser_qt.h
index 200db3266..dde9a51ce 100644
--- a/src/core/color_chooser_qt.h
+++ b/src/core/color_chooser_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef COLOR_CHOOSER_QT_H
#define COLOR_CHOOSER_QT_H
@@ -43,11 +7,12 @@
#include "content/public/browser/color_chooser.h"
#include "type_conversion.h"
-#include <QColor>
#include <QSharedPointer>
+QT_FORWARD_DECLARE_CLASS(QColor)
+
namespace content {
- class WebContents;
+class WebContents;
}
namespace QtWebEngineCore {
@@ -68,7 +33,6 @@ private:
QSharedPointer<ColorChooserController> m_controller;
};
-
-} // namespace
+} // namespace QtWebEngineCore
#endif // COLOR_CHOOSER_QT_H
diff --git a/src/core/common/extensions/api/qtwebengine_extensions_features.gni b/src/core/common/extensions/api/qtwebengine_extensions_features.gni
deleted file mode 100644
index ed7e713c6..000000000
--- a/src/core/common/extensions/api/qtwebengine_extensions_features.gni
+++ /dev/null
@@ -1,25 +0,0 @@
-import("//tools/json_schema_compiler/json_features.gni")
-
-json_features("qt_api_features") {
- feature_type = "APIFeature"
- method_name = "AddQtAPIFeatures"
- sources = [
- "//extensions/common/api/_webengine_api_features.json"
- ]
-}
-
-json_features("qt_permission_features") {
- feature_type = "PermissionFeature"
- method_name = "AddQtPermissionFeatures"
- sources = [
- "//extensions/common/api/_permission_features.json"
- ]
-}
-
-group("qtwebengine_extensions_features") {
- public_deps = [
- ":qt_api_features",
- ":qt_permission_features",
- "//extensions/common/api:extensions_features",
- ]
-}
diff --git a/src/core/common/extensions/extensions_api_provider_qt.cpp b/src/core/common/extensions/extensions_api_provider_qt.cpp
index 22154a9d1..1c8e89747 100644
--- a/src/core/common/extensions/extensions_api_provider_qt.cpp
+++ b/src/core/common/extensions/extensions_api_provider_qt.cpp
@@ -1,44 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "extensions_api_provider_qt.h"
+#include "chrome/common/extensions/permissions/chrome_api_permissions.h"
+#include "chrome/common/extensions/api/generated_schemas.h"
#include "chrome/grit/common_resources.h"
#include "extensions/common/api/api_features.h"
@@ -51,6 +17,7 @@
#include "extensions/common/features/json_feature_provider_source.h"
#include "extensions/common/permissions/permissions_info.h"
#include "extensions/grit/extensions_resources.h"
+#include "qtwebengine/common/extensions/api/generated_schemas.h"
#include "qt_api_features.h"
//#include "qt_behavior_features.h"
@@ -85,16 +52,30 @@ void ExtensionsAPIProviderQt::AddPermissionFeatures(FeatureProvider *provider)
bool ExtensionsAPIProviderQt::IsAPISchemaGenerated(const std::string &name)
{
- return api::GeneratedSchemas::IsGenerated(name);
+ return api::GeneratedSchemas::IsGenerated(name) ||
+ api::ChromeGeneratedSchemas::IsGenerated(name) ||
+ api::QtWebEngineGeneratedSchemas::IsGenerated(name);
}
base::StringPiece ExtensionsAPIProviderQt::GetAPISchema(const std::string &name)
{
- return api::GeneratedSchemas::Get(name);
+ if (!api::GeneratedSchemas::Get(name).empty())
+ return api::GeneratedSchemas::Get(name);
+
+ if (!api::ChromeGeneratedSchemas::Get(name).empty())
+ return api::ChromeGeneratedSchemas::Get(name);
+
+ if (!api::QtWebEngineGeneratedSchemas::Get(name).empty())
+ return api::QtWebEngineGeneratedSchemas::Get(name);
+
+ return "";
}
void ExtensionsAPIProviderQt::RegisterPermissions(PermissionsInfo* permissions_info)
{
+ permissions_info->RegisterPermissions(
+ chrome_api_permissions::GetPermissionInfos(),
+ chrome_api_permissions::GetPermissionAliases());
}
}
diff --git a/src/core/common/extensions/extensions_api_provider_qt.h b/src/core/common/extensions/extensions_api_provider_qt.h
index 7d8c5f98b..34e8bdd9f 100644
--- a/src/core/common/extensions/extensions_api_provider_qt.h
+++ b/src/core/common/extensions/extensions_api_provider_qt.h
@@ -1,48 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef EXTENSIONS_API_PROVIDER_QT_H
#define EXTENSIONS_API_PROVIDER_QT_H
#include "extensions/common/extensions_api_provider.h"
-#include "base/macros.h"
-
namespace extensions {
class ExtensionsAPIProviderQt : public ExtensionsAPIProvider
@@ -64,8 +26,6 @@ public:
// Registers permissions for any associated API features.
void RegisterPermissions(PermissionsInfo* permissions_info) override;
-
-DISALLOW_COPY_AND_ASSIGN(ExtensionsAPIProviderQt);
};
}
diff --git a/src/core/common/extensions/extensions_client_qt.cpp b/src/core/common/extensions/extensions_client_qt.cpp
index dd1de1483..9240e6528 100644
--- a/src/core/common/extensions/extensions_client_qt.cpp
+++ b/src/core/common/extensions/extensions_client_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -108,18 +72,18 @@ void ExtensionsClientQt::FilterHostPermissions(const URLPatternSet &hosts,
{
}
-// Replaces the scripting whitelist with |whitelist|. Used in the renderer{}
+// Replaces the scripting allowlist with |allowlist|. Used in the renderer{}
// only used for testing in the browser process.
-void ExtensionsClientQt::SetScriptingWhitelist(const ExtensionsClient::ScriptingWhitelist &whitelist)
+void ExtensionsClientQt::SetScriptingAllowlist(const ExtensionsClient::ScriptingAllowlist &allowlist)
{
- scripting_whitelist_ = whitelist;
+ scripting_allowlist_ = allowlist;
}
-// Return the whitelist of extensions that can run content scripts on
+// Return the allowlist of extensions that can run content scripts on
// any origin.
-const ExtensionsClient::ScriptingWhitelist &ExtensionsClientQt::GetScriptingWhitelist() const
+const ExtensionsClient::ScriptingAllowlist &ExtensionsClientQt::GetScriptingAllowlist() const
{
- return scripting_whitelist_;
+ return scripting_allowlist_;
}
// Get the set of chrome:// hosts that |extension| can run content scripts on.
@@ -153,11 +117,17 @@ const GURL &ExtensionsClientQt::GetWebstoreUpdateURL() const
// Returns a flag indicating whether or not a given URL is a valid
// extension blacklist URL.
-bool ExtensionsClientQt::IsBlacklistUpdateURL(const GURL &url) const
+bool ExtensionsClientQt::IsBlocklistUpdateURL(const GURL &url) const
{
return true;
}
+const GURL &ExtensionsClientQt::GetNewWebstoreBaseURL() const
+{
+ static GURL dummy;
+ return dummy;
+}
+
// Returns the set of file paths corresponding to any images within an
// extension's contents that may be displayed directly within the browser UI
// or WebUI, such as icons or theme images. This set of paths is used by the
diff --git a/src/core/common/extensions/extensions_client_qt.h b/src/core/common/extensions/extensions_client_qt.h
index e689f76b7..b2d128bf9 100644
--- a/src/core/common/extensions/extensions_client_qt.h
+++ b/src/core/common/extensions/extensions_client_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -46,9 +10,7 @@
#include "extensions/common/extensions_client.h"
-#include "base/compiler_specific.h"
#include "base/lazy_instance.h"
-#include "base/macros.h"
#include "chrome/common/extensions/permissions/chrome_permission_message_provider.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/features/json_feature_provider_source.h"
@@ -87,13 +49,13 @@ public:
URLPatternSet *new_hosts,
PermissionIDSet *permissions) const override;
- // Replaces the scripting whitelist with |whitelist|. Used in the renderer;
+ // Replaces the scripting allowlist with |allowlist|. Used in the renderer;
// only used for testing in the browser process.
- void SetScriptingWhitelist(const ScriptingWhitelist &whitelist) override;
+ void SetScriptingAllowlist(const ScriptingAllowlist &allowlist) override;
- // Return the whitelist of extensions that can run content scripts on
+ // Return the allowlist of extensions that can run content scripts on
// any origin.
- const ScriptingWhitelist &GetScriptingWhitelist() const override;
+ const ScriptingAllowlist &GetScriptingAllowlist() const override;
// Get the set of chrome:// hosts that |extension| can run content scripts on.
URLPatternSet GetPermittedChromeSchemeHosts(const Extension *extension,
@@ -110,7 +72,9 @@ public:
// Returns a flag indicating whether or not a given URL is a valid
// extension blacklist URL.
- bool IsBlacklistUpdateURL(const GURL &url) const override;
+ bool IsBlocklistUpdateURL(const GURL &url) const override;
+
+ const GURL &GetNewWebstoreBaseURL() const override;
// Returns the set of file paths corresponding to any images within an
// extension's contents that may be displayed directly within the browser UI
@@ -127,11 +91,10 @@ public:
static ExtensionsClientQt *GetInstance();
private:
- ScriptingWhitelist scripting_whitelist_;
+ ScriptingAllowlist scripting_allowlist_;
const ChromePermissionMessageProvider permission_message_provider_;
mutable GURL update_url_;
mutable GURL base_url_;
- DISALLOW_COPY_AND_ASSIGN(ExtensionsClientQt);
};
} // namespace extensions
diff --git a/src/core/common/qt_ipc_logging.cpp b/src/core/common/qt_ipc_logging.cpp
deleted file mode 100644
index 83eb5a5ad..000000000
--- a/src/core/common/qt_ipc_logging.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "ipc/ipc_buildflags.h" // Generated buildflag header
-
-#if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
-#define IPC_MESSAGE_MACROS_LOG_ENABLED
-#include "content/public/common/content_ipc_logging.h"
-#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
- content::RegisterIPCLogger(msg_id, logger)
-#include "common/qt_messages.h"
-#endif
diff --git a/src/core/common/qt_messages.cpp b/src/core/common/qt_messages.cpp
index 2f087d21f..bc3a1560d 100644
--- a/src/core/common/qt_messages.cpp
+++ b/src/core/common/qt_messages.cpp
@@ -1,6 +1,5 @@
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
// Get basic type definitions.
#define IPC_MESSAGE_IMPL
diff --git a/src/core/common/qt_messages.h b/src/core/common/qt_messages.h
index 43f07c9a6..17adcbb0d 100644
--- a/src/core/common/qt_messages.h
+++ b/src/core/common/qt_messages.h
@@ -1,116 +1,46 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
// Multiply-included file, no traditional include guard.
-#include "base/optional.h"
#include "content/public/common/common_param_traits.h"
-#include "content/public/common/webplugininfo.h"
#include "ipc/ipc_message_macros.h"
-#include "ppapi/buildflags/buildflags.h"
-#include "user_script_data.h"
-
-IPC_STRUCT_TRAITS_BEGIN(UserScriptData)
- IPC_STRUCT_TRAITS_MEMBER(source)
- IPC_STRUCT_TRAITS_MEMBER(url)
- IPC_STRUCT_TRAITS_MEMBER(injectionPoint)
- IPC_STRUCT_TRAITS_MEMBER(injectForSubframes)
- IPC_STRUCT_TRAITS_MEMBER(worldId)
- IPC_STRUCT_TRAITS_MEMBER(scriptId)
- IPC_STRUCT_TRAITS_MEMBER(globs)
- IPC_STRUCT_TRAITS_MEMBER(excludeGlobs)
- IPC_STRUCT_TRAITS_MEMBER(urlPatterns)
-IPC_STRUCT_TRAITS_END()
-
+#include "ipc/ipc_message_start.h"
+#include "url/gurl.h"
#define IPC_MESSAGE_START QtMsgStart
//-----------------------------------------------------------------------------
-// RenderView messages
// These are messages sent from the browser to the renderer process.
-IPC_MESSAGE_ROUTED1(RenderViewObserverQt_FetchDocumentMarkup,
- uint64_t /* requestId */)
-
-IPC_MESSAGE_ROUTED1(RenderViewObserverQt_FetchDocumentInnerText,
- uint64_t /* requestId */)
-
-IPC_MESSAGE_ROUTED1(RenderViewObserverQt_SetBackgroundColor,
- uint32_t /* color */)
-
-// User scripts messages
-IPC_MESSAGE_ROUTED1(RenderFrameObserverHelper_AddScript,
- UserScriptData /* script */)
-IPC_MESSAGE_ROUTED1(RenderFrameObserverHelper_RemoveScript,
- UserScriptData /* script */)
-IPC_MESSAGE_ROUTED0(RenderFrameObserverHelper_ClearScripts)
-
-IPC_MESSAGE_CONTROL1(UserResourceController_AddScript, UserScriptData /* scriptContents */)
-IPC_MESSAGE_CONTROL1(UserResourceController_RemoveScript, UserScriptData /* scriptContents */)
-IPC_MESSAGE_CONTROL0(UserResourceController_ClearScripts)
-
-// Tells the renderer whether or not a file system access has been allowed.
-IPC_MESSAGE_ROUTED2(QtWebEngineMsg_RequestFileSystemAccessAsyncResponse,
+// Tells the renderer whether or not a storage access has been allowed.
+IPC_MESSAGE_ROUTED2(QtWebEngineMsg_RequestStorageAccessAsyncResponse,
int /* request_id */,
bool /* allowed */)
-
-//-----------------------------------------------------------------------------
-// WebContents messages
-// These are messages sent from the renderer back to the browser process.
-
-IPC_MESSAGE_ROUTED2(RenderViewObserverHostQt_DidFetchDocumentMarkup,
- uint64_t /* requestId */,
- base::string16 /* markup */)
-
-IPC_MESSAGE_ROUTED2(RenderViewObserverHostQt_DidFetchDocumentInnerText,
- uint64_t /* requestId */,
- base::string16 /* innerText */)
-
-IPC_MESSAGE_ROUTED0(RenderViewObserverHostQt_DidFirstVisuallyNonEmptyLayout)
-
//-----------------------------------------------------------------------------
-// Misc messages
// These are messages sent from the renderer to the browser process.
-// Sent by the renderer process to check whether access to web databases is
-// granted by content settings.
-IPC_SYNC_MESSAGE_CONTROL3_1(QtWebEngineHostMsg_AllowDatabase,
+IPC_SYNC_MESSAGE_CONTROL4_1(QtWebEngineHostMsg_AllowStorageAccess,
int /* render_frame_id */,
GURL /* origin_url */,
GURL /* top origin url */,
+ int /* storage_type */,
bool /* allowed */)
-// Sent by the renderer process to check whether access to DOM Storage is
-// granted by content settings.
-IPC_SYNC_MESSAGE_CONTROL4_1(QtWebEngineHostMsg_AllowDOMStorage,
+IPC_SYNC_MESSAGE_CONTROL4_1(QtWebEngineHostMsg_RequestStorageAccessSync,
int /* render_frame_id */,
GURL /* origin_url */,
GURL /* top origin url */,
- bool /* if true local storage, otherwise session */,
+ int /* storage_type */,
bool /* allowed */)
-// Sent by the renderer process to check whether access to FileSystem is
+// Sent by the renderer process to check whether access to storage is
// granted by content settings.
-IPC_SYNC_MESSAGE_CONTROL3_1(QtWebEngineHostMsg_RequestFileSystemAccessSync,
- int /* render_frame_id */,
- GURL /* origin_url */,
- GURL /* top origin url */,
- bool /* allowed */)
-
-// Sent by the renderer process to check whether access to FileSystem is
-// granted by content settings.
-IPC_MESSAGE_CONTROL4(QtWebEngineHostMsg_RequestFileSystemAccessAsync,
+IPC_MESSAGE_CONTROL5(QtWebEngineHostMsg_RequestStorageAccessAsync,
int /* render_frame_id */,
int /* request_id */,
GURL /* origin_url */,
- GURL /* top origin url */)
+ GURL /* top origin url */,
+ int /* storage_type */)
-// Sent by the renderer process to check whether access to Indexed DB is
-// granted by content settings.
-IPC_SYNC_MESSAGE_CONTROL3_1(QtWebEngineHostMsg_AllowIndexedDB,
- int /* render_frame_id */,
- GURL /* origin_url */,
- GURL /* top origin url */,
- bool /* allowed */)
diff --git a/src/core/common/user_script_data.cpp b/src/core/common/user_script_data.cpp
deleted file mode 100644
index 6f4b8cb05..000000000
--- a/src/core/common/user_script_data.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "user_script_data.h"
-#include "base/pickle.h"
-
-UserScriptData::UserScriptData() : injectionPoint(AfterLoad)
- , injectForSubframes(false)
- , worldId(1)
-{
- static uint64_t idCount = 0;
- scriptId = idCount++;
-}
diff --git a/src/core/common/user_script_data.h b/src/core/common/user_script_data.h
deleted file mode 100644
index 8d98890e3..000000000
--- a/src/core/common/user_script_data.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef USER_SCRIPT_DATA_H
-#define USER_SCRIPT_DATA_H
-
-#include <QtCore/QHash>
-#include <string>
-#include "ipc/ipc_message_utils.h"
-#include "url/gurl.h"
-
-struct UserScriptData {
- enum InjectionPoint {
- AfterLoad,
- DocumentLoadFinished,
- DocumentElementCreation
- };
-
- UserScriptData();
-
- std::string source;
- GURL url;
- /*InjectionPoint*/uint8_t injectionPoint;
- bool injectForSubframes;
- uint worldId;
- uint64_t scriptId;
- std::vector<std::string> globs;
- std::vector<std::string> excludeGlobs;
- std::vector<std::string> urlPatterns;
-};
-
-QT_BEGIN_NAMESPACE
-
-Q_DECLARE_TYPEINFO(UserScriptData, Q_MOVABLE_TYPE);
-
-QT_END_NAMESPACE
-
-#endif // USER_SCRIPT_DATA_H
diff --git a/src/core/compositor/compositor.cpp b/src/core/compositor/compositor.cpp
index c45c02844..4c0bd4c0d 100644
--- a/src/core/compositor/compositor.cpp
+++ b/src/core/compositor/compositor.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "compositor.h"
@@ -43,8 +7,8 @@
#include "components/viz/common/surfaces/frame_sink_id.h"
#include <QHash>
-#include <QImage>
#include <QMutex>
+#include <QQuickWindow>
namespace QtWebEngineCore {
@@ -129,10 +93,8 @@ void Compositor::Observer::unbind()
Compositor::Handle<Compositor> Compositor::Observer::compositor()
{
- if (!m_binding)
- return nullptr;
g_bindings.lock();
- if (m_binding->compositor)
+ if (m_binding && m_binding->compositor)
return m_binding->compositor; // delay unlock
g_bindings.unlock();
return nullptr;
@@ -163,50 +125,35 @@ void Compositor::unbind()
Compositor::Handle<Compositor::Observer> Compositor::observer()
{
- if (!m_binding)
- return nullptr;
g_bindings.lock();
- if (m_binding->observer)
+ if (m_binding && m_binding->observer)
return m_binding->observer; // delay unlock
g_bindings.unlock();
return nullptr;
}
-float Compositor::devicePixelRatio()
-{
- Q_UNREACHABLE();
- return 1;
-}
-
-QImage Compositor::image()
-{
- Q_UNREACHABLE();
- return {};
-}
-
void Compositor::waitForTexture()
{
- Q_UNREACHABLE();
}
-int Compositor::textureId()
+void Compositor::releaseTexture()
{
- Q_UNREACHABLE();
- return 0;
}
-QSize Compositor::textureSize()
+QSGTexture *Compositor::texture(QQuickWindow *, uint32_t textureOptions)
{
Q_UNREACHABLE();
- return {};
+ return nullptr;
}
-bool Compositor::hasAlphaChannel()
+bool Compositor::textureIsFlipped()
{
Q_UNREACHABLE();
return false;
}
+void Compositor::releaseResources() { }
+
// static
void Compositor::unlockBindings()
{
diff --git a/src/core/compositor/compositor.h b/src/core/compositor/compositor.h
index d10cf2ef6..501559060 100644
--- a/src/core/compositor/compositor.h
+++ b/src/core/compositor/compositor.h
@@ -1,50 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef COMPOSITOR_H
#define COMPOSITOR_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
QT_BEGIN_NAMESPACE
-class QImage;
+class QQuickWindow;
class QSize;
+class QSGTexture;
QT_END_NAMESPACE
namespace viz {
@@ -55,10 +20,9 @@ namespace QtWebEngineCore {
// Produces composited frames for display.
//
-// Used by quick/widgets libraries for accessing the frame and
-// controlling frame swapping. Must be cast to a subclass to access
-// the frame as QImage or OpenGL texture, etc.
-class Q_WEBENGINECORE_PRIVATE_EXPORT Compositor
+// Used by quick/widgets libraries for accessing the frames and
+// controlling frame swapping.
+class Q_WEBENGINECORE_EXPORT Compositor
{
struct Binding;
@@ -66,7 +30,8 @@ public:
// Identifies the implementation type.
enum class Type {
Software,
- OpenGL,
+ OpenGL, // TODO: Legacy, remove it with DisplaySkiaOutputDevice!
+ Native
};
// Identifies a compositor.
@@ -110,7 +75,7 @@ public:
// Observes the compositor corresponding to the given id.
//
// Only one observer can exist per compositor.
- class Q_WEBENGINECORE_PRIVATE_EXPORT Observer
+ class Q_WEBENGINECORE_EXPORT Observer
{
public:
// Binding to compositor
@@ -125,7 +90,7 @@ public:
protected:
Observer() = default;
- ~Observer() = default;
+ ~Observer() { if (m_binding) unbind(); }
private:
Binding *m_binding = nullptr;
@@ -147,27 +112,32 @@ public:
// Ratio of pixels to DIPs.
//
// Don't use the devicePixelRatio of QImage, it's always 1.
- virtual float devicePixelRatio();
+ virtual float devicePixelRatio() = 0;
- // (Software) QImage of the frame.
- //
- // This is a big image so we should try not to make copies of it.
- // In particular, the client should drop its QImage reference
- // before calling swapFrame(), otherwise each swap will cause a
- // detach.
- virtual QImage image();
+ // Size of frame in pixels.
+ virtual QSize size() = 0;
+
+ // Whether frame needs an alpha channel.
+ virtual bool requiresAlphaChannel() = 0;
- // (OpenGL) Wait on texture fence in Qt's current OpenGL context.
+ // Wait on texture to be ready aka. sync.
virtual void waitForTexture();
- // (OpenGL) Properties of the current frame.
- virtual int textureId();
- virtual QSize textureSize();
- virtual bool hasAlphaChannel();
+ // Release any held texture resources
+ virtual void releaseTexture();
+
+ // QSGTexture of the frame.
+ virtual QSGTexture *texture(QQuickWindow *win, uint32_t textureOptions);
+
+ // Is the texture produced upside down?
+ virtual bool textureIsFlipped();
+
+ // Release resources created in texture()
+ virtual void releaseResources();
protected:
Compositor(Type type) : m_type(type) { }
- ~Compositor() = default;
+ virtual ~Compositor() { if (m_binding) unbind(); }
private:
template<typename T>
diff --git a/src/core/compositor/compositor_resource_fence.cpp b/src/core/compositor/compositor_resource_fence.cpp
index 4179395d6..bd1c95cd9 100644
--- a/src/core/compositor/compositor_resource_fence.cpp
+++ b/src/core/compositor/compositor_resource_fence.cpp
@@ -1,44 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "compositor_resource_fence.h"
-
+#include "ozone/gl_surface_qt.h"
#include "ui/gl/gl_context.h"
#include <QtGui/qopenglcontext.h>
@@ -47,6 +11,12 @@
#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
#endif
+
+#if QT_CONFIG(egl)
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#endif
+
namespace QtWebEngineCore {
void CompositorResourceFence::wait()
@@ -55,7 +25,8 @@ void CompositorResourceFence::wait()
return;
QOpenGLContext *context = QOpenGLContext::currentContext();
- Q_ASSERT(context);
+ if (!context)
+ return;
// Chromium uses its own GL bindings and stores in in thread local storage.
// For that reason, let chromium_gpu_helper.cpp contain the producing code that will run in the Chromium
diff --git a/src/core/compositor/compositor_resource_fence.h b/src/core/compositor/compositor_resource_fence.h
index 574416b8b..ab92ca5c7 100644
--- a/src/core/compositor/compositor_resource_fence.h
+++ b/src/core/compositor/compositor_resource_fence.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef COMPOSITOR_RESOURCE_FENCE_H
#define COMPOSITOR_RESOURCE_FENCE_H
diff --git a/src/core/compositor/content_gpu_client_qt.cpp b/src/core/compositor/content_gpu_client_qt.cpp
index f934979a0..6ef8048f2 100644
--- a/src/core/compositor/content_gpu_client_qt.cpp
+++ b/src/core/compositor/content_gpu_client_qt.cpp
@@ -1,45 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content_gpu_client_qt.h"
-
-#include "web_engine_context.h"
+#include "ozone/gl_share_context_qt.h"
namespace QtWebEngineCore {
@@ -51,9 +14,11 @@ ContentGpuClientQt::~ContentGpuClientQt()
{
}
-gpu::SyncPointManager *ContentGpuClientQt::GetSyncPointManager()
+gl::GLShareGroup *ContentGpuClientQt::GetInProcessGpuShareGroup()
{
- return WebEngineContext::syncPointManager();
+ if (!m_shareGroupQt.get())
+ m_shareGroupQt = new ShareGroupQt;
+ return m_shareGroupQt.get();
}
} // namespace
diff --git a/src/core/compositor/content_gpu_client_qt.h b/src/core/compositor/content_gpu_client_qt.h
index d7ad43881..33314e0bb 100644
--- a/src/core/compositor/content_gpu_client_qt.h
+++ b/src/core/compositor/content_gpu_client_qt.h
@@ -1,47 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_GPU_CLIENT_QT_H
#define CONTENT_GPU_CLIENT_QT_H
#include "content/public/gpu/content_gpu_client.h"
+namespace gl {
+class GLShareGroup;
+}
+
namespace QtWebEngineCore {
+class ShareGroupQt;
class ContentGpuClientQt : public content::ContentGpuClient {
public:
@@ -49,7 +18,10 @@ public:
~ContentGpuClientQt() override;
// content::ContentGpuClient implementation.
- gpu::SyncPointManager *GetSyncPointManager() override;
+ gl::GLShareGroup *GetInProcessGpuShareGroup() override;
+
+private:
+ scoped_refptr<ShareGroupQt> m_shareGroupQt;
};
}
diff --git a/src/core/compositor/display_gl_output_surface.cpp b/src/core/compositor/display_gl_output_surface.cpp
deleted file mode 100644
index f736bba79..000000000
--- a/src/core/compositor/display_gl_output_surface.cpp
+++ /dev/null
@@ -1,341 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "display_gl_output_surface.h"
-
-#include "type_conversion.h"
-
-#include "base/threading/thread_task_runner_handle.h"
-#include "components/viz/service/display/display.h"
-#include "components/viz/service/display/output_surface_frame.h"
-#include "gpu/command_buffer/client/gles2_implementation.h"
-#include "gpu/command_buffer/client/gles2_interface.h"
-#include "gpu/command_buffer/service/mailbox_manager.h"
-#include "gpu/command_buffer/service/texture_base.h"
-#include "gpu/ipc/in_process_command_buffer.h"
-#include "ui/gl/color_space_utils.h"
-
-namespace QtWebEngineCore {
-
-DisplayGLOutputSurface::DisplayGLOutputSurface(
- scoped_refptr<viz::VizProcessContextProvider> contextProvider)
- : OutputSurface(contextProvider)
- , Compositor(Compositor::Type::OpenGL)
- , m_commandBuffer(contextProvider->command_buffer())
- , m_gl(contextProvider->ContextGL())
- , m_vizContextProvider(contextProvider)
-{
- capabilities_.uses_default_gl_framebuffer = false;
- m_gl->GenFramebuffers(1, &m_fboId);
-}
-
-DisplayGLOutputSurface::~DisplayGLOutputSurface()
-{
- unbind();
- m_vizContextProvider->SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback());
- m_gl->DeleteFramebuffers(1, &m_fboId);
-}
-
-// Called from viz::Display::Initialize.
-void DisplayGLOutputSurface::BindToClient(viz::OutputSurfaceClient *client)
-{
- m_display = static_cast<viz::Display *>(client);
- bind(m_display->frame_sink_id());
-}
-
-// Triggered by ui::Compositor::SetVisible(true).
-void DisplayGLOutputSurface::EnsureBackbuffer()
-{
-}
-
-// Triggered by ui::Compositor::SetVisible(false). Framebuffer must be cleared.
-void DisplayGLOutputSurface::DiscardBackbuffer()
-{
- NOTIMPLEMENTED();
- // m_gl->DiscardBackbufferCHROMIUM();
-}
-
-// Called from viz::DirectRenderer::DrawFrame before rendering starts, but only
-// if the parameters differ from the previous Reshape call.
-//
-// Parameters:
-//
-// - sizeInPixels comes from ui::Compositor::SetScaleAndSize via
-// viz::HostContextFactoryPrivate::ResizeDisplay.
-//
-// - devicePixelRatio comes from viz::CompositorFrame::device_scale_factor()
-// via viz::RootCompositorFrameSinkImpl::SubmitCompositorFrame and
-// viz::Display::SetLocalSurfaceId.
-//
-// - colorSpace and hasAlpha correspond to the color_space and
-// has_transparent_background properties of the root viz::RenderPass.
-//
-// - useStencil should create a stencil buffer, but this is only needed for
-// overdraw feedback (--show-overdraw-feedback), so it's safe to ignore.
-// Accordingly, capabilities_.supports_stencil should be set to false.
-//
-void DisplayGLOutputSurface::Reshape(const gfx::Size &sizeInPixels,
- float devicePixelRatio,
- const gfx::ColorSpace &colorSpace,
- bool hasAlpha,
- bool /*useStencil*/)
-{
- m_currentShape = Shape{sizeInPixels, devicePixelRatio, colorSpace, hasAlpha};
- m_gl->ResizeCHROMIUM(sizeInPixels.width(), sizeInPixels.height(), devicePixelRatio,
- gl::ColorSpaceUtils::GetGLColorSpace(colorSpace), hasAlpha);
-}
-
-std::unique_ptr<DisplayGLOutputSurface::Buffer> DisplayGLOutputSurface::makeBuffer(const Shape &shape)
-{
- std::unique_ptr<Buffer> buffer = std::make_unique<Buffer>(this);
- buffer->shape = shape;
- m_gl->GenTextures(1, &buffer->clientId);
- m_gl->BindTexture(GL_TEXTURE_2D, buffer->clientId);
- m_gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- m_gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- m_gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- m_gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- uint32_t width = shape.sizeInPixels.width();
- uint32_t height = shape.sizeInPixels.height();
- uint32_t format = shape.hasAlpha ? GL_RGBA : GL_RGB;
- m_gl->TexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, nullptr);
- return buffer;
-}
-
-void DisplayGLOutputSurface::deleteBufferResources(Buffer *buffer)
-{
- m_gl->DeleteTextures(1, &buffer->clientId);
-}
-
-// Called by viz::GLRenderer during rendering whenever it switches to the root
-// render pass.
-void DisplayGLOutputSurface::BindFramebuffer()
-{
- if (!m_backBuffer || m_backBuffer->shape != m_currentShape)
- m_backBuffer = makeBuffer(m_currentShape);
-
- m_gl->BindFramebuffer(GL_FRAMEBUFFER, m_fboId);
- m_gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_backBuffer->clientId, 0);
-}
-
-// Called from viz::Display::DrawAndSwap after rendering.
-//
-// Parameters:
-//
-// - frame.size is the same as the size given to Reshape.
-//
-// - frame.sub_buffer_rect and frame.content_bounds are never used since these
-// are only enabled if gl::GLSurface::SupportsPostSubBuffer() or
-// gl::GLSurface::SupportsSwapBuffersWithBounds() are true, respectively,
-// but this not the case for any offscreen gl::GLSurface.
-//
-// - frame.latency_info is viz::CompositorFrame::metadata.latency_info.
-void DisplayGLOutputSurface::SwapBuffers(viz::OutputSurfaceFrame frame)
-{
- DCHECK(frame.size == m_currentShape.sizeInPixels);
- DCHECK(!frame.sub_buffer_rect.has_value());
- DCHECK(frame.content_bounds.empty());
- DCHECK(m_backBuffer);
-
- m_gl->BindFramebuffer(GL_FRAMEBUFFER, m_fboId);
- m_gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
- gpu::SyncToken syncToken;
- m_gl->GenSyncTokenCHROMIUM(syncToken.GetData());
-
- unsigned int clientId = m_backBuffer->clientId;
-
- // Now some thread-hopping:
- //
- // - We start here on the viz thread (client side of command buffer).
- //
- // - Then we'll jump to the gpu thread (service side of command buffer) to
- // get the real OpenGL texture id.
- //
- // - Then we'll get a call from the Qt Quick Scene Graph thread (could be
- // a separate thread or the main thread).
- //
- // - Finally we'll return to the viz thread to acknowledge the swap.
-
- {
- QMutexLocker locker(&m_mutex);
- m_taskRunner = base::ThreadTaskRunnerHandle::Get();
- m_middleBuffer = std::move(m_backBuffer);
- m_middleBuffer->serviceId = 0;
- }
-
- m_commandBuffer->GetTextureQt(
- clientId,
- base::BindOnce(&DisplayGLOutputSurface::swapBuffersOnGpuThread, base::Unretained(this)),
- std::vector<gpu::SyncToken>{syncToken});
-}
-
-void DisplayGLOutputSurface::swapBuffersOnGpuThread(unsigned int id, std::unique_ptr<gl::GLFence> fence)
-{
- {
- QMutexLocker locker(&m_mutex);
- m_middleBuffer->serviceId = id;
- m_middleBuffer->fence = CompositorResourceFence::create(std::move(fence));
- }
-
- if (auto obs = observer())
- obs->readyToSwap();
-}
-
-void DisplayGLOutputSurface::swapBuffersOnVizThread()
-{
- {
- QMutexLocker locker(&m_mutex);
- m_backBuffer = std::move(m_middleBuffer);
- }
-
- const auto now = base::TimeTicks::Now();
- m_display->DidReceiveSwapBuffersAck(gfx::SwapTimings{now, now});
- m_display->DidReceivePresentationFeedback(
- gfx::PresentationFeedback(now, base::TimeDelta(),
- gfx::PresentationFeedback::Flags::kVSync));
-}
-
-void DisplayGLOutputSurface::SetDrawRectangle(const gfx::Rect &)
-{
-}
-
-// Returning true here will cause viz::GLRenderer to try to render the output
-// surface as an overlay plane (see viz::DirectRenderer::DrawFrame and
-// viz::GLRenderer::ScheduleOverlays).
-bool DisplayGLOutputSurface::IsDisplayedAsOverlayPlane() const
-{
- return false;
-}
-
-// Only used if IsDisplayedAsOverlayPlane was true (called from
-// viz::GLRenderer::ScheduleOverlays).
-unsigned DisplayGLOutputSurface::GetOverlayTextureId() const
-{
- return 0;
-}
-
-// Only used if IsDisplayedAsOverlayPlane was true (called from
-// viz::DirectRender::DrawFrame).
-gfx::BufferFormat DisplayGLOutputSurface::GetOverlayBufferFormat() const
-{
- return gfx::BufferFormat();
-}
-
-// Called by viz::GLRenderer but always false in all implementations except for
-// android_webview::ParentOutputSurface.
-bool DisplayGLOutputSurface::HasExternalStencilTest() const
-{
- return false;
-}
-
-// Only called if HasExternalStencilTest was true. Dead code?
-void DisplayGLOutputSurface::ApplyExternalStencil()
-{
- NOTREACHED();
-}
-
-// Called from GLRenderer::GetFramebufferCopyTextureFormat when using
-// glCopyTexSubImage2D on our framebuffer.
-uint32_t DisplayGLOutputSurface::GetFramebufferCopyTextureFormat()
-{
- return m_currentShape.hasAlpha ? GL_RGBA : GL_RGB;
-}
-
-// Called from viz::DirectRenderer::DrawFrame, only used for overlays.
-unsigned DisplayGLOutputSurface::UpdateGpuFence()
-{
- NOTREACHED();
- return 0;
-}
-
-void DisplayGLOutputSurface::SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback callback)
-{
- m_vizContextProvider->SetUpdateVSyncParametersCallback(std::move(callback));
-}
-
-void DisplayGLOutputSurface::SetDisplayTransformHint(gfx::OverlayTransform)
-{
-}
-
-gfx::OverlayTransform DisplayGLOutputSurface::GetDisplayTransform()
-{
- return gfx::OVERLAY_TRANSFORM_NONE;
-}
-
-void DisplayGLOutputSurface::swapFrame()
-{
- QMutexLocker locker(&m_mutex);
- if (m_middleBuffer && m_middleBuffer->serviceId) {
- std::swap(m_middleBuffer, m_frontBuffer);
- m_taskRunner->PostTask(FROM_HERE,
- base::BindOnce(&DisplayGLOutputSurface::swapBuffersOnVizThread,
- base::Unretained(this)));
- m_taskRunner.reset();
- }
-}
-
-void DisplayGLOutputSurface::waitForTexture()
-{
- if (m_frontBuffer && m_frontBuffer->fence) {
- m_frontBuffer->fence->wait();
- m_frontBuffer->fence.reset();
- }
-}
-
-int DisplayGLOutputSurface::textureId()
-{
- return m_frontBuffer ? m_frontBuffer->serviceId : 0;
-}
-
-QSize DisplayGLOutputSurface::textureSize()
-{
- return m_frontBuffer ? toQt(m_frontBuffer->shape.sizeInPixels) : QSize();
-}
-
-bool DisplayGLOutputSurface::hasAlphaChannel()
-{
- return m_frontBuffer ? m_frontBuffer->shape.hasAlpha : false;
-}
-
-float DisplayGLOutputSurface::devicePixelRatio()
-{
- return m_frontBuffer ? m_frontBuffer->shape.devicePixelRatio : 1;
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/compositor/display_gl_output_surface.h b/src/core/compositor/display_gl_output_surface.h
deleted file mode 100644
index 678d0cf5c..000000000
--- a/src/core/compositor/display_gl_output_surface.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DISPLAY_GL_OUTPUT_SURFACE_H
-#define DISPLAY_GL_OUTPUT_SURFACE_H
-
-#include "compositor_resource_fence.h"
-#include "compositor.h"
-
-#include "components/viz/common/display/update_vsync_parameters_callback.h"
-#include "components/viz/service/display/output_surface.h"
-#include "components/viz/service/display_embedder/viz_process_context_provider.h"
-#include "gpu/command_buffer/common/mailbox.h"
-#include "gpu/command_buffer/common/sync_token.h"
-
-#include <QMutex>
-
-namespace viz {
-class Display;
-class SyntheticBeginFrameSource;
-} // namespace viz
-
-namespace QtWebEngineCore {
-
-class DisplayGLOutputSurface final : public viz::OutputSurface, public Compositor
-{
-public:
- DisplayGLOutputSurface(scoped_refptr<viz::VizProcessContextProvider> contextProvider);
- ~DisplayGLOutputSurface() override;
-
- // Overridden from viz::OutputSurface.
- void BindToClient(viz::OutputSurfaceClient *client) override;
- void EnsureBackbuffer() override;
- void DiscardBackbuffer() override;
- void BindFramebuffer() override;
- void SetDrawRectangle(const gfx::Rect &drawRect) override;
- bool IsDisplayedAsOverlayPlane() const override;
- unsigned GetOverlayTextureId() const override;
- gfx::BufferFormat GetOverlayBufferFormat() const override;
- void Reshape(const gfx::Size &size,
- float devicePixelRatio,
- const gfx::ColorSpace &colorSpace,
- bool hasAlpha,
- bool useStencil) override;
- bool HasExternalStencilTest() const override;
- void ApplyExternalStencil() override;
- uint32_t GetFramebufferCopyTextureFormat() override;
- void SwapBuffers(viz::OutputSurfaceFrame frame) override;
- unsigned UpdateGpuFence() override;
- void SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback callback) override;
- void SetDisplayTransformHint(gfx::OverlayTransform transform) override;
- gfx::OverlayTransform GetDisplayTransform() override;
-
- // Overridden from Compositor.
- void swapFrame() override;
- void waitForTexture() override;
- int textureId() override;
- QSize textureSize() override;
- bool hasAlphaChannel() override;
- float devicePixelRatio() override;
-
-private:
- struct Shape
- {
- gfx::Size sizeInPixels;
- float devicePixelRatio;
- gfx::ColorSpace colorSpace;
- bool hasAlpha;
-
- bool operator==(const Shape &that) const
- {
- return (sizeInPixels == that.sizeInPixels &&
- devicePixelRatio == that.devicePixelRatio &&
- colorSpace == that.colorSpace &&
- hasAlpha == that.hasAlpha);
- }
- bool operator!=(const Shape &that) const { return !(*this == that); }
- };
-
- struct Buffer
- {
- DisplayGLOutputSurface *parent;
- Shape shape;
- uint32_t clientId = 0;
- uint32_t serviceId = 0;
- scoped_refptr<CompositorResourceFence> fence;
-
- Buffer(DisplayGLOutputSurface *parent) : parent(parent) {}
- ~Buffer() { parent->deleteBufferResources(this); }
- };
-
- class Texture;
-
- void swapBuffersOnGpuThread(unsigned int id, std::unique_ptr<gl::GLFence> fence);
- void swapBuffersOnVizThread();
-
- std::unique_ptr<Buffer> makeBuffer(const Shape &shape);
- void deleteBufferResources(Buffer *buffer);
- void attachBuffer();
- void detachBuffer();
-
- gpu::InProcessCommandBuffer *const m_commandBuffer;
- gpu::gles2::GLES2Interface *const m_gl;
- mutable QMutex m_mutex;
- uint32_t m_fboId = 0;
- viz::Display *m_display = nullptr;
- Shape m_currentShape;
- std::unique_ptr<Buffer> m_backBuffer;
- std::unique_ptr<Buffer> m_middleBuffer;
- std::unique_ptr<Buffer> m_frontBuffer;
- scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner;
- scoped_refptr<viz::VizProcessContextProvider> m_vizContextProvider;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // !DISPLAY_GL_OUTPUT_SURFACE_H
diff --git a/src/core/compositor/display_overrides.cpp b/src/core/compositor/display_overrides.cpp
index 89bf8ad2f..ebaa96dbb 100644
--- a/src/core/compositor/display_overrides.cpp
+++ b/src/core/compositor/display_overrides.cpp
@@ -1,85 +1,100 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "display_gl_output_surface.h"
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "display_skia_output_device.h"
#include "display_software_output_surface.h"
+#include "native_skia_output_device.h"
#include "components/viz/service/display_embedder/output_surface_provider_impl.h"
+#include "components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h"
#include "gpu/ipc/in_process_command_buffer.h"
+
#include <qtgui-config.h>
+#include <QtQuick/qquickwindow.h>
-std::unique_ptr<viz::OutputSurface>
-viz::OutputSurfaceProviderImpl::CreateGLOutputSurface(
- scoped_refptr<VizProcessContextProvider> context_provider)
-{
#if QT_CONFIG(opengl)
- return std::make_unique<QtWebEngineCore::DisplayGLOutputSurface>(std::move(context_provider));
-#else
- return nullptr;
-#endif // QT_CONFIG(opengl)
-}
+#include "native_skia_output_device_opengl.h"
+#endif
+
+#if BUILDFLAG(ENABLE_VULKAN)
+#include "native_skia_output_device_vulkan.h"
+#endif
+
+#if defined(Q_OS_WIN)
+#include "native_skia_output_device_direct3d11.h"
+#endif
+
+#if defined(Q_OS_MACOS)
+#include "native_skia_output_device_metal.h"
+#endif
std::unique_ptr<viz::OutputSurface>
-viz::OutputSurfaceProviderImpl::CreateSoftwareOutputSurface()
+viz::OutputSurfaceProviderImpl::CreateSoftwareOutputSurface(const RendererSettings &renderer_settings)
{
- return std::make_unique<QtWebEngineCore::DisplaySoftwareOutputSurface>();
+ return std::make_unique<QtWebEngineCore::DisplaySoftwareOutputSurface>(renderer_settings.requires_alpha_channel);
}
-void gpu::InProcessCommandBuffer::GetTextureQt(
- unsigned int client_id,
- GetTextureCallback callback,
- const std::vector<SyncToken>& sync_token_fences)
+std::unique_ptr<viz::SkiaOutputDevice>
+viz::SkiaOutputSurfaceImplOnGpu::CreateOutputDevice()
{
- ScheduleGpuTask(base::BindOnce(&InProcessCommandBuffer::GetTextureQtOnGpuThread,
- gpu_thread_weak_ptr_factory_.GetWeakPtr(),
- client_id,
- std::move(callback)),
- sync_token_fences);
-}
+ static const auto graphicsApi = QQuickWindow::graphicsApi();
-void gpu::InProcessCommandBuffer::GetTextureQtOnGpuThread(
- unsigned int client_id, GetTextureCallback callback)
-{
- if (!MakeCurrent()) {
- LOG(ERROR) << "MakeCurrent failed for GetTextureQt";
- return;
+#if QT_CONFIG(opengl)
+ if (graphicsApi == QSGRendererInterface::OpenGL) {
+ if (gl::GetGLImplementation() != gl::kGLImplementationEGLANGLE) {
+#if !defined(Q_OS_MACOS)
+ return std::make_unique<QtWebEngineCore::DisplaySkiaOutputDevice>(
+ context_state_, renderer_settings_.requires_alpha_channel,
+ shared_gpu_deps_->memory_tracker(), GetDidSwapBuffersCompleteCallback());
+#else
+ qFatal("macOS only supports ANGLE.");
+#endif // !defined(Q_OS_MACOS)
+ }
+
+ return std::make_unique<QtWebEngineCore::NativeSkiaOutputDeviceOpenGL>(
+ context_state_, renderer_settings_.requires_alpha_channel,
+ shared_gpu_deps_->memory_tracker(), dependency_.get(), shared_image_factory_.get(),
+ shared_image_representation_factory_.get(), GetDidSwapBuffersCompleteCallback());
+ }
+#endif // QT_CONFIG(opengl)
+
+#if BUILDFLAG(ENABLE_VULKAN)
+ if (graphicsApi == QSGRendererInterface::Vulkan) {
+#if !defined(Q_OS_MACOS)
+ return std::make_unique<QtWebEngineCore::NativeSkiaOutputDeviceVulkan>(
+ context_state_, renderer_settings_.requires_alpha_channel,
+ shared_gpu_deps_->memory_tracker(), dependency_.get(), shared_image_factory_.get(),
+ shared_image_representation_factory_.get(), GetDidSwapBuffersCompleteCallback());
+#else
+ qFatal("Vulkan is not supported on macOS.");
+#endif // !defined(Q_OS_MACOS)
+ }
+#endif // BUILDFLAG(ENABLE_VULKAN)
+
+#if defined(Q_OS_WIN)
+ if (graphicsApi == QSGRendererInterface::Direct3D11) {
+ if (gl::GetGLImplementation() != gl::kGLImplementationEGLANGLE)
+ qFatal("Direct3D11 is only supported over ANGLE.");
+
+ return std::make_unique<QtWebEngineCore::NativeSkiaOutputDeviceDirect3D11>(
+ context_state_, renderer_settings_.requires_alpha_channel,
+ shared_gpu_deps_->memory_tracker(), dependency_.get(), shared_image_factory_.get(),
+ shared_image_representation_factory_.get(), GetDidSwapBuffersCompleteCallback());
}
- gpu::TextureBase *texture = decoder_->GetTextureBase(client_id);
- std::move(callback).Run(texture ? texture->service_id() : 0, gl::GLFence::Create());
+#endif
+
+#if defined(Q_OS_MACOS)
+ if (graphicsApi == QSGRendererInterface::Metal) {
+ if (gl::GetGLImplementation() != gl::kGLImplementationEGLANGLE)
+ qFatal("Metal is only supported over ANGLE.");
+
+ return std::make_unique<QtWebEngineCore::NativeSkiaOutputDeviceMetal>(
+ context_state_, renderer_settings_.requires_alpha_channel,
+ shared_gpu_deps_->memory_tracker(), dependency_.get(), shared_image_factory_.get(),
+ shared_image_representation_factory_.get(), GetDidSwapBuffersCompleteCallback());
+ }
+#endif
+
+ qFatal() << "Unsupported Graphics API:" << graphicsApi;
+ return nullptr;
}
diff --git a/src/core/compositor/display_skia_output_device.cpp b/src/core/compositor/display_skia_output_device.cpp
new file mode 100644
index 000000000..0ca466fe8
--- /dev/null
+++ b/src/core/compositor/display_skia_output_device.cpp
@@ -0,0 +1,240 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "display_skia_output_device.h"
+
+#include "compositor_resource_fence.h"
+#include "type_conversion.h"
+
+#include "gpu/command_buffer/service/skia_utils.h"
+#include "third_party/skia/include/core/SkSurface.h"
+#include "third_party/skia/include/core/SkSurfaceProps.h"
+#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
+#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
+
+#include <QSGTexture>
+
+namespace QtWebEngineCore {
+
+class DisplaySkiaOutputDevice::Buffer
+{
+public:
+ Buffer(DisplaySkiaOutputDevice *parent)
+ : m_parent(parent)
+ , m_shape(m_parent->m_shape)
+ {
+ }
+ void initialize()
+ {
+ const auto &colorType = m_shape.imageInfo.colorType();
+ DCHECK(colorType != kUnknown_SkColorType);
+
+ m_texture = m_parent->m_contextState->gr_context()->createBackendTexture(
+ m_shape.imageInfo.width(), m_shape.imageInfo.height(), colorType,
+ GrMipMapped::kNo, GrRenderable::kYes);
+ DCHECK(m_texture.isValid());
+
+ DCHECK(m_texture.backend() == GrBackendApi::kOpenGL);
+ auto info = SkImageInfo::Make(m_shape.imageInfo.width(), m_shape.imageInfo.height(),
+ colorType, kUnpremul_SkAlphaType);
+ m_estimatedSize = info.computeMinByteSize();
+ m_parent->memory_type_tracker_->TrackMemAlloc(m_estimatedSize);
+
+ SkSurfaceProps surfaceProps = SkSurfaceProps{0, kUnknown_SkPixelGeometry};
+ m_surface = SkSurfaces::WrapBackendTexture(
+ m_parent->m_contextState->gr_context(), m_texture,
+ m_parent->capabilities_.output_surface_origin == gfx::SurfaceOrigin::kTopLeft
+ ? kTopLeft_GrSurfaceOrigin
+ : kBottomLeft_GrSurfaceOrigin,
+ 0 /* sampleCount */, colorType, m_shape.colorSpace.ToSkColorSpace(),
+ &surfaceProps);
+ }
+
+ ~Buffer()
+ {
+ if (m_texture.isValid()) {
+ DeleteGrBackendTexture(m_parent->m_contextState.get(), &m_texture);
+ m_parent->memory_type_tracker_->TrackMemFree(m_estimatedSize);
+ }
+ }
+
+ void createFence()
+ {
+ m_fence = CompositorResourceFence::create();
+ }
+
+ void consumeFence()
+ {
+ if (m_fence) {
+ m_fence->wait();
+ m_fence.reset();
+ }
+ }
+
+ const Shape &shape() const { return m_shape; }
+ const GrBackendTexture &texture() const { return m_texture; }
+ SkSurface *surface() const { return m_surface.get(); }
+
+private:
+ DisplaySkiaOutputDevice *m_parent;
+ Shape m_shape;
+ GrBackendTexture m_texture;
+ sk_sp<SkSurface> m_surface;
+ uint64_t m_estimatedSize = 0;
+ scoped_refptr<CompositorResourceFence> m_fence;
+};
+
+DisplaySkiaOutputDevice::DisplaySkiaOutputDevice(
+ scoped_refptr<gpu::SharedContextState> contextState,
+ bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : SkiaOutputDevice(contextState->gr_context(), contextState->graphite_context(),
+ memoryTracker, didSwapBufferCompleteCallback)
+ , Compositor(Compositor::Type::OpenGL)
+ , m_contextState(contextState)
+ , m_requiresAlpha(requiresAlpha)
+{
+ capabilities_.uses_default_gl_framebuffer = false;
+ capabilities_.supports_surfaceless = true;
+ capabilities_.preserve_buffer_content = true;
+ capabilities_.only_invalidates_damage_rect = false;
+ capabilities_.number_of_buffers = 3;
+
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] =
+ kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] =
+ kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRA_8888)] =
+ kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] =
+ kRGBA_8888_SkColorType;
+}
+
+DisplaySkiaOutputDevice::~DisplaySkiaOutputDevice()
+{
+}
+
+void DisplaySkiaOutputDevice::SetFrameSinkId(const viz::FrameSinkId &id)
+{
+ bind(id);
+}
+bool DisplaySkiaOutputDevice::Reshape(const SkImageInfo &image_info,
+ const gfx::ColorSpace &colorSpace,
+ int sample_count,
+ float device_scale_factor,
+ gfx::OverlayTransform transform)
+{
+ m_shape = Shape{image_info, device_scale_factor, colorSpace};
+ DCHECK_EQ(transform, gfx::OVERLAY_TRANSFORM_NONE);
+ return true;
+}
+
+void DisplaySkiaOutputDevice::Present(const absl::optional<gfx::Rect> &update_rect,
+ BufferPresentedCallback feedback,
+ viz::OutputSurfaceFrame frame)
+{
+ DCHECK(m_backBuffer);
+
+ StartSwapBuffers(std::move(feedback));
+ m_frame = std::move(frame);
+ m_backBuffer->createFence();
+
+ {
+ QMutexLocker locker(&m_mutex);
+ m_taskRunner = base::SingleThreadTaskRunner::GetCurrentDefault();
+ std::swap(m_middleBuffer, m_backBuffer);
+ m_readyToUpdate = true;
+ }
+
+ if (auto obs = observer())
+ obs->readyToSwap();
+}
+
+void DisplaySkiaOutputDevice::EnsureBackbuffer()
+{
+}
+
+void DisplaySkiaOutputDevice::DiscardBackbuffer()
+{
+}
+
+SkSurface *DisplaySkiaOutputDevice::BeginPaint(std::vector<GrBackendSemaphore> *end_semaphores)
+{
+ if (!m_backBuffer || m_backBuffer->shape() != m_shape) {
+ m_backBuffer = std::make_unique<Buffer>(this);
+ m_backBuffer->initialize();
+ }
+ return m_backBuffer->surface();
+}
+
+void DisplaySkiaOutputDevice::EndPaint()
+{
+}
+
+void DisplaySkiaOutputDevice::swapFrame()
+{
+ QMutexLocker locker(&m_mutex);
+ if (m_readyToUpdate) {
+ std::swap(m_middleBuffer, m_frontBuffer);
+ m_taskRunner->PostTask(FROM_HERE,
+ base::BindOnce(&DisplaySkiaOutputDevice::SwapBuffersFinished,
+ base::Unretained(this)));
+ m_taskRunner.reset();
+ m_readyToUpdate = false;
+ }
+}
+
+void DisplaySkiaOutputDevice::waitForTexture()
+{
+ if (m_frontBuffer)
+ m_frontBuffer->consumeFence();
+}
+
+QSGTexture *DisplaySkiaOutputDevice::texture(QQuickWindow *win, uint32_t textureOptions)
+{
+ if (!m_frontBuffer)
+ return nullptr;
+
+ QQuickWindow::CreateTextureOptions texOpts(textureOptions);
+
+ QSGTexture *texture = nullptr;
+ GrGLTextureInfo info;
+ if (GrBackendTextures::GetGLTextureInfo(m_frontBuffer->texture(), &info))
+ texture = QNativeInterface::QSGOpenGLTexture::fromNative(info.fID, win, size(), texOpts);
+ return texture;
+}
+
+bool DisplaySkiaOutputDevice::textureIsFlipped()
+{
+ return true;
+}
+
+QSize DisplaySkiaOutputDevice::size()
+{
+ return m_frontBuffer ? toQt(m_frontBuffer->shape().imageInfo.dimensions()) : QSize();
+}
+
+bool DisplaySkiaOutputDevice::requiresAlphaChannel()
+{
+ return m_requiresAlpha;
+}
+
+float DisplaySkiaOutputDevice::devicePixelRatio()
+{
+ return m_frontBuffer ? m_frontBuffer->shape().devicePixelRatio : 1;
+}
+
+void DisplaySkiaOutputDevice::SwapBuffersFinished()
+{
+ {
+ QMutexLocker locker(&m_mutex);
+ std::swap(m_backBuffer, m_middleBuffer);
+ }
+
+ FinishSwapBuffers(gfx::SwapCompletionResult(gfx::SwapResult::SWAP_ACK),
+ gfx::Size(m_shape.imageInfo.width(), m_shape.imageInfo.height()),
+ std::move(m_frame));
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/display_skia_output_device.h b/src/core/compositor/display_skia_output_device.h
new file mode 100644
index 000000000..e6a97b810
--- /dev/null
+++ b/src/core/compositor/display_skia_output_device.h
@@ -0,0 +1,89 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef DISPLAY_SKIA_OUTPUT_DEVICE_H
+#define DISPLAY_SKIA_OUTPUT_DEVICE_H
+
+#include <QtCore/QMutex>
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+
+#include "compositor.h"
+
+#include "base/task/single_thread_task_runner.h"
+#include "components/viz/service/display_embedder/skia_output_device.h"
+#include "gpu/command_buffer/service/shared_context_state.h"
+
+QT_BEGIN_NAMESPACE
+class QQuickWindow;
+QT_END_NAMESPACE
+
+namespace QtWebEngineCore {
+
+class DisplaySkiaOutputDevice final : public viz::SkiaOutputDevice, public Compositor
+{
+public:
+ DisplaySkiaOutputDevice(scoped_refptr<gpu::SharedContextState> contextState,
+ bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~DisplaySkiaOutputDevice() override;
+
+ // Overridden from SkiaOutputDevice.
+ void SetFrameSinkId(const viz::FrameSinkId &frame_sink_id) override;
+ bool Reshape(const SkImageInfo &image_info,
+ const gfx::ColorSpace &color_space,
+ int sample_count,
+ float device_scale_factor,
+ gfx::OverlayTransform transform) override;
+ void Present(const absl::optional<gfx::Rect>& update_rect,
+ BufferPresentedCallback feedback,
+ viz::OutputSurfaceFrame frame) override;
+ void EnsureBackbuffer() override;
+ void DiscardBackbuffer() override;
+ SkSurface *BeginPaint(std::vector<GrBackendSemaphore> *semaphores) override;
+ void EndPaint() override;
+
+ // Overridden from Compositor.
+ void swapFrame() override;
+ void waitForTexture() override;
+ QSGTexture *texture(QQuickWindow *win, uint32_t texOpts) override;
+ bool textureIsFlipped() override;
+ QSize size() override;
+ bool requiresAlphaChannel() override;
+ float devicePixelRatio() override;
+
+private:
+ struct Shape
+ {
+ SkImageInfo imageInfo;
+ float devicePixelRatio;
+ gfx::ColorSpace colorSpace;
+
+ bool operator==(const Shape &that) const
+ {
+ return (imageInfo == that.imageInfo &&
+ devicePixelRatio == that.devicePixelRatio &&
+ colorSpace == that.colorSpace);
+ }
+ bool operator!=(const Shape &that) const { return !(*this == that); }
+ };
+
+ class Buffer;
+
+ void SwapBuffersFinished();
+
+ mutable QMutex m_mutex;
+ scoped_refptr<gpu::SharedContextState> m_contextState;
+ Shape m_shape;
+ std::unique_ptr<Buffer> m_frontBuffer;
+ std::unique_ptr<Buffer> m_middleBuffer;
+ std::unique_ptr<Buffer> m_backBuffer;
+ viz::OutputSurfaceFrame m_frame;
+ bool m_readyToUpdate = false;
+ bool m_requiresAlpha;
+ scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // !DISPLAY_SKIA_OUTPUT_DEVICE_H
diff --git a/src/core/compositor/display_software_output_surface.cpp b/src/core/compositor/display_software_output_surface.cpp
index b1a357615..2c208ca57 100644
--- a/src/core/compositor/display_software_output_surface.cpp
+++ b/src/core/compositor/display_software_output_surface.cpp
@@ -1,54 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "display_software_output_surface.h"
#include "compositor.h"
-#include "render_widget_host_view_qt_delegate.h"
#include "type_conversion.h"
-#include "base/threading/thread_task_runner_handle.h"
+#include "base/task/single_thread_task_runner.h"
#include "components/viz/service/display/display.h"
#include "components/viz/service/display/output_surface_frame.h"
#include <QMutex>
#include <QPainter>
+#include <QQuickWindow>
namespace QtWebEngineCore {
@@ -56,34 +20,34 @@ class DisplaySoftwareOutputSurface::Device final : public viz::SoftwareOutputDev
public Compositor
{
public:
- Device();
- ~Device();
+ Device(bool requiresAlpha);
// Overridden from viz::SoftwareOutputDevice.
void Resize(const gfx::Size &sizeInPixels, float devicePixelRatio) override;
- void OnSwapBuffers(SwapBuffersCallback swap_ack_callback) override;
+ void OnSwapBuffers(SwapBuffersCallback swap_ack_callback, gfx::FrameData data) override;
// Overridden from Compositor.
void swapFrame() override;
- QImage image() override;
+ QSGTexture *texture(QQuickWindow *win, uint32_t) override;
+ bool textureIsFlipped() override;
float devicePixelRatio() override;
+ QSize size() override;
+ bool requiresAlphaChannel() override;
private:
mutable QMutex m_mutex;
float m_devicePixelRatio = 1.0;
+ bool m_requiresAlpha;
scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner;
SwapBuffersCallback m_swapCompletionCallback;
QImage m_image;
float m_imageDevicePixelRatio = 1.0;
};
-DisplaySoftwareOutputSurface::Device::Device()
+DisplaySoftwareOutputSurface::Device::Device(bool requiresAlpha)
: Compositor(Type::Software)
-{}
-
-DisplaySoftwareOutputSurface::Device::~Device()
+ , m_requiresAlpha(requiresAlpha)
{
- unbind();
}
void DisplaySoftwareOutputSurface::Device::Resize(const gfx::Size &sizeInPixels, float devicePixelRatio)
@@ -92,14 +56,17 @@ void DisplaySoftwareOutputSurface::Device::Resize(const gfx::Size &sizeInPixels,
return;
m_devicePixelRatio = devicePixelRatio;
viewport_pixel_size_ = sizeInPixels;
- surface_ = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(sizeInPixels.width(), sizeInPixels.height()));
+ surface_ = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(sizeInPixels.width(), sizeInPixels.height()));
}
-void DisplaySoftwareOutputSurface::Device::OnSwapBuffers(SwapBuffersCallback swap_ack_callback)
+void DisplaySoftwareOutputSurface::Device::OnSwapBuffers(SwapBuffersCallback swap_ack_callback, gfx::FrameData data)
{
- QMutexLocker locker(&m_mutex);
- m_taskRunner = base::ThreadTaskRunnerHandle::Get();
- m_swapCompletionCallback = std::move(swap_ack_callback);
+ { // MEMO don't hold a lock together with an 'observer', as the call from Qt's scene graph may come at the same time
+ QMutexLocker locker(&m_mutex);
+ m_taskRunner = base::SingleThreadTaskRunner::GetCurrentDefault();
+ m_swapCompletionCallback = std::move(swap_ack_callback);
+ }
+
if (auto obs = observer())
obs->readyToSwap();
}
@@ -144,9 +111,14 @@ void DisplaySoftwareOutputSurface::Device::swapFrame()
m_taskRunner.reset();
}
-QImage DisplaySoftwareOutputSurface::Device::image()
+QSGTexture *DisplaySoftwareOutputSurface::Device::texture(QQuickWindow *win, uint32_t)
+{
+ return win->createTextureFromImage(m_image);
+}
+
+bool DisplaySoftwareOutputSurface::Device::textureIsFlipped()
{
- return m_image;
+ return false;
}
float DisplaySoftwareOutputSurface::Device::devicePixelRatio()
@@ -154,19 +126,26 @@ float DisplaySoftwareOutputSurface::Device::devicePixelRatio()
return m_imageDevicePixelRatio;
}
-DisplaySoftwareOutputSurface::DisplaySoftwareOutputSurface()
- : SoftwareOutputSurface(std::make_unique<Device>())
+QSize DisplaySoftwareOutputSurface::Device::size()
+{
+ return m_image.size();
+}
+
+bool DisplaySoftwareOutputSurface::Device::requiresAlphaChannel()
+{
+ return m_requiresAlpha;
+}
+
+DisplaySoftwareOutputSurface::DisplaySoftwareOutputSurface(bool requiresAlpha)
+ : SoftwareOutputSurface(std::make_unique<Device>(requiresAlpha))
{}
DisplaySoftwareOutputSurface::~DisplaySoftwareOutputSurface() {}
// Called from viz::Display::Initialize.
-void DisplaySoftwareOutputSurface::BindToClient(viz::OutputSurfaceClient *client)
+void DisplaySoftwareOutputSurface::SetFrameSinkId(const viz::FrameSinkId &id)
{
- auto display = static_cast<viz::Display *>(client);
- auto device = static_cast<Device *>(software_device());
- device->bind(display->frame_sink_id());
- SoftwareOutputSurface::BindToClient(client);
+ static_cast<Device *>(software_device())->bind(id);
}
} // namespace QtWebEngineCore
diff --git a/src/core/compositor/display_software_output_surface.h b/src/core/compositor/display_software_output_surface.h
index ae4b277dd..d23664d56 100644
--- a/src/core/compositor/display_software_output_surface.h
+++ b/src/core/compositor/display_software_output_surface.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DISPLAY_SOFTWARE_OUTPUT_SURFACE_H
#define DISPLAY_SOFTWARE_OUTPUT_SURFACE_H
@@ -47,11 +11,11 @@ namespace QtWebEngineCore {
class DisplaySoftwareOutputSurface final : public viz::SoftwareOutputSurface
{
public:
- DisplaySoftwareOutputSurface();
+ DisplaySoftwareOutputSurface(bool requiresAlpha);
~DisplaySoftwareOutputSurface() override;
- // Overridden from viz::SoftwareOutputSurface.
- void BindToClient(viz::OutputSurfaceClient *client) override;
+ // Overridden from viz::OutputSurface.
+ void SetFrameSinkId(const viz::FrameSinkId &id) override;
private:
class Device;
diff --git a/src/core/compositor/native_skia_output_device.cpp b/src/core/compositor/native_skia_output_device.cpp
new file mode 100644
index 000000000..708692df7
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device.cpp
@@ -0,0 +1,422 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "native_skia_output_device.h"
+
+#include "type_conversion.h"
+
+#include "components/viz/common/resources/shared_image_format.h"
+#include "components/viz/common/resources/shared_image_format_utils.h"
+#include "components/viz/service/display_embedder/skia_output_surface_dependency.h"
+#include "gpu/command_buffer/common/mailbox.h"
+#include "gpu/command_buffer/common/shared_image_usage.h"
+#include "gpu/command_buffer/service/shared_image/shared_image_factory.h"
+#include "gpu/command_buffer/service/shared_image/shared_image_representation.h"
+#include "gpu/command_buffer/service/skia_utils.h"
+#include "third_party/skia/include/gpu/GrDirectContext.h"
+#include "third_party/skia/include/core/SkSurfaceProps.h"
+#include "ui/gfx/native_pixmap.h"
+#include "ui/gfx/gpu_fence.h"
+#include "ui/gl/gl_fence.h"
+
+#if defined(USE_OZONE)
+#include "ui/ozone/public/ozone_platform.h"
+#endif
+
+namespace QtWebEngineCore {
+
+namespace {
+
+// Helper function for moving a GpuFence from a fence handle to a unique_ptr.
+std::unique_ptr<gfx::GpuFence> TakeGpuFence(gfx::GpuFenceHandle fence)
+{
+ return fence.is_null() ? nullptr : std::make_unique<gfx::GpuFence>(std::move(fence));
+}
+
+} // namespace
+
+NativeSkiaOutputDevice::NativeSkiaOutputDevice(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : SkiaOutputDevice(contextState->gr_context(), contextState->graphite_context(), memoryTracker,
+ didSwapBufferCompleteCallback)
+ , Compositor(Type::Native)
+ , m_contextState(contextState)
+ , m_requiresAlpha(requiresAlpha)
+ , m_factory(shared_image_factory)
+ , m_representationFactory(shared_image_representation_factory)
+ , m_deps(dependency)
+{
+ capabilities_.uses_default_gl_framebuffer = false;
+ capabilities_.supports_surfaceless = true;
+ capabilities_.output_surface_origin = gfx::SurfaceOrigin::kTopLeft;
+ capabilities_.preserve_buffer_content = true;
+ capabilities_.only_invalidates_damage_rect = false;
+
+#if defined(USE_OZONE)
+ m_isNativeBufferSupported = ui::OzonePlatform::GetInstance()
+ ->GetPlatformRuntimeProperties()
+ .supports_native_pixmaps;
+#endif
+}
+
+NativeSkiaOutputDevice::~NativeSkiaOutputDevice()
+{
+}
+
+void NativeSkiaOutputDevice::SetFrameSinkId(const viz::FrameSinkId &id)
+{
+ bind(id);
+}
+
+bool NativeSkiaOutputDevice::Reshape(const SkImageInfo &image_info,
+ const gfx::ColorSpace &colorSpace,
+ int sample_count,
+ float device_scale_factor,
+ gfx::OverlayTransform transform)
+{
+ m_shape = Shape{image_info, device_scale_factor, colorSpace, sample_count};
+ DCHECK_EQ(transform, gfx::OVERLAY_TRANSFORM_NONE);
+ return true;
+}
+
+void NativeSkiaOutputDevice::Present(const absl::optional<gfx::Rect> &update_rect,
+ BufferPresentedCallback feedback,
+ viz::OutputSurfaceFrame frame)
+{
+ DCHECK(m_backBuffer);
+
+ StartSwapBuffers(std::move(feedback));
+ m_frame = std::move(frame);
+ {
+ QMutexLocker locker(&m_mutex);
+ m_backBuffer->createFence();
+ m_gpuTaskRunner = base::SingleThreadTaskRunner::GetCurrentDefault();
+ std::swap(m_middleBuffer, m_backBuffer);
+ m_readyToUpdate = true;
+ }
+
+ if (auto obs = observer())
+ obs->readyToSwap();
+}
+
+void NativeSkiaOutputDevice::EnsureBackbuffer()
+{
+}
+
+void NativeSkiaOutputDevice::DiscardBackbuffer()
+{
+}
+
+SkSurface *NativeSkiaOutputDevice::BeginPaint(std::vector<GrBackendSemaphore> *end_semaphores)
+{
+ {
+ QMutexLocker locker(&m_mutex);
+ if (!m_backBuffer || m_backBuffer->shape() != m_shape) {
+ m_backBuffer = std::make_unique<Buffer>(this);
+ if (!m_backBuffer->initialize())
+ return nullptr;
+ }
+ }
+ auto surface = m_backBuffer->beginWriteSkia();
+ *end_semaphores = m_backBuffer->takeEndWriteSkiaSemaphores();
+ return surface;
+}
+
+void NativeSkiaOutputDevice::EndPaint()
+{
+ m_backBuffer->endWriteSkia(true);
+}
+
+void NativeSkiaOutputDevice::swapFrame()
+{
+ QMutexLocker locker(&m_mutex);
+ if (m_readyToUpdate) {
+ std::swap(m_frontBuffer, m_middleBuffer);
+ m_gpuTaskRunner->PostTask(FROM_HERE,
+ base::BindOnce(&NativeSkiaOutputDevice::SwapBuffersFinished,
+ base::Unretained(this)));
+ m_readyToUpdate = false;
+ if (m_frontBuffer) {
+ m_readyWithTexture = true;
+ m_frontBuffer->beginPresent();
+ }
+ if (m_middleBuffer)
+ m_middleBuffer->freeTexture();
+ m_gpuTaskRunner.reset();
+ }
+}
+
+void NativeSkiaOutputDevice::waitForTexture()
+{
+ if (m_readyWithTexture)
+ m_frontBuffer->consumeFence();
+}
+
+void NativeSkiaOutputDevice::releaseTexture()
+{
+ if (m_readyWithTexture) {
+ m_frontBuffer->endPresent();
+ m_readyWithTexture = false;
+ }
+}
+
+void NativeSkiaOutputDevice::releaseResources()
+{
+ if (m_frontBuffer)
+ m_frontBuffer->freeTexture();
+}
+
+bool NativeSkiaOutputDevice::textureIsFlipped()
+{
+ return false;
+}
+
+QSize NativeSkiaOutputDevice::size()
+{
+ return m_frontBuffer ? toQt(m_frontBuffer->shape().imageInfo.dimensions()) : QSize();
+}
+
+bool NativeSkiaOutputDevice::requiresAlphaChannel()
+{
+ return m_requiresAlpha;
+}
+
+float NativeSkiaOutputDevice::devicePixelRatio()
+{
+ return m_frontBuffer ? m_frontBuffer->shape().devicePixelRatio : 1;
+}
+
+void NativeSkiaOutputDevice::SwapBuffersFinished()
+{
+ {
+ QMutexLocker locker(&m_mutex);
+ std::swap(m_backBuffer, m_middleBuffer);
+ }
+
+ FinishSwapBuffers(gfx::SwapCompletionResult(gfx::SwapResult::SWAP_ACK),
+ gfx::Size(m_shape.imageInfo.width(), m_shape.imageInfo.height()),
+ std::move(m_frame));
+}
+
+NativeSkiaOutputDevice::Buffer::Buffer(NativeSkiaOutputDevice *parent)
+ : m_parent(parent), m_shape(m_parent->m_shape)
+{
+}
+
+NativeSkiaOutputDevice::Buffer::~Buffer()
+{
+ if (m_scopedSkiaWriteAccess)
+ endWriteSkia(false);
+
+ if (!m_mailbox.IsZero())
+ m_parent->m_factory->DestroySharedImage(m_mailbox);
+}
+
+// The following Buffer methods are based on
+// components/viz/service/display_embedder/output_presenter.cc: Copyright 2020 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+bool NativeSkiaOutputDevice::Buffer::initialize()
+{
+ static const uint32_t kDefaultSharedImageUsage = gpu::SHARED_IMAGE_USAGE_SCANOUT
+ | gpu::SHARED_IMAGE_USAGE_DISPLAY_READ | gpu::SHARED_IMAGE_USAGE_DISPLAY_WRITE
+ | gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT;
+ auto mailbox = gpu::Mailbox::GenerateForSharedImage();
+
+ SkColorType skColorType = m_shape.imageInfo.colorType();
+ if (!m_parent->m_factory->CreateSharedImage(
+ mailbox, viz::SkColorTypeToSinglePlaneSharedImageFormat(skColorType),
+ { m_shape.imageInfo.width(), m_shape.imageInfo.height() }, m_shape.colorSpace,
+ kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, m_parent->m_deps->GetSurfaceHandle(),
+ kDefaultSharedImageUsage, "QWE_SharedImageBuffer")) {
+ LOG(ERROR) << "CreateSharedImage failed.";
+ return false;
+ }
+ m_mailbox = mailbox;
+
+ m_skiaRepresentation =
+ m_parent->m_representationFactory->ProduceSkia(m_mailbox, m_parent->m_contextState);
+ if (!m_skiaRepresentation) {
+ LOG(ERROR) << "ProduceSkia() failed.";
+ return false;
+ }
+
+ if (m_parent->m_isNativeBufferSupported) {
+ m_overlayRepresentation = m_parent->m_representationFactory->ProduceOverlay(m_mailbox);
+ if (!m_overlayRepresentation) {
+ LOG(ERROR) << "ProduceOverlay() failed";
+ return false;
+ }
+ }
+
+ return true;
+}
+
+SkSurface *NativeSkiaOutputDevice::Buffer::beginWriteSkia()
+{
+ DCHECK(!m_scopedSkiaWriteAccess);
+ DCHECK(!m_presentCount);
+ DCHECK(m_endSemaphores.empty());
+
+ std::vector<GrBackendSemaphore> beginSemaphores;
+ SkSurfaceProps surface_props{ 0, kUnknown_SkPixelGeometry };
+
+ // Buffer queue is internal to GPU proc and handles texture initialization,
+ // so allow uncleared access.
+ m_scopedSkiaWriteAccess = m_skiaRepresentation->BeginScopedWriteAccess(
+ m_shape.sampleCount, surface_props, &beginSemaphores, &m_endSemaphores,
+ gpu::SharedImageRepresentation::AllowUnclearedAccess::kYes);
+ DCHECK(m_scopedSkiaWriteAccess);
+ if (!beginSemaphores.empty()) {
+ m_scopedSkiaWriteAccess->surface()->wait(beginSemaphores.size(), beginSemaphores.data(),
+ /*deleteSemaphoresAfterWait=*/false);
+ }
+ return m_scopedSkiaWriteAccess->surface();
+}
+
+void NativeSkiaOutputDevice::Buffer::endWriteSkia(bool force_flush)
+{
+ // The Flush now takes place in finishPaintCurrentBuffer on the CPU side.
+ // check if end_semaphores is not empty then flush here
+ DCHECK(m_scopedSkiaWriteAccess);
+ if (!m_endSemaphores.empty() || force_flush) {
+ GrFlushInfo flush_info = {};
+ flush_info.fNumSemaphores = m_endSemaphores.size();
+ flush_info.fSignalSemaphores = m_endSemaphores.data();
+ auto *direct_context =
+ m_scopedSkiaWriteAccess->surface()->recordingContext()->asDirectContext();
+ DCHECK(direct_context);
+ direct_context->flush(m_scopedSkiaWriteAccess->surface(), {});
+ m_scopedSkiaWriteAccess->ApplyBackendSurfaceEndState();
+ direct_context->flush(m_scopedSkiaWriteAccess->surface(), flush_info, nullptr);
+ direct_context->submit();
+ }
+ m_scopedSkiaWriteAccess.reset();
+ m_endSemaphores.clear();
+
+ // SkiaRenderer always draws the full frame.
+ m_skiaRepresentation->SetCleared();
+}
+
+std::vector<GrBackendSemaphore> NativeSkiaOutputDevice::Buffer::takeEndWriteSkiaSemaphores()
+{
+ return std::exchange(m_endSemaphores, {});
+}
+
+void NativeSkiaOutputDevice::Buffer::createSkImageOnGPUThread()
+{
+ if (!m_scopedSkiaReadAccess) {
+ m_skImageMutex.unlock();
+ return;
+ }
+
+ m_cachedSkImage = m_scopedSkiaReadAccess->CreateSkImage(m_parent->m_contextState.get());
+ m_skImageMutex.unlock();
+ if (!m_cachedSkImage)
+ qWarning("SKIA: Failed to create SkImage.");
+}
+
+void NativeSkiaOutputDevice::Buffer::beginPresent()
+{
+ if (++m_presentCount != 1) {
+ DCHECK(m_scopedOverlayReadAccess || m_scopedSkiaReadAccess);
+ return;
+ }
+
+ DCHECK(!m_scopedSkiaWriteAccess);
+ DCHECK(!m_scopedOverlayReadAccess && !m_scopedSkiaReadAccess);
+
+ if (m_overlayRepresentation) {
+ m_scopedOverlayReadAccess = m_overlayRepresentation->BeginScopedReadAccess();
+ DCHECK(m_scopedOverlayReadAccess);
+ m_acquireFence = TakeGpuFence(m_scopedOverlayReadAccess->TakeAcquireFence());
+ } else {
+ DCHECK(m_skiaRepresentation);
+ std::vector<GrBackendSemaphore> beginSemaphores;
+ m_scopedSkiaReadAccess =
+ m_skiaRepresentation->BeginScopedReadAccess(&beginSemaphores, nullptr);
+ DCHECK(m_scopedSkiaReadAccess);
+ if (!beginSemaphores.empty())
+ qWarning("SKIA: Unexpected semaphores while reading texture, wait is not implemented.");
+
+ m_skImageMutex.tryLock();
+ m_parent->m_gpuTaskRunner->PostTask(FROM_HERE,
+ base::BindOnce(&NativeSkiaOutputDevice::Buffer::createSkImageOnGPUThread,
+ base::Unretained(this)));
+ }
+}
+
+void NativeSkiaOutputDevice::Buffer::endPresent()
+{
+ if (!m_presentCount)
+ return;
+ DCHECK(m_scopedOverlayReadAccess || m_scopedSkiaReadAccess);
+ if (--m_presentCount)
+ return;
+
+ if (m_scopedOverlayReadAccess) {
+ DCHECK(!m_scopedSkiaReadAccess);
+ m_scopedOverlayReadAccess.reset();
+ } else if (m_scopedSkiaReadAccess) {
+ DCHECK(!m_scopedOverlayReadAccess);
+ QMutexLocker locker(&m_skImageMutex);
+ m_scopedSkiaReadAccess.reset();
+ }
+}
+
+void NativeSkiaOutputDevice::Buffer::freeTexture()
+{
+ if (textureCleanupCallback) {
+ textureCleanupCallback();
+ textureCleanupCallback = nullptr;
+ }
+}
+
+void NativeSkiaOutputDevice::Buffer::createFence()
+{
+ // For some reason we still need to create this, but we do not need to wait on it.
+ if (m_parent->m_contextState->gr_context_type() == gpu::GrContextType::kGL)
+ m_fence = gl::GLFence::Create();
+}
+
+void NativeSkiaOutputDevice::Buffer::consumeFence()
+{
+ if (m_acquireFence) {
+ m_acquireFence->Wait();
+ m_acquireFence.reset();
+ }
+}
+
+sk_sp<SkImage> NativeSkiaOutputDevice::Buffer::skImage()
+{
+ QMutexLocker locker(&m_skImageMutex);
+ return m_cachedSkImage;
+}
+#if defined(USE_OZONE)
+scoped_refptr<gfx::NativePixmap> NativeSkiaOutputDevice::Buffer::nativePixmap()
+{
+ DCHECK(m_presentCount);
+ if (!m_scopedOverlayReadAccess)
+ return nullptr;
+
+ return m_scopedOverlayReadAccess->GetNativePixmap();
+}
+#elif defined(Q_OS_WIN)
+absl::optional<gl::DCLayerOverlayImage> NativeSkiaOutputDevice::Buffer::overlayImage() const
+{
+ DCHECK(m_presentCount);
+ return m_scopedOverlayReadAccess->GetDCLayerOverlayImage();
+}
+#elif defined(Q_OS_MACOS)
+gfx::ScopedIOSurface NativeSkiaOutputDevice::Buffer::ioSurface() const
+{
+ DCHECK(m_presentCount);
+ return m_scopedOverlayReadAccess->GetIOSurface();
+}
+#endif
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/native_skia_output_device.h b/src/core/compositor/native_skia_output_device.h
new file mode 100644
index 000000000..2c35cef77
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device.h
@@ -0,0 +1,183 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_SKIA_OUTPUT_DEVICE_H
+#define NATIVE_SKIA_OUTPUT_DEVICE_H
+
+#include "compositor.h"
+
+#include "base/task/single_thread_task_runner.h"
+#include "components/viz/service/display_embedder/skia_output_device.h"
+#include "gpu/command_buffer/service/shared_context_state.h"
+#include "gpu/command_buffer/service/shared_image/shared_image_representation.h"
+#include "gpu/config/gpu_preferences.h"
+
+#include <QMutex>
+
+#if defined(Q_OS_WIN)
+#include "ui/gl/dc_layer_overlay_image.h"
+#endif
+
+#if defined(Q_OS_MACOS)
+#include "ui/gfx/mac/io_surface.h"
+#endif
+
+QT_BEGIN_NAMESPACE
+class QQuickWindow;
+QT_END_NAMESPACE
+
+namespace gl {
+class GLFence;
+}
+
+namespace gfx {
+class GpuFence;
+class NativePixmap;
+}
+
+namespace gpu {
+class SharedImageFactory;
+class SharedImageRepresentationFactory;
+}
+
+namespace viz {
+class SkiaOutputSurfaceDependency;
+}
+
+namespace QtWebEngineCore {
+
+class NativeSkiaOutputDevice : public viz::SkiaOutputDevice, public Compositor
+{
+public:
+ NativeSkiaOutputDevice(scoped_refptr<gpu::SharedContextState> contextState,
+ bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker,
+ viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~NativeSkiaOutputDevice() override;
+
+ // Overridden from SkiaOutputDevice.
+ void SetFrameSinkId(const viz::FrameSinkId &frame_sink_id) override;
+ bool Reshape(const SkImageInfo &image_info,
+ const gfx::ColorSpace &color_space,
+ int sample_count,
+ float device_scale_factor,
+ gfx::OverlayTransform transform) override;
+ void Present(const absl::optional<gfx::Rect>& update_rect,
+ BufferPresentedCallback feedback,
+ viz::OutputSurfaceFrame frame) override;
+ void EnsureBackbuffer() override;
+ void DiscardBackbuffer() override;
+ SkSurface *BeginPaint(std::vector<GrBackendSemaphore> *semaphores) override;
+ void EndPaint() override;
+
+ // Overridden from Compositor.
+ void swapFrame() override;
+ void waitForTexture() override;
+ void releaseTexture() override;
+ void releaseResources() override;
+ bool textureIsFlipped() override;
+ QSize size() override;
+ bool requiresAlphaChannel() override;
+ float devicePixelRatio() override;
+
+protected:
+ struct Shape
+ {
+ SkImageInfo imageInfo;
+ float devicePixelRatio;
+ gfx::ColorSpace colorSpace;
+ int sampleCount;
+
+ bool operator==(const Shape &that) const
+ {
+ return (imageInfo == that.imageInfo &&
+ devicePixelRatio == that.devicePixelRatio &&
+ colorSpace == that.colorSpace &&
+ sampleCount == that.sampleCount);
+ }
+ bool operator!=(const Shape &that) const { return !(*this == that); }
+ };
+
+ class Buffer
+ {
+ public:
+ Buffer(NativeSkiaOutputDevice *parent);
+ ~Buffer();
+
+ bool initialize();
+ SkSurface *beginWriteSkia();
+ void endWriteSkia(bool force_flush);
+ std::vector<GrBackendSemaphore> takeEndWriteSkiaSemaphores();
+ void beginPresent();
+ void endPresent();
+ void freeTexture();
+ void createFence();
+ void consumeFence();
+
+ sk_sp<SkImage> skImage();
+#if defined(USE_OZONE)
+ scoped_refptr<gfx::NativePixmap> nativePixmap();
+#elif defined(Q_OS_WIN)
+ absl::optional<gl::DCLayerOverlayImage> overlayImage() const;
+#elif defined(Q_OS_MACOS)
+ gfx::ScopedIOSurface ioSurface() const;
+#endif
+
+ const Shape &shape() const { return m_shape; }
+ viz::SharedImageFormat sharedImageFormat() const { return m_skiaRepresentation->format(); }
+
+ std::function<void()> textureCleanupCallback;
+
+ private:
+ void createSkImageOnGPUThread();
+
+ NativeSkiaOutputDevice *m_parent;
+ Shape m_shape;
+ uint64_t m_estimatedSize = 0; // FIXME: estimate size
+ std::unique_ptr<gfx::GpuFence> m_acquireFence;
+ std::unique_ptr<gl::GLFence> m_fence;
+ gpu::Mailbox m_mailbox;
+ std::unique_ptr<gpu::SkiaImageRepresentation> m_skiaRepresentation;
+ std::unique_ptr<gpu::SkiaImageRepresentation::ScopedWriteAccess> m_scopedSkiaWriteAccess;
+ std::unique_ptr<gpu::SkiaImageRepresentation::ScopedReadAccess> m_scopedSkiaReadAccess;
+ std::unique_ptr<gpu::OverlayImageRepresentation> m_overlayRepresentation;
+ std::unique_ptr<gpu::OverlayImageRepresentation::ScopedReadAccess>
+ m_scopedOverlayReadAccess;
+ std::vector<GrBackendSemaphore> m_endSemaphores;
+ int m_presentCount = 0;
+
+ mutable QMutex m_skImageMutex;
+ sk_sp<SkImage> m_cachedSkImage;
+ };
+
+protected:
+ scoped_refptr<gpu::SharedContextState> m_contextState;
+ std::unique_ptr<Buffer> m_frontBuffer;
+ bool m_readyWithTexture = false;
+ bool m_isNativeBufferSupported = true;
+
+private:
+ friend class NativeSkiaOutputDevice::Buffer;
+
+ void SwapBuffersFinished();
+
+ mutable QMutex m_mutex;
+ Shape m_shape;
+ std::unique_ptr<Buffer> m_middleBuffer;
+ std::unique_ptr<Buffer> m_backBuffer;
+ viz::OutputSurfaceFrame m_frame;
+ bool m_readyToUpdate = false;
+ bool m_requiresAlpha;
+ scoped_refptr<base::SingleThreadTaskRunner> m_gpuTaskRunner;
+
+ const raw_ptr<gpu::SharedImageFactory> m_factory;
+ const raw_ptr<gpu::SharedImageRepresentationFactory> m_representationFactory;
+ const raw_ptr<viz::SkiaOutputSurfaceDependency> m_deps;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // !NATIVE_SKIA_OUTPUT_DEVICE_H
diff --git a/src/core/compositor/native_skia_output_device_direct3d11.cpp b/src/core/compositor/native_skia_output_device_direct3d11.cpp
new file mode 100644
index 000000000..352fa9f92
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_direct3d11.cpp
@@ -0,0 +1,88 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "native_skia_output_device_direct3d11.h"
+
+#include <QtCore/private/qsystemerror_p.h>
+#include <QtQuick/qquickwindow.h>
+#include <QtQuick/qsgtexture.h>
+
+#include <d3d11_1.h>
+
+namespace QtWebEngineCore {
+
+NativeSkiaOutputDeviceDirect3D11::NativeSkiaOutputDeviceDirect3D11(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : NativeSkiaOutputDevice(contextState, requiresAlpha, memoryTracker, dependency,
+ shared_image_factory, shared_image_representation_factory,
+ didSwapBufferCompleteCallback)
+{
+ SkColorType skColorType = kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] = skColorType;
+}
+
+NativeSkiaOutputDeviceDirect3D11::~NativeSkiaOutputDeviceDirect3D11() { }
+
+QSGTexture *NativeSkiaOutputDeviceDirect3D11::texture(QQuickWindow *win, uint32_t textureOptions)
+{
+ if (!m_frontBuffer || !m_readyWithTexture)
+ return nullptr;
+
+ absl::optional<gl::DCLayerOverlayImage> overlayImage = m_frontBuffer->overlayImage();
+ if (!overlayImage) {
+ qWarning("No overlay image.");
+ return nullptr;
+ }
+
+ QSGRendererInterface *ri = win->rendererInterface();
+
+ HRESULT status = S_OK;
+ HANDLE sharedHandle = nullptr;
+ IDXGIResource1 *resource = nullptr;
+ if (!overlayImage->nv12_texture()) {
+ qWarning("No D3D texture.");
+ return nullptr;
+ }
+ status = overlayImage->nv12_texture()->QueryInterface(__uuidof(IDXGIResource1),
+ (void **)&resource);
+ Q_ASSERT(status == S_OK);
+ status = resource->CreateSharedHandle(NULL, DXGI_SHARED_RESOURCE_READ, NULL, &sharedHandle);
+ Q_ASSERT(status == S_OK);
+ Q_ASSERT(sharedHandle);
+
+ // Pass texture between two D3D devices:
+ ID3D11Device1 *device = static_cast<ID3D11Device1 *>(
+ ri->getResource(win, QSGRendererInterface::DeviceResource));
+
+ ID3D11Texture2D *qtTexture;
+ status = device->OpenSharedResource1(sharedHandle, __uuidof(ID3D11Texture2D),
+ (void **)&qtTexture);
+ if (status != S_OK) {
+ qWarning("Failed to share D3D11 texture (%s). This will result in failed rendering. Report "
+ "the bug, and try restarting with QTWEBENGINE_CHROMIUM_FLAGS=--disble-gpu",
+ qPrintable(QSystemError::windowsComString(status)));
+ ::CloseHandle(sharedHandle);
+ return nullptr;
+ }
+
+ Q_ASSERT(qtTexture);
+ QQuickWindow::CreateTextureOptions texOpts(textureOptions);
+ QSGTexture *texture =
+ QNativeInterface::QSGD3D11Texture::fromNative(qtTexture, win, size(), texOpts);
+
+ m_frontBuffer->textureCleanupCallback = [qtTexture, sharedHandle]() {
+ qtTexture->Release();
+ ::CloseHandle(sharedHandle);
+ };
+
+ return texture;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/native_skia_output_device_direct3d11.h b/src/core/compositor/native_skia_output_device_direct3d11.h
new file mode 100644
index 000000000..33cf1bcd6
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_direct3d11.h
@@ -0,0 +1,28 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_SKIA_OUTPUT_DEVICE_DIRECT3D11_H
+#define NATIVE_SKIA_OUTPUT_DEVICE_DIRECT3D11_H
+
+#include "native_skia_output_device.h"
+
+namespace QtWebEngineCore {
+
+class NativeSkiaOutputDeviceDirect3D11 final : public NativeSkiaOutputDevice
+{
+public:
+ NativeSkiaOutputDeviceDirect3D11(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~NativeSkiaOutputDeviceDirect3D11() override;
+
+ // Overridden from Compositor:
+ QSGTexture *texture(QQuickWindow *win, uint32_t textureOptions) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // NATIVE_SKIA_OUTPUT_DEVICE_DIRECT3D11_H
diff --git a/src/core/compositor/native_skia_output_device_mac.mm b/src/core/compositor/native_skia_output_device_mac.mm
new file mode 100644
index 000000000..bf21ef8d7
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_mac.mm
@@ -0,0 +1,97 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// This is a workaround to be able to include Qt headers without
+// "redefinition of 'NSString' as different kind of symbol" errors.
+// TODO: Remove this when namespace ambiguity issues are fixed properly,
+// see get_forward_declaration_macro() in cmake/Functions.cmake
+#undef Q_FORWARD_DECLARE_OBJC_CLASS
+
+#import <AppKit/AppKit.h>
+#import <IOSurface/IOSurface.h>
+#import <Metal/Metal.h>
+
+#include <QtGui/qtguiglobal.h>
+#include <QtQuick/qquickwindow.h>
+#include <QtQuick/qsgrendererinterface.h>
+#include <QtQuick/qsgtexture.h>
+
+#if QT_CONFIG(opengl)
+#include <OpenGL/OpenGL.h>
+#include <QtGui/qopenglcontext.h>
+#include <QtGui/qopenglextrafunctions.h>
+#include <QtOpenGL/qopengltextureblitter.h>
+#include <QtOpenGL/qopenglframebufferobject.h>
+#endif
+
+namespace QtWebEngineCore {
+
+QSGTexture *makeMetalTexture(QQuickWindow *win, IOSurfaceRef ioSurface, uint ioSurfacePlane,
+ const QSize &size, QQuickWindow::CreateTextureOptions texOpts)
+{
+ auto desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:size.width()
+ height:size.height()
+ mipmapped:false];
+
+ QSGRendererInterface *ri = win->rendererInterface();
+ auto device = (__bridge id<MTLDevice>)(ri->getResource(win, QSGRendererInterface::DeviceResource));
+ id<MTLTexture> texture = [device newTextureWithDescriptor:desc
+ iosurface:ioSurface
+ plane:ioSurfacePlane];
+ return QNativeInterface::QSGMetalTexture::fromNative(texture, win, size, texOpts);
+}
+
+void releaseMetalTexture(void *texture)
+{
+ [static_cast<id<MTLTexture>>(texture) release];
+}
+
+#if QT_CONFIG(opengl)
+uint32_t makeCGLTexture(QQuickWindow *win, IOSurfaceRef ioSurface, const QSize &size)
+{
+ const int width = size.width();
+ const int height = size.height();
+
+ auto glContext = QOpenGLContext::currentContext();
+ auto glFun = glContext->extraFunctions();
+ auto nscontext = glContext->nativeInterface<QNativeInterface::QCocoaGLContext>()->nativeContext();
+ CGLContextObj cglContext = [nscontext CGLContextObj];
+
+ win->beginExternalCommands();
+ // Bind the IO surface to a texture
+ GLuint glTexture;
+ glFun->glGenTextures(1, &glTexture);
+ glFun->glBindTexture(GL_TEXTURE_RECTANGLE_ARB, glTexture);
+ CGLTexImageIOSurface2D(cglContext, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, width, height, GL_BGRA,
+ GL_UNSIGNED_INT_8_8_8_8_REV, ioSurface, 0);
+ glFun->glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
+ glFun->glViewport(0, 0, width, height);
+
+ // The bound IO surface is a weird dynamic bind, so take a snapshot of it to a normal texture
+ {
+ QOpenGLFramebufferObject fbo(width, height, GL_TEXTURE_2D);
+ auto success = fbo.bind();
+ Q_ASSERT(success);
+
+ QOpenGLTextureBlitter blitter;
+ success = blitter.create();
+ Q_ASSERT(success);
+ glFun->glDisable(GL_BLEND);
+ glFun->glDisable(GL_SCISSOR_TEST);
+ blitter.bind(GL_TEXTURE_RECTANGLE_ARB);
+ blitter.blit(glTexture, {}, QOpenGLTextureBlitter::OriginBottomLeft);
+ blitter.release();
+ blitter.destroy();
+
+ glFun->glDeleteTextures(1, &glTexture);
+ glTexture = fbo.takeTexture();
+ fbo.release();
+ }
+ win->endExternalCommands();
+
+ return glTexture;
+}
+#endif // QT_CONFIG(opengl)
+
+} // namespace
diff --git a/src/core/compositor/native_skia_output_device_metal.cpp b/src/core/compositor/native_skia_output_device_metal.cpp
new file mode 100644
index 000000000..a9d6e4fd5
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_metal.cpp
@@ -0,0 +1,66 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "native_skia_output_device_metal.h"
+
+#include <QtQuick/qquickwindow.h>
+#include <QtQuick/qsgtexture.h>
+
+namespace QtWebEngineCore {
+
+NativeSkiaOutputDeviceMetal::NativeSkiaOutputDeviceMetal(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : NativeSkiaOutputDevice(contextState, requiresAlpha, memoryTracker, dependency,
+ shared_image_factory, shared_image_representation_factory,
+ didSwapBufferCompleteCallback)
+{
+ SkColorType skColorType = kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] = skColorType;
+}
+
+NativeSkiaOutputDeviceMetal::~NativeSkiaOutputDeviceMetal() { }
+
+QSGTexture *makeMetalTexture(QQuickWindow *win, IOSurfaceRef ioSurface, uint ioSurfacePlane,
+ const QSize &size, QQuickWindow::CreateTextureOptions texOpts);
+void releaseMetalTexture(void *texture);
+
+QSGTexture *NativeSkiaOutputDeviceMetal::texture(QQuickWindow *win, uint32_t textureOptions)
+{
+ if (!m_frontBuffer || !m_readyWithTexture)
+ return nullptr;
+
+ gfx::ScopedIOSurface ioSurface = m_frontBuffer->ioSurface();
+ if (!ioSurface) {
+ qWarning("No IOSurface.");
+ return nullptr;
+ }
+
+ // This is a workaround to not to release metal texture too early.
+ // In RHI, QMetalTexture wraps MTLTexture. QMetalTexture seems to be only destructed after the
+ // next MTLTexture is imported. The "old" MTLTexture can be still pontentially used by RHI
+ // while QMetalTexture is not destructed. Metal Validation Layer also warns about it.
+ // Delay releasing MTLTexture after the next one is presented.
+ if (m_currentMetalTexture) {
+ m_frontBuffer->textureCleanupCallback = [texture = m_currentMetalTexture]() {
+ releaseMetalTexture(texture);
+ };
+ m_currentMetalTexture = nullptr;
+ }
+
+ QQuickWindow::CreateTextureOptions texOpts(textureOptions);
+ QSGTexture *qsgTexture = makeMetalTexture(win, ioSurface.get(), /* plane */ 0, size(), texOpts);
+
+ auto ni = qsgTexture->nativeInterface<QNativeInterface::QSGMetalTexture>();
+ m_currentMetalTexture = ni->nativeTexture();
+
+ return qsgTexture;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/native_skia_output_device_metal.h b/src/core/compositor/native_skia_output_device_metal.h
new file mode 100644
index 000000000..8e8d0fab8
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_metal.h
@@ -0,0 +1,31 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_SKIA_OUTPUT_DEVICE_METAL_H
+#define NATIVE_SKIA_OUTPUT_DEVICE_METAL_H
+
+#include "native_skia_output_device.h"
+
+namespace QtWebEngineCore {
+
+class NativeSkiaOutputDeviceMetal final : public NativeSkiaOutputDevice
+{
+public:
+ NativeSkiaOutputDeviceMetal(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~NativeSkiaOutputDeviceMetal() override;
+
+ // Overridden from Compositor:
+ QSGTexture *texture(QQuickWindow *win, uint32_t textureOptions) override;
+
+private:
+ void *m_currentMetalTexture = nullptr;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // NATIVE_SKIA_OUTPUT_DEVICE_METAL_H
diff --git a/src/core/compositor/native_skia_output_device_opengl.cpp b/src/core/compositor/native_skia_output_device_opengl.cpp
new file mode 100644
index 000000000..058573b9e
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_opengl.cpp
@@ -0,0 +1,86 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "native_skia_output_device_opengl.h"
+
+#include <QtGui/qopenglcontext.h>
+#include <QtGui/qopenglextrafunctions.h>
+#include <QtQuick/qquickwindow.h>
+#include <QtQuick/qsgtexture.h>
+
+namespace QtWebEngineCore {
+
+NativeSkiaOutputDeviceOpenGL::NativeSkiaOutputDeviceOpenGL(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : NativeSkiaOutputDevice(contextState, requiresAlpha, memoryTracker, dependency,
+ shared_image_factory, shared_image_representation_factory,
+ didSwapBufferCompleteCallback)
+{
+ SkColorType skColorType = kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] = skColorType;
+}
+
+NativeSkiaOutputDeviceOpenGL::~NativeSkiaOutputDeviceOpenGL() { }
+
+#if defined(Q_OS_MACOS)
+uint32_t makeCGLTexture(QQuickWindow *win, IOSurfaceRef ioSurface, const QSize &size);
+#endif
+
+QSGTexture *NativeSkiaOutputDeviceOpenGL::texture(QQuickWindow *win, uint32_t textureOptions)
+{
+ if (!m_frontBuffer || !m_readyWithTexture)
+ return nullptr;
+
+#if defined(USE_OZONE)
+ scoped_refptr<gfx::NativePixmap> nativePixmap = m_frontBuffer->nativePixmap();
+ if (!nativePixmap) {
+ qWarning("No native pixmap.");
+ return nullptr;
+ }
+#elif defined(Q_OS_WIN)
+ auto overlayImage = m_frontBuffer->overlayImage();
+ if (!overlayImage) {
+ qWarning("No overlay image.");
+ return nullptr;
+ }
+#elif defined(Q_OS_MACOS)
+ gfx::ScopedIOSurface ioSurface = m_frontBuffer->ioSurface();
+ if (!ioSurface) {
+ qWarning("No IOSurface.");
+ return nullptr;
+ }
+#endif
+
+ QQuickWindow::CreateTextureOptions texOpts(textureOptions);
+ QSGTexture *texture = nullptr;
+
+#if defined(USE_OZONE)
+ // TODO(QTBUG-112281): Add ANGLE support to Linux.
+ QT_NOT_YET_IMPLEMENTED
+#elif defined(Q_OS_WIN)
+ // TODO: Add WGL support over ANGLE.
+ QT_NOT_YET_IMPLEMENTED
+#elif defined(Q_OS_MACOS)
+ uint32_t glTexture = makeCGLTexture(win, ioSurface.get(), size());
+ texture = QNativeInterface::QSGOpenGLTexture::fromNative(glTexture, win, size(), texOpts);
+
+ m_frontBuffer->textureCleanupCallback = [glTexture]() {
+ auto *glContext = QOpenGLContext::currentContext();
+ if (!glContext)
+ return;
+ auto glFun = glContext->functions();
+ glFun->glDeleteTextures(1, &glTexture);
+ };
+#endif
+
+ return texture;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/native_skia_output_device_opengl.h b/src/core/compositor/native_skia_output_device_opengl.h
new file mode 100644
index 000000000..233f51df9
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_opengl.h
@@ -0,0 +1,28 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_SKIA_OUTPUT_DEVICE_OPENGL_H
+#define NATIVE_SKIA_OUTPUT_DEVICE_OPENGL_H
+
+#include "native_skia_output_device.h"
+
+namespace QtWebEngineCore {
+
+class NativeSkiaOutputDeviceOpenGL final : public NativeSkiaOutputDevice
+{
+public:
+ NativeSkiaOutputDeviceOpenGL(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~NativeSkiaOutputDeviceOpenGL() override;
+
+ // Overridden from Compositor:
+ QSGTexture *texture(QQuickWindow *win, uint32_t textureOptions) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // NATIVE_SKIA_OUTPUT_DEVICE_OPENGL_H
diff --git a/src/core/compositor/native_skia_output_device_vulkan.cpp b/src/core/compositor/native_skia_output_device_vulkan.cpp
new file mode 100644
index 000000000..c2ad7a382
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_vulkan.cpp
@@ -0,0 +1,306 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "native_skia_output_device_vulkan.h"
+
+#include "gpu/command_buffer/service/shared_image/shared_image_format_service_utils.h"
+
+#include <QtGui/qvulkaninstance.h>
+#include <QtGui/qvulkanfunctions.h>
+#include <QtQuick/qquickwindow.h>
+#include <QtQuick/qsgtexture.h>
+
+#if defined(USE_OZONE)
+#include "ui/ozone/buildflags.h"
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+// We need to define USE_VULKAN_XCB for proper vulkan function pointers.
+// Avoiding it may lead to call wrong vulkan functions.
+// This is originally defined in chromium/gpu/vulkan/BUILD.gn.
+#define USE_VULKAN_XCB
+#endif // BUILDFLAG(OZONE_PLATFORM_X11)
+#include "gpu/vulkan/vulkan_function_pointers.h"
+
+#include "components/viz/common/gpu/vulkan_context_provider.h"
+#include "gpu/vulkan/vulkan_device_queue.h"
+#endif // defined(USE_OZONE)
+
+namespace QtWebEngineCore {
+
+NativeSkiaOutputDeviceVulkan::NativeSkiaOutputDeviceVulkan(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback)
+ : NativeSkiaOutputDevice(contextState, requiresAlpha, memoryTracker, dependency,
+ shared_image_factory, shared_image_representation_factory,
+ didSwapBufferCompleteCallback)
+{
+ SkColorType skColorType = kRGBA_8888_SkColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRA_8888)] = skColorType;
+ capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] = skColorType;
+}
+
+NativeSkiaOutputDeviceVulkan::~NativeSkiaOutputDeviceVulkan() { }
+
+QSGTexture *NativeSkiaOutputDeviceVulkan::texture(QQuickWindow *win, uint32_t textureOptions)
+{
+ if (!m_frontBuffer || !m_readyWithTexture)
+ return nullptr;
+
+#if defined(USE_OZONE)
+ Q_ASSERT(m_contextState->gr_context_type() == gpu::GrContextType::kVulkan);
+
+ GrVkImageInfo vkImageInfo;
+ scoped_refptr<gfx::NativePixmap> nativePixmap = m_frontBuffer->nativePixmap();
+ if (!nativePixmap) {
+ if (m_isNativeBufferSupported) {
+ qWarning("VULKAN: No NativePixmap.");
+ return nullptr;
+ }
+
+ sk_sp<SkImage> skImage = m_frontBuffer->skImage();
+ if (!skImage) {
+ qWarning("VULKAN: No SkImage.");
+ return nullptr;
+ }
+
+ if (!skImage->isTextureBacked()) {
+ qWarning("VULKAN: SkImage is not backed by GPU texture.");
+ return nullptr;
+ }
+
+ GrBackendTexture backendTexture;
+ bool success = SkImages::GetBackendTextureFromImage(skImage, &backendTexture, false);
+ if (!success || !backendTexture.isValid()) {
+ qWarning("VULKAN: Failed to retrieve backend texture from SkImage.");
+ return nullptr;
+ }
+
+ if (backendTexture.backend() != GrBackendApi::kVulkan) {
+ qWarning("VULKAN: Backend texture is not a Vulkan texture.");
+ return nullptr;
+ }
+
+ backendTexture.getVkImageInfo(&vkImageInfo);
+ if (vkImageInfo.fAlloc.fMemory == VK_NULL_HANDLE) {
+ qWarning("VULKAN: Unable to access Vulkan memory.");
+ return nullptr;
+ }
+ }
+#elif defined(Q_OS_WIN)
+ Q_ASSERT(m_contextState->gr_context_type() == gpu::GrContextType::kGL);
+
+ absl::optional<gl::DCLayerOverlayImage> overlayImage = m_frontBuffer->overlayImage();
+ if (!overlayImage) {
+ qWarning("No overlay image.");
+ return nullptr;
+ }
+#endif
+
+ QSGRendererInterface *ri = win->rendererInterface();
+ VkDevice qtVulkanDevice =
+ *static_cast<VkDevice *>(ri->getResource(win, QSGRendererInterface::DeviceResource));
+ VkPhysicalDevice qtPhysicalDevice = *static_cast<VkPhysicalDevice *>(
+ ri->getResource(win, QSGRendererInterface::PhysicalDeviceResource));
+ QVulkanFunctions *f = win->vulkanInstance()->functions();
+ QVulkanDeviceFunctions *df = win->vulkanInstance()->deviceFunctions(qtVulkanDevice);
+
+ VkImageLayout imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
+ VkPhysicalDeviceProperties deviceProperties;
+ f->vkGetPhysicalDeviceProperties(qtPhysicalDevice, &deviceProperties);
+ if (deviceProperties.vendorID == 0x10DE) {
+ // FIXME: This is a workaround for Nvidia driver.
+ // The imported image is empty if the initialLayout is not
+ // VK_IMAGE_LAYOUT_PREINITIALIZED.
+ imageLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
+ }
+
+ VkExternalMemoryImageCreateInfoKHR externalMemoryImageCreateInfo = {
+ VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR
+ };
+#if defined(USE_OZONE)
+ VkSubresourceLayout planeLayout = {};
+ VkImageDrmFormatModifierExplicitCreateInfoEXT modifierInfo = {
+ VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT
+ };
+ base::ScopedFD scopedFd;
+
+ if (nativePixmap) {
+ gfx::NativePixmapHandle nativePixmapHandle = nativePixmap->ExportHandle();
+ if (nativePixmapHandle.planes.size() != 1)
+ qFatal("VULKAN: Multiple planes are not supported.");
+
+ planeLayout.offset = nativePixmapHandle.planes[0].offset;
+ planeLayout.size = 0;
+ planeLayout.rowPitch = nativePixmapHandle.planes[0].stride;
+ planeLayout.arrayPitch = 0;
+ planeLayout.depthPitch = 0;
+
+ modifierInfo.drmFormatModifier = nativePixmapHandle.modifier;
+ modifierInfo.drmFormatModifierPlaneCount = 1;
+ modifierInfo.pPlaneLayouts = &planeLayout;
+
+ externalMemoryImageCreateInfo.pNext = &modifierInfo;
+ externalMemoryImageCreateInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+
+ scopedFd = std::move(nativePixmapHandle.planes[0].fd);
+ } else {
+ externalMemoryImageCreateInfo.pNext = nullptr;
+ externalMemoryImageCreateInfo.handleTypes =
+ VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
+
+ VkMemoryGetFdInfoKHR exportInfo = { VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR };
+ exportInfo.pNext = nullptr;
+ exportInfo.memory = vkImageInfo.fAlloc.fMemory;
+ exportInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
+
+ gpu::VulkanFunctionPointers *vfp = gpu::GetVulkanFunctionPointers();
+ gpu::VulkanDeviceQueue *vulkanDeviceQueue =
+ m_contextState->vk_context_provider()->GetDeviceQueue();
+ VkDevice vulkanDevice = vulkanDeviceQueue->GetVulkanDevice();
+
+ int fd = -1;
+ if (vfp->vkGetMemoryFdKHR(vulkanDevice, &exportInfo, &fd) != VK_SUCCESS)
+ qFatal("VULKAN: Unable to extract file descriptor out of external VkImage.");
+
+ scopedFd.reset(fd);
+ }
+
+ if (!scopedFd.is_valid())
+ qFatal("VULKAN: Unable to extract file descriptor.");
+#elif defined(Q_OS_WIN)
+ externalMemoryImageCreateInfo.pNext = nullptr;
+ externalMemoryImageCreateInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT;
+
+ HRESULT status = S_OK;
+ HANDLE sharedHandle = nullptr;
+ IDXGIResource1 *resource = nullptr;
+ if (!overlayImage->nv12_texture()) {
+ qWarning("VULKAN: No D3D texture.");
+ return nullptr;
+ }
+ status = overlayImage->nv12_texture()->QueryInterface(__uuidof(IDXGIResource1),
+ (void **)&resource);
+ Q_ASSERT(status == S_OK);
+ status = resource->CreateSharedHandle(NULL, DXGI_SHARED_RESOURCE_READ, NULL, &sharedHandle);
+ Q_ASSERT(status == S_OK);
+
+ if (!sharedHandle)
+ qFatal("VULKAN: Unable to extract shared handle.");
+#endif
+
+ constexpr VkImageUsageFlags kUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
+ | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT
+ | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+
+ VkImageCreateInfo importedImageCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
+ importedImageCreateInfo.pNext = &externalMemoryImageCreateInfo;
+ importedImageCreateInfo.flags = 0;
+ importedImageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
+ importedImageCreateInfo.format = gpu::ToVkFormat(m_frontBuffer->sharedImageFormat());
+ importedImageCreateInfo.extent.width = static_cast<uint32_t>(size().width());
+ importedImageCreateInfo.extent.height = static_cast<uint32_t>(size().height());
+ importedImageCreateInfo.extent.depth = 1;
+ importedImageCreateInfo.mipLevels = 1;
+ importedImageCreateInfo.arrayLayers = 1;
+ importedImageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
+ importedImageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
+ importedImageCreateInfo.usage = kUsage;
+ importedImageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
+ importedImageCreateInfo.queueFamilyIndexCount = 0;
+ importedImageCreateInfo.pQueueFamilyIndices = nullptr;
+ importedImageCreateInfo.initialLayout = imageLayout;
+
+#if defined(USE_OZONE)
+ if (nativePixmap)
+ importedImageCreateInfo.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
+ else
+ importedImageCreateInfo.tiling = vkImageInfo.fImageTiling;
+#endif
+
+ VkResult result;
+ VkImage importedImage = VK_NULL_HANDLE;
+ result = df->vkCreateImage(qtVulkanDevice, &importedImageCreateInfo, nullptr /* pAllocator */,
+ &importedImage);
+ if (result != VK_SUCCESS)
+ qFatal() << "VULKAN: vkCreateImage failed result:" << result;
+
+#if defined(USE_OZONE)
+ VkImportMemoryFdInfoKHR importMemoryHandleInfo = {
+ VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR
+ };
+ importMemoryHandleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
+ importMemoryHandleInfo.fd = scopedFd.release();
+
+ if (nativePixmap)
+ importMemoryHandleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+#elif defined(Q_OS_WIN)
+ VkImportMemoryWin32HandleInfoKHR importMemoryHandleInfo = {
+ VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR
+ };
+ importMemoryHandleInfo.pNext = nullptr;
+ importMemoryHandleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT;
+ importMemoryHandleInfo.handle = sharedHandle;
+#endif
+
+ VkMemoryDedicatedAllocateInfoKHR dedicatedMemoryInfo = {
+ VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR
+ };
+ dedicatedMemoryInfo.pNext = &importMemoryHandleInfo;
+ dedicatedMemoryInfo.image = importedImage;
+
+ VkMemoryAllocateInfo memoryAllocateInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
+ memoryAllocateInfo.pNext = &dedicatedMemoryInfo;
+
+ VkMemoryRequirements requirements;
+ df->vkGetImageMemoryRequirements(qtVulkanDevice, importedImage, &requirements);
+ if (!requirements.memoryTypeBits)
+ qFatal("VULKAN: vkGetImageMemoryRequirements failed.");
+
+ VkPhysicalDeviceMemoryProperties memoryProperties;
+ f->vkGetPhysicalDeviceMemoryProperties(qtPhysicalDevice, &memoryProperties);
+ constexpr VkMemoryPropertyFlags flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
+ constexpr uint32_t kMaxIndex = 31;
+ uint32_t memoryTypeIndex = kMaxIndex + 1;
+ for (uint32_t i = 0; i <= kMaxIndex; i++) {
+ if (((1u << i) & requirements.memoryTypeBits) == 0)
+ continue;
+ if ((memoryProperties.memoryTypes[i].propertyFlags & flags) != flags)
+ continue;
+ memoryTypeIndex = i;
+ break;
+ }
+
+ if (memoryTypeIndex > kMaxIndex)
+ qFatal("VULKAN: Cannot find valid memory type index.");
+
+ memoryAllocateInfo.allocationSize = requirements.size;
+ memoryAllocateInfo.memoryTypeIndex = memoryTypeIndex;
+
+ VkDeviceMemory importedImageMemory = VK_NULL_HANDLE;
+ result = df->vkAllocateMemory(qtVulkanDevice, &memoryAllocateInfo, nullptr /* pAllocator */,
+ &importedImageMemory);
+ if (result != VK_SUCCESS)
+ qFatal() << "VULKAN: vkAllocateMemory failed result:" << result;
+
+ df->vkBindImageMemory(qtVulkanDevice, importedImage, importedImageMemory, 0);
+
+ QQuickWindow::CreateTextureOptions texOpts(textureOptions);
+ QSGTexture *texture = QNativeInterface::QSGVulkanTexture::fromNative(importedImage, imageLayout,
+ win, size(), texOpts);
+
+ m_frontBuffer->textureCleanupCallback = [=]() {
+ df->vkDestroyImage(qtVulkanDevice, importedImage, nullptr);
+ df->vkFreeMemory(qtVulkanDevice, importedImageMemory, nullptr);
+#if defined(Q_OS_WIN)
+ ::CloseHandle(sharedHandle);
+#endif
+ };
+
+ return texture;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/compositor/native_skia_output_device_vulkan.h b/src/core/compositor/native_skia_output_device_vulkan.h
new file mode 100644
index 000000000..bead0cc11
--- /dev/null
+++ b/src/core/compositor/native_skia_output_device_vulkan.h
@@ -0,0 +1,28 @@
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_SKIA_OUTPUT_DEVICE_VULKAN_H
+#define NATIVE_SKIA_OUTPUT_DEVICE_VULKAN_H
+
+#include "native_skia_output_device.h"
+
+namespace QtWebEngineCore {
+
+class NativeSkiaOutputDeviceVulkan final : public NativeSkiaOutputDevice
+{
+public:
+ NativeSkiaOutputDeviceVulkan(
+ scoped_refptr<gpu::SharedContextState> contextState, bool requiresAlpha,
+ gpu::MemoryTracker *memoryTracker, viz::SkiaOutputSurfaceDependency *dependency,
+ gpu::SharedImageFactory *shared_image_factory,
+ gpu::SharedImageRepresentationFactory *shared_image_representation_factory,
+ DidSwapBufferCompleteCallback didSwapBufferCompleteCallback);
+ ~NativeSkiaOutputDeviceVulkan() override;
+
+ // Overridden from Compositor:
+ QSGTexture *texture(QQuickWindow *win, uint32_t textureOptions) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // NATIVE_SKIA_OUTPUT_DEVICE_VULKAN_H
diff --git a/src/core/compositor/vulkan_implementation_qt.cpp b/src/core/compositor/vulkan_implementation_qt.cpp
new file mode 100644
index 000000000..2f2259666
--- /dev/null
+++ b/src/core/compositor/vulkan_implementation_qt.cpp
@@ -0,0 +1,162 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "vulkan_implementation_qt.h"
+
+#include "base/environment.h"
+#include "base/logging.h"
+#include "gpu/vulkan/vulkan_image.h"
+#include "gpu/vulkan/vulkan_surface.h"
+#include "gpu/vulkan/vulkan_util.h"
+#include "ui/gfx/gpu_fence.h"
+
+#include <vulkan/vulkan.h>
+
+namespace gpu {
+
+VulkanImplementationQt::VulkanImplementationQt() : VulkanImplementation(false) { }
+
+VulkanImplementationQt::~VulkanImplementationQt() = default;
+
+bool VulkanImplementationQt::InitializeVulkanInstance(bool /*using_surface*/)
+{
+ std::vector<const char *> required_extensions = {
+ VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
+ VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
+ };
+
+ auto env = base::Environment::Create();
+ std::string vulkan_path;
+ if (!env->GetVar("QT_VULKAN_LIB", &vulkan_path)) {
+#if BUILDFLAG(IS_WIN)
+ vulkan_path = "vulkan-1.dll";
+#else
+ vulkan_path = "libvulkan.so.1";
+#endif
+ }
+
+ if (!vulkan_instance_.Initialize(base::FilePath::FromUTF8Unsafe(vulkan_path),
+ required_extensions, {})) {
+ LOG(ERROR) << "Failed to initialize vulkan instance";
+ return false;
+ }
+
+ return true;
+}
+
+VulkanInstance *VulkanImplementationQt::GetVulkanInstance()
+{
+ return &vulkan_instance_;
+}
+
+std::unique_ptr<VulkanSurface>
+VulkanImplementationQt::CreateViewSurface(gfx::AcceleratedWidget /*window*/)
+{
+ NOTREACHED();
+ return nullptr;
+}
+
+bool VulkanImplementationQt::GetPhysicalDevicePresentationSupport(
+ VkPhysicalDevice /*device*/,
+ const std::vector<VkQueueFamilyProperties> & /*queue_family_properties*/,
+ uint32_t /*queue_family_index*/)
+{
+ NOTREACHED();
+ return true;
+}
+
+std::vector<const char *> VulkanImplementationQt::GetRequiredDeviceExtensions()
+{
+ return {
+ VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
+#if BUILDFLAG(IS_WIN)
+ VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME,
+#else
+ VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
+#endif
+ };
+}
+
+std::vector<const char *> VulkanImplementationQt::GetOptionalDeviceExtensions()
+{
+ return {
+ VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
+#if BUILDFLAG(IS_WIN)
+ VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME,
+#else
+ VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
+ VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME,
+ VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
+ VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,
+#endif
+ };
+}
+
+VkFence VulkanImplementationQt::CreateVkFenceForGpuFence(VkDevice /*vk_device*/)
+{
+ NOTREACHED();
+ return VK_NULL_HANDLE;
+}
+
+std::unique_ptr<gfx::GpuFence>
+VulkanImplementationQt::ExportVkFenceToGpuFence(VkDevice /*vk_device*/, VkFence /*vk_fence*/)
+{
+ NOTREACHED();
+ return nullptr;
+}
+
+VkSemaphore VulkanImplementationQt::ImportSemaphoreHandle(VkDevice vk_device,
+ SemaphoreHandle sync_handle)
+{
+ return ImportVkSemaphoreHandle(vk_device, std::move(sync_handle));
+}
+
+VkExternalSemaphoreHandleTypeFlagBits VulkanImplementationQt::GetExternalSemaphoreHandleType()
+{
+#if BUILDFLAG(IS_WIN)
+ return VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT;
+#else
+ return VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
+#endif
+}
+
+bool VulkanImplementationQt::CanImportGpuMemoryBuffer(
+ VulkanDeviceQueue *device_queue,
+ gfx::GpuMemoryBufferType memory_buffer_type)
+{
+#if BUILDFLAG(IS_LINUX)
+ const auto &enabled_extensions = device_queue->enabled_extensions();
+ return gfx::HasExtension(enabled_extensions,
+ VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME) &&
+ gfx::HasExtension(enabled_extensions,
+ VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) &&
+ memory_buffer_type == gfx::GpuMemoryBufferType::NATIVE_PIXMAP;
+#else
+ return false;
+#endif
+}
+
+std::unique_ptr<VulkanImage> VulkanImplementationQt::CreateImageFromGpuMemoryHandle(VulkanDeviceQueue *device_queue,
+ gfx::GpuMemoryBufferHandle gmb_handle,
+ gfx::Size size,
+ VkFormat vk_format,
+ const gfx::ColorSpace &)
+{
+#if BUILDFLAG(IS_LINUX)
+ constexpr auto kUsage =
+ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
+ VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ auto tiling = gmb_handle.native_pixmap_handle.modifier ==
+ gfx::NativePixmapHandle::kNoModifier
+ ? VK_IMAGE_TILING_OPTIMAL
+ : VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
+ return gpu::VulkanImage::CreateFromGpuMemoryBufferHandle(
+ device_queue, std::move(gmb_handle), size, vk_format, kUsage, /*flags=*/0,
+ tiling, VK_QUEUE_FAMILY_EXTERNAL);
+#else
+ NOTIMPLEMENTED();
+ return nullptr;
+#endif
+}
+
+} // namespace gpu
diff --git a/src/core/compositor/vulkan_implementation_qt.h b/src/core/compositor/vulkan_implementation_qt.h
new file mode 100644
index 000000000..88983331f
--- /dev/null
+++ b/src/core/compositor/vulkan_implementation_qt.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef VULKAN_IMPLEMENTATION_QT_H
+#define VULKAN_IMPLEMENTATION_QT_H
+
+#include "gpu/vulkan/vulkan_implementation.h"
+#include "gpu/vulkan/vulkan_instance.h"
+
+namespace gpu {
+
+class VulkanImplementationQt : public VulkanImplementation
+{
+public:
+ VulkanImplementationQt();
+ ~VulkanImplementationQt() override;
+
+ // Overridden from VulkanImplementation.
+ bool InitializeVulkanInstance(bool using_surface) override;
+ VulkanInstance *GetVulkanInstance() override;
+ std::unique_ptr<VulkanSurface> CreateViewSurface(gfx::AcceleratedWidget window) override;
+ bool GetPhysicalDevicePresentationSupport(
+ VkPhysicalDevice device,
+ const std::vector<VkQueueFamilyProperties> &queue_family_properties,
+ uint32_t queue_family_index) override;
+ std::vector<const char *> GetRequiredDeviceExtensions() override;
+ std::vector<const char *> GetOptionalDeviceExtensions() override;
+ VkFence CreateVkFenceForGpuFence(VkDevice vk_device) override;
+ std::unique_ptr<gfx::GpuFence> ExportVkFenceToGpuFence(VkDevice vk_device,
+ VkFence vk_fence) override;
+ VkSemaphore ImportSemaphoreHandle(VkDevice vk_device, SemaphoreHandle handle) override;
+ VkExternalSemaphoreHandleTypeFlagBits GetExternalSemaphoreHandleType() override;
+ bool CanImportGpuMemoryBuffer(VulkanDeviceQueue* device_queue,
+ gfx::GpuMemoryBufferType memory_buffer_type) override;
+ std::unique_ptr<VulkanImage> CreateImageFromGpuMemoryHandle(VulkanDeviceQueue *device_queue,
+ gfx::GpuMemoryBufferHandle gmb_handle,
+ gfx::Size size, VkFormat vk_format,
+ const gfx::ColorSpace &color_space) override;
+
+private:
+ VulkanInstance vulkan_instance_;
+};
+
+} // namespace gpu
+
+#endif // VULKAN_IMPLEMENTATION_QT_H
diff --git a/src/core/config/common.pri b/src/core/config/common.pri
deleted file mode 100644
index c1658ce82..000000000
--- a/src/core/config/common.pri
+++ /dev/null
@@ -1,50 +0,0 @@
-
-qtConfig(webengine-printing-and-pdf) {
- gn_args += enable_basic_printing=true enable_print_preview=true
- gn_args += enable_pdf=true
-} else {
- gn_args += enable_basic_printing=false enable_print_preview=false
- gn_args += enable_pdf=false
-}
-
-qtConfig(webengine-pepper-plugins) {
- gn_args += enable_plugins=true
-} else {
- gn_args += enable_plugins=false
-}
-
-qtConfig(webengine-spellchecker) {
- gn_args += enable_spellcheck=true
-} else {
- gn_args += enable_spellcheck=false
-}
-
-qtConfig(webengine-webrtc) {
- gn_args += enable_webrtc=true
-} else {
- gn_args += enable_webrtc=false audio_processing_in_audio_service_supported=false
-}
-
-qtConfig(webengine-proprietary-codecs) {
- gn_args += proprietary_codecs=true ffmpeg_branding=\"Chrome\"
-} else {
- gn_args += proprietary_codecs=false
-}
-
-qtConfig(webengine-extensions) {
- gn_args += enable_extensions=true
-} else {
- gn_args += enable_extensions=false
-}
-
-qtConfig(webengine-kerberos) {
- gn_args += use_kerberos=true
-} else {
- gn_args += use_kerberos=false
-}
-
-qtConfig(webengine-nodejs) {
- gn_args += have_nodejs=true
-} else {
- gn_args += have_nodejs=false
-}
diff --git a/src/core/config/linux.pri b/src/core/config/linux.pri
deleted file mode 100644
index e98524002..000000000
--- a/src/core/config/linux.pri
+++ /dev/null
@@ -1,47 +0,0 @@
-include(common.pri)
-
-qtConfig(webengine-embedded-build) {
- gn_args += is_desktop_linux=false
-}
-
-!host_build{
-
-
-
- qtConfig(webengine-pulseaudio) {
- gn_args += use_pulseaudio=true
- } else {
- gn_args += use_pulseaudio=false
- }
-
- qtConfig(webengine-alsa) {
- gn_args += use_alsa=true
- } else {
- gn_args += use_alsa=false
- }
-
- !packagesExist(libpci): gn_args += use_libpci=false
-
- qtConfig(webengine-ozone-x11) {
- gn_args += ozone_platform_x11=true
- gn_args += use_xkbcommon=true
- packagesExist(xscrnsaver): gn_args += use_xscrnsaver=true
- qtConfig(webengine-webrtc): gn_args += rtc_use_x11=true
- }
-
- qtConfig(webengine-system-libevent): gn_args += use_system_libevent=true
- qtConfig(webengine-system-libwebp): gn_args += use_system_libwebp=true
- qtConfig(webengine-system-libxml2): gn_args += use_system_libxml=true use_system_libxslt=true
- qtConfig(webengine-system-opus): gn_args += use_system_opus=true
- qtConfig(webengine-system-snappy): gn_args += use_system_snappy=true
- qtConfig(webengine-system-libvpx): gn_args += use_system_libvpx=true
- qtConfig(webengine-system-icu): gn_args += use_system_icu=true icu_use_data_file=false
- qtConfig(webengine-system-ffmpeg): gn_args += use_system_ffmpeg=true
- qtConfig(webengine-system-re2): gn_args += use_system_re2=true
- qtConfig(webengine-system-lcms2): gn_args += use_system_lcms2=true
-
- # FIXME:
- #qtConfig(webengine-system-protobuf): gn_args += use_system_protobuf=true
- #qtConfig(webengine-system-jsoncpp): gn_args += use_system_jsoncpp=true
- #qtConfig(webengine-system-libsrtp: gn_args += use_system_libsrtp=true
-}
diff --git a/src/core/config/mac_osx.pri b/src/core/config/mac_osx.pri
deleted file mode 100644
index 9543daf90..000000000
--- a/src/core/config/mac_osx.pri
+++ /dev/null
@@ -1,8 +0,0 @@
-include(common.pri)
-
-qtConfig(build-qtwebengine-core):qtConfig(webengine-spellchecker) {
- qtConfig(webengine-native-spellchecker): gn_args += use_browser_spellchecker=true
- else: gn_args += use_browser_spellchecker=false
-} else {
- gn_args += use_browser_spellchecker=false
-}
diff --git a/src/core/config/windows.pri b/src/core/config/windows.pri
deleted file mode 100644
index 9543daf90..000000000
--- a/src/core/config/windows.pri
+++ /dev/null
@@ -1,8 +0,0 @@
-include(common.pri)
-
-qtConfig(build-qtwebengine-core):qtConfig(webengine-spellchecker) {
- qtConfig(webengine-native-spellchecker): gn_args += use_browser_spellchecker=true
- else: gn_args += use_browser_spellchecker=false
-} else {
- gn_args += use_browser_spellchecker=false
-}
diff --git a/src/core/configure.json b/src/core/configure.json
deleted file mode 100644
index 1a2162723..000000000
--- a/src/core/configure.json
+++ /dev/null
@@ -1,313 +0,0 @@
-{
- "module": "webenginecore",
- "depends": [
- "buildtools-private",
- "core-private",
- "gui-private",
- "printsupport"
- ],
- "condition": "module.gui && features.build-qtwebengine-core && features.webengine-core-support",
- "testDir": "../../config.tests",
- "commandline": {
- "options": {
- "webengine-alsa": "boolean",
- "webengine-embedded-build": "boolean",
- "webengine-full-debug-info": "boolean",
- "webengine-icu": { "type": "enum", "name": "webengine-system-icu", "values": { "system": "yes", "qt": "no" } },
- "webengine-ffmpeg": { "type": "enum", "name": "webengine-system-ffmpeg", "values": { "system": "yes", "qt": "no" } },
- "webengine-opus": { "type": "enum", "name": "webengine-system-opus", "values": { "system": "yes", "qt": "no" } },
- "webengine-webp": { "type": "enum", "name": "webengine-system-libwebp", "values": { "system": "yes", "qt": "no" } },
- "webengine-pepper-plugins": "boolean",
- "webengine-printing-and-pdf": "boolean",
- "webengine-proprietary-codecs": "boolean",
- "webengine-pulseaudio": "boolean",
- "webengine-spellchecker": "boolean",
- "webengine-native-spellchecker": "boolean",
- "webengine-extensions": "boolean",
- "webengine-webrtc": "boolean",
- "webengine-geolocation": "boolean",
- "webengine-webchannel": "boolean",
- "webengine-kerberos": "boolean",
- "alsa": { "type": "boolean", "name": "webengine-alsa" },
- "pulseaudio": { "type": "boolean", "name": "webengine-pulseaudio" },
- "ffmpeg": { "type": "enum", "name": "webengine-system-ffmpeg", "values": { "system": "yes", "qt": "no" } },
- "opus": { "type": "enum", "name": "webengine-system-opus", "values": { "system": "yes", "qt": "no" } },
- "webp": { "type": "enum", "name": "webengine-system-libwebp", "values": { "system": "yes", "qt": "no" } },
- "pepper-plugins": { "type": "boolean", "name": "webengine-pepper-plugins" },
- "printing-and-pdf": { "type": "boolean", "name": "webengine-printing-and-pdf" },
- "proprietary-codecs": { "type": "boolean", "name": "webengine-proprietary-codecs" },
- "spellchecker": { "type": "boolean", "name": "webengine-spellchecker" },
- "extensions": { "type": "boolean", "name": "webengine-extensions" },
- "webrtc": { "type": "boolean", "name": "webengine-webrtc" }
- }
- },
-
- "libraries": {
- "webengine-alsa": {
- "label": "alsa",
- "test": {
- "tail": [
- "#if SND_LIB_VERSION < 0x1000a // 1.0.10",
- "#error Alsa version found too old, require >= 1.0.10",
- "#endif"
- ]
- },
- "headers" : ["alsa/asoundlib.h"],
- "sources" : [{ "type": "pkgConfig", "args": "alsa" }
- ]
- },
- "webengine-poppler-cpp": {
- "label": "poppler-cpp",
- "sources": [
- { "type": "pkgConfig", "args": "poppler-cpp" }
- ]
- },
- "webengine-pulseaudio": {
- "label": "pulseaudio >= 0.9.10",
- "sources": [
- { "type": "pkgConfig", "args": "libpulse >= 0.9.10 libpulse-mainloop-glib" }
- ]
- }
- },
- "tests" : {
- "webengine-host-compiler": {
- "label": "host compiler",
- "test": "hostcompiler",
- "host": "true",
- "type": "compile"
- },
- "webengine-host-pkg-config": {
- "label": "host pkg-config",
- "type": "detectHostPkgConfig",
- "log": "path"
- },
- "webengine-embedded-build": {
- "label": "embedded build",
- "type": "detectEmbedded"
- },
- "webengine-noexecstack" : {
- "label": "linker supports -z noexecstack",
- "type": "linkerSupportsFlag",
- "flag": "-z,noexecstack"
- },
- "webengine-nodejs": {
- "label": "node.js",
- "type": "detectNodeJS"
- }
- },
- "features": {
- "webengine-embedded-build": {
- "label": "Embedded build",
- "purpose": "Enables the embedded build configuration.",
- "condition": "config.unix",
- "autoDetect": "tests.webengine-embedded-build",
- "output": [ "privateFeature" ]
- },
- "webengine-alsa": {
- "label": "Use ALSA",
- "condition": "config.unix && libs.webengine-alsa",
- "output": [ "privateFeature" ]
- },
- "webengine-v8-snapshot-support": {
- "label" : "Building v8 snapshot supported",
- "condition": "!config.unix || !features.cross_compile || arch.arm64 || tests.webengine-host-compiler",
- "output": [ "privateFeature" ]
- },
- "webengine-geolocation": {
- "label": "Geolocation",
- "condition": "module.positioning",
- "output": [ "publicFeature" ]
- },
- "webengine-pulseaudio": {
- "label": "Use PulseAudio",
- "autoDetect": "config.unix",
- "condition": "libs.webengine-pulseaudio",
- "output": [ "privateFeature" ]
- },
- "webengine-pepper-plugins": {
- "label": "Pepper Plugins",
- "purpose": "Enables use of Pepper Flash plugins.",
- "autoDetect": "!features.webengine-embedded-build",
- "output": [ "privateFeature" ]
- },
- "webengine-printing-and-pdf": {
- "label": "Printing and PDF",
- "purpose": "Provides printing and output to PDF.",
- "condition": "module.printsupport && features.printer",
- "autoDetect": "!features.webengine-embedded-build",
- "output": [ "privateFeature" ]
- },
- "webengine-webchannel": {
- "label": "WebChannel support",
- "purpose": "Provides QtWebChannel integration.",
- "section": "WebEngine",
- "condition": "module.webchannel",
- "output": [ "publicFeature" ]
- },
- "webengine-proprietary-codecs": {
- "label": "Proprietary Codecs",
- "purpose": "Enables the use of proprietary codecs such as h.264/h.265 and MP3.",
- "autoDetect": false,
- "output": [ "privateFeature" ]
- },
- "webengine-kerberos": {
- "label": "Kerberos Authentication",
- "purpose": "Enables Kerberos Authentication Support",
- "autoDetect": "config.win32",
- "section": "WebEngine",
- "output": [ "privateFeature" ]
- },
- "webengine-spellchecker": {
- "label": "Spellchecker",
- "purpose": "Provides a spellchecker.",
- "output": [ "publicFeature" ]
- },
- "webengine-native-spellchecker": {
- "label": "Native Spellchecker",
- "purpose": "Use the system's native spellchecking engine.",
- "autoDetect": false,
- "condition": "config.macos && features.webengine-spellchecker",
- "output": [ "publicFeature" ]
- },
- "webengine-extensions": {
- "label": "Extensions",
- "purpose": "Enables Chromium extensions within certain limits. Currently used for enabling the pdf viewer.",
- "section": "WebEngine",
- "condition": "features.webengine-printing-and-pdf",
- "autoDetect": "features.webengine-printing-and-pdf",
- "output": [ "publicFeature" ]
- },
- "webengine-webrtc": {
- "label": "WebRTC",
- "purpose": "Provides WebRTC support.",
- "autoDetect": "!features.webengine-embedded-build",
- "output": [ "privateFeature" ]
- },
- "webengine-ozone" : {
- "label": "Support qpa-xcb",
- "condition": "features.webengine-ozone-x11",
- "output": [ "privateFeature" ]
- },
- "webengine-poppler-cpp": {
- "label": "poppler-cpp",
- "autoDetect": "config.unix",
- "condition": "libs.webengine-poppler-cpp",
- "output": [ "privateFeature" ]
- },
- "webengine-full-debug-info": {
- "label": "Full debug information",
- "purpose": "Enables debug information for Blink and V8.",
- "autoDetect": false,
- "condition": "config.debug || features.debug_and_release || features.force_debug_info",
- "output": [
- { "type": "privateConfig", "name": "v8base_debug" },
- { "type": "privateConfig", "name": "webcore_debug" }
- ]
- },
- "webengine-noexecstack": {
- "label": "linker supports -z noexecstack",
- "condition": "config.unix && tests.webengine-noexecstack",
- "output": [ "privateFeature" ]
- },
- "webengine-nodejs": {
- "label": "Node.js",
- "condition": "tests.webengine-nodejs",
- "output": [ "privateFeature" ]
- }
- },
-
- "report": [
- {
- "type": "warning",
- "condition": "config.unix && !features.webengine-host-pkg-config",
- "message": "host pkg-config not found"
- },
- {
- "type": "warning",
- "condition": "config.linux && features.webengine-embedded-build && !features.webengine-system-ffmpeg && arch.arm && !features.webengine-arm-thumb",
- "message": "Thumb instruction set is required to build ffmpeg for QtWebEngine."
- },
- {
- "type": "warning",
- "condition": "config.unix && config.cross_compile && !features.webengine-v8-snapshot-support",
- "message": "V8 snapshot cannot be built. Most likely, the 32-bit host compiler does not work. Please make sure you have 32-bit devel environment installed."
- },
- {
- "type": "warning",
- "condition": "!features.webengine-nodejs",
- "message": "Building without node.js will disable some features of QtWebEngine DevTools."
- }
- ],
-
- "summary": [
- {
- "section": "Qt WebEngineCore",
- "condition": "features.build-qtwebengine-core",
- "entries": [
- "webengine-embedded-build",
- "webengine-full-debug-info",
- "webengine-pepper-plugins",
- "webengine-printing-and-pdf",
- "webengine-proprietary-codecs",
- "webengine-spellchecker",
- "webengine-native-spellchecker",
- "webengine-webrtc",
- "webengine-geolocation",
- "webengine-webchannel",
- "webengine-kerberos",
- "webengine-extensions",
- "webengine-nodejs",
- {
- "type": "feature",
- "args": "webengine-ozone",
- "condition": "config.unix"
- },
- {
- "type": "feature",
- "args": "webengine-v8-snapshot-support",
- "condition": "config.unix && config.cross_compile"
- },
- {
- "type": "feature",
- "args": "webengine-alsa",
- "condition": "config.unix"
- },
- {
- "type": "feature",
- "args": "webengine-pulseaudio",
- "condition": "config.unix"
- },
- {
- "message": "macOS version",
- "type": "macosToolchainVersion",
- "args": "macosVersion",
- "condition": "config.macos"
- },
- {
- "message": "Xcode version",
- "type": "macosToolchainVersion",
- "args": "xcodeVersion",
- "condition": "config.macos"
- },
- {
- "message": "Clang version",
- "type": "macosToolchainVersion",
- "args": "clangVersion",
- "condition": "config.macos"
- },
- {
- "message": "macOS SDK version",
- "type": "macosToolchainVersion",
- "args": "sdkVersion",
- "condition": "config.macos"
- },
- {
- "message": "macOS minimum deployment target",
- "type": "macosToolchainVersion",
- "args": "deploymentTarget",
- "condition": "config.macos"
- }
- ]
- }
- ]
-}
diff --git a/src/core/configure/BUILD.root.gn.in b/src/core/configure/BUILD.root.gn.in
new file mode 100644
index 000000000..986db5026
--- /dev/null
+++ b/src/core/configure/BUILD.root.gn.in
@@ -0,0 +1,779 @@
+import("//build/config/features.gni")
+import("//build/config/ui.gni")
+import("//chrome/common/features.gni")
+import("//components/spellcheck/spellcheck_build_features.gni")
+import("//pdf/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
+import("//printing/buildflags/buildflags.gni")
+import("//extensions/buildflags/buildflags.gni")
+import("//tools/grit/repack.gni")
+import("//build/config/locales.gni")
+import("//chrome/chrome_repack_locales.gni")
+import("//extensions/buildflags/buildflags.gni")
+import("//ui/ozone/ozone.gni")
+import("//tools/v8_context_snapshot/v8_context_snapshot.gni")
+
+# Workaround for cmake configure_file command. Words wrapped with @ characters are
+# handled as variables in this file.
+chromium_version_template = string_replace("atMAJORat.atMINORat.atBUILDat.atPATCHat", "at", "@")
+chromium_version = exec_script("//build/util/version.py",
+ [ "-f", rebase_path("//chrome/VERSION"), "-t", chromium_version_template], "list lines")
+
+moc_source_h_files = exec_script("@WEBENGINE_ROOT_SOURCE_DIR@/tools/scripts/gn_find_mocables.py",
+ [
+ @GN_HEADERS@
+ ], "list lines", ["@WEBENGINE_ROOT_SOURCE_DIR@/src/core/CMakeLists.txt"]
+)
+moc_source_cpp_files = exec_script("@WEBENGINE_ROOT_SOURCE_DIR@/tools/scripts/gn_find_mocables.py",
+ [
+ @GN_SOURCES@
+ ], "list lines", ["@WEBENGINE_ROOT_SOURCE_DIR@/src/core/CMakeLists.txt"]
+)
+if (moc_source_h_files != []) {
+ action_foreach("generate_h_mocs") {
+ script = "@WEBENGINE_ROOT_SOURCE_DIR@/tools/scripts/gn_run_binary.py"
+ sources = moc_source_h_files
+ outputs = [ "${target_gen_dir}/.moc/moc_{{source_name_part}}.cpp" ]
+ inputs = [ "@WEBENGINE_ROOT_SOURCE_DIR@/src/core/CMakeLists.txt" ]
+ args = [
+ @GN_ARGS_MOC_BIN@,
+ @GN_ARGS_DEFINES@,
+ @GN_ARGS_INCLUDES@,
+ "{{source}}",
+ "-o",
+ rebase_path("${target_gen_dir}/.moc/moc_{{source_name_part}}.cpp")
+ ]
+ }
+}
+
+if (moc_source_cpp_files != []) {
+ action_foreach("generate_cpp_mocs") {
+ script = "@WEBENGINE_ROOT_SOURCE_DIR@/tools/scripts/gn_run_binary.py"
+ sources = moc_source_cpp_files
+ outputs = [ "${target_gen_dir}/.moc/{{source_name_part}}.moc" ]
+ inputs = [ "@WEBENGINE_ROOT_SOURCE_DIR@/src/core/CMakeLists.txt" ]
+ args = [
+ @GN_ARGS_MOC_BIN@,
+ @GN_ARGS_DEFINES@,
+ @GN_ARGS_INCLUDES@,
+ "{{source}}",
+ "-o",
+ rebase_path("${target_gen_dir}/.moc/{{source_name_part}}.moc")
+ ]
+ }
+}
+
+config("QtWebEngineCore_config") {
+ cflags = [
+ @GN_CFLAGS_C@,
+ ]
+ cflags_cc = [
+ @GN_CFLAGS_CC@,
+ ]
+ defines = [
+ @GN_DEFINES@,
+ ]
+ include_dirs = [
+ @GN_INCLUDE_DIRS@,
+ rebase_path("${target_gen_dir}/.moc/")
+ ]
+}
+
+declare_args() {
+ use_embedded_config = false
+ enable_webenginedriver = true
+}
+
+config("embedded_config") {
+ defines = [ "QTWEBENGINE_EMBEDDED_SWITCHES=1" ]
+}
+
+config("cpp20_config") {
+ # Chromium is built with C++20
+ if (is_win) {
+ cflags_cc = [ "/std:c++20" ]
+ } else {
+ cflags_cc = [ "-std=c++20" ]
+ }
+}
+
+shared_library("QtWebEngineCore") {
+ rsp_types = [ "objects", "archives", "libs", "ldir"]
+ configs += [
+ ":cpp20_config",
+ ":QtWebEngineCore_config",
+ "//build/config:precompiled_headers"
+ ]
+ include_dirs = [
+ "//skia/config",
+ "//third_party",
+ "//third_party/boringssl/src/include",
+ "//third_party/skia/include/core"
+ ]
+ data_deps = []
+ defines = [ "CHROMIUM_VERSION=" + chromium_version[0] ]
+ deps = [
+ "//base",
+ "//components/autofill/content/browser",
+ "//components/autofill/content/renderer",
+ "//components/autofill/core/browser",
+ "//components/autofill/core/browser:buildflags",
+ "//components/cdm/renderer",
+ "//components/embedder_support/origin_trials",
+ "//components/error_page/common",
+ "//components/favicon/content",
+ "//components/gcm_driver",
+ "//components/history/content/browser",
+ "//components/keyed_service/content",
+ "//components/lens:buildflags",
+ "//components/navigation_interception",
+ "//components/network_hints/browser",
+ "//components/network_hints/common:mojo_bindings",
+ "//components/network_hints/renderer",
+ "//components/signin/public/base",
+ "//components/visitedlink/browser",
+ "//components/visitedlink/renderer",
+ "//components/web_cache/browser",
+ "//components/web_cache/renderer",
+ "//components/spellcheck:buildflags",
+ "//components/supervised_user/core/common:buildflags",
+ "//components/profile_metrics",
+ "//components/proxy_config",
+ "//components/user_prefs",
+ "//content/public/app",
+ "//content/public/browser",
+ "//content",
+ "//gpu/ipc:gl_in_process_context",
+ "//media:media_buildflags",
+ "//net",
+ "//services/proxy_resolver:lib",
+ "//skia",
+ "//third_party/blink/public:blink",
+ "//ui/accessibility",
+ "//ui/gl",
+ "//qtwebengine/browser:interfaces",
+ "//qtwebengine/userscript",
+ "//qtwebengine/common:mojo_bindings",
+ ":qtwebengine_sources",
+ ":qtwebengine_resources",
+ ]
+
+ if (use_ozone) {
+ _ozone_extra_directory = get_path_info(ozone_extra_path, "dir")
+ deps += [ "$_ozone_extra_directory:qt" ]
+ }
+
+ if (enable_webrtc) {
+ deps += [ "//third_party/webrtc_overrides:webrtc_component" ]
+ }
+
+ if (is_win) {
+ configs += [ "//build/config/compiler:rtti" ]
+ data_deps += [ ":QtWebEngineCoreSandbox" ]
+ }
+ if (use_embedded_config) {
+ configs += [ ":embedded_config" ]
+ }
+
+ if (is_apple) {
+ configs -= [ "//build/config/compiler:enable_arc" ]
+ }
+
+ sources = [
+ @GN_HEADERS@,
+ @GN_SOURCES@
+ ]
+ if (moc_source_h_files != []) {
+ deps += [
+ ":generate_h_mocs",
+ ]
+ sources += get_target_outputs(":generate_h_mocs")
+ }
+ if (moc_source_cpp_files != []) {
+ deps += [
+ ":generate_cpp_mocs",
+ ]
+ }
+ if (use_v8_context_snapshot) {
+ data_deps += [
+ "//tools/v8_context_snapshot:v8_context_snapshot"
+ ]
+ }
+}
+
+source_set("qtwebengine_spellcheck_sources") {
+ include_dirs = [ "@WEBENGINE_ROOT_SOURCE_DIR@/src/core/service" ]
+ configs += [ "//third_party/boringssl:external_config" ]
+ sources = [
+ "//chrome/browser/spellchecker/spell_check_host_chrome_impl.cc",
+ "//chrome/browser/spellchecker/spell_check_host_chrome_impl.h",
+ "//chrome/browser/spellchecker/spellcheck_custom_dictionary.cc",
+ "//chrome/browser/spellchecker/spellcheck_custom_dictionary.h",
+ "//chrome/browser/spellchecker/spellcheck_factory.cc",
+ "//chrome/browser/spellchecker/spellcheck_factory.h",
+ "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc",
+ "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h",
+ "//chrome/browser/spellchecker/spellcheck_service.cc",
+ "//chrome/browser/spellchecker/spellcheck_service.h",
+ ]
+ deps = [
+ "//components/language/core/browser",
+ "//components/spellcheck/browser",
+ "//components/spellcheck/renderer",
+ "//third_party/blink/public:blink",
+ "//third_party/hunspell",
+ ]
+ if (is_mac && use_browser_spellchecker) {
+ sources += [
+ "//chrome/browser/spellchecker/spelling_request.cc",
+ ]
+ }
+}
+
+source_set("devtools_sources") {
+ configs += [ ":cpp20_config" ]
+ deps = [
+ "//components/zoom",
+ "//third_party/blink/public/mojom:mojom_platform",
+ ]
+ sources = [
+ "//chrome/browser/devtools/devtools_eye_dropper.cc",
+ "//chrome/browser/devtools/devtools_eye_dropper.h",
+ "//chrome/browser/devtools/devtools_file_helper.cc",
+ "//chrome/browser/devtools/devtools_file_helper.h",
+ "//chrome/browser/devtools/devtools_file_system_indexer.cc",
+ "//chrome/browser/devtools/devtools_file_system_indexer.h",
+ "//chrome/browser/devtools/devtools_file_watcher.cc",
+ "//chrome/browser/devtools/devtools_file_watcher.h",
+ "//chrome/browser/devtools/url_constants.cc",
+ "//chrome/browser/devtools/url_constants.h",
+ "//chrome/browser/devtools/devtools_ui_bindings.cc",
+ "//chrome/browser/devtools/devtools_ui_bindings.h",
+ "//chrome/browser/devtools/devtools_settings.cc",
+ "//chrome/browser/devtools/devtools_settings.h",
+ "//chrome/browser/devtools/devtools_embedder_message_dispatcher.cc",
+ "//chrome/browser/devtools/devtools_embedder_message_dispatcher.h",
+ ]
+}
+
+source_set("qtwebengine_sources") {
+ configs += [
+ ":cpp20_config",
+ "//skia:skia_config",
+ "//third_party/boringssl:external_config",
+ ]
+ deps = [
+ ":devtools_sources",
+ "//build:branding_buildflags",
+ "//build/config/chromebox_for_meetings:buildflags",
+ "//chrome/browser:dev_ui_browser_resources_grit",
+ "//chrome/browser/resources/accessibility:resources",
+ "//chrome/browser/resources/net_internals:resources",
+ "//chrome/browser/signin:identity_manager_provider",
+ "//chrome/common:buildflags",
+ "//chrome/common:version_header",
+ "//components/custom_handlers",
+ "//components/embedder_support:embedder_support",
+ "//components/nacl/common:buildflags",
+ "//components/performance_manager",
+ "//components/permissions:permissions_common",
+ "//components/plugins/renderer/",
+ "//content/browser/resources/quota:resources",
+ "//extensions/buildflags:buildflags",
+ "//pdf:buildflags",
+ "//printing/buildflags:buildflags",
+ "//qtwebengine/common:mojo_bindings",
+ "//rlz/buildflags:buildflags",
+ "//third_party/blink/public/mojom:mojom_platform",
+ ]
+ sources = [
+ "//chrome/browser/accessibility/accessibility_ui.cc",
+ "//chrome/browser/accessibility/accessibility_ui.h",
+ "//chrome/browser/gcm/gcm_product_util.cc",
+ "//chrome/browser/gcm/gcm_product_util.h",
+ "//chrome/browser/gcm/gcm_profile_service_factory.cc",
+ "//chrome/browser/gcm/gcm_profile_service_factory.h",
+ "//chrome/browser/gcm/instance_id/instance_id_profile_service_factory.cc",
+ "//chrome/browser/gcm/instance_id/instance_id_profile_service_factory.h",
+ "//chrome/browser/media/webrtc/desktop_capturer_wrapper.cc",
+ "//chrome/browser/media/webrtc/desktop_capturer_wrapper.h",
+ "//chrome/browser/media/webrtc/desktop_media_list.cc",
+ "//chrome/browser/media/webrtc/desktop_media_list.h",
+ "//chrome/browser/media/webrtc/desktop_media_list_base.cc",
+ "//chrome/browser/media/webrtc/desktop_media_list_base.h",
+ "//chrome/browser/media/webrtc/native_desktop_media_list.cc",
+ "//chrome/browser/media/webrtc/native_desktop_media_list.h",
+ "//chrome/browser/media/webrtc/thumbnail_capturer.cc",
+ "//chrome/browser/media/webrtc/thumbnail_capturer.h",
+ "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc",
+ "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.h",
+ "//chrome/browser/prefs/chrome_command_line_pref_store.cc",
+ "//chrome/browser/prefs/chrome_command_line_pref_store.h",
+ "//chrome/browser/profiles/incognito_helpers.cc",
+ "//chrome/browser/profiles/incognito_helpers.h",
+ "//chrome/browser/profiles/profile_keyed_service_factory.cc",
+ "//chrome/browser/profiles/profile_keyed_service_factory.h",
+ "//chrome/browser/profiles/profile_selections.cc",
+ "//chrome/browser/profiles/profile_selections.h",
+ "//chrome/browser/profiles/profile.cc",
+ "//chrome/browser/profiles/profile.h",
+ "//chrome/browser/push_messaging/push_messaging_app_identifier.cc",
+ "//chrome/browser/push_messaging/push_messaging_app_identifier.h",
+ "//chrome/browser/push_messaging/push_messaging_constants.cc",
+ "//chrome/browser/push_messaging/push_messaging_constants.h",
+ "//chrome/browser/push_messaging/push_messaging_features.cc",
+ "//chrome/browser/push_messaging/push_messaging_features.h",
+ "//chrome/browser/push_messaging/push_messaging_notification_manager.cc",
+ "//chrome/browser/push_messaging/push_messaging_notification_manager.h",
+ "//chrome/browser/push_messaging/push_messaging_refresher.cc",
+ "//chrome/browser/push_messaging/push_messaging_refresher.h",
+ "//chrome/browser/push_messaging/push_messaging_service_factory.cc",
+ "//chrome/browser/push_messaging/push_messaging_service_factory.h",
+ "//chrome/browser/push_messaging/push_messaging_service_impl.cc",
+ "//chrome/browser/push_messaging/push_messaging_service_impl.h",
+ "//chrome/browser/push_messaging/push_messaging_utils.cc",
+ "//chrome/browser/push_messaging/push_messaging_utils.h",
+ "//chrome/browser/signin/chrome_signin_client.cc",
+ "//chrome/browser/signin/chrome_signin_client.h",
+ "//chrome/browser/signin/chrome_signin_client_factory.cc",
+ "//chrome/browser/signin/chrome_signin_client_factory.h",
+ "//chrome/browser/signin/force_signin_verifier.cc",
+ "//chrome/browser/signin/force_signin_verifier.h",
+ "//chrome/browser/signin/identity_manager_factory.cc",
+ "//chrome/browser/signin/identity_manager_factory.h",
+ "//chrome/browser/signin/signin_util.cc",
+ "//chrome/browser/signin/signin_util.h",
+ "//chrome/browser/tab_contents/form_interaction_tab_helper.cc",
+ "//chrome/browser/tab_contents/form_interaction_tab_helper.h",
+ "//chrome/browser/tab_contents/web_contents_collection.cc",
+ "//chrome/browser/tab_contents/web_contents_collection.h",
+ "//chrome/browser/ui/webui/device_log_ui.cc",
+ "//chrome/browser/ui/webui/device_log_ui.h",
+ "//chrome/browser/ui/webui/devtools_ui.cc",
+ "//chrome/browser/ui/webui/devtools_ui.h",
+ "//chrome/browser/ui/webui/devtools_ui_data_source.cc",
+ "//chrome/browser/ui/webui/devtools_ui_data_source.h",
+ "//chrome/browser/ui/webui/net_internals/net_internals_ui.cc",
+ "//chrome/browser/ui/webui/net_internals/net_internals_ui.h",
+ "//chrome/browser/ui/webui/user_actions/user_actions_ui.cc",
+ "//chrome/browser/ui/webui/user_actions/user_actions_ui.h",
+ "//chrome/browser/ui/webui/user_actions/user_actions_ui_handler.cc",
+ "//chrome/browser/ui/webui/user_actions/user_actions_ui_handler.h",
+ "//chrome/browser/ui/webui/webui_util.cc",
+ "//chrome/browser/ui/webui/webui_util.h",
+ "//chrome/common/chrome_switches.cc",
+ "//chrome/common/chrome_switches.h",
+ "//chrome/common/pref_names.h",
+ "//chrome/common/url_constants.cc",
+ "//chrome/common/url_constants.h",
+ "//chrome/common/webui_url_constants.cc",
+ "//chrome/common/webui_url_constants.h",
+ "//components/embedder_support/user_agent_utils.cc",
+ "//components/embedder_support/user_agent_utils.h",
+ ]
+ if (use_ozone) {
+ deps += [
+ "//ui/gfx/linux:drm",
+ ]
+
+ sources += [
+ "//ui/ozone/platform/wayland/gpu/wayland_gl_egl_utility.cc",
+ "//ui/ozone/platform/wayland/gpu/wayland_gl_egl_utility.h",
+ ]
+
+ if (ozone_platform_x11) {
+ deps += [
+ "//ui/base/x:gl",
+ "//ui/gfx/linux:gpu_memory_buffer_support_x11",
+ ]
+
+ sources += [
+ "//ui/ozone/platform/x11/gl_egl_utility_x11.cc",
+ "//ui/ozone/platform/x11/gl_egl_utility_x11.h",
+ ]
+ }
+ }
+ if (enable_extensions) {
+ deps += [
+ ":qtwebengine_extensions_features",
+ "//chrome/app:generated_resources",
+ "//chrome/browser/extensions/api:api_registration",
+ "//chrome/browser/resources:component_extension_resources_grit",
+ "//chrome/common/extensions/api:api",
+ "//chrome/common/extensions/api:extensions_features",
+ "//components/crx_file",
+ "//components/crx_file:crx_creator",
+ "//components/spellcheck:buildflags",
+ "//extensions/buildflags:buildflags",
+ "//extensions/common",
+ "//extensions/common/api",
+ "//extensions/common:core_api_provider",
+ "//extensions/browser",
+ "//extensions/browser/api",
+ "//extensions/renderer",
+ "//extensions:extensions_resources",
+ "//extensions/strings",
+ "//qtwebengine/browser/extensions/api:api_registration",
+ "//qtwebengine/common/extensions/api:api",
+ ]
+ sources += [
+ "//chrome/browser/extensions/api/streams_private/streams_private_api.cc",
+ "//chrome/browser/extensions/api/streams_private/streams_private_api.h",
+ "//chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.cc",
+ "//chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h",
+ "//chrome/common/extensions/permissions/chrome_api_permissions.cc",
+ "//chrome/common/extensions/permissions/chrome_api_permissions.h",
+ "//chrome/common/extensions/permissions/chrome_permission_message_provider.cc",
+ "//chrome/common/extensions/permissions/chrome_permission_message_provider.h",
+ "//chrome/common/extensions/permissions/chrome_permission_message_rules.cc",
+ "//chrome/common/extensions/permissions/chrome_permission_message_rules.h",
+ ]
+ } else {
+ sources += [
+ "//extensions/common/url_pattern.cc",
+ "//extensions/common/url_pattern.h",
+ ]
+ }
+ if (is_linux || is_win) {
+ sources += [
+ "//chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc",
+ "//chrome/browser/ui/webui/sandbox/sandbox_internals_ui.h",
+ ]
+ deps += [
+ "//chrome/browser/resources/sandbox_internals:resources",
+ ]
+ }
+ if (is_win) {
+ sources += [
+ "//chrome/browser/net/chrome_mojo_proxy_resolver_win.cc",
+ "//chrome/browser/net/chrome_mojo_proxy_resolver_win.h",
+ "//chrome/browser/ui/webui/sandbox/sandbox_handler.cc",
+ "//chrome/browser/ui/webui/sandbox/sandbox_handler.h",
+ ]
+ deps += [ "//services/proxy_resolver_win",
+ "//services/proxy_resolver_win/public/mojom",
+ ]
+ }
+ if (enable_spellcheck) {
+ deps += [
+ ":qtwebengine_spellcheck_sources",
+ "//chrome/tools/convert_dict:lib",
+ "//third_party/hunspell",
+ ]
+ }
+ if (enable_plugins) {
+ sources += [
+ "//chrome/renderer/pepper/pepper_shared_memory_message_filter.cc",
+ "//chrome/renderer/pepper/pepper_shared_memory_message_filter.h",
+ ]
+ }
+ if (enable_basic_printing || enable_print_preview) {
+ sources += [
+ "//chrome/browser/printing/printer_query.cc",
+ "//chrome/browser/printing/printer_query.h",
+ "//chrome/browser/printing/print_job.cc",
+ "//chrome/browser/printing/print_job.h",
+ "//chrome/browser/printing/print_job_manager.cc",
+ "//chrome/browser/printing/print_job_manager.h",
+ "//chrome/browser/printing/print_job_worker.cc",
+ "//chrome/browser/printing/print_job_worker.h",
+ ]
+ }
+ if (enable_pdf) {
+ deps += [
+ "//pdf",
+ "//chrome/browser/resources/pdf:resources",
+ "//components/pdf/browser",
+ "//components/pdf/browser:interceptors",
+ "//components/pdf/common",
+ "//components/pdf/renderer",
+ "//components/printing/browser",
+ "//components/printing/renderer",
+ ]
+ }
+
+ if (enable_webrtc && enable_extensions) {
+ deps += [
+ "//chrome/browser/resources/media:resources",
+ "//components/upload_list",
+ "//components/webrtc_logging/browser",
+ "//components/webrtc_logging/common",
+ ]
+
+ sources += [
+ "//chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc",
+ "//chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h",
+ "//chrome/browser/media/webrtc/audio_debug_recordings_handler.cc",
+ "//chrome/browser/media/webrtc/audio_debug_recordings_handler.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_history.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_history.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_common.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_local.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_local.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h",
+ "//chrome/browser/media/webrtc/webrtc_event_log_uploader.cc",
+ "//chrome/browser/media/webrtc/webrtc_event_log_uploader.h",
+ "//chrome/browser/media/webrtc/webrtc_log_buffer.cc",
+ "//chrome/browser/media/webrtc/webrtc_log_buffer.h",
+ "//chrome/browser/media/webrtc/webrtc_log_uploader.cc",
+ "//chrome/browser/media/webrtc/webrtc_log_uploader.h",
+ "//chrome/browser/media/webrtc/webrtc_logging_controller.cc",
+ "//chrome/browser/media/webrtc/webrtc_logging_controller.h",
+ "//chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc",
+ "//chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h",
+ "//chrome/browser/media/webrtc/webrtc_rtp_dump_writer.cc",
+ "//chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h",
+ "//chrome/browser/media/webrtc/webrtc_text_log_handler.cc",
+ "//chrome/browser/media/webrtc/webrtc_text_log_handler.h",
+ "//chrome/browser/ui/webui/media/webrtc_logs_ui.cc",
+ "//chrome/browser/ui/webui/media/webrtc_logs_ui.h",
+ "//chrome/renderer/media/webrtc_logging_agent_impl.cc",
+ "//chrome/renderer/media/webrtc_logging_agent_impl.h",
+ ]
+ }
+}
+
+if (is_win) {
+ static_library("QtWebEngineCoreSandbox") {
+ complete_static_lib = true
+ configs += [ ":cpp20_config",
+ ":QtWebEngineCore_config",
+ "//build/config:precompiled_headers"
+ ]
+ output_dir = "$root_out_dir"
+ sources = [
+ "@GN_SOURCE_ROOT@/sandbox_win.cpp"
+ ]
+ public_deps = [ "//sandbox/win:sandbox" ]
+ }
+}
+
+group("qtwebengine_resources") {
+ deps = [
+ "//chrome/app:generated_resources",
+ "//chrome/browser:resources",
+ "//chrome/browser/resources:component_extension_resources",
+ "//chrome/common:resources",
+ "//components/resources:components_resources",
+ ":qtwebengine_repack_resources",
+ ":qtwebengine_repack_resources_100",
+ ":qtwebengine_repack_resources_200",
+ ":qtwebengine_repack_resources_devtools",
+ ":qtwebengine_repack_locales_pack"
+ ]
+}
+
+repack("qtwebengine_repack_resources") {
+ sources = [
+ "$root_gen_dir/qtwebengine/qt_webengine_resources.pak",
+ "$root_gen_dir/chrome/accessibility_resources.pak",
+ "$root_gen_dir/chrome/common_resources.pak",
+ "$root_gen_dir/chrome/dev_ui_browser_resources.pak",
+ "$root_gen_dir/chrome/net_internals_resources.pak",
+ "$root_gen_dir/components/components_resources.pak",
+ "$root_gen_dir/components/dev_ui_components_resources.pak",
+ "$root_gen_dir/content/attribution_internals_resources.pak",
+ "$root_gen_dir/content/browser/resources/media/media_internals_resources.pak",
+ "$root_gen_dir/content/browser/tracing/tracing_resources.pak",
+ "$root_gen_dir/content/content_resources.pak",
+ "$root_gen_dir/content/gpu_resources.pak",
+ "$root_gen_dir/content/histograms_resources.pak",
+ "$root_gen_dir/content/indexed_db_resources.pak",
+ "$root_gen_dir/content/network_errors_resources.pak",
+ "$root_gen_dir/content/process_resources.pak",
+ "$root_gen_dir/content/quota_internals_resources.pak",
+ "$root_gen_dir/content/service_worker_resources.pak",
+ "$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak",
+ "$root_gen_dir/net/net_resources.pak",
+ "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak",
+ "$root_gen_dir/ui/resources/webui_resources.pak",
+ ]
+ output = "$root_out_dir/qtwebengine_resources.pak"
+ deps = [
+ "//qtwebengine/browser:qt_webengine_resources",
+ "//chrome/browser:dev_ui_browser_resources_grit",
+ "//chrome/browser/resources/accessibility:resources",
+ "//chrome/browser/resources/net_internals:resources",
+ "//chrome/common:resources_grit",
+ "//components/resources:components_resources_grit",
+ "//components/resources:dev_ui_components_resources_grit",
+ "//content/browser/resources/attribution_reporting:resources",
+ "//content/browser/resources/gpu:resources",
+ "//content/browser/resources/histograms:resources_grit",
+ "//content/browser/resources/indexed_db:resources",
+ "//content/browser/resources/media:resources",
+ "//content/browser/resources/net:resources",
+ "//content/browser/resources/process:resources",
+ "//content/browser/resources/quota:resources",
+ "//content/browser/resources/service_worker:resources",
+ "//content/browser/tracing:resources",
+ "//content:content_resources",
+ "//mojo/public/js:resources",
+ "//net:net_resources_grit",
+ "//third_party/blink/public:resources_grit",
+ "//ui/resources:webui_resources_grd",
+ ]
+ if (enable_extensions) {
+ sources += [
+ "$root_gen_dir/chrome/component_extension_resources.pak",
+ "$root_gen_dir/extensions/extensions_renderer_resources.pak",
+ "$root_gen_dir/extensions/extensions_resources.pak",
+ ]
+ deps += [
+ "//chrome/browser/resources:component_extension_resources_grit",
+ "//extensions:extensions_renderer_resources_grit",
+ "//extensions:extensions_resources_grd_grit",
+ ]
+ }
+ if (enable_webrtc) {
+ sources += [
+ "$root_gen_dir/content/browser/webrtc/resources/webrtc_internals_resources.pak",
+ ]
+ deps += [
+ "//content/browser/webrtc/resources",
+ ]
+ }
+ if (enable_webrtc && enable_extensions) {
+ sources += [
+ "$root_gen_dir/chrome/media_resources.pak",
+ ]
+ deps += [
+ "//chrome/browser/resources/media:resources",
+ ]
+ }
+ if (enable_pdf) {
+ sources += [
+ "$root_gen_dir/chrome/pdf_resources.pak",
+ ]
+ deps += [
+ "//chrome/browser/resources/pdf:resources",
+ ]
+ }
+ if (is_linux || is_win) {
+ sources += [
+ "$root_gen_dir/chrome/sandbox_internals_resources.pak",
+ ]
+ deps += [
+ "//chrome/browser/resources/sandbox_internals:resources_grit",
+ ]
+ }
+}
+
+repack("qtwebengine_repack_resources_100") {
+ sources = [
+ "$root_gen_dir/chrome/renderer_resources_100_percent.pak",
+ "$root_gen_dir/components/components_resources_100_percent.pak",
+ "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_100_percent.pak",
+ "$root_gen_dir/ui/resources/ui_resources_100_percent.pak",
+ ]
+ output = "$root_out_dir/qtwebengine_resources_100p.pak"
+ deps = [
+ "//chrome/renderer:resources_grit",
+ "//components/resources:components_scaled_resources_grit",
+ "//third_party/blink/public:scaled_resources_100_percent",
+ "//ui/resources:ui_resources_grd_grit"
+ ]
+ if (enable_extensions) {
+ sources += [
+ "$root_gen_dir/extensions/extensions_browser_resources_100_percent.pak"
+ ]
+ deps += [
+ "//extensions:extensions_browser_resources_grit"
+ ]
+ }
+}
+
+repack("qtwebengine_repack_resources_200") {
+ sources = [
+ "$root_gen_dir/chrome/renderer_resources_200_percent.pak",
+ "$root_gen_dir/components/components_resources_200_percent.pak",
+ "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_200_percent.pak",
+ "$root_gen_dir/ui/resources/ui_resources_200_percent.pak",
+ ]
+ output = "$root_out_dir/qtwebengine_resources_200p.pak"
+ deps = [
+ "//chrome/renderer:resources_grit",
+ "//components/resources:components_scaled_resources_grit",
+ "//third_party/blink/public:scaled_resources_200_percent",
+ "//ui/resources:ui_resources_grd_grit"
+ ]
+ if (enable_extensions) {
+ sources += [
+ "$root_gen_dir/extensions/extensions_browser_resources_200_percent.pak"
+ ]
+ deps += [
+ "//extensions:extensions_browser_resources_grit"
+ ]
+ }
+}
+
+repack("qtwebengine_repack_resources_devtools") {
+ sources = [
+ "$root_gen_dir/content/browser/devtools/devtools_resources.pak",
+ "$root_gen_dir/third_party/blink/public/resources/inspector_overlay_resources.pak",
+ ]
+ output = "$root_out_dir/qtwebengine_devtools_resources.pak"
+ deps = [
+ "//content/browser/devtools:devtools_resources_grit",
+ "//third_party/blink/public:devtools_inspector_resources_grit",
+ ]
+}
+
+chrome_repack_locales("qtwebengine_repack_locales_pack") {
+ input_locales = platform_pak_locales
+ output_dir = "$root_out_dir/qtwebengine_locales"
+ output_locales = platform_pak_locales
+}
+
+if (enable_extensions) {
+ import("//tools/json_schema_compiler/json_features.gni")
+ json_features("qt_api_features") {
+ feature_type = "APIFeature"
+ method_name = "AddQtAPIFeatures"
+ sources = [
+ "//extensions/common/api/_webengine_api_features.json"
+ ]
+ }
+ json_features("qt_permission_features") {
+ feature_type = "PermissionFeature"
+ method_name = "AddQtPermissionFeatures"
+ sources = [
+ "//chrome/common/extensions/api/_permission_features.json",
+ "//extensions/common/api/_permission_features.json",
+ ]
+ }
+ group("qtwebengine_extensions_features") {
+ public_deps = [
+ ":qt_api_features",
+ ":qt_permission_features",
+ "//chrome/common/extensions/api:extensions_features",
+ "//extensions/common/api:extensions_features",
+ ]
+ }
+}
+
+if (enable_spellcheck) {
+ shared_library("convert_dict") {
+ rsp_types = [ "objects", "archives", "libs", "ldir" ]
+ configs += [ "//build/config/compiler:wexit_time_destructors" ]
+ deps = [
+ "//chrome/tools/convert_dict:lib",
+ "//base",
+ "//base:i18n",
+ "//third_party/hunspell",
+ ]
+ }
+}
+
+if (enable_webenginedriver) {
+ group("webenginedriver_group") {
+ testonly = true
+ deps = [
+ "//chrome/test/chromedriver:chromedriver_server",
+ ]
+ }
+}
diff --git a/src/core/content_browser_client_qt.cpp b/src/core/content_browser_client_qt.cpp
index c8d34ae73..7192edbc2 100644
--- a/src/core/content_browser_client_qt.cpp
+++ b/src/core/content_browser_client_qt.cpp
@@ -1,200 +1,162 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content_browser_client_qt.h"
-#include "base/memory/ptr_util.h"
-#include "base/optional.h"
-#include "base/path_service.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/message_loop/message_loop.h"
-#include "base/task/post_task.h"
-#include "base/threading/thread_restrictions.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
-#if QT_CONFIG(webengine_spellchecker)
-#include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h"
-#endif
-#include "components/guest_view/browser/guest_view_base.h"
+#include "base/files/file_util.h"
+#include "chrome/browser/tab_contents/form_interaction_tab_helper.h"
+#include "components/autofill/content/browser/content_autofill_driver_factory.h"
+#include "components/custom_handlers/protocol_handler_registry.h"
+#include "components/embedder_support/user_agent_utils.h"
+#include "components/error_page/common/error.h"
+#include "components/error_page/common/localized_error.h"
#include "components/navigation_interception/intercept_navigation_throttle.h"
-#include "components/navigation_interception/navigation_params.h"
#include "components/network_hints/browser/simple_network_hints_handler_impl.h"
-#include "components/spellcheck/spellcheck_buildflags.h"
-#include "content/browser/renderer_host/render_view_host_delegate.h"
+#include "components/performance_manager/embedder/performance_manager_lifetime.h"
+#include "components/performance_manager/embedder/performance_manager_registry.h"
+#include "components/performance_manager/public/performance_manager.h"
#include "content/browser/web_contents/web_contents_impl.h"
-#include "content/common/url_schemes.h"
-#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/media_observer.h"
-#include "content/public/browser/network_service_instance.h"
+#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
-#include "content/public/browser/storage_partition.h"
+#include "content/public/browser/url_loader_request_interceptor.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_user_data.h"
+#include "content/public/browser/web_contents_view_delegate.h"
#include "content/public/browser/web_ui_url_loader_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
-#include "content/public/common/service_manager_connection.h"
-#include "content/public/common/service_names.mojom.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/user_agent.h"
-#include "media/media_buildflags.h"
#include "extensions/buildflags/buildflags.h"
-#include "extensions/browser/extension_protocols.h"
-#include "extensions/browser/guest_view/web_view/web_view_guest.h"
-#include "mojo/public/cpp/bindings/binding.h"
-#include "mojo/public/cpp/bindings/binding_set.h"
-#include "mojo/public/cpp/bindings/remote.h"
-#include "printing/buildflags/buildflags.h"
-#include "qtwebengine/browser/qtwebengine_content_browser_overlay_manifest.h"
-#include "qtwebengine/browser/qtwebengine_content_renderer_overlay_manifest.h"
+#include "mojo/public/cpp/bindings/self_owned_associated_receiver.h"
+#include "pdf/buildflags.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/client_cert_store.h"
+#include "net/ssl/ssl_private_key.h"
+#include "printing/buildflags/buildflags.h"
+#include "services/device/public/cpp/geolocation/geolocation_manager.h"
#include "services/network/network_service.h"
-#include "services/network/public/cpp/features.h"
-#include "services/service_manager/public/cpp/connector.h"
-#include "services/service_manager/public/cpp/service.h"
-#include "services/service_manager/sandbox/switches.h"
-#include "storage/browser/quota/quota_settings.h"
+#include "services/network/public/cpp/web_sandbox_flags.h"
+#include "services/network/public/mojom/websocket.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
-#include "third_party/blink/public/mojom/insecure_input/insecure_input_service.mojom.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
-#include "ui/gl/gl_context.h"
-#include "ui/gl/gl_implementation.h"
-#include "ui/gl/gl_share_group.h"
-#include "ui/gl/gpu_timing.h"
#include "url/url_util_qt.h"
#include "qtwebengine/common/renderer_configuration.mojom.h"
-#include "qtwebengine/grit/qt_webengine_resources.h"
#include "profile_adapter.h"
#include "browser_main_parts_qt.h"
#include "browser_message_filter_qt.h"
#include "certificate_error_controller.h"
-#include "certificate_error_controller_p.h"
#include "client_cert_select_controller.h"
+#include "custom_handlers/protocol_handler_registry_factory.h"
#include "devtools_manager_delegate_qt.h"
+#include "file_system_access/file_system_access_permission_request_manager_qt.h"
#include "login_delegate_qt.h"
#include "media_capture_devices_dispatcher.h"
#include "net/cookie_monster_delegate_qt.h"
#include "net/custom_url_loader_factory.h"
#include "net/proxying_restricted_cookie_manager_qt.h"
#include "net/proxying_url_loader_factory_qt.h"
-#include "net/qrc_url_scheme_handler.h"
#include "net/system_network_context_manager.h"
#include "platform_notification_service_qt.h"
-#if QT_CONFIG(webengine_printing_and_pdf)
-#include "printing/printing_message_filter_qt.h"
-#endif
#include "profile_qt.h"
#include "profile_io_data_qt.h"
-#include "quota_permission_context_qt.h"
#include "renderer_host/user_resource_controller_host.h"
+#include "select_file_dialog_factory_qt.h"
#include "type_conversion.h"
#include "web_contents_adapter_client.h"
#include "web_contents_adapter.h"
#include "web_contents_delegate_qt.h"
-#include "web_engine_context.h"
#include "web_contents_view_qt.h"
+#include "web_engine_context.h"
#include "web_engine_library_info.h"
+#include "web_engine_settings.h"
+#include "authenticator_request_client_delegate_qt.h"
#include "api/qwebenginecookiestore.h"
#include "api/qwebenginecookiestore_p.h"
-#include "api/qwebengineurlscheme.h"
+#include "api/qwebengineurlrequestinfo_p.h"
-#if defined(Q_OS_LINUX)
-#include "global_descriptors_qt.h"
-#include "ui/base/resource/resource_bundle.h"
+#if QT_CONFIG(webengine_geolocation)
+#include "base/memory/ptr_util.h"
+#include "location_provider_qt.h"
#endif
-#if QT_CONFIG(webengine_pepper_plugins)
-#include "content/public/browser/browser_ppapi_host.h"
-#include "ppapi/host/ppapi_host.h"
-#include "renderer_host/pepper/pepper_host_factory_qt.h"
+#if QT_CONFIG(webengine_spellchecker)
+#include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h"
+#include "chrome/browser/spellchecker/spellcheck_factory.h"
+#include "chrome/browser/spellchecker/spellcheck_service.h"
+#include "components/spellcheck/browser/pref_names.h"
+#include "components/spellcheck/common/spellcheck.mojom.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#endif
-#if QT_CONFIG(webengine_geolocation)
-#include "location_provider_qt.h"
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+#include "chrome/browser/media/webrtc/webrtc_logging_controller.h"
+#endif
+
+#if defined(Q_OS_LINUX)
+#include "global_descriptors_qt.h"
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
-#include "content/public/browser/file_url_loader.h"
+#include "common/extensions/extensions_client_qt.h"
+#include "components/guest_view/browser/guest_view_base.h"
+#include "extensions/browser/api/messaging/messaging_api_message_filter.h"
+#include "extensions/browser/api/mime_handler_private/mime_handler_private.h"
+#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_message_filter.h"
-#include "extensions/browser/guest_view/extensions_guest_view_message_filter.h"
+#include "extensions/browser/extension_protocols.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/browser/extension_util.h"
+#include "extensions/browser/guest_view/extensions_guest_view.h"
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
+#include "extensions/browser/guest_view/web_view/web_view_guest.h"
+#include "extensions/browser/process_map.h"
+#include "extensions/browser/url_loader_factory_manager.h"
+#include "extensions/browser/view_type_utils.h"
#include "extensions/common/constants.h"
-
-#include "common/extensions/extensions_client_qt.h"
+#include "extensions/common/manifest_handlers/mime_types_handler.h"
#include "extensions/extension_web_contents_observer_qt.h"
#include "extensions/extensions_browser_client_qt.h"
#include "net/plugin_response_interceptor_url_loader_throttle.h"
#endif
-#if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS)
-#include "media/mojo/interfaces/constants.mojom.h"
-#include "media/mojo/services/media_service_factory.h"
+#if QT_CONFIG(webengine_webchannel)
+#include "qtwebengine/browser/qtwebchannel.mojom.h"
+#include "renderer_host/web_channel_ipc_transport_host.h"
#endif
-#if BUILDFLAG(ENABLE_SPELLCHECK)
-#include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h"
-#include "components/spellcheck/common/spellcheck.mojom.h"
+#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+#include "printing/pdf_stream_delegate_qt.h"
+#include "printing/print_view_manager_qt.h"
#endif
-#include <QGuiApplication>
-#include <QLocale>
-#include <QStandardPaths>
-#if QT_CONFIG(opengl)
-# include <QOpenGLContext>
-# include <QOpenGLExtraFunctions>
+#if BUILDFLAG(ENABLE_PDF)
+#include "components/pdf/browser/pdf_navigation_throttle.h"
+#include "components/pdf/browser/pdf_url_loader_request_interceptor.h"
+#include "components/pdf/browser/pdf_document_helper.h"
+
+#include "printing/pdf_document_helper_client_qt.h"
#endif
-#include <qpa/qplatformnativeinterface.h>
-QT_BEGIN_NAMESPACE
-Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
-QT_END_NAMESPACE
+#if BUILDFLAG(ENABLE_PDF) && BUILDFLAG(ENABLE_EXTENSIONS)
+#include "extensions/pdf_iframe_navigation_throttle_qt.h"
+#endif
+
+#include <QGuiApplication>
+#include <QStandardPaths>
// Implement IsHandledProtocol as declared in //url/url_util_qt.h.
namespace url {
@@ -215,9 +177,6 @@ bool IsHandledProtocol(base::StringPiece scheme)
content::kChromeUIScheme,
url::kDataScheme,
url::kAboutScheme,
-#if !BUILDFLAG(DISABLE_FTP_SUPPORT)
- url::kFtpScheme,
-#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
url::kBlobScheme,
url::kFileSystemScheme,
url::kQrcScheme,
@@ -235,91 +194,11 @@ bool IsHandledProtocol(base::StringPiece scheme)
namespace QtWebEngineCore {
-class QtShareGLContext : public gl::GLContext {
-public:
- QtShareGLContext(QOpenGLContext *qtContext)
- : gl::GLContext(0)
- , m_handle(0)
- {
- QString platform = qApp->platformName().toLower();
- QPlatformNativeInterface *pni = QGuiApplication::platformNativeInterface();
- if (platform == QLatin1String("xcb") || platform == QLatin1String("offscreen")) {
- if (gl::GetGLImplementation() == gl::kGLImplementationEGLGLES2)
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("eglcontext"), qtContext);
- else
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("glxcontext"), qtContext);
- } else if (platform == QLatin1String("cocoa"))
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("cglcontextobj"), qtContext);
- else if (platform == QLatin1String("qnx"))
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("eglcontext"), qtContext);
- else if (platform == QLatin1String("eglfs") || platform == QLatin1String("wayland")
- || platform == QLatin1String("wayland-egl"))
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("eglcontext"), qtContext);
- else if (platform == QLatin1String("windows")) {
- if (gl::GetGLImplementation() == gl::kGLImplementationEGLGLES2)
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("eglContext"), qtContext);
- else
- m_handle = pni->nativeResourceForContext(QByteArrayLiteral("renderingcontext"), qtContext);
- } else {
- qFatal("%s platform not yet supported", platform.toLatin1().constData());
- // Add missing platforms once they work.
- Q_UNREACHABLE();
- }
- }
-
- void* GetHandle() override { return m_handle; }
- unsigned int CheckStickyGraphicsResetStatus() override
- {
-#if QT_CONFIG(opengl)
- if (QOpenGLContext *context = qt_gl_global_share_context()) {
- if (context->format().testOption(QSurfaceFormat::ResetNotification))
- return context->extraFunctions()->glGetGraphicsResetStatus();
- }
-#endif
- return 0 /*GL_NO_ERROR*/;
- }
-
- // We don't care about the rest, this context shouldn't be used except for its handle.
- bool Initialize(gl::GLSurface *, const gl::GLContextAttribs &) override { Q_UNREACHABLE(); return false; }
- bool MakeCurrent(gl::GLSurface *) override { Q_UNREACHABLE(); return false; }
- void ReleaseCurrent(gl::GLSurface *) override { Q_UNREACHABLE(); }
- bool IsCurrent(gl::GLSurface *) override { Q_UNREACHABLE(); return false; }
- scoped_refptr<gl::GPUTimingClient> CreateGPUTimingClient() override
- {
- return nullptr;
- }
- const gfx::ExtensionSet& GetExtensions() override
- {
- static const gfx::ExtensionSet s_emptySet;
- return s_emptySet;
- }
- void ResetExtensions() override
- {
- }
-
-private:
- void *m_handle;
-};
-
-class ShareGroupQt : public gl::GLShareGroup {
-public:
- gl::GLContext* GetContext() override { return m_shareContextQt.get(); }
- void AboutToAddFirstContext() override;
-
-private:
- scoped_refptr<QtShareGLContext> m_shareContextQt;
-};
-
-void ShareGroupQt::AboutToAddFirstContext()
-{
-#if QT_CONFIG(opengl)
- // This currently has to be setup by ::main in all applications using QQuickWebEngineView with delegated rendering.
- QOpenGLContext *shareContext = qt_gl_global_share_context();
- if (!shareContext) {
- qFatal("QWebEngine: OpenGL resource sharing is not set up in QtQuick. Please make sure to call QtWebEngine::initialize() in your main() function before QCoreApplication is created.");
- }
- m_shareContextQt = new QtShareGLContext(shareContext);
-#endif
+void MaybeAddThrottle(
+ std::unique_ptr<content::NavigationThrottle> maybe_throttle,
+ std::vector<std::unique_ptr<content::NavigationThrottle>>* throttles) {
+ if (maybe_throttle)
+ throttles->push_back(std::move(maybe_throttle));
}
ContentBrowserClientQt::ContentBrowserClientQt()
@@ -330,9 +209,12 @@ ContentBrowserClientQt::~ContentBrowserClientQt()
{
}
-std::unique_ptr<content::BrowserMainParts> ContentBrowserClientQt::CreateBrowserMainParts(const content::MainFunctionParams&)
+std::unique_ptr<content::BrowserMainParts> ContentBrowserClientQt::CreateBrowserMainParts(bool)
{
- return std::make_unique<BrowserMainPartsQt>();
+ Q_ASSERT(!m_browserMainParts);
+ auto browserMainParts = std::make_unique<BrowserMainPartsQt>();
+ m_browserMainParts = browserMainParts.get();
+ return browserMainParts;
}
void ContentBrowserClientQt::RenderProcessWillLaunch(content::RenderProcessHost *host)
@@ -340,6 +222,15 @@ void ContentBrowserClientQt::RenderProcessWillLaunch(content::RenderProcessHost
const int id = host->GetID();
Profile *profile = Profile::FromBrowserContext(host->GetBrowserContext());
+#if QT_CONFIG(webengine_spellchecker)
+ if (spellcheck::UseBrowserSpellChecker() && !profile->GetPrefs()->GetBoolean(spellcheck::prefs::kSpellCheckEnable))
+ SpellcheckServiceFactory::GetForContext(profile)->InitForRenderer(host);
+#endif
+
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ WebRtcLoggingController::AttachToRenderProcessHost(host, WebEngineContext::current()->webRtcLogUploader());
+#endif
+
// Allow requesting custom schemes.
const auto policy = content::ChildProcessSecurityPolicy::GetInstance();
const auto profileAdapter = static_cast<ProfileQt *>(profile)->profileAdapter();
@@ -350,115 +241,62 @@ void ContentBrowserClientQt::RenderProcessWillLaunch(content::RenderProcessHost
policy->GrantRequestScheme(id, url::kFileScheme);
profileAdapter->userResourceController()->renderProcessStartedWithHost(host);
host->AddFilter(new BrowserMessageFilterQt(id, profile));
-#if QT_CONFIG(webengine_printing_and_pdf)
- host->AddFilter(new PrintingMessageFilterQt(id));
-#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
host->AddFilter(new extensions::ExtensionMessageFilter(id, profile));
- host->AddFilter(new extensions::ExtensionsGuestViewMessageFilter(id, profile));
+ host->AddFilter(new extensions::MessagingAPIMessageFilter(id, profile));
#endif //ENABLE_EXTENSIONS
bool is_incognito_process = profile->IsOffTheRecord();
- qtwebengine::mojom::RendererConfigurationAssociatedPtr renderer_configuration;
+ mojo::AssociatedRemote<qtwebengine::mojom::RendererConfiguration> renderer_configuration;
host->GetChannel()->GetRemoteAssociatedInterface(&renderer_configuration);
renderer_configuration->SetInitialConfiguration(is_incognito_process);
}
-gl::GLShareGroup *ContentBrowserClientQt::GetInProcessGpuShareGroup()
-{
- if (!m_shareGroupQt.get())
- m_shareGroupQt = new ShareGroupQt;
- return m_shareGroupQt.get();
-}
-
content::MediaObserver *ContentBrowserClientQt::GetMediaObserver()
{
return MediaCaptureDevicesDispatcher::GetInstance();
}
-void ContentBrowserClientQt::OverrideWebkitPrefs(content::RenderViewHost *rvh, content::WebPreferences *web_prefs)
+void ContentBrowserClientQt::OverrideWebkitPrefs(content::WebContents *webContents, blink::web_pref::WebPreferences *web_prefs)
{
- if (content::WebContents *webContents = rvh->GetDelegate()->GetAsWebContents()) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
- if (guest_view::GuestViewBase::IsGuest(webContents))
- return;
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
- WebContentsDelegateQt* delegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
- if (delegate)
- delegate->overrideWebPreferences(webContents, web_prefs);
- }
-}
-
-scoped_refptr<content::QuotaPermissionContext> ContentBrowserClientQt::CreateQuotaPermissionContext()
-{
- return new QuotaPermissionContextQt;
-}
-
-void ContentBrowserClientQt::GetQuotaSettings(content::BrowserContext* context,
- content::StoragePartition* partition,
- base::OnceCallback<void(base::Optional<storage::QuotaSettings>)> callback)
-{
- storage::GetNominalDynamicSettings(partition->GetPath(), context->IsOffTheRecord(),
- storage::GetDefaultDeviceInfoHelper(), std::move(callback));
-}
+ if (guest_view::GuestViewBase::IsGuest(webContents))
+ return;
-// Copied from chrome/browser/ssl/ssl_error_handler.cc:
-static int IsCertErrorFatal(int cert_error)
-{
- switch (cert_error) {
- case net::ERR_CERT_COMMON_NAME_INVALID:
- case net::ERR_CERT_DATE_INVALID:
- case net::ERR_CERT_AUTHORITY_INVALID:
- case net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM:
- case net::ERR_CERT_WEAK_KEY:
- case net::ERR_CERT_NAME_CONSTRAINT_VIOLATION:
- case net::ERR_CERT_VALIDITY_TOO_LONG:
- case net::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED:
- case net::ERR_CERT_SYMANTEC_LEGACY:
- return false;
- case net::ERR_CERT_CONTAINS_ERRORS:
- case net::ERR_CERT_REVOKED:
- case net::ERR_CERT_INVALID:
- case net::ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY:
- case net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN:
- return true;
- default:
- NOTREACHED();
- }
- return true;
+ WebContentsViewQt *view = WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(webContents)->GetView());
+ if (!view->client())
+ return;
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+ WebContentsDelegateQt* delegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
+ if (delegate)
+ delegate->overrideWebPreferences(webContents, web_prefs);
}
void ContentBrowserClientQt::AllowCertificateError(content::WebContents *webContents,
int cert_error,
const net::SSLInfo &ssl_info,
const GURL &request_url,
- bool is_main_frame_request,
+ bool /* is_main_frame_request */,
bool strict_enforcement,
base::OnceCallback<void(content::CertificateRequestResultType)> callback)
{
WebContentsDelegateQt* contentsDelegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
- QSharedPointer<CertificateErrorController> errorController(
- new CertificateErrorController(
- new CertificateErrorControllerPrivate(
- cert_error,
- ssl_info,
- request_url,
- is_main_frame_request,
- IsCertErrorFatal(cert_error),
- strict_enforcement,
- std::move(callback))));
+ QSharedPointer<CertificateErrorController> errorController(new CertificateErrorController(
+ cert_error, ssl_info, request_url, strict_enforcement, std::move(callback)));
contentsDelegate->allowCertificateError(errorController);
}
-base::OnceClosure ContentBrowserClientQt::SelectClientCertificate(content::WebContents *webContents,
+base::OnceClosure ContentBrowserClientQt::SelectClientCertificate(content::BrowserContext *browser_context,
+ content::WebContents *webContents,
net::SSLCertRequestInfo *certRequestInfo,
net::ClientCertIdentityList clientCerts,
std::unique_ptr<content::ClientCertificateDelegate> delegate)
{
+ Q_UNUSED(browser_context);
if (!clientCerts.empty()) {
- WebContentsDelegateQt* contentsDelegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
+ WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
QSharedPointer<ClientCertSelectController> certSelectController(
new ClientCertSelectController(certRequestInfo, std::move(clientCerts), std::move(delegate)));
@@ -496,8 +334,8 @@ void ContentBrowserClientQt::AppendExtraCommandLineSwitches(base::CommandLine* c
url::CustomScheme::SaveSchemes(command_line);
std::string processType = command_line->GetSwitchValueASCII(switches::kProcessType);
- if (processType == service_manager::switches::kZygoteProcess)
- command_line->AppendSwitchASCII(switches::kLang, GetApplicationLocale());
+ if (processType == switches::kZygoteProcess)
+ command_line->AppendSwitchASCII(switches::kLang, WebEngineLibraryInfo::getApplicationLocale());
}
void ContentBrowserClientQt::GetAdditionalWebUISchemes(std::vector<std::string>* additional_schemes)
@@ -522,12 +360,17 @@ void ContentBrowserClientQt::GetAdditionalAllowedSchemesForFileSystem(std::vecto
additional_schemes->push_back(content::kChromeUIScheme);
}
+std::unique_ptr<ui::SelectFilePolicy>
+ContentBrowserClientQt::CreateSelectFilePolicy(content::WebContents *web_contents)
+{
+ return std::make_unique<SelectFilePolicyQt>(web_contents);
+}
+
#if defined(Q_OS_LINUX)
void ContentBrowserClientQt::GetAdditionalMappedFilesForChildProcess(const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings)
{
- const std::string &locale = GetApplicationLocale();
- const base::FilePath &locale_file_path = ui::ResourceBundle::GetSharedInstance().GetLocaleFilePath(locale);
- if (locale_file_path.empty())
+ const base::FilePath &locale_file_path = ui::ResourceBundle::GetSharedInstance().GetLocaleFilePath(WebEngineLibraryInfo::getResolvedLocale());
+ if (locale_file_path.empty() || !base::PathExists(locale_file_path))
return;
// Open pak file of the current locale in the Browser process and pass its file descriptor to the sandboxed
@@ -538,101 +381,20 @@ void ContentBrowserClientQt::GetAdditionalMappedFilesForChildProcess(const base:
}
#endif
-#if QT_CONFIG(webengine_pepper_plugins)
-void ContentBrowserClientQt::DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host)
-{
- browser_host->GetPpapiHost()->AddHostFactoryFilter(
- std::make_unique<QtWebEngineCore::PepperHostFactoryQt>(browser_host));
-}
-#endif
-
-content::DevToolsManagerDelegate* ContentBrowserClientQt::GetDevToolsManagerDelegate()
-{
- return new DevToolsManagerDelegateQt;
-}
-
-content::PlatformNotificationService *ContentBrowserClientQt::GetPlatformNotificationService(content::BrowserContext *browser_context)
-{
- ProfileQt *profile = static_cast<ProfileQt *>(browser_context);
- if (!profile)
- return nullptr;
- return profile->platformNotificationService();
-}
-
-// This is a really complicated way of doing absolutely nothing, but Mojo demands it:
-class ServiceDriver
- : public blink::mojom::InsecureInputService
- , public content::WebContentsUserData<ServiceDriver>
-{
-public:
- static void CreateForRenderFrameHost(content::RenderFrameHost *renderFrameHost)
- {
- content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(renderFrameHost);
- if (!web_contents)
- return;
- CreateForWebContents(web_contents);
-
- }
- static ServiceDriver* FromRenderFrameHost(content::RenderFrameHost *renderFrameHost)
- {
- content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(renderFrameHost);
- if (!web_contents)
- return nullptr;
- return FromWebContents(web_contents);
- }
- static void BindInsecureInputService(blink::mojom::InsecureInputServiceRequest request, content::RenderFrameHost *render_frame_host)
- {
- CreateForRenderFrameHost(render_frame_host);
- ServiceDriver *driver = FromRenderFrameHost(render_frame_host);
-
- if (driver)
- driver->BindInsecureInputServiceRequest(std::move(request));
- }
- void BindInsecureInputServiceRequest(blink::mojom::InsecureInputServiceRequest request)
- {
- m_insecureInputServiceBindings.AddBinding(this, std::move(request));
- }
-
- // blink::mojom::InsecureInputService:
- void DidEditFieldInInsecureContext() override
- { }
-
-private:
- WEB_CONTENTS_USER_DATA_KEY_DECL();
- explicit ServiceDriver(content::WebContents* /*web_contents*/) { }
- friend class content::WebContentsUserData<ServiceDriver>;
- mojo::BindingSet<blink::mojom::InsecureInputService> m_insecureInputServiceBindings;
-};
-
-WEB_CONTENTS_USER_DATA_KEY_IMPL(ServiceDriver)
-
-void ContentBrowserClientQt::InitFrameInterfaces()
+std::unique_ptr<content::DevToolsManagerDelegate> ContentBrowserClientQt::CreateDevToolsManagerDelegate()
{
- m_frameInterfaces = std::make_unique<service_manager::BinderRegistry>();
- m_frameInterfacesParameterized = std::make_unique<service_manager::BinderRegistryWithArgs<content::RenderFrameHost*>>();
- m_frameInterfacesParameterized->AddInterface(base::BindRepeating(&ServiceDriver::BindInsecureInputService));
-}
-
-void ContentBrowserClientQt::BindInterfaceRequestFromFrame(content::RenderFrameHost* render_frame_host,
- const std::string& interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe)
-{
- if (!m_frameInterfaces.get() && !m_frameInterfacesParameterized.get())
- InitFrameInterfaces();
-
- if (!m_frameInterfacesParameterized->TryBindInterface(interface_name, &interface_pipe, render_frame_host))
- m_frameInterfaces->TryBindInterface(interface_name, &interface_pipe);
+ return std::make_unique<DevToolsManagerDelegateQt>();
}
void ContentBrowserClientQt::BindHostReceiverForRenderer(content::RenderProcessHost *render_process_host,
mojo::GenericPendingReceiver receiver)
{
-#if BUILDFLAG(ENABLE_SPELLCHECK)
+#if QT_CONFIG(webengine_spellchecker)
if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) {
SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver));
return;
}
-#endif // BUILDFLAG(ENABLE_SPELLCHECK)
+#endif
}
static void BindNetworkHintsHandler(content::RenderFrameHost *frame_host,
@@ -641,38 +403,120 @@ static void BindNetworkHintsHandler(content::RenderFrameHost *frame_host,
network_hints::SimpleNetworkHintsHandlerImpl::Create(frame_host, std::move(receiver));
}
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+static void BindMimeHandlerService(content::RenderFrameHost *frame_host,
+ mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService>
+ receiver) {
+ auto *web_contents = content::WebContents::FromRenderFrameHost(frame_host);
+ if (!web_contents)
+ return;
+ auto *guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents);
+ if (!guest_view)
+ return;
+ extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver));
+}
+
+static void BindBeforeUnloadControl(content::RenderFrameHost *frame_host,
+ mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl>
+ receiver) {
+ auto *web_contents = content::WebContents::FromRenderFrameHost(frame_host);
+ if (!web_contents)
+ return;
+ auto *guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents);
+ if (!guest_view)
+ return;
+ guest_view->FuseBeforeUnloadControl(std::move(receiver));
+}
+#endif
+
void ContentBrowserClientQt::RegisterBrowserInterfaceBindersForFrame(
content::RenderFrameHost *render_frame_host,
- service_manager::BinderMapWithContext<content::RenderFrameHost *> *map)
+ mojo::BinderMapWithContext<content::RenderFrameHost *> *map)
{
- Q_UNUSED(render_frame_host);
map->Add<network_hints::mojom::NetworkHintsHandler>(base::BindRepeating(&BindNetworkHintsHandler));
-}
-
-void ContentBrowserClientQt::RunServiceInstance(const service_manager::Identity &identity,
- mojo::PendingReceiver<service_manager::mojom::Service> *receiver)
-{
-#if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS)
- if (identity.name() == media::mojom::kMediaServiceName) {
- service_manager::Service::RunAsyncUntilTermination(media::CreateMediaService(std::move(*receiver)));
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ map->Add<extensions::mime_handler::MimeHandlerService>(base::BindRepeating(&BindMimeHandlerService));
+ map->Add<extensions::mime_handler::BeforeUnloadControl>(base::BindRepeating(&BindBeforeUnloadControl));
+ const GURL &site = render_frame_host->GetSiteInstance()->GetSiteURL();
+ if (!site.SchemeIs(extensions::kExtensionScheme))
return;
- }
+ content::BrowserContext *browser_context = render_frame_host->GetProcess()->GetBrowserContext();
+ auto *extension = extensions::ExtensionRegistry::Get(browser_context)
+ ->enabled_extensions()
+ .GetByID(site.host());
+ if (!extension)
+ return;
+ extensions::ExtensionsBrowserClient::Get()->RegisterBrowserInterfaceBindersForFrame(map,
+ render_frame_host,
+ extension);
+#else
+ Q_UNUSED(render_frame_host);
#endif
-
- content::ContentBrowserClient::RunServiceInstance(identity, receiver);
}
-base::Optional<service_manager::Manifest> ContentBrowserClientQt::GetServiceManifestOverlay(base::StringPiece name)
+void ContentBrowserClientQt::ExposeInterfacesToRenderer(service_manager::BinderRegistry *registry,
+ blink::AssociatedInterfaceRegistry *associated_registry,
+ content::RenderProcessHost *render_process_host)
{
- if (name == content::mojom::kBrowserServiceName)
- return GetQtWebEngineContentBrowserOverlayManifest();
-
- return base::nullopt;
+ if (auto *manager = performance_manager::PerformanceManagerRegistry::GetInstance())
+ manager->CreateProcessNodeAndExposeInterfacesToRendererProcess(registry, render_process_host);
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ associated_registry->AddInterface<extensions::mojom::EventRouter>(
+ base::BindRepeating(&extensions::EventRouter::BindForRenderer, render_process_host->GetID()));
+ associated_registry->AddInterface<guest_view::mojom::GuestViewHost>(
+ base::BindRepeating(&extensions::ExtensionsGuestView::CreateForComponents, render_process_host->GetID()));
+ associated_registry->AddInterface<extensions::mojom::GuestView>(
+ base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_process_host->GetID()));
+#else
+ Q_UNUSED(associated_registry);
+#endif
}
-std::vector<service_manager::Manifest> ContentBrowserClientQt::GetExtraServiceManifests()
+void ContentBrowserClientQt::RegisterAssociatedInterfaceBindersForRenderFrameHost(
+ content::RenderFrameHost &rfh,
+ blink::AssociatedInterfaceRegistry &associated_registry)
{
- return { };
+#if QT_CONFIG(webengine_webchannel)
+ associated_registry.AddInterface<qtwebchannel::mojom::WebChannelTransportHost>(
+ base::BindRepeating(
+ [](content::RenderFrameHost *render_frame_host,
+ mojo::PendingAssociatedReceiver<qtwebchannel::mojom::WebChannelTransportHost> receiver) {
+ auto *web_contents = content::WebContents::FromRenderFrameHost(render_frame_host);
+ auto *adapter = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate())->webContentsAdapter();
+ adapter->webChannelTransport()->BindReceiver(std::move(receiver), render_frame_host);
+ }, &rfh));
+#endif
+#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+ associated_registry.AddInterface<printing::mojom::PrintManagerHost>(
+ base::BindRepeating(
+ [](content::RenderFrameHost* render_frame_host,
+ mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) {
+ PrintViewManagerQt::BindPrintManagerHost(std::move(receiver), render_frame_host);
+ }, &rfh));
+#endif
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ associated_registry.AddInterface<extensions::mojom::LocalFrameHost>(
+ base::BindRepeating(
+ [](content::RenderFrameHost *render_frame_host,
+ mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) {
+ extensions::ExtensionWebContentsObserverQt::BindLocalFrameHost(std::move(receiver), render_frame_host);
+ }, &rfh));
+#endif
+ associated_registry.AddInterface<autofill::mojom::AutofillDriver>(
+ base::BindRepeating(
+ [](content::RenderFrameHost *render_frame_host,
+ mojo::PendingAssociatedReceiver<autofill::mojom::AutofillDriver> receiver) {
+ autofill::ContentAutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host);
+ }, &rfh));
+#if BUILDFLAG(ENABLE_PDF)
+ associated_registry.AddInterface<pdf::mojom::PdfService>(
+ base::BindRepeating(
+ [](content::RenderFrameHost *render_frame_host,
+ mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) {
+ pdf::PDFDocumentHelper::BindPdfService(std::move(receiver), render_frame_host, std::make_unique<PDFDocumentHelperClientQt>());
+ }, &rfh));
+#endif // BUILDFLAG(ENABLE_PDF)
+ ContentBrowserClient::RegisterAssociatedInterfaceBindersForRenderFrameHost(rfh, associated_registry);
}
bool ContentBrowserClientQt::CanCreateWindow(
@@ -724,6 +568,15 @@ std::unique_ptr<device::LocationProvider> ContentBrowserClientQt::OverrideSystem
}
#endif
+device::GeolocationManager *ContentBrowserClientQt::GetGeolocationManager()
+{
+#if BUILDFLAG(IS_MAC)
+ return m_browserMainParts->GetGeolocationManager();
+#else
+ return nullptr;
+#endif
+}
+
bool ContentBrowserClientQt::ShouldEnableStrictSiteIsolation()
{
// mirroring AwContentBrowserClient, CastContentBrowserClient and
@@ -731,15 +584,13 @@ bool ContentBrowserClientQt::ShouldEnableStrictSiteIsolation()
return false;
}
-bool ContentBrowserClientQt::WillCreateRestrictedCookieManager(
- network::mojom::RestrictedCookieManagerRole role,
+bool ContentBrowserClientQt::WillCreateRestrictedCookieManager(network::mojom::RestrictedCookieManagerRole role,
content::BrowserContext *browser_context,
const url::Origin & /*origin*/,
- const GURL & /*site_for_cookies*/,
- const url::Origin & /*top_frame_origin*/,
- bool is_service_worker,
- int process_id,
- int routing_id,
+ const net::IsolationInfo & /*isolation_info*/,
+ bool /*is_service_worker*/,
+ int /*process_id*/,
+ int /*routing_id*/,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> *receiver)
{
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> orig_receiver = std::move(*receiver);
@@ -750,53 +601,37 @@ bool ContentBrowserClientQt::WillCreateRestrictedCookieManager(
ProxyingRestrictedCookieManagerQt::CreateAndBind(
ProfileIODataQt::FromBrowserContext(browser_context),
std::move(target_rcm_remote),
- is_service_worker, process_id, routing_id,
std::move(orig_receiver));
return false; // only made a proxy, still need the actual impl to be made.
}
-bool ContentBrowserClientQt::AllowAppCache(const GURL &manifest_url,
- const GURL &first_party,
+content::AllowServiceWorkerResult
+ContentBrowserClientQt::AllowServiceWorker(const GURL &scope,
+ const net::SiteForCookies &site_for_cookies,
+ const absl::optional<url::Origin> & /*top_frame_origin*/,
+ const GURL & /*script_url*/,
content::BrowserContext *context)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- return static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(first_party), toQt(manifest_url));
-}
-
-bool ContentBrowserClientQt::AllowServiceWorkerOnIO(const GURL &scope,
- const GURL &site_for_cookies,
- const base::Optional<url::Origin> & /*top_frame_origin*/,
- const GURL & /*script_url*/,
- content::ResourceContext *context,
- base::RepeatingCallback<content::WebContents*()> wc_getter)
-{
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- // FIXME: Chrome also checks if javascript is enabled here to check if has been disabled since the service worker
- // was started.
- return ProfileIODataQt::FromResourceContext(context)->canGetCookies(toQt(site_for_cookies), toQt(scope));
-}
-
-bool ContentBrowserClientQt::AllowServiceWorkerOnUI(const GURL &scope,
- const GURL &site_for_cookies,
- const base::Optional<url::Origin> & /*top_frame_origin*/,
- const GURL & /*script_url*/,
- content::BrowserContext *context,
- base::RepeatingCallback<content::WebContents*()> wc_getter)
-{
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (!context || context->ShutdownStarted())
+ return content::AllowServiceWorkerResult::No();
// FIXME: Chrome also checks if javascript is enabled here to check if has been disabled since the service worker
// was started.
- return static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(site_for_cookies), toQt(scope));
+ return static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(site_for_cookies.first_party_url()), toQt(scope))
+ ? content::AllowServiceWorkerResult::Yes()
+ : content::AllowServiceWorkerResult::No();
}
// We control worker access to FS and indexed-db using cookie permissions, this is mirroring Chromium's logic.
void ContentBrowserClientQt::AllowWorkerFileSystem(const GURL &url,
content::BrowserContext *context,
- const std::vector<content::GlobalFrameRoutingId> &/*render_frames*/,
+ const std::vector<content::GlobalRenderFrameHostId> &/*render_frames*/,
base::OnceCallback<void(bool)> callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (!context || context->ShutdownStarted())
+ return std::move(callback).Run(false);
std::move(callback).Run(
static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(url), toQt(url)));
}
@@ -804,55 +639,83 @@ void ContentBrowserClientQt::AllowWorkerFileSystem(const GURL &url,
bool ContentBrowserClientQt::AllowWorkerIndexedDB(const GURL &url,
content::BrowserContext *context,
- const std::vector<content::GlobalFrameRoutingId> &/*render_frames*/)
+ const std::vector<content::GlobalRenderFrameHostId> &/*render_frames*/)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (!context || context->ShutdownStarted())
+ return false;
return static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(url), toQt(url));
}
static void LaunchURL(const GURL& url,
- base::OnceCallback<content::WebContents*()> web_contents_getter,
- ui::PageTransition page_transition, bool is_main_frame, bool has_user_gesture)
+ base::RepeatingCallback<content::WebContents*()> web_contents_getter,
+ ui::PageTransition page_transition,
+ network::mojom::WebSandboxFlags sandbox_flags,
+ bool is_main_frame, bool has_user_gesture)
{
Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
content::WebContents* webContents = std::move(web_contents_getter).Run();
if (!webContents)
return;
- ProtocolHandlerRegistry* protocolHandlerRegistry =
- ProtocolHandlerRegistryFactory::GetForBrowserContext(
- webContents->GetBrowserContext());
- if (protocolHandlerRegistry &&
- protocolHandlerRegistry->IsHandledProtocol(url.scheme()))
+ custom_handlers::ProtocolHandlerRegistry *protocolHandlerRegistry =
+ ProtocolHandlerRegistryFactory::GetForBrowserContext(webContents->GetBrowserContext());
+ if (protocolHandlerRegistry && protocolHandlerRegistry->IsHandledProtocol(url.scheme()))
return;
+ // Sandbox flag logic from chrome/browser/chrome_content_browser_client.cc:
+ if (!is_main_frame) {
+ using SandboxFlags = network::mojom::WebSandboxFlags;
+ auto allow = [&](SandboxFlags flag) {
+ return (sandbox_flags & flag) == SandboxFlags::kNone;
+ };
+ bool allowed = (allow(SandboxFlags::kPopups)) ||
+ (allow(SandboxFlags::kTopNavigation)) ||
+ (allow(SandboxFlags::kTopNavigationByUserActivation) &&
+ has_user_gesture);
+
+ if (!allowed) {
+ content::RenderFrameHost *rfh = webContents->GetPrimaryMainFrame();
+ if (!base::CommandLine::ForCurrentProcess()->HasSwitch("disable-sandbox-external-protocols")) {
+ rfh->AddMessageToConsole(blink::mojom::ConsoleMessageLevel::kError,
+ "Navigation to external protocol blocked by sandbox.");
+ return;
+ }
+ }
+ }
+
WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate());
contentsDelegate->launchExternalURL(toQt(url), page_transition, is_main_frame, has_user_gesture);
}
bool ContentBrowserClientQt::HandleExternalProtocol(const GURL &url,
- base::OnceCallback<content::WebContents*()> web_contents_getter,
- int child_id,
+ base::RepeatingCallback<content::WebContents*()> web_contents_getter,
+ int frame_tree_node_id,
content::NavigationUIData *navigation_data,
- bool is_main_frame,
+ bool is_primary_main_frame,
+ bool is_in_fenced_frame_tree,
+ network::mojom::WebSandboxFlags sandbox_flags,
ui::PageTransition page_transition,
bool has_user_gesture,
- const base::Optional<url::Origin> &initiating_origin,
+ const absl::optional<url::Origin> &initiating_origin,
+ content::RenderFrameHost *initiator_document,
mojo::PendingRemote<network::mojom::URLLoaderFactory> *out_factory)
{
-// Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
- Q_UNUSED(child_id);
+ Q_UNUSED(frame_tree_node_id);
+ Q_UNUSED(is_in_fenced_frame_tree);
Q_UNUSED(navigation_data);
Q_UNUSED(initiating_origin);
+ Q_UNUSED(initiator_document);
Q_UNUSED(out_factory);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&LaunchURL,
url,
std::move(web_contents_getter),
page_transition,
- is_main_frame,
+ sandbox_flags,
+ is_primary_main_frame,
has_user_gesture));
return true;
}
@@ -862,7 +725,7 @@ namespace {
class ProtocolHandlerThrottle : public blink::URLLoaderThrottle
{
public:
- explicit ProtocolHandlerThrottle(ProtocolHandlerRegistry *protocol_handler_registry)
+ explicit ProtocolHandlerThrottle(custom_handlers::ProtocolHandlerRegistry *protocol_handler_registry)
: protocol_handler_registry_(protocol_handler_registry)
{
}
@@ -877,7 +740,8 @@ public:
const network::mojom::URLResponseHead &response_head,
bool *defer,
std::vector<std::string> *to_be_removed_headers,
- net::HttpRequestHeaders *modified_headers) override
+ net::HttpRequestHeaders *modified_headers,
+ net::HttpRequestHeaders *modified_cors_exempt_headers) override
{
TranslateUrl(&redirect_info->new_url);
}
@@ -892,7 +756,7 @@ private:
*url = translated_url;
}
- ProtocolHandlerRegistry *protocol_handler_registry_;
+ custom_handlers::ProtocolHandlerRegistry *protocol_handler_registry_;
};
} // namespace
@@ -907,7 +771,7 @@ ContentBrowserClientQt::CreateURLLoaderThrottles(
ProtocolHandlerRegistryFactory::GetForBrowserContext(browser_context)));
#if BUILDFLAG(ENABLE_EXTENSIONS)
result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>(
- browser_context, request.resource_type, frame_tree_node_id));
+ request.destination, frame_tree_node_id));
#endif
return result;
}
@@ -938,23 +802,34 @@ WebContentsAdapterClient::NavigationType pageTransitionToNavigationType(ui::Page
}
}
-static bool navigationThrottleCallback(content::WebContents *source,
- const navigation_interception::NavigationParams &params)
+static bool navigationThrottleCallback(content::NavigationHandle *handle)
{
// We call navigationRequested later in launchExternalUrl for external protocols.
// The is_external_protocol parameter here is not fully accurate though,
// and doesn't know about profile specific custom URL schemes.
+ content::WebContents *source = handle->GetWebContents();
ProfileQt *profile = static_cast<ProfileQt *>(source->GetBrowserContext());
- if (params.is_external_protocol() && !profile->profileAdapter()->urlSchemeHandler(toQByteArray(params.url().scheme())))
+ if (handle->IsExternalProtocol() && !profile->profileAdapter()->urlSchemeHandler(toQByteArray(handle->GetURL().scheme())))
return false;
- int navigationRequestAction = WebContentsAdapterClient::AcceptRequest;
- WebContentsDelegateQt *delegate = static_cast<WebContentsDelegateQt *>(source->GetDelegate());
- WebContentsAdapterClient *client = delegate->adapterClient();
- client->navigationRequested(pageTransitionToNavigationType(params.transition_type()),
- toQt(params.url()),
- navigationRequestAction,
- params.is_main_frame());
- return navigationRequestAction == static_cast<int>(WebContentsAdapterClient::IgnoreRequest);
+
+ bool navigationAccepted = true;
+
+ WebContentsAdapterClient *client =
+ WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(source)->GetView())->client();
+ if (!client)
+ return false;
+
+ // Redirects might not be reflected in transition_type at this point (see also chrome/.../web_navigation_api_helpers.cc)
+ auto transition_type = handle->GetPageTransition();
+ if (handle->WasServerRedirect())
+ transition_type = ui::PageTransitionFromInt(transition_type | ui::PAGE_TRANSITION_SERVER_REDIRECT);
+
+ client->navigationRequested(pageTransitionToNavigationType(transition_type),
+ toQt(handle->GetURL()),
+ navigationAccepted,
+ handle->IsInPrimaryMainFrame(),
+ handle->IsFormSubmission());
+ return !navigationAccepted;
}
std::vector<std::unique_ptr<content::NavigationThrottle>> ContentBrowserClientQt::CreateThrottlesForNavigation(
@@ -965,6 +840,14 @@ std::vector<std::unique_ptr<content::NavigationThrottle>> ContentBrowserClientQt
navigation_handle,
base::BindRepeating(&navigationThrottleCallback),
navigation_interception::SynchronyMode::kSync));
+
+#if BUILDFLAG(ENABLE_PDF) && BUILDFLAG(ENABLE_EXTENSIONS)
+ MaybeAddThrottle(
+ extensions::PDFIFrameNavigationThrottleQt::MaybeCreateThrottleFor(navigation_handle),
+ &throttles);
+ MaybeAddThrottle(pdf::PdfNavigationThrottle::MaybeCreateThrottleFor(navigation_handle, std::make_unique<PdfStreamDelegateQt>()), &throttles);
+#endif // BUILDFLAG(ENABLE_PDF) && BUIDLFLAG(ENABLE_EXTENSIONS)
+
return throttles;
}
@@ -973,6 +856,32 @@ bool ContentBrowserClientQt::IsHandledURL(const GURL &url)
return url::IsHandledProtocol(url.scheme());
}
+bool ContentBrowserClientQt::HasCustomSchemeHandler(content::BrowserContext *browser_context,
+ const std::string &scheme)
+{
+ if (custom_handlers::ProtocolHandlerRegistry *protocol_handler_registry =
+ ProtocolHandlerRegistryFactory::GetForBrowserContext(browser_context)) {
+ return protocol_handler_registry->IsHandledProtocol(scheme);
+ }
+
+ return false;
+}
+
+bool ContentBrowserClientQt::HasErrorPage(int httpStatusCode, content::WebContents *contents)
+{
+ if (contents) {
+ WebEngineSettings *settings = nullptr;
+ WebContentsDelegateQt *delegate =
+ static_cast<WebContentsDelegateQt*>(contents->GetDelegate());
+ if (delegate)
+ settings = delegate->webEngineSettings();
+ if (settings && !settings->testAttribute(QWebEngineSettings::ErrorPageEnabled))
+ return false;
+ }
+ // Use an internal error page, if we have one for the status code.
+ return error_page::LocalizedError::HasStrings(error_page::Error::kHttpErrorDomain, httpStatusCode);
+}
+
std::unique_ptr<content::LoginDelegate> ContentBrowserClientQt::CreateLoginDelegate(
const net::AuthChallengeInfo &authInfo,
content::WebContents *web_contents,
@@ -1033,10 +942,40 @@ bool ContentBrowserClientQt::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(base::
#endif
}
+bool ContentBrowserClientQt::DoesSchemeAllowCrossOriginSharedWorker(const std::string &scheme)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ // Extensions are allowed to start cross-origin shared workers.
+ return scheme == extensions::kExtensionScheme;
+#else
+ return false;
+#endif
+}
+
+void ContentBrowserClientQt::OverrideURLLoaderFactoryParams(content::BrowserContext *browser_context,
+ const url::Origin &origin,
+ bool is_for_isolated_world,
+ network::mojom::URLLoaderFactoryParams *factory_params)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams(
+ browser_context, origin, is_for_isolated_world, factory_params);
+#endif
+}
+
std::string ContentBrowserClientQt::getUserAgent()
{
// Mention the Chromium version we're based on to get passed stupid UA-string-based feature detection (several WebRTC demos need this)
- return content::BuildUserAgentFromProduct("QtWebEngine/" QTWEBENGINECORE_VERSION_STR " Chrome/" CHROMIUM_VERSION);
+ return content::BuildUserAgentFromProduct("QtWebEngine/" + std::string(qWebEngineVersion())
+ + " Chrome/"
+ + std::string(qWebEngineChromiumVersion()));
+}
+
+blink::UserAgentMetadata ContentBrowserClientQt::GetUserAgentMetadata()
+{
+ // Implemented only for safe-keeping. It will be overridden on WebContents level.
+ static blink::UserAgentMetadata userAgentMetadata(embedder_support::GetUserAgentMetadata());
+ return userAgentMetadata;
}
std::string ContentBrowserClientQt::GetProduct()
@@ -1068,32 +1007,30 @@ void ContentBrowserClientQt::OnNetworkServiceCreated(network::mojom::NetworkServ
SystemNetworkContextManager::GetInstance()->OnNetworkServiceCreated(network_service);
}
-mojo::Remote<network::mojom::NetworkContext> ContentBrowserClientQt::CreateNetworkContext(
+void ContentBrowserClientQt::ConfigureNetworkContextParams(
content::BrowserContext *context,
bool in_memory,
- const base::FilePath &relative_partition_path)
+ const base::FilePath &relative_partition_path,
+ network::mojom::NetworkContextParams *network_context_params,
+ cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params)
{
- mojo::Remote<network::mojom::NetworkContext> network_context;
- // ### do we need to pass in_memory and relative_partition_path to ProfileIODataQt::CreateNetworkContextParams() ?
- network::mojom::NetworkContextParamsPtr context_params = ProfileIODataQt::FromBrowserContext(context)->CreateNetworkContextParams();
- content::GetNetworkService()->CreateNetworkContext(
- network_context.BindNewPipeAndPassReceiver(), std::move(context_params));
-
- network::mojom::CookieManagerPtrInfo cookie_manager_info;
- network_context->GetCookieManager(mojo::MakeRequest(&cookie_manager_info));
- ProfileIODataQt::FromBrowserContext(context)->cookieDelegate()->setMojoCookieManager(std::move(cookie_manager_info));
+ ProfileIODataQt::FromBrowserContext(context)->ConfigureNetworkContextParams(in_memory, relative_partition_path,
+ network_context_params, cert_verifier_creation_params);
- return network_context;
+ mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_remote;
+ network_context_params->cookie_manager = cookie_manager_remote.InitWithNewPipeAndPassReceiver();
+ ProfileIODataQt::FromBrowserContext(context)->cookieDelegate()->setMojoCookieManager(std::move(cookie_manager_remote));
}
std::vector<base::FilePath> ContentBrowserClientQt::GetNetworkContextsParentDirectory()
{
return {
- toFilePath(QStandardPaths::writableLocation(QStandardPaths::DataLocation)),
+ toFilePath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)),
toFilePath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) };
}
void ContentBrowserClientQt::RegisterNonNetworkNavigationURLLoaderFactories(int frame_tree_node_id,
+ ukm::SourceIdObj ukm_source_id,
NonNetworkURLLoaderFactoryMap *factories)
{
content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
@@ -1106,7 +1043,7 @@ void ContentBrowserClientQt::RegisterNonNetworkNavigationURLLoaderFactories(int
#if BUILDFLAG(ENABLE_EXTENSIONS)
factories->emplace(
extensions::kExtensionScheme,
- extensions::CreateExtensionNavigationURLLoaderFactory(profile,
+ extensions::CreateExtensionNavigationURLLoaderFactory(profile, ukm_source_id,
!!extensions::WebViewGuest::FromWebContents(web_contents)));
#endif
}
@@ -1119,11 +1056,39 @@ void ContentBrowserClientQt::RegisterNonNetworkWorkerMainResourceURLLoaderFactor
for (const QByteArray &scheme : profileAdapter->customUrlSchemes())
factories->emplace(scheme.toStdString(), CreateCustomURLLoaderFactory(profileAdapter));
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ factories->emplace(
+ extensions::kExtensionScheme,
+ extensions::CreateExtensionWorkerMainResourceURLLoaderFactory(browser_context));
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+}
+
+void ContentBrowserClientQt::RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories(content::BrowserContext* browser_context,
+ NonNetworkURLLoaderFactoryMap* factories)
+{
+ Profile *profile = Profile::FromBrowserContext(browser_context);
+ ProfileAdapter *profileAdapter = static_cast<ProfileQt *>(profile)->profileAdapter();
+
+ for (const QByteArray &scheme : profileAdapter->customUrlSchemes()) {
+ if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(scheme.toStdString())) {
+ if (cs->flags & url::CustomScheme::ServiceWorkersAllowed)
+ factories->emplace(scheme.toStdString(), CreateCustomURLLoaderFactory(profileAdapter));
+ }
+ }
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ factories->emplace(
+ extensions::kExtensionScheme,
+ extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory(browser_context));
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
}
void ContentBrowserClientQt::RegisterNonNetworkSubresourceURLLoaderFactories(int render_process_id, int render_frame_id,
+ const absl::optional<url::Origin> &request_initiator_origin,
NonNetworkURLLoaderFactoryMap *factories)
{
+ Q_UNUSED(request_initiator_origin);
content::RenderProcessHost *process_host = content::RenderProcessHost::FromID(render_process_id);
Profile *profile = Profile::FromBrowserContext(process_host->GetBrowserContext());
ProfileAdapter *profileAdapter = static_cast<ProfileQt *>(profile)->profileAdapter();
@@ -1137,23 +1102,18 @@ void ContentBrowserClientQt::RegisterNonNetworkSubresourceURLLoaderFactories(int
if (web_contents)
url = web_contents->GetVisibleURL();
- // Install file scheme if necessary:
- // FIXME: "extension -> file" will not be needed after switching to using transferable url loaders and guest views.
- // FIXME: "qrc -> file" should be reconsidered for Qt6.
- bool install_file_scheme = url.SchemeIs("qrc");
+ bool is_background_page = false;
#if BUILDFLAG(ENABLE_EXTENSIONS)
- install_file_scheme = install_file_scheme || url.SchemeIs(extensions::kExtensionScheme);
-#endif
- if (!install_file_scheme && web_contents) {
- const auto *settings = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate())->webEngineSettings();
- if (settings->testAttribute(WebEngineSettings::LocalContentCanAccessFileUrls)) {
- for (const auto &local_scheme : url::GetLocalSchemes()) {
- if (url.SchemeIs(local_scheme)) {
- install_file_scheme = true;
- break;
- }
- }
- }
+ is_background_page = extensions::GetViewType(web_contents) == extensions::mojom::ViewType::kExtensionBackgroundPage;
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+ // Install file scheme if necessary:
+ bool install_file_scheme = false;
+ if (web_contents && !is_background_page) {
+ const std::string scheme = url.scheme();
+ install_file_scheme = base::Contains(url::GetLocalSchemes(), scheme);
+ if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(scheme))
+ install_file_scheme = cs->flags & (url::CustomScheme::LocalAccessAllowed | url::CustomScheme::Local);
}
if (install_file_scheme && factories->find(url::kFileScheme) == factories->end()) {
@@ -1189,48 +1149,236 @@ void ContentBrowserClientQt::RegisterNonNetworkSubresourceURLLoaderFactories(int
}
if (!allowed_webui_hosts.empty()) {
factories->emplace(content::kChromeUIScheme,
- content::CreateWebUIURLLoader(frame_host,
- content::kChromeUIScheme,
- std::move(allowed_webui_hosts)));
+ content::CreateWebUIURLLoaderFactory(frame_host,
+ content::kChromeUIScheme,
+ std::move(allowed_webui_hosts)));
}
#endif
}
+base::flat_set<std::string> ContentBrowserClientQt::GetPluginMimeTypesWithExternalHandlers(
+ content::BrowserContext *browser_context)
+{
+ base::flat_set<std::string> mime_types;
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ ProfileQt *profile = static_cast<ProfileQt *>(browser_context);
+ for (const std::string &extension_id : MimeTypesHandler::GetMIMETypeAllowlist()) {
+ const extensions::Extension *extension =
+ extensions::ExtensionRegistry::Get(browser_context)
+ ->enabled_extensions()
+ .GetByID(extension_id);
+ // The allowed extension may not be installed, so we have to nullptr
+ // check |extension|.
+ if (!extension ||
+ (profile->IsOffTheRecord() && !extensions::util::IsIncognitoEnabled(
+ extension_id, browser_context))) {
+ continue;
+ }
+ if (MimeTypesHandler *handler = MimeTypesHandler::GetHandler(extension)) {
+ for (const auto &supported_mime_type : handler->mime_type_set())
+ mime_types.insert(supported_mime_type);
+ }
+ }
+#endif
+#if BUILDFLAG(ENABLE_PDF)
+ mime_types.insert("application/x-google-chrome-pdf");
+#endif
+ return mime_types;
+}
+
bool ContentBrowserClientQt::WillCreateURLLoaderFactory(
content::BrowserContext *browser_context,
content::RenderFrameHost *frame,
int render_process_id,
URLLoaderFactoryType type,
const url::Origin &request_initiator,
- base::Optional<int64_t> navigation_id,
+ absl::optional<int64_t> navigation_id,
+ ukm::SourceIdObj ukm_source_id,
mojo::PendingReceiver<network::mojom::URLLoaderFactory> *factory_receiver,
mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> *header_client,
bool *bypass_redirect_checks,
- network::mojom::URLLoaderFactoryOverridePtr *factory_override)
+ bool *disable_secure_dns,
+ network::mojom::URLLoaderFactoryOverridePtr *factory_override,
+ scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner)
+{
+ Q_UNUSED(render_process_id);
+ Q_UNUSED(type);
+ Q_UNUSED(request_initiator);
+ Q_UNUSED(navigation_id);
+ Q_UNUSED(ukm_source_id);
+ Q_UNUSED(header_client);
+ Q_UNUSED(bypass_redirect_checks);
+ Q_UNUSED(disable_secure_dns);
+ Q_UNUSED(factory_override);
+ auto adapter = static_cast<ProfileQt *>(browser_context)->profileAdapter();
+ auto proxied_receiver = std::move(*factory_receiver);
+ mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_url_loader_factory;
+ *factory_receiver = pending_url_loader_factory.InitWithNewPipeAndPassReceiver();
+ // Will manage its own lifetime
+ // FIXME: use navigation_response_task_runner?
+ new ProxyingURLLoaderFactoryQt(adapter,
+ frame ? frame->GetFrameTreeNodeId() : content::RenderFrameHost::kNoFrameTreeNodeId,
+ std::move(proxied_receiver), std::move(pending_url_loader_factory));
+ return true;
+}
+
+std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>>
+ContentBrowserClientQt::WillCreateURLLoaderRequestInterceptors(content::NavigationUIData* navigation_ui_data,
+ int frame_tree_node_id, int64_t navigation_id,
+ scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner)
{
- auto *web_contents = content::WebContents::FromRenderFrameHost(frame);
- ProfileQt *profile = static_cast<ProfileQt *>(browser_context);
+ std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> interceptors;
+#if BUILDFLAG(ENABLE_PDF) && BUILDFLAG(ENABLE_EXTENSIONS)
+ {
+ std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor =
+ pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor(
+ frame_tree_node_id, std::make_unique<PdfStreamDelegateQt>());
+ if (pdf_interceptor)
+ interceptors.push_back(std::move(pdf_interceptor));
+ }
+#endif // BUILDFLAG(ENABLE_PDF) && BUIDLFLAG(ENABLE_EXTENSIONS)
- QWebEngineUrlRequestInterceptor *profile_interceptor = profile->profileAdapter()->requestInterceptor();
- QWebEngineUrlRequestInterceptor *page_interceptor = nullptr;
+ return interceptors;
+}
+
+bool ContentBrowserClientQt::WillInterceptWebSocket(content::RenderFrameHost *frame)
+{
+ return frame != nullptr;
+}
+
+QWebEngineUrlRequestInterceptor *getProfileInterceptorFromFrame(content::RenderFrameHost *frame)
+{
+ ProfileQt *profile = static_cast<ProfileQt *>(frame->GetBrowserContext());
+ if (profile)
+ return profile->profileAdapter()->requestInterceptor();
+ return nullptr;
+}
+QWebEngineUrlRequestInterceptor *getPageInterceptor(content::WebContents *web_contents)
+{
if (web_contents) {
- WebContentsAdapterClient *client =
- WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(web_contents)->GetView())->client();
- page_interceptor = client->webContentsAdapter()->requestInterceptor();
+ auto view = static_cast<content::WebContentsImpl *>(web_contents)->GetView();
+ if (WebContentsAdapterClient *client = WebContentsViewQt::from(view)->client())
+ return client->webContentsAdapter()->requestInterceptor();
}
+ return nullptr;
+}
- if (profile_interceptor || page_interceptor) {
- int process_id = type == URLLoaderFactoryType::kNavigation ? 0 : render_process_id;
- auto proxied_receiver = std::move(*factory_receiver);
- mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_url_loader_factory;
- *factory_receiver = pending_url_loader_factory.InitWithNewPipeAndPassReceiver();
- // Will manage its own lifetime
- new ProxyingURLLoaderFactoryQt(process_id, profile_interceptor, page_interceptor, std::move(proxied_receiver),
- std::move(pending_url_loader_factory));
- return true;
+void ContentBrowserClientQt::CreateWebSocket(
+ content::RenderFrameHost *frame,
+ WebSocketFactory factory,
+ const GURL &url,
+ const net::SiteForCookies &site_for_cookies,
+ const absl::optional<std::string> &user_agent,
+ mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client)
+{
+ QWebEngineUrlRequestInterceptor *profileInterceptor = getProfileInterceptorFromFrame(frame);
+ content::WebContents *web_contents = content::WebContents::FromRenderFrameHost(frame);
+ QWebEngineUrlRequestInterceptor *pageInterceptor = getPageInterceptor(web_contents);
+ std::vector<network::mojom::HttpHeaderPtr> headers;
+ GURL to_url = url;
+ bool addedUserAgent = false;
+ if (profileInterceptor || pageInterceptor) {
+ QUrl initiator = web_contents ? toQt(web_contents->GetURL()) : QUrl();
+ auto *infoPrivate = new QWebEngineUrlRequestInfoPrivate(
+ QWebEngineUrlRequestInfo::ResourceTypeWebSocket,
+ QWebEngineUrlRequestInfo::NavigationTypeOther,
+ toQt(url), toQt(site_for_cookies.first_party_url()), initiator,
+ QByteArrayLiteral("GET"));
+ QWebEngineUrlRequestInfo requestInfo(infoPrivate);
+ if (profileInterceptor) {
+ profileInterceptor->interceptRequest(requestInfo);
+ pageInterceptor = getPageInterceptor(web_contents);
+ }
+ if (pageInterceptor && !requestInfo.changed())
+ pageInterceptor->interceptRequest(requestInfo);
+ if (infoPrivate->shouldBlockRequest)
+ return; // ### should we call OnFailure on handshake_client?
+ if (infoPrivate->shouldRedirectRequest)
+ to_url = toGurl(infoPrivate->url);
+ for (auto header = infoPrivate->extraHeaders.constBegin(); header != infoPrivate->extraHeaders.constEnd(); ++header) {
+ std::string h = header.key().toStdString();
+ if (base::EqualsCaseInsensitiveASCII(h, net::HttpRequestHeaders::kUserAgent))
+ addedUserAgent = true;
+ headers.push_back(network::mojom::HttpHeader::New(h, header.value().toStdString()));
+ }
}
- return false;
+ if (!addedUserAgent && user_agent)
+ headers.push_back(network::mojom::HttpHeader::New(net::HttpRequestHeaders::kUserAgent, *user_agent));
+
+ std::move(factory).Run(to_url, std::move(headers), std::move(handshake_client), mojo::NullRemote(), mojo::NullRemote());
+}
+
+void ContentBrowserClientQt::SiteInstanceGotProcess(content::SiteInstance *site_instance)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ content::BrowserContext *context = site_instance->GetBrowserContext();
+ extensions::ExtensionRegistry *registry = extensions::ExtensionRegistry::Get(context);
+ if (!registry)
+ return;
+ if (site_instance->IsGuest())
+ return;
+ auto site_url = site_instance->GetSiteURL();
+ if (!site_url.SchemeIs(extensions::kExtensionScheme))
+ return;
+ const extensions::Extension *extension = registry->enabled_extensions().GetByID(site_url.host());
+ if (!extension)
+ return;
+
+ extensions::ProcessMap *processMap = extensions::ProcessMap::Get(context);
+ processMap->Insert(extension->id(), site_instance->GetProcess()->GetID());
+#endif
+}
+
+std::unique_ptr<content::WebContentsViewDelegate> ContentBrowserClientQt::GetWebContentsViewDelegate(content::WebContents *web_contents)
+{
+ FormInteractionTabHelper::CreateForWebContents(web_contents);
+ FileSystemAccessPermissionRequestManagerQt::CreateForWebContents(web_contents);
+ if (auto *registry = performance_manager::PerformanceManagerRegistry::GetInstance())
+ registry->MaybeCreatePageNodeForWebContents(web_contents);
+
+ return nullptr;
+}
+
+content::ContentBrowserClient::AllowWebBluetoothResult
+ContentBrowserClientQt::AllowWebBluetooth(content::BrowserContext *browser_context,
+ const url::Origin &requesting_origin,
+ const url::Origin &embedding_origin)
+{
+ DCHECK(browser_context);
+ return content::ContentBrowserClient::AllowWebBluetoothResult::BLOCK_GLOBALLY_DISABLED;
+}
+
+content::WebAuthenticationDelegate *ContentBrowserClientQt::GetWebAuthenticationDelegate()
+{
+ static base::NoDestructor<WebAuthenticationDelegateQt> delegate;
+ return delegate.get();
+}
+
+#if !BUILDFLAG(IS_ANDROID)
+std::unique_ptr<content::AuthenticatorRequestClientDelegate>
+ContentBrowserClientQt::GetWebAuthenticationRequestDelegate(
+ content::RenderFrameHost *render_frame_host)
+{
+ return std::make_unique<AuthenticatorRequestClientDelegateQt>(render_frame_host);
+}
+#endif
+
+void ContentBrowserClientQt::GetMediaDeviceIDSalt(content::RenderFrameHost *rfh,
+ const net::SiteForCookies & /*site_for_cookies*/,
+ const blink::StorageKey & /*storage_key*/,
+ base::OnceCallback<void(bool, const std::string&)> callback)
+{
+#if BUILDFLAG(ENABLE_WEBRTC)
+ content::BrowserContext *browser_context = rfh->GetBrowserContext();
+ if (!browser_context->IsOffTheRecord()) {
+ ProfileQt *profile = static_cast<ProfileQt *>(browser_context);
+ std::string mediaId = profile->GetMediaDeviceIDSalt();
+ std::move(callback).Run(true, mediaId);
+ return;
+ }
+#endif
+ std::move(callback).Run(false, "");
}
} // namespace QtWebEngineCore
diff --git a/src/core/content_browser_client_qt.h b/src/core/content_browser_client_qt.h
index f536f2427..7d8e98028 100644
--- a/src/core/content_browser_client_qt.h
+++ b/src/core/content_browser_client_qt.h
@@ -1,53 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_BROWSER_CLIENT_QT_H
#define CONTENT_BROWSER_CLIENT_QT_H
#include "qtwebenginecoreglobal_p.h"
-#include "base/memory/ref_counted.h"
#include "content/public/browser/content_browser_client.h"
-namespace net {
-class URLRequestContextGetter;
-}
-
namespace content {
class BrowserContext;
class BrowserMainParts;
@@ -59,39 +18,30 @@ class BrowserPpapiHost;
class DevToolsManagerDelegate;
class RenderFrameHost;
class RenderProcessHost;
-class RenderViewHostDelegateView;
class ResourceContext;
-class ResourceDispatcherHostDelegate;
-class WebContentsViewPort;
class WebContents;
struct MainFunctionParams;
struct Referrer;
-}
+} // namespace content
-namespace gl {
-class GLShareGroup;
-}
+namespace device {
+class GeolocationManager;
+} // namespace device
namespace QtWebEngineCore {
class BrowserMainPartsQt;
-class ProfileQt;
-class ShareGroupQt;
class ContentBrowserClientQt : public content::ContentBrowserClient
{
public:
ContentBrowserClientQt();
~ContentBrowserClientQt();
- std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(const content::MainFunctionParams&) override;
+ std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(bool is_integration_test) override;
void RenderProcessWillLaunch(content::RenderProcessHost *host) override;
- gl::GLShareGroup* GetInProcessGpuShareGroup() override;
content::MediaObserver* GetMediaObserver() override;
- scoped_refptr<content::QuotaPermissionContext> CreateQuotaPermissionContext() override;
- void GetQuotaSettings(content::BrowserContext *context,
- content::StoragePartition *partition,
- base::OnceCallback<void(base::Optional<storage::QuotaSettings>)> callback) override;
- void OverrideWebkitPrefs(content::RenderViewHost *, content::WebPreferences *) override;
+ void OverrideWebkitPrefs(content::WebContents *web_contents,
+ blink::web_pref::WebPreferences *prefs) override;
void AllowCertificateError(content::WebContents *web_contents,
int cert_error,
const net::SSLInfo &ssl_info,
@@ -99,13 +49,13 @@ public:
bool is_main_frame_request,
bool strict_enforcement,
base::OnceCallback<void(content::CertificateRequestResultType)> callback) override;
- base::OnceClosure SelectClientCertificate(content::WebContents* web_contents,
+ base::OnceClosure SelectClientCertificate(content::BrowserContext* browser_context,
+ content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
std::unique_ptr<net::ClientCertStore> CreateClientCertStore(content::BrowserContext *browser_context) override;
- content::DevToolsManagerDelegate *GetDevToolsManagerDelegate() override;
- content::PlatformNotificationService * GetPlatformNotificationService(content::BrowserContext *browser_context) override;
+ std::unique_ptr<content::DevToolsManagerDelegate> CreateDevToolsManagerDelegate() override;
std::string GetApplicationLocale() override;
std::string GetAcceptLangs(content::BrowserContext* context) override;
@@ -115,18 +65,18 @@ public:
void GetAdditionalWebUISchemes(std::vector<std::string>* additional_schemes) override;
void GetAdditionalAllowedSchemesForFileSystem(std::vector<std::string>* additional_schemes) override;
- void BindInterfaceRequestFromFrame(content::RenderFrameHost* render_frame_host,
- const std::string& interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe) override;
+ std::unique_ptr<ui::SelectFilePolicy>
+ CreateSelectFilePolicy(content::WebContents *web_contents) override;
void BindHostReceiverForRenderer(content::RenderProcessHost *render_process_host,
mojo::GenericPendingReceiver receiver) override;
void RegisterBrowserInterfaceBindersForFrame(content::RenderFrameHost *render_frame_host,
- service_manager::BinderMapWithContext<content::RenderFrameHost *> *map) override;
- void RunServiceInstance(const service_manager::Identity &identity,
- mojo::PendingReceiver<service_manager::mojom::Service> *receiver) override;
+ mojo::BinderMapWithContext<content::RenderFrameHost *> *map) override;
+ void ExposeInterfacesToRenderer(service_manager::BinderRegistry *registry,
+ blink::AssociatedInterfaceRegistry *associated_registry,
+ content::RenderProcessHost *render_process_host) override;
+ void RegisterAssociatedInterfaceBindersForRenderFrameHost(content::RenderFrameHost &render_frame_host,
+ blink::AssociatedInterfaceRegistry &associated_registry) override;
- std::vector<service_manager::Manifest> GetExtraServiceManifests() override;
- base::Optional<service_manager::Manifest> GetServiceManifestOverlay(base::StringPiece name) override;
bool CanCreateWindow(content::RenderFrameHost *opener,
const GURL &opener_url,
const GURL &opener_top_level_frame_url,
@@ -146,43 +96,44 @@ public:
network::mojom::RestrictedCookieManagerRole role,
content::BrowserContext *browser_context,
const url::Origin &origin,
- const GURL &site_for_cookies,
- const url::Origin &top_frame_origin,
+ const net::IsolationInfo &isolation_info,
bool is_service_worker,
int process_id,
int routing_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> *receiver) override;
+ bool WillInterceptWebSocket(content::RenderFrameHost *frame) override;
+ void CreateWebSocket(
+ content::RenderFrameHost *frame,
+ WebSocketFactory factory,
+ const GURL &url,
+ const net::SiteForCookies &site_for_cookies,
+ const absl::optional<std::string> &user_agent,
+ mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) override;
- bool AllowAppCache(const GURL &manifest_url,
- const GURL &first_party,
- content::BrowserContext *context) override;
-
- bool AllowServiceWorkerOnIO(const GURL &scope,
- const GURL &site_for_cookies,
- const base::Optional<url::Origin> &top_frame_origin,
- const GURL &script_url,
- content::ResourceContext *context,
- base::RepeatingCallback<content::WebContents*()> wc_getter) override;
-
- bool AllowServiceWorkerOnUI(const GURL &scope,
- const GURL &site_for_cookies,
- const base::Optional<url::Origin> &top_frame_origin,
- const GURL &script_url,
- content::BrowserContext *context,
- base::RepeatingCallback<content::WebContents*()> wc_getter) override;
+ content::AllowServiceWorkerResult AllowServiceWorker(
+ const GURL &scope,
+ const net::SiteForCookies &site_for_cookies,
+ const absl::optional<url::Origin> &top_frame_origin,
+ const GURL &script_url,
+ content::BrowserContext *context) override;
void AllowWorkerFileSystem(const GURL &url,
content::BrowserContext *context,
- const std::vector<content::GlobalFrameRoutingId> &render_frames,
+ const std::vector<content::GlobalRenderFrameHostId> &render_frames,
base::OnceCallback<void(bool)> callback) override;
bool AllowWorkerIndexedDB(const GURL &url,
content::BrowserContext *context,
- const std::vector<content::GlobalFrameRoutingId> &render_frames) override;
+ const std::vector<content::GlobalRenderFrameHostId> &render_frames) override;
+ AllowWebBluetoothResult AllowWebBluetooth(content::BrowserContext *browser_context,
+ const url::Origin &requesting_origin,
+ const url::Origin &embedding_origin) override;
#if QT_CONFIG(webengine_geolocation)
std::unique_ptr<device::LocationProvider> OverrideSystemLocationProvider() override;
#endif
+ device::GeolocationManager *GetGeolocationManager() override;
+
bool ShouldIsolateErrorPage(bool in_main_frame) override;
bool ShouldUseProcessPerSite(content::BrowserContext *browser_context, const GURL &effective_url) override;
bool DoesSiteRequireDedicatedProcess(content::BrowserContext *browser_context,
@@ -190,15 +141,15 @@ public:
bool ShouldUseSpareRenderProcessHost(content::BrowserContext *browser_context, const GURL& site_url) override;
bool ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(base::StringPiece scheme,
bool is_embedded_origin_secure) override;
-
+ bool DoesSchemeAllowCrossOriginSharedWorker(const std::string &scheme) override;
+ void OverrideURLLoaderFactoryParams(content::BrowserContext *browser_context,
+ const url::Origin &origin,
+ bool is_for_isolated_world,
+ network::mojom::URLLoaderFactoryParams *factory_params) override;
#if defined(Q_OS_LINUX)
void GetAdditionalMappedFilesForChildProcess(const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) override;
#endif
-#if QT_CONFIG(webengine_pepper_plugins)
- void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override;
-#endif
-
std::unique_ptr<content::LoginDelegate> CreateLoginDelegate(
const net::AuthChallengeInfo &auth_info,
content::WebContents *web_contents,
@@ -211,13 +162,16 @@ public:
bool HandleExternalProtocol(
const GURL &url,
- base::OnceCallback<content::WebContents*()> web_contents_getter,
- int child_id,
+ base::RepeatingCallback<content::WebContents*()> web_contents_getter,
+ int frame_tree_node_id,
content::NavigationUIData *navigation_data,
- bool is_main_frame,
+ bool is_primary_main_frame,
+ bool is_in_fenced_frame_tree,
+ network::mojom::WebSandboxFlags sandbox_flags,
ui::PageTransition page_transition,
bool has_user_gesture,
- const base::Optional<url::Origin> &initiating_origin,
+ const absl::optional<url::Origin> &initiating_origin,
+ content::RenderFrameHost *initiator_document,
mojo::PendingRemote<network::mojom::URLLoaderFactory> *out_factory) override;
std::vector<std::unique_ptr<blink::URLLoaderThrottle>> CreateURLLoaderThrottles(
@@ -229,41 +183,71 @@ public:
content::NavigationHandle *navigation_handle) override;
bool IsHandledURL(const GURL &url) override;
-
+ bool HasErrorPage(int http_status_code, content::WebContents *contents) override;
+ bool HasCustomSchemeHandler(content::BrowserContext *browser_context,
+ const std::string &scheme) override;
+ std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>>
+ WillCreateURLLoaderRequestInterceptors(content::NavigationUIData *navigation_ui_data,
+ int frame_tree_node_id,
+ int64_t navigation_id,
+ scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override;
bool WillCreateURLLoaderFactory(content::BrowserContext *browser_context,
content::RenderFrameHost *frame,
int render_process_id,
URLLoaderFactoryType type,
const url::Origin &request_initiator,
- base::Optional<int64_t> navigation_id,
+ absl::optional<int64_t> navigation_id,
+ ukm::SourceIdObj ukm_source_id,
mojo::PendingReceiver<network::mojom::URLLoaderFactory> *factory_receiver,
mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> *header_client,
bool *bypass_redirect_checks,
- network::mojom::URLLoaderFactoryOverridePtr *factory_override) override;
+ bool *disable_secure_dns,
+ network::mojom::URLLoaderFactoryOverridePtr *factory_override,
+ scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override;
scoped_refptr<network::SharedURLLoaderFactory> GetSystemSharedURLLoaderFactory() override;
network::mojom::NetworkContext *GetSystemNetworkContext() override;
void OnNetworkServiceCreated(network::mojom::NetworkService *network_service) override;
- mojo::Remote<network::mojom::NetworkContext> CreateNetworkContext(content::BrowserContext *context,
- bool in_memory,
- const base::FilePath &relative_partition_path) override;
+ void ConfigureNetworkContextParams(content::BrowserContext *context,
+ bool in_memory,
+ const base::FilePath &relative_partition_path,
+ network::mojom::NetworkContextParams *network_context_params,
+ cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params) override;
+
std::vector<base::FilePath> GetNetworkContextsParentDirectory() override;
- void RegisterNonNetworkNavigationURLLoaderFactories(int frame_tree_node_id, NonNetworkURLLoaderFactoryMap *factories) override;
+ void RegisterNonNetworkNavigationURLLoaderFactories(int frame_tree_node_id,
+ ukm::SourceIdObj ukm_source_id,
+ NonNetworkURLLoaderFactoryMap *factories) override;
void RegisterNonNetworkSubresourceURLLoaderFactories(int render_process_id, int render_frame_id,
- NonNetworkURLLoaderFactoryMap* factories) override;
+ const absl::optional<url::Origin>& request_initiator_origin,
+ NonNetworkURLLoaderFactoryMap *factories) override;
void RegisterNonNetworkWorkerMainResourceURLLoaderFactories(content::BrowserContext* browser_context,
NonNetworkURLLoaderFactoryMap* factories) override;
+ void RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories(content::BrowserContext* browser_context,
+ NonNetworkURLLoaderFactoryMap* factories) override;
+ void SiteInstanceGotProcess(content::SiteInstance *site_instance) override;
+ base::flat_set<std::string> GetPluginMimeTypesWithExternalHandlers(content::BrowserContext *browser_context) override;
+
+ std::unique_ptr<content::WebContentsViewDelegate> GetWebContentsViewDelegate(content::WebContents *web_contents) override;
static std::string getUserAgent();
std::string GetUserAgent() override { return getUserAgent(); }
+ blink::UserAgentMetadata GetUserAgentMetadata() override;
std::string GetProduct() override;
-private:
- void InitFrameInterfaces();
+ content::WebAuthenticationDelegate *GetWebAuthenticationDelegate() override;
+#if !BUILDFLAG(IS_ANDROID)
+ std::unique_ptr<content::AuthenticatorRequestClientDelegate>
+ GetWebAuthenticationRequestDelegate(content::RenderFrameHost *render_frame_host) override;
+#endif
- scoped_refptr<ShareGroupQt> m_shareGroupQt;
- std::unique_ptr<service_manager::BinderRegistry> m_frameInterfaces;
- std::unique_ptr<service_manager::BinderRegistryWithArgs<content::RenderFrameHost*>> m_frameInterfacesParameterized;
+ void GetMediaDeviceIDSalt(content::RenderFrameHost *rfh,
+ const net::SiteForCookies &site_for_cookies,
+ const blink::StorageKey &storage_key,
+ base::OnceCallback<void(bool, const std::string&)> callback) override;
+
+private:
+ BrowserMainPartsQt *m_browserMainParts = nullptr;
};
} // namespace QtWebEngineCore
diff --git a/src/core/content_client_qt.cpp b/src/core/content_client_qt.cpp
index 083e10f2a..b6a0909b0 100644
--- a/src/core/content_client_qt.cpp
+++ b/src/core/content_client_qt.cpp
@@ -1,60 +1,28 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content_client_qt.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
+#include "base/json/json_string_value_serializer.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
#include "base/version.h"
#include "content/public/common/cdm_info.h"
#include "content/public/common/content_constants.h"
+#include "content/public/common/content_switches.h"
+#include "extensions/buildflags/buildflags.h"
+#include "extensions/common/constants.h"
#include "media/base/media_switches.h"
#include "media/base/video_codecs.h"
+#include "media/cdm/supported_audio_codecs.h"
#include "media/media_buildflags.h"
#include "ui/base/layout.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
-#include "services/service_manager/embedder/switches.h"
#include "type_conversion.h"
#include <QCoreApplication>
@@ -62,8 +30,10 @@
#include <QLibraryInfo>
#include <QString>
+
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
#include "media/cdm/cdm_paths.h" // nogncheck
+#include "media/cdm/clear_key_cdm_common.h"
#include "third_party/widevine/cdm/buildflags.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#if BUILDFLAG(ENABLE_WIDEVINE) && !BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT)
@@ -71,28 +41,29 @@
// File name of the CDM on different platforms.
const char kWidevineCdmFileName[] =
-#if defined(OS_MACOSX)
+#if BUILDFLAG(IS_MAC)
"widevinecdm.plugin";
-#elif defined(OS_WIN)
+#elif BUILDFLAG(IS_WIN)
"widevinecdm.dll";
#else // OS_LINUX, etc.
"libwidevinecdm.so";
#endif
#endif
+#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
#if QT_CONFIG(webengine_printing_and_pdf)
+#include "components/pdf/common/internal_plugin_helpers.h"
#include "pdf/pdf.h"
-#include "pdf/pdf_ppapi.h"
-const char kPdfPluginMimeType[] = "application/x-google-chrome-pdf";
-const char kPdfPluginPath[] = "internal-pdf-viewer/";
-const char kPdfPluginSrc[] = "src";
+const char kPdfPluginPath[] = "internal-pdf-viewer";
#endif // QT_CONFIG(webengine_printing_and_pdf)
+using Robustness = content::CdmInfo::Robustness;
+
static QString webenginePluginsPath()
{
// Look for plugins in /plugins/webengine or application dir.
static bool initialized = false;
- static QString potentialPluginsPath = QLibraryInfo::location(QLibraryInfo::PluginsPath) % QLatin1String("/webengine");
+ static QString potentialPluginsPath = QLibraryInfo::path(QLibraryInfo::PluginsPath) % QLatin1String("/webengine");
if (!initialized) {
initialized = true;
if (!QFileInfo::exists(potentialPluginsPath))
@@ -100,7 +71,6 @@ static QString webenginePluginsPath()
}
return potentialPluginsPath;
}
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
#if defined(Q_OS_WIN)
#include <shlobj.h>
@@ -130,26 +100,14 @@ static QString getProgramFilesDir(bool x86Dir = false)
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
-#include "content/public/common/pepper_plugin_info.h"
+#include "content/public/common/content_plugin_info.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
-static const int32_t kPepperFlashPermissions = ppapi::PERMISSION_DEV |
- ppapi::PERMISSION_PRIVATE |
- ppapi::PERMISSION_BYPASS_USER_GESTURE |
- ppapi::PERMISSION_FLASH |
- ppapi::PERMISSION_SOCKET;
-
-namespace switches {
-const char kPpapiFlashPath[] = "ppapi-flash-path";
-const char kPpapiFlashVersion[] = "ppapi-flash-version";
-const char kPpapiWidevinePath[] = "ppapi-widevine-path";
-}
-
static QString ppapiPluginsPath()
{
// Look for plugins in /plugins/ppapi or application dir.
static bool initialized = false;
- static QString potentialPluginsPath = QLibraryInfo::location(QLibraryInfo::PluginsPath) % QLatin1String("/ppapi");
+ static QString potentialPluginsPath = QLibraryInfo::path(QLibraryInfo::PluginsPath) % QLatin1String("/ppapi");
if (!initialized) {
initialized = true;
if (!QFileInfo::exists(potentialPluginsPath))
@@ -158,121 +116,29 @@ static QString ppapiPluginsPath()
return potentialPluginsPath;
}
-
-content::PepperPluginInfo CreatePepperFlashInfo(const base::FilePath& path, const std::string& version)
-{
- content::PepperPluginInfo plugin;
-
- plugin.is_out_of_process = true;
- plugin.name = content::kFlashPluginName;
- plugin.path = path;
- plugin.permissions = kPepperFlashPermissions;
-
- std::vector<std::string> flash_version_numbers = base::SplitString(version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
- if (flash_version_numbers.size() < 1)
- flash_version_numbers.push_back("11");
- else if (flash_version_numbers[0].empty())
- flash_version_numbers[0] = "11";
- if (flash_version_numbers.size() < 2)
- flash_version_numbers.push_back("2");
- if (flash_version_numbers.size() < 3)
- flash_version_numbers.push_back("999");
- if (flash_version_numbers.size() < 4)
- flash_version_numbers.push_back("999");
-
- // E.g., "Shockwave Flash 10.2 r154":
- plugin.description = plugin.name + " " + flash_version_numbers[0] + "." + flash_version_numbers[1] + " r" + flash_version_numbers[2];
- plugin.version = base::JoinString(flash_version_numbers, ".");
- content::WebPluginMimeType swf_mime_type(content::kFlashPluginSwfMimeType,
- content::kFlashPluginSwfExtension,
- content::kFlashPluginSwfDescription);
- plugin.mime_types.push_back(swf_mime_type);
- content::WebPluginMimeType spl_mime_type(content::kFlashPluginSplMimeType,
- content::kFlashPluginSplExtension,
- content::kFlashPluginSplDescription);
- plugin.mime_types.push_back(spl_mime_type);
-
- return plugin;
-}
-
-void AddPepperFlashFromSystem(std::vector<content::PepperPluginInfo>* plugins)
-{
- QStringList pluginPaths;
-#if defined(Q_OS_WIN)
- QString winDir = QDir::fromNativeSeparators(qgetenv("WINDIR"));
- if (winDir.isEmpty())
- winDir = QString::fromLatin1("C:/Windows");
- QDir pluginDir(winDir + "/System32/Macromed/Flash");
- pluginDir.setFilter(QDir::Files);
- const QFileInfoList infos = pluginDir.entryInfoList(QStringList("pepflashplayer*.dll"));
- for (const QFileInfo &info : infos)
- pluginPaths << info.absoluteFilePath();
- pluginPaths << ppapiPluginsPath() + QStringLiteral("/pepflashplayer.dll");
-#endif
-#if defined(Q_OS_OSX)
- pluginPaths << "/Library/Internet Plug-Ins/PepperFlashPlayer/PepperFlashPlayer.plugin"; // System path
- QDir potentialDir(QDir::homePath() + "/Library/Application Support/Google/Chrome/PepperFlash");
- if (potentialDir.exists()) {
- QFileInfoList versionDirs = potentialDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::Reversed);
- for (int i = 0; i < versionDirs.size(); ++i) {
- pluginPaths << versionDirs.at(i).absoluteFilePath() + "/PepperFlashPlayer.plugin";
- }
- }
- pluginPaths << ppapiPluginsPath() + QStringLiteral("/PepperFlashPlayer.plugin");
-#endif
-#if defined(Q_OS_LINUX)
- pluginPaths << "/opt/google/chrome/PepperFlash/libpepflashplayer.so" // Google Chrome
- << "/usr/lib/pepperflashplugin-nonfree/libpepflashplayer.so" // Ubuntu, package pepperflashplugin-nonfree
- << "/usr/lib/adobe-flashplugin/libpepflashplayer.so" // Ubuntu, package adobe-flashplugin
- << "/usr/lib/PepperFlash/libpepflashplayer.so" // Arch
- << "/usr/lib64/chromium/PepperFlash/libpepflashplayer.so"; // OpenSuSE
- pluginPaths << ppapiPluginsPath() + QStringLiteral("/libpepflashplayer.so");
-#endif
- std::string flash_version = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kPpapiFlashVersion);
- for (auto it = pluginPaths.constBegin(); it != pluginPaths.constEnd(); ++it) {
- if (!QFile::exists(*it))
- continue;
- plugins->push_back(CreatePepperFlashInfo(QtWebEngineCore::toFilePath(*it), flash_version));
- }
-}
-
-void AddPepperFlashFromCommandLine(std::vector<content::PepperPluginInfo>* plugins)
-{
- const base::CommandLine::StringType flash_path = base::CommandLine::ForCurrentProcess()->GetSwitchValueNative(switches::kPpapiFlashPath);
- if (flash_path.empty() || !QFile::exists(QtWebEngineCore::toQt(flash_path)))
- return;
-
- // Read pepper flash plugin version from command-line. (e.g. 16.0.0.235)
- std::string flash_version = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kPpapiFlashVersion);
- plugins->push_back(CreatePepperFlashInfo(base::FilePath(flash_path), flash_version));
-}
-
-void ComputeBuiltInPlugins(std::vector<content::PepperPluginInfo>* plugins)
+void ComputeBuiltInPlugins(std::vector<content::ContentPluginInfo> *plugins)
{
#if QT_CONFIG(webengine_printing_and_pdf)
- content::PepperPluginInfo pdf_info;
+ static constexpr char kPDFPluginExtension[] = "pdf";
+ static constexpr char kPDFPluginDescription[] = "Portable Document Format";
+ content::ContentPluginInfo pdf_info;
pdf_info.is_internal = true;
pdf_info.is_out_of_process = true;
pdf_info.name = "Chromium PDF Viewer";
- pdf_info.description = "Portable Document Format";
+ pdf_info.description = kPDFPluginDescription;
pdf_info.path = base::FilePath::FromUTF8Unsafe(kPdfPluginPath);
- content::WebPluginMimeType pdf_mime_type(kPdfPluginMimeType, "pdf", "Portable Document Format");
+ content::WebPluginMimeType pdf_mime_type(
+ pdf::kInternalPluginMimeType, kPDFPluginExtension, kPDFPluginDescription);
pdf_info.mime_types.push_back(pdf_mime_type);
- pdf_info.internal_entry_points.get_interface = chrome_pdf::PPP_GetInterface;
- pdf_info.internal_entry_points.initialize_module = chrome_pdf::PPP_InitializeModule;
- pdf_info.internal_entry_points.shutdown_module = chrome_pdf::PPP_ShutdownModule;
- pdf_info.permissions = ppapi::PERMISSION_PRIVATE | ppapi::PERMISSION_DEV | ppapi::PERMISSION_PDF;
plugins->push_back(pdf_info);
#endif // QT_CONFIG(webengine_printing_and_pdf)
}
namespace QtWebEngineCore {
-void ContentClientQt::AddPepperPlugins(std::vector<content::PepperPluginInfo>* plugins)
+void ContentClientQt::AddPlugins(std::vector<content::ContentPluginInfo> *plugins)
{
ComputeBuiltInPlugins(plugins);
- AddPepperFlashFromSystem(plugins);
- AddPepperFlashFromCommandLine(plugins);
}
} // namespace QtWebEngineCore
@@ -281,11 +147,45 @@ void ContentClientQt::AddPepperPlugins(std::vector<content::PepperPluginInfo>* p
namespace QtWebEngineCore {
#if defined(WIDEVINE_CDM_AVAILABLE_NOT_COMPONENT)
+#if defined(Q_OS_LINUX)
+static const QDir widevineCdmDirHint(const QDir &widevineDir)
+{
+ const QString hintFilePath = widevineDir.absolutePath() % QDir::separator()
+ % QLatin1String("latest-component-updated-widevine-cdm");
+ if (!QFileInfo::exists(hintFilePath)) {
+ // CDM hint file does not exist.
+ return widevineDir;
+ }
+
+ std::string jsonString;
+ if (!base::ReadFileToString(toFilePath(hintFilePath), &jsonString)) {
+ // Could not read the CDM hint file.
+ return widevineDir;
+ }
+
+ std::string error_message;
+ JSONStringValueDeserializer deserializer(jsonString);
+ std::unique_ptr<base::Value> dict = deserializer.Deserialize(nullptr, &error_message);
+ if (!dict || !dict->is_dict()) {
+ DLOG(ERROR) << "Could not deserialize the CDM hint file. Error: "
+ << error_message;
+ // Could not deserialize the CDM hint file.
+ return widevineDir;
+ }
+
+ std::string *widevineCdmDirPath = dict->GetDict().FindString("Path");
+ if (!widevineCdmDirPath)
+ return widevineDir;
+
+ return QDir(QString::fromStdString(*widevineCdmDirPath));
+}
+#endif // defined(Q_OS_LINUX)
+
static bool IsWidevineAvailable(base::FilePath *cdm_path,
- content::CdmCapability *capability)
+ media::CdmCapability *capability)
{
QStringList pluginPaths;
- const base::CommandLine::StringType widevine_argument = base::CommandLine::ForCurrentProcess()->GetSwitchValueNative(service_manager::switches::kCdmWidevinePath);
+ const base::CommandLine::StringType widevine_argument = base::CommandLine::ForCurrentProcess()->GetSwitchValueNative(switches::kCdmWidevinePath);
if (!widevine_argument.empty())
pluginPaths << QtWebEngineCore::toQt(widevine_argument);
else {
@@ -350,28 +250,76 @@ static bool IsWidevineAvailable(base::FilePath *cdm_path,
}
}
#elif defined(Q_OS_LINUX)
- pluginPaths << QStringLiteral("/opt/google/chrome/libwidevinecdm.so") // Old Google Chrome
+ QList<QDir> potentialWidevineVersionDirs;
+
+ // Google Chrome widevine modules
+ QDir chromeWidevineDir(QDir::homePath() + "/.config/google-chrome/WidevineCdm");
+ if (chromeWidevineDir.exists())
+ potentialWidevineVersionDirs << widevineCdmDirHint(chromeWidevineDir);
+
+ // Firefox widevine modules
+ QDir firefoxPotentialProfilesDir(QDir::homePath() + "/.mozilla/firefox");
+ if (firefoxPotentialProfilesDir.exists()) {
+ QFileInfoList firefoxProfileDirs = firefoxPotentialProfilesDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::Reversed);
+ for (const QFileInfo &info : firefoxProfileDirs) {
+ QDir widevinePluginsDir(info.absoluteFilePath() + "/gmp-widevinecdm");
+ if (widevinePluginsDir.exists())
+ potentialWidevineVersionDirs << widevinePluginsDir;
+ }
+ }
+
+ // Chromium widevine modules (might not work with proprietary codecs)
+ QDir chromiumWidevineDir(QDir::homePath() + "/.config/chromium/WidevineCdm");
+ if (chromiumWidevineDir.exists())
+ potentialWidevineVersionDirs << widevineCdmDirHint(chromiumWidevineDir);
+
+ // Search for widewine versions
+ for (const QDir &dir : potentialWidevineVersionDirs) {
+ QFileInfoList widevineVersionDirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::Reversed);
+ widevineVersionDirs.prepend(QFileInfo(dir.absolutePath()));
+ // ### alternatively look up in the manifest.json and take the path from there.
#if Q_PROCESSOR_WORDSIZE == 8
- << QStringLiteral("/opt/google/chrome/WidevineCdm/_platform_specific/linux_x64/libwidevinecdm.so")
+ const QString library = QLatin1String("/_platform_specific/linux_x64/libwidevinecdm.so");
#else
- << QStringLiteral("/opt/google/chrome/WidevineCdm/_platform_specific/linux_x86/libwidevinecdm.so")
+ const QString library = QLatin1String("/_platform_specific/linux_x86/libwidevinecdm.so");
#endif
- << QStringLiteral("/usr/lib/chromium/libwidevinecdm.so") // Arch
+ for (const QFileInfo &info : widevineVersionDirs) {
+ pluginPaths << info.absoluteFilePath() + "/libwidevinecdm.so";
+ pluginPaths << info.absoluteFilePath() + library;
+ }
+ }
+
+ // Fixed paths:
+ pluginPaths << QStringLiteral("/usr/lib/chromium/libwidevinecdm.so") // Arch
<< QStringLiteral("/usr/lib/chromium-browser/libwidevinecdm.so") // Ubuntu/neon
- << QStringLiteral("/usr/lib64/chromium/libwidevinecdm.so"); // OpenSUSE style
+ << QStringLiteral("/usr/lib64/chromium/libwidevinecdm.so") // OpenSUSE style
+#if Q_PROCESSOR_WORDSIZE == 8
+ << QStringLiteral("/usr/lib64/chromium-browser/WidevineCdm/_platform_specific/linux_x64/libwidevinecdm.so") // Gentoo
+ << QStringLiteral("/opt/google/chrome/WidevineCdm/_platform_specific/linux_x64/libwidevinecdm.so") // Old Google Chrome
+#else
+ << QStringLiteral("/usr/lib/chromium-browser/WidevineCdm/_platform_specific/linux_x86/libwidevinecdm.so") // Gentoo
+ << QStringLiteral("/opt/google/chrome/WidevineCdm/_platform_specific/linux_x86/libwidevinecdm.so") // Old Google Chrome
+#endif
+ << QStringLiteral("/opt/google/chrome/libwidevinecdm.so"); // Older Google Chrome
#endif
}
- for (const QString &pluginPath : qAsConst(pluginPaths)) {
+ for (const QString &pluginPath : std::as_const(pluginPaths)) {
*cdm_path = QtWebEngineCore::toFilePath(pluginPath);
if (base::PathExists(*cdm_path)) {
// Add the supported codecs as if they came from the component manifest.
// This list must match the CDM that is being bundled with Chrome.
- capability->video_codecs.push_back(media::VideoCodec::kCodecVP8);
- capability->video_codecs.push_back(media::VideoCodec::kCodecVP9);
+ const std::vector<media::VideoCodecProfile> kAllProfiles = {};
+ capability->video_codecs.emplace(media::VideoCodec::kVP8, kAllProfiles);
+ capability->video_codecs.emplace(media::VideoCodec::kVP9, kAllProfiles);
+ capability->video_codecs.emplace(media::VideoCodec::kAV1, kAllProfiles);
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
- capability->video_codecs.push_back(media::VideoCodec::kCodecH264);
+ capability->video_codecs.emplace(media::VideoCodec::kH264, kAllProfiles);
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
+ capability->video_codecs.emplace(media::VideoCodec::kHEVC, kAllProfiles);
+#endif
+ capability->audio_codecs = media::GetCdmSupportedAudioCodecs();
// Add the supported encryption schemes as if they came from the
// component manifest. This list must match the CDM that is being
@@ -396,12 +344,12 @@ void ContentClientQt::AddContentDecryptionModules(std::vector<content::CdmInfo>
if (cdms) {
#if defined(WIDEVINE_CDM_AVAILABLE_NOT_COMPONENT)
base::FilePath cdm_path;
- content::CdmCapability capability;
+ media::CdmCapability capability;
if (IsWidevineAvailable(&cdm_path, &capability)) {
const base::Version version;
- cdms->push_back(content::CdmInfo(kWidevineCdmDisplayName, kWidevineCdmGuid, version, cdm_path,
- kWidevineCdmFileSystemId, std::move(capability),
- kWidevineKeySystem, false));
+ cdms->push_back(content::CdmInfo(kWidevineKeySystem, Robustness::kSoftwareSecure, std::move(capability),
+ /*supports_sub_key_systems=*/false, kWidevineCdmDisplayName,
+ kWidevineCdmType, version, cdm_path));
}
#endif // defined(WIDEVINE_CDM_AVAILABLE_NOT_COMPONENT)
@@ -410,35 +358,27 @@ void ContentClientQt::AddContentDecryptionModules(std::vector<content::CdmInfo>
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::FilePath clear_key_cdm_path = command_line->GetSwitchValuePath(switches::kClearKeyCdmPathForTesting);
if (!clear_key_cdm_path.empty() && base::PathExists(clear_key_cdm_path)) {
- // TODO(crbug.com/764480): Remove these after we have a central place for
- // External Clear Key (ECK) related information.
- // Normal External Clear Key key system.
- const char kExternalClearKeyKeySystem[] = "org.chromium.externalclearkey";
- // A variant of ECK key system that has a different GUID.
- const char kExternalClearKeyDifferentGuidTestKeySystem[] =
- "org.chromium.externalclearkey.differentguid";
-
// Supported codecs are hard-coded in ExternalClearKeyProperties.
- content::CdmCapability capability(
- {}, {media::EncryptionScheme::kCenc, media::EncryptionScheme::kCbcs},
+ media::CdmCapability capability(
+ {}, {}, {media::EncryptionScheme::kCenc, media::EncryptionScheme::kCbcs},
{media::CdmSessionType::kTemporary,
- media::CdmSessionType::kPersistentLicense},
- {});
+ media::CdmSessionType::kPersistentLicense});
- // Register kExternalClearKeyDifferentGuidTestKeySystem first separately.
+ // Register media::kExternalClearKeyDifferentCdmTypeTestKeySystem first separately.
// Otherwise, it'll be treated as a sub-key-system of normal
// kExternalClearKeyKeySystem. See MultipleCdmTypes test in
// ECKEncryptedMediaTest.
- cdms->push_back(content::CdmInfo(media::kClearKeyCdmDisplayName, media::kClearKeyCdmDifferentGuid,
- base::Version("0.1.0.0"), clear_key_cdm_path,
- media::kClearKeyCdmFileSystemId, capability,
- kExternalClearKeyDifferentGuidTestKeySystem, false));
-
- // Supported codecs are hard-coded in ExternalClearKeyProperties.
- cdms->push_back(content::CdmInfo(media::kClearKeyCdmDisplayName, media::kClearKeyCdmGuid,
- base::Version("0.1.0.0"), clear_key_cdm_path,
- media::kClearKeyCdmFileSystemId, capability,
- kExternalClearKeyKeySystem, true));
+ cdms->push_back(content::CdmInfo(media::kExternalClearKeyDifferentCdmTypeTestKeySystem,
+ Robustness::kSoftwareSecure, capability,
+ /*supports_sub_key_systems=*/false, media::kClearKeyCdmDisplayName,
+ media::kClearKeyCdmDifferentCdmType, base::Version("0.1.0.0"),
+ clear_key_cdm_path));
+
+ cdms->push_back(content::CdmInfo(media::kExternalClearKeyKeySystem,
+ Robustness::kSoftwareSecure, capability,
+ /*supports_sub_key_systems=*/true, media::kClearKeyCdmDisplayName,
+ media::kClearKeyCdmType, base::Version("0.1.0.0"),
+ clear_key_cdm_path));
}
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
}
@@ -446,10 +386,18 @@ void ContentClientQt::AddContentDecryptionModules(std::vector<content::CdmInfo>
void ContentClientQt::AddAdditionalSchemes(Schemes* schemes)
{
- schemes->standard_schemes.push_back("chrome-extension");
+ // Matching ChromeContentClient::AddAdditionalSchemes
+ schemes->standard_schemes.push_back(extensions::kExtensionScheme);
+ schemes->secure_schemes.push_back(extensions::kExtensionScheme);
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ schemes->service_worker_schemes.push_back(extensions::kExtensionScheme);
+ schemes->cors_enabled_schemes.push_back(extensions::kExtensionScheme);
+ schemes->csp_bypassing_schemes.push_back(extensions::kExtensionScheme);
+#endif
}
-base::StringPiece ContentClientQt::GetDataResource(int resource_id, ui::ScaleFactor scale_factor)
+base::StringPiece ContentClientQt::GetDataResource(int resource_id, ui::ResourceScaleFactor scale_factor)
{
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}
@@ -464,9 +412,24 @@ gfx::Image &ContentClientQt::GetNativeImageNamed(int resource_id)
return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}
-base::string16 ContentClientQt::GetLocalizedString(int message_id)
+std::u16string ContentClientQt::GetLocalizedString(int message_id)
{
return l10n_util::GetStringUTF16(message_id);
}
+// This method is a copy from chrome/common/chrome_content_client.cc:
+// Copyright 2012 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE.Chromium file.
+blink::OriginTrialPolicy *ContentClientQt::GetOriginTrialPolicy()
+{
+ // Prevent initialization race (see crbug.com/721144). There may be a
+ // race when the policy is needed for worker startup (which happens on a
+ // separate worker thread).
+ base::AutoLock auto_lock(origin_trial_policy_lock_);
+ if (!origin_trial_policy_)
+ origin_trial_policy_ = std::make_unique<embedder_support::OriginTrialPolicyImpl>();
+ return origin_trial_policy_.get();
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/content_client_qt.h b/src/core/content_client_qt.h
index a7fc7432a..f58e17f96 100644
--- a/src/core/content_client_qt.h
+++ b/src/core/content_client_qt.h
@@ -1,65 +1,40 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_CLIENT_QT_H
#define CONTENT_CLIENT_QT_H
#include "qtwebenginecoreglobal_p.h"
+
#include "base/strings/string_piece.h"
+#include "base/synchronization/lock.h"
+#include "components/embedder_support/origin_trials/origin_trial_policy_impl.h"
#include "content/public/common/content_client.h"
#include "ui/base/layout.h"
+#include <memory>
+
namespace QtWebEngineCore {
class ContentClientQt : public content::ContentClient {
public:
#if QT_CONFIG(webengine_pepper_plugins)
- void AddPepperPlugins(std::vector<content::PepperPluginInfo>* plugins) override;
+ void AddPlugins(std::vector<content::ContentPluginInfo> *plugins) override;
#endif
void AddContentDecryptionModules(std::vector<content::CdmInfo> *cdms,
std::vector<media::CdmHostFilePath> *cdm_host_file_paths) override;
void AddAdditionalSchemes(Schemes* schemes) override;
- base::StringPiece GetDataResource(int, ui::ScaleFactor) override;
+ base::StringPiece GetDataResource(int, ui::ResourceScaleFactor) override;
base::RefCountedMemory* GetDataResourceBytes(int resource_id) override;
gfx::Image &GetNativeImageNamed(int resource_id) override;
- base::string16 GetLocalizedString(int message_id) override;
+ std::u16string GetLocalizedString(int message_id) override;
+ blink::OriginTrialPolicy *GetOriginTrialPolicy() override;
+
+private:
+ // Used to lock when |origin_trial_policy_| is initialized.
+ base::Lock origin_trial_policy_lock_;
+ std::unique_ptr<embedder_support::OriginTrialPolicyImpl> origin_trial_policy_;
};
} // namespace QtWebEngineCore
diff --git a/src/core/content_main_delegate_qt.cpp b/src/core/content_main_delegate_qt.cpp
index f93a3c0ea..f949d93a5 100644
--- a/src/core/content_main_delegate_qt.cpp
+++ b/src/core/content_main_delegate_qt.cpp
@@ -1,61 +1,26 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content_main_delegate_qt.h"
#include "base/command_line.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
+#include "base/memory/ref_counted_memory.h"
+#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
-#include "media/gpu/buildflags.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
#include "net/grit/net_resources.h"
#include "net/base/net_module.h"
-#include "services/service_manager/sandbox/switches.h"
+#include "sandbox/policy/switches.h"
#include "url/url_util_qt.h"
#include "content_client_qt.h"
@@ -64,30 +29,27 @@
#include "web_engine_context.h"
#include "web_engine_library_info.h"
-#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
+#if defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX))
#include "base/cpu.h"
#endif
-#if defined(OS_LINUX)
+#if BUILDFLAG(IS_LINUX)
+#include "media/audio/audio_manager.h"
#include "ui/base/ui_base_switches.h"
#endif
-// must be included before vaapi_wrapper.h
-#include <QtCore/qcoreapplication.h>
-
-#if defined(OS_WIN)
-#include "media/gpu/windows/dxva_video_decode_accelerator_win.h"
-#include "media/gpu/windows/media_foundation_video_encode_accelerator_win.h"
+#if BUILDFLAG(IS_WIN)
+#include "media/base/win/mf_initializer.h"
+#include "sandbox/policy/win/sandbox_warmup.h"
#endif
-#if defined(OS_MACOSX)
+#if BUILDFLAG(IS_MAC)
+#include "base/trace_event/trace_event.h"
#include "content/public/common/content_features.h"
#include "media/gpu/mac/vt_video_decode_accelerator_mac.h"
#endif
-#if BUILDFLAG(USE_VAAPI)
-#include "media/gpu/vaapi/vaapi_wrapper.h"
-#endif
+#include <QtCore/qcoreapplication.h>
namespace content {
ContentClient *GetContentClient();
@@ -109,23 +71,19 @@ struct LazyDirectoryListerCacher
{
LazyDirectoryListerCacher()
{
- base::DictionaryValue dict;
- dict.SetString("header", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_HEADER));
- dict.SetString("parentDirText", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_PARENT));
- dict.SetString("headerName", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_NAME));
- dict.SetString("headerSize", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_SIZE));
- dict.SetString("headerDateModified",
- l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_DATE_MODIFIED));
- dict.SetString("language", l10n_util::GetLanguage(base::i18n::GetConfiguredLocale()));
- dict.SetString("listingParsingErrorBoxText",
- l10n_util::GetStringFUTF16(IDS_DIRECTORY_LISTING_PARSING_ERROR_BOX_TEXT,
- toString16(QCoreApplication::applicationName())));
- dict.SetString("textdirection", base::i18n::IsRTL() ? "rtl" : "ltr");
+ base::Value::Dict dict;
+ dict.Set("header", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_HEADER));
+ dict.Set("parentDirText", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_PARENT));
+ dict.Set("headerName", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_NAME));
+ dict.Set("headerSize", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_SIZE));
+ dict.Set("headerDateModified", l10n_util::GetStringUTF16(IDS_DIRECTORY_LISTING_DATE_MODIFIED));
+ dict.Set("language", l10n_util::GetLanguage(base::i18n::GetConfiguredLocale()));
+ dict.Set("textdirection", base::i18n::IsRTL() ? "rtl" : "ltr");
std::string html =
webui::GetI18nTemplateHtml(
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_DIR_HEADER_HTML),
- &dict);
- html_data = base::RefCountedString::TakeString(&html);
+ std::move(dict));
+ html_data = base::MakeRefCounted<base::RefCountedString>(std::move(html));
}
scoped_refptr<base::RefCountedMemory> html_data;
@@ -169,14 +127,16 @@ static logging::LoggingDestination DetermineLogMode(const base::CommandLine& com
void ContentMainDelegateQt::PreSandboxStartup()
{
-#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
+#if defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX))
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
#endif
net::NetModule::SetResourceProvider(PlatformResourceProvider);
- ui::ResourceBundle::InitSharedInstanceWithLocale(WebEngineLibraryInfo::getApplicationLocale(), 0, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
+
+ base::i18n::SetICUDefaultLocale(WebEngineLibraryInfo::getApplicationLocale());
+ ui::ResourceBundle::InitSharedInstanceWithLocale(WebEngineLibraryInfo::getResolvedLocale(), nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
base::CommandLine* parsedCommandLine = base::CommandLine::ForCurrentProcess();
logging::LoggingSettings settings;
@@ -191,35 +151,48 @@ void ContentMainDelegateQt::PreSandboxStartup()
false //enable_tickcount
);
- if (logging::GetMinLogLevel() >= logging::LOG_INFO) {
+ if (logging::GetMinLogLevel() >= logging::LOGGING_INFO) {
if (parsedCommandLine->HasSwitch(switches::kLoggingLevel)) {
std::string logLevelValue = parsedCommandLine->GetSwitchValueASCII(switches::kLoggingLevel);
int level = 0;
- if (base::StringToInt(logLevelValue, &level) && level >= logging::LOG_INFO && level < logging::LOG_NUM_SEVERITIES)
+ if (base::StringToInt(logLevelValue, &level) && level >= logging::LOGGING_INFO && level < logging::LOGGING_NUM_SEVERITIES)
logging::SetMinLogLevel(level);
}
}
-#if defined(OS_POSIX) && !defined(OS_ANDROID)
+#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
if (parsedCommandLine->HasSwitch(switches::kSingleProcess))
setlocale(LC_NUMERIC, "C");
#endif
- // from gpu_main.cc:
-#if BUILDFLAG(USE_VAAPI)
- media::VaapiWrapper::PreSandboxInitialization();
-#endif
-#if defined(OS_WIN)
- media::DXVAVideoDecodeAccelerator::PreSandboxInitialization();
- media::MediaFoundationVideoEncodeAccelerator::PreSandboxInitialization();
+ bool isBrowserProcess = !parsedCommandLine->HasSwitch(switches::kProcessType);
+ if (isBrowserProcess) {
+ // from gpu_main.cc:
+#if BUILDFLAG(IS_WIN)
+ media::PreSandboxMediaFoundationInitialization();
#endif
-#if defined(OS_MACOSX)
- if (base::FeatureList::IsEnabled(features::kMacV2GPUSandbox)) {
- TRACE_EVENT0("gpu", "Initialize VideoToolbox");
- media::InitializeVideoToolbox();
+#if BUILDFLAG(IS_MAC)
+ {
+ TRACE_EVENT0("gpu", "Initialize VideoToolbox");
+ media::InitializeVideoToolbox();
+ }
+#endif
}
+
+ if (parsedCommandLine->HasSwitch(switches::kApplicationName)) {
+ std::string appName = parsedCommandLine->GetSwitchValueASCII(switches::kApplicationName);
+ appName = QByteArray::fromPercentEncoding(QByteArray::fromStdString(appName)).toStdString();
+ QCoreApplication::setApplicationName(QString::fromStdString(appName));
+#if BUILDFLAG(IS_LINUX)
+ media::AudioManager::SetGlobalAppName(appName);
#endif
+ }
+}
+
+content::ContentClient *ContentMainDelegateQt::CreateContentClient()
+{
+ return &m_contentClient;
}
content::ContentBrowserClient *ContentMainDelegateQt::CreateContentBrowserClient()
@@ -236,10 +209,10 @@ content::ContentGpuClient *ContentMainDelegateQt::CreateContentGpuClient()
content::ContentRendererClient *ContentMainDelegateQt::CreateContentRendererClient()
{
-#if defined(OS_LINUX)
+#if BUILDFLAG(IS_LINUX)
base::CommandLine *parsedCommandLine = base::CommandLine::ForCurrentProcess();
std::string process_type = parsedCommandLine->GetSwitchValueASCII(switches::kProcessType);
- bool no_sandbox = parsedCommandLine->HasSwitch(service_manager::switches::kNoSandbox);
+ bool no_sandbox = parsedCommandLine->HasSwitch(sandbox::policy::switches::kNoSandbox);
// Reload locale if the renderer process is sandboxed
if (process_type == switches::kRendererProcess && !no_sandbox) {
@@ -278,20 +251,20 @@ static void SafeOverridePathImpl(const char *keyName, int key, const base::FileP
#define SafeOverridePath(KEY, PATH) SafeOverridePathImpl(#KEY, KEY, PATH)
-bool ContentMainDelegateQt::BasicStartupComplete(int *exit_code)
+absl::optional<int> ContentMainDelegateQt::BasicStartupComplete()
{
SafeOverridePath(base::FILE_EXE, WebEngineLibraryInfo::getPath(base::FILE_EXE));
SafeOverridePath(base::DIR_QT_LIBRARY_DATA, WebEngineLibraryInfo::getPath(base::DIR_QT_LIBRARY_DATA));
+ SafeOverridePath(base::DIR_ASSETS, WebEngineLibraryInfo::getPath(base::DIR_ASSETS));
+ SafeOverridePath(base::DIR_EXE, WebEngineLibraryInfo::getPath(base::DIR_ASSETS));
SafeOverridePath(ui::DIR_LOCALES, WebEngineLibraryInfo::getPath(ui::DIR_LOCALES));
#if QT_CONFIG(webengine_spellchecker)
SafeOverridePath(base::DIR_APP_DICTIONARIES, WebEngineLibraryInfo::getPath(base::DIR_APP_DICTIONARIES));
#endif
- if (!content::GetContentClient())
- content::SetContentClient(new ContentClientQt);
url::CustomScheme::LoadSchemes(base::CommandLine::ForCurrentProcess());
- return false;
+ return absl::nullopt;
}
} // namespace QtWebEngineCore
diff --git a/src/core/content_main_delegate_qt.h b/src/core/content_main_delegate_qt.h
index 4d2f33792..a177bd6df 100644
--- a/src/core/content_main_delegate_qt.h
+++ b/src/core/content_main_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_MAIN_DELEGATE_QT_H
#define CONTENT_MAIN_DELEGATE_QT_H
@@ -44,6 +8,7 @@
#include "compositor/content_gpu_client_qt.h"
#include "content_browser_client_qt.h"
+#include "content_client_qt.h"
#include "content_utility_client_qt.h"
namespace QtWebEngineCore {
@@ -56,13 +21,15 @@ public:
// before the sandbox is engaged.
void PreSandboxStartup() override;
+ content::ContentClient *CreateContentClient() override;
content::ContentBrowserClient* CreateContentBrowserClient() override;
content::ContentGpuClient* CreateContentGpuClient() override;
content::ContentRendererClient* CreateContentRendererClient() override;
content::ContentUtilityClient* CreateContentUtilityClient() override;
- bool BasicStartupComplete(int* /*exit_code*/) override;
+ absl::optional<int> BasicStartupComplete() override;
private:
+ ContentClientQt m_contentClient;
std::unique_ptr<ContentBrowserClientQt> m_browserClient;
std::unique_ptr<ContentGpuClientQt> m_gpuClient;
std::unique_ptr<ContentUtilityClientQt> m_utilityClient;
diff --git a/src/core/content_utility_client_qt.cpp b/src/core/content_utility_client_qt.cpp
index 3582e15a7..7af90c7a1 100644
--- a/src/core/content_utility_client_qt.cpp
+++ b/src/core/content_utility_client_qt.cpp
@@ -1,48 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "content_utility_client_qt.h"
-#include "base/no_destructor.h"
#include "mojo/public/cpp/bindings/service_factory.h"
#include "services/proxy_resolver/proxy_resolver_factory_impl.h"
+#if BUILDFLAG(IS_WIN)
+#include "services/proxy_resolver_win/public/mojom/proxy_resolver_win.mojom.h"
+#include "services/proxy_resolver_win/windows_system_proxy_resolver_impl.h"
+#endif
+
namespace QtWebEngineCore {
ContentUtilityClientQt::ContentUtilityClientQt()
@@ -56,12 +24,21 @@ auto RunProxyResolver(mojo::PendingReceiver<proxy_resolver::mojom::ProxyResolver
return std::make_unique<proxy_resolver::ProxyResolverFactoryImpl>(std::move(receiver));
}
-mojo::ServiceFactory *ContentUtilityClientQt::GetIOThreadServiceFactory()
+#if BUILDFLAG(IS_WIN)
+auto RunWindowsSystemProxyResolver(
+ mojo::PendingReceiver<proxy_resolver_win::mojom::WindowsSystemProxyResolver> receiver)
+{
+ return std::make_unique<proxy_resolver_win::WindowsSystemProxyResolverImpl>(
+ std::move(receiver));
+}
+#endif
+
+void ContentUtilityClientQt::RegisterIOThreadServices(mojo::ServiceFactory &services)
{
- static base::NoDestructor<mojo::ServiceFactory> factory {
- RunProxyResolver,
- };
- return factory.get();
+ services.Add(RunProxyResolver);
+#if BUILDFLAG(IS_WIN)
+ services.Add(RunWindowsSystemProxyResolver);
+#endif
}
} // namespace
diff --git a/src/core/content_utility_client_qt.h b/src/core/content_utility_client_qt.h
index fc1d1eb05..f2d287cf5 100644
--- a/src/core/content_utility_client_qt.h
+++ b/src/core/content_utility_client_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_UTILITY_CLIENT_QT_H
#define CONTENT_UTILITY_CLIENT_QT_H
@@ -53,7 +17,7 @@ public:
~ContentUtilityClientQt() override;
// content::ContentUtilityClient:
- mojo::ServiceFactory *GetIOThreadServiceFactory() override;
+ void RegisterIOThreadServices(mojo::ServiceFactory &services) override;
};
} // namespace
diff --git a/src/core/core.pro b/src/core/core.pro
deleted file mode 100644
index f2d3fd307..000000000
--- a/src/core/core.pro
+++ /dev/null
@@ -1,48 +0,0 @@
-include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri)
-QT_FOR_CONFIG += buildtools-private
-TEMPLATE = subdirs
-
-# core_headers is a dummy module to syncqt the headers so we can
-# use them by later targets
-core_headers.file = core_headers.pro
-core_api.file = api/core_api.pro
-
-# This will take the compile output of ninja, and link+deploy the final binary.
-core_module.file = core_module.pro
-core_module.depends = core_api
-
-core_generator.file = core_generator.pro
-core_generator.depends = core_headers
-
-# core_gn_generator.pro is a dummy .pro file that is used by qmake
-# to generate our main BUILD.gn file
-
-gn_run.file = gn_run.pro
-gn_run.depends = core_generator
-
-core_api.depends = gn_run
-
-# A fake project for qt creator
-core_project.file = core_project.pro
-core_project.depends = gn_run
-
-!qtConfig(webengine-core-support):qtConfig(build-qtwebengine-core):!build_pass {
- !qtwebengine_makeCheckWebEngineCoreError() {
- errorbuild.commands = @echo $$shell_quote("QtWebEngineCore module will not be built. $${skipBuildReason}")
- } else {
- errorbuild.commands = @echo $$shell_quote("QtWebEngineCore module will not be built for unknown reason, please open a bug report at https://bugreports.qt.io")
- }
- errorbuild.CONFIG = phony
- QMAKE_EXTRA_TARGETS += errorbuild
- first.depends += errorbuild
- QMAKE_EXTRA_TARGETS += first
-} else {
- SUBDIRS += \
- core_headers \
- core_generator \
- gn_run \
- core_api \
- core_module
-
- false: SUBDIRS += core_project
-}
diff --git a/src/core/core_chromium.pri b/src/core/core_chromium.pri
deleted file mode 100644
index 14a65a39c..000000000
--- a/src/core/core_chromium.pri
+++ /dev/null
@@ -1,347 +0,0 @@
-qtConfig(debug_and_release): CONFIG += debug_and_release
-
-macos {
- # This fixes namespace builds on macOS. Specifically namespace ambiguity issues between Qt and
- # Chromium forward declarations of NSString.
-
- # The single quotes are present so that qmake iteration does not interpret the space as
- # delimiting a new value, they are removed before writing to the GN file, and the final shell
- # quoting is done by GN itself.
- forward_declaration_macro = "'Q_FORWARD_DECLARE_OBJC_CLASS(name)=class name;'"
-} else {
- forward_declaration_macro = "Q_FORWARD_DECLARE_OBJC_CLASS=QT_FORWARD_DECLARE_CLASS"
-}
-
-# Defining keywords such as 'signal' clashes with the chromium code base.
-DEFINES += QT_NO_KEYWORDS \
- QT_USE_QSTRINGBUILDER \
- $$forward_declaration_macro \
- QTWEBENGINECORE_VERSION_STR=\"$$MODULE_VERSION\" \
- QTWEBENGINEPROCESS_NAME=\"$$QTWEBENGINEPROCESS_NAME\" \
- BUILDING_CHROMIUM
-
-# Ensure that response files, generated by qtbase/mkspecs/features/moc.prf, are found by moc.
-MOC_DIR = $$OUT_PWD/$$getConfigDir()/.moc
-RCC_DIR = $$OUT_PWD/$$getConfigDir()/.rcc
-
-# Assume that we want mobile touch and low-end hardware behaviors
-# whenever we are cross compiling.
-qtConfig(webengine-embedded-build): DEFINES += QTWEBENGINE_EMBEDDED_SWITCHES
-
-INCLUDEPATH += $$PWD $$PWD/api
-
-clang_cl {
- QMAKE_CFLAGS -= $$QMAKE_CFLAGS_MSVC_COMPAT
- QMAKE_CXXFLAGS -= $$QMAKE_CFLAGS_MSVC_COMPAT
-}
-
-SOURCES = \
- accessibility_activation_observer.cpp \
- accessibility_tree_formatter_qt.cpp \
- authentication_dialog_controller.cpp \
- browser_accessibility_manager_qt.cpp \
- browser_accessibility_qt.cpp \
- browsing_data_remover_delegate_qt.cpp \
- browser_main_parts_qt.cpp \
- browser_message_filter_qt.cpp \
- certificate_error_controller.cpp \
- chromium_overrides.cpp \
- client_cert_select_controller.cpp \
- clipboard_qt.cpp \
- color_chooser_qt.cpp \
- color_chooser_controller.cpp \
- common/qt_ipc_logging.cpp \
- common/qt_messages.cpp \
- common/user_script_data.cpp \
- compositor/compositor.cpp \
- compositor/content_gpu_client_qt.cpp \
- compositor/display_overrides.cpp \
- compositor/display_software_output_surface.cpp \
- content_client_qt.cpp \
- content_browser_client_qt.cpp \
- content_main_delegate_qt.cpp \
- content_utility_client_qt.cpp \
- delegated_frame_host_client_qt.cpp \
- desktop_screen_qt.cpp \
- devtools_frontend_qt.cpp \
- devtools_manager_delegate_qt.cpp \
- download_manager_delegate_qt.cpp \
- favicon_manager.cpp \
- file_picker_controller.cpp \
- find_text_helper.cpp \
- javascript_dialog_controller.cpp \
- javascript_dialog_manager_qt.cpp \
- login_delegate_qt.cpp \
- media_capture_devices_dispatcher.cpp \
- native_web_keyboard_event_qt.cpp \
- net/client_cert_override.cpp \
- net/client_cert_store_data.cpp \
- net/cookie_monster_delegate_qt.cpp \
- net/custom_url_loader_factory.cpp \
- net/proxy_config_monitor.cpp \
- net/proxy_config_service_qt.cpp \
- net/proxying_url_loader_factory_qt.cpp \
- net/proxying_restricted_cookie_manager_qt.cpp \
- net/qrc_url_scheme_handler.cpp \
- net/ssl_host_state_delegate_qt.cpp \
- net/system_network_context_manager.cpp \
- net/url_request_custom_job_delegate.cpp \
- net/url_request_custom_job_proxy.cpp \
- net/webui_controller_factory_qt.cpp \
- ozone/gl_context_qt.cpp \
- ozone/gl_ozone_egl_qt.cpp \
- ozone/gl_surface_qt.cpp \
- ozone/gl_surface_egl_qt.cpp \
- ozone/gl_surface_wgl_qt.cpp \
- ozone/platform_window_qt.cpp \
- ozone/surface_factory_qt.cpp \
- permission_manager_qt.cpp \
- platform_notification_service_qt.cpp \
- process_main.cpp \
- profile_adapter.cpp \
- profile_adapter_client.cpp \
- profile_qt.cpp \
- profile_io_data_qt.cpp \
- quota_permission_context_qt.cpp \
- quota_request_controller_impl.cpp \
- pref_service_adapter.cpp \
- register_protocol_handler_request_controller_impl.cpp \
- render_view_context_menu_qt.cpp \
- render_widget_host_view_qt.cpp \
- render_widget_host_view_qt_delegate_client.cpp \
- renderer/content_renderer_client_qt.cpp \
- renderer/content_settings_observer_qt.cpp \
- renderer/render_frame_observer_qt.cpp \
- renderer/render_view_observer_qt.cpp \
- renderer/render_thread_observer_qt.cpp \
- renderer/user_resource_controller.cpp \
- renderer/plugins/plugin_placeholder_qt.cpp \
- renderer_host/render_view_observer_host_qt.cpp \
- renderer_host/user_resource_controller_host.cpp \
- resource_bundle_qt.cpp \
- resource_context_qt.cpp \
- touch_handle_drawable_qt.cpp \
- touch_selection_controller_client_qt.cpp \
- touch_selection_menu_controller.cpp \
- type_conversion.cpp \
- user_notification_controller.cpp \
- user_script.cpp \
- visited_links_manager_qt.cpp \
- web_contents_adapter.cpp \
- web_contents_delegate_qt.cpp \
- web_contents_view_qt.cpp \
- web_engine_context.cpp \
- web_engine_context_threads.cpp \
- web_engine_error.cpp \
- web_engine_library_info.cpp \
- web_engine_settings.cpp \
- web_event_factory.cpp
-
-HEADERS = \
- accessibility_activation_observer.h \
- authentication_dialog_controller_p.h \
- authentication_dialog_controller.h \
- build_config_qt.h \
- browser_accessibility_manager_qt.h \
- browser_accessibility_qt.h \
- browsing_data_remover_delegate_qt.h \
- browser_main_parts_qt.h \
- browser_message_filter_qt.h \
- certificate_error_controller_p.h \
- certificate_error_controller.h \
- client_cert_select_controller.h \
- clipboard_change_observer.h \
- clipboard_qt.h \
- color_chooser_qt.h \
- color_chooser_controller_p.h \
- color_chooser_controller.h \
- common/qt_messages.h \
- common/user_script_data.h \
- compositor/compositor.h \
- compositor/content_gpu_client_qt.h \
- compositor/display_software_output_surface.h \
- content_client_qt.h \
- content_browser_client_qt.h \
- content_main_delegate_qt.h \
- content_utility_client_qt.h \
- delegated_frame_host_client_qt.h \
- desktop_screen_qt.h \
- devtools_frontend_qt.h \
- devtools_manager_delegate_qt.h \
- download_manager_delegate_qt.h \
- favicon_manager.h \
- file_picker_controller.h \
- find_text_helper.h \
- global_descriptors_qt.h \
- javascript_dialog_controller_p.h \
- javascript_dialog_controller.h \
- javascript_dialog_manager_qt.h \
- login_delegate_qt.h \
- media_capture_devices_dispatcher.h \
- net/client_cert_override.h \
- net/client_cert_store_data.h \
- net/cookie_monster_delegate_qt.h \
- net/custom_url_loader_factory.h \
- net/proxying_url_loader_factory_qt.h \
- net/proxying_restricted_cookie_manager_qt.h \
- net/qrc_url_scheme_handler.h \
- net/ssl_host_state_delegate_qt.h \
- net/system_network_context_manager.h \
- net/url_request_custom_job_delegate.h \
- net/url_request_custom_job_proxy.h \
- net/webui_controller_factory_qt.h \
- ozone/gl_context_qt.h \
- ozone/gl_ozone_egl_qt.h \
- ozone/gl_surface_qt.h \
- ozone/gl_surface_egl_qt.h \
- ozone/gl_surface_wgl_qt.h \
- ozone/platform_window_qt.h \
- ozone/surface_factory_qt.h \
- permission_manager_qt.h \
- platform_notification_service_qt.h \
- pref_service_adapter.h \
- process_main.h \
- profile_adapter.h \
- profile_adapter_client.h \
- profile_qt.h \
- profile_io_data_qt.h \
- proxy_config_monitor.h \
- proxy_config_service_qt.h \
- quota_permission_context_qt.h \
- quota_request_controller.h \
- quota_request_controller_impl.h \
- register_protocol_handler_request_controller.h \
- register_protocol_handler_request_controller_impl.h \
- render_view_context_menu_qt.h \
- render_widget_host_view_qt.h \
- render_widget_host_view_qt_delegate.h \
- render_widget_host_view_qt_delegate_client.h \
- renderer/content_renderer_client_qt.h \
- renderer/content_settings_observer_qt.h \
- renderer/render_frame_observer_qt.h \
- renderer/render_view_observer_qt.h \
- renderer/render_thread_observer_qt.h \
- renderer/user_resource_controller.h \
- renderer/plugins/plugin_placeholder_qt.h \
- renderer_host/render_view_observer_host_qt.h \
- renderer_host/user_resource_controller_host.h \
- request_controller.h \
- resource_context_qt.h \
- touch_handle_drawable_client.h \
- touch_handle_drawable_qt.h \
- touch_selection_controller_client_qt.h \
- touch_selection_menu_controller.h \
- type_conversion.h \
- user_notification_controller.h \
- user_script.h \
- visited_links_manager_qt.h \
- web_contents_adapter.h \
- web_contents_adapter_client.h \
- web_contents_delegate_qt.h \
- web_contents_view_qt.h \
- web_engine_context.h \
- web_engine_error.h \
- web_engine_library_info.h \
- web_engine_settings.h \
- web_event_factory.h
-
-qtConfig(webengine-ozone-x11) {
- HEADERS += ozone/gl_ozone_glx_qt.h \
- ozone/gl_surface_glx_qt.h
- SOURCES += ozone/gl_surface_glx_qt.cpp \
- ozone/gl_ozone_glx_qt.cpp
-}
-
-qtConfig(webengine-pepper-plugins) {
-
- SOURCES += \
- renderer_host/pepper/pepper_flash_browser_host_qt.cpp \
- renderer_host/pepper/pepper_host_factory_qt.cpp \
- renderer_host/pepper/pepper_isolated_file_system_message_filter.cpp \
- renderer/pepper/pepper_flash_renderer_host_qt.cpp \
- renderer/pepper/pepper_renderer_host_factory_qt.cpp \
- renderer/plugins/loadable_plugin_placeholder_qt.cpp
-
- HEADERS += \
- renderer_host/pepper/pepper_flash_browser_host_qt.h \
- renderer_host/pepper/pepper_host_factory_qt.h \
- renderer_host/pepper/pepper_isolated_file_system_message_filter.h \
- renderer/pepper/pepper_flash_renderer_host_qt.h \
- renderer/pepper/pepper_renderer_host_factory_qt.h \
- renderer/plugins/loadable_plugin_placeholder_qt.h
-}
-
-qtConfig(webengine-printing-and-pdf) {
-
- SOURCES += \
- printing/printing_message_filter_qt.cpp \
- printing/print_view_manager_base_qt.cpp \
- printing/print_view_manager_qt.cpp \
- renderer/print_web_view_helper_delegate_qt.cpp
-
- HEADERS += \
- printing/printing_message_filter_qt.h \
- printing/print_view_manager_base_qt.h \
- printing/print_view_manager_qt.h \
- renderer/print_web_view_helper_delegate_qt.h
-
- # pdf sources
- SOURCES += printing/pdfium_document_wrapper_qt.cpp
- HEADERS += printing/pdfium_document_wrapper_qt.h
-}
-
-contains(QT_CONFIG, opengl) {
- SOURCES += \
- compositor/compositor_resource_fence.cpp \
- compositor/display_gl_output_surface.cpp
- HEADERS += \
- compositor/compositor_resource_fence.h \
- compositor/display_gl_output_surface.h
-}
-
-qtConfig(webengine-geolocation) {
- SOURCES += location_provider_qt.cpp
- HEADERS += location_provider_qt.h
-}
-
-qtConfig(webengine-webchannel) {
- HEADERS += renderer/web_channel_ipc_transport.h \
- renderer_host/web_channel_ipc_transport_host.h
-
- SOURCES += renderer/web_channel_ipc_transport.cpp \
- renderer_host/web_channel_ipc_transport_host.cpp
-}
-
-qtConfig(webengine-extensions) {
- SOURCES += \
- common/extensions/extensions_api_provider_qt.cpp \
- common/extensions/extensions_client_qt.cpp \
- extensions/component_extension_resource_manager_qt.cpp \
- extensions/extension_system_qt.cpp \
- extensions/extension_system_factory_qt.cpp \
- extensions/extension_web_contents_observer_qt.cpp \
- extensions/extensions_api_client_qt.cpp \
- extensions/extensions_browser_client_qt.cpp \
- extensions/mime_handler_view_guest_delegate_qt.cpp \
- net/plugin_response_interceptor_url_loader_throttle.cpp \
- renderer/extensions/extensions_dispatcher_delegate_qt.cpp \
- renderer/extensions/extensions_renderer_client_qt.cpp \
- renderer/extensions/renderer_permissions_policy_delegate_qt.cpp \
- renderer/extensions/resource_request_policy_qt.cpp
-
- HEADERS += \
- common/extensions/extensions_api_provider_qt.h \
- common/extensions/extensions_client_qt.h \
- extensions/component_extension_resource_manager_qt.h \
- extensions/extension_system_qt.h \
- extensions/extension_system_factory_qt.h \
- extensions/extension_web_contents_observer_qt.h \
- extensions/extensions_api_client_qt.h \
- extensions/extensions_browser_client_qt.h \
- extensions/mime_handler_view_guest_delegate_qt.h \
- net/plugin_response_interceptor_url_loader_throttle.h \
- renderer/extensions/extensions_dispatcher_delegate_qt.h \
- renderer/extensions/extensions_renderer_client_qt.h \
- renderer/extensions/renderer_permissions_policy_delegate_qt.h \
- renderer/extensions/resource_request_policy_qt.h
-}
diff --git a/src/core/core_common.pri b/src/core/core_common.pri
deleted file mode 100644
index e10d14267..000000000
--- a/src/core/core_common.pri
+++ /dev/null
@@ -1,20 +0,0 @@
-include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri)
-include($$QTWEBENGINE_OUT_ROOT/src/core/qtwebenginecore-config.pri)
-QT_FOR_CONFIG += buildtools-private webenginecore webenginecore-private
-
-# NOTE: The TARGET, QT, QT_PRIVATE variables are used in both core_module.pro and core_gyp_generator.pro
-# gyp/ninja will take care of the compilation, qmake/make will finish with linking and install.
-
-TARGET = QtWebEngineCore
-QT += qml-private quick-private gui-private core-private
-QT_PRIVATE += webenginecoreheaders-private
-
-qtConfig(webengine-geolocation): QT += positioning
-qtConfig(webengine-webchannel): QT += webchannel
-
-# LTO does not work for Chromium at the moment, so disable it completely for core.
-CONFIG -= ltcg
-
-# Chromium requires C++14
-CONFIG += c++14
-
diff --git a/src/core/core_generator.pro b/src/core/core_generator.pro
deleted file mode 100644
index 935c653a4..000000000
--- a/src/core/core_generator.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-include(core_common.pri)
-
-include(core_gn_config.pri)
-
-TEMPLATE = lib
-
-include(core_chromium.pri)
diff --git a/src/core/core_gn_config.pri b/src/core/core_gn_config.pri
deleted file mode 100644
index 2b8f2e18f..000000000
--- a/src/core/core_gn_config.pri
+++ /dev/null
@@ -1,17 +0,0 @@
-CONFIG = gn_generator $$CONFIG
-GN_SRC_DIR = $$PWD
-GN_FILE = $$OUT_PWD/$$getConfigDir()/BUILD.gn
-GN_FIND_MOCABLES_SCRIPT = $$shell_path($$QTWEBENGINE_ROOT/tools/scripts/gn_find_mocables.py)
-GN_RUN_BINARY_SCRIPT = $$shell_path($$QTWEBENGINE_ROOT/tools/scripts/gn_run_binary.py)
-GN_IMPORTS = $$PWD/qtwebengine.gni
-qtConfig (webengine-extensions) {
- GN_INCLUDES += $$PWD/qtwebengine_sources.gni $$PWD/qtwebengine_resources.gni $$PWD/common/extensions/api/qtwebengine_extensions_features.gni
-} else {
- GN_INCLUDES = $$PWD/qtwebengine_sources.gni $$PWD/qtwebengine_resources.gni
-}
-GN_CORE_INCLUDE_DIRS = $$PWD/service
-GN_CREATE_PRI = true
-GN_PRECOMPILED_HEADERS = true
-QMAKE_INTERNAL_INCLUDED_FILES = $$GN_IMPORTS $$GN_INCLUDES $$GN_FILE
-
-
diff --git a/src/core/core_headers.pro b/src/core/core_headers.pro
deleted file mode 100644
index cd5352eb7..000000000
--- a/src/core/core_headers.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-TARGET = QtWebEngineCore
-CONFIG += no_private_module header_module internal_module no_plist
-QT -= core gui
-MODULE = webenginecoreheaders
-MODULE_CFG_FILE = qtwebenginecore-config
-load(qt_module)
diff --git a/src/core/core_module.pro b/src/core/core_module.pro
deleted file mode 100644
index 5007012ac..000000000
--- a/src/core/core_module.pro
+++ /dev/null
@@ -1,163 +0,0 @@
-MODULE = webenginecore
-
-include(core_common.pri)
-# Needed to set a CFBundleIdentifier
-QMAKE_INFO_PLIST = Info_mac.plist
-
-linking_pri = $$OUT_PWD/$$getConfigDir()/$${TARGET}.pri
-
-!include($$linking_pri) {
- error("Could not find the linking information that gn should have generated.")
-}
-
-api_library_name = qtwebenginecoreapi$$qtPlatformTargetSuffix()
-api_library_path = $$OUT_PWD/api/$$getConfigDir()
-
-# Do not precompile any headers. We are only interested in the linker step.
-PRECOMPILED_HEADER =
-
-isEmpty(NINJA_OBJECTS): error("Missing object files from QtWebEngineCore linking pri.")
-isEmpty(NINJA_LFLAGS): error("Missing linker flags from QtWebEngineCore linking pri")
-isEmpty(NINJA_ARCHIVES): error("Missing archive files from QtWebEngineCore linking pri")
-isEmpty(NINJA_LIBS): error("Missing library files from QtWebEngineCore linking pri")
-NINJA_OBJECTS = $$eval($$list($$NINJA_OBJECTS))
-# Do manual response file linking for macOS and Linux
-
-RSP_OBJECT_FILE = $$OUT_PWD/$$getConfigDir()/$${TARGET}_o.rsp
-for(object, NINJA_OBJECTS): RSP_O_CONTENT += $$object
-write_file($$RSP_OBJECT_FILE, RSP_O_CONTENT)
-RSP_ARCHIVE_FILE = $$OUT_PWD/$$getConfigDir()/$${TARGET}_a.rsp
-for(archive, NINJA_ARCHIVES): RSP_A_CONTENT += $$archive
-write_file($$RSP_ARCHIVE_FILE, RSP_A_CONTENT)
-
-macos:LIBS_PRIVATE += -Wl,-filelist,$$shell_quote($${RSP_OBJECT_FILE}) @$${RSP_ARCHIVE_FILE}
-linux:QMAKE_LFLAGS += @$${RSP_OBJECT_FILE} -Wl,--start-group @$${RSP_ARCHIVE_FILE} -Wl,--end-group
-win32:QMAKE_LFLAGS += @$${RSP_OBJECT_FILE} @$${RSP_ARCHIVE_FILE}
-
-LIBS_PRIVATE += $$NINJA_LIB_DIRS $$NINJA_LIBS
-# GN's LFLAGS doesn't always work across all the Linux configurations we support.
-# The Windows and macOS ones from GN does provide a few useful flags however
-
-unix:qtConfig(webengine-noexecstack): \
- QMAKE_LFLAGS += -Wl,-z,noexecstack
-linux {
- # add chromium flags
- for(flag, NINJA_LFLAGS) {
- # filter out some flags
- !contains(flag, .*noexecstack$): \
- !contains(flag, .*as-needed$): \
- !contains(flag, ^-B.*): \
- !contains(flag, ^-fuse-ld.*): \
- QMAKE_LFLAGS += $$flag
- }
-} else {
- QMAKE_LFLAGS += $$NINJA_LFLAGS
-}
-
-POST_TARGETDEPS += $$NINJA_TARGETDEPS
-
-
-LIBS_PRIVATE += -L$$api_library_path
-CONFIG *= no_smart_library_merge
-osx {
- LIBS_PRIVATE += -Wl,-force_load,$${api_library_path}$${QMAKE_DIR_SEP}lib$${api_library_name}.a
-} else: win32 {
- !qtConfig(webengine-developer-build) {
- # Remove unused functions and data in debug non-developer builds, because the binaries will
- # be smaller in the shipped packages.
- QMAKE_LFLAGS += /OPT:REF
- } else:CONFIG(debug, debug|release):!clang_cl {
- # Make sure to override qtbase's QMAKE_LFLAGS_DEBUG option in debug developer builds,
- # because qmake chooses and overrides the option when it gets appended to QMAKE_LFLAGS in
- # qtbase\mkspecs\features\default_post.prf, regardless of what Chromium passes back from GN.
- QMAKE_LFLAGS_DEBUG -= /DEBUG
- QMAKE_LFLAGS_DEBUG += /DEBUG:FASTLINK
- }
- # Simulate -whole-archive by passing the list of object files that belong to the public
- # API library as response file to the linker.
- QMAKE_LFLAGS += @$${api_library_path}$${QMAKE_DIR_SEP}$${api_library_name}.lib.objects
-} else {
- QMAKE_LFLAGS += -Wl,-whole-archive -l$$api_library_name -Wl,-no-whole-archive
-}
-
-win32 {
- POST_TARGETDEPS += $${api_library_path}$${QMAKE_DIR_SEP}$${api_library_name}.lib
-} else {
- POST_TARGETDEPS += $${api_library_path}$${QMAKE_DIR_SEP}lib$${api_library_name}.a
-}
-
-# Using -Wl,-Bsymbolic-functions seems to confuse the dynamic linker
-# and doesn't let Chromium get access to libc symbols through dlsym.
-CONFIG -= bsymbolic_functions
-
-linux:qtConfig(separate_debug_info): QMAKE_POST_LINK="cd $(DESTDIR) && $(STRIP) --strip-unneeded $(TARGET)"
-
-REPACK_DIR = $$OUT_PWD/$$getConfigDir()
-
-# Duplicated from resources/resources.gyp
-LOCALE_LIST = am ar bg bn ca cs da de el en-GB en-US es-419 es et fa fi fil fr gu he hi hr hu id it ja kn ko lt lv ml mr ms nb nl pl pt-BR pt-PT ro ru sk sl sr sv sw ta te th tr uk vi zh-CN zh-TW
-for(LOC, LOCALE_LIST) {
- locales.files += $$REPACK_DIR/qtwebengine_locales/$${LOC}.pak
-}
-resources.files = $$REPACK_DIR/qtwebengine_resources.pak \
- $$REPACK_DIR/qtwebengine_resources_100p.pak \
- $$REPACK_DIR/qtwebengine_resources_200p.pak \
- $$REPACK_DIR/qtwebengine_devtools_resources.pak
-
-icu.files = $$OUT_PWD/$$getConfigDir()/icudtl.dat
-
-!qtConfig(debug_and_release)|!qtConfig(build_all)|CONFIG(release, debug|release) {
- qtConfig(framework) {
- locales.version = Versions
- locales.path = Resources/qtwebengine_locales
- resources.version = Versions
- resources.path = Resources
- icu.version = Versions
- icu.path = Resources
- # No files, this prepares the bundle Helpers symlink, process.pro will create the directories
- qtwebengineprocessplaceholder.version = Versions
- qtwebengineprocessplaceholder.path = Helpers
- QMAKE_BUNDLE_DATA += icu locales resources qtwebengineprocessplaceholder
- } else {
- locales.CONFIG += no_check_exist
- locales.path = $$[QT_INSTALL_TRANSLATIONS]/qtwebengine_locales
- resources.CONFIG += no_check_exist
- resources.path = $$[QT_INSTALL_DATA]/resources
- INSTALLS += locales resources
-
- !qtConfig(webengine-system-icu) {
- icu.CONFIG += no_check_exist
- icu.path = $$[QT_INSTALL_DATA]/resources
- INSTALLS += icu
- }
- }
-
- !qtConfig(framework):!force_independent {
- #
- # Copy essential files to the qtbase build directory for non-prefix builds
- #
-
- !qtConfig(webengine-system-icu) {
- COPIES += icu
- }
-
- COPIES += resources locales
- }
-}
-
-!build_pass:qtConfig(debug_and_release) {
- # Special GNU make target that ensures linking isn't done for both debug and release builds
- # at the same time.
- notParallel.target = .NOTPARALLEL
- QMAKE_EXTRA_TARGETS += notParallel
-}
-
-OTHER_FILES = \
- $$files(../3rdparty/chromium/*.py, true) \
- $$files(../3rdparty/chromium/*.gyp, true) \
- $$files(../3rdparty/chromium/*.gypi, true) \
- $$files(../3rdparty/chromium/*.gn, true) \
- $$files(../3rdparty/chromium/*.gni, true)
-
-load(qt_module)
-
diff --git a/src/core/core_project.pro b/src/core/core_project.pro
deleted file mode 100644
index 9c8e20808..000000000
--- a/src/core/core_project.pro
+++ /dev/null
@@ -1,28 +0,0 @@
-TEMPLATE = lib
-# Fake project to make QtCreator happy.
-
-include(core_common.pri)
-
-
-linking_pri = $$OUT_PWD/$$getConfigDir()/$${TARGET}.pri
-
-!include($$linking_pri) {
- error("Could not find the linking information that gn should have generated.")
-}
-
-CHROMIUM_SRC_DIR = $$QTWEBENGINE_ROOT/$$getChromiumSrcDir()
-INCLUDEPATH += $$CHROMIUM_SRC_DIR \
- $$CHROMIUM_SRC_DIR/third_party/blink/public \
- $$OUT_PWD/$$getConfigDir()/gen
-
-SOURCES += $$NINJA_SOURCES
-HEADERS += $$NINJA_HEADERS
-DEFINES += $$NINJA_DEFINES
-
-lupdate_run {
- SOURCES += clipboard_qt.cpp \
- profile_adapter_client.cpp \
- profile_adapter.cpp \
- render_view_context_menu_qt.cpp \
- web_contents_adapter.cpp
-}
diff --git a/src/core/custom_handlers/protocol_handler_registry_delegate_qt.cpp b/src/core/custom_handlers/protocol_handler_registry_delegate_qt.cpp
new file mode 100644
index 000000000..a5074fb88
--- /dev/null
+++ b/src/core/custom_handlers/protocol_handler_registry_delegate_qt.cpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/custom_handlers/chrome_protocol_handler_registry_delegate.cc:
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "protocol_handler_registry_delegate_qt.h"
+
+#include "content/public/browser/child_process_security_policy.h"
+#include "url/url_util_qt.h"
+
+namespace QtWebEngineCore {
+
+using content::ChildProcessSecurityPolicy;
+
+ProtocolHandlerRegistryDelegateQt::ProtocolHandlerRegistryDelegateQt() = default;
+
+ProtocolHandlerRegistryDelegateQt::~ProtocolHandlerRegistryDelegateQt() = default;
+
+// ProtocolHandlerRegistry::Delegate:
+void ProtocolHandlerRegistryDelegateQt::RegisterExternalHandler(const std::string &protocol)
+{
+ ChildProcessSecurityPolicy *policy = ChildProcessSecurityPolicy::GetInstance();
+ if (!policy->IsWebSafeScheme(protocol)) {
+ policy->RegisterWebSafeScheme(protocol);
+ }
+}
+
+bool ProtocolHandlerRegistryDelegateQt::IsExternalHandlerRegistered(const std::string &protocol)
+{
+ return url::IsHandledProtocol(protocol);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/custom_handlers/protocol_handler_registry_delegate_qt.h b/src/core/custom_handlers/protocol_handler_registry_delegate_qt.h
new file mode 100644
index 000000000..6a0753d22
--- /dev/null
+++ b/src/core/custom_handlers/protocol_handler_registry_delegate_qt.h
@@ -0,0 +1,35 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/custom_handlers/chrome_protocol_handler_registry_delegate.h:
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PROTOCOL_HANDLER_REGISTRY_DELEGATE_QT_H_
+#define PROTOCOL_HANDLER_REGISTRY_DELEGATE_QT_H_
+
+#include <string>
+
+#include "components/custom_handlers/protocol_handler_registry.h"
+
+namespace QtWebEngineCore {
+
+// This class implements the ProtocolHandlerRegistry::Delegate
+// abstract class to provide an OS dependent implementation
+class ProtocolHandlerRegistryDelegateQt : public custom_handlers::ProtocolHandlerRegistry::Delegate {
+public:
+ ProtocolHandlerRegistryDelegateQt();
+ ~ProtocolHandlerRegistryDelegateQt() override;
+
+ ProtocolHandlerRegistryDelegateQt(const ProtocolHandlerRegistryDelegateQt &other) = delete;
+ ProtocolHandlerRegistryDelegateQt &operator=(const ProtocolHandlerRegistryDelegateQt &other) = delete;
+
+ // ProtocolHandlerRegistry::Delegate:
+ void RegisterExternalHandler(const std::string &protocol) override;
+ bool IsExternalHandlerRegistered(const std::string &protocol) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // PROTOCOL_HANDLER_REGISTRY_DELEGATE_QT_H_
diff --git a/src/core/custom_handlers/protocol_handler_registry_factory.cpp b/src/core/custom_handlers/protocol_handler_registry_factory.cpp
new file mode 100644
index 000000000..50b17006b
--- /dev/null
+++ b/src/core/custom_handlers/protocol_handler_registry_factory.cpp
@@ -0,0 +1,75 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/custom_handlers/protocol_handler_registry_factory.cc
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "protocol_handler_registry_factory.h"
+
+#include <memory>
+
+#include "base/memory/singleton.h"
+#include "components/custom_handlers/protocol_handler_registry.h"
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+
+#include "protocol_handler_registry_delegate_qt.h"
+
+namespace QtWebEngineCore {
+
+// static
+ProtocolHandlerRegistryFactory *ProtocolHandlerRegistryFactory::GetInstance()
+{
+ return base::Singleton<ProtocolHandlerRegistryFactory>::get();
+}
+
+// static
+custom_handlers::ProtocolHandlerRegistry *ProtocolHandlerRegistryFactory::GetForBrowserContext(content::BrowserContext *context)
+{
+ return static_cast<custom_handlers::ProtocolHandlerRegistry *>(GetInstance()->GetServiceForBrowserContext(context, true));
+}
+
+ProtocolHandlerRegistryFactory::ProtocolHandlerRegistryFactory()
+ : BrowserContextKeyedServiceFactory("ProtocolHandlerRegistry", BrowserContextDependencyManager::GetInstance()) {}
+
+ProtocolHandlerRegistryFactory::~ProtocolHandlerRegistryFactory()
+{
+}
+
+// Will be created when initializing profile_io_data, so we might
+// as well have the framework create this along with other
+// PKSs to preserve orderly civic conduct :)
+bool ProtocolHandlerRegistryFactory::ServiceIsCreatedWithBrowserContext() const
+{
+ return true;
+}
+
+// Allows the produced registry to be used in incognito mode.
+content::BrowserContext *ProtocolHandlerRegistryFactory::GetBrowserContextToUse(content::BrowserContext *context) const
+{
+ return context;
+// return chrome::GetBrowserContextRedirectedInIncognito(context);
+}
+
+// Do not create this service for tests. MANY tests will fail
+// due to the threading requirements of this service. ALSO,
+// not creating this increases test isolation (which is GOOD!)
+bool ProtocolHandlerRegistryFactory::ServiceIsNULLWhileTesting() const
+{
+ return true;
+}
+
+KeyedService *ProtocolHandlerRegistryFactory::BuildServiceInstanceFor(content::BrowserContext *context) const
+{
+ custom_handlers::ProtocolHandlerRegistry *registry =
+ new custom_handlers::ProtocolHandlerRegistry(/*prefs*/ nullptr,
+ std::make_unique<ProtocolHandlerRegistryDelegateQt>());
+
+ // Must be called as a part of the creation process.
+ registry->InitProtocolSettings();
+
+ return registry;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/custom_handlers/protocol_handler_registry_factory.h b/src/core/custom_handlers/protocol_handler_registry_factory.h
new file mode 100644
index 000000000..6559addc0
--- /dev/null
+++ b/src/core/custom_handlers/protocol_handler_registry_factory.h
@@ -0,0 +1,57 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/custom_handlers/protocol_handler_registry_factory.h:
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PROTOCOL_HANDLER_REGISTRY_FACTORY_H_
+#define PROTOCOL_HANDLER_REGISTRY_FACTORY_H_
+
+#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
+
+namespace custom_handlers {
+class ProtocolHandlerRegistry;
+}
+
+namespace base {
+template <typename T> struct DefaultSingletonTraits;
+}
+
+namespace QtWebEngineCore {
+
+// Singleton that owns all ProtocolHandlerRegistrys and associates them with
+// Profiles. Listens for the Profile's destruction notification and cleans up
+// the associated ProtocolHandlerRegistry.
+class ProtocolHandlerRegistryFactory : public BrowserContextKeyedServiceFactory {
+public:
+ // Returns the singleton instance of the ProtocolHandlerRegistryFactory.
+ static ProtocolHandlerRegistryFactory *GetInstance();
+
+ // Returns the ProtocolHandlerRegistry that provides intent registration for
+ // |context|. Ownership stays with this factory object.
+ static custom_handlers::ProtocolHandlerRegistry *GetForBrowserContext(content::BrowserContext *context);
+
+ ProtocolHandlerRegistryFactory(const ProtocolHandlerRegistryFactory &) = delete;
+ ProtocolHandlerRegistryFactory &operator=(const ProtocolHandlerRegistryFactory &) = delete;
+
+protected:
+ // BrowserContextKeyedServiceFactory implementation.
+ bool ServiceIsCreatedWithBrowserContext() const override;
+ content::BrowserContext *GetBrowserContextToUse(content::BrowserContext *context) const override;
+ bool ServiceIsNULLWhileTesting() const override;
+
+private:
+ friend struct base::DefaultSingletonTraits<ProtocolHandlerRegistryFactory>;
+
+ ProtocolHandlerRegistryFactory();
+ ~ProtocolHandlerRegistryFactory() override;
+
+ // BrowserContextKeyedServiceFactory implementation.
+ KeyedService *BuildServiceInstanceFor(content::BrowserContext *profile) const override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // PROTOCOL_HANDLER_REGISTRY_FACTORY_H_
diff --git a/src/core/custom_handlers/register_protocol_handler_request_controller.h b/src/core/custom_handlers/register_protocol_handler_request_controller.h
new file mode 100644
index 000000000..6305ce5b7
--- /dev/null
+++ b/src/core/custom_handlers/register_protocol_handler_request_controller.h
@@ -0,0 +1,26 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
+#define REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
+
+#include "request_controller.h"
+
+namespace QtWebEngineCore {
+
+class RegisterProtocolHandlerRequestController : public RequestController {
+public:
+ RegisterProtocolHandlerRequestController(QUrl origin, QString scheme)
+ : RequestController(std::move(origin))
+ , m_scheme(std::move(scheme))
+ {}
+
+ QString scheme() const { return m_scheme; }
+
+private:
+ QString m_scheme;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
diff --git a/src/core/custom_handlers/register_protocol_handler_request_controller_impl.cpp b/src/core/custom_handlers/register_protocol_handler_request_controller_impl.cpp
new file mode 100644
index 000000000..efaf54cd2
--- /dev/null
+++ b/src/core/custom_handlers/register_protocol_handler_request_controller_impl.cpp
@@ -0,0 +1,49 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "custom_handlers/register_protocol_handler_request_controller_impl.h"
+
+#include "components/custom_handlers/protocol_handler_registry.h"
+#include "content/public/browser/web_contents.h"
+
+#include "custom_handlers/protocol_handler_registry_factory.h"
+#include "type_conversion.h"
+
+namespace QtWebEngineCore {
+
+RegisterProtocolHandlerRequestControllerImpl::RegisterProtocolHandlerRequestControllerImpl(
+ content::WebContents *webContents,
+ custom_handlers::ProtocolHandler handler)
+ : RegisterProtocolHandlerRequestController(
+ toQt(handler.url()),
+ toQt(handler.protocol()))
+ , content::WebContentsObserver(webContents)
+ , m_handler(handler)
+{}
+
+RegisterProtocolHandlerRequestControllerImpl::~RegisterProtocolHandlerRequestControllerImpl()
+{
+ reject();
+}
+
+custom_handlers::ProtocolHandlerRegistry *RegisterProtocolHandlerRequestControllerImpl::protocolHandlerRegistry()
+{
+ content::WebContents *webContents = web_contents();
+ if (!webContents)
+ return nullptr;
+ content::BrowserContext *context = webContents->GetBrowserContext();
+ return ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
+}
+
+void RegisterProtocolHandlerRequestControllerImpl::accepted()
+{
+ if (custom_handlers::ProtocolHandlerRegistry *registry = protocolHandlerRegistry())
+ registry->OnAcceptRegisterProtocolHandler(m_handler);
+}
+
+void RegisterProtocolHandlerRequestControllerImpl::rejected()
+{
+ if (custom_handlers::ProtocolHandlerRegistry *registry = protocolHandlerRegistry())
+ registry->OnIgnoreRegisterProtocolHandler(m_handler);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/custom_handlers/register_protocol_handler_request_controller_impl.h b/src/core/custom_handlers/register_protocol_handler_request_controller_impl.h
new file mode 100644
index 000000000..073ca9bf8
--- /dev/null
+++ b/src/core/custom_handlers/register_protocol_handler_request_controller_impl.h
@@ -0,0 +1,38 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
+#define REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
+
+#include "register_protocol_handler_request_controller.h"
+
+#include "content/public/browser/web_contents_observer.h"
+#include "components/custom_handlers/protocol_handler.h"
+
+namespace custom_handlers {
+class ProtocolHandlerRegistry;
+}
+
+namespace QtWebEngineCore {
+
+class RegisterProtocolHandlerRequestControllerImpl final : public RegisterProtocolHandlerRequestController,
+ private content::WebContentsObserver {
+public:
+ RegisterProtocolHandlerRequestControllerImpl(
+ content::WebContents *webContents,
+ custom_handlers::ProtocolHandler handler);
+
+ ~RegisterProtocolHandlerRequestControllerImpl();
+
+protected:
+ void accepted() override;
+ void rejected() override;
+
+private:
+ custom_handlers::ProtocolHandlerRegistry *protocolHandlerRegistry();
+ custom_handlers::ProtocolHandler m_handler;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
diff --git a/src/core/delegated_frame_host_client_qt.cpp b/src/core/delegated_frame_host_client_qt.cpp
index d3f5a4ade..ad1de91f6 100644
--- a/src/core/delegated_frame_host_client_qt.cpp
+++ b/src/core/delegated_frame_host_client_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "delegated_frame_host_client_qt.h"
@@ -58,19 +22,14 @@ SkColor DelegatedFrameHostClientQt::DelegatedFrameHostGetGutterColor() const
return p->GetBackgroundColor().value_or(SK_ColorWHITE);
}
-void DelegatedFrameHostClientQt::OnBeginFrame(base::TimeTicks frame_time)
+void DelegatedFrameHostClientQt::OnFrameTokenChanged(uint32_t frame_token, base::TimeTicks activation_time)
{
- p->host()->ProgressFlingIfNeeded(frame_time);
-}
-
-void DelegatedFrameHostClientQt::OnFrameTokenChanged(uint32_t frame_token)
-{
- p->OnFrameTokenChangedForView(frame_token);
+ p->OnFrameTokenChangedForView(frame_token, activation_time);
}
float DelegatedFrameHostClientQt::GetDeviceScaleFactor() const
{
- return p->m_screenInfo.device_scale_factor;
+ return p->GetScreenInfo().device_scale_factor;
}
void DelegatedFrameHostClientQt::InvalidateLocalSurfaceIdOnEviction()
diff --git a/src/core/delegated_frame_host_client_qt.h b/src/core/delegated_frame_host_client_qt.h
index b5dc6eb59..184b84d7a 100644
--- a/src/core/delegated_frame_host_client_qt.h
+++ b/src/core/delegated_frame_host_client_qt.h
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DELEGATED_FRAME_HOST_CLIENT_QT_H
#define DELEGATED_FRAME_HOST_CLIENT_QT_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include "content/browser/renderer_host/delegated_frame_host.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
@@ -57,8 +21,8 @@ public:
ui::Layer *DelegatedFrameHostGetLayer() const override;
bool DelegatedFrameHostIsVisible() const override;
SkColor DelegatedFrameHostGetGutterColor() const override;
- void OnBeginFrame(base::TimeTicks frame_time) override;
- void OnFrameTokenChanged(uint32_t frame_token) override;
+ void OnFrameTokenChanged(uint32_t frame_token,
+ base::TimeTicks activation_time) override;
float GetDeviceScaleFactor() const override;
void InvalidateLocalSurfaceIdOnEviction() override;
std::vector<viz::SurfaceId> CollectSurfaceIdsForEviction() override;
diff --git a/src/core/desktop_media_controller.cpp b/src/core/desktop_media_controller.cpp
new file mode 100644
index 000000000..50ac0a40c
--- /dev/null
+++ b/src/core/desktop_media_controller.cpp
@@ -0,0 +1,244 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "desktop_media_controller.h"
+#include "desktop_media_controller_p.h"
+#include "type_conversion.h"
+
+#include "base/containers/contains.h"
+#include "base/functional/callback.h"
+#include "chrome/browser/media/webrtc/desktop_capturer_wrapper.h"
+#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
+#include "content/public/browser/desktop_media_id.h"
+
+#if QT_CONFIG(webengine_webrtc)
+#include "content/public/browser/desktop_capture.h"
+#endif // QT_CONFIG(webengine_webrtc)
+
+namespace QtWebEngineCore {
+namespace {
+DesktopMediaList::Type toMediaListType(DesktopMediaType type)
+{
+ switch (type) {
+ case DesktopMediaType::Screen:
+ return DesktopMediaList::Type::kScreen;
+ case DesktopMediaType::Window:
+ return DesktopMediaList::Type::kWindow;
+ default:
+ return DesktopMediaList::Type::kNone;
+ }
+}
+
+std::unique_ptr<DesktopMediaList> createMediaList(DesktopMediaType type)
+{
+#if QT_CONFIG(webengine_webrtc)
+ DesktopMediaList::Type listType = toMediaListType(type);
+ webrtc::DesktopCaptureOptions options = content::desktop_capture::CreateDesktopCaptureOptions();
+
+ switch (listType) {
+ case DesktopMediaList::Type::kScreen: {
+ std::unique_ptr<webrtc::DesktopCapturer> screenCapturer =
+ webrtc::DesktopCapturer::CreateScreenCapturer(options);
+ std::unique_ptr<DesktopCapturerWrapper> capturer =
+ std::make_unique<DesktopCapturerWrapper>(std::move(screenCapturer));
+ return std::make_unique<NativeDesktopMediaList>(listType, std::move(capturer));
+ }
+ case DesktopMediaList::Type::kWindow: {
+ std::unique_ptr<webrtc::DesktopCapturer> windowCapturer =
+ webrtc::DesktopCapturer::CreateWindowCapturer(options);
+ std::unique_ptr<DesktopCapturerWrapper> capturer =
+ std::make_unique<DesktopCapturerWrapper>(std::move(windowCapturer));
+ return std::make_unique<NativeDesktopMediaList>(
+ listType, std::move(capturer),
+ !content::desktop_capture::ShouldEnumerateCurrentProcessWindows());
+ }
+ default: {
+ Q_UNREACHABLE();
+ }
+ }
+#else
+ return nullptr;
+#endif // QT_CONFIG(webengine_webrtc)
+}
+} // namespace
+
+class DesktopMediaListQtPrivate : public DesktopMediaListObserver
+{
+public:
+ DesktopMediaListQtPrivate(DesktopMediaType type, DesktopMediaListQt *qq);
+
+ void init();
+ void startUpdating();
+ const DesktopMediaList::Source& getSource(int index) const;
+
+ void OnSourceAdded(int index) override;
+ void OnSourceRemoved(int index) override;
+ void OnSourceMoved(int old_index, int new_index) override;
+ void OnSourceNameChanged(int index) override;
+ void OnSourceThumbnailChanged(int index) override { }
+ void OnSourcePreviewChanged(size_t index) override { }
+ void OnDelegatedSourceListSelection() override { }
+ void OnDelegatedSourceListDismissed() override { }
+
+ bool isInitialized;
+ std::unique_ptr<DesktopMediaList> mediaList;
+ DesktopMediaListQt *q_ptr;
+ Q_DECLARE_PUBLIC(DesktopMediaListQt)
+};
+
+DesktopMediaListQtPrivate::DesktopMediaListQtPrivate(DesktopMediaType type, DesktopMediaListQt *qq)
+ : isInitialized(false)
+ , mediaList(createMediaList(type))
+ , q_ptr(qq)
+{
+}
+
+const DesktopMediaList::Source& DesktopMediaListQtPrivate::getSource(int index) const
+{
+ return mediaList->GetSource(index);
+}
+
+void DesktopMediaListQtPrivate::init()
+{
+ // Work around the asynchronous initialization of the source list.
+ // DesktopMediaList::Update populates the list and notifies the controller when it completes.
+ // This makes direct 'selectScreen/Window' calls possible from the frontend.
+ // Note: StartUpdating should be called after Update is completed as it can overwrite the
+ // internal cb.
+ base::OnceCallback<void()> onComplete = base::BindOnce(
+ [](DesktopMediaListQtPrivate *observer) {
+ observer->isInitialized = true;
+ Q_EMIT observer->q_ptr->initialized();
+ observer->startUpdating();
+ },
+ this);
+ mediaList->Update(std::move(onComplete));
+}
+
+void DesktopMediaListQtPrivate::startUpdating()
+{
+ mediaList->StartUpdating(this);
+}
+
+void DesktopMediaListQtPrivate::OnSourceAdded(int index)
+{
+ Q_Q(DesktopMediaListQt);
+ Q_EMIT q->sourceAdded(index);
+}
+
+void DesktopMediaListQtPrivate::OnSourceRemoved(int index)
+{
+ Q_Q(DesktopMediaListQt);
+ Q_EMIT q->sourceRemoved(index);
+}
+
+void DesktopMediaListQtPrivate::OnSourceMoved(int old_index, int new_index)
+{
+ Q_Q(DesktopMediaListQt);
+ Q_EMIT q->sourceMoved(old_index, new_index);
+}
+
+void DesktopMediaListQtPrivate::OnSourceNameChanged(int index)
+{
+ Q_Q(DesktopMediaListQt);
+ Q_EMIT q->sourceNameChanged(index);
+}
+
+DesktopMediaListQt::DesktopMediaListQt(DesktopMediaType type)
+ : d(new DesktopMediaListQtPrivate(type, this))
+{
+}
+
+DesktopMediaListQt::~DesktopMediaListQt() { }
+
+QString DesktopMediaListQt::getSourceName(int index) const
+{
+ const auto &source = d->getSource(index);
+ return toQt(source.name);
+}
+
+int DesktopMediaListQt::getSourceCount() const
+{
+ return d->mediaList->GetSourceCount();
+}
+
+bool DesktopMediaListQt::isInitialized() const
+{
+ return d->isInitialized;
+}
+
+DesktopMediaControllerPrivate::DesktopMediaControllerPrivate(
+ base::OnceCallback<void(content::DesktopMediaID)> doneCallback)
+ : doneCallback(std::move(doneCallback))
+ , screens(new DesktopMediaListQt(DesktopMediaType::Screen))
+ , windows(new DesktopMediaListQt(DesktopMediaType::Window))
+{
+}
+
+void DesktopMediaControllerPrivate::selectScreen(int index)
+{
+ const auto &source = screens->d->getSource(index);
+ std::move(doneCallback).Run(source.id);
+}
+
+void DesktopMediaControllerPrivate::selectWindow(int index)
+{
+ const auto &source = windows->d->getSource(index);
+ std::move(doneCallback).Run(source.id);
+}
+
+void DesktopMediaControllerPrivate::cancel()
+{
+ std::move(doneCallback).Run({});
+}
+
+DesktopMediaController::DesktopMediaController(DesktopMediaControllerPrivate *dd)
+ : d(dd)
+{
+ // Make sure both lists are populated before sending the request.
+ DesktopMediaListQt *screens = DesktopMediaController::screens();
+ DesktopMediaListQt *windows = DesktopMediaController::windows();
+ QObject::connect(screens, &DesktopMediaListQt::initialized, [windows, this]() {
+ if (windows->isInitialized())
+ Q_EMIT mediaListsInitialized();
+ });
+
+ QObject::connect(windows, &DesktopMediaListQt::initialized, [screens, this]() {
+ if (screens->isInitialized())
+ Q_EMIT mediaListsInitialized();
+ });
+
+ screens->d->init();
+ windows->d->init();
+}
+
+DesktopMediaController::~DesktopMediaController()
+{
+}
+
+void DesktopMediaController::selectScreen(int index)
+{
+ d->selectScreen(index);
+}
+
+void DesktopMediaController::selectWindow(int index)
+{
+ d->selectWindow(index);
+}
+
+void DesktopMediaController::cancel()
+{
+ d->cancel();
+}
+
+DesktopMediaListQt *DesktopMediaController::screens() const
+{
+ return d->screens.data();
+}
+
+DesktopMediaListQt *DesktopMediaController::windows() const
+{
+ return d->windows.data();
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/desktop_media_controller.h b/src/core/desktop_media_controller.h
new file mode 100644
index 000000000..0cb741225
--- /dev/null
+++ b/src/core/desktop_media_controller.h
@@ -0,0 +1,65 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef DESKTOP_MEDIA_CONTROLLER_H
+#define DESKTOP_MEDIA_CONTROLLER_H
+
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+#include <QtCore/QObject>
+
+#include <QString>
+
+namespace QtWebEngineCore {
+class DesktopMediaListQtPrivate;
+class DesktopMediaControllerPrivate;
+
+enum DesktopMediaType { Screen = 0, Window };
+
+class Q_WEBENGINECORE_EXPORT DesktopMediaListQt : public QObject
+{
+ Q_OBJECT
+public:
+ ~DesktopMediaListQt() override;
+
+ QString getSourceName(int index) const;
+ int getSourceCount() const;
+
+Q_SIGNALS:
+ void initialized();
+ void itemSelected(int index);
+ void sourceAdded(int index);
+ void sourceRemoved(int index);
+ void sourceMoved(int oldIndex, int newIndex);
+ void sourceNameChanged(int index);
+
+private:
+ friend class DesktopMediaController;
+ friend class DesktopMediaControllerPrivate;
+ bool isInitialized() const;
+ explicit DesktopMediaListQt(DesktopMediaType type);
+ std::unique_ptr<DesktopMediaListQtPrivate> d;
+};
+
+class Q_WEBENGINECORE_EXPORT DesktopMediaController : public QObject
+{
+ Q_OBJECT
+public:
+ explicit DesktopMediaController(DesktopMediaControllerPrivate *dd);
+ ~DesktopMediaController() override;
+
+ DesktopMediaListQt *screens() const;
+ DesktopMediaListQt *windows() const;
+
+ void selectScreen(int index);
+ void selectWindow(int index);
+ void cancel();
+
+Q_SIGNALS:
+ void mediaListsInitialized();
+
+private:
+ std::unique_ptr<DesktopMediaControllerPrivate> d;
+};
+
+} // namespace QtWebEngineCore
+#endif // DESKTOP_MEDIA_CONTROLLER_H
diff --git a/src/core/desktop_media_controller_p.h b/src/core/desktop_media_controller_p.h
new file mode 100644
index 000000000..4bb3a6312
--- /dev/null
+++ b/src/core/desktop_media_controller_p.h
@@ -0,0 +1,28 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef DESKTOP_MEDIA_CONTROLLER_P_H
+#define DESKTOP_MEDIA_CONTROLLER_P_H
+
+#include <QtCore/QObject>
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+
+#include "content/public/browser/desktop_media_id.h"
+#include "base/functional/callback.h"
+
+namespace QtWebEngineCore {
+class Q_WEBENGINECORE_EXPORT DesktopMediaControllerPrivate
+{
+public:
+ DesktopMediaControllerPrivate(base::OnceCallback<void(content::DesktopMediaID)> doneCallback);
+ void selectScreen(int index);
+ void selectWindow(int index);
+ void cancel();
+ base::OnceCallback<void(content::DesktopMediaID)> doneCallback;
+ QScopedPointer<DesktopMediaListQt> screens;
+ QScopedPointer<DesktopMediaListQt> windows;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // DESKTOP_MEDIA_CONTROLLER_P_H
diff --git a/src/core/desktop_screen_qt.cpp b/src/core/desktop_screen_qt.cpp
index 15a3856fc..fb68f7b09 100644
--- a/src/core/desktop_screen_qt.cpp
+++ b/src/core/desktop_screen_qt.cpp
@@ -1,113 +1,156 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "desktop_screen_qt.h"
#include "ui/display/display.h"
-#include "ui/gfx/geometry/point.h"
-#include <QtGlobal>
+#include "type_conversion.h"
-namespace QtWebEngineCore {
+#include <QGuiApplication>
+#include <QScreen>
-gfx::Point DesktopScreenQt::GetCursorScreenPoint()
-{
- Q_UNREACHABLE();
- return gfx::Point();
-}
+#if defined(USE_OZONE)
+#include "ui/ozone/buildflags.h"
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+#define USE_XSCREENSAVER
+#include "ui/base/x/x11_screensaver.h"
+#include "ui/base/x/x11_util.h"
+#endif
+#endif
-bool DesktopScreenQt::IsWindowUnderCursor(gfx::NativeWindow)
-{
- Q_UNREACHABLE();
- return false;
-}
+#include <cmath>
+
+namespace QtWebEngineCore {
-gfx::NativeWindow DesktopScreenQt::GetWindowAtScreenPoint(const gfx::Point& point)
+static display::Display::Rotation toDisplayRotation(Qt::ScreenOrientation orientation)
{
- Q_UNREACHABLE();
- return gfx::NativeWindow();
+ switch (orientation) {
+ case Qt::PrimaryOrientation:
+ case Qt::LandscapeOrientation:
+ return display::Display::ROTATE_0;
+ case Qt::PortraitOrientation:
+ return display::Display::ROTATE_90;
+ case Qt::InvertedLandscapeOrientation:
+ return display::Display::ROTATE_180;
+ case Qt::InvertedPortraitOrientation:
+ return display::Display::ROTATE_270;
+ }
}
-int DesktopScreenQt::GetNumDisplays() const
+display::Display toDisplayDisplay(int id, const QScreen *screen)
{
- Q_UNREACHABLE();
- return 0;
+ auto display = display::Display(id, toGfx(screen->geometry()));
+ display.set_work_area(toGfx(screen->availableGeometry()));
+ display.set_is_monochrome(screen->depth() == 1);
+ display.set_color_depth(screen->depth());
+ display.set_depth_per_component(8); // FIXME: find the real value
+ display.set_display_frequency(std::ceil(screen->refreshRate()));
+ display.set_rotation(toDisplayRotation(screen->orientation()));
+
+ // FIXME: support lower scale factor
+ float pixelRatio = screen->devicePixelRatio();
+ if (pixelRatio < 1) {
+ qWarning("Unsupported scale factor (%f) detected on Display%d", pixelRatio, id);
+ display.set_device_scale_factor(qGuiApp->devicePixelRatio());
+ } else {
+ display.set_device_scale_factor(pixelRatio);
+ }
+
+ if (screen->nativeOrientation() != Qt::PrimaryOrientation)
+ display.set_panel_rotation(toDisplayRotation(screen->nativeOrientation()));
+ return display;
}
-std::vector<display::Display>& DesktopScreenQt::GetAllDisplays() const
+DesktopScreenQt::DesktopScreenQt()
{
- static std::vector<display::Display> empty;
- return empty;
+ initializeScreens();
}
-display::Display DesktopScreenQt::GetDisplayNearestWindow(gfx::NativeWindow window) const
+DesktopScreenQt::~DesktopScreenQt()
{
- // RenderViewHostImpl::OnStartDragging uses this to determine
- // the scale factor for the view.
- return display::Display(0);
+ for (auto conn : std::as_const(m_connections))
+ QObject::disconnect(conn);
}
-display::Display DesktopScreenQt::GetDisplayNearestPoint(const gfx::Point& point) const
+void DesktopScreenQt::initializeScreens()
{
- Q_UNREACHABLE();
- return display::Display();
+ if (updateAllScreens()) {
+ m_connections[0] =
+ QObject::connect(qApp, &QGuiApplication::primaryScreenChanged, [this] (QScreen *screen) {
+ ProcessDisplayChanged(toDisplayDisplay(0, screen), true /* is_primary */);
+ });
+ // no guarantees how these will affect ids:
+ m_connections[1] =
+ QObject::connect(qApp, &QGuiApplication::screenAdded, [this] (QScreen *) {
+ updateAllScreens();
+ });
+ m_connections[2] =
+ QObject::connect(qApp, &QGuiApplication::screenRemoved, [this] (QScreen *) {
+ updateAllScreens();
+ });
+ } else {
+ // Running headless
+ ProcessDisplayChanged(display::Display::GetDefaultDisplay(), true /* is_primary */);
+ m_connections[0] =
+ QObject::connect(qApp, &QGuiApplication::screenAdded, [this] (QScreen *) {
+ display_list().RemoveDisplay(display::kDefaultDisplayId);
+ QObject::disconnect(m_connections[0]);
+ initializeScreens();
+ });
+ }
}
-display::Display DesktopScreenQt::GetDisplayMatching(const gfx::Rect& match_rect) const
+bool DesktopScreenQt::updateAllScreens()
{
- Q_UNREACHABLE();
- return display::Display();
+ Q_ASSERT(qApp->primaryScreen() == qApp->screens().first());
+ const auto screens = qApp->screens();
+ const int oldLen = GetNumDisplays();
+ for (int i = screens.length(); i < oldLen; ++i)
+ display_list().RemoveDisplay(i);
+ for (int i = 0; i < screens.length(); ++i)
+ ProcessDisplayChanged(toDisplayDisplay(i, screens.at(i)), i == 0 /* is_primary */);
+
+ return screens.length() > 0;
}
-display::Display DesktopScreenQt::GetPrimaryDisplay() const
+display::Display DesktopScreenQt::GetDisplayNearestWindow(gfx::NativeWindow /*window*/) const
{
- return display::Display(0);
+ return GetPrimaryDisplay();
}
-void DesktopScreenQt::AddObserver(display::DisplayObserver* observer)
+#if defined(USE_XSCREENSAVER)
+class XScreenSuspender : public display::Screen::ScreenSaverSuspender
{
- Q_UNREACHABLE();
+public:
+ XScreenSuspender()
+ {
+ ui::SuspendX11ScreenSaver(true);
+ }
+ ~XScreenSuspender() override
+ {
+ ui::SuspendX11ScreenSaver(false);
+ }
+};
+#endif
+#if BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_LINUX)
+std::unique_ptr<display::Screen::ScreenSaverSuspender> DesktopScreenQt::SuspendScreenSaver()
+{
+#if defined(USE_XSCREENSAVER)
+ return std::make_unique<XScreenSuspender>();
+#else
+ return nullptr;
+#endif
}
+#endif
-void DesktopScreenQt::RemoveObserver(display::DisplayObserver* observer)
+bool DesktopScreenQt::IsScreenSaverActive() const
{
- Q_UNREACHABLE();
+#if defined(USE_XSCREENSAVER)
+ return ui::IsXScreensaverActive();
+#else
+ return false;
+#endif
}
} // namespace QtWebEngineCore
diff --git a/src/core/desktop_screen_qt.h b/src/core/desktop_screen_qt.h
index 0c52c615a..a322c4840 100644
--- a/src/core/desktop_screen_qt.h
+++ b/src/core/desktop_screen_qt.h
@@ -1,63 +1,31 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DESKTOP_SCREEN_QT_H
#define DESKTOP_SCREEN_QT_H
-#include "ui/display/screen.h"
+#include "ui/display/screen_base.h"
+
+#include <qmetaobject.h>
namespace QtWebEngineCore {
-class DesktopScreenQt : public display::Screen {
+class DesktopScreenQt : public display::ScreenBase
+{
public:
- // Overridden from gfx::Screen:
- gfx::Point GetCursorScreenPoint() override;
- bool IsWindowUnderCursor(gfx::NativeWindow) override;
- gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) override;
- int GetNumDisplays() const override;
- std::vector<display::Display>& GetAllDisplays() const override;
- display::Display GetDisplayNearestWindow(gfx::NativeWindow window) const override;
- display::Display GetDisplayNearestPoint(const gfx::Point& point) const override;
- display::Display GetDisplayMatching(const gfx::Rect& match_rect) const override;
- display::Display GetPrimaryDisplay() const override;
- void AddObserver(display::DisplayObserver* observer) override;
- void RemoveObserver(display::DisplayObserver* observer) override;
+ DesktopScreenQt();
+ ~DesktopScreenQt() override;
+
+ display::Display GetDisplayNearestWindow(gfx::NativeWindow /*window*/) const override;
+#if BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_LINUX)
+ std::unique_ptr<ScreenSaverSuspender> SuspendScreenSaver() override;
+#endif
+ bool IsScreenSaverActive() const override;
+
+private:
+ void initializeScreens();
+ bool updateAllScreens();
+ QMetaObject::Connection m_connections[3];
};
} // namespace QtWebEngineCore
diff --git a/src/core/devtools_frontend_qt.cpp b/src/core/devtools_frontend_qt.cpp
index 52d7dc669..7cea68390 100644
--- a/src/core/devtools_frontend_qt.cpp
+++ b/src/core/devtools_frontend_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on content/shell/browser/shell_devtools_frontend.cc:
// Copyright 2013 The Chromium Authors. All rights reserved.
@@ -44,151 +8,44 @@
#include "devtools_frontend_qt.h"
-#include "profile_adapter.h"
#include "profile_qt.h"
#include "web_contents_adapter.h"
+#include "web_contents_delegate_qt.h"
-#include "base/base64.h"
-#include "base/json/json_reader.h"
-#include "base/json/json_writer.h"
-#include "base/json/string_escape.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
-#include "base/values.h"
-#include "chrome/common/url_constants.h"
-#include "components/prefs/in_memory_pref_store.h"
-#include "components/prefs/json_pref_store.h"
+#include "chrome/browser/devtools/devtools_eye_dropper.h"
+#include "chrome/browser/devtools/devtools_ui_bindings.h"
+#include "chrome/common/pref_names.h"
+#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/file_url_loader.h"
+#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/navigation_controller.h"
-#include "content/public/browser/navigation_handle.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/shared_cors_origin_access_list.h"
-#include "content/public/browser/storage_partition.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/content_client.h"
-#include "content/public/common/url_constants.h"
-#include "content/public/common/url_utils.h"
-#include "ipc/ipc_channel.h"
-#include "net/http/http_response_headers.h"
-#include "net/traffic_annotation/network_traffic_annotation.h"
-#include "services/network/public/cpp/simple_url_loader.h"
-#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"
+#include "content/public/browser/page_navigator.h"
+#include "content/public/browser/site_instance.h"
+#include "url/gurl.h"
using namespace QtWebEngineCore;
namespace {
-
-std::unique_ptr<base::DictionaryValue> BuildObjectForResponse(const net::HttpResponseHeaders *rh)
-{
- auto response = std::make_unique<base::DictionaryValue>();
- response->SetInteger("statusCode", rh ? rh->response_code() : 200);
-
- auto headers = std::make_unique<base::DictionaryValue>();
- size_t iterator = 0;
- std::string name;
- std::string value;
- // TODO(caseq): this probably needs to handle duplicate header names
- // correctly by folding them.
- while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value))
- headers->SetString(name, value);
-
- response->Set("headers", std::move(headers));
- return response;
-}
+static const char kScreencastEnabled[] = "screencastEnabled";
static std::string GetFrontendURL()
{
- return "devtools://devtools/bundled/devtools_app.html";
+ return "devtools://devtools/bundled/inspector.html";
}
-
-} // namespace
+} // namespace
namespace QtWebEngineCore {
-class DevToolsFrontendQt::NetworkResourceLoader
- : public network::SimpleURLLoaderStreamConsumer {
-public:
- NetworkResourceLoader(int stream_id,
- int request_id,
- DevToolsFrontendQt *bindings,
- std::unique_ptr<network::SimpleURLLoader> loader,
- network::mojom::URLLoaderFactory *url_loader_factory)
- : stream_id_(stream_id),
- request_id_(request_id),
- bindings_(bindings),
- loader_(std::move(loader))
- {
- loader_->SetOnResponseStartedCallback(base::BindOnce(
- &NetworkResourceLoader::OnResponseStarted, base::Unretained(this)));
- loader_->DownloadAsStream(url_loader_factory, this);
- }
-
-private:
- void OnResponseStarted(const GURL &final_url,
- const network::mojom::URLResponseHead &response_head)
- {
- response_headers_ = response_head.headers;
- }
-
- void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override
- {
- base::Value chunkValue;
-
- bool encoded = !base::IsStringUTF8(chunk);
- if (encoded) {
- std::string encoded_string;
- base::Base64Encode(chunk, &encoded_string);
- chunkValue = base::Value(std::move(encoded_string));
- } else {
- chunkValue = base::Value(chunk);
- }
- base::Value id(stream_id_);
- base::Value encodedValue(encoded);
-
- bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue);
- std::move(resume).Run();
- }
-
- void OnComplete(bool success) override
- {
- Q_UNUSED(success);
- auto response = BuildObjectForResponse(response_headers_.get());
- bindings_->SendMessageAck(request_id_, response.get());
- bindings_->m_loaders.erase(bindings_->m_loaders.find(this));
- }
-
- void OnRetry(base::OnceClosure start_retry) override { NOTREACHED(); }
-
- const int stream_id_;
- const int request_id_;
- DevToolsFrontendQt *const bindings_;
- std::unique_ptr<network::SimpleURLLoader> loader_;
- scoped_refptr<net::HttpResponseHeaders> response_headers_;
-
- DISALLOW_COPY_AND_ASSIGN(NetworkResourceLoader);
-};
-
-// This constant should be in sync with
-// the constant at devtools_ui_bindings.cc.
-const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;
-
// static
-DevToolsFrontendQt *DevToolsFrontendQt::Show(QSharedPointer<WebContentsAdapter> frontendAdapter, content::WebContents *inspectedContents)
+DevToolsFrontendQt *DevToolsFrontendQt::Show(QSharedPointer<WebContentsAdapter> frontendAdapter,
+ content::WebContents *inspectedContents)
{
DCHECK(frontendAdapter);
DCHECK(inspectedContents);
if (!frontendAdapter->isInitialized()) {
- scoped_refptr<content::SiteInstance> site =
- content::SiteInstance::CreateForURL(frontendAdapter->profile(), GURL(GetFrontendURL()));
+ scoped_refptr<content::SiteInstance> site = content::SiteInstance::CreateForURL(
+ frontendAdapter->profile(), GURL(GetFrontendURL()));
frontendAdapter->initialize(site.get());
}
@@ -200,13 +57,15 @@ DevToolsFrontendQt *DevToolsFrontendQt::Show(QSharedPointer<WebContentsAdapter>
return nullptr;
}
- DevToolsFrontendQt *devtoolsFrontend = new DevToolsFrontendQt(frontendAdapter, inspectedContents);
+ DevToolsFrontendQt *devtoolsFrontend =
+ new DevToolsFrontendQt(frontendAdapter, inspectedContents);
if (contents->GetURL() == GURL(GetFrontendURL())) {
- contents->GetController().Reload(content::ReloadType::ORIGINAL_REQUEST_URL, false);
- } else {
+ contents->GetController().LoadOriginalRequestURL();
+ } else {
content::NavigationController::LoadURLParams loadParams((GURL(GetFrontendURL())));
- loadParams.transition_type = ui::PageTransitionFromInt(ui::PAGE_TRANSITION_AUTO_TOPLEVEL | ui::PAGE_TRANSITION_FROM_API);
+ loadParams.transition_type = ui::PageTransitionFromInt(ui::PAGE_TRANSITION_AUTO_TOPLEVEL
+ | ui::PAGE_TRANSITION_FROM_API);
contents->GetController().LoadURLWithParams(loadParams);
}
@@ -216,33 +75,33 @@ DevToolsFrontendQt *DevToolsFrontendQt::Show(QSharedPointer<WebContentsAdapter>
DevToolsFrontendQt::DevToolsFrontendQt(QSharedPointer<WebContentsAdapter> webContentsAdapter,
content::WebContents *inspectedContents)
: content::WebContentsObserver(webContentsAdapter->webContents())
- , m_webContentsAdapter(webContentsAdapter)
+ , m_frontendAdapter(webContentsAdapter)
, m_inspectedContents(inspectedContents)
- , m_inspect_element_at_x(-1)
- , m_inspect_element_at_y(-1)
- , m_prefStore(nullptr)
- , m_weakFactory(this)
+ , m_outermostContents(inspectedContents->GetOutermostWebContents())
+ , m_bindings(new DevToolsUIBindings(webContentsAdapter->webContents()))
{
- // We use a separate prefstore than one in ProfileQt, because that one is in-memory only, and this
- // needs to be stored or it will show introduction text on every load.
- if (webContentsAdapter->profileAdapter()->isOffTheRecord())
- m_prefStore = scoped_refptr<PersistentPrefStore>(new InMemoryPrefStore());
- else
- CreateJsonPreferences(false);
-
- m_frontendDelegate = static_cast<WebContentsDelegateQt *>(webContentsAdapter->webContents()->GetDelegate());
-}
+ // bindings take ownership over devtools
+ m_bindings->SetDelegate(this);
+ m_bindings->AttachTo(content::DevToolsAgentHost::GetOrCreateFor(m_inspectedContents));
+ auto *prefService = m_bindings->profile()->GetPrefs();
+ const auto &devtoolsPrefs = prefService->GetDict(prefs::kDevToolsPreferences);
+
+ if (!devtoolsPrefs.Find(kScreencastEnabled)) {
+ ScopedDictPrefUpdate update(prefService, prefs::kDevToolsPreferences);
+ update->Set(kScreencastEnabled, "false");
+ }
+}
DevToolsFrontendQt::~DevToolsFrontendQt()
{
- if (QSharedPointer<WebContentsAdapter> p = m_webContentsAdapter)
+ if (QSharedPointer<WebContentsAdapter> p = m_frontendAdapter)
p->setInspector(false);
}
void DevToolsFrontendQt::Activate()
{
- m_frontendDelegate->ActivateContents(web_contents());
+ web_contents()->GetDelegate()->ActivateContents(web_contents());
}
void DevToolsFrontendQt::Focus()
@@ -252,12 +111,11 @@ void DevToolsFrontendQt::Focus()
void DevToolsFrontendQt::InspectElementAt(int x, int y)
{
- if (m_agentHost)
- m_agentHost->InspectElement(m_inspectedContents->GetFocusedFrame(), x, y);
- else {
- m_inspect_element_at_x = x;
- m_inspect_element_at_y = y;
- }
+ if (!m_inspectedContents)
+ return;
+ scoped_refptr<content::DevToolsAgentHost> agent(
+ content::DevToolsAgentHost::GetOrCreateFor(m_inspectedContents));
+ agent->InspectElement(m_inspectedContents->GetFocusedFrame(), x, y);
}
void DevToolsFrontendQt::Close()
@@ -268,304 +126,96 @@ void DevToolsFrontendQt::Close()
void DevToolsFrontendQt::DisconnectFromTarget()
{
- if (!m_agentHost)
- return;
- m_agentHost->DetachClient(this);
- m_agentHost = nullptr;
+ m_bindings->Detach();
}
-void DevToolsFrontendQt::ReadyToCommitNavigation(content::NavigationHandle *navigationHandle)
+WebContentsDelegateQt *DevToolsFrontendQt::frontendDelegate() const
{
- // ShellDevToolsFrontend does this in RenderViewCreated,
- // but that doesn't work for us for some reason.
- content::RenderFrameHost *frame = navigationHandle->GetRenderFrameHost();
- if (navigationHandle->IsInMainFrame()) {
- // If the frontend for some reason goes to some place other than devtools, stop the bindings
- if (navigationHandle->GetURL() != GetFrontendURL())
- m_frontendHost.reset(nullptr);
- else
- m_frontendHost = content::DevToolsFrontendHost::Create(
- frame,
- base::Bind(&DevToolsFrontendQt::HandleMessageFromDevToolsFrontend,
- base::Unretained(this)));
- }
+ return static_cast<WebContentsDelegateQt *>(web_contents()->GetDelegate());
}
-void DevToolsFrontendQt::DocumentAvailableInMainFrame()
+void DevToolsFrontendQt::ColorPickedInEyeDropper(int r, int g, int b, int a)
{
- if (!m_inspectedContents)
- return;
- // Don't call AttachClient multiple times for the same DevToolsAgentHost.
- // Otherwise it will call AgentHostClosed which closes the DevTools window.
- // This may happen in cases where the DevTools content fails to load.
- scoped_refptr<content::DevToolsAgentHost> agent_host =
- content::DevToolsAgentHost::GetOrCreateFor(m_inspectedContents);
- if (agent_host != m_agentHost) {
- if (m_agentHost)
- m_agentHost->DetachClient(this);
- m_agentHost = agent_host;
- m_agentHost->AttachClient(this);
- if (m_inspect_element_at_x != -1) {
- m_agentHost->InspectElement(m_inspectedContents->GetFocusedFrame(), m_inspect_element_at_x, m_inspect_element_at_y);
- m_inspect_element_at_x = -1;
- m_inspect_element_at_y = -1;
- }
- }
+ base::Value::Dict color;
+ color.Set("r", r);
+ color.Set("g", g);
+ color.Set("b", b);
+ color.Set("a", a);
+ m_bindings->CallClientMethod("DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
+// content::WebContentsObserver implementation
void DevToolsFrontendQt::WebContentsDestroyed()
{
- if (m_inspectedContents)
- static_cast<WebContentsDelegateQt *>(m_inspectedContents->GetDelegate())->webContentsAdapter()->devToolsFrontendDestroyed(this);
+ // If m_inspectedContents was a guest view it was probably already destroyed,
+ // but its embedder still lives.
+ WebContentsAdapter *inspectedAdapter =
+ static_cast<WebContentsDelegateQt *>(m_outermostContents->GetDelegate())
+ ->webContentsAdapter();
+ if (inspectedAdapter)
+ inspectedAdapter->devToolsFrontendDestroyed(this);
- if (m_agentHost) {
- m_agentHost->DetachClient(this);
- m_agentHost = nullptr;
- }
- delete this;
+ delete m_bindings; // it will call ~DevToolsFrontendQt()
}
-void DevToolsFrontendQt::SetPreference(const std::string &name, const std::string &value)
+// DevToolsUIBindings::Delegate implementation
+void DevToolsFrontendQt::ActivateWindow()
{
- DCHECK(m_prefStore);
- m_prefStore->SetValue(name, base::WrapUnique(new base::Value(value)), 0);
+ web_contents()->Focus();
}
-void DevToolsFrontendQt::RemovePreference(const std::string &name)
+void DevToolsFrontendQt::OnLoadCompleted()
{
- DCHECK(m_prefStore);
- m_prefStore->RemoveValue(name, 0);
+ m_bindings->CallClientMethod("DevToolsAPI", "setUseSoftMenu", base::Value(true));
}
-void DevToolsFrontendQt::ClearPreferences()
+void DevToolsFrontendQt::OpenInNewTab(const std::string &url)
{
- if (web_contents()->GetBrowserContext()->IsOffTheRecord())
- m_prefStore = scoped_refptr<PersistentPrefStore>(new InMemoryPrefStore());
- else
- CreateJsonPreferences(true);
-}
+ content::OpenURLParams params(GURL(url), content::Referrer(),
+ WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui::PAGE_TRANSITION_LINK, false);
-void DevToolsFrontendQt::CreateJsonPreferences(bool clear)
-{
- content::BrowserContext *browserContext = web_contents()->GetBrowserContext();
- DCHECK(!browserContext->IsOffTheRecord());
- JsonPrefStore *jsonPrefStore = new JsonPrefStore(
- browserContext->GetPath().Append(FILE_PATH_LITERAL("devtoolsprefs.json")));
- // We effectively clear the preferences by not calling ReadPrefs
- if (!clear)
- jsonPrefStore->ReadPrefs();
-
- m_prefStore = scoped_refptr<PersistentPrefStore>(jsonPrefStore);
+ m_inspectedContents->OpenURL(params);
}
-void DevToolsFrontendQt::HandleMessageFromDevToolsFrontend(const std::string &message)
+void DevToolsFrontendQt::SetEyeDropperActive(bool active)
{
- if (!m_agentHost)
- return;
- std::string method;
- base::ListValue *params = nullptr;
- base::DictionaryValue *dict = nullptr;
- std::unique_ptr<base::Value> parsed_message = base::JSONReader::ReadDeprecated(message);
- if (!parsed_message || !parsed_message->GetAsDictionary(&dict) || !dict->GetString("method", &method))
- return;
- int request_id = 0;
- dict->GetInteger("id", &request_id);
- dict->GetList("params", &params);
-
- if (method == "dispatchProtocolMessage" && params && params->GetSize() == 1) {
- std::string protocol_message;
- if (!params->GetString(0, &protocol_message))
- return;
- m_agentHost->DispatchProtocolMessage(this, protocol_message);
- } else if (method == "loadCompleted") {
- web_contents()->GetMainFrame()->ExecuteJavaScript(base::ASCIIToUTF16("DevToolsAPI.setUseSoftMenu(true);"),
- base::NullCallback());
- } else if (method == "loadNetworkResource" && params->GetSize() == 3) {
- // TODO(pfeldman): handle some of the embedder messages in content.
- std::string url;
- std::string headers;
- int stream_id;
- if (!params->GetString(0, &url) || !params->GetString(1, &headers) || !params->GetInteger(2, &stream_id))
- return;
-
- GURL gurl(url);
- if (!gurl.is_valid()) {
- base::DictionaryValue response;
- response.SetInteger("statusCode", 404);
- SendMessageAck(request_id, &response);
- return;
- }
-
- net::NetworkTrafficAnnotationTag traffic_annotation =
- net::DefineNetworkTrafficAnnotation(
- "devtools_handle_front_end_messages", R"(
- semantics {
- sender: "Developer Tools"
- description:
- "When user opens Developer Tools, the browser may fetch "
- "additional resources from the network to enrich the debugging "
- "experience (e.g. source map resources)."
- trigger: "User opens Developer Tools to debug a web page."
- data: "Any resources requested by Developer Tools."
- destination: OTHER
- }
- policy {
- cookies_allowed: YES
- cookies_store: "user"
- setting:
- "It's not possible to disable this feature from settings."
- chrome_policy {
- DeveloperToolsAvailability {
- policy_options {mode: MANDATORY}
- DeveloperToolsAvailability: 2
- }
- }
- })");
- auto resource_request = std::make_unique<network::ResourceRequest>();
- resource_request->url = gurl;
- // TODO(caseq): this preserves behavior of URLFetcher-based implementation.
- // We really need to pass proper first party origin from the front-end.
- resource_request->site_for_cookies = gurl;
- resource_request->headers.AddHeadersFromString(headers);
-
- std::unique_ptr<network::mojom::URLLoaderFactory> file_url_loader_factory;
- scoped_refptr<network::SharedURLLoaderFactory> network_url_loader_factory;
- network::mojom::URLLoaderFactory *url_loader_factory;
- if (gurl.SchemeIsFile()) {
- file_url_loader_factory = content::CreateFileURLLoaderFactory(base::FilePath(), nullptr);
- url_loader_factory = file_url_loader_factory.get();
- } else if (content::HasWebUIScheme(gurl)) {
- base::DictionaryValue response;
- response.SetInteger("statusCode", 403);
- SendMessageAck(request_id, &response);
- return;
- } else {
- auto *partition = content::BrowserContext::GetStoragePartitionForSite(
- web_contents()->GetBrowserContext(), gurl);
- network_url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess();
- url_loader_factory = network_url_loader_factory.get();
- }
- auto simple_url_loader = network::SimpleURLLoader::Create(
- std::move(resource_request), traffic_annotation);
- auto resource_loader = std::make_unique<NetworkResourceLoader>(
- stream_id, request_id, this, std::move(simple_url_loader),
- url_loader_factory);
- m_loaders.insert(std::move(resource_loader));
- return;
- } else if (method == "getPreferences") {
- m_preferences = std::move(*m_prefStore->GetValues());
- SendMessageAck(request_id, &m_preferences);
+ if (!m_inspectedContents)
return;
- } else if (method == "setPreference") {
- std::string name;
- std::string value;
- if (!params->GetString(0, &name) || !params->GetString(1, &value))
- return;
- SetPreference(name, value);
- } else if (method == "removePreference") {
- std::string name;
- if (!params->GetString(0, &name))
- return;
- RemovePreference(name);
- } else if (method == "clearPreferences") {
- ClearPreferences();
- } else if (method == "requestFileSystems") {
- web_contents()->GetMainFrame()->ExecuteJavaScript(base::ASCIIToUTF16("DevToolsAPI.fileSystemsLoaded([]);"),
- base::NullCallback());
- } else if (method == "reattach") {
- m_agentHost->DetachClient(this);
- m_agentHost->AttachClient(this);
- } else if (method == "openInNewTab") {
- std::string urlString;
- if (!params->GetString(0, &urlString))
- return;
- GURL url(urlString);
- if (!url.is_valid())
- return;
- content::OpenURLParams openParams(GURL(url),
- content::Referrer(),
- WindowOpenDisposition::NEW_FOREGROUND_TAB,
- ui::PAGE_TRANSITION_LINK,
- false);
- // OpenURL will (via WebContentsDelegateQt::OpenURLFromTab) call
- // application code, which may decide to close this devtools view (see
- // quicknanobrowser for example).
- //
- // Chromium always calls SendMessageAck through a callback bound to a
- // WeakPtr, we do the same here, except without the callback.
- base::WeakPtr<DevToolsFrontendQt> weakThis = m_weakFactory.GetWeakPtr();
- web_contents()->OpenURL(openParams);
- if (!weakThis)
- return;
- } else if (method == "bringToFront") {
- Activate();
+ if (active) {
+ m_eyeDropper.reset(new DevToolsEyeDropper(
+ m_inspectedContents,
+ base::BindRepeating(&DevToolsFrontendQt::ColorPickedInEyeDropper,
+ base::Unretained(this))));
} else {
- VLOG(1) << "Unimplemented devtools method: " << message;
- return;
+ m_eyeDropper.reset();
}
-
- if (request_id)
- SendMessageAck(request_id, nullptr);
}
-void DevToolsFrontendQt::DispatchProtocolMessage(content::DevToolsAgentHost *agentHost, const std::string &message)
+// static
+bool DevToolsFrontendQt::IsValidFrontendURL(const GURL &url)
{
- Q_UNUSED(agentHost);
- if (message.length() < kMaxMessageChunkSize) {
- std::string param;
- base::EscapeJSONString(message, true, &param);
- std::string code = "DevToolsAPI.dispatchMessage(" + param + ");";
- base::string16 javascript = base::UTF8ToUTF16(code);
- web_contents()->GetMainFrame()->ExecuteJavaScript(javascript, base::NullCallback());
- return;
- }
-
- size_t total_size = message.length();
- for (size_t pos = 0; pos < message.length(); pos += kMaxMessageChunkSize) {
- std::string param;
- base::EscapeJSONString(message.substr(pos, kMaxMessageChunkSize), true, &param);
- std::string code = "DevToolsAPI.dispatchMessageChunk(" + param + ","
- + std::to_string(pos ? 0 : total_size) + ");";
- base::string16 javascript = base::UTF8ToUTF16(code);
- web_contents()->GetMainFrame()->ExecuteJavaScript(javascript, base::NullCallback());
- }
+ // NOTE: the inspector app does not change the frontend url.
+ // If we bring back the devtools_app, the url must be sanitized
+ // according to chrome/browser/devtools/devtools_ui_bindings.cc.
+ return url.spec() == GetFrontendURL();
}
-void DevToolsFrontendQt::CallClientFunction(const std::string &function_name,
- const base::Value *arg1,
- const base::Value *arg2,
- const base::Value *arg3)
+void DevToolsFrontendQt::InspectedContentsClosing()
{
- std::string javascript = function_name + "(";
- if (arg1) {
- std::string json;
- base::JSONWriter::Write(*arg1, &json);
- javascript.append(json);
- if (arg2) {
- base::JSONWriter::Write(*arg2, &json);
- javascript.append(", ").append(json);
- if (arg3) {
- base::JSONWriter::Write(*arg3, &json);
- javascript.append(", ").append(json);
- }
- }
- }
- javascript.append(");");
- web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(javascript), base::NullCallback());
+ // Called for already destroyed guest views
+ m_inspectedContents = nullptr;
+ web_contents()->ClosePage();
}
-void DevToolsFrontendQt::SendMessageAck(int request_id, const base::Value *arg)
+std::string DevToolsFrontendQt::GetId(content::WebContents *inspectedContents)
{
- base::Value id_value(request_id);
- CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr);
+ return content::DevToolsAgentHost::GetOrCreateFor(inspectedContents)->GetId();
}
-void DevToolsFrontendQt::AgentHostClosed(content::DevToolsAgentHost *agentHost)
+void DevToolsFrontendQt::CloseWindow()
{
- DCHECK(agentHost == m_agentHost.get());
- m_agentHost = nullptr;
- m_inspectedContents = nullptr;
- Close();
+ web_contents()->Close();
}
} // namespace QtWebEngineCore
diff --git a/src/core/devtools_frontend_qt.h b/src/core/devtools_frontend_qt.h
index fed2d47fc..b867d4af1 100644
--- a/src/core/devtools_frontend_qt.h
+++ b/src/core/devtools_frontend_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DEVTOOLS_FRONTEND_QT_H
#define DEVTOOLS_FRONTEND_QT_H
@@ -45,34 +9,26 @@
#include "web_contents_delegate_qt.h"
-#include "base/compiler_specific.h"
#include "base/containers/unique_ptr_adapters.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
-#include "base/values.h"
-#include "content/public/browser/devtools_agent_host.h"
-#include "content/public/browser/devtools_frontend_host.h"
+#include "chrome/browser/devtools/devtools_ui_bindings.h"
#include "content/public/browser/web_contents_observer.h"
-namespace base {
-class Value;
-}
+class DevToolsEyeDropper;
namespace content {
-class NavigationHandle;
-class RenderViewHost;
+class DevToolsAgentHost;
class WebContents;
-} // namespace content
-
-class PersistentPrefStore;
+} // namespace content
namespace QtWebEngineCore {
+class WebContentsAdapter;
-class DevToolsFrontendQt : public content::WebContentsObserver
- , public content::DevToolsAgentHostClient {
+class DevToolsFrontendQt : public DevToolsUIBindings::Delegate, public content::WebContentsObserver
+{
public:
- static DevToolsFrontendQt *Show(QSharedPointer<WebContentsAdapter> frontendAdapter, content::WebContents *inspectedContents);
+ static DevToolsFrontendQt *Show(QSharedPointer<WebContentsAdapter> frontendAdapter,
+ content::WebContents *inspectedContents);
void Activate();
void Focus();
@@ -81,58 +37,50 @@ public:
void DisconnectFromTarget();
- void CallClientFunction(const std::string& function_name,
- const base::Value* arg1,
- const base::Value* arg2,
- const base::Value* arg3);
+ WebContentsDelegateQt *frontendDelegate() const;
- WebContentsDelegateQt *frontendDelegate() const
- {
- return m_frontendDelegate;
- }
+ static bool IsValidFrontendURL(const GURL &url);
+ static std::string GetId(content::WebContents *inspectedContents);
protected:
- DevToolsFrontendQt(QSharedPointer<WebContentsAdapter> webContentsAdapter, content::WebContents *inspectedContents);
+ DevToolsFrontendQt(QSharedPointer<WebContentsAdapter> webContentsAdapter,
+ content::WebContents *inspectedContents);
~DevToolsFrontendQt() override;
- // content::DevToolsAgentHostClient implementation.
- void AgentHostClosed(content::DevToolsAgentHost* agent_host) override;
- void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, const std::string& message) override;
-
- void SetPreferences(const std::string& json);
- virtual void HandleMessageFromDevToolsFrontend(const std::string& message);
-
private:
- // WebContentsObserver overrides
- void ReadyToCommitNavigation(content::NavigationHandle* navigation_handle) override;
- void DocumentAvailableInMainFrame() override;
+ void ColorPickedInEyeDropper(int r, int g, int b, int a);
+
+ // content::WebContentsObserver overrides
void WebContentsDestroyed() override;
- void SendMessageAck(int request_id, const base::Value* arg1);
- void SetPreference(const std::string &name, const std::string &value);
- void RemovePreference(const std::string &name);
- void ClearPreferences();
- void CreateJsonPreferences(bool clear);
+ // DevToolsUIBindings::Delegate overrides
+ void ActivateWindow() override;
+ void SetEyeDropperActive(bool active) override;
+ void OpenInNewTab(const std::string &url) override;
+ void InspectedContentsClosing() override;
+ void OnLoadCompleted() override;
+
+ void InspectElementCompleted() override{};
+ void CloseWindow() override;
+ void Inspect(scoped_refptr<content::DevToolsAgentHost>) override{};
+ void SetInspectedPageBounds(const gfx::Rect &) override{};
+ void SetIsDocked(bool) override{};
+ void SetWhitelistedShortcuts(const std::string &) override{};
+ void OpenNodeFrontend() override{};
+ void ReadyForTest() override{};
+ void ConnectionReady() override{};
+ void SetOpenNewWindowForPopups(bool) override{};
+ void RenderProcessGone(bool) override{};
+ void ShowCertificateViewer(const std::string &) override{};
// We shouldn't be keeping it alive
- QWeakPointer<WebContentsAdapter> m_webContentsAdapter;
- WebContentsDelegateQt *m_frontendDelegate;
+ QWeakPointer<WebContentsAdapter> m_frontendAdapter;
content::WebContents *m_inspectedContents;
- scoped_refptr<content::DevToolsAgentHost> m_agentHost;
- int m_inspect_element_at_x;
- int m_inspect_element_at_y;
- std::unique_ptr<content::DevToolsFrontendHost> m_frontendHost;
-
- class NetworkResourceLoader;
- std::set<std::unique_ptr<NetworkResourceLoader>, base::UniquePtrComparator> m_loaders;
-
- base::DictionaryValue m_preferences;
- scoped_refptr<PersistentPrefStore> m_prefStore;
- base::WeakPtrFactory<DevToolsFrontendQt> m_weakFactory;
-
- DISALLOW_COPY_AND_ASSIGN(DevToolsFrontendQt);
+ content::WebContents *m_outermostContents;
+ std::unique_ptr<DevToolsEyeDropper> m_eyeDropper;
+ DevToolsUIBindings *m_bindings;
};
} // namespace QtWebEngineCore
-#endif // DEVTOOLS_FRONTEND_QT_H
+#endif // DEVTOOLS_FRONTEND_QT_H
diff --git a/src/core/devtools_manager_delegate_qt.cpp b/src/core/devtools_manager_delegate_qt.cpp
index ecd2a7d40..6654ead0e 100644
--- a/src/core/devtools_manager_delegate_qt.cpp
+++ b/src/core/devtools_manager_delegate_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on content/shell/browser/shell_devtools_manager_delegate.cc:
// Copyright 2013 The Chromium Authors. All rights reserved.
@@ -43,31 +7,19 @@
// found in the LICENSE.Chromium file.
#include "devtools_manager_delegate_qt.h"
+#include "qtwebengine/grit/qt_webengine_resources.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
#include "content/browser/devtools/devtools_http_handler.h"
#include "content/public/browser/devtools_agent_host.h"
-#include "content/public/browser/devtools_frontend_host.h"
#include "content/public/browser/devtools_socket_factory.h"
-#include "content/public/browser/favicon_status.h"
-#include "content/public/browser/navigation_entry.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/content_switches.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/socket/tcp_server_socket.h"
#include "ui/base/resource/resource_bundle.h"
-#include "qtwebengine/grit/qt_webengine_resources.h"
-
-#include "type_conversion.h"
-
using content::DevToolsAgentHost;
namespace {
@@ -93,7 +45,6 @@ private:
const std::string m_address;
int m_port;
int m_backlog;
- DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory);
};
} // namespace
@@ -114,7 +65,7 @@ DevToolsServerQt::~DevToolsServerQt()
void DevToolsServerQt::parseAddressAndPort()
{
- const QString inspectorEnv = QString::fromUtf8(qgetenv("QTWEBENGINE_REMOTE_DEBUGGING"));
+ const QString inspectorEnv = qEnvironmentVariable("QTWEBENGINE_REMOTE_DEBUGGING");
const base::CommandLine &commandLine = *base::CommandLine::ForCurrentProcess();
QString portStr;
@@ -181,7 +132,7 @@ void DevToolsManagerDelegateQt::Initialized(const net::IPEndPoint *ip_address)
std::string DevToolsManagerDelegateQt::GetDiscoveryPageHTML()
{
- return ui::ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_DEVTOOLS_DISCOVERY_PAGE_HTML).as_string();
+ return ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_DEVTOOLS_DISCOVERY_PAGE_HTML);
}
bool DevToolsManagerDelegateQt::HasBundledFrontendResources()
@@ -189,4 +140,4 @@ bool DevToolsManagerDelegateQt::HasBundledFrontendResources()
return true;
}
-} //namespace QtWebEngineCore
+} // namespace QtWebEngineCore
diff --git a/src/core/devtools_manager_delegate_qt.h b/src/core/devtools_manager_delegate_qt.h
index 3a519a03f..6e02b04a4 100644
--- a/src/core/devtools_manager_delegate_qt.h
+++ b/src/core/devtools_manager_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DEV_TOOLS_HTTP_HANDLER_DELEGATE_QT_H
#define DEV_TOOLS_HTTP_HANDLER_DELEGATE_QT_H
diff --git a/src/core/doc/QtWebEngineDoc b/src/core/doc/QtWebEngineDoc
new file mode 100644
index 000000000..7ab3164fd
--- /dev/null
+++ b/src/core/doc/QtWebEngineDoc
@@ -0,0 +1,3 @@
+#include <QtWebEngineCore/QtWebEngineCore>
+#include <QtWebEngineQuick/QtWebEngineQuick>
+#include <QtWebEngineWidgets/QtWebEngineWidgets>
diff --git a/src/core/doc/about_credits.tmpl b/src/core/doc/about_credits.tmpl
new file mode 100644
index 000000000..57fae9e78
--- /dev/null
+++ b/src/core/doc/about_credits.tmpl
@@ -0,0 +1 @@
+{{entries}}
diff --git a/src/core/doc/about_credits_entry.tmpl b/src/core/doc/about_credits_entry.tmpl
new file mode 100644
index 000000000..aa94f2945
--- /dev/null
+++ b/src/core/doc/about_credits_entry.tmpl
@@ -0,0 +1,13 @@
+/*!
+\page qtwebengine-3rdparty-{{name-sanitized}}.html
+\attribution
+\ingroup qtwebengine-licensing
+\brief {{license-type}}
+\title {{name}}
+
+\l{{{url}}}{Project Homepage}
+
+\badcode
+{{license}}
+\endcode
+*/
diff --git a/src/core/doc/qtwebengine.qdocconf b/src/core/doc/qtwebengine.qdocconf
new file mode 100644
index 000000000..6b78f13f8
--- /dev/null
+++ b/src/core/doc/qtwebengine.qdocconf
@@ -0,0 +1,96 @@
+include($QT_INSTALL_DOCS/global/qt-module-defaults.qdocconf)
+include($QT_INSTALL_DOCS/config/exampleurl-qtwebengine.qdocconf)
+
+project = QtWebEngine
+description = Qt WebEngine Reference Documentation
+version = $QT_VERSION
+
+qhp.projects = QtWebEngine
+
+qhp.QtWebEngine.file = qtwebengine.qhp
+qhp.QtWebEngine.namespace = org.qt-project.qtwebengine.$QT_VERSION_TAG
+qhp.QtWebEngine.virtualFolder = qtwebengine
+qhp.QtWebEngine.indexTitle = Qt WebEngine
+qhp.QtWebEngine.indexRoot =
+
+qhp.QtWebEngine.subprojects = classes qmltypes examples
+
+qhp.QtWebEngine.subprojects.classes.title = C++ Classes and Namespaces
+qhp.QtWebEngine.subprojects.classes.indexTitle = Qt WebEngine C++ Classes and Namespaces
+qhp.QtWebEngine.subprojects.classes.selectors = class group:qtwebengine-namespaces doc:headerfile
+qhp.QtWebEngine.subprojects.classes.sortPages = true
+
+qhp.QtWebEngine.subprojects.qmltypes.title = QML Types
+qhp.QtWebEngine.subprojects.qmltypes.indexTitle = Qt WebEngine QML Types
+qhp.QtWebEngine.subprojects.qmltypes.selectors = qmltype
+qhp.QtWebEngine.subprojects.qmltypes.sortPages = true
+
+qhp.QtWebEngine.subprojects.examples.title = Examples
+qhp.QtWebEngine.subprojects.examples.indexTitle = Qt WebEngine Examples
+qhp.QtWebEngine.subprojects.examples.selectors = doc:example
+qhp.QtWebEngine.subprojects.examples.sortPages = true
+
+manifestmeta.highlighted.names += "QtWebEngine/WebEngine Widgets Simple Browser Example" \
+ "QtWebEngine/WebEngine Quick Nano Browser" \
+ "QtWebEngine/Recipe Browser"
+
+tagfile = ../../../doc/qtwebengine/qtwebengine.tags
+
+# Custom module header for clang that pulls in also QtWebEngineWidgets
+moduleheader = QtWebEngineDoc
+
+# Additional include paths for clang
+includepaths += -I .
+
+depends += qtcore \
+ qtcore5compat \
+ qtdesigner \
+ qtgui \
+ qtnetwork \
+ qtprintsupport \
+ qtpositioning \
+ qtqml \
+ qtqmlmodels \
+ qtquick \
+ qtquickcontrols \
+ qtdoc \
+ qtcmake \
+ qtwebchannel \
+ qtwebview \
+ qtwidgets
+
+headerdirs += ../../core/api \
+ ../../webenginequick/api \
+ ../../webenginewidgets/api
+
+sourcedirs += ../../core/api \
+ ../../core/doc \
+ ../../webenginequick/api \
+ ../../webenginequick/doc \
+ ../../webenginewidgets/api \
+ ../../webenginewidgets/doc
+
+exampledirs += ../../../examples \
+ ../../core/doc/snippets \
+ ../../webenginequick/doc/snippets \
+ ../../webenginewidgets/doc/snippets
+
+#exclude Qt PDF example directories
+excludedirs += ../../../examples/pdfwidgets \
+ ../../../examples/pdf
+
+examples.fileextensions += *.aff *.dic *.html
+
+imagedirs += \
+ images \
+ ../../webenginequick/doc/images
+
+navigation.landingpage = "Qt WebEngine"
+navigation.cppclassespage = "Qt WebEngine C++ Classes and Namespaces"
+navigation.qmltypespage = "Qt WebEngine QML Types"
+
+# \QWE macro expands to 'Qt WebEngine' without auto-linking anywhere.
+macro.QWE = "Qt \\WebEngine"
+
+# Enforce zero documentation warnings
+warninglimit = 0
diff --git a/src/core/doc/snippets/qtwebengine_qwebenginepage_snippet.cpp b/src/core/doc/snippets/qtwebengine_qwebenginepage_snippet.cpp
new file mode 100644
index 000000000..6b39eed03
--- /dev/null
+++ b/src/core/doc/snippets/qtwebengine_qwebenginepage_snippet.cpp
@@ -0,0 +1,14 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+void wrapInFunction()
+{
+
+//! [0]
+ m_view->page()->findText(QStringLiteral("Qt"), QWebEnginePage::FindFlags(), [this](const QWebEngineFindTextResult &result) {
+ if (result.numberOfMatches() == 0) QMessageBox::information(m_view, QString(), QStringLiteral("No occurrences found"));
+ });
+//! [0]
+
+}
+
diff --git a/src/core/doc/snippets/qtwebenginecore_build_snippet.qdoc b/src/core/doc/snippets/qtwebenginecore_build_snippet.qdoc
index 94e26c9c5..9a7370d62 100644
--- a/src/core/doc/snippets/qtwebenginecore_build_snippet.qdoc
+++ b/src/core/doc/snippets/qtwebenginecore_build_snippet.qdoc
@@ -1,35 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
//! [0]
QT += webenginecore
//! [0]
-
-//! [1]
-#include <QtWebEngineCore>
-//! [1]
+//! [2]
+find_package(Qt6 REQUIRED COMPONENTS WebEngineCore)
+target_link_libraries(target PRIVATE Qt6::WebEngineCore)
+//! [2]
diff --git a/src/core/doc/src/external-resources.qdoc b/src/core/doc/src/external-resources.qdoc
new file mode 100644
index 000000000..775492c7e
--- /dev/null
+++ b/src/core/doc/src/external-resources.qdoc
@@ -0,0 +1,138 @@
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \externalpage http://www.chromium.org
+ \title Chromium Project
+*/
+
+/*!
+ \externalpage https://developers.google.com/web/tools/chrome-devtools
+ \title Chrome DevTools
+*/
+
+/*!
+ \externalpage https://developer.chrome.com/docs/devtools/console/
+ \title Chrome console API
+*/
+
+/*!
+ \externalpage http://ffmpeg.org/
+ \title FFmpeg
+*/
+
+/*!
+ \externalpage http://www.openh264.org/
+ \title OpenH264 Project Homepage
+*/
+
+/*!
+ \externalpage http://html5demos.com/drag
+ \title HTML5 Demos - Drag and Drop
+*/
+
+/*!
+ \externalpage http://html5demos.com/drag-anything
+ \title HTML5 Demos - Simple Drag and Drop
+*/
+
+/*!
+ \externalpage http://html5demos.com/dnd-upload
+ \title HTML5 Demos - Drag and Drop, Automatic Upload
+*/
+
+/*!
+ \externalpage http://html5demos.com/file-api
+ \title HTML5 Demos - File API
+*/
+
+/*!
+ \externalpage http://www.widevine.com
+ \title Widevine CDM
+*/
+
+/*!
+ \externalpage http://demo.castlabs.com/
+ \title castLabs
+*/
+
+/*!
+ \externalpage http://ssdemo04.swankmp.net/
+ \title Swank Motion Pictures, Inc.
+*/
+
+/*!
+ \externalpage https://bitmovin.com/demos/drm
+ \title Bitmovin Player
+*/
+
+/*!
+ \externalpage https://sourceforge.net/projects/hunspell/
+ \title Hunspell Project
+*/
+
+/*!
+ \externalpage https://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
+ \title RFC 2616 section 19.5.1
+*/
+
+/*!
+ \externalpage https://www.iana.org/assignments/uri-schemes/prov/view-source
+ \title view-source URI scheme
+*/
+
+/*!
+ \externalpage https://wiki.greasespot.net/Metadata_Block
+ \title Greasemonkey
+*/
+
+/*!
+ \externalpage https://http2.github.io/
+ \title HTTP/2
+*/
+
+/*!
+ \externalpage https://http2.akamai.com/demo
+ \title Akamai HTTP/2 Demo
+*/
+
+/*!
+ \externalpage https://www.chromium.org/developers/design-documents/user-scripts
+ \title User Scripts
+*/
+
+/*!
+ \externalpage https://wiki.greasespot.net/Metadata_Block#.40name
+ \title Metadata Block
+*/
+
+/*!
+ \externalpage https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler
+ \title registerProtocolHandler
+*/
+
+/*!
+ \externalpage https://www.w3.org/TR/notifications
+ \title Web Notifications API
+*/
+
+/*!
+ \externalpage https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
+ \title Autoplay Policy Changes
+*/
+
+// Workarounds for broken links introduced by README.chromium license files
+/*!
+ \externalpage #
+ \title This is the canonical public repository
+*/
+
+/*!
+ \externalpage #
+ \title NA
+*/
+
+/*!
+ \externalpage https://source.chromium.org/chromium/chromium/src/+/master:v8/src/base/ieee754.cc
+ \title source.chromium.org/chromium/chromium/src/+/master:v8/src/base/ieee754.cc
+*/
diff --git a/src/core/doc/src/qt6-changes.qdoc b/src/core/doc/src/qt6-changes.qdoc
new file mode 100644
index 000000000..5061c77ab
--- /dev/null
+++ b/src/core/doc/src/qt6-changes.qdoc
@@ -0,0 +1,131 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-changes-qt6.html
+ \title Changes to Qt WebEngine
+ \ingroup changes-qt-5-to-6
+ \brief Migrate Qt WebEngine to Qt 6.
+
+ Qt 6 is a result of the conscious effort to make the framework more
+ efficient and easy to use.
+
+ We try to maintain binary and source compatibility for all the public
+ APIs in each release. But some changes were inevitable in an effort to
+ make Qt a better framework
+
+ In this topic we summarize those changes in Qt WebEngine, and provide guidance
+ to handle them.
+
+ \section1 Moved Classes
+
+ \section2 The Qt WebEngine module
+ Has been renamed to the Qt WebEngineQuick module to not collide with the name of
+ the super module, and to be consistent with other Quick modules.
+
+ If you port your Qt Quick application, please remember to use the new module
+ name in your qmake project file.
+
+ \code
+ QT += webenginequick
+ \endcode
+
+ \section2 Classes moved from Qt WebEngineWidgets to Qt WebEngineCore
+ Several classes have been moved from Qt WebEngineWidgets to Qt WebEngineCore if they
+ did not use the Widgets module. In most cases this change should be source compatible unless
+ you included the module name in the include header, in which case you need to update your
+ includes.
+
+ \section3 Classes moved with minimal changes
+ \list
+ \li QWebEngineHistory
+ \li QWebEngineProfile
+ \li QWebEngineScript
+ \li QWebEngineScriptCollection
+ \li QWebEngineClientCertificateSelection
+ \li QWebEngineSettings
+ \li QWebEngineFullScreenRequest
+ \endlist
+
+ \section3 QWebEngineCertificateError
+ Has been unified between QML and C++ versions, so both are now accepted or rejected via methods
+ on the class.
+
+ \section3 QWebEngineContextMenuData
+ Has been moved to Core and renamed QWebEngineContextMenuRequest.
+
+ \section3 QWebEngineDownloadItem
+ Has been moved to Core and renamed QWebEngineDownloadRequest.
+
+ \section3 QWebEnginePage
+ Has been moved to Core, and API that worked on QWebEngineView or QPrinter has been moved, and can now
+ be accessed only from QWebEngineView. See Changed API.
+
+ \section2 Classes moved from Qt WebEngineQuick to Qt WebEngineCore
+
+ \section3 WebEngineNavigationRequest
+ Is now QWebEngineNavigationRequest, and accessible from C++ API as well, adding a more
+ informative variant of QWebEnginePage::acceptNavigationRequest().
+
+ \section3 WebEngineNewViewRequest
+ Is now WebEngineNewWindowRequest and QWebEngineNewWindowRequest, and accessible from C++ API as well,
+ adding a more informative variant of QWebEnginePage::createWindow().
+
+
+ \section1 Changed API
+
+ \section2 C++
+
+ \section3 QWebEnginePage::certificateError()
+ Is now a signal instead of a derived method. The errors are either accepted or rejected
+ via methods on the QWebEngineCertificateError class.
+
+ \section3 QWebEnginePage::print()
+ Has been moved to QWebEngineView::print() and no longer takes a callback argument but
+ signals finished with QWebEngineView::printFinished() instead. It was never possible
+ to have two active print jobs at the same time.
+
+ \section3 QWebEnginePage::view()
+ Has been removed as QWebEnginePage and QWebEngineView are now in different modules. The view
+ associated with a page can be accessed using the static helper QWebEngineView::forPage().
+
+ \section3 QWebEngineProfile::defaultProfile()
+ Has been removed. The default profile is now an off-the-record profile, and only used if a
+ QWebEnginePage is created without an explicit profile. To maintain Qt 5 like behavior, create
+ a global profile called "Default" and use it when creating every QWebEnginePage.
+
+ \section2 QML
+
+ \section3 WebEngineNavigationRequest
+ The navigation requests are now accepted or rejected like other request objects using accept()
+ or reject() methods.
+
+ \section3 WebEngineNewViewRequest
+ Has been renamed WebEngineNewWindowRequest.
+
+ \section1 Changed Behavior
+
+ \section2 Default Profile
+ The default profile is now \e{off the record}. To have a standard browser profile with
+ disk-cache and cookies, we recommend creating your own profile and using that explicitly.
+
+ \section2 QRC Scheme
+ Can no longer be accessed from custom schemes by default, nor can it access local content
+ directly. If the Qt 5 behavior is needed, it can be restored by registering the qrc scheme
+ like a custom URL scheme, and setting the CorsEnabled and LocalAccessAllowed access flags.
+ \code
+ QWebEngineUrlScheme qrcScheme(QByteArrayLiteral("qrc"));
+ qrcScheme.setFlags(QWebEngineUrlScheme::SecureScheme
+ | QWebEngineUrlScheme::LocalAccessAllowed
+ | QWebEngineUrlScheme::CorsEnabled
+ | QWebEngineUrlScheme::ViewSourceAllowed);
+ QWebEngineUrlScheme::registerScheme(qrcScheme);
+ \endcode
+
+ \section2 OCSP Certificate Revocation Checking
+ In Qt 5 OCSP could be enabled on Linux using QWebEngineProfile::setUseForGlobalCertificateVerification(true)
+ on a QWebEngineProfile. This has been removed in Qt6 as this specific form of OCSP is considered bad. As
+ of Qt 6.2, no new method for revoked certificate checking on Linux has yet been added.
+
+
+*/
diff --git a/src/core/doc/src/qt_webengine_add_convert_dictionary.qdoc b/src/core/doc/src/qt_webengine_add_convert_dictionary.qdoc
new file mode 100644
index 000000000..6af681cc5
--- /dev/null
+++ b/src/core/doc/src/qt_webengine_add_convert_dictionary.qdoc
@@ -0,0 +1,54 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+\page qt-add-webengine-dictionary.html
+\ingroup cmake-commands-qtwebenginecore
+
+\title qt_add_webengine_dictionary
+\keyword qt6_add_webengine_dictionary
+
+\brief Converts the hunspell dictionary format into \e bdict binary format.
+
+\cmakecommandsince 6.3
+
+\section1 Synopsis
+
+\badcode
+qt_add_webengine_dictionary(
+ [TARGET]
+ [SOURCE]
+ [OUTPUT_DIRECTORY]
+)
+
+\endcode
+
+\versionlessCMakeCommandsNote qt6_webengine_add_dictionary()
+
+\section1 Description
+
+ A spell checker in Qt Web Engine needs dictionaries in a specific binary format.
+ This CMake command converts dictionaries from the \l{Hunspell project}. into the \c bdict
+ binary format. It creates a \c qtwebengine_dictionaries target, which your project can
+ use as a dependency. This way your project can easily add dictionaries for the spell
+ checker. Refer to the \l{WebEngine Widgets Spellchecker Example}{spell checker example}
+ for more details.
+
+\section1 Arguments
+
+ \c TARGET is an optinal argument and specifies the name of the application target that should
+ depend on \c qtwebengine_dictionaries target. In other words it is used to define a build
+ dependency to create the binary format of dictionaries before building \c TARGET.
+
+ \c SOURCE is the absolute path to the \l{Hunspell project} dictionary for which
+ a corresponding binary format (\c.bdict) will be created.
+
+ \c OUTPUT_DIRECTORY is an optional argument and specifies the directory where the binary format
+ of the dictionary will be created. If not specified, \c CMAKE_CURRENT_BINARY_DIR will be used
+ as \c OUTPUT_DIRECTORY.
+
+ \note The \c qtwebengine_dictionaries directory or \c <CONFIG>/qtwebengine_dictionaries
+ directories in the case of the multi-config generator is appended to OUTPUT_DIRECTORY. This
+ helps to utilize dictionaries, as the \c webengine_dictionaries directory is the default
+ search location.
+*/
diff --git a/src/core/doc/src/qtwebengine-debugging.qdoc b/src/core/doc/src/qtwebengine-debugging.qdoc
new file mode 100644
index 000000000..3dd4d9276
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-debugging.qdoc
@@ -0,0 +1,112 @@
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-debugging.html
+ \title Qt WebEngine Debugging and Profiling
+
+ \section1 Console Logging
+
+ JavaScript executed inside \QWE can use the
+ \l{Chrome console API} to log information to a console. The logging messages
+ are forwarded to Qt's logging facilities inside a \c js
+ \l{QLoggingCategory}{logging category}. However, only warning and fatal
+ messages are printed by default. To change this, you either have to set custom
+ rules for the \c js category, or provide custom message handlers
+ by reimplementing \l{QWebEnginePage::javaScriptConsoleMessage()}, or
+ connecting to \l{WebEngineView::javaScriptConsoleMessage()}.
+
+ All messages can also be accessed through the \QWE developer
+ tools.
+
+ \section1 Qt WebEngine Developer Tools
+
+ The \QWE module provides web developer tools that make it easy
+ to inspect and debug layout and performance issues of any web content.
+
+ The developer tools are accessed as a local web page using a Chromium or
+ \QWE based browser, such as the Chrome browser.
+
+ To activate the developer tools, start an application that uses \QWE
+ with the command-line argument \c {--remote-debugging-port=<portnumber>}.
+
+ \note Any WebEngine command line options should be specified after the
+ \c {--webEngineArgs} option, which is used to separate the user's application
+ specific options from the WebEngine's ones.
+
+ \badcode
+ --webEngineArgs --remote-debugging-port=<portnumber>
+ \endcode
+
+ Where \c <port_number> refers to a local network port. The web developer
+ tools can then be accessed by launching a browser at the address
+ \c http://localhost:<port_number>.
+
+ Alternatively, the environment variable QTWEBENGINE_REMOTE_DEBUGGING
+ can be set. It can be set as either just a port working similarly to
+ \c --remote-debugging-port or given both a host address and a port. The
+ latter can be used to control which network interface to export the
+ interface on, so that you can access the developer tools from a remote
+ device.
+
+ To avoid WebSocket errors during remote debugging, add an additional command-line
+ argument \c {--remote-allow-origins=<origin>[,<origin>, ...]}, where \c <origin> refers to the request origin.
+ Use \c {--remote-allow-origins=*} to allow connections from all origins. If nothing is specified,
+ \QWE will add \c {--remote-allow-origins=*} to command-line arguments when remote-debugging is enabled,
+ thereby allowing requests from all origins.
+
+ For a detailed explanation of the capabilities of developer tools, see the
+ \l {Chrome DevTools} page.
+
+ \section1 Using Command-Line Arguments
+
+ You can use the following command-line arguments while debugging to provide
+ input for bug reports:
+
+ \list
+ \li \c {--disable-gpu} disables GPU hardware acceleration. This is
+ useful when diagnosing OpenGL problems.
+ \li \c {--disable-logging} disables console logging, which might be
+ useful for debug builds.
+ \li \c {--enable-logging --log-level=0} enables console logging and sets
+ the logging level to 0, which means that messages of the severity
+ \c info and above are recorded in the log. This is the default for
+ debug builds. Other possible log levels are \c 1 for warnings, \c 2
+ for errors, and \c 3 for fatal errors.
+ \li \c {--v=1} Increases the logging level beyond what \c {--log-level}
+ can, and enables logging debug messages up to verbosity level \c 1.
+ A higher number further increases verbosity, but may result in a
+ large number of logged messages. Default is \c 0 (no debug messages).
+ \li \c {--no-sandbox} disables the sandbox for the renderer and plugin
+ processes. Keep in mind that disabling the sandbox might present a
+ security risk.
+ \li \c {--single-process} runs the renderer and plugins in the same
+ process as the browser. This is useful for getting stack traces for
+ renderer crashes.
+ \li \c {--enable-features=NetworkServiceInProcess} runs networking in
+ the main process. This may help firewall management, since only the
+ application executable will need to be whitelisted and
+ not QtWebEngineProcess. It means losing the security of
+ sandboxing of the network service though.
+ \endlist
+
+ Alternatively, the environment variable QTWEBENGINE_CHROMIUM_FLAGS can be
+ set. For example, the following value could be set to disable logging while
+ debugging an application called \e mybrowser:
+
+ \code
+ QTWEBENGINE_CHROMIUM_FLAGS="--disable-logging" mybrowser
+ \endcode
+
+ QTWEBENGINE_CHROMIUM_FLAGS can also be set using \c qputenv from within the
+ application if called before QtWebEngineQuick::initialize().
+
+ \section1 Dump WebEngineContext Information
+
+ For dumping the WebEngineContext information, you can set the \c QT_LOGGING_RULES
+ environment variable to \c "qt.webenginecontext.debug=true".
+
+ The output contains information about the graphical backend, and the way how \QWE
+ is initialized for the application. This is particularly useful for reproducing
+ issues.
+*/
diff --git a/src/core/doc/src/qtwebengine-deploying.qdoc b/src/core/doc/src/qtwebengine-deploying.qdoc
new file mode 100644
index 000000000..3d8a976c8
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-deploying.qdoc
@@ -0,0 +1,199 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-deploying.html
+ \title Deploying Qt WebEngine Applications
+ \ingroup explanations-webtechnologies
+
+ The way to package and deploy applications varies between operating systems.
+ For Windows and \macos, \l{The Windows Deployment Tool}{windeployqt} and
+ \l{Deploying Applications on macOS}{macdeployqt} automate the steps to
+ generate a stand-alone application package.
+
+ When manually deploying applications that depend on \QWE, all the
+ files that are required to run the application have to be included:
+ libraries, QML imports, plugins, and translations.
+
+ For more information, see \l {Deploying Qt Applications}.
+
+ \section1 Target Platforms
+
+ \QWE does try to support all \l{Supported Platforms} of Qt. However,
+ due to different requirements of Chromium this is not always possible. Known
+ limitations are:
+
+ \list
+ \li \QWE currently supports only Windows, Linux, and \macos.
+
+ \li On Windows, \QWE only supports Windows Vista or newer as
+ target platform. Due to use of newer API in Chromium, Windows XP is
+ not supported. WinRT is not supported, either.
+ \endlist
+
+ \section1 Deploying Applications Manually
+
+ When manually deploying applications that depend on \QWE, the
+ following files might have to be deployed:
+
+ \list
+ \li Libraries
+ \li QML imports
+ \li \QWE process
+ \li Resources
+ \li Translations
+ \li Audio and video codecs
+ \endlist
+
+ \section2 Deploying Libraries
+
+ The following libraries must be deployed with applications that depend on
+ \QWE:
+
+ \list
+ \li QtWebEngineCore library
+ \li QtWebEngineWidgets or QtWebEngine libraries, depending on
+ application type
+ \endlist
+
+ \section2 Deploying QML Imports
+
+ If Qt Quick integration is used in the application, the QtWebEngine import
+ directory needs to be deployed.
+
+ \section2 Deploying \QWE Processes
+
+ \QWE takes advantage of the multi-process model that the Chromium
+ project offers. The multi-process model requires that the \QWE
+ Process executable be deployed alongside your application.
+
+ The WebEngine process is executed for each QWebEngineView or WebEngineView
+ instance. For example, a browser application
+ with two tabs open should have two separate instances of the process
+ running. This is a common approach used by most modern web engines to
+ provide a stable browsing experience.
+
+ At runtime, \QWE looks for the \c QtWebEngineProcess executable in
+ the directory that
+ QLibraryInfo::location(QLibraryInfo::LibraryExecutablesPath) returns.
+ For Qt installations, this is \c QTDIR/libexec (Linux) or \c QTDIR\bin
+ (Windows). The path can be changed by defining a \c qt.conf file, for
+ example. Alternatively, an executable path can be set as a value of the
+ \c QTWEBENGINEPROCESS_PATH environment variable. On \macos, \QWE
+ looks for the executable in \c .app/Helpers/QtWebEngineProcess.
+
+ \section2 Deploying Resources
+
+ \QWE requires the following resource files:
+
+ \list
+ \li \c qtwebengine_resources.pak contains the resources needed by
+ Chromium.
+ \li \c qtwebengine_devtools_resources.pak contains tools for remote
+ debugging.
+ \li \c qtwebengine_resources_100p.pak contains images suitable for low
+ resolution displays.
+ \li \c qtwebengine_resources_200p.pak contains images suitable for high
+ DPI displays.
+ \li \c icudtl.dat provides support for International Components for
+ Unicode (ICU). It is the Chromium version of ICU, which is not
+ needed if \QWE was configured to use the system ICU.
+ \li \c v8_context_snapshot.bin contains a previously prepared snapshot
+ of a v8 context used to speed up initialization. Debug builds use
+ separate snapshots with the file name extension \c .debug.bin instead
+ of \c .bin. On \macos, there is a snapshot for each architecture named
+ accordingly, for example \c v8_context_snapshot.arm64.bin or
+ \c v8_context_snapshot.arm64.debug.bin.
+ \endlist
+
+ Resources are searched from the following locations:
+
+ \list
+ \li On Linux and Windows: the \c resources directory in the directory
+ specified by QLibraryInfo::location(QLibraryInfo::DataPath)
+ \li On \macos: \c .app/Content/Resources
+ \li The application directory specified by QCoreApplication::applicationDirPath()
+ \endlist
+
+ Alternatively, a resources directory path can be set as a value of the
+ \c QTWEBENGINE_RESOURCES_PATH environment variable.
+
+ \section2 Translations
+
+ Locale data (such as \c en-US.pak) is searched form the following locations:
+
+ \list
+ \li On \macos: \c .app/Content/Resources
+ \li On Linux and Windows: \c qtwebengine_locales directory in the
+ directory specified by
+ QLibraryInfo::location(QLibraryInfo::TranslationsPath)
+ \endlist
+
+ Alternatively, a locales directory path can be set as a value of the
+ \c QTWEBENGINE_LOCALES_PATH environment variable.
+
+ \section2 JavaScript Files in Qt Resource Files
+
+ If your WebEngine application is built using the Qt Quick Compiler, and the application ships
+ JavaScript files inside .qrc resources, and these files are supposed to be loaded from inside
+ HTML pages, make sure to specify the resource files in a \c QTQUICK_COMPILER_SKIPPED_RESOURCES
+ qmake variable inside your project. This prevents the Qt Quick Compiler from trying to generate
+ C++ code for the corresponding JavaScript code, as well as removing the original JavaScript code
+ from the Qt resources file, which would lead to broken HTML pages. For example:
+
+ \code
+ QTQUICK_COMPILER_SKIPPED_RESOURCES += resources/my_resource.qrc
+ \endcode
+
+ \section2 \macos Specific Deployment Steps
+
+ To deploy a \QWE application on \macos, you will need to ensure that the \QWE process is signed
+ with an entitlements file that at least contains the entitlements listed in
+ QtWebEngineCore.framework/Helpers/QtWebEngineProcess.app/Contents/Resources/QtWebEngineProcess.entitlements.
+
+ To deploy a \QWE application that accesses the microphone or camera
+ on \macos, you will need to provide texts for the messages that will be shown to the user to
+ explain why the application asks for permission to access to the camera or microphone.
+ To do this, add the texts to the application's \c Info.plist file using the keys
+ described below.
+
+ For the camera usage message, provide a text using the following key:
+ \code
+ <key>NSCameraUsageDescription</key>
+ <string>Your message text for camera usage.</string>
+ \endcode
+
+ See also \l{https://developer.apple.com/documentation/bundleresources/information_property_list/nscamerausagedescription}
+ {Apple's property list file documentation}.
+
+ For the microphone usage message, provide a text using the following key:
+ \code
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Your message text for microphone usage.</string>
+ \endcode
+
+ See also \l{https://developer.apple.com/documentation/bundleresources/information_property_list/nsmicrophoneusagedescription}
+ {Apple's property list file documentation}.
+
+ To notarize an application that accesses the camera or the microphone,
+ you will need to add the corresponding keys to your application's entitlements file used for
+ deployment and notarization.
+
+ To enable access to the camera, add:
+ \code
+ <key>com.apple.security.device.camera</key>
+ <true/>
+ \endcode
+
+ See also \l{https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_device_camera}
+ {Apple's camera entitlement documentation}.
+
+ To enable access to the microphone, add:
+ \code
+ <key>com.apple.security.device.microphone</key>
+ <true/>
+ \endcode
+
+ See also \l{https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_device_microphone}
+ {Apple's microphone entitlement documentation}.
+*/
diff --git a/src/core/doc/src/qtwebengine-features.qdoc b/src/core/doc/src/qtwebengine-features.qdoc
new file mode 100644
index 000000000..9465d75a2
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-features.qdoc
@@ -0,0 +1,777 @@
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-features.html
+ \title Qt WebEngine Features
+ \ingroup explanations-webtechnologies
+
+ \brief Summarizes \QWE features.
+
+ \QWE supports the following features:
+
+ \list
+ \li \l{Audio and Video Codecs}
+ \li \l{WebEngineDriver}
+ \li \l{Chromium DevTools}
+ \li \l{Client Certificates}
+ \li \l{Custom Schemes}
+ \li \l{Drag and Drop}
+ \li \l{Favicon}
+ \li \l{Fullscreen}
+ \li \l{Hardware Acceleration}
+ \li \l{HTML5 DRM}
+ \li \l{HTML5 Geolocation}
+ \li \l{HTML5 WebSockets}
+ \li \l{HTTP/2 Protocol}
+ \li \l{Local Storage}
+ \li \l{Native Dialogs}
+ \li \l{PDF File Viewing}
+ \li \l{Page Lifecycle API}
+ \li \l{Print to PDF}
+ \li \l{Process Models}
+ \li \l{Spellchecker}
+ \li \l{Touch}
+ \li \l{View Source}
+ \li \l{Web Notifications}
+ \li \l{WebGL}
+ \li \l{webrtc_feature}{WebRTC}
+ \endlist
+
+ \section1 Audio and Video Codecs
+
+ \QWE supports the MPEG-4 Part 14 (MP4) file format only if the
+ required proprietary audio and video codecs, such as H.264 and MPEG layer-3
+ (MP3), have been enabled. Proprietary codecs can be enabled by passing the
+ following option to the \c configure tool when configuring Qt:
+
+ \badcode
+ -webengine-proprietary-codecs
+ \endcode
+
+ For example, the following option could be passed when configuring Qt for
+ building it at the top level:
+
+ \badcode
+ configure -webengine-proprietary-codecs
+ \endcode
+
+ For more information, see \l{Qt Configure Options}.
+
+ When using cmake to build just the \QWE module, the following
+ command can be used to configure and build (in this example, the \QWE source code is
+ located in \c {C:\qt\qtwebengine}):
+
+ \badcode
+ qt-configure-module C:\qt\qtwebengine -webengine-proprietary-codecs
+ cmake --build . --parallel
+ \endcode
+
+ \warning When distributing proprietary codec libraries, you must acquire
+ licenses for them.
+
+ \l FFmpeg is a cross-platform solution to record, convert, and stream audio
+ and video. It can be configured for use with several codecs, which rises
+ licensing issues during distribution with the codec libraries. For some
+ codecs, open source implementations, such as \l{OpenH264 Project Homepage}
+ {OpenH264}, are available.
+
+ \section1 WebEngineDriver
+
+ With WebEngineDriver, you can automate the testing of web sites across browsers.
+ WebEngineDriver is based on ChromeDriver and can be used the same way.
+ For more information about ChromeDriver and its use, visit
+ \l {https://chromedriver.chromium.org/}{ChromeDriver user site}.
+
+ WebEngineDriver has slight modifications compared to ChromeDriver to be able to connect to
+ \QWE based browsers. It is compatible with \QWE example browsers, such as
+ \l {WebEngine Widgets Simple Browser Example}{Simple Browser} or
+ \l{WebEngine Quick Nano Browser}{Nano Browser}.
+
+ The browser automation is scripted through a WebDriver client like the
+ \l {https://www.selenium.dev/}{Selenium WebDriver}.
+ For example, WebEngineDriver can be used with the Python lanugage bindings of
+ Selenium WebDriver:
+
+ \code
+ from selenium import webdriver
+ from selenium.webdriver.chrome.service import Service
+
+ service = Service(executable_path='QTDIR/libexec/webenginedriver')
+ options = webdriver.ChromeOptions()
+ options.binary_location = 'path/to/browser_binary'
+
+ driver = webdriver.Chrome(service=service, options=options)
+ driver.get("http://www.google.com/")
+ driver.quit()
+ \endcode
+
+ In this example,
+ \list
+ \li \c executable_path has to be set to the WebEngineDriver's binary path
+ \li \c QTDIR is the directory where Qt is installed
+ \li \c options.binary_location has to be set to the browser's binary path
+ \endlist
+
+ \note On Windows: \c executable_path='QTDIR/bin/webenginedriver.exe'
+
+ Before executing the script, the \c QTWEBENGINE_REMOTE_DEBUGGING environment variable has to
+ be set. Its value is a port number what is used by both the browser and WebEngineDriver to
+ communicate with each other.
+ \badcode
+ export QTWEBENGINE_REMOTE_DEBUGGING=12345
+ \endcode
+
+ By executing, the script opens the specified web browser and loads the Google web site.
+
+ WebEngineDriver can be also attached to an already running browser if it was started with the
+ remote debugging port set. \c options.debugger_address has to be set to the remote debugging
+ address in the script:
+
+ \code
+ options.debugger_address = 'localhost:12345'
+ \endcode
+
+ In this case, \c options.binary_location should not be set because the browser is already
+ running. The environment variable \c QTWEBENGINE_REMOTE_DEBUGGING is not used by the
+ WebEngineDriver if \c options.debugger_address is set.
+
+ \note WebEngineDriver must be built with the same version of Chromium as \QWE is using.
+
+ \section1 Chromium DevTools
+
+ The Chromium DevTools provide the ability to inspect and debug layout and
+ performance issues of any web content.
+
+ This feature can be tested by launching a \QWE application with the
+ command line option \c {--remote-debugging-port=[your-port]} or by setting
+ the environment variable \c QTWEBENGINE_REMOTE_DEBUGGING and then using a
+ Chromium based browser (such as \l{WebEngine Widgets Simple Browser Example}
+ {Simple Browser} or \l{WebEngine Quick Nano Browser}{Nano Browser}) to connect
+ to \c {http://localhost:[your-port]}.
+
+ \note Any WebEngine command line options should be specified after the
+ \c {--webEngineArgs} option, which is used to separate the user's application
+ specific options from the WebEngine's ones.
+
+ \badcode
+ --webEngineArgs --remote-debugging-port=5000
+ \endcode
+
+ To avoid WebSocket errors during remote debugging, add an additional command-line argument
+ \c {--remote-allow-origins=<origin>[,<origin>, ...]}, where \c <origin> refers to the request origin.
+ Use \c {--remote-allow-origins=*} to allow connections from all origins. If nothing is specified,
+ \QWE will add \c {--remote-allow-origins=*} to command-line arguments when remote-debugging is enabled,
+ thereby allowing requests from all origins.
+
+ The Chromium DevTools page can also be shown within the application. To set
+ this up, you can call either QWebEnginePage::setInspectedPage() to the page
+ to be inspected, which implicitly loads the DevTools into the \c this page,
+ or QWebEnginePage::setDevToolsPage() to let the \c this page be inspected.
+
+ The respective QML properties are \l{WebEngineView::devToolsView}
+ {WebEngineView.devToolsView} and \l{WebEngineView::inspectedView}
+ {WebEngineView.inspectedView}.
+
+ For more information, see \l {Qt WebEngine Debugging and Profiling}.
+
+ \section1 Client Certificates
+
+ Some web servers, in particular many intranet sites, require the client to
+ authenticate itself with a certificate, called a \e {client certificate}. \QWE
+ will read the client certificates installed in the system settings in macOS and
+ Windows, and on Linux those installed into the NSS database. Certificates can
+ be installed into the NSS database using the \c pk12util tool.
+
+ By default, \QWE will not offer any client certificates to servers, as doing
+ so uniquely identifies the user and might violate privacy expectations.
+
+ To activate support for client certificates, an application needs to listen to
+ the QWebEnginePage::selectClientCertificate or
+ \l{WebEngineView::selectClientCertificate}{WebEngineView.selectClientCertificate}
+ signals and select one of the offered
+ certificates. For applications that can navigate to untrusted web sites, it is
+ recommended to always give the user a choice before uniquely identifying them
+ to a remote server.
+
+ In addition to the client certificate stored in system settings, \QWE offers also
+ the in-memory store. The QWebEngineClientCertificateStore instance can be obtained with
+ the QWebEngineProfile::clientCertificateStore() method. An application can use this
+ class to add a new certificate with a QWebEngineClientCertificateStore::add() call.
+ Note that during the \c selectClientCertificate calls, \QWE lists both system
+ and in-memory stored clients certificates.
+
+ See also \l{WebEngine Widgets Client Certificate Example}{Client Certificate Example}
+ for more implementation details.
+
+ \section1 Custom Schemes
+
+ \QWE makes it possible for the application to define its own custom
+ URL schemes with specialized security policies and transport mechanisms.
+
+ Custom schemes can be used to implement alternative network protocols with
+ all the usual web security policies, privileged internal schemes for
+ displaying user interface components or debugging information, sandboxed
+ schemes with extra restrictions, and so on.
+
+ For more information, see \l QWebEngineUrlScheme and \l
+ QWebEngineUrlSchemeHandler.
+
+ \section1 Drag and Drop
+
+ \QWE supports HTML5 drag and drop.
+
+ This feature can be tested by opening an HTML5 drag and drop demo, such as
+ \l{HTML5 Demos - Drag and Drop}, \l{HTML5 Demos - Simple Drag and Drop}, or
+ \l{HTML5 Demos - Drag and Drop, Automatic Upload}, in \l{WebEngine Widgets
+ Simple Browser Example}{Simple Browser} or \l{WebEngine Quick Nano Browser}
+ {Nano Browser}.
+
+ Dragging files into the browser is not actually part of HTML5, but it is
+ supported. It can be tested by opening \l{HTML5 Demos - File API}.
+
+ Support for this feature was added in Qt 5.7.0.
+
+ \section1 Favicon
+
+ \QWE supports the web site URL icon, \e favicon. Each icon is stored in the internal
+ database for each \l QWebEngineProfile and can be accessed using a \l QWebEnginePage::icon()
+ call or a \l {WebEngineView::icon}{WebEngineView.icon} property for the currently loaded content.
+
+ Moreover \QWE provides API for accessing already stored icons in the internal profile's database.
+
+ \note The icon database is not available for off-the-record profiles.
+
+ \section2 QML Favicon Handling
+
+ For accessing icons a \c QQuickImageProvider is registered. This provider can be
+ accessed by a special URL where the scheme is "image:" and the host is "favicon".
+
+ \qml
+ Image {
+ source: "image://favicon/url"
+ }
+ \endqml
+
+ The \c url can be the URL of the favicon:
+
+ \qml
+ Image {
+ source: "image://favicon/https://www.qt.io/hubfs/2016_Qt_Logo/qt_logo_green_rgb_16x16.png"
+ }
+ \endqml
+
+ The \c url also can be a page URL to access its icon:
+
+ \qml
+ Image {
+ source: "image://favicon/https://www.qt.io/"
+ }
+ \endqml
+
+ If more than one icon is available, the \l {Image::sourceSize} property can be
+ specified to choose the icon with the desired size. If \l {Image::sourceSize}
+ is not specified or 0, the largest available icon will be chosen.
+
+ The image provider looks up the requested icon in the existing \l {WebEngineView}
+ instances. First, it tries to match the currently displayed icons. If no match
+ has been found it requests the icon from the database. Each profile has its
+ own icon database and it is stored in the persistent storage thus the stored icons
+ can be accessed without network connection too. The icon must be previously loaded
+ to be stored in the database.
+
+ \section2 C++ Favicon Handling
+
+ A user can request an icon from the previously loaded content for each
+ \l QWebEngineProfile using the \l QWebEngineProfile::requestIconForPageURL() or
+ \l QWebEngineProfile::requestIconForIconURL() calls. Note that the profile's database is
+ stored in the persistent storage and can be accessed without a network connection.
+
+ \section1 Fullscreen
+
+ \QWE supports viewing web content in fullscreen mode. For more
+ information, see \l{WebEngineSettings::fullscreenSupportEnabled}
+ {WebEngineSettings.fullscreenSupportEnabled},
+ \l{WebEngineView::fullScreenRequested}{WebEngineView.fullScreenRequested},
+ QWebEngineSettings::FullScreenSupportEnabled, and
+ QWebEnginePage::fullScreenRequested.
+
+ This feature can be tested by playing a video from YouTube in \l{WebEngine
+ Widgets Video Player Example}{Video Player} or \l{WebEngine Quick Nano Browser}
+ {Nano Browser}, and clicking the full screen icon to go into fullscreen
+ mode.
+
+ Support for this feature was added in Qt 5.6.0.
+
+ \section1 Hardware Acceleration
+
+ QtWebEngine tries to use hardware acceleration for rendering the content. It uses
+ \c OpenGL or \c OpenGLES APIs to execute rendering calls on the GPU. As a fallback,
+ software rendering is used whenever the hardware does not meet the required set of
+ OpenGL functionality. A user can check the current hardware acceleration state by
+ loading the \c {chrome://gpu} internal page. Moreover, the acceleration can be explicitly
+ disabled with \c {QTWEBENGINE_CHROMIUM_FLAGS} using the \c {disable-gpu} switch.
+ For example on Linux:
+
+ \badcode
+ export QTWEBENGINE_CHROMIUM_FLAGS=--disable-gpu
+ \endcode
+
+ \section1 HTML5 DRM
+
+ \QWE supports viewing DRM protected videos if the \l{Widevine CDM} plugin has been installed.
+ CDM plugin is a replacement of Flash based plugins for displaying DRM-protected content.
+ It comes only in a binary format, so it can hide DRM decryption implementation details.
+ It can be obtained from a third party or from a Google Chrome installation.
+
+ \QWE on startup looks for the \l{Widevine CDM} plugin in well know locations, like
+ default Google Chrome installation directory or Linux distro specific paths. However, plugin
+ location can be also passed with \c {QTWEBENGINE_CHROMIUM_FLAGS} using \c {widevine-path}.
+
+ On Windows:
+ \badcode
+ set QTWEBENGINE_CHROMIUM_FLAGS=--widevine-path="C:/some path/widevinecdm.dll"
+ \endcode
+
+ On Linux:
+ \badcode
+ export QTWEBENGINE_CHROMIUM_FLAGS=--widevine-path="/some path/libwidevinecdm.so"
+ \endcode
+
+ On macOS:
+ \badcode
+ export QTWEBENGINE_CHROMIUM_FLAGS=--widevine-path="/some path/libwidevinecdm.dylib"
+ \endcode
+
+
+ The video format most commonly used by DRM services, H.264, requires
+ proprietary audio and video codecs. For more information about enabling the
+ codecs, see \l{Audio and Video Codecs}.
+
+ This feature can be tested by playing a video in \l{WebEngine Widgets Simple Browser
+ Example}{Simple Browser} or \l{WebEngine Quick Nano Browser}{Nano Browser}
+ from \l{castLabs}, \l{Swank Motion Pictures, Inc.}, or \l{Bitmovin Player}.
+
+ Support for this feature was added in Qt 5.7.0.
+
+ \section1 HTML5 Geolocation
+
+ \QWE supports JavaScript Geolocation API with \l {Qt Positioning} as a
+ backend. HTML5 geolocation is disabled by default. To explicitly allow it, the application
+ needs to listen to QWebEnginePage::featurePermissionRequested. Use QWebEnginePage::Geolocation
+ with a QWebEnginePage::setFeaturePermission() call or \l{WebEngineView::Feature}
+ with a \l{WebEngineView::grantFeaturePermission} {WebEngineView.grantFeaturePermission}() call
+ to grant the required permission.
+
+ If \QWE was built with Qt Positioning support then this feature can be
+ tested by using \l{WebEngine Widgets Maps Example}{Maps} and allowing it to
+ find the current position of the user.
+
+ \note On Windows 11, enable settings to grant the maps example access to
+ Windows location services. In the Settings App under
+ \uicontrol {Privacy & Security} > \uicontrol {Location}, enable \uicontrol
+ {Location services}, \uicontrol {Let apps access your location} and \uicontrol
+ {Let desktop apps access your location}.
+
+ See \l{Qt Positioning} for a possible backend setup like the GPS or IP based positioning.
+
+ Support for this feature was added in Qt 5.5.0.
+
+ \section1 HTML5 WebSockets
+
+ \QWE supports the WebSocket JavaScript API to communicate with WebSocket servers
+ using the \c {ws://} or \c {wss://} protocols. Moreover, integration with Qt WebChannel
+ and Qt WebSockets enables communication between JavaScript and the native side of
+ the application.
+
+ The Qt WebChannel module has a great example for a
+ \l[QtWebChannel]{Qt WebChannel ChatServer Example}{chat server}
+ and its web based
+ \l[QtWebChannel]{Qt WebChannel ChatClient HTML Example}{chat client}.
+ The client works out of the box in the example browsers of \QWE
+ (such as \l{WebEngine Widgets Simple Browser Example}
+ {Simple Browser} or \l{WebEngine Quick Nano Browser}{Nano Browser}).
+
+ \section1 HTTP/2 Protocol
+
+ \QWE supports the Chromium implementation of the \l{HTTP/2}
+ protocol.
+
+ This feature can be tested by opening an HTTP/2 demo, such as the
+ \l{Akamai HTTP/2 Demo}, in \l{WebEngine Widgets Simple Browser Example}
+ {Simple Browser} or \l{WebEngine Quick Nano Browser}{Nano Browser}.
+
+ \section1 Local Storage
+
+ \QWE supports saving key-value pairs in a \c {Local Storage} with no expiration date.
+ This is a part of the \l
+ {https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API}
+ {Web Storage API}, where a user can access a \c Storage object for the given domains
+ using the \c Window.localStorage JavaScript property. The stored data will persist even
+ after the page or the browser application is closed.
+
+ Note that the \c Local Storage can be also disabled with a
+ \l QWebEngineSettings::LocalStorageEnabled
+ setting. Moreover, the storage path can be adjusted with a
+ \l QWebEngineProfile::setPersistentStoragePath
+ call.
+
+ \code
+ QWebEngineProfile profile("MyProfile");
+ profile.settings()->setAttribute(QWebEngineSettings::LocalStorageEnabled, isEnabled);
+ profile.setPersistentStoragePath("/path/to/storage");
+ \endcode
+
+ \QWE offers also an easy way of investigating the content of the \c {Local Storage}
+ with \l {Qt WebEngine Developer Tools} by visiting the \uicontrol Application panel
+ and expanding the \uicontrol {Local Storage} menu.
+
+ \section1 Native Dialogs
+
+ A web page might request dialogs for the following functions:
+
+ \list
+ \li Entering user credentials for HTTP and proxy authentication
+ \li Displaying JavaScript alerts, confirmation dialogs, and prompts
+ \li Picking colors
+ \li Selecting files
+ \li Displaying form validation messages
+ \endlist
+
+ \QWE provides standard dialogs for these functions. In widget-based
+ applications, the standard dialogs are based on QDialog, whereas in Qt Quick
+ applications, they can be based either on Qt Quick Controls 1 or Qt Quick
+ Controls 2 (since Qt 5.8). The latter are used only on \c eglfs platforms.
+
+ To explicitly force either dialogs based on Qt Quick Controls 1 or Qt Quick
+ Controls 2, set the \c QTWEBENGINE_DIALOG_SET environment variable to either
+ \c{QtQuickControls1} or \c{QtQuickControls2}.
+
+ \QWE Widgets dialogs can be customized by reimplementing the
+ QWebEnginePage::chooseFiles(), QWebEnginePage::javaScriptAlert(),
+ QWebEnginePage::javaScriptConfirm(), and QWebEnginePage::javaScriptPrompt()
+ functions.
+
+ Since Qt 5.8, Qt Quick dialogs can be customized by connecting to the
+ WebEngineView::authenticationDialogRequested(),
+ WebEngineView::javaScriptDialogRequested(),
+ WebEngineView::colorDialogRequested(),
+ WebEngineView::fileDialogRequested(), and
+ WebEngineView::formValidationMessageRequested() signals. For an example,
+
+ \section1 PDF File Viewing
+
+ \QWE supports viewing PDF documents by navigating to them. This feature uses the Chromium
+ extensions API and PDF viewer plugin to display the PDF documents.
+ It can be tested in \l{WebEngine Widgets Simple Browser Example}{Simple Browser} or
+ \l{WebEngine Quick Nano Browser}{Nano Browser}.
+
+ Loading plugins needs to be enabled using QWebEngineSettings::PluginsEnabled or
+ WebEngineSettings::pluginsEnabled in order to use this feature.
+
+ This feature can be turned on (default) or off via the QWebEngineSettings::PdfViewerEnabled or
+ WebEngineSettings::pdfViewerEnabled setting.
+
+ Support for this feature was added in Qt 5.13.0.
+
+ \section1 Page Lifecycle API
+
+ \QWE supports the \l {https://wicg.github.io/page-lifecycle/spec.html}{Page
+ Lifecycle API specification}, a work-in-progress extension to the HTML
+ standard for allowing user agents to reduce their resource consumption by
+ freezing or discarding background pages. The feature is exposed both in the
+ Widgets and QML APIs.
+
+ For an example of the QML API in use, see the \l {WebEngine Lifecycle
+ Example}.
+
+ Support for this feature was added in Qt 5.14.0.
+
+ \section2 Overview of Lifecycle States
+
+ Each \l {WebEngineView} item (or \l {QWebEnginePage} object) can be in one
+ of three \e {lifecycle states}: active, frozen, or discarded. These states,
+ like the sleep states of a CPU, control the resource usage of web views.
+
+ The \e {active} state is the normal, unrestricted state of a web view. All
+ visible web views are always in the active state, as are all web views that
+ have not yet finished loading. Only invisible, idle web views can be
+ transitioned to other lifecycle states.
+
+ The \e {frozen} state is a low CPU usage state. In this state, most HTML
+ task sources are suspended (frozen) and, as a result, most DOM event
+ processing and JavaScript execution will also be suspended. The web view
+ must be invisible in order to be frozen as rendering is not possible in this
+ state.
+
+ The \e {discarded} state is an extreme resource-saving state. In this state,
+ the browsing context of the web view will be discarded and the corresponding
+ renderer subprocess shut down. CPU and memory usage in this state is reduced
+ virtually to zero. On exiting this state the web page will be automatically
+ reloaded. The process of entering and exiting the discarded state is similar
+ to serializing the browsing history of the web view and destroying the view,
+ then creating a new view and restoring its history.
+
+ See also \l {WebEngineView::LifecycleState}. The equivalent in the Widgets
+ API is \l {QWebEnginePage::LifecycleState}.
+
+ \section2 The \c {lifecycleState} and \c {recommendedState} Properties
+
+ The \l {WebEngineView::}{lifecycleState} property of the \l {WebEngineView}
+ type is a read-write property that controls the current lifecycle state of
+ the web view. This property is designed to place as few restrictions as
+ possible on what states can be transitioned to. For example, it is allowed
+ to freeze a web view that is currently playing music in the background,
+ stopping the music. In order to implement a less aggressive resource-saving
+ strategy that avoids interrupting user-visible background activity, the \l
+ {WebEngineView::} {recommendedState} property must be used.
+
+ The \l {WebEngineView::}{recommendedState} property of the \l
+ {WebEngineView} type is a read-only property that calculates a safe limit on
+ the \l {WebEngineView::}{lifecycleState} property, taking into account the
+ current activity of the web view. So, in the example of a web view playing
+ music in the background, the recommended state will be \c {Active} since a
+ more aggressive state would stop the music. If the application wants to
+ avoid interrupting background activity, then it should avoid putting the web
+ view into a more aggressively resource-saving lifecycle state than what's
+ given by \l {WebEngineView::}{recommendedState}.
+
+ See also \l {WebEngineView::lifecycleState} and \l
+ {WebEngineView::recommendedState}. The equivalents in the Widgets API are \l
+ {QWebEnginePage::lifecycleState} and \l {QWebEnginePage::recommendedState}.
+
+ \section2 The DOM Extensions
+
+ The \l {WebEngineView::}{lifecycleState} property is connected to the \l
+ {https://wicg.github.io/page-lifecycle/spec.html}{Page Lifecycle API
+ specification}, which specifies two new DOM events, \c {freeze} and \c
+ {resume}, and adds a new \c {Document.wasDiscarded} boolean property. The \c
+ {freeze} and \c {resume} events are fired when transitioning from the \c
+ {Active} to the \c {Frozen state}, and vice-versa. The \c
+ {Document.wasDiscarded} property is set to \c {true} when transitioning from
+ the \c {Discarded} state to the \c {Active} state.
+
+ \section1 Print to PDF
+
+ \QWE supports printing a web page to a PDF file. For more
+ information, see QWebEnginePage::printToPdf() and
+ \l{WebEngineView::printToPdf}{WebEngineView.printToPdf}.
+
+ This feature can be tested using \l{WebEngine Widgets Html2Pdf Example}
+ {Html2Pdf}.
+
+ Support for this feature was added in Qt 5.7.0.
+
+ \section1 Process Models
+
+ \QWE uses multiple OS processes to isolate web sites from each other
+ and from the client application, improving security and robustness. The
+ following process models, or ways to divide web sites between OS processes,
+ are supported:
+
+ \list
+ \li \l{Process per Site Instance}
+ \li \l{Process per Site}
+ \li \l{Single Process}
+ \endlist
+
+ \section2 Process per Site Instance
+
+ This is the default model. Pages from separate sites are put into separate
+ processes and separate visits to the same site are also isolated.
+
+ Two web pages are considered as belonging to the same site if they originate
+ from the same registered domain name (for example, \c wikipedia.org) and
+ scheme (for example, \c https). This is similar to the same-origin policy
+ but subdomains are ignored. For example, both \c{https://en.wikipedia.org/}
+ and \c{https://de.wikipedia.org/} would belong to the same site.
+
+ A site instance is a collection of web pages belonging to the same site.
+ When the application explicitly loads a URL into \QWE (via \l
+ QWebEnginePage::setUrl, for example), a new site instance is created for the
+ page. However, when the user clicks same-site links on the page, the
+ existing site instance is merely extended with more pages.
+
+ For instance, in the \l{WebEngine Widgets Simple Browser Example}{Simple
+ Browser} example, when a user opens two tabs and explicitly enters
+ \c{https://en.wikipedia.org/} into the URL bars, both tabs will have their
+ own separate OS processes (because explicitly entering a URL creates a new
+ site instance). However, when the user then middle-clicks some same-site
+ links to open more tabs, these new tabs will share the same OS process
+ (because user interaction extends the existing site instance).
+
+ \section2 Process per Site
+
+ Pages from separate sites are put into separate processes. Unlike Process
+ per Site Instance, all visits to the same site will share an OS process.
+
+ The benefit of this model is reduced memory consumption, because more web
+ pages will share processes. The drawbacks include reduced security,
+ robustness, and responsiveness.
+
+ To enable this model, use the command-line argument \c{--process-per-site}.
+ See \l{Using Command-Line Arguments}.
+
+ \section2 Single Process
+
+ For debugging purposes only, a single process mode can be enabled using the
+ command-line argument \c{--single-process}. See \l{Using Command-Line
+ Arguments} and \l{Qt WebEngine Debugging and Profiling}.
+
+ \section1 Spellchecker
+
+ \QWE supports integrating spellchecking support into HTML forms to
+ enable users to submit spellchecked messages. When the user clicks on
+ an underlined misspelled word, the default context menu displays up to four
+ suggestions. Selecting one will replace the misspelled word.
+
+ To be able to check the spelling, the spellchecker needs dictionaries. It
+ supports dictionaries from the \l{Hunspell project}, but they have to be
+ compiled into a special binary format. A Hunspell dictionary consists of two
+ files:
+
+ \list
+
+ \li A \c .dic file that is a dictionary containing words for the
+ language
+ \li An \c .aff file that defines the meaning of special flags in the
+ dictionary
+ \endlist
+
+ These two files can be converted into the \c bdic format by using the
+ \c qwebengine_convert_dict tool that is shipped together with Qt.
+ When the \QWE spellchecker initializes, it will try to load the
+ \c bdict dictionaries and to check them for consistency.
+
+ If \c QTWEBENGINE_DICTIONARIES_PATH is set, the spellchecker uses the
+ dictionaries in the specified directory without looking anywere else.
+ Otherwise, it uses the \e qtwebengine_dictionaries directory relative to the
+ executable if it exists. If it does not exist, it will look in \c
+ QT_INSTALL_PREFIX/qtwebengine_dictionaries.
+
+ On macOS, depending on how \QWE is configured at build time, there
+ are two possibilities how spellchecking data is found:
+
+ \list
+ \li Hunspell dictionaries (default) - .bdic dictionaries are used, just
+ like on other platforms
+ \li Native dictionaries - the macOS spellchecking APIs are used (which
+ means the results will depend on the installed OS dictionaries)
+ \endlist
+
+ Thus, in the macOS Hunspell case, \QWE will look in the \e
+ qtwebengine_dictionaries subdirectory located inside the application bundle
+ \c Resources directory, and also in the \c Resources directory located
+ inside the Qt framework bundle.
+
+ To summarize, in case of Hunspell usage, the following paths are considered:
+
+ \list
+ \li \c QTWEBENGINE_DICTIONARIES_PATH, if set
+ \li QCoreApplication::applicationDirPath()/qtwebengine_dictionaries
+ or QCoreApplication::applicationDirPath()/../Contents/Resources/qtwebengine_dictionaries
+ (on macOS)
+ \li [QLibraryInfo::DataPath]/qtwebengine_dictionaries
+ or path/to/QtWebEngineCore.framework/Resources/qtwebengine_dictionaries (Qt framework
+ bundle on macOS)
+ \endlist
+
+ Spellchecking is disabled by default and can be enabled per profile by
+ using the QWebEngineProfile::setSpellCheckEnabled() method in widget-based
+ applications and the \l {QQuickWebEngineProfile::spellCheckEnabled}
+ {WebEngineProfile.spellCheckEnabled} property in Qt Quick applications.
+
+ The current language used for spellchecking is defined per profile, and can
+ be set using the QWebEngineProfile::setSpellCheckLanguages() method or the
+ \l {QQuickWebEngineProfile::spellCheckLanguages}
+ {WebEngineProfile.spellCheckLanguages} property.
+
+ This feature can be tested by building and running the
+ \l{WebEngine Widgets Spellchecker Example}{Spellchecker Example}.
+
+ \QWE can be compiled also without spellchecker support with the use of
+ a \c {webengine-spellchecker} configure switch.
+
+ \badcode
+ qt-configure-module path\to\qtwebengine\sources -no-webengine-spellchecker
+ \endcode
+
+ For more information, see \l{Qt Configure Options}.
+
+ Support for this feature was added in Qt 5.8.0.
+
+ \section1 Touch
+
+ \QWE supports touch devices for navigating and interacting with web pages.
+
+ Applications can prohibit the use of touch events in the following ways:
+
+ \list
+ \li Passing the flag \c --touch-events=disabled on the command line will disable touch event
+ support in JavaScript API (meaning \c ontouchstart and related handlers will not be present
+ in the \c document.window object). Touch events will still be delivered to web pages.
+
+ \li Installing an event filter object using \l {QObject::installEventFilter} on the WebEngine
+ view focus proxy object, and filtering out all touch events.
+
+ \endlist
+
+ \section1 View Source
+
+ \QWE supports viewing the HTML source of a web page.
+
+ This feature can be used from custom menus or assigned to custom events.
+ For more information, see WebEngineView::WebAction, and QWebEnginePage::WebAction.
+
+ This feature can be tested by opening a web page in \l{WebEngine Widgets
+ Simple Browser Example}{Simple Browser} or \l{WebEngine Quick Nano Browser}
+ {Nano Browser}, and then selecting \c{Page Source} in the context menu. The
+ \c{Page Source} context menu entry opens the source view in a new tab.
+
+ For opening the source view in the current tab, URLs with \l{view-source URI scheme}
+ are also supported. For example, you can type the following URL to the URL bar
+ to view the HTML source of the qt.io web page:
+ \badcode
+ view-source:https://www.qt.io/
+ \endcode
+
+ Auto-completion of incomplete URLs with \l{view-source URI scheme} makes the usage of
+ this feature more comfortable. For example, the following incomplete URL also loads
+ the source view of the qt.io web page:
+ \badcode
+ view-source:qt.io
+ \endcode
+
+ Support for this feature was added in Qt 5.8.0.
+
+ \section1 Web Notifications
+
+ Qt WebEngine supports JavaScript \l{Web Notifications API}.
+ The application has to explicitly allow the feature by using
+ QWebEnginePage::Notifications or \l{WebEngineView::Feature}
+ {WebEngineView.Notifications}.
+
+ Support for this feature was added in Qt 5.13.0.
+
+ \section1 WebGL
+
+ \QWE supports WebGL for some graphics stacks setups. A user can visit the
+ chrome://gpu page using the QtWebEngine powered application. The \e {Graphics Feature Status}
+ overview states if WebGL is supported for the current platform setup. A user can also
+ check the \l {https://webglreport.com}{WebGL Report}.
+
+ The WebGL support is enabled by default. You can disable it with the
+ \l QWebEngineSettings::WebGLEnabled setting.
+
+ \target webrtc_feature
+ \section1 WebRTC
+
+ WebRTC provides browsers with Real-Time Communications (RTC) capabilities
+ via simple APIs. For more information, see \l{WebEngineView::Feature}
+ {WebEngineView.Feature}, and QWebEnginePage::Feature.
+
+ This feature can be tested by setting up a webcam or microphone and then
+ opening \c https://test.webrtc.org/ in \l{WebEngine Widgets Simple Browser
+ Example}{Simple Browser} or \l{WebEngine Quick Nano Browser}{Nano Browser}.
+
+*/
diff --git a/src/core/doc/src/qtwebengine-global.qdoc b/src/core/doc/src/qtwebengine-global.qdoc
new file mode 100644
index 000000000..7f6636c16
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-global.qdoc
@@ -0,0 +1,56 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \headerfile <qtwebenginecoreglobal.h>
+ \inmodule QtWebEngineCore
+ \title Global Qt WebEngine Core Declarations
+ \ingroup funclists
+
+ \brief Helper functions for the \QWE Core module.
+
+*/
+
+
+/*!
+ \fn const char *qWebEngineVersion() noexcept
+ \relates <qtwebenginecoreglobal.h>
+ \since 6.2
+
+ Returns the version number of \QWE at run-time as a string
+ (for example, "6.2.0"). This may be a different version than the
+ version the application was compiled against, and a different version
+ than Qt.
+*/
+
+/*!
+ \fn const char *qWebEngineChromiumVersion() noexcept
+ \relates <qtwebenginecoreglobal.h>
+ \since 6.2
+
+ Returns the version number of Chromium used by \QWE at run-time
+ as a string (for example, "83.0.4103.122").
+*/
+
+/*!
+ \fn const char *qWebEngineChromiumSecurityPatchVersion() noexcept
+ \relates <qtwebenginecoreglobal.h>
+ \since 6.3
+
+ Returns the version number of last Chromium version security patches have been
+ merged from.
+*/
+
+/*!
+ \fn QString qWebEngineGetDomainAndRegistry(const QUrl &url)
+ \relates <qtwebenginecoreglobal.h>
+ \since 6.6
+
+ Returns the domain of the host, that is, the effective top-level domain
+ (eTLD) and the first domain below it, from \a url.
+
+ This function supports internationalized domain names (IDN). In this case,
+ it returns the domain encoded in Punycode.
+
+ If the host is not a domain, returns an empty string.
+*/
diff --git a/src/core/doc/src/qtwebengine-index.qdoc b/src/core/doc/src/qtwebengine-index.qdoc
new file mode 100644
index 000000000..b20a96dc1
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-index.qdoc
@@ -0,0 +1,47 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-index.html
+ \title Qt WebEngine
+
+ \brief Provides functionality for rendering regions of dynamic web content.
+
+ \QWE provides functionality for rendering regions of dynamic web content.
+
+ The functionality in \QWE is divided into the following modules:
+
+ \annotatedlist qtwebengine-modules
+
+ \section1 Articles and Guides
+
+ \list
+ \li \l{Qt WebEngine Overview}
+ \li \l{Qt WebEngine Features}
+ \li \l{Qt WebEngine Platform Notes}
+ \li \l{Qt WebEngine Licensing}
+ \li \l{Qt WebEngine Debugging and Profiling}
+ \li \l{Deploying Qt WebEngine Applications}
+ \li \l{Porting from Qt WebKit to Qt WebEngine}
+ \endlist
+
+
+ \section1 Module Evolution
+
+ \l{Changes to Qt WebEngine} lists important changes in the module API
+ and functionality that were done for the Qt 6 series of Qt.
+
+ \section1 Examples
+
+ \list
+ \li \l{Qt WebEngine Quick Examples}
+ \li \l{Qt WebEngine Widgets Examples}
+ \endlist
+
+ \section1 API References
+
+ \list
+ \li \l{Qt WebEngine C++ Classes and Namespaces}
+ \li \l{Qt WebEngine QML Types}
+ \endlist
+*/
diff --git a/src/core/doc/src/qtwebengine-modules.qdoc b/src/core/doc/src/qtwebengine-modules.qdoc
new file mode 100644
index 000000000..ee1ad8188
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-modules.qdoc
@@ -0,0 +1,25 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-modules.html
+ \title Qt WebEngine C++ Classes and Namespaces
+ \brief Provides functionality for rendering regions of dynamic web content.
+
+ \QWE provides functionality for rendering regions of dynamic web content.
+
+ \section1 Namespaces
+ \annotatedlist qtwebengine-namespaces
+
+ \section1 Classes
+
+ \section2 Qt WebEngine Core Module
+ \generatelist {classesbymodule QtWebEngineCore}
+
+ \section2 Qt WebEngine Widgets Module
+ \generatelist {classesbymodule QtWebEngineWidgets}
+
+ \section2 Qt WebEngine Quick Module
+ \generatelist {classesbymodule QtWebEngineQuick}
+
+*/
diff --git a/src/core/doc/src/qtwebengine-overview.qdoc b/src/core/doc/src/qtwebengine-overview.qdoc
new file mode 100644
index 000000000..6eccc669e
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-overview.qdoc
@@ -0,0 +1,307 @@
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-overview.html
+ \title Qt WebEngine Overview
+ \ingroup explanations-webtechnologies
+
+ The \QWE module provides a web browser engine that makes it easy to embed content from
+ the World Wide Web into your Qt application on platforms that do not have a native web engine.
+
+ \QWE provides C++ classes and QML types for rendering HTML, XHTML, and SVG documents,
+ styled using Cascading Style Sheets (CSS) and scripted with JavaScript. HTML documents can be
+ made fully editable by the user through the use of the \c{contenteditable} attribute on HTML
+ elements.
+
+ \section1 Qt WebEngine Architecture
+
+ \image qtwebengine-architecture.png
+
+ The functionality in \QWE is divided into the following modules:
+
+ \list
+ \li \l{Qt WebEngine Widgets Module} for creating widget-based web applications
+ \li \l{Qt WebEngine Module} for creating Qt Quick based web applications
+ \li \l{Qt WebEngine Core Module} for interacting with Chromium
+ \endlist
+
+ Page rendering and JavaScript execution are separated from the GUI process into the \QWE
+ Process. It is a library that must be shipped with the application if the Qt libraries are
+ bundled into the application.
+
+ \section2 Qt WebEngine Widgets Module
+
+ \image qtwebenginewidgets-model.png
+
+ A \e {web engine view} is the main widget component of the \QWE module. It can be used
+ in various applications to load web content. Within a view, a \e {web engine page} holds a main
+ frame that is responsible for web content, the \e history of navigated links, and \e actions.
+ The view and page are quite similar, as they provide a set of common functions.
+
+ All pages belong to a \e {web engine profile} that contains shared \e settings, \e scripts, and
+ \e cookies. Profiles can be used to isolate pages from each other. A typical use case is a
+ dedicated profile for a \e {private browsing} mode, where no information is permanently saved.
+
+ \note The \QWE Widgets module uses the \l{Qt Quick Scene Graph}{Qt Quick scene graph}
+ to compose the elements of a web page into one view. This means that the UI process
+ requires OpenGL ES 2.0 or OpenGL 2.0 for its rendering.
+
+ \section2 Qt WebEngine Module
+
+ \image qtwebengine-model.png
+
+ The \QWE QML implementation contains the same elements as the \QWE Widgets
+ implementation, except that there is no separately accessible web engine page.
+ The supported page functionality is integrated into the web engine view.
+
+ \section2 Qt WebEngine Core Module
+
+ The \QWE core is based on the \l {Chromium Project}. Chromium provides its own network
+ and painting engines and is developed tightly together with its dependent modules.
+ Even though the QtNetwork stack is not used, its setup can be synchronized with the \QWE.
+ See \l {Proxy Support}, \l {Managing Certificates}, \l {Client Certificates}, and
+ \l {QWebEngineCookieStore} for more details.
+
+ \note \QWE is based on Chromium, but does not contain or use any services
+ or add-ons that might be part of the Chrome browser that is built and delivered by Google.
+ You can find more detailed information about the differences between Chromium and Chrome in this
+ \l{https://chromium.googlesource.com/chromium/src/+/master/docs/chromium_browser_vs_google_chrome.md}{overview}
+ that is part of the documentation in the \l {Chromium Project} upstream source tree.
+
+ The Chromium version used is the one used by the latest stable Chrome version at the time of Qt feature freeze
+ for the current version of \QWE. Additional security patches are cherry picked from newer Chrome releases on
+ every patch release, security patches released in time for the Qt patch release freeze will be included.
+ If Chrome releases critical fixes outside our release window, the next patch release is sped up to ensure a
+ patched \QWE is released before the patch details goes public.
+
+ If you need a newer \QWE beyond security fixes, and can not update all of Qt, \QWE supports building with
+ older version of Qt back to the last Qt LTS. For instance \QWE 6.3, 6.4, and 6.5 can all be built with Qt 6.2.
+ In Qt LTS releases, \QWE may be fully replaced with such a newer version to make security patching easier.
+
+ The relevant Chromium versions in question can also be read at runtime using the
+ \l qWebEngineChromiumVersion() method, and \l qWebEngineChromiumSecurityPatchVersion()
+ to read the current security patch level. You can also find the versions in the \QWE
+ sources in the CHROMIUM_VERSION file.
+
+ \section2 Qt WebEngine Process
+
+ The \QWE Process is a separate executable that is used to render web pages and
+ execute JavaScript. This mitigates security issues and isolates crashes caused by specific
+ content.
+
+ \section1 Embedding Web Content into Widget Based Applications
+
+ Use the QWebEngineView class to display web pages in the simplest way. Because it is a widget,
+ you can embed QWebEngineView into your forms and use its convenience functions to download and
+ display web sites.
+
+ \code
+ QWebEngineView *view = new QWebEngineView(parent);
+ view->load(QUrl("http://www.qt.io/"));
+ view->show();
+ \endcode
+
+ An instance of QWebEngineView has one QWebEnginePage. QWebEnginePage can have a
+ QWebEngineHistory that provides access to the page's navigation history and several QAction
+ objects that apply actions on the web page. In addition, a QWebEnginePage has the ability to
+ run JavaScript code in the context of the page's main frame and to enable customization of
+ handlers for specific events like showing custom authentication dialogs.
+
+ Each QWebEnginePage belongs to a QWebEngineProfile that can have a QWebEngineSettings
+ for specifying page settings, a QWebEngineScriptCollection for running scripts on the page, and
+ a QWebEngineCookieStore for accessing the HTTP cookies of Chromium. A QWebEnginePage can also
+ directly point to a script collection.
+
+ For a widget based application, the web engine is automatically initialized, unless it is
+ placed in a plugin. In that case, it must be initialized in the application main source file
+ by using \l QtWebEngineQuick::initialize, as illustrated by the following code snippet:
+
+ \code
+ int main(int argc, char **argv)
+ {
+ QtWebEngineQuick::initialize();
+
+ QApplication app(argc, argv);
+
+ QMainWindow window;
+ window.show();
+
+ return app.exec();
+ }
+ \endcode
+
+ \section1 Embedding Web Content into Qt Quick Applications
+
+ The WebEngineView QML type allows Qt Quick applications to render regions of dynamic web
+ content. A \e{WebEngineView} type may share the screen with other QML types or encompass the
+ full screen as specified within the Qt Quick application.
+
+ To make sure that OpenGL context can be shared between the GUI and render processes, the web
+ engine must be initialized by using \l QtWebEngineQuick::initialize in the application main source
+ file, as illustrated by the following code snippet:
+
+ \code
+ int main(int argc, char *argv[])
+ {
+ QGuiApplication app(argc, argv);
+
+ QtWebEngineQuick::initialize();
+
+ QQmlApplicationEngine engine;
+ engine.load(QUrl("qrc:/main.qml"));
+
+ return app.exec();
+ }
+ \endcode
+
+ An application can load pages into the WebEngineView, using either an URL or HTML string, and
+ navigate within session history. By default, links to different pages load within the same
+ WebEngineView object, but web sites may request them to be opened as a new tab, window, or
+ dialog.
+
+ The following sample QML application loads a web page using the \l{WebEngineView::}{url}
+ property:
+
+ \quotefromfile minimal/main.qml
+ \skipto import
+ \printuntil /^\}/
+
+ \section1 Script Injection
+
+ \QWE does not allow direct access to the document object model (DOM) of a page.
+ However, the DOM can be inspected and adapted by injecting scripts.
+
+ The DOM of a page is constructed when the document is ready, typically
+ when the page is completely loaded. Therefore, executing scripts as soon as a document is
+ created is not suitable for DOM operations, where one has to wait until the DOM is ready.
+
+ In addition, an injected script shares the same \e world as the other scripts executed on the
+ page, which might lead to conflicts. To avoid this, the QWebEngineScript class and the
+ WebEngineScript QML type provide implementations of the Chromium API for
+ \e{Content Script Extensions}. They specify the
+ script to run, the injection point, and the world where the script is run. This enables
+ accessing the DOM to manipulate it within a world.
+
+ Since Qt 5.8, \QWE supports augmenting a script by using the
+ following \l{Metadata Block}{Greasemonkey-like attributes}:
+
+ \list
+ \li \c {@exclude <regexp>}
+ \li \c {@include <regexp>}
+ \li \c {@match <regexp>}
+ \li \c {@name <free text>}
+ \li \c {@run-at [document-start|document-end|document-idle]}
+ \endlist
+
+ The attributes determine if and when a \l {User Scripts}{user script} is
+ run. They must be placed immediately in the beginning of the script, inside
+ a \c ==UserScript== comment:
+
+ \code
+ // ==UserScript==
+ // @include http://*.qt.io/*
+ // @exclude http://wiki.qt.io/*
+ // ==/UserScript==
+
+ window.alert("Page is from qt.io, but not wiki.qt.io");
+ \endcode
+
+ If your WebEngine application is built using the Qt Quick Compiler, and the application ships
+ JavaScript files inside .qrc resources, consider reading the section
+ \l{JavaScript Files in Qt Resource Files}.
+
+ \section1 Managing Certificates
+
+ \QWE uses its own network stack, and therefore QSslConfiguration is not used to
+ open SSL connections. Instead, \QWE uses the root CA certificates from the operating
+ system to validate the peer's certificate.
+
+ The \l{WebEngineCertificateError::type} and \l{QWebEngineCertificateError::Type} enumerations
+ provide information about the types of certificate errors that might occur. The errors can be
+ handled by using the WebEngineView::certificateError QML method or by connecting to the
+ QWebEnginePage::certificateError signal.
+
+ \section1 Proxy Support
+
+ \QWE uses the proxy settings from \l{Qt Network}, and forwards them to Chromium's
+ networking stack. If QNetworkProxy::applicationProxy is set, it will also be used for \QWE.
+ If QNetworkProxyFactory::usesSystemConfiguration() is enabled, the proxy settings
+ are automatically retrieved from the system. Settings from an installed QNetworkProxyFactory
+ will be ignored, though.
+
+ In case QNetworkProxy::user() and QNetworkProxy::password() are set, these credentials
+ will be automatically used for proxy authentication. It is up to the user to provide valid
+ credentials, since there is no error handling callback.
+
+ If no credentials are set with QNetworkProxy, but the proxy requires authentication,
+ QWebEnginePage::proxyAuthenticationRequired is emitted.
+ For Qt Quick, a dialog is shown.
+
+ Not all properties of QNetworkProxy are supported by \QWE. That is,
+ QNetworkProxy::type(), QNetworkProxy::hostName() and QNetworkProxy::port() are taken into
+ account. All other proxy settings such as QNetworkProxy::rawHeader() are ignored.
+
+ \section1 High DPI Support
+
+ To support High DPI devices, it is recommended that the application attribute
+ Qt::AA_EnableHighDpiScaling is set to enable automatic scaling based on the
+ pixel density of the monitor. In \QWE applications, the scaling
+ affects the default zooming factor and scrollbar size.
+
+ For example:
+
+ \code
+ int main(int argc, char *argv[])
+ {
+ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+ QApplication app(argc, argv);
+ // ...
+ }
+ \endcode
+
+ \QWE bundles images for normal and high-dpi resolutions into
+ \e qtwebengine_resources_100p.pak and \e qtwebengine_resources_200p.pak
+ files. Depending on the target resolutions, one or both of these files need
+ to be deployed.
+
+ For more information, see \l{High DPI}.
+
+ \section1 Using WebEngine Core
+
+ \QWE Core provides an API shared by \QWE and \QWE Widgets for handling
+ URL requests issued for the networking stack of Chromium and for accessing its HTTP cookies.
+
+ Implementing the QWebEngineUrlRequestInterceptor interface and installing the interceptor on a
+ profile enables intercepting, blocking, and modifying URL requests (QWebEngineUrlRequestInfo)
+ before they reach the networking stack of Chromium.
+
+ A QWebEngineUrlSchemeHandler can be registered for a profile to add support for custom URL
+ schemes. Requests for the scheme are then issued to QWebEngineUrlSchemeHandler::requestStarted()
+ as QWebEngineUrlRequestJob objects.
+
+ The QWebEngineCookieStore class provides functions for accessing HTTP cookies of Chromium.
+ The functions can be used to synchronize cookies with QNetworkAccessManager, as well as to set,
+ delete, and intercept cookies during navigation.
+
+ \section1 Platform Notes
+
+ \QWE currently supports only Windows, Linux, and \macos. Due to Chromium build
+ requirements it also often requires a newer compiler than the rest of Qt. See
+ \l{Qt WebEngine Platform Notes} for further details.
+
+ \section1 Related Modules
+
+ \QWE supersedes the \l{http://doc.qt.io/archives/qt-5.3/qtwebkit-index.html}{Qt WebKit}
+ module, which is based on the
+ WebKit project, but has not been actively synchronized with the upstream WebKit code since
+ Qt 5.2 and has been deprecated in Qt 5.5. For tips on how to change a Qt \WebKit widgets
+ application to use \QWE widgets, see \l{Porting from Qt WebKit to Qt WebEngine}.
+
+ The \l{Qt WebView} module allows to use a native web browser on platforms where one is
+ available.
+
+ The \l{Qt WebChannel} module can be used to create a bi-directional communication channel
+ between QObject objects on the C++ side and JavaScript on the QML side.
+
+*/
diff --git a/src/core/doc/src/qtwebengine-platform-notes.qdoc b/src/core/doc/src/qtwebengine-platform-notes.qdoc
new file mode 100644
index 000000000..33bac101a
--- /dev/null
+++ b/src/core/doc/src/qtwebengine-platform-notes.qdoc
@@ -0,0 +1,223 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page qtwebengine-platform-notes.html
+ \title Qt WebEngine Platform Notes
+
+ \brief Contains information about issues that are specific to the \QWE module.
+
+ \section1 Building \QWE from Source
+
+ Static builds are not supported.
+
+ The requirements for building Qt modules from source are listed separately for each supported
+ platform:
+
+ \list
+ \li \l{Qt for Windows - Building from Source}
+ \li \l{Qt for X11 Requirements}
+ \li \l{Qt for macOS - Building from Source}
+ \endlist
+
+ In addition, the following tools are required for building the \l {Qt WebEngine} module:
+
+ \list
+ \li \l {All Platforms}
+ \li \l {Windows}
+ \li \l {Linux}
+ \li \l {macOS}
+ \endlist
+
+ \section2 All Platforms
+
+ On all platforms, the following tools are required at build time:
+
+ \list
+ \li C++20 compiler support
+ \li CMake 3.19 or newer
+ \li \l Python 3 with html5lib library
+ \li Bison, Flex
+ \li GPerf
+ \li Node.js version 14 or later
+ \endlist
+
+ \section2 Windows
+
+ On Windows, the following additional tools are required:
+
+ \list
+ \li Visual Studio 2019 or later, or clang-cl version 10 or later
+ \li Active Template Library (ATL), usually included in the Visual Studio
+ installation
+ \li Windows 11 SDK version 10.0.22621.0 or later
+ \endlist
+
+ \note It is not recommended to use tools from \c msys2 or \c cygwin to build \QWE as it may result in build errors.
+
+ \section2 Linux
+
+ On Linux, Clang or GCC version 9 or later is required.
+
+ \QWE requires \c pkg-config to detect most of its dependencies. The
+ following \c pkg-config files are required:
+
+ \list
+ \li \c dbus-1
+ \li \c fontconfig
+ \endlist
+
+ If Qt was configured for \c xcb, the following \c pkg-config files are also
+ required:
+
+ \list
+ \li \c libdrm
+ \li \c xcomposite
+ \li \c xcursor
+ \li \c xi
+ \li \c xrandr
+ \li \c xscrnsaver
+ \li \c xtst
+ \endlist
+
+ \section2 \macos
+
+ On \macos, the following are required:
+
+ \list
+ \li \macos 10.14 or later
+ \li Xcode 12.0 or later
+ \li \macos 11 SDK or later
+ \endlist
+
+ \note \QWE cannot be built for the 32-bit mode of \macos (using the
+ \c macx-clang-32 \c mkspec).
+
+ \section1 Using Earlier Qt Versions to Build \QWE
+
+ Building \QWE with earlier Qt versions (down to the last LTS
+ version) is supported. It means that \QWE 6.4 can be built with
+ Qt 6.2.x, Qt 6.3.x, and Qt 6.4.
+
+ To use an earlier Qt version to build Qt Webengine:
+
+ \list 1
+ \li Download the qtwebengine sources.
+ \li From the earlier Qt version, run
+ \c {qmake && make (&& make install)}.
+ \endlist
+
+ \section1 Mac App Store Compatibility
+
+ Applications using \QWE are not compatible with the Mac App Store, because:
+
+ \list
+ \li The Chromium part of the code uses several private API methods, which are prohibited by
+ the App Store.
+ \li Applications submitted to the App Store must be code-signed with the App Sandbox feature
+ enabled. The App Sandbox feature interferes with Chromium's own sandbox
+ initialization, which results in Chromium not being properly initialized. This also
+ ties in with the private API usage. Furthermore, standalone Chromium itself is not
+ officially tested with the App Sandbox enabled, and even if work is done to bypass
+ the App Store's restrictions, that would not guarantee correct behavior of the library.
+
+ \endlist
+
+ \section1 macOS Airplay Support on MacBooks with Dual GPUs
+
+ To make \QWE work correctly when streaming to an AppleTV from a MacBook that supports
+ GPU switching, it is important to add the \c NSSupportsAutomaticGraphicsSwitching option to the
+ application Info.plist file, with the value set to \c YES. Otherwise rendering issues might
+ occur when creating new web engine view instances after Airplay is switched on or off.
+
+ \section1 Default QSurfaceFormat OpenGL Profile Support
+
+ If a new default QSurfaceFormat with a modified OpenGL profile has to be set, it should be set
+ before the application instance is declared, to make sure that all created OpenGL contexts use
+ the same OpenGL profile.
+
+ On \macos, if the default QSurfaceFormat is set after the application instance, the application
+ will exit with qFatal(), and print a message that the default QSurfaceFormat should be set
+ before the application instance.
+
+ \section1 Sandboxing Support
+
+ \QWE provides out-of-the-box sandboxing support for Chromium render
+ processes.
+
+ On Linux, note the following restrictions:
+
+ \list
+ \li The kernel has to support the anonymous namespaces feature
+ (kernel version 3.8 or later). However, on Debian, Ubuntu,
+ and other Debian-derived distributions, this feature is off
+ by default. It can be turned on by setting
+ \c /proc/sys/kernel/unprivileged_userns_clone to 1.
+ \li The kernel has to support the \c seccomp-bpf feature (kernel
+ version 3.5 or later).
+ \li Setuid sandboxes are not supported and are thus disabled.
+ \endlist
+
+ To explicitly disable sandboxing, use one of the following options:
+
+ \list
+ \li Set the \c QTWEBENGINE_DISABLE_SANDBOX environment variable to 1.
+ \li Pass the \c{--no-sandbox} command line argument to the user
+ application executable.
+ \li Set \c QTWEBENGINE_CHROMIUM_FLAGS to \c{--no-sandbox}.
+ \endlist
+
+ For more information, see \l{Using Command-Line Arguments}.
+
+ \section1 Memory Requirements in Docker Environment
+
+ When running Qt Web Engine examples in a Docker container and browsing
+ content-heavy sites, BUS errors (SIGBUS) might be reported. Typically,
+ this is caused by Docker running a container with a too small memory space
+ (such as 64MB). To fix this problem, increase the memory space size.
+
+ \section1 Accessibility and Performance
+
+ \QWE enables accessibility support for web pages when the following conditions
+ are met:
+
+ \list
+ \li Qt Core is configured and built with accessibility support enabled.
+ \li The QPA plugin is notified by the operating system that accessibility should be
+ activated. This happens for example when using a screen reader application on Windows
+ or VoiceOver on \macos.
+ \endlist
+
+ On some old Linux configurations, accessibility can cause a significant slowdown
+ on large HTML pages.
+
+ Because of that, \QWE accessibility support can be disabled on Linux, by setting the
+ \c QTWEBENGINE_ENABLE_LINUX_ACCESSIBILITY environment variable to 0.
+
+ \section1 Popups in Fullscreen Applications on Windows
+ Because of a limitation in the Windows compositor, applications that show a fullscreen web
+ engine view will not properly display popups or other top-level windows. The reason and
+ workaround is described in \l {Fullscreen OpenGL Based Windows}.
+
+ \target windows_manifest
+ \section1 Windows Application Manifest
+ A manifest is an XML file that is read when the program starts and informs Windows how to run the program.
+ Some \QWE features may require adding a manifest file for the user application to work correctly on Windows.
+
+ The following snippets show the manifest file's structure and how to embed it into the program.
+
+ \note These code snippets are taken from the \l {WebEngine Quick Nano Browser} example.
+
+ The manifest file defines which Windows versions the application supports.
+ \l {QWebEngineProfile::} {httpUserAgent} needs this information to report the correct Windows version.
+ \quotefile ../../../../examples/webenginequick/quicknanobrowser/quicknanobrowser.exe.manifest
+
+ To embed the file into the executable, add it to the sources:
+ \quotefromfile ../../../../examples/webenginequick/quicknanobrowser/CMakeLists.txt
+ \skipto qt_add_executable
+ \dots
+ \printuntil endif
+ \dots
+
+ For more information, see the \l {https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests} {Application manifest documentation page}.
+*/
diff --git a/src/core/doc/src/qtwebenginecore-index.qdoc b/src/core/doc/src/qtwebenginecore-index.qdoc
index 692e33d1d..e6fc0b307 100644
--- a/src/core/doc/src/qtwebenginecore-index.qdoc
+++ b/src/core/doc/src/qtwebenginecore-index.qdoc
@@ -1,49 +1,26 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page qtwebenginecore-index.html
\title Qt WebEngine Core
- \brief Provides common API shared by \QWE and \QWE Widgets.
+ \brief Provides common API shared by \QWE Quick and \QWE Widgets.
- \QWE Core provides API shared by \l {Qt WebEngine} and \l {Qt WebEngine Widgets}.
+ \QWE Core provides API shared by \l {Qt WebEngine QML Types}{Qt WebEngine Quick} and
+ \l {Qt WebEngine Widgets C++ Classes}{Qt WebEngine Widgets}.
\section1 Getting Started
- To include the definitions of the module's classes, use the
- following directive:
-
- \snippet qtwebenginecore_build_snippet.qdoc 1
-
To link against the module, add this line to your qmake project file:
\snippet qtwebenginecore_build_snippet.qdoc 0
+ For build with CMake use the \c find_package() command to locate the needed module components
+ in the Qt6 package and \c target_link_libraries() to link against the module:
+
+ \snippet qtwebenginecore_build_snippet.qdoc 2
+
\section1 Articles and Guides
\list
diff --git a/src/core/doc/src/qtwebenginecore-module.qdoc b/src/core/doc/src/qtwebenginecore-module.qdoc
index c976d024c..188609793 100644
--- a/src/core/doc/src/qtwebenginecore-module.qdoc
+++ b/src/core/doc/src/qtwebenginecore-module.qdoc
@@ -1,53 +1,32 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\module QtWebEngineCore
\title Qt WebEngine Core C++ Classes
- \brief Provides public API shared by both QtWebEngine and QtWebEngineWidgets.
+ \brief Provides public API shared by both QtWebEngineQuick and QtWebEngineWidgets.
\since 5.6
\ingroup qtwebengine-modules
\ingroup modules
-
- To include the definitions of the module's classes, use the
- following directive:
-
- \snippet qtwebenginecore_build_snippet.qdoc 1
+ \qtvariable webenginecore
+ \qtcmakepackage WebEngineCore
If you use qmake to build your projects, \QWE Core is usually
- indirectly included through the \l{Qt WebEngine QML Types}{Qt WebEngine} or
+ indirectly included through the \l{Qt WebEngine QML Types}{Qt WebEngine Quick} or
\l{Qt WebEngine Widgets C++ Classes}{Qt WebEngine Widgets} modules.
\if !defined(qtforpython)
- To link against the module, add this line to your qmake project file:
+ To link against the module using build with qmake,
+ add this line to your qmake project file:
\snippet qtwebenginecore_build_snippet.qdoc 0
- However, \c webenginecore is implied by adding \c webengine or \c webenginewidgets.
+ However, \c webenginecore is implied by adding \c webenginequick or \c webenginewidgets.
+
+ For build with CMake use the \c find_package() command to locate the needed module components
+ in the Qt6 package and \c target_link_libraries() to link against the module:
+
+ \snippet qtwebenginecore_build_snippet.qdoc 2
\endif
*/
diff --git a/src/core/doc/src/qwebengine-licensing.qdoc b/src/core/doc/src/qwebengine-licensing.qdoc
new file mode 100644
index 000000000..796a9664d
--- /dev/null
+++ b/src/core/doc/src/qwebengine-licensing.qdoc
@@ -0,0 +1,34 @@
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+\group qtwebengine-licensing
+\title Qt WebEngine Licensing
+
+The Qt specific parts of the \QWE module are dual-licensed
+under Commercial and GNU Lesser General Public License (LGPLv3).
+In addition, the module contains code licensed under LGPLv2.
+
+The module includes a snapshot of Chromium. As such, users need to
+respect the licenses of Chromium, and third-party code included in
+Chromium. The arguably most restrictive license to be respected by
+all users is LGPLv2.1.
+
+\note Any GPL licenses listed below are only used to access Linux system
+resources. \QWE does not link to nor distribute GPL binary code, and
+it does not affect users of \QWE.
+
+Third party licenses included in the sources are:
+*/
+
+/*!
+\page qtwebengine-3rdparty-chromium-global.html
+\attribution
+\ingroup qtwebengine-licensing
+\title Chromium License
+\brief BSD
+
+The Google-authored portion of Chromium is released under a BSD license:
+
+\quotefile ../../../3rdparty/chromium/LICENSE
+*/
diff --git a/src/core/doc/src/qwebenginehistory_lgpl.qdoc b/src/core/doc/src/qwebenginehistory_lgpl.qdoc
new file mode 100644
index 000000000..f61bb3b85
--- /dev/null
+++ b/src/core/doc/src/qwebenginehistory_lgpl.qdoc
@@ -0,0 +1,272 @@
+// Copyright (C) 2015 The Qt Company Ltd.
+// Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+// The documentation in this file was imported from QtWebKit and is thus constrained
+// by its LGPL license. Documentation written from scratch for new methods should be
+// placed inline in the code as usual.
+
+/*!
+ \class QWebEngineHistoryItem
+ \brief The QWebEngineHistoryItem class represents one item in the history of a web engine page.
+ \since 5.4
+ \inmodule QtWebEngineCore
+
+ Each web engine history item represents an entry in the history stack of a web page,
+ containing information about the page, its location, and the time when it was last visited.
+
+ \sa QWebEngineHistory, QWebEnginePage::history()
+*/
+
+/*!
+ \fn QWebEngineHistoryItem::QWebEngineHistoryItem(const QWebEngineHistoryItem &other)
+ Constructs a history item from \a other. The new item and \a other
+ will share their data, and modifying either this item or \a other will
+ modify both instances.
+*/
+
+/*!
+ \fn QWebEngineHistoryItem &QWebEngineHistoryItem::operator=(const QWebEngineHistoryItem &other)
+ Assigns the \a other history item to this. This item and \a other
+ will share their data, and modifying either this item or \a other will
+ modify both instances.
+*/
+
+/*!
+ \fn QWebEngineHistoryItem::~QWebEngineHistoryItem()
+ Destroys the history item.
+*/
+
+/*!
+ \fn QUrl QWebEngineHistoryItem::originalUrl() const
+ Returns the original URL associated with the history item.
+
+ \sa url()
+*/
+
+/*!
+ \fn QUrl QWebEngineHistoryItem::url() const
+ Returns the URL associated with the history item.
+
+ \sa originalUrl(), title(), lastVisited()
+*/
+
+/*!
+ \fn QString QWebEngineHistoryItem::title() const
+ Returns the title of the page associated with the history item.
+
+ \sa url(), lastVisited()
+*/
+
+/*!
+ \fn QDateTime QWebEngineHistoryItem::lastVisited() const
+ Returns the date and time when the page associated with the item was last visited.
+
+ \sa title(), url()
+*/
+
+/*!
+ \fn bool QWebEngineHistoryItem::isValid() const
+ Returns whether this is a valid history item.
+*/
+
+/*!
+ \class QWebEngineHistoryModel
+ \inmodule QtWebEngineCore
+ \since 6.2
+
+ \brief A data model that represents the history of a web engine page.
+
+ The QWebEngineHistoryModel type exposes the \e title, \e url, \e icon, and \e offset roles.
+ The \e title, \e url and \e icon specify the title, URL, and favicon of the visited page.
+ The \e offset specifies the position of the page in respect to the current page (0).
+ A positive number indicates that the page was visited after the current page, whereas a
+ negative number indicates that the page was visited before the current page.
+
+ This type is uncreatable, but it can be accessed by using the QWebEngineHistory::itemsModel,
+ QWebEngineHistory::backItemsModel, QWebEngineHistory::forwardItemsModel methods.
+
+ \sa QWebEngineHistory
+*/
+
+/*!
+ \enum QWebEngineHistoryModel::Roles
+
+ This enum describes specific roles, which history data model supports.
+
+ \value UrlRole URL of the visited page
+ \value TitleRole Title of the visited page
+ \value OffsetRole The offset of the page in respect to the current page (0)
+ \value IconUrlRole Favicon of the visited page
+*/
+
+/*!
+ \class QWebEngineHistory
+ \brief The QWebEngineHistory class represents the history of a web engine page.
+ \since 5.4
+ \inmodule QtWebEngineCore
+
+ Each web engine page contains a history of visited pages that can be accessed
+ by QWebEnginePage::history().
+
+ The history uses the concept of a \e{current item}, dividing the pages visited
+ into those that can be visited by navigating \e back and \e forward using the
+ back() and forward() functions. The current item can be obtained by calling
+ currentItem(), and an arbitrary item in the history can be made the current
+ item by passing it to goToItem().
+
+ A list of items describing the pages that can be visited by going back can be
+ obtained by calling the backItems() function; similarly, items describing the
+ pages ahead of the current page can be obtained with the forwardItems() function.
+ The total list of items is obtained with the items() function.
+
+ Also, the following QWebEngineHistoryModel data model objects are provided:
+
+ \list
+ \li \c backItemsModel(), which contains the URLs of visited pages.
+ \li \c forwardItemsModel(), which contains the URLs of the pages that were visited after visiting
+ the current page.
+ \li \c itemsModel(), which contains the URLs of the back and forward items, as well as the URL of
+ the current page.
+ \endlist
+
+ Just as with containers, functions are available to examine the history in terms
+ of a list. Arbitrary items in the history can be obtained with itemAt(), the total
+ number of items is given by count(), and the history can be cleared with the
+ clear() function.
+
+ QWebEngineHistory's state can be saved to a QDataStream using the >> operator and loaded
+ by using the << operator.
+
+ \sa QWebEngineHistoryItem, QWebEnginePage
+*/
+
+/*!
+ \fn void QWebEngineHistory::clear()
+ Clears the history.
+
+ \sa count(), items()
+*/
+
+/*!
+ \fn QList<QWebEngineHistoryItem> QWebEngineHistory::items() const
+ Returns a list of all items currently in the history.
+
+ \sa count(), clear()
+*/
+
+/*!
+ \fn QList<QWebEngineHistoryItem> QWebEngineHistory::backItems(int maxItems) const
+ Returns the list of items in the backwards history list.
+ At most \a maxItems entries are returned.
+
+ \sa forwardItems()
+*/
+
+/*!
+ \fn QList<QWebEngineHistoryItem> QWebEngineHistory::forwardItems(int maxItems) const
+ Returns the list of items in the forward history list.
+ At most \a maxItems entries are returned.
+
+ \sa backItems()
+*/
+
+/*!
+ \fn QWebEngineHistoryModel *QWebEngineHistory::itemsModel() const
+ Returns the data model, which represents URLs of back items, forward items,
+ and the current item in the history.
+*/
+
+/*!
+ \fn QWebEngineHistoryModel *QWebEngineHistory::backItemsModel() const
+ Return the data model, which represents URLs of visited pages.
+*/
+
+/*!
+ \fn QWebEngineHistoryModel *QWebEngineHistory::forwardItemsModel() const
+ Return the data model, which represents URLs of the pages
+ that were visited after visiting the current page.
+*/
+
+/*!
+ \fn bool QWebEngineHistory::canGoBack() const
+ Returns \c true if there is an item preceding the current item in the history;
+ otherwise returns \c false.
+
+ \sa canGoForward()
+*/
+
+/*!
+ \fn bool QWebEngineHistory::canGoForward() const
+ Returns \c true if we have an item to go forward to; otherwise returns \c false.
+
+ \sa canGoBack()
+*/
+
+/*!
+ \fn void QWebEngineHistory::back()
+ Sets the current item to be the previous item in the history and goes to the
+ corresponding page; that is, goes back one history item.
+
+ \sa forward(), goToItem()
+*/
+
+/*!
+ \fn void QWebEngineHistory::forward()
+ Sets the current item to be the next item in the history and goes to the
+ corresponding page; that is, goes forward one history item.
+
+ \sa back(), goToItem()
+*/
+
+/*!
+ \fn void QWebEngineHistory::goToItem(const QWebEngineHistoryItem &item)
+ Sets the current item to be the specified \a item in the history and goes to the page.
+
+ \sa back(), forward()
+*/
+
+/*!
+ \fn QWebEngineHistoryItem QWebEngineHistory::backItem() const
+ Returns the item before the current item in the history.
+*/
+
+/*!
+ \fn QWebEngineHistoryItem QWebEngineHistory::currentItem() const
+ Returns the current item in the history.
+*/
+
+/*!
+ \fn QWebEngineHistoryItem QWebEngineHistory::forwardItem() const
+ Returns the item after the current item in the history.
+*/
+
+/*!
+ \fn int QWebEngineHistory::currentItemIndex() const
+ Returns the index of the current item in history.
+*/
+
+/*!
+ \fn QWebEngineHistoryItem QWebEngineHistory::itemAt(int i) const
+ Returns the item at index \a i in the history.
+*/
+
+/*!
+ \fn int QWebEngineHistory::count() const
+ Returns the total number of items in the history.
+*/
+
+/*!
+ \fn QDataStream& operator<<(QDataStream& stream, const QWebEngineHistory& history)
+ \relates QWebEngineHistory
+
+ Saves the web engine history \a history into \a stream.
+*/
+
+
+/*!
+ \fn QDataStream& operator>>(QDataStream& stream, QWebEngineHistory& history)
+ \relates QWebEngineHistory
+
+ Loads the web engine history from \a stream into \a history.
+*/
diff --git a/src/core/doc/src/qwebenginepage_lgpl.qdoc b/src/core/doc/src/qwebenginepage_lgpl.qdoc
new file mode 100644
index 000000000..c2515cd13
--- /dev/null
+++ b/src/core/doc/src/qwebenginepage_lgpl.qdoc
@@ -0,0 +1,838 @@
+// Copyright (C) 2019 The Qt Company Ltd.
+// Copyright (C) 2008, 2009, 2012 Nokia Corporation and/or its subsidiary(-ies)
+// Copyright (C) 2007 Staikos Computing Services Inc.
+// Copyright (C) 2007 Apple Inc.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+// The documentation in this file was imported from QtWebKit and is thus constrained
+// by its LGPL license. Documentation written from scratch for new methods should be
+// placed inline in the code as usual.
+
+/*!
+ \class QWebEnginePage
+ \brief The QWebEnginePage class provides an object to view and edit web documents.
+ \since 5.4
+ \inmodule QtWebEngineCore
+
+ A \e {web engine page} holds the contents of an HTML document, the history of navigated
+ links, and actions.
+
+ QWebEnginePage's API is very similar to QWebEngineView, as you are still provided with
+ common functions like action() (known as
+ \l{QWebEngineView::pageAction()}{pageAction}() in QWebEngineView), triggerAction(),
+ and findText().
+
+ A page can be loaded using load() or setUrl(). Alternatively, if you have
+ the HTML content readily available, you can use setHtml(). The GET method is
+ always used to load URLs.
+
+ The QWebEnginePage class also offers methods to retrieve both the URL currently
+ loaded by the page (see url()) as well as the URL originally requested
+ to be loaded (see requestedUrl()). These methods make possible the retrieval
+ of the URL before and after a DNS resolution or a redirection occurs during
+ the load process. The requestedUrl() also matches to the URL added to the
+ page history (\l{QWebEngineHistory}) if load is successful.
+
+ The title of an HTML page can be accessed with the title() property.
+ Additionally, a page may also specify an icon, which can be accessed
+ using the icon() or its URL using the iconUrl() property.
+ If the title or the icon changes, the corresponding titleChanged(), iconChanged()
+ and iconUrlChanged() signals will be emitted.
+ The zoomFactor() property enables zooming the contents of the web page by a
+ scale factor.
+
+ The loadStarted() signal is emitted when the page begins to load, whereas the loadProgress()
+ signal is emitted whenever an element of the web page completes loading, such as an embedded
+ image or a script. The loadFinished() signal is emitted when the page contents
+ have been loaded completely, independent of script execution or page rendering.
+ Its argument, either \c true or \c false, indicates whether or not the load
+ operation succeeded.
+
+ An HTML document is loaded in a \e {main frame} within the web page. If it references
+ \e {child frames} (as defined by the \c <frame> or \c <iframe> elements), they are considered
+ part of the content. Child frames are individually accessible only through JavaScript.
+
+ Web sites define \e {security origin} for safely accessing each other's resources for
+ client-side scripting or databases. An origin consist of a host name, a scheme, and a port
+ number. For example, the sites \c http://www.example.com/my/page.html and
+ \c http://www.example.com/my/overview.html are allowed to share the same database or access
+ each other's documents when used in HTML frame sets and JavaScript. At the same time,
+ \c http://www.malicious.com/evil.html is prevented from accessing the resources of
+ \c http://www.example.com/, because they are of a different security origin.
+ By default, local schemes like \c file:// and \c qrc:// are considered to be in the same
+ security origin, and can access each other's resources. Local resources are by default
+ restricted from accessing remote content, which means that \c file:// will not be able to
+ access \c http://domain.com/foo.html.
+
+ Scripts can be executed on the web page by using runJavaScript(), either in the main
+ JavaScript \e world, along with the rest of the JavaScript coming from the web contents, or in
+ their own isolated world. While the DOM of the page can be accessed from any world, JavaScript
+ variables of a function defined in one world are not accessible from a different one.
+ QWebEngineScript::ScriptWorldId provides some predefined IDs for this purpose. Using the
+ \c runJavaScript() version without the world ID is the same as running the script in the
+ \c MainWorld.
+
+ The \l {QWebEngineSettings::FocusOnNavigationEnabled} {FocusOnNavigationEnabled} setting can be
+ used to make the view associated with the page automatically receive focus when a navigation
+ operation occurs (like loading or reloading a page or navigating through history).
+*/
+
+/*!
+ \enum QWebEnginePage::FindFlag
+
+ This enum describes the options available to the findText() function. The options
+ can be OR-ed together from the following list:
+
+ \value FindBackward Searches backwards instead of forwards.
+ \value FindCaseSensitively By default findText() works case insensitive. Specifying this option
+ changes the behavior to a case sensitive find operation.
+*/
+
+/*!
+ \enum QWebEnginePage::WebAction
+
+ This enum describes the types of action which can be performed on the web page.
+
+ Actions only have an effect when they are applicable.
+
+ The availability of actions can be be determined by checking
+ \l{QAction::}{isEnabled()} on the action returned by action().
+
+ \value NoWebAction No action is triggered.
+ \value Back Navigate back in the history of navigated links.
+ \value Forward Navigate forward in the history of navigated links.
+ \value Stop Stop loading the current page.
+ \value Reload Reload the current page.
+ \value ReloadAndBypassCache Reload the current page, but do not use any local cache.
+ \value Cut Cut the content currently selected into the clipboard.
+ \value Copy Copy the content currently selected into the clipboard.
+ \value Paste Paste content from the clipboard.
+ \value Undo Undo the last editing action.
+ \value Redo Redo the last editing action.
+ \value SelectAll Select all content. This action is only enabled when the page's content is focused.
+ The focus can be forced by the JavaScript \c{window.focus()} call, or the
+ \l{QWebEngineSettings::FocusOnNavigationEnabled} {FocusOnNavigationEnabled} setting
+ should be enabled to get automatic focus.
+ \value PasteAndMatchStyle Paste content from the clipboard with current style.
+
+ \value [since 5.6] OpenLinkInThisWindow Open the current link in the current window.
+ \value [since 5.6] OpenLinkInNewWindow Open the current link in a new window. Requires implementation of
+ \l createWindow() or \l newWindowRequested().
+ \value [since 5.6] OpenLinkInNewTab Open the current link in a new tab. Requires implementation of
+ \l createWindow() or \l newWindowRequested().
+ \value [since 5.7] OpenLinkInNewBackgroundTab Open the current link in a new background tab. Requires
+ implementation of \l createWindow() or \l newWindowRequested().
+ \value [since 5.6] CopyLinkToClipboard Copy the current link to the clipboard.
+
+ \value [since 5.6] CopyImageToClipboard Copy the clicked image to the clipboard.
+ \value [since 5.6] CopyImageUrlToClipboard Copy the clicked image's URL to the clipboard.
+ \value [since 5.6] CopyMediaUrlToClipboard Copy the hovered audio or video's URL to the clipboard.
+ \value [since 5.6] ToggleMediaControls Toggle between showing and hiding the controls for the hovered audio
+ or video element.
+ \value [since 5.6] ToggleMediaLoop Toggle whether the hovered audio or video should loop on completetion or
+ not.
+ \value [since 5.6] ToggleMediaPlayPause Toggle the play/pause state of the hovered audio or video element.
+ \value [since 5.6] ToggleMediaMute Mute or unmute the hovered audio or video element.
+ \value [since 5.6] DownloadLinkToDisk Download the current link to the disk. Requires a slot for
+ \l{QWebEngineProfile::}{downloadRequested()}.
+ \value [since 5.6] DownloadImageToDisk Download the highlighted image to the disk. Requires a slot for
+ \l{QWebEngineProfile::}{downloadRequested()}.
+ \value [since 5.6] DownloadMediaToDisk Download the hovered audio or video to the disk. Requires a slot for
+ \l{QWebEngineProfile::}{downloadRequested()}.
+
+ \value [since 5.6] InspectElement Trigger any attached Web Inspector to inspect the highlighed element.
+ \value [since 5.6] ExitFullScreen Exit the fullscreen mode.
+ \value [since 5.6] RequestClose Request to close the web page. If defined, the \c{window.onbeforeunload}
+ handler is run, and the user can confirm or reject to close the page. If the close
+ request is confirmed, \c windowCloseRequested is emitted.
+ \value [since 5.7] Unselect Clear the current selection.
+ \value [since 5.7] SavePage Save the current page to disk. MHTML is the default format that is used to store
+ the web page on disk. Requires a slot for \l{QWebEngineProfile::}{downloadRequested()}.
+ \value [since 5.8] ViewSource Show the source of the current page in a new tab. Requires implementation of
+ \l createWindow() or \l newWindowRequested().
+
+ \value [since 5.10] ToggleBold
+ Toggles boldness for the selection or at the cursor position.
+ Requires \c contenteditable="true".
+ \value [since 5.10] ToggleItalic
+ Toggles italics for the selection or at the cursor position.
+ Requires \c contenteditable="true".
+ \value [since 5.10] ToggleUnderline
+ Toggles underlining of the selection or at the cursor position.
+ Requires \c contenteditable="true".
+ \value [since 5.10] ToggleStrikethrough
+ Toggles striking through the selection or at the cursor position.
+ Requires \c contenteditable="true".
+
+ \value [since 5.10] AlignLeft
+ Aligns the lines containing the selection or the cursor to the left.
+ Requires \c contenteditable="true".
+ \value [since 5.10] AlignCenter
+ Aligns the lines containing the selection or the cursor at the center.
+ Requires \c contenteditable="true".
+ \value [since 5.10] AlignRight
+ Aligns the lines containing the selection or the cursor to the right.
+ Requires \c contenteditable="true".
+ \value [since 5.10] AlignJustified
+ Stretches the lines containing the selection or the cursor so that each
+ line has equal width.
+ Requires \c contenteditable="true".
+ \value [since 5.10] Indent
+ Indents the lines containing the selection or the cursor.
+ Requires \c contenteditable="true".
+ \value [since 5.10] Outdent
+ Outdents the lines containing the selection or the cursor.
+ Requires \c contenteditable="true".
+
+ \value [since 5.10] InsertOrderedList
+ Inserts an ordered list at the current cursor position, deleting the current selection.
+ Requires \c contenteditable="true".
+ \value [since 5.10] InsertUnorderedList
+ Inserts an unordered list at the current cursor position,
+ deleting the current selection.
+ Requires \c contenteditable="true".
+ \value [since 6.6] ChangeTextDirectionLTR
+ Changes text direction to left-to-right in the focused input element.
+ \value [since 6.6] ChangeTextDirectionRTL
+ Changes text direction to right-to-left in the focused input element.
+ \omitvalue WebActionCount
+
+*/
+
+/*!
+ \enum QWebEnginePage::WebWindowType
+
+ This enum describes the types of window that can be created by the createWindow() function:
+
+ \value WebBrowserWindow
+ A complete web browser window.
+ \value WebBrowserTab
+ A web browser tab.
+ \value WebDialog
+ A window without decoration.
+ \value [since 5.7] WebBrowserBackgroundTab
+ A web browser tab without hiding the current visible WebEngineView.
+*/
+
+/*!
+ \enum QWebEnginePage::JavaScriptConsoleMessageLevel
+
+ This enum describes the different severity levels a JavaScript console message can have:
+
+ \value InfoMessageLevel The message is purely informative and can safely be ignored.
+ \value WarningMessageLevel The message informs about unexpected behavior or errors that may
+ need attention.
+ \value ErrorMessageLevel The message indicates there has been an error.
+*/
+
+/*!
+ \enum QWebEnginePage::FileSelectionMode
+
+ This enum indicates whether the implementation of the chooseFiles() function should
+ return only one file or may return multiple files:
+
+ \value FileSelectOpen
+ Return only one file name.
+ \value FileSelectOpenMultiple
+ Return multiple file names.
+ \value FileSelectUploadFolder
+ Allows users to specify a single existing folder for upload.
+ \value FileSelectSave
+ Specify a new file to be created.
+
+ \sa chooseFiles()
+*/
+
+/*!
+ \enum QWebEnginePage::PermissionPolicy
+
+ This enum describes the permission policies that the user may set for data or device access:
+
+ \value PermissionUnknown It is unknown whether the user grants or denies permission.
+ \value PermissionGrantedByUser The user has granted permission.
+ \value PermissionDeniedByUser The user has denied permission.
+
+ \sa featurePermissionRequested(), featurePermissionRequestCanceled(), setFeaturePermission(), Feature
+*/
+
+/*!
+ \enum QWebEnginePage::NavigationType
+
+ This enum describes the type of a navigation request:
+
+ \value NavigationTypeLinkClicked The navigation request resulted from a clicked link.
+ \value NavigationTypeTyped The navigation request resulted from an explicitly loaded URL.
+ \value NavigationTypeFormSubmitted The navigation request resulted from a form submission.
+ \value NavigationTypeBackForward The navigation request resulted from a back or forward action.
+ \value NavigationTypeReload The navigation request resulted from a reload action.
+ \value [since 5.14] NavigationTypeRedirect The navigation request resulted from a content or server controlled redirect. This also includes automatic reloads.
+ \value NavigationTypeOther The navigation request was triggered by other means not covered by the above.
+
+ \sa acceptNavigationRequest()
+*/
+
+/*!
+ \enum QWebEnginePage::Feature
+
+ This enum describes the platform feature access categories that the user may be asked to grant
+ or deny access to:
+
+ \value Notifications
+ Web notifications for the end-user.
+ \value Geolocation
+ Location hardware or service.
+ \value MediaAudioCapture
+ Audio capture devices, such as microphones.
+ \value MediaVideoCapture
+ Video devices, such as cameras.
+ \value MediaAudioVideoCapture
+ Both audio and video capture devices.
+ \value MouseLock
+ Mouse locking, which locks the mouse pointer to the web view and is typically used in
+ games.
+ \value [since 5.10] DesktopVideoCapture
+ Video output capture, that is, the capture of the user's display,
+ for screen sharing purposes for example.
+ \value [since 5.10] DesktopAudioVideoCapture
+ Both audio and video output capture.
+ \value [since 6.8] ClipboardReadWrite
+ Read and write access for the clipboard. If both \l{QWebEngineSettings::JavascriptCanPaste}
+ {JavascriptCanPaste} and \l{QWebEngineSettings::JavascriptCanAccessClipboard}
+ {JavascriptCanAccessClipboard} settings are enabled, this permission will always be granted
+ automatically and no feature requests will be made.
+ \value [since 6.8] LocalFontsAccess
+ Access to the fonts installed on the user's machine. Only available on desktop platforms.
+
+ \sa featurePermissionRequested(), featurePermissionRequestCanceled(), setFeaturePermission(), PermissionPolicy
+
+*/
+
+/*!
+ \fn QWebEnginePage::QWebEnginePage(QObject *parent)
+ Constructs an empty QWebEnginePage with the parent \a parent.
+*/
+
+/*!
+ \fn QWebEnginePage::~QWebEnginePage()
+ Destroys the web page.
+*/
+
+/*!
+ \fn QWebEngineHistory *QWebEnginePage::history() const
+ Returns a pointer to the view's history of navigated web pages.
+*/
+
+/*!
+ \fn void QWebEnginePage::javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString& message, int lineNumber, const QString& sourceID)
+ This function is called when a JavaScript program tries to print the \a message to the web
+ browser's console.
+
+ For example, in case of evaluation errors the source URL may be provided in \a sourceID as well
+ as the \a lineNumber.
+
+ \a level indicates the severity of the event that triggered the message. That is, whether it
+ was triggered by an error or a less severe event.
+
+ Since Qt 5.6, the default implementation logs the messages in a \c js
+ \l{QLoggingCategory}{logging category}.
+
+ \sa{Console Logging}
+*/
+
+/*!
+ \fn bool QWebEnginePage::acceptNavigationRequest(const QUrl &url, NavigationType type, bool isMainFrame)
+ \since 5.5
+ This function is called upon receiving a request to navigate to the specified \a url by means of
+ the specified navigation type \a type. \a isMainFrame indicates whether the request corresponds
+ to the main frame or a child frame. If the function returns \c true, the navigation request is
+ accepted and \c url is loaded. The default implementation accepts all navigation requests.
+
+ Navigation requests can be delegated to the Qt application instead of having the HTML handler
+ engine process them by overloading this function. This is necessary when an HTML document is
+ used as part of the user interface, and not to display external data, for example, when
+ displaying a list of results.
+
+ \note This function is not called for fragment navigation on the same page. Such navigation,
+ for example, happens by clicking a link to a '#fragment' within the page. It does not trigger
+ a load to a different document, even though it changes page's url and adds history entry.
+ It only serves as a shortcut to scroll within the page. Hence, no delegation of this navigation
+ type is expected to happen.
+
+ \note The loading process is started and the loadStarted() signal is emitted
+ \e before the request is accepted or rejected. Therefore, a loadFinished()
+ signal that returns \c false is to be expected even after delegating the
+ request.
+
+ \note When using setHtml or setContent with relative links, make
+ sure to specify a base url, otherwise the links will be considered
+ invalid and no navigation requests will be emitted.
+
+ The \l{QWebEngineUrlRequestInterceptor} class offers further options for intercepting and
+ manipulating requests.
+*/
+
+/*!
+ \fn void QWebEnginePage::javaScriptAlert(const QUrl &securityOrigin, const QString& msg)
+ This function is called whenever a JavaScript program running in a frame affiliated with
+ \a securityOrigin calls the \c alert() function with the message \a msg.
+
+ The default implementation shows the message, \a msg, with QMessageBox::information.
+*/
+
+/*!
+ \fn bool QWebEnginePage::javaScriptConfirm(const QUrl &securityOrigin, const QString& msg)
+ This function is called whenever a JavaScript program running in a frame affiliated with
+ \a securityOrigin calls the \c confirm() function with the message \a msg. Returns \c true
+ if the user confirms the message; otherwise returns \c false.
+
+ It is also called when the \c onbeforeunload handler is requesting a confirmation before
+ leaving a page.
+
+ The default implementation executes the query using QMessageBox::information with QMessageBox::Ok and QMessageBox::Cancel buttons.
+*/
+
+/*!
+ \fn bool QWebEnginePage::javaScriptPrompt(const QUrl &securityOrigin, const QString& msg, const QString& defaultValue, QString* result)
+ This function is called whenever a JavaScript program running in a frame affiliated with \a securityOrigin tries to prompt the user for input.
+ The program may provide an optional message, \a msg, as well as a default value for the input in \a defaultValue.
+
+ If the prompt was cancelled by the user, the implementation should return \c false; otherwise the
+ result should be written to \a result and \c true should be returned. If the prompt was not
+ cancelled by the user, the implementation should return \c true and the result string must not
+ be null.
+
+ The default implementation uses QInputDialog::getText().
+*/
+
+/*!
+ \fn QWebEnginePage *QWebEnginePage::createWindow(WebWindowType type)
+ This function is called to create a new window of the specified \a type. For example, when a
+ JavaScript program requests to open a document in a new window.
+
+ If the new window can be created, the new window's QWebEnginePage is returned; otherwise a null pointer is returned.
+
+ If the view associated with the web page is a QWebEngineView object, then the default implementation forwards
+ the request to QWebEngineView::createWindow(); otherwise it returns a null pointer.
+
+ If this call is not implemented or does not return a new page, \l newWindowRequested()
+ is emitted to handle the request.
+
+ \note In the cases when the window creation is being triggered by JavaScript, apart from
+ reimplementing this method the application must also set
+ QWebEngineSettings::JavascriptCanOpenWindows to \c true in order for the method to get called.
+
+ \sa QWebEngineView::createWindow(), newWindowRequested()
+*/
+
+/*!
+ \fn void QWebEnginePage::triggerAction(WebAction action, bool checked = false)
+ This function can be called to trigger the specified \a action.
+ It is also called by \QWE if the user triggers the action, for example
+ through a context menu item.
+
+ If \a action is a checkable action, then \a checked specifies whether the action
+ is toggled or not.
+
+ \sa action()
+*/
+
+/*!
+ \property QWebEnginePage::hasSelection
+ \brief Whether this page contains selected content or not.
+
+ \sa selectionChanged()
+*/
+
+/*!
+ \property QWebEnginePage::selectedText
+ \brief The text currently selected.
+
+ By default, this property contains an empty string.
+
+ \sa selectionChanged()
+*/
+
+/*!
+ \fn QAction *QWebEnginePage::action(WebAction action) const
+ Returns a QAction for the specified WebAction \a action.
+
+ The action is owned by the QWebEnginePage but you can customize the look by
+ changing its properties.
+
+ \l{QWebEnginePage::action(WebAction action)} does not have a default styled icon.
+ Use \l{QWebEngineView::pageAction()} to have an action with a default styled icon.
+
+ QWebEnginePage also takes care of implementing the action, so that upon
+ triggering the corresponding action is performed on the page.
+
+ \sa triggerAction()
+*/
+
+/*!
+ \fn void QWebEnginePage::findText(const QString &subString, QWebEnginePage::FindFlags options = {}, const std::function<void(const QWebEngineFindTextResult &)> &resultCallback = std::function<void(const QWebEngineFindTextResult &)>)
+ Finds the specified string, \a subString, in the page, using the given \a options.
+ The findTextFinished() signal is emitted when a string search is completed.
+
+ To clear the search highlight, just pass an empty string.
+
+ The \a resultCallback must take a QWebEngineFindTextResult parameter.
+
+ \warning We guarantee that the callback (\a resultCallback) is always called, but it might be done
+ during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid
+ value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.
+
+ For example:
+ \snippet qtwebengine_qwebenginepage_snippet.cpp 0
+
+ \sa findTextFinished()
+*/
+
+/*!
+ \fn QWebEngineSettings *QWebEnginePage::settings() const
+ Returns a pointer to the page's settings object.
+*/
+
+/*!
+ \fn void QWebEnginePage::certificateError(const QWebEngineCertificateError & certificateError)
+ This signal is emitted when an invalid certificate error is raised while loading a given request.
+
+ The \a certificateError parameter contains information about the certificate and details of the error,
+ it also provides the way to ignore the error and complete the request or stop loading
+ the request.
+
+ \sa QWebEngineCertificateError
+*/
+
+/*!
+ \fn QString QWebEnginePage::chooseFiles(FileSelectionMode mode, const QStringList& oldFiles, const QStringList& acceptedMimeTypes)
+ This function is called when the web content requests a file name, for example
+ as a result of the user clicking on a file upload button in an HTML form.
+
+ \a mode indicates whether only one file or multiple files are expected to be returned.
+
+ A suggested filename may be provided as the first entry of \a oldFiles. \a acceptedMimeTypes is ignored by the default implementation,
+ but might be used by overrides.
+*/
+
+/*!
+ \fn void QWebEnginePage::loadStarted()
+
+ This signal is emitted when a page starts loading content.
+
+ \sa loadFinished(), acceptNavigationRequest()
+*/
+
+/*!
+ \fn void QWebEnginePage::loadProgress(int progress)
+
+ This signal is emitted when the global progress status changes.
+ The current value is provided by \a progress and scales from 0 to 100,
+ which is the default range of QProgressBar.
+ It accumulates changes from all the child frames.
+
+*/
+
+/*!
+ \fn void QWebEnginePage::loadFinished(bool ok)
+
+ This signal is emitted when the page finishes loading content. This signal
+ is independent of script execution or page rendering.
+ \a ok will indicate whether the load was successful or any error occurred.
+
+ \note Navigation requests can be delegated to the Qt application instead
+ of having the HTML handler engine process them by overloading the
+ acceptNavigationRequest() function. Because the loading process is started
+ and the loadStarted() signal is emitted \e before the request is accepted
+ or rejected, a \c loadFinished() signal that returns \c false is to be
+ expected even after delegating the request.
+
+ \sa loadStarted(), acceptNavigationRequest()
+*/
+
+/*!
+ \fn void QWebEnginePage::selectionChanged()
+
+ This signal is emitted whenever the selection changes, either interactively
+ or programmatically. For example, by calling triggerAction() with a selection action.
+
+ \note When using the mouse to select text by left-clicking and dragging, the signal will be
+ emitted for each new character selected, and not upon releasing the left mouse button.
+
+ \sa selectedText()
+*/
+
+/*!
+ \fn void QWebEnginePage::linkHovered(const QString &url)
+
+ This signal is emitted when the mouse hovers over a link.
+ \a url contains the target URL of the link.
+*/
+
+/*!
+
+ \fn void QWebEnginePage::authenticationRequired(const QUrl &requestUrl, QAuthenticator *authenticator)
+
+ This signal is emitted when access to \a requestUrl requires authentication.
+ \a authenticator should be used to pass the user name and password for the connection.
+*/
+
+/*!
+ \fn void QWebEnginePage::proxyAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *authenticator, const QString &proxyHost)
+
+ This signal is emitted when access to \a requestUrl via \a proxyHost requires authentication for the proxy.
+ \a authenticator should be used to pass the user name and password for the connection.
+
+*/
+
+/*!
+ \fn void QWebEnginePage::geometryChangeRequested(const QRect& geom)
+
+ This signal is emitted whenever the document wants to change the position and size of the
+ page to \a geom. This can happen for example through JavaScript.
+
+ \note \l{QWindow::}{setGeometry()} expects a size excluding the window
+ decoration, while \a geom includes it. You have to remove the size of the frame margins
+ from \a geom to handle this signal correctly.
+
+ \code
+ window->setGeometry(geom.marginsRemoved(window->frameMargins()));
+ \endcode
+*/
+
+/*!
+ \fn void QWebEnginePage::windowCloseRequested()
+
+ This signal is emitted whenever the page requests the web browser window to be closed,
+ for example through the JavaScript \c{window.close()} call.
+
+ \sa RequestClose
+*/
+
+/*!
+ \fn void QWebEnginePage::toHtml(const std::function<void(const QString &)> &resultCallback) const
+ Asynchronous method to retrieve the page's content as HTML, enclosed in HTML and BODY tags.
+ Upon successful completion, \a resultCallback is called with the page's content.
+
+ \note \a resultCallback can be any of a function pointer, a functor or a lambda, and it is expected to take a QString parameter.
+
+ \warning We guarantee that the callback (\a resultCallback) is always called, but it might be done
+ during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid
+ value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.
+
+ \sa setHtml(), toPlainText()
+*/
+
+/*!
+ \fn void QWebEnginePage::toPlainText(const std::function<void(const QString &)> &resultCallback) const
+ Asynchronous method to retrieve the page's content converted to plain text, completely stripped of all
+ HTML formatting.
+ Upon successful completion, \a resultCallback is called with the page's content.
+
+ \note \a resultCallback can be any of a function pointer, a functor or a lambda, and it is expected to take a QString parameter.
+
+ \warning We guarantee that the callback (\a resultCallback) is always called, but it might be done
+ during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid
+ value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.
+
+ \sa toHtml()
+*/
+
+/*!
+ \property QWebEnginePage::title
+ \brief The title of the page as defined by the HTML \c <title> element.
+
+ If the page has no \c <title> element, then the URL is used instead. For \c
+ file:// URLs only the filename is used and not the full path.
+
+ By default, before any content has been loaded, this property contains an
+ empty string.
+
+ \sa titleChanged()
+*/
+
+/*!
+ \property QWebEnginePage::url
+ \brief The URL of the page currently viewed.
+
+ Setting this property clears the view and loads the URL.
+
+ By default, this property contains an empty, invalid URL.
+
+ \sa urlChanged()
+*/
+
+/*!
+ \property QWebEnginePage::requestedUrl
+ \brief The URL that was originally requested to be loaded by the page
+ that is currently viewed.
+
+ \note The URL may differ from the one returned by url(), which is the actual
+ URL that results from DNS resolution or redirection.
+
+ \sa url(), setUrl()
+*/
+
+/*!
+ \fn void QWebEnginePage::load(const QUrl &url)
+ Loads \a url into this page.
+
+ \note The view remains the same until enough data has arrived to display the new URL.
+
+ \sa setUrl(), setHtml(), setContent()
+*/
+
+/*!
+ \fn void QWebEnginePage::setHtml(const QString &html, const QUrl &baseUrl)
+ Sets the content of this page to \a html. \a baseUrl is optional and used to resolve relative
+ URLs in the document, such as referenced images or stylesheets.
+
+ The \a html is loaded immediately; external objects are loaded asynchronously.
+
+ If a script in the \a html runs longer than the default script timeout (currently 10 seconds),
+ for example due to being blocked by a modal JavaScript alert dialog, this method will return
+ as soon as possible after the timeout and any subsequent \a html will be loaded asynchronously.
+
+ When using this method, the web engine assumes that external resources, such as JavaScript programs or style
+ sheets, are encoded in UTF-8 unless otherwise specified. For example, the encoding of an external
+ script can be specified through the charset attribute of the HTML script tag. It is also possible
+ for the encoding to be specified by the web server.
+
+ This is a convenience function equivalent to setContent(html, "text/html", baseUrl).
+
+ \note This method will not affect session or global history for the page.
+
+ \warning This function works only for HTML, for other mime types (such as XHTML and SVG)
+ setContent() should be used instead.
+
+ \warning The content will be percent encoded before being sent to the renderer via IPC.
+ This may increase its size. The maximum size of the percent encoded content is
+ 2 megabytes minus 30 bytes.
+
+ \sa toHtml(), setContent(), load()
+*/
+
+/*!
+ \fn void QWebEnginePage::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl)
+ Sets the content of the web page to \a data. If the \a mimeType argument
+ is empty, it is assumed that the content is \c{text/plain,charset=US-ASCII}.
+
+ External objects referenced in the content are located relative to \a baseUrl.
+ For external objects with relative URLs to be loaded, \c baseUrl cannot be empty.
+
+ The \a data is loaded immediately; external objects are loaded asynchronously.
+
+ \note This method will not affect session or global history for the page.
+
+ \warning The content will be percent encoded before being sent to the renderer via IPC.
+ This may increase its size. The maximum size of the percent encoded content is
+ 2 megabytes minus 6 bytes plus the length of the mime type string.
+
+ \sa toHtml(), setHtml()
+*/
+
+/*!
+ \property QWebEnginePage::zoomFactor
+ \brief The zoom factor for the page content.
+
+ Valid values are within the range from \c{0.25} to \c{5.0}. The default factor is \c{1.0}.
+*/
+
+/*!
+ \fn void QWebEnginePage::runJavaScript(const QString &scriptSource, quint32 worldId = 0, const std::function<void(const QVariant &)> &resultCallback = {})
+ \fn void QWebEnginePage::runJavaScript(const QString &scriptSource, const std::function<void(const QVariant &)> &resultCallback)
+ \since 5.7
+
+ Runs the JavaScript code contained in \a scriptSource without checking
+ whether the DOM of the page has been constructed. If you need more
+ control over how the script is run, consider using \l scripts() instead.
+
+ To avoid conflicts with other scripts executed on the page, the world in
+ which the script is run is specified by \a worldId. The world ID values are
+ the same as provided by QWebEngineScript::ScriptWorldId, and between \c 0
+ and \c 256. If you leave out the \c world ID, the script is run in the
+ \c MainWorld.
+
+ When the script has been executed, \a resultCallback is called with the result of the last
+ executed statement. \c resultCallback can be any of a function pointer, a functor or a lambda,
+ and it is expected to take a QVariant parameter. For example:
+
+ \code
+ page.runJavaScript("document.title", [](const QVariant &v) { qDebug() << v.toString(); });
+ \endcode
+
+ Only plain data can be returned from JavaScript as the result value.
+ Supported data types include all of the JSON data types as well as, for
+ example, \c{Date} and \c{ArrayBuffer}. Unsupported data types include, for
+ example, \c{Function} and \c{Promise}.
+
+ \warning Do not execute lengthy routines in the callback function, because it might block the
+ rendering of the web engine page.
+
+ \warning We guarantee that the callback (\a resultCallback) is always called, but it might be done
+ during page destruction. When QWebEnginePage is deleted, the callback is triggered with an invalid
+ value and it is not safe to use the corresponding QWebEnginePage or QWebEngineView instance inside it.
+
+ \sa scripts(), QWebEngineScript::ScriptWorldId, {Script Injection}
+*/
+
+/*!
+ \fn void QWebEnginePage::setFeaturePermission(const QUrl &securityOrigin, Feature feature, PermissionPolicy policy)
+
+ Sets the permission for the web site identified by \a securityOrigin to use \a feature to \a policy.
+
+ \note This method is primarily for calling after a featurePermissionRequested() signal has been emitted
+ to trigger the feature permission response. It can also be called before a request has been emitted,
+ but will only set a granted permission for passive checks, mainly for Notification APIs that can check
+ if permission has already been granted before explicitly requesting it.
+
+ \sa featurePermissionRequested(), featurePermissionRequestCanceled()
+*/
+
+/*!
+ \fn void QWebEnginePage::featurePermissionRequested(const QUrl &securityOrigin, Feature feature)
+
+ This signal is emitted when the web site identified by \a securityOrigin requests to make use of
+ the resource or device identified by \a feature.
+
+ \sa featurePermissionRequestCanceled(), setFeaturePermission()
+*/
+
+/*!
+ \fn void QWebEnginePage::featurePermissionRequestCanceled(const QUrl &securityOrigin, Feature feature)
+
+ This signal is emitted when the web site identified by \a securityOrigin cancels a previously issued
+ request to make use of \a feature.
+
+ \sa featurePermissionRequested(), setFeaturePermission()
+
+*/
+
+/*!
+ \fn void QWebEnginePage::titleChanged(const QString &title)
+
+ This signal is emitted whenever the title of the page changes.
+ The \a title string specifies the new title.
+
+ \sa title()
+*/
+
+/*!
+ \fn void QWebEnginePage::urlChanged(const QUrl &url)
+
+ This signal is emitted with the URL of the page when the page title is
+ received. The new URL is specified by \a url.
+
+ \sa url()
+*/
+
+/*!
+ \fn void QWebEnginePage::webAuthUxRequested(QWebEngineWebAuthUxRequest *request);
+ \since 6.7
+
+ This signal is emitted when a WebAuth authenticator needs user interaction
+ during the authentication process. These requests are handled by displaying a dialog to the user.
+
+ The \a request contains the information and API required to complete the WebAuth UX request.
+
+ \sa QWebEngineWebAuthUxRequest
+*/
diff --git a/src/core/doc/src/qwebenginesettings_lgpl.qdoc b/src/core/doc/src/qwebenginesettings_lgpl.qdoc
new file mode 100644
index 000000000..cd7ff8e8c
--- /dev/null
+++ b/src/core/doc/src/qwebenginesettings_lgpl.qdoc
@@ -0,0 +1,332 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+// The documentation in this file was imported from QtWebKit and is thus constrained
+// by its LGPL license. Documentation written from scratch for new methods should be
+// placed inline in the code as usual.
+
+/*!
+ \class QWebEngineSettings
+ \since 5.4
+ \brief The QWebEngineSettings class provides an object to store the settings used
+ by QWebEnginePage.
+
+ \inmodule QtWebEngineCore
+
+ QWebEngineSettings allows configuration of browser properties, such as font sizes and
+ families, and generic attributes, such as JavaScript support.
+ Individual attributes are set using the setAttribute() function. The
+ \l{QWebEngineSettings::WebAttribute}{WebAttribute} enum further describes each attribute.
+
+ Each QWebEnginePage object has its own QWebEngineSettings object, which configures the
+ settings for that page. If a setting is not configured for a web engine
+ page, it is looked up in the settings of the profile the page belongs to.
+
+ \sa QWebEnginePage::settings(), QWebEngineView::settings()
+*/
+
+/*!
+ \enum QWebEngineSettings::FontFamily
+
+ This enum describes the generic font families defined by CSS 2.
+ For more information see the
+ \l{http://www.w3.org/TR/REC-CSS2/fonts.html#generic-font-families}{CSS standard}.
+
+ \value StandardFont
+ \value FixedFont
+ \value SerifFont
+ \value SansSerifFont
+ \value CursiveFont
+ \value FantasyFont
+ \value PictographFont
+ (added in Qt 5.7, deprecated Qt 6.4)
+*/
+
+/*!
+ \enum QWebEngineSettings::FontSize
+
+ This enum describes the font sizes configurable through QWebEngineSettings:
+
+ \value MinimumFontSize The hard minimum font size.
+ \value MinimumLogicalFontSize The minimum logical font size that is applied
+ when zooming out.
+ \value DefaultFontSize The default font size for regular text.
+ \value DefaultFixedFontSize The default font size for fixed-pitch text.
+*/
+
+/*!
+ \enum QWebEngineSettings::WebAttribute
+
+ This enum type specifies settings for web pages:
+
+ \value AutoLoadImages
+ Automatically dowloads images for web pages. When this setting is
+ disabled, images are loaded from the cache. Enabled by default.
+ \value JavascriptEnabled
+ Enables the running of JavaScript programs in the
+ \l{QWebEngineScript::MainWorld}{MainWorld}. Enabled by default.
+ \value JavascriptCanOpenWindows
+ Allows JavaScript programs to open popup windows without user
+ interaction. Enabled by default.
+ \value JavascriptCanAccessClipboard
+ Allows JavaScript programs to read from and write to the clipboard.
+ Writing to the clipboard is always allowed if it is specifically requested by the user.
+ See JavascriptCanPaste to also allow pasting the content of the clipboard content from
+ JavaScript. Since unrestricted clipboard access is a potential security concern, it is
+ recommended that applications leave this disabled and instead respond to
+ \l{QWebEnginePage::ClipboardReadWrite}{ClipboardReadWrite} feature permission requests.
+ Disabled by default.
+ \value LinksIncludedInFocusChain
+ Includes hyperlinks in the keyboard focus chain. Enabled by default.
+ \value LocalStorageEnabled
+ Enables support for the HTML 5 local storage feature. Enabled by default.
+ \value LocalContentCanAccessRemoteUrls
+ Allows local origin documents to access remote resources that would normally be blocked.
+ Disabled by default. Note DnsPrefetchEnabled below operates independently of this setting,
+ and can if enabled, cause remote accesses from local content.
+ \value XSSAuditingEnabled
+ Obsolete and has no effect.
+ \value SpatialNavigationEnabled
+ Enables the Spatial Navigation feature, which means the ability to navigate between
+ focusable elements, such as hyperlinks and form controls, on a web page by using the
+ Left, Right, Up and Down arrow keys. For example, if a user presses the
+ Right key, heuristics determine whether there is an element they might be
+ trying to reach towards the right and which element they probably want.
+ Disabled by default.
+ \value LocalContentCanAccessFileUrls
+ Allows locally loaded documents to access other local URLs. Disabling this makes QtWebEngine
+ behave more like Chrome and Firefox does by default. Enabled by default.
+ \value HyperlinkAuditingEnabled
+ Enables support for the \c ping attribute for hyperlinks. Disabled by default.
+ \value ScrollAnimatorEnabled
+ Enables animated scrolling. Disabled by default.
+ \value ErrorPageEnabled
+ Enables displaying the built-in error pages of Chromium. Enabled by default.
+ \value PluginsEnabled
+ Enables support for Pepper plugins, such as the Flash player. Disabled by default.
+ See also \l{Pepper Plugin API}. (Added in Qt 5.6)
+ \value FullScreenSupportEnabled
+ Enables fullscreen support in an application. Disabled by default. (Added in Qt 5.6)
+ \value ScreenCaptureEnabled
+ Enables screen capture in an application. Disabled by default. (Added in Qt 5.7)
+ \value WebGLEnabled
+ Enables support for HTML 5 WebGL. Enabled by default if available. (Added in Qt 5.7)
+ \value Accelerated2dCanvasEnabled
+ Specifies whether the HTML5 2D canvas should be a OpenGL framebuffer.
+ This makes many painting operations faster, but slows down pixel access. Enabled by default if available. (Added in Qt 5.7)
+ \value AutoLoadIconsForPage
+ Automatically downloads icons for web pages. Enabled by default. (Added in Qt 5.7)
+ \value TouchIconsEnabled
+ Enables support for touch icons and precomposed touch icons
+ Disabled by default. (Added in Qt 5.7)
+ \value FocusOnNavigationEnabled
+ Gives focus to the view associated with the page, whenever a navigation operation occurs
+ (load, stop, reload, reload and bypass cache, forward, backward, set content, and so
+ on).
+ Disabled by default. (Added in Qt 5.8)
+ \value PrintElementBackgrounds
+ Turns on printing of CSS backgrounds when printing a web page.
+ Enabled by default. (Added in Qt 5.8)
+ \value AllowRunningInsecureContent
+ By default, HTTPS pages cannot run JavaScript, CSS, plugins or
+ web-sockets from HTTP URLs. This provides an override to get
+ the old insecure behavior.
+ Disabled by default. (Added in Qt 5.8)
+ \value AllowGeolocationOnInsecureOrigins
+ Since Qt 5.7, only secure origins such as HTTPS have been able to request
+ Geolocation features. This provides an override to allow non secure
+ origins to access Geolocation again.
+ Disabled by default. (Added in Qt 5.9)
+ \value AllowWindowActivationFromJavaScript
+ Allows activating windows by using the window.focus() JavaScript
+ method. Disabled by default.
+ (Added in Qt 5.10)
+ \value ShowScrollBars
+ Shows scroll bars.
+ Enabled by default. (Added in Qt 5.10)
+ \value PlaybackRequiresUserGesture
+ Inhibits playback of media content until the user interacts with
+ the page. By default, WebEngine uses Chromium settings, as described
+ in \l {Autoplay Policy Changes}. This is similar to how Chrome on
+ Android behaves, while the default behavior when it is disabled is
+ similar to Chrome on desktops. To overwrite the default behavior,
+ disable this setting. (Added in Qt 5.11)
+ \value JavascriptCanPaste
+ Enables JavaScript \c{execCommand("paste")}. This also requires enabling
+ JavascriptCanAccessClipboard. Since unrestricted clipboard access is a potential
+ security concern, it is recommended that applications leave this disabled
+ and instead respond to \l{QWebEnginePage::ClipboardReadWrite}{ClipboardReadWrite}
+ feature permission requests.
+ Disabled by default. (Added in Qt 5.11)
+ \value WebRTCPublicInterfacesOnly
+ Limits WebRTC to public IP addresses only. When disabled WebRTC may also use
+ local network IP addresses, but remote hosts can also see your local network
+ IP address.
+ Disabled by default. (Added in Qt 5.11)
+ \value DnsPrefetchEnabled Specifies whether WebEngine will try to pre-fetch DNS entries to
+ speed up browsing.
+ Disabled by default. (Added in Qt 5.12)
+ \value PdfViewerEnabled Specifies that PDF documents will be opened in the internal PDF viewer
+ instead of being downloaded.
+ Enabled by default. (Added in Qt 5.13)
+ \value NavigateOnDropEnabled Specifies that navigations can be triggered by dropping URLs on
+ the view.
+ Enabled by default. (Added in Qt 6.4)
+ \value ReadingFromCanvasEnabled Specifies that reading from all canvas elements is enabled.
+ This setting will have impact on all HTML5 canvas elements irrespective of origin, and can be disabled
+ to prevent canvas fingerprinting.
+ Enabled by default. (Added in Qt 6.6)
+ \value ForceDarkMode Specifies that all web contents will be rendered using a dark theme.
+ For more information, see \l{https://developer.chrome.com/blog/auto-dark-theme/}{Auto dark theme}.
+ Disabled by default. (Added in Qt 6.7)
+*/
+
+/*!
+ \enum QWebEngineSettings::UnknownUrlSchemePolicy
+ \since Qt 5.11
+
+ This enum describes how navigation requests to URLs with unknown schemes are handled.
+
+ \value DisallowUnknownUrlSchemes
+ Disallows all navigation requests to URLs with unknown schemes.
+ \value AllowUnknownUrlSchemesFromUserInteraction
+ Allows navigation requests to URLs with unknown schemes that are issued from
+ user-interaction (like a mouse-click), whereas other navigation requests (for example
+ from JavaScript) are suppressed.
+ \value AllowAllUnknownUrlSchemes
+ Allows all navigation requests to URLs with unknown schemes.
+ \omitvalue InheritedUnknownUrlSchemePolicy
+
+ \sa unknownUrlSchemePolicy setUnknownUrlSchemePolicy resetUnknownUrlSchemePolicy
+*/
+
+/*!
+ \enum QWebEngineSettings::ImageAnimationPolicy
+ \since Qt 6.8
+
+ This enum describes how an image animation should be handled when the image frames
+ are rendered for animation.
+
+ \value AllowImageAnimation
+ Allows image animation when the image frames are rendered.
+ \value AnimateImageOnce
+ Animate the image once when the image frames are rendered.
+ \value DisallowImageAnimation
+ Disallows image animation when the image frames are rendered.
+ \omitvalue InheritedImageAnimationPolicy
+
+ \sa imageAnimationPolicy setImageAnimationPolicy resetImageAnimationPolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::setFontSize(FontSize type, int size)
+ Sets the font size for \a type to \a size in pixels.
+*/
+
+/*!
+ \fn int QWebEngineSettings::fontSize(FontSize type) const
+ Returns the default font size for \a type in pixels.
+*/
+
+/*!
+ \fn void QWebEngineSettings::resetFontSize(FontSize type)
+ Resets the font size for \a type to the size specified in the profile that
+ the page belongs to.
+*/
+
+/*!
+ \fn void QWebEngineSettings::setDefaultTextEncoding(const QString& encoding)
+ Specifies the default text encoding system.
+
+ The value of \a encoding must be a string describing an encoding such as "utf-8" or
+ "iso-8859-1". If left empty, a default value will be used. For a more
+ extensive list of encoding names see \l{QTextCodec}.
+
+ \sa defaultTextEncoding()
+*/
+
+/*!
+ \fn QString QWebEngineSettings::defaultTextEncoding() const
+ Returns the default text encoding.
+
+ \sa setDefaultTextEncoding()
+*/
+
+/*!
+ \fn QString QWebEngineSettings::fontFamily(FontFamily which) const
+ Returns the actual font family for the specified generic font family,
+ \a which.
+*/
+
+/*!
+ \fn void QWebEngineSettings::resetFontFamily(FontFamily which)
+ Resets the actual font family specified by \a which to the one specified
+ in the profile that the page belongs to.
+*/
+
+/*!
+ \fn QWebEngineSettings::UnknownUrlSchemePolicy QWebEngineSettings::unknownUrlSchemePolicy() const
+ \since Qt 5.11
+ Returns the currently selected policy for handling navigation requests to URLs with
+ unknown schemes. Default is \l{QWebEngineSettings::AllowUnknownUrlSchemesFromUserInteraction}.
+ \sa setUnknownUrlSchemePolicy resetUnknownUrlSchemePolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::setUnknownUrlSchemePolicy(QWebEngineSettings::UnknownUrlSchemePolicy policy)
+ \since Qt 5.11
+ Sets the policy for handling navigation requests to URLs with unknown schemes to \a policy.
+ Default is \l{QWebEngineSettings::AllowUnknownUrlSchemesFromUserInteraction}.
+ \sa unknownUrlSchemePolicy resetUnknownUrlSchemePolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::resetUnknownUrlSchemePolicy()
+ \since Qt 5.11
+ Removes the policy for handling navigation requests to URLs with unknown schemes.
+ \sa unknownUrlSchemePolicy setUnknownUrlSchemePolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::setAttribute(WebAttribute attribute, bool on)
+
+ Enables or disables the specified \a attribute feature depending on the
+ value of \a on.
+*/
+
+/*!
+ \fn bool QWebEngineSettings::testAttribute(WebAttribute attribute) const
+
+ Returns \c true if \a attribute is enabled; otherwise returns \c false.
+*/
+
+/*!
+ \fn void QWebEngineSettings::resetAttribute(WebAttribute attribute)
+
+ Resets the setting of \a attribute to the value specified in the
+ profile that the page belongs to.
+*/
+
+/*!
+ \fn QWebEngineSettings::ImageAnimationPolicy QWebEngineSettings::imageAnimationPolicy() const
+ \since Qt 6.8
+ Returns the currently selected policy for handling image animation when the image frames are rendered.
+ Default is \l{QWebEngineSettings::AllowImageAnimation}.
+ \sa setImageAnimationPolicy resetImageAnimationPolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::setImageAnimationPolicy(QWebEngineSettings::ImageAnimationPolicy policy)
+ \since Qt 6.8
+ Sets the policy for handling image animation when the image frames are rendered to \a policy.
+ Default is \l{QWebEngineSettings::AllowImageAnimation}.
+ \sa imageAnimationPolicy resetImageAnimationPolicy
+*/
+
+/*!
+ \fn void QWebEngineSettings::resetImageAnimationPolicy()
+ \since Qt 6.7
+ Removes the policy for handling image animation.
+ \sa imageAnimationPolicy setImageAnimationPolicy
+*/
diff --git a/src/core/download_manager_delegate_qt.cpp b/src/core/download_manager_delegate_qt.cpp
index ebf498fdf..c0fd0d3ee 100644
--- a/src/core/download_manager_delegate_qt.cpp
+++ b/src/core/download_manager_delegate_qt.cpp
@@ -1,46 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "download_manager_delegate_qt.h"
-#include "base/files/file_util.h"
-#include "base/time/time_to_iso8601.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/save_page_type.h"
@@ -49,9 +11,7 @@
#include "net/http/http_content_disposition.h"
#include <QDir>
-#include <QFile>
#include <QFileInfo>
-#include <QMap>
#include <QMimeDatabase>
#include <QStandardPaths>
@@ -68,7 +28,6 @@ DownloadManagerDelegateQt::DownloadManagerDelegateQt(ProfileAdapter *profileAdap
: m_profileAdapter(profileAdapter)
, m_currentId(0)
, m_weakPtrFactory(this)
- , m_nextDownloadIsUserRequested(false)
{
Q_ASSERT(m_profileAdapter);
}
@@ -77,30 +36,36 @@ DownloadManagerDelegateQt::~DownloadManagerDelegateQt()
{
}
-void DownloadManagerDelegateQt::GetNextId(const content::DownloadIdCallback& callback)
+void DownloadManagerDelegateQt::GetNextId(content::DownloadIdCallback callback)
{
- callback.Run(m_currentId);
+ std::move(callback).Run(m_currentId);
}
download::DownloadItem *DownloadManagerDelegateQt::findDownloadById(quint32 downloadId)
{
- content::DownloadManager* dlm = content::BrowserContext::GetDownloadManager(m_profileAdapter->profile());
+ content::DownloadManager *dlm = m_profileAdapter->profile()->GetDownloadManager();
return dlm->GetDownload(downloadId);
}
-void DownloadManagerDelegateQt::cancelDownload(const content::DownloadTargetCallback& callback)
+void DownloadManagerDelegateQt::cancelDownload(content::DownloadTargetCallback callback)
{
- callback.Run(base::FilePath(),
- download::DownloadItem::TARGET_DISPOSITION_PROMPT,
- download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
- base::FilePath(),
- download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
+ std::move(callback).Run(base::FilePath(),
+ download::DownloadItem::TARGET_DISPOSITION_PROMPT,
+ download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
+ download::DownloadItem::UNKNOWN,
+ base::FilePath(),
+ base::FilePath(),
+ std::string(),
+ download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
}
-void DownloadManagerDelegateQt::cancelDownload(quint32 downloadId)
+bool DownloadManagerDelegateQt::cancelDownload(quint32 downloadId)
{
- if (download::DownloadItem *download = findDownloadById(downloadId))
+ if (download::DownloadItem *download = findDownloadById(downloadId)) {
download->Cancel(/* user_cancel */ true);
+ return true;
+ }
+ return false;
}
void DownloadManagerDelegateQt::pauseDownload(quint32 downloadId)
@@ -121,8 +86,8 @@ void DownloadManagerDelegateQt::removeDownload(quint32 downloadId)
download->Remove();
}
-bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem* item,
- const content::DownloadTargetCallback& callback)
+bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem *item,
+ content::DownloadTargetCallback *callback)
{
m_currentId = item->GetId();
@@ -130,25 +95,47 @@ bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem*
// will already return that the file exists. Forced file paths seem to be only used for
// store downloads and other special downloads, so they might never end up here anyway.
if (!item->GetForcedFilePath().empty()) {
- callback.Run(item->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_PROMPT,
- download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetForcedFilePath(), download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_NONE);
+ std::move(*callback).Run(item->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_PROMPT,
+ download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
+ download::DownloadItem::VALIDATED,
+ item->GetForcedFilePath(),
+ item->GetFileNameToReportUser(),
+ item->GetMimeType(),
+ download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
- QString suggestedFilename = toQt(item->GetSuggestedFilename());
+ bool acceptedByDefault = false;
+ QString suggestedFilePath;
+ QString suggestedFilename;
+ bool isSavePageDownload = false;
+ WebContentsAdapterClient *adapterClient = nullptr;
+ if (content::WebContents *webContents = content::DownloadItemUtils::GetWebContents(item)) {
+ WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(webContents->GetDelegate());
+ adapterClient = contentsDelegate->adapterClient();
+ if (SavePageInfo *spi = contentsDelegate->savePageInfo()) {
+ // We end up here when saving non text-based files (MHTML, PDF or images)
+ suggestedFilePath = spi->requestedFilePath;
+ const QFileInfo fileInfo(suggestedFilePath);
+ if (fileInfo.isRelative()) {
+ const QDir downloadDir(m_profileAdapter->downloadPath());
+ suggestedFilePath = downloadDir.absoluteFilePath(suggestedFilePath);
+ }
+ suggestedFilename = fileInfo.fileName();
+
+ if (!suggestedFilePath.isEmpty() && !suggestedFilename.isEmpty())
+ acceptedByDefault = true;
+ isSavePageDownload = true;
+
+ // Clear the delegate's SavePageInfo. It's only valid for the page currently being saved.
+ contentsDelegate->setSavePageInfo(nullptr);
+ }
+ }
+
QString mimeTypeString = toQt(item->GetMimeType());
- int downloadType = 0;
- if (m_nextDownloadIsUserRequested) {
- downloadType = ProfileAdapterClient::UserRequested;
- m_nextDownloadIsUserRequested = false;
- } else {
- bool isAttachment = net::HttpContentDisposition(item->GetContentDisposition(), std::string()).is_attachment();
- if (isAttachment)
- downloadType = ProfileAdapterClient::Attachment;
- else
- downloadType = ProfileAdapterClient::DownloadAttribute;
- }
+ if (suggestedFilename.isEmpty())
+ suggestedFilename = toQt(item->GetSuggestedFilename());
if (suggestedFilename.isEmpty())
suggestedFilename = toQt(net::HttpContentDisposition(item->GetContentDisposition(), net::kCharsetLatin1).filename());
@@ -156,8 +143,11 @@ bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem*
if (suggestedFilename.isEmpty())
suggestedFilename = toQt(item->GetTargetFilePath().AsUTF8Unsafe());
- if (suggestedFilename.isEmpty())
- suggestedFilename = QUrl::fromPercentEncoding(toQByteArray(item->GetURL().ExtractFileName()));
+ if (suggestedFilename.isEmpty()) {
+ GURL itemUrl = item->GetURL();
+ if (!itemUrl.SchemeIs("about") && !itemUrl.SchemeIs("data"))
+ suggestedFilename = QUrl::fromPercentEncoding(toQByteArray(itemUrl.ExtractFileName()));
+ }
if (suggestedFilename.isEmpty()) {
suggestedFilename = QStringLiteral("qwe_download");
@@ -168,16 +158,12 @@ bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem*
QDir defaultDownloadDirectory(m_profileAdapter->downloadPath());
- QString suggestedFilePath = m_profileAdapter->determineDownloadPath(defaultDownloadDirectory.absolutePath(), suggestedFilename, item->GetStartTime().ToTimeT());
+ if (suggestedFilePath.isEmpty())
+ suggestedFilePath = m_profileAdapter->determineDownloadPath(defaultDownloadDirectory.absolutePath(), suggestedFilename, item->GetStartTime().ToTimeT());
item->AddObserver(this);
QList<ProfileAdapterClient*> clients = m_profileAdapter->clients();
if (!clients.isEmpty()) {
- content::WebContents *webContents = content::DownloadItemUtils::GetWebContents(item);
- WebContentsAdapterClient *adapterClient = nullptr;
- if (webContents)
- adapterClient = static_cast<WebContentsDelegateQt *>(webContents->GetDelegate())->adapterClient();
-
Q_ASSERT(m_currentId == item->GetId());
ProfileAdapterClient::DownloadItemInfo info = {
item->GetId(),
@@ -188,17 +174,17 @@ bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem*
mimeTypeString,
suggestedFilePath,
ProfileAdapterClient::UnknownSavePageFormat,
- false /* accepted */,
+ acceptedByDefault,
false /* paused */,
false /* done */,
- downloadType,
+ isSavePageDownload,
item->GetLastReason(),
adapterClient,
suggestedFilename,
item->GetStartTime().ToTimeT()
};
- for (ProfileAdapterClient *client : qAsConst(clients)) {
+ for (ProfileAdapterClient *client : std::as_const(clients)) {
client->downloadRequested(info);
if (info.accepted)
break;
@@ -207,23 +193,34 @@ bool DownloadManagerDelegateQt::DetermineDownloadTarget(download::DownloadItem*
QFileInfo suggestedFile(info.path);
if (info.accepted && !suggestedFile.absoluteDir().mkpath(suggestedFile.absolutePath())) {
+#if defined(Q_OS_WIN)
+ // TODO: Remove this when https://bugreports.qt.io/browse/QTBUG-85997 is fixed.
+ QDir suggestedDir = QDir(suggestedFile.absolutePath());
+ if (!suggestedDir.isRoot() || !suggestedDir.exists()) {
+#endif
qWarning("Creating download path failed, download cancelled: %s", suggestedFile.absolutePath().toUtf8().data());
info.accepted = false;
+#if defined(Q_OS_WIN)
+ }
+#endif
}
if (!info.accepted) {
- cancelDownload(callback);
+ cancelDownload(std::move(*callback));
return true;
}
base::FilePath filePathForCallback(toFilePathString(suggestedFile.absoluteFilePath()));
- callback.Run(filePathForCallback,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
- filePathForCallback.AddExtension(toFilePathString("download")),
- download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_NONE);
+ std::move(*callback).Run(filePathForCallback,
+ download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
+ download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
+ download::DownloadItem::VALIDATED,
+ filePathForCallback.AddExtension(toFilePathString("download")),
+ base::FilePath(),
+ item->GetMimeType(),
+ download::DownloadInterruptReason::DOWNLOAD_INTERRUPT_REASON_NONE);
} else
- cancelDownload(callback);
+ cancelDownload(std::move(*callback));
return true;
}
@@ -250,12 +247,18 @@ void DownloadManagerDelegateQt::ChooseSavePath(content::WebContents *web_content
if (clients.isEmpty())
return;
+ bool acceptedByDefault = false;
+ QString suggestedFilePath;
+ ProfileAdapterClient::SavePageFormat suggestedSaveFormat = ProfileAdapterClient::UnknownSavePageFormat;
WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(
web_contents->GetDelegate());
- const SavePageInfo &spi = contentsDelegate->savePageInfo();
+ if (SavePageInfo *spi = contentsDelegate->savePageInfo()) {
+ suggestedFilePath = spi->requestedFilePath;
+ suggestedSaveFormat = static_cast<ProfileAdapterClient::SavePageFormat>(spi->requestedFormat);
+ // Clear the delegate's SavePageInfo. It's only valid for the page currently being saved.
+ contentsDelegate->setSavePageInfo(nullptr);
+ }
- bool acceptedByDefault = false;
- QString suggestedFilePath = spi.requestedFilePath;
if (suggestedFilePath.isEmpty()) {
suggestedFilePath = QFileInfo(toQt(suggested_path.AsUTF8Unsafe())).completeBaseName()
+ QStringLiteral(".mhtml");
@@ -267,14 +270,9 @@ void DownloadManagerDelegateQt::ChooseSavePath(content::WebContents *web_content
suggestedFilePath = downloadDir.absoluteFilePath(suggestedFilePath);
}
- ProfileAdapterClient::SavePageFormat suggestedSaveFormat
- = static_cast<ProfileAdapterClient::SavePageFormat>(spi.requestedFormat);
if (suggestedSaveFormat == ProfileAdapterClient::UnknownSavePageFormat)
suggestedSaveFormat = ProfileAdapterClient::MimeHtmlSaveFormat;
- // Clear the delegate's SavePageInfo. It's only valid for the page currently being saved.
- contentsDelegate->setSavePageInfo(SavePageInfo());
-
WebContentsAdapterClient *adapterClient = nullptr;
if (web_contents)
adapterClient = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate())->adapterClient();
@@ -284,7 +282,7 @@ void DownloadManagerDelegateQt::ChooseSavePath(content::WebContents *web_content
++m_currentId,
toQt(web_contents->GetURL()),
download::DownloadItem::IN_PROGRESS,
- 0, /* totalBytes */
+ -1, /* totalBytes */
0, /* receivedBytes */
QStringLiteral("application/x-mimearchive"),
suggestedFilePath,
@@ -292,14 +290,14 @@ void DownloadManagerDelegateQt::ChooseSavePath(content::WebContents *web_content
acceptedByDefault,
false, /* paused */
false, /* done */
- ProfileAdapterClient::SavePage,
+ true, /* isSavePageDownload */
ProfileAdapterClient::NoReason,
adapterClient,
QFileInfo(suggestedFilePath).fileName(),
QDateTime::currentMSecsSinceEpoch()
};
- for (ProfileAdapterClient *client : qAsConst(clients)) {
+ for (ProfileAdapterClient *client : std::as_const(clients)) {
client->downloadRequested(info);
if (info.accepted)
break;
@@ -309,8 +307,8 @@ void DownloadManagerDelegateQt::ChooseSavePath(content::WebContents *web_content
return;
std::move(callback).Run(toFilePath(info.path), static_cast<content::SavePageType>(info.savePageFormat),
- base::Bind(&DownloadManagerDelegateQt::savePackageDownloadCreated,
- m_weakPtrFactory.GetWeakPtr()));
+ base::BindOnce(&DownloadManagerDelegateQt::savePackageDownloadCreated,
+ m_weakPtrFactory.GetWeakPtr()));
}
void DownloadManagerDelegateQt::savePackageDownloadCreated(download::DownloadItem *item)
@@ -347,7 +345,7 @@ void DownloadManagerDelegateQt::OnDownloadUpdated(download::DownloadItem *downlo
download->GetStartTime().ToTimeT()
};
- for (ProfileAdapterClient *client : qAsConst(clients)) {
+ for (ProfileAdapterClient *client : std::as_const(clients)) {
client->downloadUpdated(info);
}
}
diff --git a/src/core/download_manager_delegate_qt.h b/src/core/download_manager_delegate_qt.h
index 0cdbd6ee3..cc6d49764 100644
--- a/src/core/download_manager_delegate_qt.h
+++ b/src/core/download_manager_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DOWNLOAD_MANAGER_DELEGATE_QT_H
#define DOWNLOAD_MANAGER_DELEGATE_QT_H
@@ -60,8 +24,6 @@ class DownloadItem;
namespace QtWebEngineCore {
class ProfileAdapter;
-class DownloadManagerDelegateInstance;
-class DownloadTargetHelper;
class DownloadManagerDelegateQt
: public content::DownloadManagerDelegate
@@ -70,10 +32,10 @@ class DownloadManagerDelegateQt
public:
DownloadManagerDelegateQt(ProfileAdapter *profileAdapter);
~DownloadManagerDelegateQt();
- void GetNextId(const content::DownloadIdCallback& callback) override;
+ void GetNextId(content::DownloadIdCallback callback) override;
- bool DetermineDownloadTarget(download::DownloadItem* item,
- const content::DownloadTargetCallback& callback) override;
+ bool DetermineDownloadTarget(download::DownloadItem *item,
+ content::DownloadTargetCallback *callback) override;
void GetSaveDir(content::BrowserContext* browser_context,
base::FilePath* website_save_dir,
@@ -84,32 +46,25 @@ public:
bool can_save_as_complete,
content::SavePackagePathPickedCallback callback) override;
- void cancelDownload(quint32 downloadId);
+ bool cancelDownload(quint32 downloadId);
void pauseDownload(quint32 downloadId);
void resumeDownload(quint32 downloadId);
void removeDownload(quint32 downloadId);
- void markNextDownloadAsUserRequested() { m_nextDownloadIsUserRequested = true; }
-
// Inherited from content::DownloadItem::Observer
void OnDownloadUpdated(download::DownloadItem *download) override;
void OnDownloadDestroyed(download::DownloadItem *download) override;
private:
- void cancelDownload(const content::DownloadTargetCallback& callback);
+ void cancelDownload(content::DownloadTargetCallback callback);
download::DownloadItem *findDownloadById(quint32 downloadId);
void savePackageDownloadCreated(download::DownloadItem *download);
ProfileAdapter *m_profileAdapter;
uint32_t m_currentId;
base::WeakPtrFactory<DownloadManagerDelegateQt> m_weakPtrFactory;
- bool m_nextDownloadIsUserRequested;
-
- friend class DownloadManagerDelegateInstance;
- friend class ProfileAdapter;
- DISALLOW_COPY_AND_ASSIGN(DownloadManagerDelegateQt);
};
} // namespace QtWebEngineCore
-#endif //DOWNLOAD_MANAGER_DELEGATE_QT_H
+#endif // DOWNLOAD_MANAGER_DELEGATE_QT_H
diff --git a/src/core/extensions/component_extension_resource_manager_qt.cpp b/src/core/extensions/component_extension_resource_manager_qt.cpp
index 1f58de151..428f673d3 100644
--- a/src/core/extensions/component_extension_resource_manager_qt.cpp
+++ b/src/core/extensions/component_extension_resource_manager_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on chrome/browser/extensions/chrome_component_extension_resource_manager.cc:
// Copyright 2014 The Chromium Authors. All rights reserved.
@@ -44,12 +8,24 @@
#include "component_extension_resource_manager_qt.h"
-#include "base/logging.h"
+#include "base/check.h"
+#include "base/containers/contains.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "base/values.h"
-
#include "chrome/grit/component_extension_resources_map.h"
+#include "content/public/browser/browser_thread.h"
+#include "extensions/common/constants.h"
+#include "pdf/buildflags.h"
+#include "ppapi/buildflags/buildflags.h"
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+#include "chrome/grit/pdf_resources_map.h"
+#endif
+
+#if BUILDFLAG(ENABLE_PDF)
+#include "qtwebengine/browser/pdf/pdf_extension_util.h"
+#endif // BUILDFLAG(ENABLE_PDF)
namespace extensions {
@@ -57,6 +33,18 @@ ComponentExtensionResourceManagerQt::ComponentExtensionResourceManagerQt()
{
AddComponentResourceEntries(kComponentExtensionResources,
kComponentExtensionResourcesSize);
+#if BUILDFLAG(ENABLE_PLUGINS)
+ AddComponentResourceEntries(kPdfResources, kPdfResourcesSize);
+#endif
+#if BUILDFLAG(ENABLE_PDF)
+ base::Value::Dict dict;
+ pdf_extension_util::AddStrings(pdf_extension_util::PdfViewerContext::kPdfViewer, &dict);
+ pdf_extension_util::AddAdditionalData(/*enable_annotations=*/true, &dict);
+
+ ui::TemplateReplacements pdf_viewer_replacements;
+ ui::TemplateReplacementsFromDictionaryValue(dict, &pdf_viewer_replacements);
+ template_replacements_[extension_misc::kPdfExtensionId] = std::move(pdf_viewer_replacements);
+#endif
}
ComponentExtensionResourceManagerQt::~ComponentExtensionResourceManagerQt() {}
@@ -85,24 +73,25 @@ bool ComponentExtensionResourceManagerQt::IsComponentExtensionResource(const bas
return false;
}
-const ui::TemplateReplacements *ComponentExtensionResourceManagerQt::GetTemplateReplacementsForExtension(const std::string &) const
+const ui::TemplateReplacements *ComponentExtensionResourceManagerQt::GetTemplateReplacementsForExtension(const std::string &extension_id) const
{
- return nullptr;
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ auto it = template_replacements_.find(extension_id);
+ return it != template_replacements_.end() ? &it->second : nullptr;
}
-void ComponentExtensionResourceManagerQt::AddComponentResourceEntries(const GritResourceMap *entries, size_t size)
+void ComponentExtensionResourceManagerQt::AddComponentResourceEntries(const webui::ResourcePath *entries, size_t size)
{
base::FilePath gen_folder_path = base::FilePath().AppendASCII("@out_folder@/gen/chrome/browser/resources/");
gen_folder_path = gen_folder_path.NormalizePathSeparators();
for (size_t i = 0; i < size; ++i) {
- base::FilePath resource_path = base::FilePath().AppendASCII(entries[i].name);
+ base::FilePath resource_path = base::FilePath().AppendASCII(entries[i].path);
resource_path = resource_path.NormalizePathSeparators();
-
if (!gen_folder_path.IsParent(resource_path)) {
DCHECK(!base::Contains(path_to_resource_id_, resource_path));
- path_to_resource_id_[resource_path] = entries[i].value;
+ path_to_resource_id_[resource_path] = entries[i].id;
} else {
// If the resource is a generated file, strip the generated folder's path,
// so that it can be served from a normal URL (as if it were not
@@ -111,7 +100,7 @@ void ComponentExtensionResourceManagerQt::AddComponentResourceEntries(const Grit
base::FilePath().AppendASCII(resource_path.AsUTF8Unsafe().substr(
gen_folder_path.value().length()));
DCHECK(!base::Contains(path_to_resource_id_, effective_path));
- path_to_resource_id_[effective_path] = entries[i].value;
+ path_to_resource_id_[effective_path] = entries[i].id;
}
}
}
diff --git a/src/core/extensions/component_extension_resource_manager_qt.h b/src/core/extensions/component_extension_resource_manager_qt.h
index b719c8960..4da18890e 100644
--- a/src/core/extensions/component_extension_resource_manager_qt.h
+++ b/src/core/extensions/component_extension_resource_manager_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -48,8 +12,7 @@
#include "base/files/file_path.h"
#include "extensions/browser/component_extension_resource_manager.h"
-
-struct GritResourceMap;
+#include "ui/base/webui/resource_path.h"
namespace extensions {
@@ -66,13 +29,14 @@ public:
const ui::TemplateReplacements *GetTemplateReplacementsForExtension(const std::string &extension_id) const override;
private:
- void AddComponentResourceEntries(const GritResourceMap *entries, size_t size);
+ void AddComponentResourceEntries(const webui::ResourcePath *entries, size_t size);
// A map from a resource path to the resource ID. Used by
// IsComponentExtensionResource.
std::map<base::FilePath, int> path_to_resource_id_;
- DISALLOW_COPY_AND_ASSIGN(ComponentExtensionResourceManagerQt);
+ // A map from an extension ID to its i18n template replacements.
+ std::map<std::string, ui::TemplateReplacements> template_replacements_;
};
} // namespace extensions
diff --git a/src/core/extensions/extension_host_delegate_qt.cpp b/src/core/extensions/extension_host_delegate_qt.cpp
new file mode 100644
index 000000000..aa408a544
--- /dev/null
+++ b/src/core/extensions/extension_host_delegate_qt.cpp
@@ -0,0 +1,116 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "extension_host_delegate_qt.h"
+
+#include "desktop_media_controller.h"
+#include "desktop_media_controller_p.h"
+#include "extension_web_contents_observer_qt.h"
+#include "media_capture_devices_dispatcher.h"
+#include "extension_system_qt.h"
+#include "web_contents_view_qt.h"
+
+#include "base/functional/callback.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "extensions/browser/extension_host.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
+
+using namespace QtWebEngineCore;
+
+namespace extensions {
+
+ExtensionHostDelegateQt::ExtensionHostDelegateQt()
+{
+}
+
+void ExtensionHostDelegateQt::OnExtensionHostCreated(content::WebContents *web_contents)
+{
+ extensions::ExtensionWebContentsObserverQt::CreateForWebContents(web_contents);
+}
+
+void ExtensionHostDelegateQt::OnMainFrameCreatedForBackgroundPage(ExtensionHost *host)
+{
+ Q_UNUSED(host);
+}
+
+content::JavaScriptDialogManager *ExtensionHostDelegateQt::GetJavaScriptDialogManager()
+{
+ Q_UNREACHABLE();
+ return nullptr;
+}
+
+void ExtensionHostDelegateQt::CreateTab(std::unique_ptr<content::WebContents> web_contents,
+ const std::string &extension_id,
+ WindowOpenDisposition disposition,
+ const blink::mojom::WindowFeatures &features,
+ bool user_gesture)
+{
+ Q_UNUSED(web_contents);
+ Q_UNUSED(extension_id);
+ Q_UNUSED(disposition);
+ Q_UNUSED(features);
+ Q_UNUSED(user_gesture);
+
+ Q_UNREACHABLE();
+}
+
+static void processMediaAccessRequest(content::WebContents *webContents,
+ const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback,
+ content::DesktopMediaID id)
+{
+ MediaCaptureDevicesDispatcher::GetInstance()->processMediaAccessRequest(
+ webContents, request, std::move(callback), id);
+}
+
+void ExtensionHostDelegateQt::ProcessMediaAccessRequest(content::WebContents *web_contents,
+ const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback,
+ const Extension *extension)
+{
+ Q_UNUSED(extension);
+ base::OnceCallback<void(content::DesktopMediaID)> cb = base::BindOnce(
+ &processMediaAccessRequest, web_contents, std::move(request), std::move(callback));
+
+ // ownership is taken by the request
+ auto *controller = new DesktopMediaController(new DesktopMediaControllerPrivate(std::move(cb)));
+ base::WeakPtr<content::WebContents> webContents = web_contents->GetWeakPtr();
+ QObject::connect(controller, &DesktopMediaController::mediaListsInitialized, [controller, webContents]() {
+ if (webContents) {
+ auto *client = WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(webContents.get())->GetView())->client();
+ client->desktopMediaRequested(controller);
+ } else {
+ controller->deleteLater();
+ }
+ });
+}
+
+bool ExtensionHostDelegateQt::CheckMediaAccessPermission(content::RenderFrameHost *render_frame_host,
+ const GURL &security_origin,
+ blink::mojom::MediaStreamType type,
+ const Extension *extension)
+{
+ Q_UNUSED(render_frame_host);
+ Q_UNUSED(security_origin);
+ Q_UNUSED(type);
+ Q_UNUSED(extension);
+
+ Q_UNREACHABLE();
+ return false;
+}
+
+content::PictureInPictureResult ExtensionHostDelegateQt::EnterPictureInPicture(content::WebContents *web_contents)
+{
+ Q_UNUSED(web_contents);
+
+ Q_UNREACHABLE();
+ return content::PictureInPictureResult::kNotSupported;
+}
+
+void ExtensionHostDelegateQt::ExitPictureInPicture()
+{
+ Q_UNREACHABLE();
+}
+
+} // namespace extensions
diff --git a/src/core/extensions/extension_host_delegate_qt.h b/src/core/extensions/extension_host_delegate_qt.h
new file mode 100644
index 000000000..1c2688933
--- /dev/null
+++ b/src/core/extensions/extension_host_delegate_qt.h
@@ -0,0 +1,39 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef EXTENSION_HOST_DELEGATE_QT_H
+#define EXTENSION_HOST_DELEGATE_QT_H
+
+#include "extensions/browser/extension_host_delegate.h"
+
+namespace extensions {
+
+class ExtensionHostDelegateQt : public ExtensionHostDelegate
+{
+public:
+ ExtensionHostDelegateQt();
+
+ // EtensionHostDelegate implementation.
+ void OnExtensionHostCreated(content::WebContents *web_contents) override;
+ void OnMainFrameCreatedForBackgroundPage(ExtensionHost *host) override;
+ content::JavaScriptDialogManager *GetJavaScriptDialogManager() override;
+ void CreateTab(std::unique_ptr<content::WebContents> web_contents,
+ const std::string &extension_id,
+ WindowOpenDisposition disposition,
+ const blink::mojom::WindowFeatures &features,
+ bool user_gesture) override;
+ void ProcessMediaAccessRequest(content::WebContents *web_contents,
+ const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback,
+ const Extension *extension) override;
+ bool CheckMediaAccessPermission(content::RenderFrameHost *render_frame_host,
+ const GURL &security_origin,
+ blink::mojom::MediaStreamType type,
+ const Extension *extension) override;
+ content::PictureInPictureResult EnterPictureInPicture(content::WebContents *web_contents) override;
+ void ExitPictureInPicture() override;
+};
+
+} // namespace extensions
+
+#endif // EXTENSION_HOST_DELEGATE_QT_H
diff --git a/src/core/extensions/extension_system_factory_qt.cpp b/src/core/extensions/extension_system_factory_qt.cpp
index 41ba31214..63d88fcaf 100644
--- a/src/core/extensions/extension_system_factory_qt.cpp
+++ b/src/core/extensions/extension_system_factory_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -44,7 +8,6 @@
#include "extension_system_factory_qt.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
-#include "extensions/browser/declarative_user_script_manager_factory.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_prefs_factory.h"
#include "extensions/browser/extension_registry_factory.h"
diff --git a/src/core/extensions/extension_system_factory_qt.h b/src/core/extensions/extension_system_factory_qt.h
index 6e840b6d6..b6f6acc5d 100644
--- a/src/core/extensions/extension_system_factory_qt.h
+++ b/src/core/extensions/extension_system_factory_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -44,7 +8,6 @@
#ifndef EXTENSION_SYSTEM_FACTORY_QT_H_
#define EXTENSION_SYSTEM_FACTORY_QT_H_
-#include "base/macros.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "extensions/browser/extension_system_provider.h"
@@ -73,8 +36,6 @@ private:
KeyedService *BuildServiceInstanceFor(content::BrowserContext *context) const override;
content::BrowserContext *GetBrowserContextToUse(content::BrowserContext *context) const override;
bool ServiceIsCreatedWithBrowserContext() const override;
-
- DISALLOW_COPY_AND_ASSIGN(ExtensionSystemFactoryQt);
};
} // namespace extensions
diff --git a/src/core/extensions/extension_system_qt.cpp b/src/core/extensions/extension_system_qt.cpp
index a66051fbd..b9f11646d 100644
--- a/src/core/extensions/extension_system_qt.cpp
+++ b/src/core/extensions/extension_system_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -47,7 +11,7 @@
#include "base/base_paths.h"
#include "base/base_switches.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
@@ -57,19 +21,21 @@
#include "base/path_service.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
+#include "chrome/common/buildflags.h"
#include "components/crx_file/id_util.h"
+#include "components/value_store/value_store_factory.h"
+#include "components/value_store/value_store_factory_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
-#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/common/webplugininfo.h"
+#include "extensions/browser/app_sorting.h"
#include "extensions/browser/content_verifier.h"
#include "extensions/browser/content_verifier_delegate.h"
#include "extensions/browser/extension_pref_store.h"
@@ -77,24 +43,24 @@
#include "extensions/browser/extension_pref_value_map_factory.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
-#include "extensions/browser/info_map.h"
-#include "extensions/browser/notification_types.h"
-#include "extensions/browser/null_app_sorting.h"
#include "extensions/browser/quota_service.h"
#include "extensions/browser/renderer_startup_helper.h"
-#include "extensions/browser/runtime_data.h"
-#include "extensions/browser/shared_user_script_master.h"
#include "extensions/browser/service_worker_manager.h"
-#include "extensions/browser/value_store/value_store_factory_impl.h"
+#include "extensions/browser/task_queue_util.h"
+#include "extensions/browser/user_script_manager.h"
#include "extensions/common/constants.h"
-#include "extensions/common/extension_messages.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/mime_types_handler.h"
#include "extensions/common/manifest_url_handlers.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "chrome/grit/component_extension_resources.h"
-#include "chrome/grit/browser_resources.h"
#include "net/base/mime_util.h"
+#include "pdf/buildflags.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "qtwebengine/grit/qt_webengine_resources.h"
+#include "ui/base/resource/resource_bundle.h"
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+#include "content/public/browser/plugin_service.h"
+#endif
using content::BrowserThread;
@@ -102,28 +68,28 @@ namespace extensions {
namespace {
-std::string GenerateId(const base::DictionaryValue *manifest, const base::FilePath &path)
+std::string GenerateId(const base::Value::Dict &manifest, const base::FilePath &path)
{
- std::string raw_key;
+ const std::string *raw_key;
std::string id_input;
- CHECK(manifest->GetString(manifest_keys::kPublicKey, &raw_key));
- CHECK(Extension::ParsePEMKeyBytes(raw_key, &id_input));
+ CHECK(raw_key = manifest.FindString(manifest_keys::kPublicKey));
+ CHECK(Extension::ParsePEMKeyBytes(*raw_key, &id_input));
std::string id = crx_file::id_util::GenerateId(id_input);
return id;
}
// Implementation based on ComponentLoader::ParseManifest.
-std::unique_ptr<base::DictionaryValue> ParseManifest(const std::string &manifest_contents)
+absl::optional<base::Value::Dict> ParseManifest(base::StringPiece manifest_contents)
{
JSONStringValueDeserializer deserializer(manifest_contents);
- std::unique_ptr<base::Value> manifest(deserializer.Deserialize(NULL, NULL));
+ std::unique_ptr<base::Value> manifest = deserializer.Deserialize(nullptr, nullptr);
if (!manifest.get() || !manifest->is_dict()) {
LOG(ERROR) << "Failed to parse extension manifest.";
- return NULL;
+ return absl::nullopt;
}
- // Transfer ownership to the caller.
- return base::DictionaryValue::From(std::move(manifest));
+
+ return std::move(*manifest).TakeDict();
}
} // namespace
@@ -162,38 +128,25 @@ public:
void Shutdown() override {}
};
-void ExtensionSystemQt::LoadExtension(std::string extension_id, std::unique_ptr<base::DictionaryValue> manifest, const base::FilePath &directory)
+void ExtensionSystemQt::LoadExtension(std::string extension_id, const base::Value::Dict &manifest, const base::FilePath &directory)
{
int flags = Extension::REQUIRE_KEY;
std::string error;
+
scoped_refptr<const Extension> extension = Extension::Create(
directory,
- Manifest::COMPONENT,
- *manifest,
+ mojom::ManifestLocation::kComponent,
+ manifest,
flags,
&error);
if (!extension.get())
LOG(ERROR) << error;
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::Bind(&InfoMap::AddExtension,
- base::Unretained(info_map()),
- base::RetainedRef(extension),
- base::Time::Now(),
- true,
- false));
extension_registry_->AddEnabled(extension.get());
NotifyExtensionLoaded(extension.get());
}
-void ExtensionSystemQt::OnExtensionRegisteredWithRequestContexts(scoped_refptr<const extensions::Extension> extension)
-{
- extension_registry_->AddReady(extension);
- if (extension_registry_->enabled_extensions().Contains(extension->id()))
- extension_registry_->TriggerOnReady(extension.get());
-}
-
// Implementation based on ExtensionService::NotifyExtensionLoaded.
void ExtensionSystemQt::NotifyExtensionLoaded(const Extension *extension)
{
@@ -203,11 +156,7 @@ void ExtensionSystemQt::NotifyExtensionLoaded(const Extension *extension)
// that the request context doesn't yet know about. The profile is responsible
// for ensuring its URLRequestContexts appropriately discover the loaded
// extension.
- RegisterExtensionWithRequestContexts(
- extension,
- base::Bind(&ExtensionSystemQt::OnExtensionRegisteredWithRequestContexts,
- weak_ptr_factory_.GetWeakPtr(),
- base::WrapRefCounted(extension)));
+ ActivateTaskQueueForExtension(browser_context_, extension);
// Tell renderers about the loaded extension.
renderer_helper_->OnExtensionLoaded(*extension);
@@ -221,14 +170,18 @@ void ExtensionSystemQt::NotifyExtensionLoaded(const Extension *extension)
// know about it.
extension_registry_->TriggerOnLoaded(extension);
+#if BUILDFLAG(ENABLE_PLUGINS)
// Register plugins included with the extension.
// Implementation based on PluginManager::OnExtensionLoaded.
+ bool plugins_changed = false;
const MimeTypesHandler *handler = MimeTypesHandler::GetHandler(extension);
- if (handler && !handler->handler_url().empty()) {
+ if (handler && handler->HasPlugin()) {
+ plugins_changed = true;
content::WebPluginInfo info;
info.type = content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN;
info.name = base::UTF8ToUTF16(extension->name());
- info.path = base::FilePath::FromUTF8Unsafe(extension->url().spec());
+ info.path = handler->GetPluginPath();
+ info.background_color = handler->GetBackgroundColor();
for (std::set<std::string>::const_iterator mime_type = handler->mime_type_set().begin();
mime_type != handler->mime_type_set().end(); ++mime_type) {
content::WebPluginMimeType mime_type_info;
@@ -245,6 +198,13 @@ void ExtensionSystemQt::NotifyExtensionLoaded(const Extension *extension)
plugin_service->RefreshPlugins();
plugin_service->RegisterInternalPlugin(info, true);
}
+ if (plugins_changed)
+ content::PluginService::GetInstance()->PurgePluginListCache(browser_context_, false);
+#endif // BUILDFLAG(ENABLE_PLUGINS)
+
+ extension_registry_->AddReady(extension);
+ if (extension_registry_->enabled_extensions().Contains(extension->id()))
+ extension_registry_->TriggerOnReady(extension);
}
bool ExtensionSystemQt::FinishDelayedInstallationIfReady(const std::string &extension_id, bool install_immediately)
@@ -269,19 +229,14 @@ ExtensionService *ExtensionSystemQt::extension_service()
return nullptr;
}
-RuntimeData *ExtensionSystemQt::runtime_data()
-{
- return runtime_data_.get();
-}
-
ManagementPolicy *ExtensionSystemQt::management_policy()
{
return nullptr;
}
-SharedUserScriptMaster *ExtensionSystemQt::shared_user_script_master()
+UserScriptManager *ExtensionSystemQt::user_script_manager()
{
- return shared_user_script_master_.get();
+ return user_script_manager_.get();
}
StateStore *ExtensionSystemQt::state_store()
@@ -294,16 +249,14 @@ StateStore *ExtensionSystemQt::rules_store()
return nullptr;
}
-scoped_refptr<ValueStoreFactory> ExtensionSystemQt::store_factory()
+StateStore *ExtensionSystemQt::dynamic_user_scripts_store()
{
- return store_factory_;
+ return nullptr;
}
-InfoMap *ExtensionSystemQt::info_map()
+scoped_refptr<value_store::ValueStoreFactory> ExtensionSystemQt::store_factory()
{
- if (!info_map_.get())
- info_map_ = new InfoMap;
- return info_map_.get();
+ return store_factory_;
}
QuotaService *ExtensionSystemQt::quota_service()
@@ -313,7 +266,7 @@ QuotaService *ExtensionSystemQt::quota_service()
AppSorting *ExtensionSystemQt::app_sorting()
{
- return app_sorting_.get();
+ return nullptr;
}
ContentVerifier *ExtensionSystemQt::content_verifier()
@@ -326,7 +279,7 @@ ContentVerifier *ExtensionSystemQt::content_verifier()
ExtensionSystemQt::ExtensionSystemQt(content::BrowserContext *browserContext)
: browser_context_(browserContext)
- , store_factory_(new ValueStoreFactoryImpl(browserContext->GetPath()))
+ , store_factory_(new value_store::ValueStoreFactoryImpl(browserContext->GetPath()))
, extension_registry_(ExtensionRegistry::Get(browserContext))
, renderer_helper_(extensions::RendererStartupHelperFactory::GetForBrowserContext(browserContext))
, initialized_(false)
@@ -345,13 +298,9 @@ void ExtensionSystemQt::Init(bool extensions_enabled)
initialized_ = true;
- service_worker_manager_.reset(new ServiceWorkerManager(browser_context_));
- runtime_data_.reset(new RuntimeData(extension_registry_));
- quota_service_.reset(new QuotaService);
- app_sorting_.reset(new NullAppSorting);
-
- shared_user_script_master_ =
- std::make_unique<SharedUserScriptMaster>(browser_context_);
+ service_worker_manager_ = std::make_unique<ServiceWorkerManager>(browser_context_);
+ user_script_manager_ = std::make_unique<UserScriptManager>(browser_context_);
+ quota_service_ = std::make_unique<QuotaService>();
// Make the chrome://extension-icon/ resource available.
// content::URLDataSource::Add(browser_context_, new ExtensionIconSource(browser_context_));
@@ -359,20 +308,34 @@ void ExtensionSystemQt::Init(bool extensions_enabled)
if (extensions_enabled) {
// Inform the rest of the extensions system to start.
ready_.Signal();
- content::NotificationService::current()->Notify(
- NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
- content::Source<content::BrowserContext>(browser_context_),
- content::NotificationService::NoDetails());
-
- std::string pdf_manifest = ui::ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_PDF_MANIFEST).as_string();
- base::ReplaceFirstSubstringAfterOffset(&pdf_manifest, 0, "<NAME>", "chromium-pdf");
-
- std::unique_ptr<base::DictionaryValue> pdfManifestDict = ParseManifest(pdf_manifest);
- base::FilePath path;
- base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &path);
- path = path.Append(base::FilePath(FILE_PATH_LITERAL("pdf")));
- std::string id = GenerateId(pdfManifestDict.get(), path);
- LoadExtension(id, std::move(pdfManifestDict), path);
+
+#if BUILDFLAG(ENABLE_PDF)
+ {
+ std::string pdf_manifest = ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_PDF_MANIFEST);
+ base::ReplaceFirstSubstringAfterOffset(&pdf_manifest, 0, "<NAME>", "chromium-pdf");
+
+ auto pdfManifestDict = ParseManifest(pdf_manifest);
+ CHECK(pdfManifestDict);
+ base::FilePath path;
+ base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &path);
+ path = path.Append(base::FilePath(FILE_PATH_LITERAL("pdf")));
+ std::string id = GenerateId(pdfManifestDict.value(), path);
+ LoadExtension(id, pdfManifestDict.value(), path);
+ }
+#endif // BUILDFLAG(ENABLE_PDF)
+
+#if BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION)
+ {
+ std::string hangout_manifest = ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_HANGOUT_SERVICES_MANIFEST);
+ auto hangoutManifestDict = ParseManifest(hangout_manifest);
+ CHECK(hangoutManifestDict);
+ base::FilePath path;
+ base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &path);
+ path = path.Append(base::FilePath(FILE_PATH_LITERAL("hangout_services")));
+ std::string id = GenerateId(hangoutManifestDict.value(), path);
+ LoadExtension(id, hangoutManifestDict.value(), path);
+ }
+#endif // BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION)
}
}
@@ -380,8 +343,6 @@ void ExtensionSystemQt::InitForRegularProfile(bool extensions_enabled)
{
if (initialized_)
return; // Already initialized.
- // The InfoMap needs to be created before the ProcessManager.
- info_map();
Init(extensions_enabled);
}
@@ -391,40 +352,9 @@ std::unique_ptr<ExtensionSet> ExtensionSystemQt::GetDependentExtensions(const Ex
return base::WrapUnique(new ExtensionSet());
}
-#if !defined(TOOLKIT_QT)
-void ExtensionSystemQt::InstallUpdate(const std::string &extension_id,
- const std::string &public_key,
- const base::FilePath &unpacked_dir,
- bool install_immediately,
- InstallUpdateCallback install_update_callback)
+bool ExtensionSystemQt::is_ready() const
{
- NOTREACHED() << "Not yet implemented";
- base::DeleteFile(unpacked_dir, true /* recursive */);
- std::move(install_update_callback).Run(CrxInstallError(CrxInstallErrorType::DECLINED, CrxInstallErrorDetail::DISALLOWED_BY_POLICY));
+ return ready_.is_signaled();
}
-#endif
-
-void ExtensionSystemQt::RegisterExtensionWithRequestContexts(const Extension *extension,
- const base::Closure &callback)
-{
- base::Time install_time = base::Time::Now();
-
- bool incognito_enabled = false;
- bool notifications_disabled = false;
- base::PostTaskAndReply(
- FROM_HERE, {BrowserThread::IO},
- base::Bind(&InfoMap::AddExtension, info_map(),
- base::RetainedRef(extension), install_time, incognito_enabled,
- notifications_disabled),
- callback);
-}
-
-void ExtensionSystemQt::UnregisterExtensionWithRequestContexts(const std::string &extension_id,
- const UnloadedExtensionReason reason)
-{
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
- base::Bind(&InfoMap::RemoveExtension, info_map(), extension_id, reason));
-}
} // namespace extensions
diff --git a/src/core/extensions/extension_system_qt.h b/src/core/extensions/extension_system_qt.h
index 04bffb74d..c213671a7 100644
--- a/src/core/extensions/extension_system_qt.h
+++ b/src/core/extensions/extension_system_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -50,12 +14,15 @@
#include <string>
#include "base/one_shot_event.h"
-#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/extension_set.h"
+namespace value_store {
+class ValueStoreFactory;
+}
+
namespace extensions {
class ExtensionRegistry;
@@ -63,8 +30,6 @@ class InfoMap;
class RendererStartupHelper;
class ServiceWorkerManager;
class StateStoreNotificationObserver;
-class ValueStoreFactory;
-class ValueStoreFactoryImpl;
// The ExtensionSystem for ProfileImpl and OffTheRecordProfileImpl.
// Implementation details: non-shared services are owned by
@@ -86,70 +51,48 @@ public:
// ExtensionSystem implementation:
void InitForRegularProfile(bool extensions_enabled) override;
ExtensionService *extension_service() override;
- RuntimeData *runtime_data() override;
ManagementPolicy *management_policy() override;
ServiceWorkerManager *service_worker_manager() override;
- SharedUserScriptMaster *shared_user_script_master() override;
+ UserScriptManager *user_script_manager() override;
StateStore *state_store() override;
StateStore *rules_store() override;
- scoped_refptr<ValueStoreFactory> store_factory() override;
- InfoMap *info_map() override;
+ StateStore *dynamic_user_scripts_store() override;
+ scoped_refptr<value_store::ValueStoreFactory> store_factory() override;
QuotaService *quota_service() override;
AppSorting *app_sorting() override;
- void RegisterExtensionWithRequestContexts(const Extension *extension,
- const base::Closure &callback) override;
-
- void UnregisterExtensionWithRequestContexts(const std::string &extension_id,
- const UnloadedExtensionReason reason) override;
-
ContentVerifier *content_verifier() override;
std::unique_ptr<ExtensionSet> GetDependentExtensions(const Extension *extension) override;
-#if !defined(TOOLKIT_QT)
- void InstallUpdate(const std::string &extension_id,
- const std::string &public_key,
- const base::FilePath &unpacked_dir,
- bool install_immediately,
- InstallUpdateCallback install_update_callback) override;
-#endif // TOOLKIT_QT
- //friend class ExtensionSystemSharedFactory;
-
bool FinishDelayedInstallationIfReady(const std::string &extension_id, bool install_immediately) override;
void Init(bool extensions_enabled);
const base::OneShotEvent &ready() const override { return ready_; }
+ bool is_ready() const override;
-private:
- void OnExtensionRegisteredWithRequestContexts(scoped_refptr<const extensions::Extension> extension);
+ void PerformActionBasedOnOmahaAttributes(const std::string &, const base::Value::Dict &) override { /* fixme? */}
+private:
void NotifyExtensionLoaded(const Extension *extension);
- void LoadExtension(std::string extension_id, std::unique_ptr<base::DictionaryValue> manifest, const base::FilePath &directory);
- // The services that are shared between normal and incognito profiles.
-
- // Data to be accessed on the IO thread. Must outlive process_manager_.
- scoped_refptr<InfoMap> info_map_;
+ void LoadExtension(std::string extension_id, const base::Value::Dict &manifest, const base::FilePath &directory);
+ // The services that are shared between normal and incognito profiles.
std::unique_ptr<ServiceWorkerManager> service_worker_manager_;
- std::unique_ptr<RuntimeData> runtime_data_;
std::unique_ptr<QuotaService> quota_service_;
- std::unique_ptr<AppSorting> app_sorting_;
- std::unique_ptr<SharedUserScriptMaster> shared_user_script_master_;
-
+ std::unique_ptr<UserScriptManager> user_script_manager_;
// For verifying the contents of extensions read from disk.
scoped_refptr<ContentVerifier> content_verifier_;
base::OneShotEvent ready_;
content::BrowserContext *browser_context_;
- scoped_refptr<ValueStoreFactory> store_factory_;
+ scoped_refptr<value_store::ValueStoreFactory> store_factory_;
ExtensionRegistry *extension_registry_;
extensions::RendererStartupHelper *renderer_helper_;
bool initialized_;
base::WeakPtrFactory<ExtensionSystemQt> weak_ptr_factory_;
- DISALLOW_COPY_AND_ASSIGN(ExtensionSystemQt);
};
} // namespace extensions
diff --git a/src/core/extensions/extension_web_contents_observer_qt.cpp b/src/core/extensions/extension_web_contents_observer_qt.cpp
index 5b1514bb4..a33954a20 100644
--- a/src/core/extensions/extension_web_contents_observer_qt.cpp
+++ b/src/core/extensions/extension_web_contents_observer_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,17 +7,21 @@
#include "extension_web_contents_observer_qt.h"
+#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/common/url_constants.h"
+#include "content/public/browser/render_view_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/manifest.h"
+#include "third_party/blink/public/common/chrome_debug_urls.h"
+
+#include "render_widget_host_view_qt.h"
namespace extensions {
ExtensionWebContentsObserverQt::ExtensionWebContentsObserverQt(content::WebContents *web_contents)
: ExtensionWebContentsObserver(web_contents)
+ , content::WebContentsUserData<ExtensionWebContentsObserverQt>(*web_contents)
{
}
@@ -73,6 +41,8 @@ void ExtensionWebContentsObserverQt::CreateForWebContents(content::WebContents *
void ExtensionWebContentsObserverQt::RenderFrameCreated(content::RenderFrameHost *render_frame_host)
{
ExtensionWebContentsObserver::RenderFrameCreated(render_frame_host);
+ QtWebEngineCore::RenderWidgetHostViewQt::registerInputEventObserver(web_contents(),
+ render_frame_host);
const Extension *extension = GetExtensionFromFrame(render_frame_host, false);
if (!extension)
@@ -82,9 +52,9 @@ void ExtensionWebContentsObserverQt::RenderFrameCreated(content::RenderFrameHost
auto *policy = content::ChildProcessSecurityPolicy::GetInstance();
if (extension->is_extension() && Manifest::IsComponentLocation(extension->location()))
- policy->GrantRequestOrigin(process_id, url::Origin::Create(GURL(content::kChromeUIResourcesURL)));
+ policy->GrantRequestOrigin(process_id, url::Origin::Create(GURL(blink::kChromeUIResourcesURL)));
}
-WEB_CONTENTS_USER_DATA_KEY_IMPL(ExtensionWebContentsObserverQt)
+WEB_CONTENTS_USER_DATA_KEY_IMPL(ExtensionWebContentsObserverQt);
} // namespace extensions
diff --git a/src/core/extensions/extension_web_contents_observer_qt.h b/src/core/extensions/extension_web_contents_observer_qt.h
index 658966b31..ff50b28e2 100644
--- a/src/core/extensions/extension_web_contents_observer_qt.h
+++ b/src/core/extensions/extension_web_contents_observer_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -65,7 +29,6 @@ public:
private:
friend class content::WebContentsUserData<ExtensionWebContentsObserverQt>;
WEB_CONTENTS_USER_DATA_KEY_DECL();
- DISALLOW_COPY_AND_ASSIGN(ExtensionWebContentsObserverQt);
};
} // namespace extensions
diff --git a/src/core/extensions/extensions_api_client_qt.cpp b/src/core/extensions/extensions_api_client_qt.cpp
index 731b79a63..678c252cc 100644
--- a/src/core/extensions/extensions_api_client_qt.cpp
+++ b/src/core/extensions/extensions_api_client_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -43,14 +7,21 @@
// found in the LICENSE file.
#include "extensions_api_client_qt.h"
+#include "file_system_delegate_qt.h"
+#include "messaging_delegate_qt.h"
#include <memory>
-//#include "base/memory/ptr_util.h"
+
#include "extension_web_contents_observer_qt.h"
-#include "components/pdf/browser/pdf_web_contents_helper.h"
#include "extensions/browser/guest_view/extensions_guest_view_manager_delegate.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest_delegate.h"
+#include "mime_handler_view_guest_delegate_qt.h"
+#include "pdf/buildflags.h"
+#include "printing/buildflags/buildflags.h"
+
+#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
#include "printing/print_view_manager_qt.h"
+#endif
namespace extensions {
@@ -65,21 +36,37 @@ AppViewGuestDelegate *ExtensionsAPIClientQt::CreateAppViewGuestDelegate() const
return nullptr;
}
-std::unique_ptr<guest_view::GuestViewManagerDelegate> ExtensionsAPIClientQt::CreateGuestViewManagerDelegate(content::BrowserContext *context) const
+FileSystemDelegate *ExtensionsAPIClientQt::GetFileSystemDelegate()
+{
+ if (!m_fileSystemDelegate)
+ m_fileSystemDelegate = std::make_unique<FileSystemDelegateQt>();
+ return m_fileSystemDelegate.get();
+}
+
+std::unique_ptr<guest_view::GuestViewManagerDelegate> ExtensionsAPIClientQt::CreateGuestViewManagerDelegate() const
{
- return std::make_unique<guest_view::GuestViewManagerDelegate>();
+ return std::make_unique<extensions::ExtensionsGuestViewManagerDelegate>();
}
std::unique_ptr<MimeHandlerViewGuestDelegate> ExtensionsAPIClientQt::CreateMimeHandlerViewGuestDelegate(MimeHandlerViewGuest *guest) const
{
- return std::make_unique<MimeHandlerViewGuestDelegate>();
+ return std::make_unique<MimeHandlerViewGuestDelegateQt>(guest);
}
void ExtensionsAPIClientQt::AttachWebContentsHelpers(content::WebContents *web_contents) const
{
// PrefsTabHelper::CreateForWebContents(web_contents);
+#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
QtWebEngineCore::PrintViewManagerQt::CreateForWebContents(web_contents);
+#endif
ExtensionWebContentsObserverQt::CreateForWebContents(web_contents);
}
+MessagingDelegate *ExtensionsAPIClientQt::GetMessagingDelegate()
+{
+ if (!m_messagingDelegate)
+ m_messagingDelegate = std::make_unique<MessagingDelegateQt>();
+ return m_messagingDelegate.get();
+}
+
} // namespace extensions
diff --git a/src/core/extensions/extensions_api_client_qt.h b/src/core/extensions/extensions_api_client_qt.h
index 2fa69f539..e7838138c 100644
--- a/src/core/extensions/extensions_api_client_qt.h
+++ b/src/core/extensions/extensions_api_client_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -49,6 +13,9 @@
namespace extensions {
+class FileSystemDelegate;
+class MessagingDelegate;
+
class ExtensionsAPIClientQt : public ExtensionsAPIClient
{
public:
@@ -56,11 +23,17 @@ public:
// ExtensionsAPIClient implementation.
AppViewGuestDelegate *CreateAppViewGuestDelegate() const override;
+ FileSystemDelegate *GetFileSystemDelegate() override;
std::unique_ptr<guest_view::GuestViewManagerDelegate>
- CreateGuestViewManagerDelegate(content::BrowserContext *context) const override;
+ CreateGuestViewManagerDelegate() const override;
std::unique_ptr<MimeHandlerViewGuestDelegate>
CreateMimeHandlerViewGuestDelegate(MimeHandlerViewGuest *guest) const override;
void AttachWebContentsHelpers(content::WebContents *web_contents) const override;
+ MessagingDelegate *GetMessagingDelegate() override;
+
+private:
+ std::unique_ptr<FileSystemDelegate> m_fileSystemDelegate;
+ std::unique_ptr<MessagingDelegate> m_messagingDelegate;
};
} // namespace extensions
diff --git a/src/core/extensions/extensions_browser_client_qt.cpp b/src/core/extensions/extensions_browser_client_qt.cpp
index 1b2bb51f4..19fc6c808 100644
--- a/src/core/extensions/extensions_browser_client_qt.cpp
+++ b/src/core/extensions/extensions_browser_client_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -49,29 +13,27 @@
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
-#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
+#include "base/task/thread_pool.h"
#include "base/memory/ref_counted_memory.h"
+#include "chrome/browser/extensions/api/generated_api_registration.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
+#include "extensions/browser/api/core_extensions_browser_api_provider.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/api/runtime/runtime_api_delegate.h"
-#include "extensions/browser/app_sorting.h"
-#include "extensions/browser/core_extensions_browser_api_provider.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_host_delegate.h"
#include "extensions/browser/extension_protocols.h"
+#include "extensions/browser/extensions_browser_api_provider.h"
#include "extensions/browser/extensions_browser_interface_binders.h"
-#include "extensions/browser/mojo/interface_registration.h"
#include "extensions/browser/url_request_util.h"
#include "extensions/common/file_util.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "net/base/completion_once_callback.h"
#include "net/base/mime_util.h"
-#include "services/network/public/cpp/resource_response.h"
+#include "qtwebengine/browser/extensions/api/generated_api_registration.h"
+#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_loader.mojom.h"
+#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/zlib/google/compression_utils.h"
#include "ui/base/resource/resource_bundle.h"
@@ -80,10 +42,10 @@
#include "extension_web_contents_observer_qt.h"
#include "extensions_api_client_qt.h"
#include "extensions_browser_client_qt.h"
+#include "extension_host_delegate_qt.h"
#include "web_engine_library_info.h"
using content::BrowserContext;
-using content::BrowserThread;
namespace {
@@ -113,29 +75,13 @@ scoped_refptr<base::RefCountedMemory> GetResource(int resource_id, const std::st
extension_id)
: nullptr;
- bool is_gzipped = rb.IsGzipped(resource_id);
- if (!bytes->size() || (!replacements && !is_gzipped)) {
- return bytes;
- }
-
- base::StringPiece input(reinterpret_cast<const char *>(bytes->front()), bytes->size());
-
- std::string temp_str;
-
- base::StringPiece source = input;
- if (is_gzipped) {
- temp_str.resize(compression::GetUncompressedSize(input));
- source = temp_str;
- CHECK(compression::GzipUncompress(input, source));
- }
-
if (replacements) {
- temp_str = ui::ReplaceTemplateExpressions(source, *replacements);
+ base::StringPiece input(reinterpret_cast<const char *>(bytes->front()), bytes->size());
+ std::string temp_str = ui::ReplaceTemplateExpressions(input, *replacements);
+ DCHECK(!temp_str.empty());
+ return base::MakeRefCounted<base::RefCountedString>(std::move(temp_str));
}
-
- DCHECK(!temp_str.empty());
-
- return base::RefCountedString::TakeString(&temp_str);
+ return bytes;
}
// Loads an extension resource in a Chrome .pak file. These are used by
@@ -147,18 +93,20 @@ public:
mojo::PendingReceiver<network::mojom::URLLoader> loader,
mojo::PendingRemote<network::mojom::URLLoaderClient> client_info,
const base::FilePath &filename, int resource_id,
- const std::string &content_security_policy, bool send_cors_header)
+ scoped_refptr<net::HttpResponseHeaders> headers)
{
// Owns itself. Will live as long as its URLLoader and URLLoaderClientPtr
// bindings are alive - essentially until either the client gives up or all
// file data has been sent to it.
- auto *bundle_loader = new ResourceBundleFileLoader(content_security_policy, send_cors_header);
+ auto *bundle_loader = new ResourceBundleFileLoader(std::move(headers));
bundle_loader->Start(request, std::move(loader), std::move(client_info), filename, resource_id);
}
// mojom::URLLoader implementation:
void FollowRedirect(const std::vector<std::string> &removed_headers,
- const net::HttpRequestHeaders &modified_headers, const base::Optional<GURL> &new_url) override
+ const net::HttpRequestHeaders &modified_headers,
+ const net::HttpRequestHeaders &modified_cors_exempt_headers,
+ const absl::optional<GURL> &new_url) override
{
NOTREACHED() << "No redirects for local file loads.";
}
@@ -169,9 +117,9 @@ public:
void ResumeReadingBodyFromNet() override {}
private:
- ResourceBundleFileLoader(const std::string &content_security_policy, bool send_cors_header) : binding_(this)
+ ResourceBundleFileLoader(scoped_refptr<net::HttpResponseHeaders> headers)
+ : response_headers_(std::move(headers))
{
- response_headers_ = extensions::BuildHttpHeaders(content_security_policy, send_cors_header, base::Time());
}
~ResourceBundleFileLoader() override = default;
@@ -181,16 +129,16 @@ private:
const base::FilePath &filename, int resource_id)
{
client_.Bind(std::move(client_info_remote));
- binding_.Bind(std::move(loader));
- binding_.set_connection_error_handler(
- base::BindOnce(&ResourceBundleFileLoader::OnBindingError, base::Unretained(this)));
- client_.set_connection_error_handler(
- base::BindOnce(&ResourceBundleFileLoader::OnConnectionError, base::Unretained(this)));
+ receiver_.Bind(std::move(loader));
+ receiver_.set_disconnect_handler(base::BindOnce(
+ &ResourceBundleFileLoader::OnReceiverError, base::Unretained(this)));
+ client_.set_disconnect_handler(base::BindOnce(
+ &ResourceBundleFileLoader::OnMojoDisconnect, base::Unretained(this)));
auto data = GetResource(resource_id, request.url.host());
std::string *read_mime_type = new std::string;
- base::PostTaskAndReplyWithResult(
- FROM_HERE, { base::ThreadPool(), base::MayBlock() },
+ base::ThreadPool::PostTaskAndReplyWithResult(
+ FROM_HERE, { base::MayBlock() },
base::BindOnce(&net::GetMimeTypeFromFile, filename, base::Unretained(read_mime_type)),
base::BindOnce(&ResourceBundleFileLoader::OnMimeTypeRead, weak_factory_.GetWeakPtr(), std::move(data),
base::Owned(read_mime_type)));
@@ -198,49 +146,48 @@ private:
void OnMimeTypeRead(scoped_refptr<base::RefCountedMemory> data, std::string *read_mime_type, bool read_result)
{
- network::ResourceResponseHead head;
- head.request_start = base::TimeTicks::Now();
- head.response_start = base::TimeTicks::Now();
- head.content_length = data->size();
- head.mime_type = *read_mime_type;
- DetermineCharset(head.mime_type, data.get(), &head.charset);
- mojo::DataPipe pipe(data->size());
- if (!pipe.consumer_handle.is_valid()) {
+ auto head = network::mojom::URLResponseHead::New();
+ head->request_start = base::TimeTicks::Now();
+ head->response_start = base::TimeTicks::Now();
+ head->content_length = data->size();
+ head->mime_type = *read_mime_type;
+ DetermineCharset(head->mime_type, data.get(), &head->charset);
+ mojo::ScopedDataPipeProducerHandle producer_handle;
+ mojo::ScopedDataPipeConsumerHandle consumer_handle;
+ if (mojo::CreateDataPipe(data->size(), producer_handle, consumer_handle) != MOJO_RESULT_OK) {
client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
client_.reset();
MaybeDeleteSelf();
return;
}
- head.headers = response_headers_;
- head.headers->AddHeader(base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentLength,
- base::NumberToString(head.content_length).c_str()));
- if (!head.mime_type.empty()) {
- head.headers->AddHeader(
- base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentType, head.mime_type.c_str()));
+ head->headers = response_headers_;
+ head->headers->AddHeader(net::HttpRequestHeaders::kContentLength,
+ base::NumberToString(head->content_length).c_str());
+ if (!head->mime_type.empty()) {
+ head->headers->AddHeader(net::HttpRequestHeaders::kContentType, head->mime_type.c_str());
}
- client_->OnReceiveResponse(head);
- client_->OnStartLoadingResponseBody(std::move(pipe.consumer_handle));
+ client_->OnReceiveResponse(std::move(head), std::move(consumer_handle), absl::nullopt);
uint32_t write_size = data->size();
- MojoResult result = pipe.producer_handle->WriteData(data->front(), &write_size, MOJO_WRITE_DATA_FLAG_NONE);
+ MojoResult result = producer_handle->WriteData(data->front(), &write_size, MOJO_WRITE_DATA_FLAG_NONE);
OnFileWritten(result);
}
- void OnConnectionError()
+ void OnMojoDisconnect()
{
client_.reset();
MaybeDeleteSelf();
}
- void OnBindingError()
+ void OnReceiverError()
{
- binding_.Close();
+ receiver_.reset();
MaybeDeleteSelf();
}
void MaybeDeleteSelf()
{
- if (!binding_.is_bound() && !client_.is_bound())
+ if (!receiver_.is_bound() && !client_.is_bound())
delete this;
}
@@ -256,23 +203,51 @@ private:
MaybeDeleteSelf();
}
- mojo::Binding<network::mojom::URLLoader> binding_;
- network::mojom::URLLoaderClientPtr client_;
+ mojo::Receiver<network::mojom::URLLoader> receiver_{this};
+ mojo::Remote<network::mojom::URLLoaderClient> client_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
- base::WeakPtrFactory<ResourceBundleFileLoader> weak_factory_{ this };
-
- DISALLOW_COPY_AND_ASSIGN(ResourceBundleFileLoader);
+ base::WeakPtrFactory<ResourceBundleFileLoader> weak_factory_{this};
};
} // namespace
namespace extensions {
+// Copied from chrome/browser/extensions/chrome_extensions_browser_api_provider.(h|cc)
+class ChromeExtensionsBrowserAPIProvider : public ExtensionsBrowserAPIProvider
+{
+public:
+ ChromeExtensionsBrowserAPIProvider() = default;
+ ~ChromeExtensionsBrowserAPIProvider() override = default;
+
+ void RegisterExtensionFunctions(ExtensionFunctionRegistry *registry) override
+ {
+ // Generated APIs from Chrome.
+ api::ChromeGeneratedFunctionRegistry::RegisterAll(registry);
+ }
+
+};
+
+class QtWebEngineExtensionsBrowserAPIProvider : public ExtensionsBrowserAPIProvider
+{
+public:
+ QtWebEngineExtensionsBrowserAPIProvider() = default;
+ ~QtWebEngineExtensionsBrowserAPIProvider() override = default;
+
+ void RegisterExtensionFunctions(ExtensionFunctionRegistry *registry) override
+ {
+ // Generated APIs from QtWebEngine.
+ api::QtWebEngineGeneratedFunctionRegistry::RegisterAll(registry);
+ }
+};
+
ExtensionsBrowserClientQt::ExtensionsBrowserClientQt()
: api_client_(new ExtensionsAPIClientQt)
, resource_manager_(new ComponentExtensionResourceManagerQt)
{
AddAPIProvider(std::make_unique<CoreExtensionsBrowserAPIProvider>());
+ AddAPIProvider(std::make_unique<ChromeExtensionsBrowserAPIProvider>());
+ AddAPIProvider(std::make_unique<QtWebEngineExtensionsBrowserAPIProvider>());
}
ExtensionsBrowserClientQt::~ExtensionsBrowserClientQt()
@@ -289,7 +264,7 @@ bool ExtensionsBrowserClientQt::AreExtensionsDisabled(const base::CommandLine &c
return false;
}
-bool ExtensionsBrowserClientQt::IsValidContext(BrowserContext *context)
+bool ExtensionsBrowserClientQt::IsValidContext(void *)
{
return true;
}
@@ -316,11 +291,35 @@ BrowserContext *ExtensionsBrowserClientQt::GetOriginalContext(BrowserContext *co
return context;
}
-bool ExtensionsBrowserClientQt::IsGuestSession(BrowserContext *context) const
+content::BrowserContext* ExtensionsBrowserClientQt::GetContextRedirectedToOriginal(content::BrowserContext *context, bool)
+{
+ // like in ShellExtensionsBrowserClient:
+ return context;
+}
+
+content::BrowserContext* ExtensionsBrowserClientQt::GetContextOwnInstance(content::BrowserContext *context, bool)
+{
+ // like in ShellExtensionsBrowserClient:
+ return context;
+}
+
+content::BrowserContext* ExtensionsBrowserClientQt::GetContextForOriginalOnly(content::BrowserContext *context, bool)
+{
+ // like in ShellExtensionsBrowserClient:
+ return context;
+}
+
+bool ExtensionsBrowserClientQt::AreExtensionsDisabledForContext(content::BrowserContext*)
{
+ // like in ShellExtensionsBrowserClient:
return false;
}
+bool ExtensionsBrowserClientQt::IsGuestSession(BrowserContext *context) const
+{
+ return context->IsOffTheRecord();
+}
+
bool ExtensionsBrowserClientQt::IsExtensionIncognitoEnabled(const std::string &extension_id,
content::BrowserContext *context) const
{
@@ -369,17 +368,16 @@ void ExtensionsBrowserClientQt::LoadResourceFromResourceBundle(const network::Re
mojo::PendingReceiver<network::mojom::URLLoader> loader,
const base::FilePath &resource_relative_path,
int resource_id,
- const std::string &content_security_policy,
- mojo::PendingRemote<network::mojom::URLLoaderClient> client,
- bool send_cors_header)
+ scoped_refptr<net::HttpResponseHeaders> headers,
+ mojo::PendingRemote<network::mojom::URLLoaderClient> client)
{
ResourceBundleFileLoader::CreateAndStart(request, std::move(loader), std::move(client), resource_relative_path,
- resource_id, content_security_policy, send_cors_header);
+ resource_id, headers);
}
-bool ExtensionsBrowserClientQt::AllowCrossRendererResourceLoad(const GURL &url,
- content::ResourceType resource_type,
+bool ExtensionsBrowserClientQt::AllowCrossRendererResourceLoad(const network::ResourceRequest &request,
+ network::mojom::RequestDestination destination,
ui::PageTransition page_transition,
int child_id,
bool is_incognito,
@@ -387,12 +385,15 @@ bool ExtensionsBrowserClientQt::AllowCrossRendererResourceLoad(const GURL &url,
const ExtensionSet &extensions,
const ProcessMap &process_map)
{
-
if (extension && extension->id() == extension_misc::kPdfExtensionId)
return true;
+ // hangout services id
+ if (extension && extension->id() == "nkeimhogjdpnpccoofpliimaahmaaome")
+ return true;
+
bool allowed = false;
- if (url_request_util::AllowCrossRendererResourceLoad(url, resource_type,
+ if (url_request_util::AllowCrossRendererResourceLoad(request, destination,
page_transition, child_id,
is_incognito, extension, extensions,
process_map, &allowed)) {
@@ -419,9 +420,7 @@ ProcessManagerDelegate *ExtensionsBrowserClientQt::GetProcessManagerDelegate() c
std::unique_ptr<ExtensionHostDelegate> ExtensionsBrowserClientQt::CreateExtensionHostDelegate()
{
- // TODO(extensions): Implement to support Apps.
- NOTREACHED();
- return std::unique_ptr<ExtensionHostDelegate>();
+ return std::unique_ptr<ExtensionHostDelegate>(new ExtensionHostDelegateQt);
}
bool ExtensionsBrowserClientQt::DidVersionUpdate(BrowserContext *context)
@@ -449,15 +448,8 @@ ExtensionSystemProvider *ExtensionsBrowserClientQt::GetExtensionSystemFactory()
return ExtensionSystemFactoryQt::GetInstance();
}
-void ExtensionsBrowserClientQt::RegisterExtensionInterfaces(service_manager::BinderRegistryWithArgs<content::RenderFrameHost *> *registry,
- content::RenderFrameHost *render_frame_host,
- const Extension *extension) const
-{
- RegisterInterfacesForExtension(registry, render_frame_host, extension);
-}
-
void ExtensionsBrowserClientQt::RegisterBrowserInterfaceBindersForFrame(
- service_manager::BinderMapWithContext<content::RenderFrameHost*> *binder_map,
+ mojo::BinderMapWithContext<content::RenderFrameHost*> *binder_map,
content::RenderFrameHost* render_frame_host,
const Extension* extension) const
{
@@ -478,7 +470,8 @@ const ComponentExtensionResourceManager *ExtensionsBrowserClientQt::GetComponent
void ExtensionsBrowserClientQt::BroadcastEventToRenderers(events::HistogramValue histogram_value,
const std::string &event_name,
- std::unique_ptr<base::ListValue> args, bool dispatch_to_off_the_record_profiles)
+ base::Value::List args,
+ bool dispatch_to_off_the_record_profiles)
{
NOTIMPLEMENTED();
// TODO : do the event routing
@@ -531,7 +524,6 @@ ExtensionWebContentsObserver *ExtensionsBrowserClientQt::GetExtensionWebContents
KioskDelegate *ExtensionsBrowserClientQt::GetKioskDelegate()
{
- NOTREACHED();
return nullptr;
}
@@ -545,4 +537,10 @@ void ExtensionsBrowserClientQt::SetAPIClientForTest(ExtensionsAPIClient *api_cli
api_client_.reset(api_client);
}
+media_device_salt::MediaDeviceSaltService *ExtensionsBrowserClientQt::GetMediaDeviceSaltService(content::BrowserContext *context)
+{
+ // Not needed for QWE
+ return nullptr;
+}
+
} // namespace extensions
diff --git a/src/core/extensions/extensions_browser_client_qt.h b/src/core/extensions/extensions_browser_client_qt.h
index 97da83240..bcc8f142b 100644
--- a/src/core/extensions/extensions_browser_client_qt.h
+++ b/src/core/extensions/extensions_browser_client_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -45,8 +9,9 @@
#ifndef EXTENSIONS_BROWSER_CLIENT_QT_H_
#define EXTENSIONS_BROWSER_CLIENT_QT_H_
-#include "base/compiler_specific.h"
#include "extensions/browser/extensions_browser_client.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
namespace extensions {
@@ -64,23 +29,27 @@ public:
bool IsShuttingDown() override;
bool AreExtensionsDisabled(const base::CommandLine &command_line,
content::BrowserContext *context) override;
- bool IsValidContext(content::BrowserContext *context) override;
+ bool IsValidContext(void*) override;
bool IsSameContext(content::BrowserContext *first,
content::BrowserContext *second) override;
bool HasOffTheRecordContext(content::BrowserContext *context) override;
content::BrowserContext *GetOffTheRecordContext(content::BrowserContext *context) override;
content::BrowserContext *GetOriginalContext(content::BrowserContext *context) override;
+ content::BrowserContext *GetContextRedirectedToOriginal(content::BrowserContext*, bool) override;
+ content::BrowserContext *GetContextOwnInstance(content::BrowserContext*, bool) override;
+ content::BrowserContext *GetContextForOriginalOnly(content::BrowserContext*, bool) override;
bool IsGuestSession(content::BrowserContext *context) const override;
bool IsExtensionIncognitoEnabled(const std::string &extension_id, content::BrowserContext *context) const override;
bool CanExtensionCrossIncognito(const Extension *extension, content::BrowserContext *context) const override;
- bool AllowCrossRendererResourceLoad(const GURL &url,
- content::ResourceType resource_type,
+ bool AllowCrossRendererResourceLoad(const network::ResourceRequest &request,
+ network::mojom::RequestDestination destination,
ui::PageTransition page_transition,
int child_id,
bool is_incognito,
const Extension *extension,
const ExtensionSet &extensions,
const ProcessMap &process_map) override;
+
PrefService *GetPrefServiceForContext(content::BrowserContext *context) override;
void GetEarlyExtensionPrefsObservers(content::BrowserContext *context,
std::vector<EarlyExtensionPrefsObserver *> *observers) const override;
@@ -91,17 +60,15 @@ public:
bool IsRunningInForcedAppMode() override;
bool IsLoggedInAsPublicAccount() override;
ExtensionSystemProvider *GetExtensionSystemFactory() override;
- void RegisterBrowserInterfaceBindersForFrame(service_manager::BinderMapWithContext<content::RenderFrameHost*> *,
+ void RegisterBrowserInterfaceBindersForFrame(mojo::BinderMapWithContext<content::RenderFrameHost*> *,
content::RenderFrameHost *, const extensions::Extension *) const override;
+
std::unique_ptr<RuntimeAPIDelegate> CreateRuntimeAPIDelegate(content::BrowserContext *context) const override;
- void RegisterExtensionInterfaces(service_manager::BinderRegistryWithArgs<content::RenderFrameHost *> *registry,
- content::RenderFrameHost *render_frame_host,
- const Extension *extension) const override;
const ComponentExtensionResourceManager *
GetComponentExtensionResourceManager() override;
void BroadcastEventToRenderers(events::HistogramValue histogram_value,
const std::string &event_name,
- std::unique_ptr<base::ListValue> args,
+ base::Value::List args,
bool dispatch_to_off_the_record_profiles) override;
ExtensionCache *GetExtensionCache() override;
bool IsBackgroundUpdateAllowed() override;
@@ -126,9 +93,8 @@ public:
mojo::PendingReceiver<network::mojom::URLLoader> loader,
const base::FilePath &resource_relative_path,
int resource_id,
- const std::string &content_security_policy,
- mojo::PendingRemote<network::mojom::URLLoaderClient> client,
- bool send_cors_header) override;
+ scoped_refptr<net::HttpResponseHeaders> headers,
+ mojo::PendingRemote<network::mojom::URLLoaderClient> client) override;
// Returns the locale used by the application.
std::string GetApplicationLocale() override;
@@ -138,6 +104,10 @@ public:
// Sets the API client.
void SetAPIClientForTest(ExtensionsAPIClient *api_client);
+ bool AreExtensionsDisabledForContext(content::BrowserContext*) override;
+
+ media_device_salt::MediaDeviceSaltService *GetMediaDeviceSaltService(content::BrowserContext *context) override;
+
private:
// Support for extension APIs.
std::unique_ptr<ExtensionsAPIClient> api_client_;
@@ -146,8 +116,6 @@ private:
std::unique_ptr<ComponentExtensionResourceManager> resource_manager_;
//scoped_refptr<EventRouterForwarder> event_router_forwarder_;
-
- DISALLOW_COPY_AND_ASSIGN(ExtensionsBrowserClientQt);
};
} // namespace extensions
diff --git a/src/core/extensions/file_system_delegate_qt.cpp b/src/core/extensions/file_system_delegate_qt.cpp
new file mode 100644
index 000000000..7c1c5bbd8
--- /dev/null
+++ b/src/core/extensions/file_system_delegate_qt.cpp
@@ -0,0 +1,146 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "file_system_delegate_qt.h"
+
+#include "select_file_dialog_factory_qt.h"
+#include "type_conversion.h"
+
+#include "base/files/file_path.h"
+#include "base/files/file_path.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback.h"
+#include "base/memory/ref_counted.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents.h"
+#include "extensions/browser/api/file_system/file_system_delegate.h"
+#include "extensions/browser/extension_function.h"
+#include "ui/shell_dialogs/selected_file_info.h"
+
+#include <QStandardPaths>
+
+namespace extensions {
+
+FileEntryPickerQt::FileEntryPickerQt(
+ content::WebContents *web_contents,
+ const base::FilePath &suggested_name,
+ const ui::SelectFileDialog::FileTypeInfo *file_type_info,
+ ui::SelectFileDialog::Type picker_type,
+ FileSystemDelegate::FilesSelectedCallback files_selected_callback,
+ base::OnceClosure file_selection_canceled_callback)
+ : m_filesSelectedCallback(std::move(files_selected_callback))
+ , m_fileSelectionCanceledCallback(std::move(file_selection_canceled_callback))
+{
+ const GURL caller = web_contents->GetPrimaryMainFrame()->GetLastCommittedURL();
+ m_selectFileDialog = ui::SelectFileDialog::Create(
+ this, std::make_unique<QtWebEngineCore::SelectFilePolicyQt>(web_contents));
+ m_selectFileDialog->SelectFile(
+ picker_type, std::u16string(), suggested_name, file_type_info, 0,
+ base::FilePath::StringType(), nullptr, nullptr, &caller);
+}
+
+FileEntryPickerQt::~FileEntryPickerQt() = default;
+
+void FileEntryPickerQt::FileSelected(const base::FilePath &path,
+ int index,
+ void *params)
+{
+ MultiFilesSelected({path}, params);
+}
+
+void FileEntryPickerQt::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
+ int index,
+ void *params)
+{
+ FileSelected(file.file_path, index, params);
+}
+
+void FileEntryPickerQt::MultiFilesSelected(const std::vector<base::FilePath>& files,
+ void* params)
+{
+ Q_UNUSED(params);
+ std::move(m_filesSelectedCallback).Run(files);
+ delete this;
+}
+
+void FileEntryPickerQt::MultiFilesSelectedWithExtraInfo(
+ const std::vector<ui::SelectedFileInfo> &files,
+ void *params)
+{
+ std::vector<base::FilePath> paths;
+ for (const auto& file : files)
+ paths.push_back(file.file_path);
+ MultiFilesSelected(paths, params);
+}
+
+void FileEntryPickerQt::FileSelectionCanceled(void *params)
+{
+ std::move(m_fileSelectionCanceledCallback).Run();
+ delete this;
+}
+
+FileSystemDelegateQt::FileSystemDelegateQt()
+{
+}
+
+base::FilePath FileSystemDelegateQt::GetDefaultDirectory()
+{
+ return QtWebEngineCore::toFilePath(
+ QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
+}
+
+base::FilePath FileSystemDelegateQt::GetManagedSaveAsDirectory(
+ content::BrowserContext *browser_context,
+ const Extension &extension)
+{
+ Q_UNUSED(browser_context);
+ Q_UNUSED(extension);
+ return base::FilePath();
+}
+
+bool FileSystemDelegateQt::ShowSelectFileDialog(
+ scoped_refptr<ExtensionFunction> extension_function,
+ ui::SelectFileDialog::Type type,
+ const base::FilePath &default_path,
+ const ui::SelectFileDialog::FileTypeInfo *file_type_info,
+ FileSystemDelegate::FilesSelectedCallback files_selected_callback,
+ base::OnceClosure file_selection_canceled_callback)
+{
+ content::WebContents *web_contents = extension_function->GetSenderWebContents();
+ if (!web_contents)
+ return false;
+
+ new FileEntryPickerQt(web_contents, default_path, file_type_info, type,
+ std::move(files_selected_callback),
+ std::move(file_selection_canceled_callback));
+ return true;
+}
+
+void FileSystemDelegateQt::ConfirmSensitiveDirectoryAccess(
+ bool has_write_permission,
+ const std::u16string &app_name,
+ content::WebContents *web_contents,
+ base::OnceClosure on_accept,
+ base::OnceClosure on_cancel)
+{
+ Q_UNUSED(has_write_permission);
+ Q_UNUSED(app_name);
+ Q_UNUSED(web_contents);
+ Q_UNUSED(on_accept);
+ std::move(on_cancel).Run();
+}
+
+int FileSystemDelegateQt::GetDescriptionIdForAcceptType(const std::string &accept_type)
+{
+ Q_UNUSED(accept_type);
+ return 0;
+}
+
+SavedFilesServiceInterface *FileSystemDelegateQt::GetSavedFilesService(
+ content::BrowserContext *browser_context)
+{
+ Q_UNUSED(browser_context);
+ return nullptr;
+}
+
+} // namespace extensions
diff --git a/src/core/extensions/file_system_delegate_qt.h b/src/core/extensions/file_system_delegate_qt.h
new file mode 100644
index 000000000..1e9d87c38
--- /dev/null
+++ b/src/core/extensions/file_system_delegate_qt.h
@@ -0,0 +1,89 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_DELEGATE_QT_H
+#define FILE_SYSTEM_DELEGATE_QT_H
+
+#include "extensions/browser/api/file_system/file_system_delegate.h"
+
+#include "base/files/file_path.h"
+#include "base/functional/callback.h"
+#include "base/memory/ref_counted.h"
+#include "extensions/browser/extension_function.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
+
+#include <memory>
+#include <vector>
+
+namespace content {
+class BrowserContext;
+} // namespace content
+
+namespace extensions {
+
+class FileEntryPickerQt : public ui::SelectFileDialog::Listener {
+public:
+ FileEntryPickerQt(
+ content::WebContents *web_contents,
+ const base::FilePath &suggested_name,
+ const ui::SelectFileDialog::FileTypeInfo *file_type_info,
+ ui::SelectFileDialog::Type picker_type,
+ FileSystemDelegate::FilesSelectedCallback files_selected_callback,
+ base::OnceClosure file_selection_canceled_callback);
+
+ FileEntryPickerQt(const FileEntryPickerQt &) = delete;
+ FileEntryPickerQt &operator=(const FileEntryPickerQt &) = delete;
+
+private:
+ ~FileEntryPickerQt() override;
+
+ // ui::SelectFileDialog::Listener implementation.
+ void FileSelected(const base::FilePath &path,
+ int index,
+ void *params) override;
+ void FileSelectedWithExtraInfo(const ui::SelectedFileInfo &file,
+ int index,
+ void *params) override;
+ void MultiFilesSelected(const std::vector<base::FilePath> &files,
+ void *params) override;
+ void MultiFilesSelectedWithExtraInfo(
+ const std::vector<ui::SelectedFileInfo> &files,
+ void *params) override;
+ void FileSelectionCanceled(void *params) override;
+
+ FileSystemDelegate::FilesSelectedCallback m_filesSelectedCallback;
+ base::OnceClosure m_fileSelectionCanceledCallback;
+ scoped_refptr<ui::SelectFileDialog> m_selectFileDialog;
+};
+
+class FileSystemDelegateQt : public FileSystemDelegate
+{
+public:
+ FileSystemDelegateQt();
+
+ // FileSystemDelegate implementation
+ virtual base::FilePath GetDefaultDirectory() override;
+ virtual base::FilePath GetManagedSaveAsDirectory(
+ content::BrowserContext *browser_context,
+ const Extension &extension) override;
+ virtual bool ShowSelectFileDialog(
+ scoped_refptr<ExtensionFunction> extension_function,
+ ui::SelectFileDialog::Type type,
+ const base::FilePath &default_path,
+ const ui::SelectFileDialog::FileTypeInfo *file_types,
+ FileSystemDelegate::FilesSelectedCallback files_selected_callback,
+ base::OnceClosure file_selection_canceled_callback) override;
+ virtual void ConfirmSensitiveDirectoryAccess(
+ bool has_write_permission,
+ const std::u16string &app_name,
+ content::WebContents *web_contents,
+ base::OnceClosure on_accept,
+ base::OnceClosure on_cancel) override;
+ virtual int GetDescriptionIdForAcceptType(const std::string &accept_type) override;
+ virtual SavedFilesServiceInterface *GetSavedFilesService(
+ content::BrowserContext *browser_context) override;
+};
+
+} // namespace extensions
+
+#endif // FILE_SYSTEM_DELEGATE_QT_H
diff --git a/src/core/extensions/messaging_delegate_qt.cpp b/src/core/extensions/messaging_delegate_qt.cpp
new file mode 100644
index 000000000..b0089aea2
--- /dev/null
+++ b/src/core/extensions/messaging_delegate_qt.cpp
@@ -0,0 +1,20 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "messaging_delegate_qt.h"
+
+#include <QtGlobal>
+
+namespace extensions {
+
+MessagingDelegateQt::MessagingDelegateQt()
+{
+}
+
+absl::optional<base::Value::Dict> MessagingDelegateQt::MaybeGetTabInfo(content::WebContents *web_contents)
+{
+ Q_UNUSED(web_contents);
+ return absl::nullopt;
+}
+
+} // namespace extensions
diff --git a/src/core/extensions/messaging_delegate_qt.h b/src/core/extensions/messaging_delegate_qt.h
new file mode 100644
index 000000000..c3c6244f5
--- /dev/null
+++ b/src/core/extensions/messaging_delegate_qt.h
@@ -0,0 +1,30 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef MESSAGING_DELEGATE_QT_H
+#define MESSAGING_DELEGATE_QT_H
+
+#include "extensions/browser/api/messaging/messaging_delegate.h"
+
+namespace base {
+class DictionaryValue;
+}
+
+namespace content {
+class WebContents;
+}
+
+namespace extensions {
+
+class MessagingDelegateQt : public MessagingDelegate
+{
+public:
+ MessagingDelegateQt();
+
+ // MessagingDelegate implementation.
+ absl::optional<base::Value::Dict> MaybeGetTabInfo(content::WebContents *web_contents) override;
+};
+
+} // namespace extensions
+
+#endif // MESSAGING_DELEGATE_QT_H
diff --git a/src/core/extensions/mime_handler_view_guest_delegate_qt.cpp b/src/core/extensions/mime_handler_view_guest_delegate_qt.cpp
index 022bc7db6..fcea708b0 100644
--- a/src/core/extensions/mime_handler_view_guest_delegate_qt.cpp
+++ b/src/core/extensions/mime_handler_view_guest_delegate_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -44,33 +8,45 @@
#include "mime_handler_view_guest_delegate_qt.h"
-#include "content/browser/browser_plugin/browser_plugin_guest.h"
-#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/context_menu_params.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
+#include "profile_adapter.h"
+#include "qwebenginecontextmenurequest.h"
+#include "qwebenginecontextmenurequest_p.h"
+#include "render_widget_host_view_qt.h"
+#include "touch_selection_controller_client_qt.h"
+#include "web_contents_adapter.h"
+#include "web_contents_adapter_client.h"
+#include "web_contents_view_qt.h"
+
namespace extensions {
MimeHandlerViewGuestDelegateQt::MimeHandlerViewGuestDelegateQt(MimeHandlerViewGuest *)
: MimeHandlerViewGuestDelegate()
+ , m_contextMenuRequest(new QWebEngineContextMenuRequest(new QWebEngineContextMenuRequestPrivate))
{
}
MimeHandlerViewGuestDelegateQt::~MimeHandlerViewGuestDelegateQt()
{
+ delete m_contextMenuRequest;
}
-bool MimeHandlerViewGuestDelegateQt::HandleContextMenu(content::WebContents *web_contents, const content::ContextMenuParams &params)
+bool MimeHandlerViewGuestDelegateQt::HandleContextMenu(content::RenderFrameHost &render_frame_host, const content::ContextMenuParams &params)
{
- content::ContextMenuParams new_params = params;
-
- gfx::Point guest_coordinates =
- static_cast<content::WebContentsImpl *>(web_contents)->GetBrowserPluginGuest()->GetScreenCoordinates(gfx::Point());
-
- // Adjust (x,y) position for offset from guest to embedder.
- new_params.x += guest_coordinates.x();
- new_params.y += guest_coordinates.y();
+ content::WebContents *web_contents = content::WebContents::FromRenderFrameHost(&render_frame_host);
+ content::WebContents *parent_web_contents = guest_view::GuestViewBase::GetTopLevelWebContents(web_contents);
+ if (auto rwhv = static_cast<QtWebEngineCore::RenderWidgetHostViewQt *>(parent_web_contents->GetRenderWidgetHostView())) {
+ if (rwhv->getTouchSelectionControllerClient()->handleContextMenu(params))
+ return true;
+
+ QtWebEngineCore::WebContentsAdapterClient *adapterClient = rwhv->adapterClient();
+ QtWebEngineCore::WebContentsViewQt::update(m_contextMenuRequest, params, adapterClient->profileAdapter()->isSpellCheckEnabled());
+ adapterClient->contextMenuRequested(m_contextMenuRequest);
+ return true;
+ }
return false;
}
diff --git a/src/core/extensions/mime_handler_view_guest_delegate_qt.h b/src/core/extensions/mime_handler_view_guest_delegate_qt.h
index 6cd80689c..bdb3c840b 100644
--- a/src/core/extensions/mime_handler_view_guest_delegate_qt.h
+++ b/src/core/extensions/mime_handler_view_guest_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Portions copyright 2015 The Chromium Embedded Framework Authors.
// Portions copyright 2014 The Chromium Authors. All rights reserved.
@@ -46,8 +10,11 @@
#define MIME_HANDLER_VIEW_GUEST_DELEGATE_QT_H_
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest_delegate.h"
-#include "content/browser/web_contents/web_contents_view.h"
-#include "content/public/browser/web_contents.h"
+#include "api/qtwebenginecoreglobal_p.h"
+
+QT_BEGIN_NAMESPACE
+class QWebEngineContextMenuRequest;
+QT_END_NAMESPACE
namespace content {
struct ContextMenuParams;
@@ -62,11 +29,11 @@ public:
explicit MimeHandlerViewGuestDelegateQt(MimeHandlerViewGuest *guest);
~MimeHandlerViewGuestDelegateQt() override;
- bool HandleContextMenu(content::WebContents *web_contents,
+ bool HandleContextMenu(content::RenderFrameHost &render_frame_host,
const content::ContextMenuParams &params) override;
private:
- DISALLOW_COPY_AND_ASSIGN(MimeHandlerViewGuestDelegateQt);
+ QWebEngineContextMenuRequest *m_contextMenuRequest;
};
} // namespace extensions
diff --git a/src/core/extensions/pdf_iframe_navigation_throttle_qt.cpp b/src/core/extensions/pdf_iframe_navigation_throttle_qt.cpp
new file mode 100644
index 000000000..a494e2f49
--- /dev/null
+++ b/src/core/extensions/pdf_iframe_navigation_throttle_qt.cpp
@@ -0,0 +1,194 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on //chrome/browser/plugins/pdf_iframe_navigation_throttle.cc
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+
+#include "extensions/pdf_iframe_navigation_throttle_qt.h"
+
+#include "base/task/sequenced_task_runner.h"
+#include "chrome/grit/renderer_resources.h"
+#include "components/strings/grit/components_strings.h"
+#include "content/public/browser/download_utils.h"
+#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/plugin_service.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_user_data.h"
+#include "content/public/common/webplugininfo.h"
+#include "base/strings/escape.h"
+#include "net/http/http_response_headers.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/base/webui/jstemplate_builder.h"
+#include "ui/base/webui/web_ui_util.h"
+
+#include "pdf_util_qt.h"
+
+#include <QtGlobal>
+
+namespace extensions {
+
+// Used to scope the posted navigation task to the lifetime of |web_contents|.
+class PdfWebContentsLifetimeHelper : public content::WebContentsUserData<PdfWebContentsLifetimeHelper>
+{
+public:
+ explicit PdfWebContentsLifetimeHelper(content::WebContents *web_contents)
+ : content::WebContentsUserData<PdfWebContentsLifetimeHelper>(*web_contents)
+ {}
+
+ base::WeakPtr<PdfWebContentsLifetimeHelper> GetWeakPtr()
+ {
+ return weak_factory_.GetWeakPtr();
+ }
+
+ void NavigateIFrameToPlaceholder(const content::OpenURLParams &url_params)
+ {
+ GetWebContents().OpenURL(url_params);
+ }
+
+private:
+ friend class content::WebContentsUserData<PdfWebContentsLifetimeHelper>;
+
+ base::WeakPtrFactory<PdfWebContentsLifetimeHelper> weak_factory_{this};
+
+ WEB_CONTENTS_USER_DATA_KEY_DECL();
+};
+
+WEB_CONTENTS_USER_DATA_KEY_IMPL(PdfWebContentsLifetimeHelper);
+
+bool IsPDFPluginEnabled(content::NavigationHandle *navigation_handle, bool *is_stale)
+{
+ content::WebContents *web_contents = navigation_handle->GetWebContents();
+ Q_ASSERT(web_contents);
+
+ if (web_contents->IsInnerWebContentsForGuest())
+ web_contents = web_contents->GetOuterWebContents();
+
+ int process_id = web_contents->GetPrimaryMainFrame()->GetProcess()->GetID();
+ int routing_id = web_contents->GetPrimaryMainFrame()->GetRoutingID();
+ content::WebPluginInfo plugin_info;
+ // Will check WebEngineSettings by PluginServiceFilterQt
+ return content::PluginService::GetInstance()->GetPluginInfo(
+ process_id, routing_id,
+ navigation_handle->GetWebContents()->GetBrowserContext(),
+ navigation_handle->GetURL(),
+ QtWebEngineCore::kPDFMimeType, false /* allow_wildcard */,
+ is_stale, &plugin_info, nullptr /* actual_mime_type */);
+}
+
+std::string GetPDFPlaceholderHTML(const GURL &pdf_url)
+{
+ std::string template_html = ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_PDF_PLUGIN_HTML);
+ webui::AppendWebUiCssTextDefaults(&template_html);
+
+ base::Value::Dict values;
+ values.Set("fileName", pdf_url.ExtractFileName());
+ values.Set("open", l10n_util::GetStringUTF8(IDS_ACCNAME_OPEN));
+ values.Set("pdfUrl", pdf_url.spec());
+
+ return webui::GetI18nTemplateHtml(template_html, std::move(values));
+}
+
+// static
+std::unique_ptr<content::NavigationThrottle>
+PDFIFrameNavigationThrottleQt::MaybeCreateThrottleFor(content::NavigationHandle *handle)
+{
+ if (handle->IsInMainFrame())
+ return nullptr;
+ return std::make_unique<PDFIFrameNavigationThrottleQt>(handle);
+}
+
+PDFIFrameNavigationThrottleQt::PDFIFrameNavigationThrottleQt(content::NavigationHandle *handle)
+ : content::NavigationThrottle(handle)
+{
+}
+
+PDFIFrameNavigationThrottleQt::~PDFIFrameNavigationThrottleQt()
+{
+}
+
+content::NavigationThrottle::ThrottleCheckResult PDFIFrameNavigationThrottleQt::WillProcessResponse()
+{
+ const net::HttpResponseHeaders *response_headers = navigation_handle()->GetResponseHeaders();
+ if (!response_headers)
+ return content::NavigationThrottle::PROCEED;
+
+ std::string mime_type;
+ response_headers->GetMimeType(&mime_type);
+ if (mime_type != QtWebEngineCore::kPDFMimeType)
+ return content::NavigationThrottle::PROCEED;
+
+ // We MUST download responses marked as attachments rather than showing
+ // a placeholder.
+ if (content::download_utils::MustDownload(navigation_handle()->GetWebContents()
+ ? navigation_handle()->GetWebContents()->GetBrowserContext()
+ : nullptr,
+ navigation_handle()->GetURL(), response_headers, mime_type))
+ return content::NavigationThrottle::PROCEED;
+
+ bool is_stale = false;
+ bool pdf_plugin_enabled = IsPDFPluginEnabled(navigation_handle(), &is_stale);
+
+ if (is_stale) {
+ // On browser start, the plugin list may not be ready yet.
+ content::PluginService::GetInstance()->GetPlugins(
+ base::BindOnce(&PDFIFrameNavigationThrottleQt::OnPluginsLoaded,
+ weak_factory_.GetWeakPtr()));
+ return content::NavigationThrottle::DEFER;
+ }
+
+ // If the plugin was found, proceed on the navigation. Otherwise fall through
+ // to the placeholder case.
+ if (pdf_plugin_enabled)
+ return content::NavigationThrottle::PROCEED;
+
+ LoadPlaceholderHTML();
+ return content::NavigationThrottle::CANCEL_AND_IGNORE;
+}
+
+const char *PDFIFrameNavigationThrottleQt::GetNameForLogging()
+{
+ return "PDFIFrameNavigationThrottleQt";
+}
+
+void PDFIFrameNavigationThrottleQt::OnPluginsLoaded(
+ const std::vector<content::WebPluginInfo> &plugins)
+{
+ if (IsPDFPluginEnabled(navigation_handle(), nullptr /* is_stale */)) {
+ Resume();
+ } else {
+ LoadPlaceholderHTML();
+ CancelDeferredNavigation(content::NavigationThrottle::CANCEL_AND_IGNORE);
+ }
+}
+
+void PDFIFrameNavigationThrottleQt::LoadPlaceholderHTML()
+{
+ // Prepare the params to navigate to the placeholder.
+ std::string html = GetPDFPlaceholderHTML(navigation_handle()->GetURL());
+ GURL data_url("data:text/html," + base::EscapePath(html));
+ content::OpenURLParams params = content::OpenURLParams::FromNavigationHandle(navigation_handle());
+ params.url = data_url;
+ params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
+
+ // Post a task to navigate to the placeholder HTML. We don't navigate
+ // synchronously here, as starting a navigation within a navigation is
+ // an antipattern. Use a helper object scoped to the WebContents lifetime to
+ // scope the navigation task to the WebContents lifetime.
+ content::WebContents *web_contents = navigation_handle()->GetWebContents();
+ if (!web_contents)
+ return;
+
+ PdfWebContentsLifetimeHelper::CreateForWebContents(web_contents);
+ PdfWebContentsLifetimeHelper *helper = PdfWebContentsLifetimeHelper::FromWebContents(web_contents);
+ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&PdfWebContentsLifetimeHelper::NavigateIFrameToPlaceholder,
+ helper->GetWeakPtr(), std::move(params)));
+}
+
+} // namespace extensions
diff --git a/src/core/extensions/pdf_iframe_navigation_throttle_qt.h b/src/core/extensions/pdf_iframe_navigation_throttle_qt.h
new file mode 100644
index 000000000..fdc168aec
--- /dev/null
+++ b/src/core/extensions/pdf_iframe_navigation_throttle_qt.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on //chrome/browser/plugins/pdf_iframe_navigation_throttle.h
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_IFRAME_NAVIGATION_THROTTLE_QT
+#define PDF_IFRAME_NAVIGATION_THROTTLE_QT
+
+#include "content/public/browser/navigation_throttle.h"
+
+#include "base/memory/weak_ptr.h"
+
+namespace content {
+class NavigationHandle;
+struct WebPluginInfo;
+}
+
+namespace extensions {
+
+// This class prevents automatical download of PDFs when they are embedded
+// in subframes and plugins are disabled in API.
+class PDFIFrameNavigationThrottleQt : public content::NavigationThrottle
+{
+public:
+ static std::unique_ptr<content::NavigationThrottle> MaybeCreateThrottleFor(content::NavigationHandle *handle);
+
+ explicit PDFIFrameNavigationThrottleQt(content::NavigationHandle *handle);
+ ~PDFIFrameNavigationThrottleQt() override;
+
+ // content::NavigationThrottle
+ content::NavigationThrottle::ThrottleCheckResult WillProcessResponse() override;
+ const char *GetNameForLogging() override;
+
+private:
+ void OnPluginsLoaded(const std::vector<content::WebPluginInfo> &plugins);
+ void LoadPlaceholderHTML();
+
+ base::WeakPtrFactory<PDFIFrameNavigationThrottleQt> weak_factory_{this};
+};
+
+} // namespace extensions
+
+#endif // PDF_IFRAME_NAVIGATION_THROTTLE_QT
diff --git a/src/core/extensions/pdf_web_contents_helper_client_qt.h b/src/core/extensions/pdf_web_contents_helper_client_qt.h
deleted file mode 100644
index 9a37375b3..000000000
--- a/src/core/extensions/pdf_web_contents_helper_client_qt.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef PDF_WEB_CONTENTS_HELPER_CLIENT_QT_H_
-#define PDF_WEB_CONTENTS_HELPER_CLIENT_QT_H_
-
-#include "base/macros.h"
-#include "components/pdf/browser/pdf_web_contents_helper_client.h"
-
-namespace extensions {
-
-class PDFWebContentsHelperClientQt : public pdf::PDFWebContentsHelperClient
-{
-public:
- PDFWebContentsHelperClientQt();
- ~PDFWebContentsHelperClientQt() override;
-
-private:
- // pdf::PDFWebContentsHelperClient:
- void UpdateContentRestrictions(content::WebContents *contents, int content_restrictions) override;
- void OnPDFHasUnsupportedFeature(content::WebContents *contents) override;
- void OnSaveURL(content::WebContents *contents) override;
-
- DISALLOW_COPY_AND_ASSIGN(PDFWebContentsHelperClientQt);
-};
-
-} // namespace extensions
-
-#endif // PDF_WEB_CONTENTS_HELPER_CLIENT_QT_H_
diff --git a/src/core/extensions/plugin_service_filter_qt.cpp b/src/core/extensions/plugin_service_filter_qt.cpp
new file mode 100644
index 000000000..1f6c606bc
--- /dev/null
+++ b/src/core/extensions/plugin_service_filter_qt.cpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "extensions/plugin_service_filter_qt.h"
+
+#include "content/public/browser/render_process_host.h"
+
+#include "web_contents_delegate_qt.h"
+#include "web_engine_settings.h"
+
+using namespace QtWebEngineCore;
+
+namespace extensions {
+
+// static
+PluginServiceFilterQt *PluginServiceFilterQt::GetInstance()
+{
+ return base::Singleton<PluginServiceFilterQt>::get();
+}
+
+bool PluginServiceFilterQt::IsPluginAvailable(int render_process_id, int render_frame_id,
+ content::BrowserContext *browser_context,
+ const content::WebPluginInfo &plugin)
+{
+ Q_UNUSED(plugin);
+ Q_UNUSED(browser_context);
+ content::RenderFrameHost *frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id);
+ content::WebContents *web_contents = content::WebContents::FromRenderFrameHost(frame_host);
+ if (!web_contents) {
+ // Availability checked somewhere before/during WebContents initialization. Let it load and enable
+ // all the plugins at this phase. This information will be queried again when receiving the response
+ // for the requested content. Postponing our decision and enabling/blocking there makes WebEngineSettings
+ // modifiable in runtime without reconstructing WebContents.
+ return true;
+ }
+
+ if (web_contents->IsInnerWebContentsForGuest())
+ web_contents = web_contents->GetOuterWebContents();
+
+ if (auto *delegate = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate())) {
+ const WebEngineSettings *settings = delegate->webEngineSettings();
+ if (!settings->testAttribute(QWebEngineSettings::PdfViewerEnabled)
+ || !settings->testAttribute(QWebEngineSettings::PluginsEnabled))
+ return false;
+ }
+
+ return true;
+}
+
+bool PluginServiceFilterQt::CanLoadPlugin(int render_process_id,
+ const base::FilePath &path)
+{
+ return true;
+}
+
+PluginServiceFilterQt::PluginServiceFilterQt()
+{
+}
+
+PluginServiceFilterQt::~PluginServiceFilterQt()
+{
+}
+
+} // namespace extensions
diff --git a/src/core/extensions/plugin_service_filter_qt.h b/src/core/extensions/plugin_service_filter_qt.h
new file mode 100644
index 000000000..d171edfde
--- /dev/null
+++ b/src/core/extensions/plugin_service_filter_qt.h
@@ -0,0 +1,33 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef PLUGIN_SERVICE_FILTER_QT
+#define PLUGIN_SERVICE_FILTER_QT
+
+#include "content/public/browser/plugin_service_filter.h"
+
+#include "base/memory/singleton.h"
+
+namespace extensions {
+
+class PluginServiceFilterQt : public content::PluginServiceFilter {
+public:
+ static PluginServiceFilterQt* GetInstance();
+
+ bool IsPluginAvailable(int render_process_id, int render_frame_id,
+ content::BrowserContext *browser_context,
+ const content::WebPluginInfo &plugin) override;
+
+ bool CanLoadPlugin(int render_process_id,
+ const base::FilePath &path) override;
+
+private:
+ friend struct base::DefaultSingletonTraits<PluginServiceFilterQt>;
+
+ PluginServiceFilterQt();
+ ~PluginServiceFilterQt();
+};
+
+} // namespace extensions
+
+#endif // PLUGIN_SERVICE_FILTER_QT
diff --git a/src/core/favicon_driver_qt.cpp b/src/core/favicon_driver_qt.cpp
new file mode 100644
index 000000000..bb4a734b4
--- /dev/null
+++ b/src/core/favicon_driver_qt.cpp
@@ -0,0 +1,422 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// Based on components/favicon/content/content_favicon_driver.cc:
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "favicon_driver_qt.h"
+#include "type_conversion.h"
+#include "web_contents_adapter_client.h"
+#include "web_engine_settings.h"
+
+#include "components/favicon/content/favicon_url_util.h"
+#include "components/favicon/core/favicon_service.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/navigation_handle.h"
+#include "content/public/browser/page.h"
+#include "content/public/browser/render_frame_host.h"
+#include "third_party/blink/public/mojom/manifest/manifest.mojom.h"
+
+namespace QtWebEngineCore {
+
+namespace {
+
+int activeHandlersCount(QWebEngineSettings *settings)
+{
+ bool touchIconsEnabled = settings->testAttribute(QWebEngineSettings::TouchIconsEnabled);
+ return touchIconsEnabled ? 2 : 1;
+}
+
+} // namespace
+
+FaviconStatusQt::FaviconStatusQt()
+ : FaviconStatus(), source(favicon::FaviconDriverObserver::NON_TOUCH_16_DIP)
+{
+}
+
+// static
+void FaviconDriverQt::CreateForWebContents(content::WebContents *webContents,
+ favicon::CoreFaviconService *faviconService,
+ WebContentsAdapterClient *viewClient)
+{
+ if (FromWebContents(webContents))
+ return;
+
+ webContents->SetUserData(
+ UserDataKey(),
+ base::WrapUnique(new FaviconDriverQt(webContents, faviconService, viewClient)));
+}
+
+FaviconDriverQt::FaviconDriverQt(content::WebContents *webContents,
+ favicon::CoreFaviconService *faviconService,
+ WebContentsAdapterClient *viewClient)
+ : content::WebContentsObserver(webContents)
+ , content::WebContentsUserData<FaviconDriverQt>(*webContents)
+ , m_faviconService(faviconService)
+ , m_viewClient(viewClient)
+{
+ if (!m_faviconService)
+ return;
+
+ m_handlers.push_back(std::make_unique<favicon::FaviconHandler>(
+ m_faviconService, this, favicon::FaviconDriverObserver::NON_TOUCH_16_DIP));
+ m_handlers.push_back(std::make_unique<favicon::FaviconHandler>(
+ m_faviconService, this, favicon::FaviconDriverObserver::NON_TOUCH_LARGEST));
+ m_handlers.push_back(std::make_unique<favicon::FaviconHandler>(
+ m_faviconService, this, favicon::FaviconDriverObserver::TOUCH_LARGEST));
+}
+
+void FaviconDriverQt::FetchFavicon(const GURL &page_url, bool is_same_document)
+{
+ QWebEngineSettings *settings = m_viewClient->webEngineSettings();
+ bool iconsEnabled = settings->testAttribute(QWebEngineSettings::AutoLoadIconsForPage);
+ bool touchIconsEnabled = settings->testAttribute(QWebEngineSettings::TouchIconsEnabled);
+
+ if (!iconsEnabled)
+ return;
+
+ for (const std::unique_ptr<favicon::FaviconHandler> &handler : m_handlers) {
+ switch (handler->Type()) {
+ case favicon::FaviconDriverObserver::NON_TOUCH_16_DIP:
+ if (touchIconsEnabled)
+ continue;
+ break;
+ case favicon::FaviconDriverObserver::NON_TOUCH_LARGEST:
+ case favicon::FaviconDriverObserver::TOUCH_LARGEST:
+ if (!touchIconsEnabled)
+ continue;
+ break;
+ }
+
+ handler->FetchFavicon(page_url, is_same_document);
+ }
+}
+
+gfx::Image FaviconDriverQt::GetFavicon() const
+{
+ // Like GetTitle(), we also want to use the favicon for the last committed
+ // entry rather than a pending navigation entry.
+ content::NavigationController &controller = web_contents()->GetController();
+
+ content::NavigationEntry *entry = controller.GetLastCommittedEntry();
+ if (entry)
+ return entry->GetFavicon().image;
+ return gfx::Image();
+}
+
+bool FaviconDriverQt::FaviconIsValid() const
+{
+ content::NavigationController &controller = web_contents()->GetController();
+
+ content::NavigationEntry *entry = controller.GetLastCommittedEntry();
+ if (entry)
+ return entry->GetFavicon().valid;
+
+ return false;
+}
+
+GURL FaviconDriverQt::GetActiveURL()
+{
+ content::NavigationEntry *entry = web_contents()->GetController().GetLastCommittedEntry();
+ return entry ? entry->GetURL() : GURL();
+}
+
+GURL FaviconDriverQt::GetManifestURL(content::RenderFrameHost *rfh)
+{
+ DocumentManifestData *document_data = DocumentManifestData::GetOrCreateForCurrentDocument(rfh);
+ return document_data->has_manifest_url ? rfh->GetPage().GetManifestUrl().value_or(GURL())
+ : GURL();
+}
+
+GURL FaviconDriverQt::GetFaviconURL() const
+{
+ content::NavigationController &controller = web_contents()->GetController();
+
+ content::NavigationEntry *entry = controller.GetLastCommittedEntry();
+ if (entry)
+ return entry->GetFavicon().url;
+ return GURL();
+}
+
+FaviconDriverQt::DocumentManifestData::DocumentManifestData(content::RenderFrameHost *rfh)
+ : content::DocumentUserData<DocumentManifestData>(rfh)
+{
+}
+
+FaviconDriverQt::DocumentManifestData::~DocumentManifestData() = default;
+
+FaviconDriverQt::NavigationManifestData::NavigationManifestData(
+ content::NavigationHandle &navigation_handle)
+{
+}
+
+FaviconDriverQt::NavigationManifestData::~NavigationManifestData() = default;
+
+void FaviconDriverQt::OnDidDownloadManifest(ManifestDownloadCallback callback,
+ const GURL &manifest_url,
+ blink::mojom::ManifestPtr manifest)
+{
+ Q_UNUSED(manifest_url);
+
+ // ~WebContentsImpl triggers running any pending callbacks for manifests.
+ // As we're about to be destroyed ignore the request. To do otherwise may
+ // result in calling back to this and attempting to use the WebContents, which
+ // will crash.
+ if (!web_contents())
+ return;
+
+ std::vector<favicon::FaviconURL> candidates;
+ if (manifest) {
+ for (const auto &icon : manifest->icons) {
+ candidates.emplace_back(icon.src, favicon_base::IconType::kWebManifestIcon, icon.sizes);
+ }
+ }
+ std::move(callback).Run(candidates);
+}
+
+int FaviconDriverQt::DownloadImage(const GURL &url, int max_image_size,
+ ImageDownloadCallback callback)
+{
+ bool bypass_cache = (m_bypassCachePageURL == GetActiveURL());
+ m_bypassCachePageURL = GURL();
+
+ const gfx::Size preferred_size(max_image_size, max_image_size);
+ return web_contents()->DownloadImage(url, true, preferred_size,
+ /*max_bitmap_size=*/max_image_size,
+ bypass_cache, std::move(callback));
+}
+
+void FaviconDriverQt::DownloadManifest(const GURL &url, ManifestDownloadCallback callback)
+{
+ // TODO(crbug.com/1201237): This appears to be reachable from pages other
+ // than the primary page. This code should likely be refactored so that either
+ // this is unreachable from other pages, or the correct page is plumbed in
+ // here.
+ web_contents()->GetPrimaryPage().GetManifest(base::BindOnce(
+ &FaviconDriverQt::OnDidDownloadManifest, base::Unretained(this), std::move(callback)));
+}
+
+bool FaviconDriverQt::IsOffTheRecord()
+{
+ DCHECK(web_contents());
+ return web_contents()->GetBrowserContext()->IsOffTheRecord();
+}
+
+void FaviconDriverQt::OnFaviconUpdated(
+ const GURL &page_url,
+ favicon::FaviconDriverObserver::NotificationIconType notification_icon_type,
+ const GURL &icon_url, bool icon_url_changed, const gfx::Image &image)
+{
+ Q_UNUSED(page_url);
+
+ QWebEngineSettings *settings = m_viewClient->webEngineSettings();
+ bool touchIconsEnabled = settings->testAttribute(QWebEngineSettings::TouchIconsEnabled);
+
+ // Prefer touch icons over favicons if touch icons are enabled.
+ if (!touchIconsEnabled
+ || m_latestFavicon.source != favicon::FaviconDriverObserver::TOUCH_LARGEST
+ || notification_icon_type == favicon::FaviconDriverObserver::TOUCH_LARGEST) {
+ m_latestFavicon.valid = true;
+ m_latestFavicon.url = icon_url;
+ m_latestFavicon.image = image;
+ m_latestFavicon.source = notification_icon_type;
+ }
+
+ NotifyFaviconUpdatedObservers(notification_icon_type, icon_url, icon_url_changed, image);
+ emitIconChangedIfNeeded();
+}
+
+void FaviconDriverQt::OnFaviconDeleted(
+ const GURL &page_url,
+ favicon::FaviconDriverObserver::NotificationIconType notification_icon_type)
+{
+ content::NavigationEntry *entry = web_contents()->GetController().GetLastCommittedEntry();
+ DCHECK(entry && entry->GetURL() == page_url);
+
+ entry->GetFavicon() = FaviconStatusQt();
+ web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TAB);
+
+ NotifyFaviconUpdatedObservers(notification_icon_type, /*icon_url=*/GURL(),
+ /*icon_url_changed=*/true, FaviconStatusQt().image);
+}
+
+void FaviconDriverQt::OnHandlerCompleted(favicon::FaviconHandler *handler)
+{
+ Q_UNUSED(handler);
+
+ if (activeHandlersCount(m_viewClient->webEngineSettings()) > m_completedHandlersCount)
+ ++m_completedHandlersCount;
+ emitIconChangedIfNeeded();
+}
+
+void FaviconDriverQt::DidUpdateFaviconURL(
+ content::RenderFrameHost *rfh, const std::vector<blink::mojom::FaviconURLPtr> &candidates)
+{
+ // Ignore the update if there is no last committed navigation entry. This can
+ // occur when loading an initially blank page.
+ content::NavigationEntry *entry = web_contents()->GetController().GetLastCommittedEntry();
+
+ if (!entry)
+ return;
+
+ // We update |m_faviconUrls| even if the list is believed to be partial
+ // (checked below), because callers of our getter favicon_urls() expect so.
+ std::vector<blink::mojom::FaviconURLPtr> faviconUrls;
+ for (const auto &candidate : candidates)
+ faviconUrls.push_back(candidate.Clone());
+ m_faviconUrls = std::move(faviconUrls);
+
+ if (!rfh->IsDocumentOnLoadCompletedInMainFrame())
+ return;
+
+ OnUpdateCandidates(rfh->GetLastCommittedURL(),
+ favicon::FaviconURLsFromContentFaviconURLs(candidates), GetManifestURL(rfh));
+}
+
+void FaviconDriverQt::DidUpdateWebManifestURL(content::RenderFrameHost *rfh,
+ const GURL &manifest_url)
+{
+ Q_UNUSED(manifest_url);
+
+ // Ignore the update if there is no last committed navigation entry. This can
+ // occur when loading an initially blank page.
+ content::NavigationEntry *entry = web_contents()->GetController().GetLastCommittedEntry();
+ if (!entry || !rfh->IsDocumentOnLoadCompletedInMainFrame())
+ return;
+
+ DocumentManifestData *document_data = DocumentManifestData::GetOrCreateForCurrentDocument(rfh);
+ document_data->has_manifest_url = true;
+
+ // On regular page loads, DidUpdateManifestURL() is guaranteed to be called
+ // before DidUpdateFaviconURL(). However, a page can update the favicons via
+ // javascript.
+ if (!rfh->FaviconURLs().empty()) {
+ OnUpdateCandidates(rfh->GetLastCommittedURL(),
+ favicon::FaviconURLsFromContentFaviconURLs(rfh->FaviconURLs()),
+ GetManifestURL(rfh));
+ }
+}
+
+void FaviconDriverQt::DidStartNavigation(content::NavigationHandle *navigation_handle)
+{
+ if (!navigation_handle->IsInPrimaryMainFrame())
+ return;
+
+ if (!navigation_handle->IsSameDocument()) {
+ m_completedHandlersCount = 0;
+ m_latestFavicon = FaviconStatusQt();
+ m_viewClient->iconChanged(QUrl());
+ }
+
+ content::ReloadType reload_type = navigation_handle->GetReloadType();
+ if (reload_type == content::ReloadType::NONE || IsOffTheRecord())
+ return;
+
+ if (!navigation_handle->IsSameDocument()) {
+ NavigationManifestData *navigation_data =
+ NavigationManifestData::GetOrCreateForNavigationHandle(*navigation_handle);
+ navigation_data->has_manifest_url = false;
+ }
+
+ if (reload_type == content::ReloadType::BYPASSING_CACHE)
+ m_bypassCachePageURL = navigation_handle->GetURL();
+
+ SetFaviconOutOfDateForPage(navigation_handle->GetURL(),
+ reload_type == content::ReloadType::BYPASSING_CACHE);
+}
+
+void FaviconDriverQt::DidFinishNavigation(content::NavigationHandle *navigation_handle)
+{
+ if (!navigation_handle->IsInPrimaryMainFrame() || !navigation_handle->HasCommitted()
+ || navigation_handle->IsErrorPage()) {
+ return;
+ }
+
+ // Transfer in-flight navigation data to the document user data.
+ NavigationManifestData *navigation_data =
+ NavigationManifestData::GetOrCreateForNavigationHandle(*navigation_handle);
+ DocumentManifestData *document_data = DocumentManifestData::GetOrCreateForCurrentDocument(
+ navigation_handle->GetRenderFrameHost());
+ document_data->has_manifest_url = navigation_data->has_manifest_url;
+
+ // Wait till the user navigates to a new URL to start checking the cache
+ // again. The cache may be ignored for non-reload navigations (e.g.
+ // history.replace() in-page navigation). This is allowed to increase the
+ // likelihood that "reloading a page ignoring the cache" redownloads the
+ // favicon. In particular, a page may do an in-page navigation before
+ // FaviconHandler has the time to determine that the favicon needs to be
+ // redownloaded.
+ GURL url = navigation_handle->GetURL();
+ if (url != m_bypassCachePageURL)
+ m_bypassCachePageURL = GURL();
+
+ // Get the favicon, either from history or request it from the net.
+ FetchFavicon(url, navigation_handle->IsSameDocument());
+}
+
+void FaviconDriverQt::SetFaviconOutOfDateForPage(const GURL &url, bool force_reload)
+{
+ if (m_faviconService) {
+ m_faviconService->SetFaviconOutOfDateForPage(url);
+ if (force_reload)
+ m_faviconService->ClearUnableToDownloadFavicons();
+ }
+}
+
+void FaviconDriverQt::OnUpdateCandidates(const GURL &page_url,
+ const std::vector<favicon::FaviconURL> &candidates,
+ const GURL &manifest_url)
+{
+ QWebEngineSettings *settings = m_viewClient->webEngineSettings();
+ bool touchIconsEnabled = settings->testAttribute(QWebEngineSettings::TouchIconsEnabled);
+ for (const std::unique_ptr<favicon::FaviconHandler> &handler : m_handlers) {
+ switch (handler->Type()) {
+ case favicon::FaviconDriverObserver::NON_TOUCH_16_DIP:
+ if (touchIconsEnabled)
+ continue;
+ break;
+ case favicon::FaviconDriverObserver::NON_TOUCH_LARGEST:
+ case favicon::FaviconDriverObserver::TOUCH_LARGEST:
+ if (!touchIconsEnabled)
+ continue;
+ break;
+ }
+
+ // We feed in the Web Manifest URL (if any) to the instance handling type
+ // kWebManifestIcon, because those compete which each other (i.e. manifest
+ // icons override inline touch icons).
+ handler->OnUpdateCandidates(
+ page_url, candidates,
+ (handler->icon_types().count(favicon_base::IconType::kWebManifestIcon) != 0)
+ ? manifest_url
+ : GURL::EmptyGURL());
+ }
+}
+
+void FaviconDriverQt::emitIconChangedIfNeeded()
+{
+ if (activeHandlersCount(m_viewClient->webEngineSettings()) != m_completedHandlersCount)
+ return;
+
+ content::NavigationEntry *entry = web_contents()->GetController().GetLastCommittedEntry();
+ DCHECK(entry);
+
+ if (entry->GetFavicon().url != m_latestFavicon.url) {
+ entry->GetFavicon().valid = m_latestFavicon.valid;
+ entry->GetFavicon().url = m_latestFavicon.url;
+ entry->GetFavicon().image = m_latestFavicon.image;
+ web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TAB);
+ }
+
+ m_viewClient->iconChanged(toQt(m_latestFavicon.url));
+}
+
+NAVIGATION_HANDLE_USER_DATA_KEY_IMPL(FaviconDriverQt::NavigationManifestData);
+DOCUMENT_USER_DATA_KEY_IMPL(FaviconDriverQt::DocumentManifestData);
+WEB_CONTENTS_USER_DATA_KEY_IMPL(FaviconDriverQt);
+
+} // namespace QtWebEngineCore
diff --git a/src/core/favicon_driver_qt.h b/src/core/favicon_driver_qt.h
new file mode 100644
index 000000000..96bd682a2
--- /dev/null
+++ b/src/core/favicon_driver_qt.h
@@ -0,0 +1,151 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef FAVICON_DRIVER_QT_H
+#define FAVICON_DRIVER_QT_H
+
+#include "qtwebenginecoreglobal_p.h"
+
+#include "components/favicon/core/favicon_driver.h"
+#include "components/favicon/core/favicon_handler.h"
+#include "content/public/browser/document_user_data.h"
+#include "content/public/browser/favicon_status.h"
+#include "content/public/browser/navigation_handle_user_data.h"
+#include "content/public/browser/web_contents_observer.h"
+#include "content/public/browser/web_contents_user_data.h"
+#include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h"
+
+namespace content {
+class WebContents;
+}
+
+namespace favicon {
+class CoreFaviconService;
+}
+
+namespace QtWebEngineCore {
+
+class WebContentsAdapterClient;
+
+struct FaviconStatusQt : public content::FaviconStatus
+{
+ FaviconStatusQt();
+
+ // Type of the favicon::FaviconHandler that provided this icon.
+ favicon::FaviconDriverObserver::NotificationIconType source;
+};
+
+class FaviconDriverQt : public favicon::FaviconDriver,
+ public favicon::FaviconHandler::Delegate,
+ public content::WebContentsObserver,
+ public content::WebContentsUserData<FaviconDriverQt>
+{
+public:
+ static void CreateForWebContents(content::WebContents *webContents,
+ favicon::CoreFaviconService *faviconService,
+ WebContentsAdapterClient *viewClient);
+
+ // FaviconDriver implementation.
+ void FetchFavicon(const GURL &page_url, bool is_same_document) override;
+ gfx::Image GetFavicon() const override;
+ bool FaviconIsValid() const override;
+ GURL GetActiveURL() override;
+
+ GURL GetManifestURL(content::RenderFrameHost *rfh);
+ GURL GetFaviconURL() const;
+
+protected:
+ FaviconDriverQt(content::WebContents *webContent, favicon::CoreFaviconService *faviconService,
+ WebContentsAdapterClient *viewClient);
+
+private:
+ friend class content::WebContentsUserData<FaviconDriverQt>;
+
+ // TODO(crbug.com/1205018): these two classes are current used to ensure that
+ // we disregard manifest URL updates that arrive prior to onload firing.
+ struct DocumentManifestData : public content::DocumentUserData<DocumentManifestData>
+ {
+ explicit DocumentManifestData(content::RenderFrameHost *rfh);
+ ~DocumentManifestData() override;
+ DOCUMENT_USER_DATA_KEY_DECL();
+ bool has_manifest_url = false;
+ };
+
+ struct NavigationManifestData : public content::NavigationHandleUserData<NavigationManifestData>
+ {
+ explicit NavigationManifestData(content::NavigationHandle &navigation_handle);
+ ~NavigationManifestData() override;
+ NAVIGATION_HANDLE_USER_DATA_KEY_DECL();
+ bool has_manifest_url = false;
+ };
+
+ // Callback when a manifest is downloaded.
+ void OnDidDownloadManifest(ManifestDownloadCallback callback, const GURL &manifest_url,
+ blink::mojom::ManifestPtr manifest);
+
+ // FaviconHandler::Delegate implementation.
+ int DownloadImage(const GURL &url, int max_image_size, ImageDownloadCallback callback) override;
+ void DownloadManifest(const GURL &url, ManifestDownloadCallback callback) override;
+ bool IsOffTheRecord() override;
+ void OnFaviconUpdated(const GURL &page_url,
+ favicon::FaviconDriverObserver::NotificationIconType icon_type,
+ const GURL &icon_url, bool icon_url_changed,
+ const gfx::Image &image) override;
+ void OnFaviconDeleted(
+ const GURL &page_url,
+ favicon::FaviconDriverObserver::NotificationIconType notification_icon_type) override;
+ void OnHandlerCompleted(favicon::FaviconHandler *handler) override;
+
+ // content::WebContentsObserver implementation.
+ void DidUpdateFaviconURL(content::RenderFrameHost *rfh,
+ const std::vector<blink::mojom::FaviconURLPtr> &candidates) override;
+ void DidUpdateWebManifestURL(content::RenderFrameHost *rfh, const GURL &manifest_url) override;
+ void DidStartNavigation(content::NavigationHandle *navigation_handle) override;
+ void DidFinishNavigation(content::NavigationHandle *navigation_handle) override;
+
+ // Informs CoreFaviconService that the favicon for |url| is out of date. If
+ // |force_reload| is true, then discard information about favicon download
+ // failures.
+ void SetFaviconOutOfDateForPage(const GURL &url, bool force_reload);
+
+ // Broadcasts new favicon URL candidates to FaviconHandlers.
+ void OnUpdateCandidates(const GURL &page_url,
+ const std::vector<favicon::FaviconURL> &candidates,
+ const GURL &manifest_url);
+
+ void emitIconChangedIfNeeded();
+
+ // KeyedService used by FaviconDriverImpl. It may be null during testing,
+ // but if it is defined, it must outlive the FaviconDriverImpl.
+ raw_ptr<favicon::CoreFaviconService> m_faviconService;
+
+ WebContentsAdapterClient *m_viewClient;
+
+ // FaviconHandlers are used to download the different kind of favicons.
+ std::vector<std::unique_ptr<favicon::FaviconHandler>> m_handlers;
+
+ GURL m_bypassCachePageURL;
+
+ // nullopt until the actual list is reported via DidUpdateFaviconURL().
+ absl::optional<std::vector<blink::mojom::FaviconURLPtr>> m_faviconUrls;
+
+ int m_completedHandlersCount = 0;
+ FaviconStatusQt m_latestFavicon;
+
+ WEB_CONTENTS_USER_DATA_KEY_DECL();
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FAVICON_DRIVER_QT_H
diff --git a/src/core/favicon_manager.cpp b/src/core/favicon_manager.cpp
deleted file mode 100644
index 412aab90d..000000000
--- a/src/core/favicon_manager.cpp
+++ /dev/null
@@ -1,418 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "favicon_manager.h"
-#include "type_conversion.h"
-#include "web_contents_adapter_client.h"
-#include "web_engine_settings.h"
-
-#include "base/bind.h"
-#include "content/public/browser/favicon_status.h"
-#include "content/public/browser/navigation_entry.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/url_constants.h"
-#include "net/base/data_url.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkPixelRef.h"
-#include "ui/gfx/geometry/size.h"
-
-namespace QtWebEngineCore {
-
-static inline bool isResourceUrl(const QUrl &url)
-{
- return !url.scheme().compare(QLatin1String("qrc"));
-}
-
-static inline bool isDataUrl(const QUrl &url)
-{
- return !url.scheme().compare(QLatin1String(url::kDataScheme));
-}
-
-static inline unsigned area(const QSize &size)
-{
- return size.width() * size.height();
-}
-
-
-FaviconManager::FaviconManager(content::WebContents *webContents, WebContentsAdapterClient *viewClient)
- : m_webContents(webContents)
- , m_viewClient(viewClient)
- , m_candidateCount(0)
- , m_weakFactory(new base::WeakPtrFactory<FaviconManager>(this))
-{
-}
-
-FaviconManager::~FaviconManager()
-{
-}
-
-int FaviconManager::downloadIcon(const QUrl &url)
-{
- static const uint32_t maxSize = 256;
- static int fakeId = 0;
- int id;
-
- bool cached = m_icons.contains(url);
- if (isResourceUrl(url) || isDataUrl(url) || cached) {
- id = --fakeId;
- m_pendingRequests.insert(id, url);
- } else {
- id = m_webContents->DownloadImage(
- toGurl(url),
- true, // is_favicon
- 0, // preferred_size
- maxSize,
- false, // normal cache policy
- base::Bind(&FaviconManager::iconDownloadFinished, m_weakFactory->GetWeakPtr()));
- }
-
- Q_ASSERT(!m_inProgressRequests.contains(id));
- m_inProgressRequests.insert(id, url);
-
- return id;
-}
-
-void FaviconManager::iconDownloadFinished(int id,
- int status,
- const GURL &url,
- const std::vector<SkBitmap> &bitmaps,
- const std::vector<gfx::Size> &original_bitmap_sizes)
-{
- Q_UNUSED(status);
- Q_UNUSED(url);
- Q_UNUSED(original_bitmap_sizes);
-
- storeIcon(id, toQIcon(bitmaps));
-}
-
-/* Pending requests are used to mark icons that are already downloaded (cached icons or icons
- * stored in qrc). These requests are also stored in the m_inProgressRequests but the corresponding
- * icons are stored in m_icons explicitly by this function. It is necessary to avoid
- * m_inProgressRequests being emptied right before the next icon is added by a downloadIcon() call.
- */
-void FaviconManager::downloadPendingRequests()
-{
- for (auto it = m_pendingRequests.cbegin(), end = m_pendingRequests.cend(); it != end; ++it) {
- QIcon icon;
-
- QUrl requestUrl = it.value();
- if (!m_icons.contains(requestUrl)) {
- if (isResourceUrl(requestUrl)) {
- icon = QIcon(requestUrl.toString().remove(0, 3));
- } else if (isDataUrl(requestUrl)) {
- std::string mime_type, char_set, data;
- if (net::DataURL::Parse(toGurl(requestUrl), &mime_type, &char_set, &data) && !data.empty()) {
- const unsigned char *src_data = reinterpret_cast<const unsigned char *>(data.data());
- QImage image = QImage::fromData(src_data, data.size());
- icon.addPixmap(QPixmap::fromImage(image).copy());
- }
- }
- }
-
- storeIcon(it.key(), icon);
- }
-
- m_pendingRequests.clear();
-}
-
-void FaviconManager::storeIcon(int id, const QIcon &icon)
-{
-
- // Icon download has been interrupted
- if (!m_inProgressRequests.contains(id))
- return;
-
- QUrl requestUrl = m_inProgressRequests[id];
- FaviconInfo &faviconInfo = m_faviconInfoMap[requestUrl];
-
- unsigned iconCount = 0;
- if (!icon.isNull())
- iconCount = icon.availableSizes().count();
-
- if (iconCount > 0) {
- m_icons.insert(requestUrl, icon);
-
- faviconInfo.size = icon.availableSizes().at(0);
- if (iconCount > 1) {
- faviconInfo.multiSize = true;
- unsigned bestArea = area(faviconInfo.size);
- for (unsigned i = 1; i < iconCount; ++i) {
- QSize iconSize = icon.availableSizes().at(i);
- if (bestArea < area(iconSize)) {
- faviconInfo.size = iconSize;
- bestArea = area(iconSize);
- }
- }
- }
- } else if (id >= 0) {
- // Reset size if icon cannot be downloaded
- faviconInfo.size = QSize(0, 0);
- }
-
- m_inProgressRequests.remove(id);
- if (m_inProgressRequests.isEmpty()) {
- WebEngineSettings *settings = m_viewClient->webEngineSettings();
- bool touchIconsEnabled = settings->testAttribute(WebEngineSettings::TouchIconsEnabled);
-
- generateCandidateIcon(touchIconsEnabled);
- const QUrl &iconUrl = candidateIconUrl(touchIconsEnabled);
- propagateIcon(iconUrl);
- }
-}
-
-void FaviconManager::propagateIcon(const QUrl &iconUrl) const
-{
- content::NavigationEntry *entry = m_webContents->GetController().GetVisibleEntry();
- if (entry) {
- content::FaviconStatus &favicon = entry->GetFavicon();
- favicon.url = toGurl(iconUrl);
- favicon.valid = true;
- }
-
- m_viewClient->iconChanged(iconUrl);
-}
-
-QIcon FaviconManager::getIcon(const QUrl &url) const
-{
- if (url.isEmpty())
- return m_candidateIcon;
-
- if (!m_icons.contains(url))
- return QIcon();
-
- return m_icons[url];
-}
-
-FaviconInfo FaviconManager::getFaviconInfo(const QUrl &url) const
-{
- Q_ASSERT(m_faviconInfoMap.contains(url));
- return m_faviconInfoMap[url];
-}
-
-QList<FaviconInfo> FaviconManager::getFaviconInfoList(bool candidatesOnly) const
-{
- QList<FaviconInfo> faviconInfoList = m_faviconInfoMap.values();
-
- if (candidatesOnly) {
- const auto hasNoCandidate = [](const FaviconInfo &info) { return !info.candidate; };
- faviconInfoList.erase(std::remove_if(faviconInfoList.begin(), faviconInfoList.end(),
- hasNoCandidate),
- faviconInfoList.end());
- }
-
- return faviconInfoList;
-}
-
-void FaviconManager::update(const QList<FaviconInfo> &candidates)
-{
- updateCandidates(candidates);
-
- WebEngineSettings *settings = m_viewClient->webEngineSettings();
- if (!settings->testAttribute(WebEngineSettings::AutoLoadIconsForPage)) {
- m_viewClient->iconChanged(QUrl());
- return;
- }
-
- bool touchIconsEnabled = settings->testAttribute(WebEngineSettings::TouchIconsEnabled);
-
- const QList<FaviconInfo> &faviconInfoList = getFaviconInfoList(true /* candidates only */);
- for (auto it = faviconInfoList.cbegin(), end = faviconInfoList.cend(); it != end; ++it) {
- if (!touchIconsEnabled && !(it->type & FaviconInfo::Favicon))
- continue;
-
- if (it->isValid())
- downloadIcon(it->url);
- }
-
- downloadPendingRequests();
-
- // Reset icon if nothing was downloaded
- if (m_inProgressRequests.isEmpty()) {
- content::NavigationEntry *entry = m_webContents->GetController().GetVisibleEntry();
- if (entry && !entry->GetFavicon().valid)
- m_viewClient->iconChanged(QUrl());
- }
-}
-
-void FaviconManager::updateCandidates(const QList<FaviconInfo> &candidates)
-{
- // Invalidate types of the already stored candidate icons because it might differ
- // among pages.
- for (FaviconInfo candidateFaviconInfo : candidates) {
- const QUrl &candidateUrl = candidateFaviconInfo.url;
- if (m_faviconInfoMap.contains(candidateUrl))
- m_faviconInfoMap[candidateUrl].type = FaviconInfo::InvalidIcon;
- }
-
- m_candidateCount = candidates.count();
- for (FaviconInfo candidateFaviconInfo : candidates) {
- const QUrl &candidateUrl = candidateFaviconInfo.url;
-
- if (!m_faviconInfoMap.contains(candidateUrl))
- m_faviconInfoMap.insert(candidateUrl, candidateFaviconInfo);
- else {
- // The same icon URL can be used for different types.
- m_faviconInfoMap[candidateUrl].type |= candidateFaviconInfo.type;
- }
-
- m_faviconInfoMap[candidateUrl].candidate = true;
- }
-}
-
-void FaviconManager::resetCandidates()
-{
- // Interrupt in progress icon downloads
- m_pendingRequests.clear();
- m_inProgressRequests.clear();
-
- m_candidateCount = 0;
- m_candidateIcon = QIcon();
- for (auto it = m_faviconInfoMap.begin(), end = m_faviconInfoMap.end(); it != end; ++it)
- it->candidate = false;
-}
-
-bool FaviconManager::hasCandidate() const
-{
- return (m_candidateCount > 0);
-}
-
-QUrl FaviconManager::candidateIconUrl(bool touchIconsEnabled) const
-{
- QUrl iconUrl;
- const QList<FaviconInfo> &faviconInfoList = getFaviconInfoList(true /* candidates only */);
-
- unsigned bestArea = 0;
- for (auto it = faviconInfoList.cbegin(), end = faviconInfoList.cend(); it != end; ++it) {
- if (!touchIconsEnabled && !(it->type & FaviconInfo::Favicon))
- continue;
-
- if (it->isValid() && bestArea < area(it->size)) {
- iconUrl = it->url;
- bestArea = area(it->size);
- }
- }
-
- return iconUrl;
-}
-
-void FaviconManager::generateCandidateIcon(bool touchIconsEnabled)
-{
- Q_ASSERT(m_candidateCount);
-
- m_candidateIcon = QIcon();
- const QList<FaviconInfo> &faviconInfoList = getFaviconInfoList(true /* candidates only */);
-
- for (auto it = faviconInfoList.cbegin(), end = faviconInfoList.cend(); it != end; ++it) {
- if (!touchIconsEnabled && !(it->type & FaviconInfo::Favicon))
- continue;
-
- if (!it->isValid() || !it->isDownloaded())
- continue;
-
- const QIcon &icon = getIcon(it->url);
-
- if (!it->multiSize) {
- if (!m_candidateIcon.availableSizes().contains(it->size))
- m_candidateIcon.addPixmap(icon.pixmap(it->size));
-
- continue;
- }
-
- const auto sizes = icon.availableSizes();
- for (const QSize &size : sizes) {
- if (!m_candidateIcon.availableSizes().contains(size))
- m_candidateIcon.addPixmap(icon.pixmap(size));
- }
- }
-}
-
-void FaviconManager::copyStateFrom(FaviconManager *source)
-{
- m_faviconInfoMap = source->m_faviconInfoMap;
- m_icons = source->m_icons;
-}
-
-FaviconInfo::FaviconInfo()
- : url(QUrl())
- , type(FaviconInfo::InvalidIcon)
- , size(QSize(0, 0))
- , candidate(false)
- , multiSize(false)
-{
-}
-
-FaviconInfo::FaviconInfo(const FaviconInfo &other)
- : url(other.url)
- , type(other.type)
- , size(other.size)
- , candidate(other.candidate)
- , multiSize(other.multiSize)
-{
-}
-
-FaviconInfo::FaviconInfo(const QUrl &url, FaviconInfo::FaviconTypeFlags type)
- : url(url)
- , type(type)
- , size(QSize(0, 0))
- , candidate(false)
- , multiSize(false)
-{
-}
-
-FaviconInfo::~FaviconInfo()
-{
-}
-
-bool FaviconInfo::isValid() const
-{
- if (type == FaviconInfo::InvalidIcon)
- return false;
-
- if (url.isEmpty() || !url.isValid())
- return false;
-
- return true;
-}
-
-bool FaviconInfo::isDownloaded() const
-{
- return area(size) > 0;
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/favicon_manager.h b/src/core/favicon_manager.h
deleted file mode 100644
index a8247d15f..000000000
--- a/src/core/favicon_manager.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef FAVICON_MANAGER_H
-#define FAVICON_MANAGER_H
-
-#include "qtwebenginecoreglobal_p.h"
-#include <memory>
-#include <QtCore/QMap>
-#include <QtCore/QObject>
-#include <QtCore/QSize>
-#include <QtCore/QUrl>
-#include <QtGui/QIcon>
-
-#include "web_engine_settings.h"
-
-class GURL;
-class SkBitmap;
-
-namespace gfx {
-class Size;
-}
-
-namespace content {
-class WebContents;
-}
-
-namespace base {
-template<class T>
-class WeakPtrFactory;
-}
-
-namespace QtWebEngineCore {
-
-class WebContentsAdapterClient;
-
-// Based on src/3rdparty/chromium/content/public/common/favicon_url.h
-class Q_WEBENGINECORE_PRIVATE_EXPORT FaviconInfo {
-public:
- enum FaviconTypeFlag {
- InvalidIcon = 0,
- Favicon = 1 << 0,
- TouchIcon = 1 << 1,
- TouchPrecomposedIcon = 1 << 2
- };
- Q_DECLARE_FLAGS(FaviconTypeFlags, FaviconTypeFlag)
-
- FaviconInfo();
- FaviconInfo(const FaviconInfo &);
- FaviconInfo(const QUrl &, FaviconInfo::FaviconTypeFlags);
- ~FaviconInfo();
-
- bool isValid() const;
- bool isDownloaded() const;
-
- QUrl url;
- FaviconTypeFlags type;
- // Stores the largest size in case of multi-size icon
- QSize size;
- bool candidate;
- bool multiSize;
-};
-
-
-class Q_WEBENGINECORE_PRIVATE_EXPORT FaviconManager {
-
-public:
- FaviconManager(content::WebContents *, WebContentsAdapterClient *);
- ~FaviconManager();
-
- QIcon getIcon(const QUrl &url = QUrl()) const;
- FaviconInfo getFaviconInfo(const QUrl &) const;
- QList<FaviconInfo> getFaviconInfoList(bool) const;
- void copyStateFrom(FaviconManager *source);
-
-private:
- void update(const QList<FaviconInfo> &);
- void updateCandidates(const QList<FaviconInfo> &);
- void resetCandidates();
- bool hasCandidate() const;
- QUrl candidateIconUrl(bool touchIconsEnabled) const;
- void generateCandidateIcon(bool touchIconsEnabled);
- int downloadIcon(const QUrl &);
- void iconDownloadFinished(int, int, const GURL &, const std::vector<SkBitmap> &, const std::vector<gfx::Size> &);
- void storeIcon(int, const QIcon &);
- void downloadPendingRequests();
- void propagateIcon(const QUrl &) const;
-
-private:
- content::WebContents *m_webContents;
- WebContentsAdapterClient *m_viewClient;
- QMap<QUrl, FaviconInfo> m_faviconInfoMap;
- int m_candidateCount;
- QIcon m_candidateIcon;
- QMap<QUrl, QIcon> m_icons;
- QMap<int, QUrl> m_inProgressRequests;
- QMap<int, QUrl> m_pendingRequests;
- std::unique_ptr<base::WeakPtrFactory<FaviconManager>> m_weakFactory;
- friend class WebContentsDelegateQt;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // FAVICON_MANAGER_H
diff --git a/src/core/favicon_service_factory_qt.cpp b/src/core/favicon_service_factory_qt.cpp
new file mode 100644
index 000000000..dd2a1979a
--- /dev/null
+++ b/src/core/favicon_service_factory_qt.cpp
@@ -0,0 +1,163 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "favicon_service_factory_qt.h"
+
+#include "base/files/file_util.h"
+#include "components/favicon/core/favicon_service_impl.h"
+#include "components/history/content/browser/content_visit_delegate.h"
+#include "components/history/content/browser/history_database_helper.h"
+#include "components/history/core/browser/history_backend_client.h"
+#include "components/history/core/browser/history_database_params.h"
+#include "components/history/core/browser/history_service.h"
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "content/public/browser/browser_context.h"
+#include "url/gurl.h"
+
+namespace QtWebEngineCore {
+
+void HistoryClientQt::OnHistoryServiceCreated(history::HistoryService *history_service)
+{
+ Q_UNUSED(history_service);
+}
+
+void HistoryClientQt::Shutdown() { }
+
+static bool CanAddURL(const GURL &url)
+{
+ Q_UNUSED(url);
+ return true;
+}
+
+history::CanAddURLCallback HistoryClientQt::GetThreadSafeCanAddURLCallback() const
+{
+ return base::BindRepeating(&CanAddURL);
+}
+
+void HistoryClientQt::NotifyProfileError(sql::InitStatus init_status,
+ const std::string &diagnostics)
+{
+ Q_UNUSED(init_status);
+ Q_UNUSED(diagnostics);
+}
+
+std::unique_ptr<history::HistoryBackendClient> HistoryClientQt::CreateBackendClient()
+{
+ return nullptr;
+}
+
+void HistoryClientQt::UpdateBookmarkLastUsedTime(const base::Uuid &, base::Time /*time*/)
+{
+}
+
+// static
+history::HistoryService *
+HistoryServiceFactoryQt::GetForBrowserContext(content::BrowserContext *context)
+{
+ if (context->IsOffTheRecord())
+ return nullptr;
+
+
+ return static_cast<history::HistoryService *>(
+ GetInstance()->GetServiceForBrowserContext(context, true));
+}
+
+// static
+HistoryServiceFactoryQt *HistoryServiceFactoryQt::GetInstance()
+{
+ return base::Singleton<HistoryServiceFactoryQt>::get();
+}
+
+HistoryServiceFactoryQt::HistoryServiceFactoryQt()
+ : BrowserContextKeyedServiceFactory("HistoryService",
+ BrowserContextDependencyManager::GetInstance())
+{
+}
+
+HistoryServiceFactoryQt::~HistoryServiceFactoryQt() { }
+
+content::BrowserContext *
+HistoryServiceFactoryQt::GetBrowserContextToUse(content::BrowserContext *context) const
+{
+ return context;
+}
+
+KeyedService *
+HistoryServiceFactoryQt::BuildServiceInstanceFor(content::BrowserContext *context) const
+{
+ Q_ASSERT(!context->IsOffTheRecord());
+
+ std::unique_ptr<history::HistoryService> historyService(
+ new history::HistoryService(std::make_unique<HistoryClientQt>(), nullptr));
+ if (!historyService->Init(history::HistoryDatabaseParamsForPath(context->GetPath(), version_info::Channel::DEFAULT))) {
+ return nullptr;
+ }
+ return historyService.release();
+}
+
+bool FaviconClientQt::IsNativeApplicationURL(const GURL &url)
+{
+ Q_UNUSED(url);
+ return false;
+}
+
+bool FaviconClientQt::IsReaderModeURL(const GURL &url)
+{
+ Q_UNUSED(url)
+ return false;
+}
+
+const GURL FaviconClientQt::GetOriginalUrlFromReaderModeUrl(const GURL &url)
+{
+ return url;
+}
+
+base::CancelableTaskTracker::TaskId FaviconClientQt::GetFaviconForNativeApplicationURL(
+ const GURL &url, const std::vector<int> &desired_sizes_in_pixel,
+ favicon_base::FaviconResultsCallback callback, base::CancelableTaskTracker *tracker)
+{
+ Q_UNUSED(url);
+ Q_UNUSED(desired_sizes_in_pixel);
+ Q_UNUSED(callback);
+ Q_UNUSED(tracker);
+
+ return base::CancelableTaskTracker::kBadTaskId;
+}
+
+// static
+favicon::FaviconService *
+FaviconServiceFactoryQt::GetForBrowserContext(content::BrowserContext *context)
+{
+ return static_cast<favicon::FaviconService *>(
+ GetInstance()->GetServiceForBrowserContext(context, true));
+}
+
+// static
+FaviconServiceFactoryQt *FaviconServiceFactoryQt::GetInstance()
+{
+ return base::Singleton<FaviconServiceFactoryQt>::get();
+}
+
+FaviconServiceFactoryQt::FaviconServiceFactoryQt()
+ : BrowserContextKeyedServiceFactory("FaviconService",
+ BrowserContextDependencyManager::GetInstance())
+{
+}
+
+FaviconServiceFactoryQt::~FaviconServiceFactoryQt() { }
+
+content::BrowserContext *
+FaviconServiceFactoryQt::GetBrowserContextToUse(content::BrowserContext *context) const
+{
+ return context;
+}
+
+KeyedService *
+FaviconServiceFactoryQt::BuildServiceInstanceFor(content::BrowserContext *context) const
+{
+ history::HistoryService *historyService = static_cast<history::HistoryService *>(
+ HistoryServiceFactoryQt::GetInstance()->GetForBrowserContext(context));
+ return new favicon::FaviconServiceImpl(std::make_unique<FaviconClientQt>(), historyService);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/favicon_service_factory_qt.h b/src/core/favicon_service_factory_qt.h
new file mode 100644
index 000000000..55d5f3b33
--- /dev/null
+++ b/src/core/favicon_service_factory_qt.h
@@ -0,0 +1,111 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef FAVICON_SERVICE_FACTORY_QT_H
+#define FAVICON_SERVICE_FACTORY_QT_H
+
+#include "qtwebenginecoreglobal_p.h"
+
+#include "base/memory/singleton.h"
+#include "base/task/cancelable_task_tracker.h"
+#include "components/favicon/core/favicon_client.h"
+#include "components/history/core/browser/history_client.h"
+#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
+
+class GURL;
+
+namespace content {
+class BrowserContext;
+}
+
+namespace favicon {
+class FaviconService;
+}
+
+namespace history {
+class HistoryBackendClient;
+class HistoryService;
+}
+
+namespace QtWebEngineCore {
+
+class HistoryClientQt : public history::HistoryClient
+{
+public:
+ HistoryClientQt() { }
+ virtual ~HistoryClientQt() { }
+
+ void OnHistoryServiceCreated(history::HistoryService *history_service) override;
+ void Shutdown() override;
+ history::CanAddURLCallback GetThreadSafeCanAddURLCallback() const override;
+ void NotifyProfileError(sql::InitStatus init_status, const std::string &diagnostics) override;
+ std::unique_ptr<history::HistoryBackendClient> CreateBackendClient() override;
+ void UpdateBookmarkLastUsedTime(const base::Uuid &, base::Time) override;
+};
+
+class HistoryServiceFactoryQt : public BrowserContextKeyedServiceFactory
+{
+public:
+ static history::HistoryService *GetForBrowserContext(content::BrowserContext *context);
+ static HistoryServiceFactoryQt *GetInstance();
+
+private:
+ friend struct base::DefaultSingletonTraits<HistoryServiceFactoryQt>;
+
+ HistoryServiceFactoryQt();
+ ~HistoryServiceFactoryQt() override;
+
+ // BrowserContextKeyedServiceFactory:
+ content::BrowserContext *
+ GetBrowserContextToUse(content::BrowserContext *context) const override;
+ KeyedService *BuildServiceInstanceFor(content::BrowserContext *context) const override;
+};
+
+class FaviconClientQt : public favicon::FaviconClient
+{
+public:
+ FaviconClientQt() { }
+ virtual ~FaviconClientQt() { }
+
+ bool IsNativeApplicationURL(const GURL &url) override;
+ bool IsReaderModeURL(const GURL &url) override;
+ const GURL GetOriginalUrlFromReaderModeUrl(const GURL &url) override;
+ base::CancelableTaskTracker::TaskId
+ GetFaviconForNativeApplicationURL(const GURL &url,
+ const std::vector<int> &desired_sizes_in_pixel,
+ favicon_base::FaviconResultsCallback callback,
+ base::CancelableTaskTracker *tracker) override;
+};
+
+class FaviconServiceFactoryQt : public BrowserContextKeyedServiceFactory
+{
+public:
+ static favicon::FaviconService *GetForBrowserContext(content::BrowserContext *context);
+ static FaviconServiceFactoryQt *GetInstance();
+
+private:
+ friend struct base::DefaultSingletonTraits<FaviconServiceFactoryQt>;
+
+ FaviconServiceFactoryQt();
+ ~FaviconServiceFactoryQt() override;
+
+ // BrowserContextKeyedServiceFactory:
+ content::BrowserContext *
+ GetBrowserContextToUse(content::BrowserContext *context) const override;
+ KeyedService *BuildServiceInstanceFor(content::BrowserContext *context) const override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FAVICON_SERVICE_FACTORY_QT_H
diff --git a/src/core/file_picker_controller.cpp b/src/core/file_picker_controller.cpp
index 65e2c6f00..9b4521358 100644
--- a/src/core/file_picker_controller.cpp
+++ b/src/core/file_picker_controller.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "file_picker_controller.h"
#include "type_conversion.h"
@@ -44,7 +8,9 @@
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/file_select_listener.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
+#include <QtCore/qcoreapplication.h>
#include <QDir>
#include <QFileInfo>
#include <QMimeDatabase>
@@ -53,16 +19,48 @@
namespace QtWebEngineCore {
-FilePickerController::FilePickerController(FileChooserMode mode, std::unique_ptr<content::FileSelectListener> listener, const QString &defaultFileName, const QStringList &acceptedMimeTypes, QObject *parent)
+class FilePickerControllerPrivate {
+public:
+ FilePickerController::FileChooserMode mode;
+ scoped_refptr<content::FileSelectListener> fileDialogListener;
+ ui::SelectFileDialog::Listener *fileSystemAccessDialogListener;
+ QString defaultFileName;
+ QStringList acceptedMimeTypes;
+};
+
+FilePickerController *createFilePickerController(
+ FilePickerController::FileChooserMode mode, scoped_refptr<content::FileSelectListener> listener,
+ const QString &defaultFileName, const QStringList &acceptedMimeTypes, QObject *parent = nullptr)
+{
+ auto priv = new FilePickerControllerPrivate { mode, listener, nullptr, defaultFileName,
+ acceptedMimeTypes };
+ return new FilePickerController(priv, parent);
+}
+
+FilePickerController *createFilePickerController(FilePickerController::FileChooserMode mode,
+ ui::SelectFileDialog::Listener *listener,
+ const QString &defaultFileName,
+ const QStringList &acceptedMimeTypes,
+ QObject *parent = nullptr)
+{
+ auto priv = new FilePickerControllerPrivate { mode, nullptr, listener, defaultFileName,
+ acceptedMimeTypes };
+ return new FilePickerController(priv, parent);
+}
+
+FilePickerController::FilePickerController(FilePickerControllerPrivate *priv, QObject *parent)
: QObject(parent)
- , m_defaultFileName(defaultFileName)
- , m_acceptedMimeTypes(acceptedMimeTypes)
- , m_listener(std::move(listener))
- , m_mode(mode)
+ , d_ptr(priv)
{
}
-FilePickerController::~FilePickerController() = default;
+FilePickerController::~FilePickerController()
+{
+ if (!m_isHandled) {
+ rejected();
+ }
+ delete d_ptr;
+}
void FilePickerController::accepted(const QStringList &files)
{
@@ -79,25 +77,25 @@ void FilePickerController::accepted(const QStringList &files)
if (urlString.startsWith("file:")) {
base::FilePath filePath = toFilePath(urlString).NormalizePathSeparators();
std::vector<base::FilePath::StringType> pathComponents;
- // Splits the file URL into host name, path and file name.
- filePath.GetComponents(&pathComponents);
+ // Splits the file URL into scheme, host name, path and file name.
+ pathComponents = filePath.GetComponents();
QString absolutePath;
-#if !defined(OS_WIN)
+#if !defined(Q_OS_WIN)
absolutePath = "/";
#endif
QString scheme = toQt(pathComponents[0]);
if (scheme.size() > 5) {
-#if defined(OS_WIN)
+#if defined(Q_OS_WIN)
// There is no slash at the end of the file scheme and it is valid on Windows: file:C:/
- if (scheme.at(5).isLetter() && scheme.at(6) != ':') {
+ if (scheme.size() == 7 && scheme.at(5).isLetter() && scheme.at(6) == ':') {
absolutePath += scheme.at(5) + ":/";
} else {
#endif
qWarning("Ignoring invalid item in FilePickerController::accepted(QStringList): %s", qPrintable(urlString));
continue;
-#if defined(OS_WIN)
+#if defined(Q_OS_WIN)
}
#endif
}
@@ -106,7 +104,7 @@ void FilePickerController::accepted(const QStringList &files)
if (base::FilePath::IsSeparator(urlString.at(5).toLatin1())
&& base::FilePath::IsSeparator(urlString.at(6).toLatin1())
&& !base::FilePath::IsSeparator(urlString.at(7).toLatin1())) {
-#if defined(OS_WIN)
+#if defined(Q_OS_WIN)
if (urlString.at(8) != ':' && pathComponents.size() > 2) {
absolutePath += "//";
#else
@@ -138,7 +136,7 @@ void FilePickerController::accepted(const QVariant &files)
{
QStringList stringList;
- if (files.canConvert(QVariant::StringList)) {
+ if (files.canConvert(QMetaType{QMetaType::QStringList})) {
stringList = files.toStringList();
} else if (files.canConvert<QList<QUrl> >()) {
const QList<QUrl> urls = files.value<QList<QUrl>>();
@@ -177,38 +175,62 @@ ASSERT_ENUMS_MATCH(FilePickerController::Save, blink::mojom::FileChooserParams_M
void FilePickerController::filesSelectedInChooser(const QStringList &filesList)
{
- QStringList files(filesList);
- if (this->m_mode == UploadFolder && !filesList.isEmpty()
- && QFileInfo(filesList.first()).isDir()) // Enumerate the directory
- files = listRecursively(QDir(filesList.first()));
-
- std::vector<blink::mojom::FileChooserFileInfoPtr> chooser_files;
- for (const auto &file : qAsConst(files)) {
- chooser_files.push_back(blink::mojom::FileChooserFileInfo::NewNativeFile(
- blink::mojom::NativeFileInfo::New(toFilePath(file), base::string16())));
- }
+ m_isHandled = true;
+ if (d_ptr->fileDialogListener) {
+ QStringList files(filesList);
+ base::FilePath baseDir;
+ if (d_ptr->mode == UploadFolder && !filesList.isEmpty()) {
+ if (QFileInfo(filesList.first()).isDir()) {
+ // Enumerate the directory
+ files = listRecursively(QDir(filesList.first()));
+ baseDir = toFilePath(filesList.first());
+ } else {
+ baseDir = toFilePath(filesList.first()).DirName();
+ }
+ }
+
+ std::vector<blink::mojom::FileChooserFileInfoPtr> chooser_files;
+ for (const auto &file : std::as_const(files)) {
+ chooser_files.push_back(blink::mojom::FileChooserFileInfo::NewNativeFile(
+ blink::mojom::NativeFileInfo::New(toFilePath(file), std::u16string())));
+ }
+
+ if (files.isEmpty())
+ d_ptr->fileDialogListener->FileSelectionCanceled();
+ else
+ d_ptr->fileDialogListener->FileSelected(
+ std::move(chooser_files), baseDir,
+ static_cast<blink::mojom::FileChooserParams::Mode>(d_ptr->mode));
+
+ // release the fileSelectListener manually because it blocks fullscreen requests in chromium
+ // see QTBUG-106975
+ d_ptr->fileDialogListener.reset();
+ } else if (d_ptr->fileSystemAccessDialogListener) {
+ std::vector<base::FilePath> files;
+ for (const auto &file : std::as_const(filesList)) {
+ files.push_back(toFilePath(file));
+ }
- if (files.isEmpty())
- m_listener->FileSelectionCanceled();
- else
- m_listener->FileSelected(std::move(chooser_files),
- /* FIXME? */ base::FilePath(),
- static_cast<blink::mojom::FileChooserParams::Mode>(this->m_mode));
+ if (files.empty())
+ d_ptr->fileSystemAccessDialogListener->FileSelectionCanceled(nullptr);
+ else
+ d_ptr->fileSystemAccessDialogListener->MultiFilesSelected(files, nullptr);
+ }
}
QStringList FilePickerController::acceptedMimeTypes() const
{
- return m_acceptedMimeTypes;
+ return d_ptr->acceptedMimeTypes;
}
FilePickerController::FileChooserMode FilePickerController::mode() const
{
- return m_mode;
+ return d_ptr->mode;
}
QString FilePickerController::defaultFileName() const
{
- return m_defaultFileName;
+ return d_ptr->defaultFileName;
}
QStringList FilePickerController::nameFilters(const QStringList &acceptedMimeTypes)
@@ -236,7 +258,7 @@ QStringList FilePickerController::nameFilters(const QStringList &acceptedMimeTyp
const QMimeType &mimeType = mimeDatabase.mimeTypeForName(type);
if (mimeType.isValid() && !mimeType.globPatterns().isEmpty()) {
QString globs = mimeType.globPatterns().join(" ");
- acceptedGlobs.append(globs);
+ acceptedGlobs.append(mimeType.globPatterns());
nameFilters.append(mimeType.comment() + " (" + globs + ")");
}
} else if (type.endsWith("/*")) {
@@ -247,7 +269,7 @@ QStringList FilePickerController::nameFilters(const QStringList &acceptedMimeTyp
for (const QMimeType &m : allMimeTypes) {
if (m.name().startsWith(type) && !m.globPatterns().isEmpty()) {
QString globs = m.globPatterns().join(" ");
- acceptedGlobs.append(globs);
+ acceptedGlobs.append(m.globPatterns());
nameFilters.append(m.comment() + " (" + globs + ")");
}
}
@@ -256,7 +278,10 @@ QStringList FilePickerController::nameFilters(const QStringList &acceptedMimeTyp
}
}
- nameFilters.prepend(QObject::tr("Accepted types") + " (" + acceptedGlobs.join(" ") + ")");
+ const QString filter =
+ QCoreApplication::translate("FilePickerController",
+ "Accepted types (%1)").arg(acceptedGlobs.join(' '));
+ nameFilters.prepend(filter);
return nameFilters;
}
diff --git a/src/core/file_picker_controller.h b/src/core/file_picker_controller.h
index 0b680161a..42ffd6a2d 100644
--- a/src/core/file_picker_controller.h
+++ b/src/core/file_picker_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,20 +15,14 @@
#ifndef FILE_PICKER_CONTROLLER_H
#define FILE_PICKER_CONTROLLER_H
-#include "qtwebenginecoreglobal_p.h"
-
-#include <memory>
-
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QObject>
#include <QStringList>
-namespace content {
- class FileSelectListener;
-}
-
namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT FilePickerController : public QObject {
+class FilePickerControllerPrivate;
+class Q_WEBENGINECORE_EXPORT FilePickerController : public QObject {
Q_OBJECT
public:
enum FileChooserMode {
@@ -74,8 +32,9 @@ public:
Save
};
- FilePickerController(FileChooserMode mode, std::unique_ptr<content::FileSelectListener> listener, const QString &defaultFileName, const QStringList &acceptedMimeTypes, QObject * = 0);
+ FilePickerController(FilePickerControllerPrivate *priv, QObject *parent = nullptr);
~FilePickerController() override;
+
QStringList acceptedMimeTypes() const;
QString defaultFileName() const;
FileChooserMode mode() const;
@@ -89,13 +48,12 @@ public Q_SLOTS:
private:
void filesSelectedInChooser(const QStringList &filesList);
- QString m_defaultFileName;
- QStringList m_acceptedMimeTypes;
- std::unique_ptr<content::FileSelectListener> m_listener;
- FileChooserMode m_mode;
-
+ FilePickerControllerPrivate *d_ptr;
+ // Using Quick, the FileSelectListenerImpl destructor may crash in debug mode
+ // if the browser window is closed and the FilePicker is still open
+ bool m_isHandled = false;
};
-} // namespace
+} // namespace QtWebEngineCore
#endif // FILE_PICKER_CONTROLLER_H
diff --git a/src/core/file_system_access/file_system_access_permission_context_factory_qt.cpp b/src/core/file_system_access/file_system_access_permission_context_factory_qt.cpp
new file mode 100644
index 000000000..51c8a8991
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_context_factory_qt.cpp
@@ -0,0 +1,61 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "file_system_access_permission_context_factory_qt.h"
+
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+
+#include <QtGlobal>
+
+namespace QtWebEngineCore {
+
+// static
+FileSystemAccessPermissionContextQt *
+FileSystemAccessPermissionContextFactoryQt::GetForProfile(content::BrowserContext *profile)
+{
+ return static_cast<FileSystemAccessPermissionContextQt *>(
+ GetInstance()->GetServiceForBrowserContext(profile, true));
+}
+
+// static
+FileSystemAccessPermissionContextQt *
+FileSystemAccessPermissionContextFactoryQt::GetForProfileIfExists(content::BrowserContext *profile)
+{
+ return static_cast<FileSystemAccessPermissionContextQt *>(
+ GetInstance()->GetServiceForBrowserContext(profile, true));
+}
+
+// static
+FileSystemAccessPermissionContextFactoryQt *
+FileSystemAccessPermissionContextFactoryQt::GetInstance()
+{
+ return base::Singleton<FileSystemAccessPermissionContextFactoryQt>::get();
+}
+
+FileSystemAccessPermissionContextFactoryQt::FileSystemAccessPermissionContextFactoryQt()
+ : BrowserContextKeyedServiceFactory("FileSystemAccessPermissionContext",
+ BrowserContextDependencyManager::GetInstance())
+{
+}
+
+FileSystemAccessPermissionContextFactoryQt::~FileSystemAccessPermissionContextFactoryQt() = default;
+
+content::BrowserContext *FileSystemAccessPermissionContextFactoryQt::GetBrowserContextToUse(
+ content::BrowserContext *context) const
+{
+ return context;
+}
+
+KeyedService *FileSystemAccessPermissionContextFactoryQt::BuildServiceInstanceFor(
+ content::BrowserContext *context) const
+{
+ return new FileSystemAccessPermissionContextQt(context);
+}
+
+void FileSystemAccessPermissionContextFactoryQt::BrowserContextShutdown(
+ content::BrowserContext *context)
+{
+ Q_UNUSED(context);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/file_system_access/file_system_access_permission_context_factory_qt.h b/src/core/file_system_access/file_system_access_permission_context_factory_qt.h
new file mode 100644
index 000000000..1d98243d6
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_context_factory_qt.h
@@ -0,0 +1,37 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_FACTORY_QT_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_FACTORY_QT_H
+
+#include "base/memory/singleton.h"
+#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
+
+#include "file_system_access_permission_context_qt.h"
+
+namespace QtWebEngineCore {
+
+class FileSystemAccessPermissionContextFactoryQt : public BrowserContextKeyedServiceFactory
+{
+public:
+ static FileSystemAccessPermissionContextQt *GetForProfile(content::BrowserContext *profile);
+ static FileSystemAccessPermissionContextQt *
+ GetForProfileIfExists(content::BrowserContext *profile);
+ static FileSystemAccessPermissionContextFactoryQt *GetInstance();
+
+private:
+ friend struct base::DefaultSingletonTraits<FileSystemAccessPermissionContextFactoryQt>;
+
+ FileSystemAccessPermissionContextFactoryQt();
+ ~FileSystemAccessPermissionContextFactoryQt() override;
+
+ // BrowserContextKeyedServiceFactory
+ content::BrowserContext *
+ GetBrowserContextToUse(content::BrowserContext *context) const override;
+ KeyedService *BuildServiceInstanceFor(content::BrowserContext *profile) const override;
+ void BrowserContextShutdown(content::BrowserContext *context) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_FACTORY_QT_H
diff --git a/src/core/file_system_access/file_system_access_permission_context_qt.cpp b/src/core/file_system_access/file_system_access_permission_context_qt.cpp
new file mode 100644
index 000000000..c290aab82
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_context_qt.cpp
@@ -0,0 +1,479 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// This file is based on chrome/browser/file_system_access/chrome_file_system_access_permission_context.cc:
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "file_system_access_permission_context_qt.h"
+
+#include "base/base_paths.h"
+#include "base/path_service.h"
+#include "base/task/task_traits.h"
+#include "base/task/thread_pool.h"
+#include "chrome/common/chrome_paths.h"
+#include "components/content_settings/core/common/content_settings_types.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+
+#include "file_system_access_permission_grant_qt.h"
+#include "type_conversion.h"
+
+#include <QCoreApplication>
+#include <QStandardPaths>
+
+namespace QtWebEngineCore {
+
+// Sentinel used to indicate that no PathService key is specified for a path in
+// the struct below.
+constexpr const int kNoBasePathKey = -1;
+
+enum BlockType { kBlockAllChildren, kBlockNestedDirectories, kDontBlockChildren, kDontBlockAppFolder };
+
+const struct
+{
+ // base::BasePathKey value (or one of the platform specific extensions to it)
+ // for a path that should be blocked. Specify kNoBasePathKey if |path| should
+ // be used instead.
+ int base_path_key;
+
+ // Explicit path to block instead of using |base_path_key|. Set to nullptr to
+ // use |base_path_key| on its own. If both |base_path_key| and |path| are set,
+ // |path| is treated relative to the path |base_path_key| resolves to.
+ const base::FilePath::CharType *path;
+
+ // If this is set to kDontBlockChildren, only the given path and its parents
+ // are blocked. If this is set to kBlockAllChildren, all children of the given
+ // path are blocked as well. Finally if this is set to kBlockNestedDirectories
+ // access is allowed to individual files in the directory, but nested
+ // directories are still blocked.
+ // The BlockType of the nearest ancestor of a path to check is what ultimately
+ // determines if a path is blocked or not. If a blocked path is a descendent
+ // of another blocked path, then it may override the child-blocking policy of
+ // its ancestor. For example, if /home blocks all children, but
+ // /home/downloads does not, then /home/downloads/file.ext will *not* be
+ // blocked.
+ BlockType type;
+} kBlockedPaths[] = {
+ // Don't allow users to share their entire home directory, entire desktop or
+ // entire documents folder, but do allow sharing anything inside those
+ // directories not otherwise blocked.
+ { base::DIR_HOME, nullptr, kDontBlockChildren },
+ { base::DIR_USER_DESKTOP, nullptr, kDontBlockChildren },
+ { chrome::DIR_USER_DOCUMENTS, nullptr, kDontBlockChildren },
+ // Similar restrictions for the downloads directory.
+ { chrome::DIR_DEFAULT_DOWNLOADS, nullptr, kDontBlockChildren },
+ { chrome::DIR_DEFAULT_DOWNLOADS_SAFE, nullptr, kDontBlockChildren },
+ // The Chrome installation itself should not be modified by the web.
+ { base::DIR_EXE, nullptr, kBlockAllChildren },
+ { base::DIR_MODULE, nullptr, kBlockAllChildren },
+ { base::DIR_ASSETS, nullptr, kBlockAllChildren },
+ // And neither should the configuration of at least the currently running
+ // Chrome instance (note that this does not take --user-data-dir command
+ // line overrides into account).
+ { chrome::DIR_USER_DATA, nullptr, kBlockAllChildren },
+ // ~/.ssh is pretty sensitive on all platforms, so block access to that.
+ { base::DIR_HOME, FILE_PATH_LITERAL(".ssh"), kBlockAllChildren },
+ // And limit access to ~/.gnupg as well.
+ { base::DIR_HOME, FILE_PATH_LITERAL(".gnupg"), kBlockAllChildren },
+#if defined(OS_WIN)
+ // Some Windows specific directories to block, basically all apps, the
+ // operating system itself, as well as configuration data for apps.
+ { base::DIR_PROGRAM_FILES, nullptr, kBlockAllChildren },
+ { base::DIR_PROGRAM_FILESX86, nullptr, kBlockAllChildren },
+ { base::DIR_PROGRAM_FILES6432, nullptr, kBlockAllChildren },
+ { base::DIR_WINDOWS, nullptr, kBlockAllChildren },
+ { base::DIR_ROAMING_APP_DATA, nullptr, kBlockAllChildren },
+ { base::DIR_LOCAL_APP_DATA, nullptr, kBlockAllChildren },
+ // Whitelist AppData\Local\Temp to make the default location of QDir::tempPath(),
+ // QTemporaryFile and QTemporaryDir working on Windows.
+ { base::DIR_LOCAL_APP_DATA, FILE_PATH_LITERAL("Temp"), kDontBlockAppFolder },
+ { base::DIR_COMMON_APP_DATA, nullptr, kBlockAllChildren },
+ // Opening a file from an MTP device, such as a smartphone or a camera, is
+ // implemented by Windows as opening a file in the temporary internet files
+ // directory. To support that, allow opening files in that directory, but
+ // not whole directories.
+ { base::DIR_IE_INTERNET_CACHE, nullptr, kBlockNestedDirectories },
+#endif
+#if defined(OS_MAC)
+ // Similar Mac specific blocks.
+ { base::DIR_APP_DATA, nullptr, kBlockAllChildren },
+ { base::DIR_HOME, FILE_PATH_LITERAL("Library"), kBlockAllChildren },
+ // Allow access to iCloud files.
+ { base::DIR_HOME, FILE_PATH_LITERAL("Library/Mobile Documents"), kDontBlockChildren },
+#endif
+#if defined(OS_LINUX) || defined(OS_CHROMEOS)
+ // On Linux also block access to devices via /dev, as well as security
+ // sensitive data in /sys and /proc.
+ { kNoBasePathKey, FILE_PATH_LITERAL("/dev"), kBlockAllChildren },
+ { kNoBasePathKey, FILE_PATH_LITERAL("/sys"), kBlockAllChildren },
+ { kNoBasePathKey, FILE_PATH_LITERAL("/proc"), kBlockAllChildren },
+ // And block all of ~/.config, matching the similar restrictions on mac
+ // and windows.
+ { base::DIR_HOME, FILE_PATH_LITERAL(".config"), kBlockAllChildren },
+ // Block ~/.dbus as well, just in case, although there probably isn't much a
+ // website can do with access to that directory and its contents.
+ { base::DIR_HOME, FILE_PATH_LITERAL(".dbus"), kBlockAllChildren },
+#endif
+ // TODO(https://crbug.com/984641): Refine this list, for example add
+ // XDG_CONFIG_HOME when it is not set ~/.config?
+};
+
+bool ShouldBlockAccessToPath(const base::FilePath &check_path, HandleType handle_type)
+{
+ DCHECK(!check_path.empty());
+ DCHECK(check_path.IsAbsolute());
+
+ base::FilePath nearest_ancestor;
+ int nearest_ancestor_path_key = kNoBasePathKey;
+ BlockType nearest_ancestor_block_type = kDontBlockChildren;
+ for (const auto &block : kBlockedPaths) {
+ base::FilePath blocked_path;
+ if (block.base_path_key != kNoBasePathKey) {
+ if (!base::PathService::Get(block.base_path_key, &blocked_path))
+ continue;
+ if (block.path)
+ blocked_path = blocked_path.Append(block.path);
+ } else {
+ DCHECK(block.path);
+ blocked_path = base::FilePath(block.path);
+ }
+
+ if (check_path == blocked_path || check_path.IsParent(blocked_path)) {
+ VLOG(1) << "Blocking access to " << check_path << " because it is a parent of "
+ << blocked_path << " (" << block.base_path_key << ")";
+ return true;
+ }
+
+ if (blocked_path.IsParent(check_path)
+ && (nearest_ancestor.empty() || nearest_ancestor.IsParent(blocked_path))) {
+ nearest_ancestor = blocked_path;
+ nearest_ancestor_path_key = block.base_path_key;
+ nearest_ancestor_block_type = block.type;
+ }
+ }
+
+ // The path we're checking is not in a potentially blocked directory, or the
+ // nearest ancestor does not block access to its children. Grant access.
+ if (nearest_ancestor.empty() || nearest_ancestor_block_type == kDontBlockChildren)
+ return false;
+
+ // The path we're checking is a file, and the nearest ancestor only blocks
+ // access to directories. Grant access.
+ if (handle_type == HandleType::kFile && nearest_ancestor_block_type == kBlockNestedDirectories)
+ return false;
+
+ if (nearest_ancestor_block_type == kDontBlockAppFolder) {
+ // Relative path from the nearest blocklisted ancestor
+ base::FilePath diff;
+ nearest_ancestor.AppendRelativePath(check_path, &diff);
+
+ auto diff_components = diff.GetComponents();
+ if (diff_components.size() > 0 && toQt(diff_components[0]).contains(QCoreApplication::applicationName())) {
+ // The relative path contains the application name. Grant access.
+ return false;
+ }
+ }
+
+ // The nearest ancestor blocks access to its children, so block access.
+ VLOG(1) << "Blocking access to " << check_path << " because it is inside " << nearest_ancestor
+ << " (" << nearest_ancestor_path_key << ")";
+ return true;
+}
+
+struct FileSystemAccessPermissionContextQt::OriginState
+{
+ // Raw pointers, owned collectively by all the handles that reference this
+ // grant. When last reference goes away this state is cleared as well by
+ // PermissionGrantDestroyed().
+ std::map<base::FilePath, FileSystemAccessPermissionGrantQt *> read_grants;
+ std::map<base::FilePath, FileSystemAccessPermissionGrantQt *> write_grants;
+};
+
+FileSystemAccessPermissionContextQt::FileSystemAccessPermissionContextQt(
+ content::BrowserContext *context)
+ : m_profile(context)
+{
+}
+
+FileSystemAccessPermissionContextQt::~FileSystemAccessPermissionContextQt() = default;
+
+scoped_refptr<content::FileSystemAccessPermissionGrant>
+FileSystemAccessPermissionContextQt::GetReadPermissionGrant(const url::Origin &origin,
+ const base::FilePath &path,
+ HandleType handle_type,
+ UserAction user_action)
+{
+ auto &origin_state = m_origins[origin];
+ auto *&existing_grant = origin_state.read_grants[path];
+ scoped_refptr<FileSystemAccessPermissionGrantQt> new_grant;
+
+ if (existing_grant && existing_grant->handleType() != handle_type) {
+ // |path| changed from being a directory to being a file or vice versa,
+ // don't just re-use the existing grant but revoke the old grant before
+ // creating a new grant.
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::DENIED);
+ existing_grant = nullptr;
+ }
+
+ if (!existing_grant) {
+ new_grant = base::MakeRefCounted<FileSystemAccessPermissionGrantQt>(
+ m_weakFactory.GetWeakPtr(), origin, path, handle_type, GrantType::kRead);
+ existing_grant = new_grant.get();
+ }
+
+ // If a parent directory is already readable this new grant should also be readable.
+ if (new_grant && AncestorHasActivePermission(origin, path, GrantType::kRead)) {
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ return existing_grant;
+ }
+
+ switch (user_action) {
+ case UserAction::kOpen:
+ case UserAction::kSave:
+ // Open and Save dialog only grant read access for individual files.
+ if (handle_type == HandleType::kDirectory)
+ break;
+ Q_FALLTHROUGH();
+ case UserAction::kDragAndDrop:
+ // Drag&drop grants read access for all handles.
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ break;
+ case UserAction::kLoadFromStorage:
+ break;
+ case UserAction::kNone:
+ Q_UNREACHABLE();
+ }
+
+ return existing_grant;
+}
+
+scoped_refptr<content::FileSystemAccessPermissionGrant>
+FileSystemAccessPermissionContextQt::GetWritePermissionGrant(const url::Origin &origin,
+ const base::FilePath &path,
+ HandleType handle_type,
+ UserAction user_action)
+{
+ auto &origin_state = m_origins[origin];
+ auto *&existing_grant = origin_state.write_grants[path];
+ scoped_refptr<FileSystemAccessPermissionGrantQt> new_grant;
+
+ if (existing_grant && existing_grant->handleType() != handle_type) {
+ // |path| changed from being a directory to being a file or vice versa,
+ // don't just re-use the existing grant but revoke the old grant before
+ // creating a new grant.
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::DENIED);
+ existing_grant = nullptr;
+ }
+
+ if (!existing_grant) {
+ new_grant = base::MakeRefCounted<FileSystemAccessPermissionGrantQt>(
+ m_weakFactory.GetWeakPtr(), origin, path, handle_type, GrantType::kWrite);
+ existing_grant = new_grant.get();
+ }
+
+ // If a parent directory is already writable this new grant should also be writable.
+ if (new_grant && AncestorHasActivePermission(origin, path, GrantType::kWrite)) {
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ return existing_grant;
+ }
+
+ switch (user_action) {
+ case UserAction::kSave:
+ // Only automatically grant write access for save dialogs.
+ existing_grant->SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ break;
+ case UserAction::kOpen:
+ case UserAction::kDragAndDrop:
+ case UserAction::kLoadFromStorage:
+ break;
+ case UserAction::kNone:
+ Q_UNREACHABLE();
+ }
+
+ return existing_grant;
+}
+
+void FileSystemAccessPermissionContextQt::ConfirmSensitiveEntryAccess(
+ const url::Origin &origin, PathType path_type, const base::FilePath &path,
+ HandleType handle_type, UserAction user_action,
+ content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(SensitiveEntryResult)> callback)
+{
+ if (path_type == PathType::kExternal) {
+ std::move(callback).Run(SensitiveEntryResult::kAllowed);
+ return;
+ }
+
+ base::ThreadPool::PostTaskAndReplyWithResult(
+ FROM_HERE, { base::MayBlock(), base::TaskPriority::USER_VISIBLE },
+ base::BindOnce(&ShouldBlockAccessToPath, path, handle_type),
+ base::BindOnce(&FileSystemAccessPermissionContextQt::DidConfirmSensitiveDirectoryAccess,
+ m_weakFactory.GetWeakPtr(), origin, path, handle_type, user_action, frame_id,
+ std::move(callback)));
+}
+
+void FileSystemAccessPermissionContextQt::PerformAfterWriteChecks(
+ std::unique_ptr<content::FileSystemAccessWriteItem> item,
+ content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(AfterWriteCheckResult)> callback)
+{
+ Q_UNUSED(item);
+ Q_UNUSED(frame_id);
+ std::move(callback).Run(AfterWriteCheckResult::kAllow);
+}
+
+bool FileSystemAccessPermissionContextQt::CanObtainReadPermission(const url::Origin &origin)
+{
+ Q_UNUSED(origin);
+ return true;
+}
+
+bool FileSystemAccessPermissionContextQt::CanObtainWritePermission(const url::Origin &origin)
+{
+ Q_UNUSED(origin);
+ return true;
+}
+
+void FileSystemAccessPermissionContextQt::SetLastPickedDirectory(const url::Origin &origin,
+ const std::string &id,
+ const base::FilePath &path,
+ const PathType type)
+{
+ Q_UNUSED(origin);
+
+ FileSystemAccessPermissionContextQt::PathInfo info;
+ info.path = path;
+ info.type = type;
+ m_lastPickedDirectories.insert({ id, info });
+}
+
+FileSystemAccessPermissionContextQt::PathInfo
+FileSystemAccessPermissionContextQt::GetLastPickedDirectory(const url::Origin &origin,
+ const std::string &id)
+{
+ Q_UNUSED(origin);
+
+ return m_lastPickedDirectories.find(id) != m_lastPickedDirectories.end()
+ ? m_lastPickedDirectories[id]
+ : FileSystemAccessPermissionContextQt::PathInfo();
+}
+
+base::FilePath FileSystemAccessPermissionContextQt::GetWellKnownDirectoryPath(
+ blink::mojom::WellKnownDirectory directory, const url::Origin &origin)
+{
+ QStandardPaths::StandardLocation location = QStandardPaths::DocumentsLocation;
+ switch (directory) {
+ case blink::mojom::WellKnownDirectory::kDirDesktop:
+ location = QStandardPaths::DesktopLocation;
+ break;
+ case blink::mojom::WellKnownDirectory::kDirDocuments:
+ location = QStandardPaths::DocumentsLocation;
+ break;
+ case blink::mojom::WellKnownDirectory::kDirDownloads:
+ location = QStandardPaths::DownloadLocation;
+ break;
+ case blink::mojom::WellKnownDirectory::kDirMusic:
+ location = QStandardPaths::MusicLocation;
+ break;
+ case blink::mojom::WellKnownDirectory::kDirPictures:
+ location = QStandardPaths::PicturesLocation;
+ break;
+ case blink::mojom::WellKnownDirectory::kDirVideos:
+ location = QStandardPaths::MoviesLocation;
+ break;
+ }
+
+ return toFilePath(QStandardPaths::writableLocation(location));
+}
+
+void FileSystemAccessPermissionContextQt::NavigatedAwayFromOrigin(const url::Origin &origin)
+{
+ // If the last top-level WebContents for an origin is closed (or is navigated to another
+ // origin), all the permissions for that origin will be revoked.
+
+ auto it = m_origins.find(origin);
+ // If we have no permissions for the origin, there is nothing to do.
+ if (it == m_origins.end())
+ return;
+
+ std::vector<content::WebContentsImpl *> list = content::WebContentsImpl::GetAllWebContents();
+ for (content::WebContentsImpl *web_contents : list) {
+ url::Origin web_contents_origin = url::Origin::Create(web_contents->GetLastCommittedURL());
+ // Found a tab for this origin, so early exit and don't revoke grants.
+ if (web_contents_origin == origin)
+ return;
+ }
+
+ OriginState &origin_state = it->second;
+ for (auto &grant : origin_state.read_grants)
+ grant.second->SetStatus(blink::mojom::PermissionStatus::ASK);
+ for (auto &grant : origin_state.write_grants)
+ grant.second->SetStatus(blink::mojom::PermissionStatus::ASK);
+}
+
+void FileSystemAccessPermissionContextQt::DidConfirmSensitiveDirectoryAccess(
+ const url::Origin &origin, const base::FilePath &path, HandleType handle_type, UserAction user_action,
+ content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(SensitiveEntryResult)> callback, bool should_block)
+{
+ Q_UNUSED(origin);
+ Q_UNUSED(path);
+ Q_UNUSED(handle_type);
+ Q_UNUSED(user_action);
+ Q_UNUSED(frame_id);
+
+ if (should_block)
+ std::move(callback).Run(SensitiveEntryResult::kAbort);
+ else
+ std::move(callback).Run(SensitiveEntryResult::kAllowed);
+}
+
+bool FileSystemAccessPermissionContextQt::AncestorHasActivePermission(
+ const url::Origin &origin, const base::FilePath &path, GrantType grant_type) const
+{
+ auto it = m_origins.find(origin);
+ if (it == m_origins.end())
+ return false;
+
+ const auto &relevant_grants = grant_type == GrantType::kWrite ? it->second.write_grants : it->second.read_grants;
+ if (relevant_grants.empty())
+ return false;
+
+ // Permissions are inherited from the closest ancestor.
+ for (base::FilePath parent = path.DirName(); parent != parent.DirName(); parent = parent.DirName()) {
+ auto i = relevant_grants.find(parent);
+ if (i != relevant_grants.end() && i->second && i->second->GetStatus() == blink::mojom::PermissionStatus::GRANTED)
+ return true;
+ }
+ return false;
+}
+
+std::u16string FileSystemAccessPermissionContextQt::GetPickerTitle(const blink::mojom::FilePickerOptionsPtr &)
+{
+ return {};
+}
+
+void FileSystemAccessPermissionContextQt::PermissionGrantDestroyed(
+ FileSystemAccessPermissionGrantQt *grant)
+{
+ auto it = m_origins.find(grant->origin());
+ if (it == m_origins.end())
+ return;
+
+ auto &grants =
+ grant->type() == GrantType::kRead ? it->second.read_grants : it->second.write_grants;
+ auto grant_it = grants.find(grant->path());
+
+ if (grant_it == grants.end()) {
+ return;
+ }
+ if (grant_it->second == grant)
+ grants.erase(grant_it);
+}
+
+void FileSystemAccessPermissionContextQt::NotifyEntryMoved(const url::Origin &, const base::FilePath &, const base::FilePath &)
+{
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/file_system_access/file_system_access_permission_context_qt.h b/src/core/file_system_access/file_system_access_permission_context_qt.h
new file mode 100644
index 000000000..06fbfae3f
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_context_qt.h
@@ -0,0 +1,86 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// This file is based on chrome/browser/file_system_access/chrome_file_system_access_permission_context.h:
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_QT_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_QT_H
+
+#include "base/files/file_path.h"
+#include "components/keyed_service/core/keyed_service.h"
+#include "content/public/browser/file_system_access_permission_context.h"
+#include "content/public/browser/global_routing_id.h"
+
+namespace content {
+class BrowserContext;
+}
+
+namespace QtWebEngineCore {
+class FileSystemAccessPermissionGrantQt;
+class FileSystemAccessPermissionContextQt : public content::FileSystemAccessPermissionContext,
+ public KeyedService
+{
+public:
+ explicit FileSystemAccessPermissionContextQt(content::BrowserContext *context);
+ ~FileSystemAccessPermissionContextQt() override;
+
+ enum class GrantType { kRead, kWrite };
+
+ // content::FileSystemAccessPermissionContext:
+ scoped_refptr<content::FileSystemAccessPermissionGrant>
+ GetReadPermissionGrant(const url::Origin &origin, const base::FilePath &path,
+ HandleType handle_type, UserAction user_action) override;
+ scoped_refptr<content::FileSystemAccessPermissionGrant>
+ GetWritePermissionGrant(const url::Origin &origin, const base::FilePath &path,
+ HandleType handle_type, UserAction user_action) override;
+ void ConfirmSensitiveEntryAccess(
+ const url::Origin &origin, PathType path_type, const base::FilePath &path,
+ HandleType handle_type, UserAction user_action,
+ content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(SensitiveEntryResult)> callback) override;
+ void PerformAfterWriteChecks(std::unique_ptr<content::FileSystemAccessWriteItem> item,
+ content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(AfterWriteCheckResult)> callback) override;
+ bool CanObtainReadPermission(const url::Origin &origin) override;
+ bool CanObtainWritePermission(const url::Origin &origin) override;
+ void SetLastPickedDirectory(const url::Origin &origin, const std::string &id,
+ const base::FilePath &path, const PathType type) override;
+ FileSystemAccessPermissionContextQt::PathInfo
+ GetLastPickedDirectory(const url::Origin &origin, const std::string &id) override;
+ base::FilePath GetWellKnownDirectoryPath(blink::mojom::WellKnownDirectory directory, const url::Origin &origin) override;
+ std::u16string GetPickerTitle(const blink::mojom::FilePickerOptionsPtr &) override;
+ void NotifyEntryMoved(const url::Origin &, const base::FilePath &, const base::FilePath &) override;
+
+ void NavigatedAwayFromOrigin(const url::Origin &origin);
+ content::BrowserContext *profile() const { return m_profile; }
+
+ void PermissionGrantDestroyed(FileSystemAccessPermissionGrantQt *);
+
+private:
+ class PermissionGrantImpl;
+
+ void DidConfirmSensitiveDirectoryAccess(
+ const url::Origin &origin, const base::FilePath &path, HandleType handle_type,
+ UserAction user_action, content::GlobalRenderFrameHostId frame_id,
+ base::OnceCallback<void(SensitiveEntryResult)> callback, bool should_block);
+ bool AncestorHasActivePermission(const url::Origin &origin,
+ const base::FilePath &path,
+ GrantType grant_type) const;
+
+ content::BrowserContext *m_profile;
+
+ // Permission state per origin.
+ struct OriginState;
+ std::map<url::Origin, OriginState> m_origins;
+
+ std::map<std::string, FileSystemAccessPermissionContextQt::PathInfo> m_lastPickedDirectories;
+
+ base::WeakPtrFactory<FileSystemAccessPermissionContextQt> m_weakFactory { this };
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_QT_H
diff --git a/src/core/file_system_access/file_system_access_permission_grant_qt.cpp b/src/core/file_system_access/file_system_access_permission_grant_qt.cpp
new file mode 100644
index 000000000..67fa1c8cf
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_grant_qt.cpp
@@ -0,0 +1,146 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "file_system_access_permission_grant_qt.h"
+
+#include "file_system_access_permission_request_manager_qt.h"
+
+#include "components/permissions/permission_util.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/disallow_activation_reason.h"
+#include "url/origin.h"
+
+namespace QtWebEngineCore {
+
+FileSystemAccessPermissionGrantQt::FileSystemAccessPermissionGrantQt(
+ base::WeakPtr<FileSystemAccessPermissionContextQt> context, const url::Origin &origin,
+ const base::FilePath &path, HandleType handle_type, GrantType type)
+ : m_context(context), m_origin(origin), m_path(path), m_handleType(handle_type), m_type(type)
+{
+}
+FileSystemAccessPermissionGrantQt::~FileSystemAccessPermissionGrantQt()
+{
+ if (m_context)
+ m_context->PermissionGrantDestroyed(this);
+}
+void FileSystemAccessPermissionGrantQt::RequestPermission(
+ content::GlobalRenderFrameHostId frame_id, UserActivationState user_activation_state,
+ base::OnceCallback<void(PermissionRequestOutcome)> callback)
+{
+ // Check if a permission request has already been processed previously. This
+ // check is done first because we don't want to reset the status of a
+ // permission if it has already been granted.
+ if (GetStatus() != blink::mojom::PermissionStatus::ASK || !m_context) {
+ if (GetStatus() == blink::mojom::PermissionStatus::GRANTED)
+ SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ std::move(callback).Run(PermissionRequestOutcome::kRequestAborted);
+ return;
+ }
+
+ // Otherwise, perform checks and ask the user for permission.
+
+ content::RenderFrameHost *rfh = content::RenderFrameHost::FromID(frame_id);
+ if (!rfh) {
+ // Requested from a no longer valid render frame host.
+ std::move(callback).Run(PermissionRequestOutcome::kInvalidFrame);
+ return;
+ }
+
+ // Don't show request permission UI for an inactive RenderFrameHost as the
+ // page might not distinguish properly between user denying the permission
+ // and automatic rejection, leading to an inconsistent UX once the page
+ // becomes active again.
+ // - If this is called when RenderFrameHost is in BackForwardCache, evict
+ // the document from the cache.
+ // - If this is called when RenderFrameHost is in prerendering, cancel
+ // prerendering.
+ if (rfh->IsInactiveAndDisallowActivation(
+ content::DisallowActivationReasonId::kFileSystemAccessPermissionRequest)) {
+ std::move(callback).Run(PermissionRequestOutcome::kInvalidFrame);
+ return;
+ }
+
+ if (user_activation_state == UserActivationState::kRequired
+ && !rfh->HasTransientUserActivation()) {
+ // No permission prompts without user activation.
+ std::move(callback).Run(PermissionRequestOutcome::kNoUserActivation);
+ return;
+ }
+
+ content::WebContents *web_contents = content::WebContents::FromRenderFrameHost(rfh);
+ if (!web_contents) {
+ // Requested from a worker, or a no longer existing tab.
+ std::move(callback).Run(PermissionRequestOutcome::kInvalidFrame);
+ return;
+ }
+
+ url::Origin embedding_origin = url::Origin::Create(web_contents->GetLastCommittedURL());
+ if (embedding_origin != m_origin) {
+ // Third party iframes are not allowed to request more permissions.
+ std::move(callback).Run(PermissionRequestOutcome::kThirdPartyContext);
+ return;
+ }
+
+ auto *request_manager =
+ FileSystemAccessPermissionRequestManagerQt::FromWebContents(web_contents);
+ if (!request_manager) {
+ std::move(callback).Run(PermissionRequestOutcome::kRequestAborted);
+ return;
+ }
+
+ // Drop fullscreen mode so that the user sees the URL bar.
+ base::ScopedClosureRunner fullscreen_block = web_contents->ForSecurityDropFullscreen();
+
+ FileSystemAccessPermissionRequestManagerQt::Access access = m_type == GrantType::kRead
+ ? FileSystemAccessPermissionRequestManagerQt::Access::kRead
+ : FileSystemAccessPermissionRequestManagerQt::Access::kWrite;
+
+ // If a website wants both read and write access, code in content will
+ // request those as two separate requests. The |request_manager| will then
+ // detect this and combine the two requests into one prompt. As such this
+ // code does not have to have any way to request Access::kReadWrite.
+
+ request_manager->AddRequest(
+ { m_origin, m_path, m_handleType, access },
+ base::BindOnce(&FileSystemAccessPermissionGrantQt::OnPermissionRequestResult, this,
+ std::move(callback)),
+ std::move(fullscreen_block));
+}
+
+void FileSystemAccessPermissionGrantQt::SetStatus(blink::mojom::PermissionStatus status)
+{
+ bool should_notify = m_status != status;
+ m_status = status;
+ if (should_notify)
+ NotifyPermissionStatusChanged();
+}
+
+void FileSystemAccessPermissionGrantQt::OnPermissionRequestResult(
+ base::OnceCallback<void(PermissionRequestOutcome)> callback, permissions::PermissionAction result)
+{
+ switch (result) {
+ case permissions::PermissionAction::GRANTED:
+ SetStatus(blink::mojom::PermissionStatus::GRANTED);
+ std::move(callback).Run(PermissionRequestOutcome::kUserGranted);
+ break;
+ case permissions::PermissionAction::DENIED:
+ SetStatus(blink::mojom::PermissionStatus::DENIED);
+ std::move(callback).Run(PermissionRequestOutcome::kUserDenied);
+ break;
+ case permissions::PermissionAction::DISMISSED:
+ case permissions::PermissionAction::IGNORED:
+ std::move(callback).Run(PermissionRequestOutcome::kUserDismissed);
+ break;
+ case permissions::PermissionAction::REVOKED:
+ case permissions::PermissionAction::GRANTED_ONCE:
+ case permissions::PermissionAction::NUM:
+ NOTREACHED();
+ break;
+ }
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/file_system_access/file_system_access_permission_grant_qt.h b/src/core/file_system_access/file_system_access_permission_grant_qt.h
new file mode 100644
index 000000000..829d2b889
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_grant_qt.h
@@ -0,0 +1,59 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_GRANT_QT_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_GRANT_QT_H
+
+#include "content/public/browser/file_system_access_permission_grant.h"
+#include "url/origin.h"
+#include "file_system_access_permission_context_qt.h"
+#include "content/public/browser/global_routing_id.h"
+#include "components/permissions/permission_util.h"
+
+namespace QtWebEngineCore {
+
+using HandleType = content::FileSystemAccessPermissionContext::HandleType;
+using GrantType = FileSystemAccessPermissionContextQt::GrantType;
+
+class FileSystemAccessPermissionGrantQt : public content::FileSystemAccessPermissionGrant
+{
+public:
+ FileSystemAccessPermissionGrantQt(base::WeakPtr<FileSystemAccessPermissionContextQt> context,
+ const url::Origin &origin, const base::FilePath &path,
+ HandleType handle_type, GrantType type);
+
+ // content::FileSystemAccessPermissionGrant:
+ blink::mojom::PermissionStatus GetStatus() override { return m_status; }
+ base::FilePath GetPath() override { return m_path; }
+ void RequestPermission(content::GlobalRenderFrameHostId frame_id,
+ UserActivationState user_activation_state,
+ base::OnceCallback<void(PermissionRequestOutcome)> callback) override;
+
+ const url::Origin &origin() const { return m_origin; }
+ HandleType handleType() const { return m_handleType; }
+ const base::FilePath &path() const { return m_path; }
+ GrantType type() const { return m_type; }
+
+ void SetStatus(blink::mojom::PermissionStatus status);
+
+protected:
+ ~FileSystemAccessPermissionGrantQt() override;
+
+private:
+ void OnPermissionRequestResult(base::OnceCallback<void(PermissionRequestOutcome)> callback,
+ permissions::PermissionAction result);
+
+ base::WeakPtr<FileSystemAccessPermissionContextQt> const m_context;
+ const url::Origin m_origin;
+ const base::FilePath m_path;
+ const HandleType m_handleType;
+ const GrantType m_type;
+
+ // This member should only be updated via SetStatus(), to make sure
+ // observers are properly notified about any change in status.
+ blink::mojom::PermissionStatus m_status = blink::mojom::PermissionStatus::ASK;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_GRANT_QT_H
diff --git a/src/core/file_system_access/file_system_access_permission_request_controller.h b/src/core/file_system_access/file_system_access_permission_request_controller.h
new file mode 100644
index 000000000..e659f81a7
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_request_controller.h
@@ -0,0 +1,39 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_H
+
+#include "api/qwebenginefilesystemaccessrequest.h"
+#include "request_controller.h"
+
+using HandleType = QWebEngineFileSystemAccessRequest::HandleType;
+using AccessFlags = QWebEngineFileSystemAccessRequest::AccessFlags;
+
+namespace QtWebEngineCore {
+
+class FileSystemAccessPermissionRequestController : public RequestController
+{
+public:
+ FileSystemAccessPermissionRequestController(const QUrl &origin, const QUrl &filePath,
+ HandleType handleType, AccessFlags accessType)
+ : RequestController(origin)
+ , m_filePath(filePath)
+ , m_handleType(handleType)
+ , m_accessType(accessType)
+ {
+ }
+
+ QUrl filePath() const { return m_filePath; }
+ HandleType handleType() const { return m_handleType; }
+ AccessFlags accessFlags() const { return m_accessType; }
+
+private:
+ QUrl m_filePath;
+ HandleType m_handleType;
+ AccessFlags m_accessType;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_H
diff --git a/src/core/file_system_access/file_system_access_permission_request_controller_impl.cpp b/src/core/file_system_access/file_system_access_permission_request_controller_impl.cpp
new file mode 100644
index 000000000..f77c974d0
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_request_controller_impl.cpp
@@ -0,0 +1,48 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "file_system_access_permission_request_controller_impl.h"
+
+#include "components/permissions/permission_util.h"
+#include "content/public/browser/file_system_access_permission_context.h"
+#include "type_conversion.h"
+
+namespace QtWebEngineCore {
+
+ASSERT_ENUMS_MATCH(content::FileSystemAccessPermissionContext::HandleType::kFile,
+ QWebEngineFileSystemAccessRequest::HandleType::File);
+ASSERT_ENUMS_MATCH(content::FileSystemAccessPermissionContext::HandleType::kDirectory,
+ QWebEngineFileSystemAccessRequest::HandleType::Directory);
+
+ASSERT_ENUMS_MATCH(FileSystemAccessPermissionRequestManagerQt::Access::kRead,
+ QWebEngineFileSystemAccessRequest::AccessFlag::Read);
+ASSERT_ENUMS_MATCH(FileSystemAccessPermissionRequestManagerQt::Access::kWrite,
+ QWebEngineFileSystemAccessRequest::AccessFlag::Write);
+
+FileSystemAccessPermissionRequestControllerImpl::FileSystemAccessPermissionRequestControllerImpl(
+ const FileSystemAccessPermissionRequestManagerQt::RequestData &request,
+ base::OnceCallback<void(permissions::PermissionAction result)> callback)
+ : FileSystemAccessPermissionRequestController(
+ toQt(request.origin.GetURL()), QUrl::fromLocalFile(toQt(request.path.value())),
+ (HandleType)request.handle_type, AccessFlags((int)request.access))
+ , m_callback(std::move(callback))
+{
+}
+
+FileSystemAccessPermissionRequestControllerImpl::~FileSystemAccessPermissionRequestControllerImpl()
+{
+ if (m_callback)
+ std::move(m_callback).Run(permissions::PermissionAction::IGNORED);
+}
+
+void FileSystemAccessPermissionRequestControllerImpl::accepted()
+{
+ std::move(m_callback).Run(permissions::PermissionAction::GRANTED);
+}
+
+void FileSystemAccessPermissionRequestControllerImpl::rejected()
+{
+ std::move(m_callback).Run(permissions::PermissionAction::DENIED);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/file_system_access/file_system_access_permission_request_controller_impl.h b/src/core/file_system_access/file_system_access_permission_request_controller_impl.h
new file mode 100644
index 000000000..6cca1e549
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_request_controller_impl.h
@@ -0,0 +1,32 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_IMPL_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_IMPL_H
+
+#include "file_system_access_permission_request_controller.h"
+#include "file_system_access_permission_request_manager_qt.h"
+
+namespace QtWebEngineCore {
+
+class FileSystemAccessPermissionRequestControllerImpl final
+ : public FileSystemAccessPermissionRequestController
+{
+public:
+ FileSystemAccessPermissionRequestControllerImpl(
+ const FileSystemAccessPermissionRequestManagerQt::RequestData &request,
+ base::OnceCallback<void(permissions::PermissionAction result)> callback);
+
+ ~FileSystemAccessPermissionRequestControllerImpl();
+
+protected:
+ void accepted() override;
+ void rejected() override;
+
+private:
+ base::OnceCallback<void(permissions::PermissionAction result)> m_callback;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_CONTROLLER_IMPL_H
diff --git a/src/core/file_system_access/file_system_access_permission_request_manager_qt.cpp b/src/core/file_system_access/file_system_access_permission_request_manager_qt.cpp
new file mode 100644
index 000000000..c384dc7b3
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_request_manager_qt.cpp
@@ -0,0 +1,195 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "file_system_access_permission_request_manager_qt.h"
+
+#include "components/permissions/permission_util.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/navigation_handle.h"
+
+#include "api/qwebenginefilesystemaccessrequest.h"
+#include "file_system_access_permission_context_factory_qt.h"
+#include "file_system_access_permission_request_controller_impl.h"
+#include "web_contents_adapter_client.h"
+#include "web_contents_view_qt.h"
+
+namespace QtWebEngineCore {
+
+bool RequestsAreIdentical(const FileSystemAccessPermissionRequestManagerQt::RequestData &a,
+ const FileSystemAccessPermissionRequestManagerQt::RequestData &b)
+{
+ return a.origin == b.origin && a.path == b.path && a.handle_type == b.handle_type
+ && a.access == b.access;
+}
+
+bool RequestsAreForSamePath(const FileSystemAccessPermissionRequestManagerQt::RequestData &a,
+ const FileSystemAccessPermissionRequestManagerQt::RequestData &b)
+{
+ return a.origin == b.origin && a.path == b.path && a.handle_type == b.handle_type;
+}
+
+struct FileSystemAccessPermissionRequestManagerQt::Request
+{
+ Request(RequestData data,
+ base::OnceCallback<void(permissions::PermissionAction result)> callback,
+ base::ScopedClosureRunner fullscreen_block)
+ : data(std::move(data))
+ {
+ callbacks.push_back(std::move(callback));
+ fullscreen_blocks.push_back(std::move(fullscreen_block));
+ }
+
+ RequestData data;
+ std::vector<base::OnceCallback<void(permissions::PermissionAction result)>> callbacks;
+ std::vector<base::ScopedClosureRunner> fullscreen_blocks;
+};
+
+FileSystemAccessPermissionRequestManagerQt::~FileSystemAccessPermissionRequestManagerQt() = default;
+
+void FileSystemAccessPermissionRequestManagerQt::AddRequest(
+ RequestData data, base::OnceCallback<void(permissions::PermissionAction result)> callback,
+ base::ScopedClosureRunner fullscreen_block)
+{
+ // Check if any pending requests are identical to the new request.
+ if (m_currentRequest && RequestsAreIdentical(m_currentRequest->data, data)) {
+ m_currentRequest->callbacks.push_back(std::move(callback));
+ m_currentRequest->fullscreen_blocks.push_back(std::move(fullscreen_block));
+ return;
+ }
+ for (const auto &request : m_queuedRequests) {
+ if (RequestsAreIdentical(request->data, data)) {
+ request->callbacks.push_back(std::move(callback));
+ request->fullscreen_blocks.push_back(std::move(fullscreen_block));
+ return;
+ }
+ if (RequestsAreForSamePath(request->data, data)) {
+ // This means access levels are different. Change the existing request
+ // to kReadWrite, and add the new callback.
+ request->data.access = Access::kReadWrite;
+ request->callbacks.push_back(std::move(callback));
+ request->fullscreen_blocks.push_back(std::move(fullscreen_block));
+ return;
+ }
+ }
+
+ m_queuedRequests.push_back(std::make_unique<Request>(std::move(data), std::move(callback),
+ std::move(fullscreen_block)));
+ if (!IsShowingRequest())
+ ScheduleShowRequest();
+}
+
+FileSystemAccessPermissionRequestManagerQt::FileSystemAccessPermissionRequestManagerQt(
+ content::WebContents *web_contents)
+ : content::WebContentsObserver(web_contents)
+ , content::WebContentsUserData<FileSystemAccessPermissionRequestManagerQt>(*web_contents)
+{
+}
+
+bool FileSystemAccessPermissionRequestManagerQt::CanShowRequest() const
+{
+ // Delay showing requests until the main frame is fully loaded.
+ // ScheduleShowRequest() will be called again when that happens.
+ return web_contents()->IsDocumentOnLoadCompletedInPrimaryMainFrame() && !m_queuedRequests.empty()
+ && !m_currentRequest;
+}
+
+void FileSystemAccessPermissionRequestManagerQt::ScheduleShowRequest()
+{
+ if (!CanShowRequest())
+ return;
+
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&FileSystemAccessPermissionRequestManagerQt::DequeueAndShowRequest,
+ m_weakFactory.GetWeakPtr()));
+}
+
+void FileSystemAccessPermissionRequestManagerQt::DequeueAndShowRequest()
+{
+ if (!CanShowRequest())
+ return;
+
+ m_currentRequest = std::move(m_queuedRequests.front());
+ m_queuedRequests.pop_front();
+
+ WebContentsAdapterClient *client =
+ WebContentsViewQt::from(
+ static_cast<content::WebContentsImpl *>(web_contents())->GetView())
+ ->client();
+ if (!client) {
+ LOG(ERROR)
+ << "Attempt to request file system access from content missing WebContents client";
+ for (auto &callback : m_currentRequest->callbacks)
+ std::move(callback).Run(permissions::PermissionAction::DENIED);
+ return;
+ }
+
+ QWebEngineFileSystemAccessRequest request(
+ std::make_shared<FileSystemAccessPermissionRequestControllerImpl>(
+ m_currentRequest->data,
+ base::BindOnce(
+ &FileSystemAccessPermissionRequestManagerQt::OnPermissionDialogResult,
+ m_weakFactory.GetWeakPtr())));
+ client->runFileSystemAccessRequest(std::move(request));
+}
+
+void FileSystemAccessPermissionRequestManagerQt::DocumentOnLoadCompletedInPrimaryMainFrame()
+{
+ // This is scheduled because while all calls to the browser have been
+ // issued at DOMContentLoaded, they may be bouncing around in scheduled
+ // callbacks finding the UI thread still. This makes sure we allow those
+ // scheduled calls to AddRequest to complete before we show the page-load
+ // permissions bubble.
+ if (!m_queuedRequests.empty())
+ ScheduleShowRequest();
+}
+
+void FileSystemAccessPermissionRequestManagerQt::DidFinishNavigation(
+ content::NavigationHandle *navigation)
+{
+ // We only care about top-level navigations that actually committed.
+ if (!navigation->IsInMainFrame() || !navigation->HasCommitted())
+ return;
+
+ auto src_origin = url::Origin::Create(navigation->GetPreviousPrimaryMainFrameURL());
+ auto dest_origin = url::Origin::Create(navigation->GetURL());
+ if (src_origin == dest_origin)
+ return;
+
+ // Navigated away from |src_origin|, tell permission context to check if
+ // permissions need to be revoked.
+ auto *context = FileSystemAccessPermissionContextFactoryQt::GetForProfileIfExists(
+ web_contents()->GetBrowserContext());
+ if (context)
+ context->NavigatedAwayFromOrigin(src_origin);
+}
+
+void FileSystemAccessPermissionRequestManagerQt::WebContentsDestroyed()
+{
+ auto src_origin = web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin();
+
+ // Navigated away from |src_origin|, tell permission context to check if
+ // permissions need to be revoked.
+ auto *context = FileSystemAccessPermissionContextFactoryQt::GetForProfileIfExists(
+ web_contents()->GetBrowserContext());
+ if (context)
+ context->NavigatedAwayFromOrigin(src_origin);
+}
+
+void FileSystemAccessPermissionRequestManagerQt::OnPermissionDialogResult(
+ permissions::PermissionAction result)
+{
+ DCHECK(m_currentRequest);
+ for (auto &callback : m_currentRequest->callbacks)
+ std::move(callback).Run(result);
+
+ m_currentRequest = nullptr;
+ if (!m_queuedRequests.empty())
+ ScheduleShowRequest();
+}
+
+WEB_CONTENTS_USER_DATA_KEY_IMPL(FileSystemAccessPermissionRequestManagerQt);
+
+} // namespace QtWebEngineCore
diff --git a/src/core/file_system_access/file_system_access_permission_request_manager_qt.h b/src/core/file_system_access/file_system_access_permission_request_manager_qt.h
new file mode 100644
index 000000000..840854911
--- /dev/null
+++ b/src/core/file_system_access/file_system_access_permission_request_manager_qt.h
@@ -0,0 +1,79 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_MANAGER_QT_H
+#define FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_MANAGER_QT_H
+
+#include "base/containers/circular_deque.h"
+#include "base/files/file_path.h"
+#include "base/functional/callback_helpers.h"
+#include "base/memory/weak_ptr.h"
+#include "content/public/browser/file_system_access_permission_context.h"
+#include "content/public/browser/web_contents_observer.h"
+#include "content/public/browser/web_contents_user_data.h"
+#include "url/origin.h"
+
+namespace permissions {
+enum class PermissionAction;
+}
+
+namespace QtWebEngineCore {
+
+class FileSystemAccessPermissionRequestManagerQt
+ : public content::WebContentsObserver,
+ public content::WebContentsUserData<FileSystemAccessPermissionRequestManagerQt>
+{
+public:
+ ~FileSystemAccessPermissionRequestManagerQt() override;
+
+ enum class Access {
+ // Only ask for read access.
+ kRead = 0x1,
+ // Only ask for write access, assuming read access has already been granted.
+ kWrite = 0x2,
+ // Ask for both read and write access.
+ kReadWrite = 0x3
+ };
+
+ struct RequestData
+ {
+ url::Origin origin;
+ base::FilePath path;
+ content::FileSystemAccessPermissionContext::HandleType handle_type;
+ Access access;
+ };
+
+ void AddRequest(RequestData request,
+ base::OnceCallback<void(permissions::PermissionAction result)> callback,
+ base::ScopedClosureRunner fullscreen_block);
+
+private:
+ friend class content::WebContentsUserData<FileSystemAccessPermissionRequestManagerQt>;
+
+ explicit FileSystemAccessPermissionRequestManagerQt(content::WebContents *web_contents);
+
+ bool IsShowingRequest() const { return m_currentRequest != nullptr; }
+ bool CanShowRequest() const;
+ void ScheduleShowRequest();
+ void DequeueAndShowRequest();
+
+ // content::WebContentsObserver
+ void DocumentOnLoadCompletedInPrimaryMainFrame() override;
+ void DidFinishNavigation(content::NavigationHandle *navigation_handle) override;
+ void WebContentsDestroyed() override;
+
+ void OnPermissionDialogResult(permissions::PermissionAction result);
+
+ struct Request;
+ // Request currently being shown in prompt.
+ std::unique_ptr<Request> m_currentRequest;
+ // Queued up requests.
+ base::circular_deque<std::unique_ptr<Request>> m_queuedRequests;
+
+ base::WeakPtrFactory<FileSystemAccessPermissionRequestManagerQt> m_weakFactory { this };
+ WEB_CONTENTS_USER_DATA_KEY_DECL();
+};
+
+} // namespace QtWebEngineCore
+
+#endif // FILE_SYSTEM_ACCESS_PERMISSION_REQUEST_MANAGER_QT_H
diff --git a/src/core/find_text_helper.cpp b/src/core/find_text_helper.cpp
index da9d7f352..5dc12fab7 100644
--- a/src/core/find_text_helper.cpp
+++ b/src/core/find_text_helper.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "find_text_helper.h"
#include "qwebenginefindtextresult.h"
@@ -64,17 +28,18 @@ FindTextHelper::~FindTextHelper()
stopFinding();
}
-void FindTextHelper::startFinding(const QString &findText, bool caseSensitively, bool findBackward, const QWebEngineCallback<bool> resultCallback)
+void FindTextHelper::startFinding(const QString &findText, bool caseSensitively, bool findBackward, const std::function<void(const QWebEngineFindTextResult &)> &resultCallback)
{
if (findText.isEmpty()) {
stopFinding();
m_viewClient->findTextFinished(QWebEngineFindTextResult());
- m_widgetCallbacks.invokeEmpty(resultCallback);
+ if (resultCallback)
+ resultCallback(QWebEngineFindTextResult());
return;
}
startFinding(findText, caseSensitively, findBackward);
- m_widgetCallbacks.registerCallback(m_currentFindRequestId, resultCallback);
+ m_widgetCallbacks.insert(m_currentFindRequestId, resultCallback);
}
void FindTextHelper::startFinding(const QString &findText, bool caseSensitively, bool findBackward, const QJSValue &resultCallback)
@@ -97,30 +62,30 @@ void FindTextHelper::startFinding(const QString &findText, bool caseSensitively,
void FindTextHelper::startFinding(const QString &findText, bool caseSensitively, bool findBackward)
{
- if (findText.isEmpty()) {
- stopFinding();
- return;
- }
+ Q_ASSERT(!findText.isEmpty());
- if (m_currentFindRequestId > m_lastCompletedFindRequestId) {
+ const bool findNext = !m_previousFindText.isEmpty() && findText == m_previousFindText;
+ if (isFindTextInProgress()) {
// There are cases where the render process will overwrite a previous request
// with the new search and we'll have a dangling callback, leaving the application
// waiting for it forever.
// Assume that any unfinished find has been unsuccessful when a new one is started
// to cover that case.
m_lastCompletedFindRequestId = m_currentFindRequestId;
+ if (!findNext)
+ m_webContents->StopFinding(content::STOP_FIND_ACTION_KEEP_SELECTION);
m_viewClient->findTextFinished(QWebEngineFindTextResult());
- invokeResultCallback(m_currentFindRequestId, 0);
+ invokeResultCallback(m_currentFindRequestId, 0, 0);
}
blink::mojom::FindOptionsPtr options = blink::mojom::FindOptions::New();
options->forward = !findBackward;
options->match_case = caseSensitively;
- options->find_next = findText == m_previousFindText;
+ options->new_session = !findNext;
m_previousFindText = findText;
m_currentFindRequestId = m_findRequestIdCounter++;
- m_webContents->Find(m_currentFindRequestId, toString16(findText), std::move(options));
+ m_webContents->Find(m_currentFindRequestId, toString16(findText), std::move(options), /*skip_delay=*/true);
}
void FindTextHelper::stopFinding()
@@ -148,7 +113,7 @@ void FindTextHelper::handleFindReply(content::WebContents *source, int requestId
Q_ASSERT(m_currentFindRequestId == requestId);
m_lastCompletedFindRequestId = requestId;
m_viewClient->findTextFinished(QWebEngineFindTextResult(numberOfMatches, activeMatch));
- invokeResultCallback(requestId, numberOfMatches);
+ invokeResultCallback(requestId, numberOfMatches, activeMatch);
}
void FindTextHelper::handleLoadCommitted()
@@ -157,15 +122,15 @@ void FindTextHelper::handleLoadCommitted()
m_previousFindText = QString();
}
-void FindTextHelper::invokeResultCallback(int requestId, int numberOfMatches)
+void FindTextHelper::invokeResultCallback(int requestId, int numberOfMatches, int activeMatch)
{
if (m_quickCallbacks.contains(requestId)) {
QJSValue resultCallback = m_quickCallbacks.take(requestId);
QJSValueList args;
args.append(QJSValue(numberOfMatches));
resultCallback.call(args);
- } else {
- m_widgetCallbacks.invoke(requestId, numberOfMatches > 0);
+ } else if (auto func = m_widgetCallbacks.take(requestId)) {
+ func(QWebEngineFindTextResult(numberOfMatches, activeMatch));
}
}
diff --git a/src/core/find_text_helper.h b/src/core/find_text_helper.h
index 9843dc8b5..6d2e48b63 100644
--- a/src/core/find_text_helper.h
+++ b/src/core/find_text_helper.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,10 +15,13 @@
#ifndef FIND_TEXT_HELPER_H
#define FIND_TEXT_HELPER_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
-#include "qwebenginecallback_p.h"
#include <QJSValue>
+#include <QMap>
+#include <QString>
+
+#include <functional>
namespace content {
class WebContents;
@@ -64,16 +31,18 @@ namespace gfx {
class Rect;
}
+QT_FORWARD_DECLARE_CLASS(QWebEngineFindTextResult)
+
namespace QtWebEngineCore {
class WebContentsAdapterClient;
-class Q_WEBENGINECORE_PRIVATE_EXPORT FindTextHelper {
+class Q_WEBENGINECORE_EXPORT FindTextHelper {
public:
FindTextHelper(content::WebContents *webContents, WebContentsAdapterClient *viewClient);
~FindTextHelper();
- void startFinding(const QString &findText, bool caseSensitively, bool findBackward, const QWebEngineCallback<bool> resultCallback);
+ void startFinding(const QString &findText, bool caseSensitively, bool findBackward, const std::function<void(const QWebEngineFindTextResult &)> &resultCallback);
void startFinding(const QString &findText, bool caseSensitively, bool findBackward, const QJSValue &resultCallback);
void startFinding(const QString &findText, bool caseSensitively, bool findBackward);
void stopFinding();
@@ -82,7 +51,7 @@ public:
void handleLoadCommitted();
private:
- void invokeResultCallback(int requestId, int numberOfMatches);
+ void invokeResultCallback(int requestId, int numberOfMatches, int activeMatch);
content::WebContents *m_webContents;
WebContentsAdapterClient *m_viewClient;
@@ -94,7 +63,7 @@ private:
QString m_previousFindText;
QMap<int, QJSValue> m_quickCallbacks;
- CallbackDirectory m_widgetCallbacks;
+ QMap<int, std::function<void(const QWebEngineFindTextResult &)>> m_widgetCallbacks;
};
} // namespace QtWebEngineCore
diff --git a/src/core/global_descriptors_qt.h b/src/core/global_descriptors_qt.h
index b9d622606..f9b08f1d6 100644
--- a/src/core/global_descriptors_qt.h
+++ b/src/core/global_descriptors_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GLOBAL_DESCRIPTORS_QT_H
#define GLOBAL_DESCRIPTORS_QT_H
diff --git a/src/core/gn_run.pro b/src/core/gn_run.pro
deleted file mode 100644
index 4688ea59d..000000000
--- a/src/core/gn_run.pro
+++ /dev/null
@@ -1,68 +0,0 @@
-include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri)
-include($$QTWEBENGINE_OUT_ROOT/src/core/qtwebenginecore-config.pri)
-QT_FOR_CONFIG += buildtools-private webenginecore-private core-private gui-private
-
-TEMPLATE = aux
-
-qtConfig(debug_and_release): CONFIG += debug_and_release
-qtConfig(build_all): CONFIG += build_all
-
-QT_TOOL.ninja.binary = $$shell_quote($$shell_path($$ninjaPath()))
-
-win32 {
- # Add the gnuwin32/bin subdir of qt5.git to PATH. Needed for calling bison and friends.
- gnuwin32path.name = PATH
- gnuwin32path.value = $$shell_path($$clean_path($$QTWEBENGINE_ROOT/../gnuwin32/bin))
- gnuwin32path.CONFIG += prepend
- exists($$gnuwin32path.value): QT_TOOL_ENV = gnuwin32path
-}
-
-qtPrepareTool(NINJA, ninja)
-QT_TOOL_ENV =
-
-build_pass|!debug_and_release {
- gn_binary = gn
-
- runninja.target = run_ninja
-
- gn_args = $$gnWebEngineArgs()
-
- gn_args += "qtwebengine_target=\"$$system_path($$OUT_PWD/$$getConfigDir()):QtWebEngineCore\""
-
- !qtConfig(webengine-system-gn) {
- gn_binary = $$system_quote($$system_path($$gnPath()))
- }
-
- gn_args = $$system_quote($$gn_args)
- gn_src_root = $$system_quote($$system_path($$QTWEBENGINE_ROOT/$$getChromiumSrcDir()))
- gn_build_root = $$system_quote($$system_path($$OUT_PWD/$$getConfigDir()))
- gn_python = "--script-executable=$$pythonPathForSystem()"
- gn_run = $$gn_binary gen $$gn_build_root $$gn_python --args=$$gn_args --root=$$gn_src_root
-
- message("Running: $$gn_run ")
- !system($$gn_run) {
- error("GN run error!")
- }
-
- ninjaflags = $$(NINJAFLAGS)
- isEmpty(ninjaflags):!silent: ninjaflags = "-v"
-
- runninja.commands = $$NINJA $$ninjaflags \$\(NINJAJOBS\) -C $$gn_build_root QtWebEngineCore
- QMAKE_EXTRA_TARGETS += runninja
-
- build_pass:build_all: default_target.target = all
- else: default_target.target = first
- default_target.depends = runninja
- QMAKE_EXTRA_TARGETS += default_target
-}
-
-!build_pass:debug_and_release {
- # Special GNU make target for the meta Makefile that ensures that our debug and release Makefiles won't both run ninja in parallel.
- notParallel.target = .NOTPARALLEL
- QMAKE_EXTRA_TARGETS += notParallel
-}
-
-build_pass:CONFIG(debug, debug|release) {
- TARGET = gn_run_debug
-}
-
diff --git a/src/core/javascript_dialog_controller.cpp b/src/core/javascript_dialog_controller.cpp
index 86f5b9795..c8a6a58bf 100644
--- a/src/core/javascript_dialog_controller.cpp
+++ b/src/core/javascript_dialog_controller.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "javascript_dialog_controller.h"
#include "javascript_dialog_controller_p.h"
@@ -45,7 +9,7 @@
namespace QtWebEngineCore {
-void JavaScriptDialogControllerPrivate::dialogFinished(bool accepted, const base::string16 &promptValue)
+void JavaScriptDialogControllerPrivate::dialogFinished(bool accepted, const std::u16string &promptValue)
{
// Clear the queue first as this could result in the engine asking us to run another dialog,
// but hold a shared pointer so the dialog does not get deleted prematurely when running in-process.
diff --git a/src/core/javascript_dialog_controller.h b/src/core/javascript_dialog_controller.h
index ba9f51944..6c1ee269f 100644
--- a/src/core/javascript_dialog_controller.h
+++ b/src/core/javascript_dialog_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -59,7 +23,7 @@ namespace QtWebEngineCore {
class JavaScriptDialogControllerPrivate;
-class Q_WEBENGINECORE_PRIVATE_EXPORT JavaScriptDialogController : public QObject {
+class Q_WEBENGINECORE_EXPORT JavaScriptDialogController : public QObject {
Q_OBJECT
public:
~JavaScriptDialogController();
diff --git a/src/core/javascript_dialog_controller_p.h b/src/core/javascript_dialog_controller_p.h
index ab7b09268..af064250b 100644
--- a/src/core/javascript_dialog_controller_p.h
+++ b/src/core/javascript_dialog_controller_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef JAVASCRIPT_DIALOG_CONTROLLER_P_H
#define JAVASCRIPT_DIALOG_CONTROLLER_P_H
@@ -51,12 +15,13 @@
// We mean it.
//
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "web_contents_adapter_client.h"
#include <QString>
+#include <QUrl>
namespace content {
class WebContents;
@@ -67,7 +32,7 @@ namespace QtWebEngineCore {
class JavaScriptDialogControllerPrivate {
public:
- void dialogFinished(bool accepted, const base::string16 &promptValue);
+ void dialogFinished(bool accepted, const std::u16string &promptValue);
JavaScriptDialogControllerPrivate(WebContentsAdapterClient::JavascriptDialogType, const QString &message, const QString &prompt
, const QString& title, const QUrl &securityOrigin
, content::JavaScriptDialogManager::DialogClosedCallback &&, content::WebContents *);
diff --git a/src/core/javascript_dialog_manager_qt.cpp b/src/core/javascript_dialog_manager_qt.cpp
index 289947237..c5ee357ad 100644
--- a/src/core/javascript_dialog_manager_qt.cpp
+++ b/src/core/javascript_dialog_manager_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "javascript_dialog_manager_qt.h"
@@ -63,8 +27,8 @@ JavaScriptDialogManagerQt *JavaScriptDialogManagerQt::GetInstance()
void JavaScriptDialogManagerQt::RunJavaScriptDialog(content::WebContents *webContents,
content::RenderFrameHost *renderFrameHost,
content::JavaScriptDialogType dialog_type,
- const base::string16 &messageText,
- const base::string16 &defaultPromptText,
+ const std::u16string &messageText,
+ const std::u16string &defaultPromptText,
content::JavaScriptDialogManager::DialogClosedCallback callback,
bool *didSuppressMessage)
{
@@ -87,12 +51,12 @@ void JavaScriptDialogManagerQt::RunBeforeUnloadDialog(content::WebContents *webC
runDialogForContents(webContents, WebContentsAdapterClient::UnloadDialog, QString(), QString(), toQt(originUrl), std::move(callback));
}
-bool JavaScriptDialogManagerQt::HandleJavaScriptDialog(content::WebContents *contents, bool accept, const base::string16 *promptOverride)
+bool JavaScriptDialogManagerQt::HandleJavaScriptDialog(content::WebContents *contents, bool accept, const std::u16string *promptOverride)
{
QSharedPointer<JavaScriptDialogController> dialog = m_activeDialogs.value(contents);
if (!dialog)
return false;
- dialog->d->dialogFinished(accept, promptOverride ? *promptOverride : base::string16());
+ dialog->d->dialogFinished(accept, promptOverride ? *promptOverride : std::u16string());
takeDialogForContents(contents);
return true;
}
diff --git a/src/core/javascript_dialog_manager_qt.h b/src/core/javascript_dialog_manager_qt.h
index ca7432a77..2a587afc7 100644
--- a/src/core/javascript_dialog_manager_qt.h
+++ b/src/core/javascript_dialog_manager_qt.h
@@ -1,45 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef JAVASCRIPT_DIALOG_MANAGER_QT_H
#define JAVASCRIPT_DIALOG_MANAGER_QT_H
-#include "base/callback.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "web_contents_adapter_client.h"
@@ -61,14 +24,14 @@ public:
static JavaScriptDialogManagerQt *GetInstance();
void RunJavaScriptDialog(content::WebContents *, content::RenderFrameHost *, content::JavaScriptDialogType dialog_type,
- const base::string16 &messageText, const base::string16 &defaultPromptText,
+ const std::u16string &messageText, const std::u16string &defaultPromptText,
DialogClosedCallback callback,
bool *didSuppressMessage) override;
void RunBeforeUnloadDialog(content::WebContents *web_contents,
content::RenderFrameHost *render_frame_host,
bool is_reload,
DialogClosedCallback callback) override;
- bool HandleJavaScriptDialog(content::WebContents *, bool accept, const base::string16 *promptOverride) override;
+ bool HandleJavaScriptDialog(content::WebContents *, bool accept, const std::u16string *promptOverride) override;
void CancelDialogs(content::WebContents *contents, bool /*reset_state*/) override
{
takeDialogForContents(contents);
diff --git a/src/core/location_provider_qt.cpp b/src/core/location_provider_qt.cpp
index d5a7f1297..dc0d80aa7 100644
--- a/src/core/location_provider_qt.cpp
+++ b/src/core/location_provider_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "location_provider_qt.h"
@@ -48,13 +12,18 @@
#include <QtCore/QThread>
#include <QtPositioning/QGeoPositionInfoSource>
-#include "base/bind.h"
+#if QT_CONFIG(permissions)
+#include <QtCore/qpermissions.h>
+#endif
+
+#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
-#include "base/message_loop/message_loop.h"
#include "content/public/browser/browser_thread.h"
#include "services/device/geolocation/geolocation_provider.h"
#include "services/device/geolocation/geolocation_provider_impl.h"
+#include "services/device/public/mojom/geoposition.mojom.h"
+
namespace QtWebEngineCore {
using content::BrowserThread;
@@ -72,14 +41,14 @@ public:
private Q_SLOTS:
void updatePosition(const QGeoPositionInfo &);
void error(QGeoPositionInfoSource::Error positioningError);
- void timeout();
private:
+ void startImpl(bool highAccuracy);
LocationProviderQt *m_locationProvider;
QGeoPositionInfoSource *m_positionInfoSource;
base::WeakPtrFactory<LocationProviderQt> m_locationProviderFactory;
- void postToLocationProvider(const base::Closure &task);
+ void postToLocationProvider(base::OnceClosure task);
friend class LocationProviderQt;
};
@@ -104,6 +73,38 @@ static bool isHighAccuracySource(const QGeoPositionInfoSource *source)
void QtPositioningHelper::start(bool highAccuracy)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ // New Qt permissions API from 6.5.0
+#if QT_CONFIG(permissions)
+ QLocationPermission locationPermission;
+ locationPermission.setAvailability(QLocationPermission::WhenInUse);
+
+ QLocationPermission::Accuracy accuracy = highAccuracy ? QLocationPermission::Precise
+ : QLocationPermission::Approximate;
+ locationPermission.setAccuracy(accuracy);
+
+ switch (qApp->checkPermission(locationPermission)) {
+ case Qt::PermissionStatus::Undetermined:
+ qApp->requestPermission(locationPermission, this,
+ [this, &highAccuracy](const QPermission &permission) {
+ if (permission.status() == Qt::PermissionStatus::Granted)
+ this->startImpl(highAccuracy);
+ });
+
+ return;
+ case Qt::PermissionStatus::Denied:
+ qWarning("Failed to initialize location provider: The user does not have the right "
+ "permissions or has denied the permission request.");
+ return;
+ case Qt::PermissionStatus::Granted:
+ break; // Proceed
+ }
+#endif
+ startImpl(highAccuracy);
+}
+
+void QtPositioningHelper::startImpl(bool highAccuracy){
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!m_positionInfoSource)
m_positionInfoSource = QGeoPositionInfoSource::createDefaultSource(this);
if (!m_positionInfoSource) {
@@ -134,9 +135,8 @@ void QtPositioningHelper::start(bool highAccuracy)
connect(m_positionInfoSource, &QGeoPositionInfoSource::positionUpdated, this, &QtPositioningHelper::updatePosition);
// disambiguate the error getter and the signal in QGeoPositionInfoSource.
- connect(m_positionInfoSource, static_cast<void (QGeoPositionInfoSource::*)(QGeoPositionInfoSource::Error)>(&QGeoPositionInfoSource::error)
+ connect(m_positionInfoSource, static_cast<void (QGeoPositionInfoSource::*)(QGeoPositionInfoSource::Error)>(&QGeoPositionInfoSource::errorOccurred)
, this, &QtPositioningHelper::error);
- connect(m_positionInfoSource, &QGeoPositionInfoSource::updateTimeout, this, &QtPositioningHelper::timeout);
m_positionInfoSource->startUpdates();
return;
@@ -163,80 +163,75 @@ void QtPositioningHelper::updatePosition(const QGeoPositionInfo &pos)
if (!pos.isValid())
return;
Q_ASSERT(m_positionInfoSource->error() == QGeoPositionInfoSource::NoError);
- device::mojom::Geoposition newPos;
- newPos.error_code = device::mojom::Geoposition::ErrorCode::NONE;
- newPos.error_message.clear();
+ auto newPos = device::mojom::Geoposition::New();
- newPos.timestamp = toTime(pos.timestamp());
- newPos.latitude = pos.coordinate().latitude();
- newPos.longitude = pos.coordinate().longitude();
+ newPos->timestamp = toTime(pos.timestamp());
+ newPos->latitude = pos.coordinate().latitude();
+ newPos->longitude = pos.coordinate().longitude();
const double altitude = pos.coordinate().altitude();
if (!qIsNaN(altitude))
- newPos.altitude = altitude;
+ newPos->altitude = altitude;
// Chromium's geoposition needs a valid (as in >=0.) accuracy field.
// try and get an accuracy estimate from QGeoPositionInfo.
// If we don't have any accuracy info, 100m seems a pesimistic enough default.
if (!pos.hasAttribute(QGeoPositionInfo::VerticalAccuracy) && !pos.hasAttribute(QGeoPositionInfo::HorizontalAccuracy))
- newPos.accuracy = 100;
+ newPos->accuracy = 100;
else {
const double vAccuracy = pos.hasAttribute(QGeoPositionInfo::VerticalAccuracy) ? pos.attribute(QGeoPositionInfo::VerticalAccuracy) : 0;
const double hAccuracy = pos.hasAttribute(QGeoPositionInfo::HorizontalAccuracy) ? pos.attribute(QGeoPositionInfo::HorizontalAccuracy) : 0;
- newPos.accuracy = sqrt(vAccuracy * vAccuracy + hAccuracy * hAccuracy);
+ newPos->accuracy = sqrt(vAccuracy * vAccuracy + hAccuracy * hAccuracy);
}
// And now the "nice to have" fields (-1 means invalid).
- newPos.speed = pos.hasAttribute(QGeoPositionInfo::GroundSpeed) ? pos.attribute(QGeoPositionInfo::GroundSpeed) : -1;
- newPos.heading = pos.hasAttribute(QGeoPositionInfo::Direction) ? pos.attribute(QGeoPositionInfo::Direction) : -1;
+ newPos->speed = pos.hasAttribute(QGeoPositionInfo::GroundSpeed) ? pos.attribute(QGeoPositionInfo::GroundSpeed) : -1;
+ newPos->heading = pos.hasAttribute(QGeoPositionInfo::Direction) ? pos.attribute(QGeoPositionInfo::Direction) : -1;
+ auto newResult = device::mojom::GeopositionResult::NewPosition(std::move(newPos));
if (m_locationProvider)
- postToLocationProvider(base::Bind(&LocationProviderQt::updatePosition, m_locationProviderFactory.GetWeakPtr(), newPos));
+ postToLocationProvider(base::BindOnce(&LocationProviderQt::updatePosition, m_locationProviderFactory.GetWeakPtr(), std::move(newResult)));
}
void QtPositioningHelper::error(QGeoPositionInfoSource::Error positioningError)
{
Q_ASSERT(positioningError != QGeoPositionInfoSource::NoError);
- device::mojom::Geoposition newPos;
+ auto newError = device::mojom::GeopositionError::New();
switch (positioningError) {
case QGeoPositionInfoSource::AccessError:
- newPos.error_code = device::mojom::Geoposition::ErrorCode::PERMISSION_DENIED;
+ newError->error_code = device::mojom::GeopositionErrorCode::kPermissionDenied;
+ break;
+ case QGeoPositionInfoSource::UpdateTimeoutError:
+ // content::Geoposition::ERROR_CODE_TIMEOUT is not handled properly in the renderer process, and the timeout
+ // argument used in JS never comes all the way to the browser process.
+ // Let's just treat it like any other error where the position is unavailable.
+ newError->error_code = device::mojom::GeopositionErrorCode::kPositionUnavailable;
break;
case QGeoPositionInfoSource::ClosedError:
case QGeoPositionInfoSource::UnknownSourceError: // position unavailable is as good as it gets in Geoposition
default:
- newPos.error_code = device::mojom::Geoposition::ErrorCode::POSITION_UNAVAILABLE;
+ newError->error_code = device::mojom::GeopositionErrorCode::kPositionUnavailable;
break;
}
+ auto newResult = device::mojom::GeopositionResult::NewError(std::move(newError));
if (m_locationProvider)
- postToLocationProvider(base::Bind(&LocationProviderQt::updatePosition, m_locationProviderFactory.GetWeakPtr(), newPos));
-}
-
-void QtPositioningHelper::timeout()
-{
- device::mojom::Geoposition newPos;
- // content::Geoposition::ERROR_CODE_TIMEOUT is not handled properly in the renderer process, and the timeout
- // argument used in JS never comes all the way to the browser process.
- // Let's just treat it like any other error where the position is unavailable.
- newPos.error_code = device::mojom::Geoposition::ErrorCode::POSITION_UNAVAILABLE;
- if (m_locationProvider)
- postToLocationProvider(base::Bind(&LocationProviderQt::updatePosition, m_locationProviderFactory.GetWeakPtr(), newPos));
+ postToLocationProvider(base::BindOnce(&LocationProviderQt::updatePosition, m_locationProviderFactory.GetWeakPtr(), std::move(newResult)));
}
-inline void QtPositioningHelper::postToLocationProvider(const base::Closure &task)
+inline void QtPositioningHelper::postToLocationProvider(base::OnceClosure task)
{
- static_cast<device::GeolocationProviderImpl*>(device::GeolocationProvider::GetInstance())->task_runner()->PostTask(FROM_HERE, task);
+ static_cast<device::GeolocationProviderImpl*>(device::GeolocationProvider::GetInstance())->task_runner()->PostTask(FROM_HERE, std::move(task));
}
LocationProviderQt::LocationProviderQt()
- : m_positioningHelper(0)
+ : m_positioningHelper(nullptr)
{
}
LocationProviderQt::~LocationProviderQt()
{
if (m_positioningHelper) {
- m_positioningHelper->m_locationProvider = 0;
+ m_positioningHelper->m_locationProvider = nullptr;
m_positioningHelper->m_locationProviderFactory.InvalidateWeakPtrs();
m_positioningHelper->deleteLater();
}
@@ -270,10 +265,10 @@ void LocationProviderQt::SetUpdateCallback(const LocationProviderUpdateCallback&
m_callback = callback;
}
-void LocationProviderQt::updatePosition(const device::mojom::Geoposition &position)
+void LocationProviderQt::updatePosition(device::mojom::GeopositionResultPtr position)
{
- m_lastKnownPosition = position;
- m_callback.Run(this, position);
+ m_lastKnownPosition = std::move(position);
+ m_callback.Run(this, m_lastKnownPosition.Clone());
}
} // namespace QtWebEngineCore
diff --git a/src/core/location_provider_qt.h b/src/core/location_provider_qt.h
index 8e5ad0e54..93e409d77 100644
--- a/src/core/location_provider_qt.h
+++ b/src/core/location_provider_qt.h
@@ -1,56 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef LOCATION_PROVIDER_QT_H
#define LOCATION_PROVIDER_QT_H
-#include <QtCore/qcompilerdetection.h>
+#include <QtCore/qtconfigmacros.h>
#include "services/device/public/cpp/geolocation/geoposition.h"
#include "services/device/public/cpp/geolocation/location_provider.h"
QT_FORWARD_DECLARE_CLASS(QThread)
-namespace base {
-class MessageLoop;
-}
-
namespace QtWebEngineCore {
class QtPositioningHelper;
@@ -63,16 +23,17 @@ public:
// LocationProvider
void StartProvider(bool high_accuracy) override;
void StopProvider() override;
- const device::mojom::Geoposition& GetPosition() override { return m_lastKnownPosition; }
+ const device::mojom::GeopositionResult* GetPosition() override { return m_lastKnownPosition.get(); }
void OnPermissionGranted() override;
- void SetUpdateCallback(const LocationProviderUpdateCallback& callback) override;
+ void SetUpdateCallback(const LocationProviderUpdateCallback &callback) override;
+ void FillDiagnostics(device::mojom::GeolocationDiagnostics &) override {}
private:
friend class QtPositioningHelper;
- void updatePosition(const device::mojom::Geoposition &);
+ void updatePosition(device::mojom::GeopositionResultPtr);
- device::mojom::Geoposition m_lastKnownPosition;
+ device::mojom::GeopositionResultPtr m_lastKnownPosition;
LocationProviderUpdateCallback m_callback;
QtPositioningHelper *m_positioningHelper;
};
diff --git a/src/core/login_delegate_qt.cpp b/src/core/login_delegate_qt.cpp
index 7942c8279..3f916b797 100644
--- a/src/core/login_delegate_qt.cpp
+++ b/src/core/login_delegate_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,28 +7,15 @@
#include "login_delegate_qt.h"
-#include "base/task/post_task.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
-#include "extensions/buildflags/buildflags.h"
-#include "services/network/public/cpp/features.h"
-
-#if BUILDFLAG(ENABLE_EXTENSIONS)
-#include "extensions/browser/info_map.h"
-#include "extensions/common/extension.h"
-#include "extensions/common/manifest_handlers/mime_types_handler.h"
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
#include "net/url_request/url_request.h"
+#include "services/network/public/cpp/features.h"
#include "authentication_dialog_controller.h"
#include "authentication_dialog_controller_p.h"
-#if BUILDFLAG(ENABLE_EXTENSIONS)
-#include "extensions/extension_system_qt.h"
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-#include "resource_context_qt.h"
#include "type_conversion.h"
#include "web_contents_view_qt.h"
#include "web_engine_context.h"
@@ -82,8 +33,7 @@ LoginDelegateQt::LoginDelegateQt(const net::AuthChallengeInfo &authInfo,
, m_auth_required_callback(std::move(auth_required_callback))
, m_weakFactory(this)
{
- base::PostTask(
- FROM_HERE, { content::BrowserThread::UI },
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&LoginDelegateQt::triggerDialog, m_weakFactory.GetWeakPtr()));
}
@@ -145,7 +95,7 @@ void LoginDelegateQt::sendAuthToRequester(bool success, const QString &user, con
if (success && web_contents())
std::move(m_auth_required_callback).Run(net::AuthCredentials(toString16(user), toString16(password)));
else
- std::move(m_auth_required_callback).Run(base::nullopt);
+ std::move(m_auth_required_callback).Run(absl::nullopt);
}
}
diff --git a/src/core/login_delegate_qt.h b/src/core/login_delegate_qt.h
index 7b8d869e1..b1bae0c0b 100644
--- a/src/core/login_delegate_qt.h
+++ b/src/core/login_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef LOGIN_DELEGATE_QT_H
#define LOGIN_DELEGATE_QT_H
diff --git a/src/core/media_capture_devices_dispatcher.cpp b/src/core/media_capture_devices_dispatcher.cpp
index 2293c424a..6dc45c442 100644
--- a/src/core/media_capture_devices_dispatcher.cpp
+++ b/src/core/media_capture_devices_dispatcher.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,33 +7,35 @@
#include "media_capture_devices_dispatcher.h"
-#include "javascript_dialog_manager_qt.h"
#include "type_conversion.h"
#include "web_contents_delegate_qt.h"
#include "web_contents_view_qt.h"
#include "web_engine_settings.h"
-#include "base/strings/utf_string_conversions.h"
+#include "base/strings/strcat.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/media_capture_devices.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/notification_source.h"
-#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
-#include "content/public/common/origin_util.h"
#include "media/audio/audio_device_description.h"
#include "media/audio/audio_manager_base.h"
-#include "ui/base/l10n/l10n_util.h"
+#include "services/network/public/cpp/is_potentially_trustworthy.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#if QT_CONFIG(webengine_webrtc)
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#endif
-#include <QtCore/qcoreapplication.h>
+#if defined(WEBRTC_USE_X11)
+#include <dlfcn.h>
+#include <X11/extensions/Xrandr.h>
+#include <X11/Xlib.h>
+#endif
namespace QtWebEngineCore {
@@ -87,74 +53,174 @@ const blink::MediaStreamDevice *findDeviceWithId(const blink::MediaStreamDevices
return &(*iter);
}
}
- return 0;
+ return nullptr;
+}
+
+// Based on chrome/browser/media/webrtc/desktop_capture_devices_util.cc:
+media::mojom::CaptureHandlePtr CreateCaptureHandle(content::WebContents *capturer,
+ const url::Origin &capturer_origin,
+ const content::DesktopMediaID &captured_id)
+{
+ if (capturer_origin.opaque())
+ return nullptr;
+
+ content::RenderFrameHost *const captured_rfh =
+ content::RenderFrameHost::FromID(
+ captured_id.web_contents_id.render_process_id,
+ captured_id.web_contents_id.main_render_frame_id);
+ if (!captured_rfh || !captured_rfh->IsActive())
+ return nullptr;
+
+ content::WebContents *const captured = content::WebContents::FromRenderFrameHost(captured_rfh);
+ if (!captured)
+ return nullptr;
+
+ const auto &captured_config = captured->GetCaptureHandleConfig();
+ if (!captured_config.all_origins_permitted &&
+ std::none_of(captured_config.permitted_origins.begin(),
+ captured_config.permitted_origins.end(),
+ [capturer_origin](const url::Origin& permitted_origin) {
+ return capturer_origin.IsSameOriginWith(permitted_origin);
+ }))
+ {
+ return nullptr;
+ }
+
+ // Observing CaptureHandle when either the capturing or the captured party
+ // is incognito is disallowed, except for self-capture.
+ if (capturer->GetPrimaryMainFrame() != captured->GetPrimaryMainFrame()) {
+ if (capturer->GetBrowserContext()->IsOffTheRecord() ||
+ captured->GetBrowserContext()->IsOffTheRecord()) {
+ return nullptr;
+ }
+ }
+
+ if (!captured_config.expose_origin && captured_config.capture_handle.empty())
+ return nullptr;
+
+ auto result = media::mojom::CaptureHandle::New();
+ if (captured_config.expose_origin)
+ result->origin = captured->GetPrimaryMainFrame()->GetLastCommittedOrigin();
+
+ result->capture_handle = captured_config.capture_handle;
+
+ return result;
}
// Based on chrome/browser/media/webrtc/desktop_capture_devices_util.cc:
-void getDevicesForDesktopCapture(blink::MediaStreamDevices *devices,
+media::mojom::DisplayMediaInformationPtr DesktopMediaIDToDisplayMediaInformation(content::WebContents *capturer,
+ const url::Origin &capturer_origin,
+ const content::DesktopMediaID &media_id)
+{
+ media::mojom::DisplayCaptureSurfaceType display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR;
+ bool logical_surface = true;
+ media::mojom::CursorCaptureType cursor = media::mojom::CursorCaptureType::NEVER;
+#if defined(USE_AURA)
+ const bool uses_aura = (media_id.window_id != content::DesktopMediaID::kNullId ? true : false);
+#else
+ const bool uses_aura = false;
+#endif // defined(USE_AURA)
+
+ media::mojom::CaptureHandlePtr capture_handle;
+ switch (media_id.type) {
+ case content::DesktopMediaID::TYPE_SCREEN:
+ display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR;
+ cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION
+ : media::mojom::CursorCaptureType::ALWAYS;
+ break;
+ case content::DesktopMediaID::TYPE_WINDOW:
+ display_surface = media::mojom::DisplayCaptureSurfaceType::WINDOW;
+ cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION
+ : media::mojom::CursorCaptureType::ALWAYS;
+ break;
+ case content::DesktopMediaID::TYPE_WEB_CONTENTS:
+ display_surface = media::mojom::DisplayCaptureSurfaceType::BROWSER;
+ cursor = media::mojom::CursorCaptureType::MOTION;
+ capture_handle = CreateCaptureHandle(capturer, capturer_origin, media_id);
+ break;
+ case content::DesktopMediaID::TYPE_NONE:
+ break;
+ }
+
+ return media::mojom::DisplayMediaInformation::New(display_surface, logical_surface, cursor, std::move(capture_handle));
+}
+
+
+// Based on chrome/browser/media/webrtc/desktop_capture_devices_util.cc:
+std::string DeviceNamePrefix(content::WebContents *web_contents,
+ blink::mojom::MediaStreamType requested_stream_type,
+ const content::DesktopMediaID &media_id)
+{
+ if (!web_contents || requested_stream_type != blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE_THIS_TAB) {
+ return std::string();
+ }
+
+ // Note that all of these must still be checked, as the explicit-selection
+ // dialog for DISPLAY_VIDEO_CAPTURE_THIS_TAB could still return something
+ // other than the current tab - be it a screen, window, or another tab.
+ if (media_id.type == content::DesktopMediaID::TYPE_WEB_CONTENTS &&
+ web_contents->GetPrimaryMainFrame()->GetProcess()->GetID() ==
+ media_id.web_contents_id.render_process_id &&
+ web_contents->GetPrimaryMainFrame()->GetRoutingID() ==
+ media_id.web_contents_id.main_render_frame_id) {
+ return "current-";
+ }
+
+ return std::string();
+}
+
+// Based on chrome/browser/media/webrtc/desktop_capture_devices_util.cc:
+std::string DeviceName(content::WebContents *web_contents,
+ blink::mojom::MediaStreamType requested_stream_type,
+ const content::DesktopMediaID &media_id)
+{
+ const std::string prefix =
+ DeviceNamePrefix(web_contents, requested_stream_type, media_id);
+ if (media_id.type == content::DesktopMediaID::TYPE_WEB_CONTENTS) {
+ return base::StrCat({prefix, content::kWebContentsCaptureScheme,
+ base::UnguessableToken::Create().ToString()});
+ } else {
+ // TODO(crbug.com/1252682): MediaStreamTrack.label leaks internal state for
+ // screen/window
+ return base::StrCat({prefix, media_id.ToString()});
+ }
+}
+
+// Based on chrome/browser/media/webrtc/desktop_capture_devices_util.cc:
+void getDevicesForDesktopCapture(const content::MediaStreamRequest &request,
+ content::WebContents *web_contents,
content::DesktopMediaID mediaId,
bool captureAudio,
- MediaStreamType videoType,
- MediaStreamType audioType)
+ bool disableLocalEcho,
+ blink::mojom::StreamDevices &out_devices)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Add selected desktop source to the list.
- devices->push_back(blink::MediaStreamDevice(videoType, mediaId.ToString(), mediaId.ToString()));
+ blink::MediaStreamDevice device(request.video_type, mediaId.ToString(),
+ DeviceName(web_contents, request.video_type, mediaId));
+ device.display_media_info = DesktopMediaIDToDisplayMediaInformation(
+ web_contents, url::Origin::Create(request.security_origin), mediaId);
+ out_devices.video_device = device;
+
if (captureAudio) {
+ DCHECK_NE(request.audio_type, blink::mojom::MediaStreamType::NO_SERVICE);
+
if (mediaId.type == content::DesktopMediaID::TYPE_WEB_CONTENTS) {
- devices->push_back(
- blink::MediaStreamDevice(audioType, mediaId.ToString(), "Tab audio"));
+ content::WebContentsMediaCaptureId web_id = mediaId.web_contents_id;
+ web_id.disable_local_echo = disableLocalEcho;
+ out_devices.audio_device = blink::MediaStreamDevice(request.audio_type, web_id.ToString(), "Tab audio");
} else {
// Use the special loopback device ID for system audio capture.
- devices->push_back(blink::MediaStreamDevice(
- audioType,
- media::AudioDeviceDescription::kLoopbackInputDeviceId,
- "System Audio"));
+ out_devices.audio_device = blink::MediaStreamDevice(
+ request.audio_type, (disableLocalEcho
+ ? media::AudioDeviceDescription::kLoopbackWithMuteDeviceId
+ : media::AudioDeviceDescription::kLoopbackInputDeviceId),
+ "System Audio");
}
}
}
-content::DesktopMediaID getDefaultScreenId()
-{
- // While this function is executing another thread may also want to create a
- // DesktopCapturer [1]. Unfortunately, creating a DesktopCapturer is not
- // thread safe on X11 due to the use of webrtc::XErrorTrap. It's safe to
- // disable this code on X11 since we don't actually need to create a
- // DesktopCapturer to get the screen id anyway
- // (ScreenCapturerLinux::GetSourceList always returns 0 as the id).
- //
- // [1]: webrtc::InProcessVideoCaptureDeviceLauncher::DoStartDesktopCaptureOnDeviceThread
-
-#if QT_CONFIG(webengine_webrtc) && !defined(WEBRTC_USE_X11)
- // Source id patterns are different across platforms.
- // On Linux, the hardcoded value "0" is used.
- // On Windows, the screens are enumerated consecutively in increasing order from 0.
- // On macOS the source ids are randomish numbers assigned by the OS.
-
- // In order to provide a correct screen id, we query for the available screen ids, and
- // select the first one as the main display id.
- // The code is based on the file
- // src/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc.
- webrtc::DesktopCaptureOptions options =
- webrtc::DesktopCaptureOptions::CreateDefault();
- options.set_disable_effects(false);
- std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
- webrtc::DesktopCapturer::CreateScreenCapturer(options));
-
- if (screen_capturer) {
- webrtc::DesktopCapturer::SourceList screens;
- if (screen_capturer->GetSourceList(&screens)) {
- if (screens.size() > 0) {
- return content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, screens[0].id);
- }
- }
- }
-#endif
-
- return content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0);
-}
-
WebContentsAdapterClient::MediaRequestFlags mediaRequestFlagsForRequest(const content::MediaStreamRequest &request)
{
if (request.audio_type == MediaStreamType::DEVICE_AUDIO_CAPTURE &&
@@ -173,8 +239,17 @@ WebContentsAdapterClient::MediaRequestFlags mediaRequestFlagsForRequest(const co
request.video_type == MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE)
return {WebContentsAdapterClient::MediaDesktopAudioCapture, WebContentsAdapterClient::MediaDesktopVideoCapture};
- if (request.video_type == MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE ||
+ if (request.audio_type == MediaStreamType::DISPLAY_AUDIO_CAPTURE &&
request.video_type == MediaStreamType::DISPLAY_VIDEO_CAPTURE)
+ return {WebContentsAdapterClient::MediaDesktopAudioCapture, WebContentsAdapterClient::MediaDesktopVideoCapture};
+
+ if (request.audio_type == MediaStreamType::DISPLAY_AUDIO_CAPTURE &&
+ request.video_type == MediaStreamType::DISPLAY_VIDEO_CAPTURE_THIS_TAB)
+ return {WebContentsAdapterClient::MediaDesktopAudioCapture, WebContentsAdapterClient::MediaDesktopVideoCapture};
+
+ if (request.video_type == MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE ||
+ request.video_type == MediaStreamType::DISPLAY_VIDEO_CAPTURE ||
+ request.video_type == MediaStreamType::DISPLAY_VIDEO_CAPTURE_THIS_TAB)
return {WebContentsAdapterClient::MediaDesktopVideoCapture};
return {};
@@ -184,42 +259,57 @@ WebContentsAdapterClient::MediaRequestFlags mediaRequestFlagsForRequest(const co
class MediaStreamUIQt : public content::MediaStreamUI
{
public:
- MediaStreamUIQt(content::WebContents *webContents, const blink::MediaStreamDevices &devices)
+ MediaStreamUIQt(content::WebContents *webContents, const blink::mojom::StreamDevices &devices)
: m_delegate(static_cast<WebContentsDelegateQt *>(webContents->GetDelegate())->AsWeakPtr())
, m_devices(devices)
{
- DCHECK(!m_devices.empty());
+ DCHECK(m_devices.audio_device.has_value() ||
+ m_devices.video_device.has_value());
}
~MediaStreamUIQt() override
{
if (m_started && m_delegate)
m_delegate->removeDevices(m_devices);
+ m_onStop.Reset();
}
private:
- gfx::NativeViewId OnStarted(base::OnceClosure, SourceCallback) override
+ gfx::NativeViewId OnStarted(base::RepeatingClosure stop, SourceCallback source,
+ const std::string& label,
+ std::vector<content::DesktopMediaID> screen_capture_ids,
+ StateChangeCallback state_change) override
{
- DCHECK(!m_started);
+ if (m_started) {
+ // Ignore possibly-compromised renderers that might call
+ // MediaStreamDispatcherHost::OnStreamStarted() more than once.
+ // See: https://crbug.com/1155426
+ return 0;
+ }
m_started = true;
+ m_onStop = std::move(stop);
if (m_delegate)
m_delegate->addDevices(m_devices);
return 0;
}
-
+ void OnDeviceStopped(const std::string &label, const content::DesktopMediaID &media_id) override
+ {
+ Q_UNUSED(label);
+ Q_UNUSED(media_id);
+ }
+ void OnDeviceStoppedForSourceChange(const std::string&, const content::DesktopMediaID&, const content::DesktopMediaID&) override
+ {}
base::WeakPtr<WebContentsDelegateQt> m_delegate;
- const blink::MediaStreamDevices m_devices;
+ const blink::mojom::StreamDevices m_devices;
bool m_started = false;
-
- DISALLOW_COPY_AND_ASSIGN(MediaStreamUIQt);
+ base::RepeatingClosure m_onStop; // currently unused
};
-
} // namespace
-MediaCaptureDevicesDispatcher::PendingAccessRequest::PendingAccessRequest(const content::MediaStreamRequest &request,
- const RepeatingMediaResponseCallback &callback)
- : request(request)
- , callback(callback)
+MediaCaptureDevicesDispatcher::PendingAccessRequest::PendingAccessRequest(
+ const content::MediaStreamRequest &request, content::MediaResponseCallback callback,
+ content::DesktopMediaID id)
+ : request(request), callback(std::move(callback)), mediaId(id)
{
}
@@ -231,13 +321,13 @@ void MediaCaptureDevicesDispatcher::handleMediaAccessPermissionResponse(content:
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- blink::MediaStreamDevices devices;
+ blink::mojom::StreamDevicesSet deviceSet;
auto it = m_pendingRequests.find(webContents);
if (it == m_pendingRequests.end() || it->second.empty())
return;
RequestsQueue &queue(it->second);
- content::MediaStreamRequest &request = queue.front().request;
+ content::MediaStreamRequest &request = queue.front()->request;
const QUrl requestSecurityOrigin(toQt(request.security_origin));
bool securityOriginsMatch = (requestSecurityOrigin.host() == securityOrigin.host()
@@ -255,42 +345,48 @@ void MediaCaptureDevicesDispatcher::handleMediaAccessPermissionResponse(content:
bool desktopVideoRequested = finalFlags.testFlag(WebContentsAdapterClient::MediaDesktopVideoCapture);
if (securityOriginsMatch) {
+ content::DesktopMediaID &id = queue.front()->mediaId;
+
if (microphoneRequested || webcamRequested) {
switch (request.request_type) {
case blink::MEDIA_OPEN_DEVICE_PEPPER_ONLY:
- getDefaultDevices("", "", microphoneRequested, webcamRequested, &devices);
+ getDefaultDevices("", "", microphoneRequested, webcamRequested, deviceSet);
break;
case blink::MEDIA_DEVICE_ACCESS:
case blink::MEDIA_DEVICE_UPDATE:
case blink::MEDIA_GENERATE_STREAM:
+ case blink::MEDIA_GET_OPEN_DEVICE:
getDefaultDevices(request.requested_audio_device_id, request.requested_video_device_id,
- microphoneRequested, webcamRequested, &devices);
+ microphoneRequested, webcamRequested, deviceSet);
break;
}
- } else if (desktopVideoRequested) {
- getDevicesForDesktopCapture(&devices, getDefaultScreenId(), desktopAudioRequested,
- request.video_type, request.audio_type);
+ } else if (desktopVideoRequested && !id.is_null()) {
+ deviceSet.stream_devices.emplace_back(blink::mojom::StreamDevices::New());
+ bool captureAudio = desktopAudioRequested && m_loopbackAudioSupported;
+ blink::mojom::StreamDevices &stream_devices = *deviceSet.stream_devices[0];
+ getDevicesForDesktopCapture(request, webContents, id, captureAudio,
+ request.disable_local_echo, stream_devices);
}
}
- content::MediaResponseCallback callback = std::move(queue.front().callback);
+ content::MediaResponseCallback callback = std::move(queue.front()->callback);
queue.pop_front();
if (!queue.empty()) {
// Post a task to process next queued request. It has to be done
// asynchronously to make sure that calling infobar is not destroyed until
// after this function returns.
- base::PostTask(FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&MediaCaptureDevicesDispatcher::ProcessQueuedAccessRequest,
base::Unretained(this), webContents));
}
- if (devices.empty())
- std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE,
+ if (deviceSet.stream_devices.empty())
+ std::move(callback).Run(deviceSet, MediaStreamRequestResult::INVALID_STATE,
std::unique_ptr<content::MediaStreamUI>());
else
- std::move(callback).Run(devices, MediaStreamRequestResult::OK,
- std::make_unique<MediaStreamUIQt>(webContents, devices));
+ std::move(callback).Run(deviceSet, MediaStreamRequestResult::OK,
+ std::make_unique<MediaStreamUIQt>(webContents, *deviceSet.stream_devices[0]));
}
MediaCaptureDevicesDispatcher *MediaCaptureDevicesDispatcher::GetInstance()
@@ -299,45 +395,47 @@ MediaCaptureDevicesDispatcher *MediaCaptureDevicesDispatcher::GetInstance()
}
MediaCaptureDevicesDispatcher::MediaCaptureDevicesDispatcher()
+ : m_webContentsCollection(this)
{
- // MediaCaptureDevicesDispatcher is a singleton. It should be created on
- // UI thread. Otherwise, it will not receive
- // content::NOTIFICATION_WEB_CONTENTS_DESTROYED, and that will result in
- // possible use after free.
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- m_notificationsRegistrar.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
- content::NotificationService::AllSources());
+#if defined(Q_OS_WIN)
+ // Currently loopback audio capture is supported only on Windows.
+ m_loopbackAudioSupported = true;
+#endif
}
MediaCaptureDevicesDispatcher::~MediaCaptureDevicesDispatcher()
{
}
-void MediaCaptureDevicesDispatcher::Observe(int type, const content::NotificationSource &source, const content::NotificationDetails &details)
+void MediaCaptureDevicesDispatcher::WebContentsDestroyed(content::WebContents *webContents)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) {
- content::WebContents *webContents = content::Source<content::WebContents>(source).ptr();
- m_pendingRequests.erase(webContents);
- }
+ m_pendingRequests.erase(webContents);
}
-void MediaCaptureDevicesDispatcher::processMediaAccessRequest(WebContentsAdapterClient *adapterClient, content::WebContents *webContents, const content::MediaStreamRequest &request, content::MediaResponseCallback callback)
+void MediaCaptureDevicesDispatcher::processMediaAccessRequest(
+ content::WebContents *webContents, const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback, content::DesktopMediaID id)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ // Ensure we are observing the deletion of |webContents|.
+ m_webContentsCollection.StartObserving(webContents);
WebContentsAdapterClient::MediaRequestFlags flags = mediaRequestFlagsForRequest(request);
if (!flags) {
- std::move(callback).Run(blink::MediaStreamDevices(), MediaStreamRequestResult::NOT_SUPPORTED, std::unique_ptr<content::MediaStreamUI>());
+ std::move(callback).Run(blink::mojom::StreamDevicesSet(), MediaStreamRequestResult::NOT_SUPPORTED, std::unique_ptr<content::MediaStreamUI>());
return;
}
+ WebContentsDelegateQt *delegate = static_cast<WebContentsDelegateQt *>(webContents->GetDelegate());
+ WebContentsAdapterClient *adapterClient = delegate->adapterClient();
+
if (flags.testFlag(WebContentsAdapterClient::MediaDesktopVideoCapture)) {
- const bool screenCaptureEnabled =
- adapterClient->webEngineSettings()->testAttribute(WebEngineSettings::ScreenCaptureEnabled);
- const bool originIsSecure = content::IsOriginSecure(request.security_origin);
- if (!screenCaptureEnabled || !originIsSecure) {
- std::move(callback).Run(blink::MediaStreamDevices(), MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>());
+ const bool screenCaptureEnabled = adapterClient->webEngineSettings()->testAttribute(
+ QWebEngineSettings::ScreenCaptureEnabled);
+ const bool originIsSecure = network::IsUrlPotentiallyTrustworthy(request.security_origin);
+ if (!screenCaptureEnabled || !originIsSecure || (id.is_null() && request.requested_video_device_id.empty())) {
+ std::move(callback).Run(blink::mojom::StreamDevicesSet(), MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>());
return;
}
@@ -348,57 +446,60 @@ void MediaCaptureDevicesDispatcher::processMediaAccessRequest(WebContentsAdapter
}
}
- enqueueMediaAccessRequest(webContents, request, std::move(callback));
+ enqueueMediaAccessRequest(webContents, request, std::move(callback), id);
// We might not require this approval for pepper requests.
adapterClient->runMediaAccessPermissionRequest(toQt(request.security_origin), flags);
}
void MediaCaptureDevicesDispatcher::processDesktopCaptureAccessRequest(content::WebContents *webContents, const content::MediaStreamRequest &request, content::MediaResponseCallback callback)
{
- blink::MediaStreamDevices devices;
+ blink::mojom::StreamDevicesSet deviceSet;
content::WebContents *const web_contents_for_stream = content::WebContents::FromRenderFrameHost(
content::RenderFrameHost::FromID(request.render_process_id, request.render_frame_id));
- content::RenderFrameHost *const main_frame = web_contents_for_stream ? web_contents_for_stream->GetMainFrame() : NULL;
+ content::RenderFrameHost *const main_frame = web_contents_for_stream ? web_contents_for_stream->GetPrimaryMainFrame() : nullptr;
content::DesktopMediaID mediaId;
if (main_frame) {
- // The extension name that the stream is registered with.
- std::string originalExtensionName;
// Resolve DesktopMediaID for the specified device id.
mediaId = content::DesktopStreamsRegistry::GetInstance()->RequestMediaForStreamId(
request.requested_video_device_id, main_frame->GetProcess()->GetID(),
main_frame->GetRoutingID(), url::Origin::Create(request.security_origin),
- &originalExtensionName, content::kRegistryStreamTypeDesktop);
+ content::kRegistryStreamTypeDesktop);
}
// Received invalid device id.
if (mediaId.type == content::DesktopMediaID::TYPE_NONE) {
- std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>());
+ std::move(callback).Run(deviceSet, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>());
return;
}
// Audio is only supported for screen capture streams.
- bool capture_audio = (mediaId.type == content::DesktopMediaID::TYPE_SCREEN && request.audio_type == MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE);
+ bool audioRequested = (request.audio_type == MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE ||
+ request.audio_type == MediaStreamType::DISPLAY_AUDIO_CAPTURE);
+ bool audioSupported = (mediaId.type == content::DesktopMediaID::TYPE_SCREEN && m_loopbackAudioSupported);
+ bool captureAudio = (audioRequested && audioSupported);
- getDevicesForDesktopCapture(&devices, mediaId, capture_audio, request.video_type, request.audio_type);
+ deviceSet.stream_devices.emplace_back(blink::mojom::StreamDevices::New());
+ blink::mojom::StreamDevices &stream_devices = *deviceSet.stream_devices[0];
+ getDevicesForDesktopCapture(request, webContents, mediaId, captureAudio, request.disable_local_echo, stream_devices);
- if (devices.empty())
- std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE,
+ if (deviceSet.stream_devices.empty())
+ std::move(callback).Run(deviceSet, MediaStreamRequestResult::INVALID_STATE,
std::unique_ptr<content::MediaStreamUI>());
else
- std::move(callback).Run(devices, MediaStreamRequestResult::OK,
- std::make_unique<MediaStreamUIQt>(webContents, devices));
+ std::move(callback).Run(deviceSet, MediaStreamRequestResult::OK,
+ std::make_unique<MediaStreamUIQt>(webContents, *deviceSet.stream_devices[0]));
}
-void MediaCaptureDevicesDispatcher::enqueueMediaAccessRequest(content::WebContents *webContents,
- const content::MediaStreamRequest &request,
- content::MediaResponseCallback callback)
+void MediaCaptureDevicesDispatcher::enqueueMediaAccessRequest(
+ content::WebContents *webContents, const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback, content::DesktopMediaID id)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RequestsQueue &queue = m_pendingRequests[webContents];
- queue.push_back(PendingAccessRequest(request, base::AdaptCallbackForRepeating(std::move(callback))));
+ queue.push_back(std::make_unique<PendingAccessRequest>(request, std::move(callback), id));
}
void MediaCaptureDevicesDispatcher::ProcessQueuedAccessRequest(content::WebContents *webContents)
@@ -410,25 +511,27 @@ void MediaCaptureDevicesDispatcher::ProcessQueuedAccessRequest(content::WebConte
return;
RequestsQueue &queue(it->second);
- content::MediaStreamRequest &request = queue.front().request;
+ content::MediaStreamRequest &request = queue.front()->request;
WebContentsAdapterClient *adapterClient = WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(webContents)->GetView())->client();
adapterClient->runMediaAccessPermissionRequest(toQt(request.security_origin), mediaRequestFlagsForRequest(request));
}
void MediaCaptureDevicesDispatcher::getDefaultDevices(const std::string &audioDeviceId, const std::string &videoDeviceId,
- bool audio, bool video, blink::MediaStreamDevices *devices)
+ bool audio, bool video, blink::mojom::StreamDevicesSet &devicesSet)
{
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(audio || video);
+ devicesSet.stream_devices.emplace_back(blink::mojom::StreamDevices::New());
+ blink::mojom::StreamDevices& devices = *devicesSet.stream_devices[0];
if (audio) {
const blink::MediaStreamDevices &audioDevices = content::MediaCaptureDevices::GetInstance()->GetAudioCaptureDevices();
const blink::MediaStreamDevice *device = findDeviceWithId(audioDevices, audioDeviceId);
if (!device && !audioDevices.empty())
device = &audioDevices.front();
if (device)
- devices->push_back(*device);
+ devices.audio_device = *device;
}
if (video) {
@@ -437,14 +540,14 @@ void MediaCaptureDevicesDispatcher::getDefaultDevices(const std::string &audioDe
if (!device && !videoDevices.empty())
device = &videoDevices.front();
if (device)
- devices->push_back(*device);
+ devices.video_device = *device;
}
}
void MediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(int render_process_id, int render_frame_id, int page_request_id, const GURL &security_origin, blink::mojom::MediaStreamType stream_type, content::MediaRequestState state)
{
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- base::PostTask(FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&MediaCaptureDevicesDispatcher::updateMediaRequestStateOnUIThread,
base::Unretained(this), render_process_id, render_frame_id,
page_request_id, security_origin, stream_type, state));
@@ -464,9 +567,9 @@ void MediaCaptureDevicesDispatcher::updateMediaRequestStateOnUIThread(int render
for (auto &pair : m_pendingRequests) {
RequestsQueue &queue = pair.second;
for (auto it = queue.begin(); it != queue.end(); ++it) {
- if (it->request.render_process_id == render_process_id
- && it->request.render_frame_id == render_frame_id
- && it->request.page_request_id == page_request_id) {
+ if ((*it)->request.render_process_id == render_process_id
+ && (*it)->request.render_frame_id == render_frame_id
+ && (*it)->request.page_request_id == page_request_id) {
queue.erase(it);
return;
}
diff --git a/src/core/media_capture_devices_dispatcher.h b/src/core/media_capture_devices_dispatcher.h
index 6a67a53e9..2b6bb98d8 100644
--- a/src/core/media_capture_devices_dispatcher.h
+++ b/src/core/media_capture_devices_dispatcher.h
@@ -1,78 +1,37 @@
-/****************************************************************************
-**
-** Copyright (c) 2012 The Chromium Authors. All rights reserved.
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef MEDIA_CAPTURE_DEVICES_DISPATCHER_H
#define MEDIA_CAPTURE_DEVICES_DISPATCHER_H
-#include <deque>
-#include <list>
-#include <map>
-
#include "web_contents_adapter_client.h"
-#include "base/callback.h"
#include "base/containers/circular_deque.h"
+#include "base/containers/flat_map.h"
#include "base/memory/singleton.h"
-#include "base/observer_list.h"
+#include "chrome/browser/tab_contents/web_contents_collection.h"
#include "content/public/browser/media_observer.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-#include "content/public/browser/web_contents_delegate.h"
+#include "content/public/browser/media_stream_request.h"
namespace QtWebEngineCore {
// This singleton is used to receive updates about media events from the content
// layer. Based on Chrome's implementation.
class MediaCaptureDevicesDispatcher : public content::MediaObserver,
- public content::NotificationObserver
+ public WebContentsCollection::Observer
{
public:
static MediaCaptureDevicesDispatcher *GetInstance();
- void processMediaAccessRequest(WebContentsAdapterClient *, content::WebContents *, const content::MediaStreamRequest &, content::MediaResponseCallback);
+ void processMediaAccessRequest(content::WebContents *, const content::MediaStreamRequest &,
+ content::MediaResponseCallback, content::DesktopMediaID);
// Called back from our WebContentsAdapter to grant the requested permission.
void handleMediaAccessPermissionResponse(content::WebContents *, const QUrl &securityOrigin, WebContentsAdapterClient::MediaRequestFlags);
private:
- void getDefaultDevices(const std::string &audioDeviceId, const std::string &videoDeviceId, bool audio, bool video, blink::MediaStreamDevices *);
+ void getDefaultDevices(const std::string &audioDeviceId, const std::string &videoDeviceId, bool audio, bool video, blink::mojom::StreamDevicesSet &devices);
// Overridden from content::MediaObserver:
void OnAudioCaptureDevicesChanged() override {}
@@ -93,30 +52,29 @@ private:
friend struct base::DefaultSingletonTraits<MediaCaptureDevicesDispatcher>;
- typedef base::RepeatingCallback<void(const blink::MediaStreamDevices &devices,
- blink::mojom::MediaStreamRequestResult result,
- std::unique_ptr<content::MediaStreamUI> ui)>
- RepeatingMediaResponseCallback;
-
struct PendingAccessRequest {
- PendingAccessRequest(const content::MediaStreamRequest &request, const RepeatingMediaResponseCallback &callback);
+ PendingAccessRequest(const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback, content::DesktopMediaID id);
~PendingAccessRequest();
content::MediaStreamRequest request;
- RepeatingMediaResponseCallback callback;
+ content::MediaResponseCallback callback;
+ content::DesktopMediaID mediaId;
};
- typedef base::circular_deque<PendingAccessRequest> RequestsQueue;
- typedef std::map<content::WebContents *, RequestsQueue> RequestsQueues;
+ typedef base::circular_deque<std::unique_ptr<PendingAccessRequest>> RequestsQueue;
+ typedef base::flat_map<content::WebContents *, RequestsQueue> RequestsQueues;
MediaCaptureDevicesDispatcher();
virtual ~MediaCaptureDevicesDispatcher();
- // content::NotificationObserver implementation.
- void Observe(int type, const content::NotificationSource &source, const content::NotificationDetails &details) override;
+ // WebContentsCollection::Observer:
+ void WebContentsDestroyed(content::WebContents *webContents) override;
// Helpers for ProcessMediaAccessRequest().
+ void handleRequest(content::WebContents *, const content::MediaStreamRequest &, content::MediaResponseCallback);
void processDesktopCaptureAccessRequest(content::WebContents *, const content::MediaStreamRequest &, content::MediaResponseCallback);
- void enqueueMediaAccessRequest(content::WebContents *, const content::MediaStreamRequest &, content::MediaResponseCallback);
+ void enqueueMediaAccessRequest(content::WebContents *, const content::MediaStreamRequest &,
+ content::MediaResponseCallback, content::DesktopMediaID);
void ProcessQueuedAccessRequest(content::WebContents *);
// Called by the MediaObserver() functions, executed on UI thread.
@@ -125,9 +83,9 @@ private:
RequestsQueues m_pendingRequests;
- content::NotificationRegistrar m_notificationsRegistrar;
+ WebContentsCollection m_webContentsCollection;
- DISALLOW_COPY_AND_ASSIGN(MediaCaptureDevicesDispatcher);
+ bool m_loopbackAudioSupported = false;
};
} // namespace QtWebEngineCore
diff --git a/src/core/native_web_keyboard_event_qt.cpp b/src/core/native_web_keyboard_event_qt.cpp
index b2e857aaf..9a5576fbb 100644
--- a/src/core/native_web_keyboard_event_qt.cpp
+++ b/src/core/native_web_keyboard_event_qt.cpp
@@ -1,101 +1,88 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
-#include "content/public/browser/native_web_keyboard_event.h"
-#include <QKeyEvent>
+#include <QtCore/qglobal.h>
-namespace {
+#if !defined(Q_OS_MACOS)
+#include "native_web_keyboard_event_qt.h"
+
+#include <QtGui/QKeyEvent>
+
+namespace QtWebEngineCore {
+gfx::NativeEvent ToNativeEvent(QKeyEvent *keyEvent)
+{
+ return reinterpret_cast<gfx::NativeEvent>(keyEvent);
+}
+
+QKeyEvent *ToKeyEvent(gfx::NativeEvent nativeEvent)
+{
+ return reinterpret_cast<QKeyEvent *>(nativeEvent);
+}
+} // namespace QtWebEngineCore
+namespace {
// We need to copy |os_event| in NativeWebKeyboardEvent because it is
// queued in RenderWidgetHost and may be passed and used
// RenderViewHostDelegate::HandledKeybardEvent after the original aura
// event is destroyed.
-gfx::NativeEvent CopyEvent(gfx::NativeEvent event)
+gfx::NativeEvent CopyEvent(gfx::NativeEvent nativeEvent)
{
- return event ? reinterpret_cast<gfx::NativeEvent>(new QKeyEvent(*reinterpret_cast<QKeyEvent*>(event))) : 0;
+ if (!nativeEvent)
+ return nullptr;
+
+ QKeyEvent *keyEvent = QtWebEngineCore::ToKeyEvent(nativeEvent);
+ return QtWebEngineCore::ToNativeEvent(keyEvent->clone());
}
-void DestroyEvent(gfx::NativeEvent event)
+void DestroyEvent(gfx::NativeEvent nativeEvent)
{
- delete reinterpret_cast<QKeyEvent*>(event);
+ delete QtWebEngineCore::ToKeyEvent(nativeEvent);
}
+} // namespace
-} // namespace
-
-using blink::WebKeyboardEvent;
namespace content {
-NativeWebKeyboardEvent::NativeWebKeyboardEvent(blink::WebKeyboardEvent const&, gfx::NativeView)
- : os_event(0)
- , skip_in_browser(false)
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(const blink::WebKeyboardEvent &web_event, gfx::NativeView)
+ : blink::WebKeyboardEvent(web_event)
+ , os_event(nullptr)
+ , skip_if_unhandled(false)
{
}
-NativeWebKeyboardEvent::NativeWebKeyboardEvent(blink::WebInputEvent::Type, int, base::TimeTicks)
- : os_event(0)
- , skip_in_browser(false)
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(blink::WebInputEvent::Type type, int modifiers,
+ base::TimeTicks timestamp)
+ : blink::WebKeyboardEvent(type, modifiers, timestamp)
+ , os_event(nullptr)
+ , skip_if_unhandled(false)
{
}
NativeWebKeyboardEvent::NativeWebKeyboardEvent(gfx::NativeEvent native_event)
- : os_event(CopyEvent(native_event)),
- skip_in_browser(false)
+ : os_event(CopyEvent(native_event))
+ , skip_if_unhandled(false)
{
}
NativeWebKeyboardEvent::NativeWebKeyboardEvent(const NativeWebKeyboardEvent& other)
- : WebKeyboardEvent(other),
- os_event(CopyEvent(other.os_event)),
- skip_in_browser(other.skip_in_browser)
+ : blink::WebKeyboardEvent(other)
+ , os_event(CopyEvent(other.os_event))
+ , skip_if_unhandled(other.skip_if_unhandled)
{
}
-NativeWebKeyboardEvent& NativeWebKeyboardEvent::operator=(const NativeWebKeyboardEvent& other) {
- WebKeyboardEvent::operator=(other);
+NativeWebKeyboardEvent &NativeWebKeyboardEvent::operator=(const NativeWebKeyboardEvent &other)
+{
+ if (this == &other)
+ return *this;
+ blink::WebKeyboardEvent::operator=(other);
DestroyEvent(os_event);
os_event = CopyEvent(other.os_event);
- skip_in_browser = other.skip_in_browser;
+ skip_if_unhandled = other.skip_if_unhandled;
return *this;
}
@@ -104,3 +91,4 @@ NativeWebKeyboardEvent::~NativeWebKeyboardEvent() {
}
} // namespace content
+#endif // !defined(Q_OS_MACOS)
diff --git a/src/core/native_web_keyboard_event_qt.h b/src/core/native_web_keyboard_event_qt.h
new file mode 100644
index 000000000..13179d07a
--- /dev/null
+++ b/src/core/native_web_keyboard_event_qt.h
@@ -0,0 +1,20 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef NATIVE_WEB_KEYBOARD_EVENT_QT_H
+#define NATIVE_WEB_KEYBOARD_EVENT_QT_H
+
+#include <QtCore/qglobal.h>
+
+#include "content/public/common/input/native_web_keyboard_event.h"
+
+QT_FORWARD_DECLARE_CLASS(QKeyEvent)
+
+namespace QtWebEngineCore {
+
+gfx::NativeEvent ToNativeEvent(QKeyEvent *keyEvent);
+QKeyEvent *ToKeyEvent(gfx::NativeEvent event);
+
+} // namespace QtWebEngineCore
+
+#endif // NATIVE_WEB_KEYBOARD_EVENT_QT_H
diff --git a/src/core/native_web_keyboard_event_qt_mac.mm b/src/core/native_web_keyboard_event_qt_mac.mm
new file mode 100644
index 000000000..0f5b12db4
--- /dev/null
+++ b/src/core/native_web_keyboard_event_qt_mac.mm
@@ -0,0 +1,155 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// Copyright 2011 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE.Chromium file.
+
+// This is a workaround to be able to include Qt headers without
+// "redefinition of 'NSString' as different kind of symbol" errors.
+// TODO: Remove this when namespace ambiguity issues are fixed properly,
+// see get_forward_declaration_macro() in cmake/Functions.cmake
+#undef Q_FORWARD_DECLARE_OBJC_CLASS
+
+#include "native_web_keyboard_event_qt.h"
+
+#include <AppKit/AppKit.h>
+
+#include "base/apple/owned_objc.h"
+
+#include <QtGui/QKeyEvent>
+#include <QtGui/private/qapplekeymapper_p.h>
+
+namespace QtWebEngineCore {
+
+base::apple::OwnedNSEvent ToNativeEvent(QKeyEvent *keyEvent)
+{
+ NSEventType type;
+ switch (keyEvent->type()) {
+ case QEvent::KeyPress:
+ type = NSEventTypeKeyDown;
+ break;
+ case QEvent::KeyRelease:
+ type = NSEventTypeKeyUp;
+ break;
+ default:
+ Q_UNREACHABLE();
+ return base::apple::OwnedNSEvent();
+ }
+
+ NSString *text = keyEvent->text().toNSString();
+ if (text.length == 0) {
+ Qt::Key key = static_cast<Qt::Key>(keyEvent->key());
+ QChar cocoaKey = QAppleKeyMapper::toCocoaKey(key);
+ text = QStringView(&cocoaKey, 1).toNSString();
+ }
+
+ return base::apple::OwnedNSEvent([NSEvent
+ keyEventWithType:type
+ location:NSZeroPoint
+ modifierFlags:QAppleKeyMapper::toCocoaModifiers(keyEvent->modifiers())
+ timestamp:keyEvent->timestamp() / 1000
+ windowNumber:0
+ context:nil
+ characters:text
+ charactersIgnoringModifiers:text
+ isARepeat:keyEvent->isAutoRepeat()
+ keyCode:keyEvent->nativeVirtualKey()
+ ]);
+}
+
+// Based on qtbase/src/plugins/platforms/cocoa/qnsview_keys.mm (KeyEvent::KeyEvent())
+QKeyEvent *ToKeyEvent(base::apple::OwnedNSEvent event)
+{
+ NSEvent *nsevent = event.Get();
+
+ QEvent::Type type = QEvent::None;
+ switch (nsevent.type) {
+ case NSEventTypeKeyDown:
+ type = QEvent::KeyPress;
+ break;
+ case NSEventTypeKeyUp:
+ type = QEvent::KeyRelease;
+ break;
+ default:
+ Q_UNREACHABLE();
+ return nullptr;
+ }
+
+ // Scan codes are hardware dependent codes for each key. There is no way to get these
+ // from Carbon or Cocoa, so leave it 0, as documented in QKeyEvent::nativeScanCode().
+ quint32 nativeScanCode = 0;
+ quint32 nativeVirtualKey = nsevent.keyCode;
+
+ NSEventModifierFlags nativeModifiers = nsevent.modifierFlags;
+ Qt::KeyboardModifiers modifiers = QAppleKeyMapper::fromCocoaModifiers(nativeModifiers);
+
+ NSString *charactersIgnoringModifiers = nsevent.charactersIgnoringModifiers;
+ NSString *characters = nsevent.characters;
+
+ // If a dead key occurs as a result of pressing a key combination then
+ // characters will have 0 length, but charactersIgnoringModifiers will
+ // have a valid character in it. This enables key combinations such as
+ // ALT+E to be used as a shortcut with an English keyboard even though
+ // pressing ALT+E will give a dead key while doing normal text input.
+ Qt::Key key = Qt::Key_unknown;
+ if (characters.length || charactersIgnoringModifiers.length) {
+ QChar character = QChar::ReplacementCharacter;
+ if (nativeModifiers & (NSEventModifierFlagControl | NSEventModifierFlagOption)
+ && charactersIgnoringModifiers.length)
+ character = QChar([charactersIgnoringModifiers characterAtIndex:0]);
+ else if (characters.length)
+ character = QChar([characters characterAtIndex:0]);
+ key = QAppleKeyMapper::fromCocoaKey(character);
+ }
+
+ QString text = QString::fromNSString(characters);
+ bool autorep = nsevent.ARepeat;
+
+ return new QKeyEvent(type, key, modifiers, nativeScanCode, nativeVirtualKey, nativeModifiers,
+ text, autorep);
+}
+
+} // namespace QtWebEngineCore
+
+namespace content {
+
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(const blink::WebKeyboardEvent &web_event, gfx::NativeView)
+ : blink::WebKeyboardEvent(web_event)
+ , skip_if_unhandled(false)
+{
+}
+
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(blink::WebInputEvent::Type type, int modifiers,
+ base::TimeTicks timestamp)
+ : blink::WebKeyboardEvent(type, modifiers, timestamp)
+ , skip_if_unhandled(false)
+{
+}
+
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(gfx::NativeEvent native_event)
+ : os_event(native_event) // FIXME: Copy?
+ , skip_if_unhandled(false)
+{
+}
+
+NativeWebKeyboardEvent::NativeWebKeyboardEvent(const NativeWebKeyboardEvent& other)
+ : blink::WebKeyboardEvent(other)
+ , os_event(other.os_event) // FIXME: Copy?
+ , skip_if_unhandled(other.skip_if_unhandled)
+{
+}
+
+NativeWebKeyboardEvent &NativeWebKeyboardEvent::operator=(const NativeWebKeyboardEvent &other)
+{
+ blink::WebKeyboardEvent::operator=(other);
+
+ os_event = other.os_event; // FIXME: Copy?
+ skip_if_unhandled = other.skip_if_unhandled;
+
+ return *this;
+}
+
+NativeWebKeyboardEvent::~NativeWebKeyboardEvent() = default;
+
+} // namespace content
diff --git a/src/core/net/client_cert_override.cpp b/src/core/net/client_cert_override.cpp
deleted file mode 100644
index f33515f63..000000000
--- a/src/core/net/client_cert_override.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "client_cert_override.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/task/post_task.h"
-#include "base/callback_forward.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "net/ssl/client_cert_store.h"
-#include "net/ssl/ssl_cert_request_info.h"
-#include "net/ssl/ssl_private_key.h"
-#include "net/cert/x509_certificate.h"
-#include "third_party/boringssl/src/include/openssl/pem.h"
-#include "third_party/boringssl/src/include/openssl/err.h"
-#include "third_party/boringssl/src/include/openssl/evp.h"
-
-#include "client_cert_store_data.h"
-#include "profile_io_data_qt.h"
-
-#include <QtNetwork/qtnetworkglobal.h>
-
-#if defined(USE_NSS_CERTS)
-#include "net/ssl/client_cert_store_nss.h"
-#endif
-
-#if defined(OS_WIN)
-#include "net/ssl/client_cert_store_win.h"
-#endif
-
-#if defined(OS_MACOSX)
-#include "net/ssl/client_cert_store_mac.h"
-#endif
-
-namespace {
-
-class ClientCertIdentityOverride : public net::ClientCertIdentity
-{
-public:
- ClientCertIdentityOverride(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key)
- : net::ClientCertIdentity(std::move(cert)), m_key(std::move(key)) {}
- ~ClientCertIdentityOverride() override = default;
-
- void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<net::SSLPrivateKey>)> private_key_callback) override
- {
- std::move(private_key_callback).Run(m_key);
- }
-
-#if defined(OS_MACOSX)
- SecIdentityRef sec_identity_ref() const override
- {
- return nullptr;
- }
-#endif
-
-private:
- scoped_refptr<net::SSLPrivateKey> m_key;
-};
-
-} // namespace
-
-namespace QtWebEngineCore {
-
-ClientCertOverrideStore::ClientCertOverrideStore(ClientCertificateStoreData *storeData)
- : ClientCertStore()
- , m_storeData(storeData)
- , m_nativeStore(createNativeStore())
-{
-}
-
-ClientCertOverrideStore::~ClientCertOverrideStore() = default;
-
-#if QT_CONFIG(ssl)
-net::ClientCertIdentityList ClientCertOverrideStore::GetClientCertsOnUIThread(const net::SSLCertRequestInfo &cert_request_info)
-{
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- const auto &clientCertOverrideData = m_storeData->extraCerts;
- // Look for certificates in memory store
- for (int i = 0; i < clientCertOverrideData.length(); i++) {
- scoped_refptr<net::X509Certificate> cert = clientCertOverrideData[i]->certPtr;
- if (cert != NULL && cert->IsIssuedByEncoded(cert_request_info.cert_authorities)) {
- net::ClientCertIdentityList selected_identities;
- selected_identities.push_back(std::make_unique<ClientCertIdentityOverride>(cert, clientCertOverrideData[i]->keyPtr));
- return selected_identities;
- }
- }
- return net::ClientCertIdentityList();
-}
-
-void ClientCertOverrideStore::GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info,
- ClientCertListCallback callback,
- net::ClientCertIdentityList &&result)
-{
- // Continue with native cert store if matching certificatse were not found in memory
- if (result.empty() && m_nativeStore)
- m_nativeStore->GetClientCerts(cert_request_info, std::move(callback));
- else
- std::move(callback).Run(std::move(result));
-}
-
-#endif // QT_CONFIG(ssl)
-
-void ClientCertOverrideStore::GetClientCerts(const net::SSLCertRequestInfo &cert_request_info,
- ClientCertListCallback callback)
-{
-#if QT_CONFIG(ssl)
- // Access the user-provided data from the UI thread, but return on whatever thread this is.
- if (base::PostTaskAndReplyWithResult(
- FROM_HERE, { content::BrowserThread::UI },
- base::BindOnce(&ClientCertOverrideStore::GetClientCertsOnUIThread,
- base::Unretained(this), std::cref(cert_request_info)),
- base::BindOnce(&ClientCertOverrideStore::GetClientCertsReturn,
- base::Unretained(this), std::cref(cert_request_info), std::move(callback)))
- ) {
- return;
- }
-#endif // QT_CONFIG(ssl)
-
- // Continue with native cert store if we failed to post task
- if (m_nativeStore)
- m_nativeStore->GetClientCerts(cert_request_info, std::move(callback));
- else
- std::move(callback).Run(net::ClientCertIdentityList());
-}
-
-// static
-std::unique_ptr<net::ClientCertStore> ClientCertOverrideStore::createNativeStore()
-{
-#if defined(USE_NSS_CERTS)
- return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(net::ClientCertStoreNSS::PasswordDelegateFactory()));
-#elif defined(OS_WIN)
- return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
-#elif defined(OS_MACOSX)
- return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
-#else
- return nullptr;
-#endif
-}
-} // namespace QtWebEngineCore
diff --git a/src/core/net/client_cert_override.h b/src/core/net/client_cert_override.h
deleted file mode 100644
index 7fd28eaeb..000000000
--- a/src/core/net/client_cert_override.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CLIENT_CERT_OVERRIDE_P_H
-#define CLIENT_CERT_OVERRIDE_P_H
-
-#include "net/ssl/client_cert_store.h"
-#include "base/callback_forward.h"
-#include "net/cert/x509_certificate.h"
-
-namespace net {
-class SSLCertRequestInfo;
-} // namespace net
-
-namespace QtWebEngineCore {
-struct ClientCertificateStoreData;
-
-class ClientCertOverrideStore : public net::ClientCertStore
-{
-public:
- ClientCertOverrideStore(ClientCertificateStoreData *storeData);
- virtual ~ClientCertOverrideStore() override;
- void GetClientCerts(const net::SSLCertRequestInfo &cert_request_info,
- ClientCertListCallback callback) override;
-private:
- static std::unique_ptr<net::ClientCertStore> createNativeStore();
- net::ClientCertIdentityList GetClientCertsOnUIThread(const net::SSLCertRequestInfo &request);
- void GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info,
- ClientCertListCallback callback,
- net::ClientCertIdentityList &&result);
- ClientCertificateStoreData *m_storeData;
- std::unique_ptr<net::ClientCertStore> m_nativeStore;
-};
-
-} // QtWebEngineCore
-
-#endif
diff --git a/src/core/net/client_cert_qt.cpp b/src/core/net/client_cert_qt.cpp
new file mode 100644
index 000000000..044e5618e
--- /dev/null
+++ b/src/core/net/client_cert_qt.cpp
@@ -0,0 +1,148 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "client_cert_qt.h"
+
+#include "base/functional/bind.h"
+#include "base/functional/callback_forward.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "crypto/crypto_buildflags.h"
+#include "net/ssl/client_cert_store.h"
+#include "net/ssl/ssl_cert_request_info.h"
+#include "net/ssl/ssl_private_key.h"
+#include "net/cert/x509_certificate.h"
+#include "third_party/boringssl/src/include/openssl/pem.h"
+#include "third_party/boringssl/src/include/openssl/err.h"
+#include "third_party/boringssl/src/include/openssl/evp.h"
+
+#include "client_cert_store_data.h"
+
+#include <QtNetwork/qtnetworkglobal.h>
+
+#if BUILDFLAG(USE_NSS_CERTS)
+#include "net/ssl/client_cert_store_nss.h"
+#endif
+
+#if defined(Q_OS_WIN)
+#include "net/ssl/client_cert_store_win.h"
+#endif
+
+#if BUILDFLAG(IS_MAC)
+#include "net/ssl/client_cert_store_mac.h"
+#endif
+
+namespace {
+
+class ClientCertIdentityQt : public net::ClientCertIdentity
+{
+public:
+ ClientCertIdentityQt(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key)
+ : net::ClientCertIdentity(std::move(cert)), m_key(std::move(key)) {}
+ ~ClientCertIdentityQt() override = default;
+
+ void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<net::SSLPrivateKey>)> private_key_callback) override
+ {
+ std::move(private_key_callback).Run(m_key);
+ }
+
+private:
+ scoped_refptr<net::SSLPrivateKey> m_key;
+};
+
+} // namespace
+
+namespace QtWebEngineCore {
+
+ClientCertStoreQt::ClientCertStoreQt(ClientCertificateStoreData *storeData)
+ : ClientCertStore()
+ , m_storeData(storeData)
+ , m_nativeStore(createNativeStore())
+{
+}
+
+ClientCertStoreQt::~ClientCertStoreQt() = default;
+
+#if QT_CONFIG(ssl)
+net::ClientCertIdentityList ClientCertStoreQt::GetClientCertsOnUIThread(const net::SSLCertRequestInfo &cert_request_info)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ const auto &clientCertOverrideData = m_storeData->extraCerts;
+
+ // Look for certificates in memory store
+ net::ClientCertIdentityList selected_identities;
+ for (int i = 0; i < clientCertOverrideData.length(); i++) {
+ scoped_refptr<net::X509Certificate> cert = clientCertOverrideData[i]->certPtr;
+ if (cert) {
+ if (cert->HasExpired()) {
+ qWarning() << "Expired certificate" << clientCertOverrideData[i];
+ continue;
+ }
+ if (cert_request_info.cert_authorities.empty()
+ || cert->IsIssuedByEncoded(cert_request_info.cert_authorities)) {
+ selected_identities.push_back(std::make_unique<ClientCertIdentityQt>(
+ cert, clientCertOverrideData[i]->keyPtr));
+ }
+ }
+ }
+ return selected_identities;
+}
+
+void ClientCertStoreQt::GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info,
+ ClientCertListCallback callback,
+ net::ClientCertIdentityList &&result)
+{
+ // Continue with native cert store and append them after memory certificates
+ if (m_nativeStore) {
+ ClientCertListCallback callback2 = base::BindOnce(
+ [](ClientCertStoreQt::ClientCertListCallback callback,
+ net::ClientCertIdentityList result1, net::ClientCertIdentityList result2) {
+ while (!result2.empty()) {
+ result1.push_back(std::move(result2.back()));
+ result2.pop_back();
+ }
+ std::move(callback).Run(std::move(result1));
+ },
+ std::move(callback), std::move(result));
+ m_nativeStore->GetClientCerts(cert_request_info, std::move(callback2));
+ } else {
+ std::move(callback).Run(std::move(result));
+ }
+}
+
+#endif // QT_CONFIG(ssl)
+
+void ClientCertStoreQt::GetClientCerts(const net::SSLCertRequestInfo &cert_request_info,
+ ClientCertListCallback callback)
+{
+#if QT_CONFIG(ssl)
+ // Access the user-provided data from the UI thread, but return on whatever thread this is.
+ bool ok = content::GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult(
+ FROM_HERE,
+ base::BindOnce(&ClientCertStoreQt::GetClientCertsOnUIThread,
+ base::Unretained(this), std::cref(cert_request_info)),
+ base::BindOnce(&ClientCertStoreQt::GetClientCertsReturn,
+ base::Unretained(this), std::cref(cert_request_info), std::move(callback)));
+ DCHECK(ok); // callback is already moved and we can't really recover here.
+#else
+ if (m_nativeStore)
+ m_nativeStore->GetClientCerts(cert_request_info, std::move(callback));
+ else
+ std::move(callback).Run(net::ClientCertIdentityList());
+#endif // QT_CONFIG(ssl)
+}
+
+// static
+std::unique_ptr<net::ClientCertStore> ClientCertStoreQt::createNativeStore()
+{
+#if BUILDFLAG(USE_NSS_CERTS)
+ return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(net::ClientCertStoreNSS::PasswordDelegateFactory()));
+#elif defined(Q_OS_WIN)
+ return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
+#elif BUILDFLAG(IS_MAC)
+ return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
+#else
+ return nullptr;
+#endif
+}
+} // namespace QtWebEngineCore
diff --git a/src/core/net/client_cert_qt.h b/src/core/net/client_cert_qt.h
new file mode 100644
index 000000000..96579fae6
--- /dev/null
+++ b/src/core/net/client_cert_qt.h
@@ -0,0 +1,37 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef CLIENT_CERT_QT_P_H
+#define CLIENT_CERT_QT_P_H
+
+#include "base/functional/callback_forward.h"
+#include "net/cert/x509_certificate.h"
+#include "net/ssl/client_cert_store.h"
+
+namespace net {
+class SSLCertRequestInfo;
+} // namespace net
+
+namespace QtWebEngineCore {
+struct ClientCertificateStoreData;
+
+class ClientCertStoreQt : public net::ClientCertStore
+{
+public:
+ ClientCertStoreQt(ClientCertificateStoreData *storeData);
+ virtual ~ClientCertStoreQt() override;
+ void GetClientCerts(const net::SSLCertRequestInfo &cert_request_info,
+ ClientCertListCallback callback) override;
+private:
+ static std::unique_ptr<net::ClientCertStore> createNativeStore();
+ net::ClientCertIdentityList GetClientCertsOnUIThread(const net::SSLCertRequestInfo &request);
+ void GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info,
+ ClientCertListCallback callback,
+ net::ClientCertIdentityList &&result);
+ ClientCertificateStoreData *m_storeData;
+ std::unique_ptr<net::ClientCertStore> m_nativeStore;
+};
+
+} // QtWebEngineCore
+
+#endif
diff --git a/src/core/net/client_cert_store_data.cpp b/src/core/net/client_cert_store_data.cpp
index 314e64145..0de6885df 100644
--- a/src/core/net/client_cert_store_data.cpp
+++ b/src/core/net/client_cert_store_data.cpp
@@ -1,48 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "net/client_cert_store_data.h"
#if QT_CONFIG(ssl)
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "net/base/net_errors.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/ssl_platform_key_util.h"
@@ -59,16 +20,16 @@
namespace {
-class SSLPlatformKeyOverride : public net::ThreadedSSLPrivateKey::Delegate
+class SSLPlatformKeyQt : public net::ThreadedSSLPrivateKey::Delegate
{
public:
- SSLPlatformKeyOverride(const QByteArray &sslKeyInBytes)
+ SSLPlatformKeyQt(const QByteArray &sslKeyInBytes)
{
m_mem = BIO_new_mem_buf(sslKeyInBytes, -1);
m_key = PEM_read_bio_PrivateKey(m_mem, nullptr, nullptr, nullptr);
}
- ~SSLPlatformKeyOverride() override
+ ~SSLPlatformKeyQt() override
{
if (m_key)
EVP_PKEY_free(m_key);
@@ -104,8 +65,8 @@ public:
std::vector<uint16_t> GetAlgorithmPreferences() override
{
- return { SSL_SIGN_RSA_PKCS1_SHA1, SSL_SIGN_RSA_PKCS1_SHA512
- , SSL_SIGN_RSA_PKCS1_SHA384, SSL_SIGN_RSA_PKCS1_SHA256 };
+ return net::SSLPrivateKey::DefaultAlgorithmPreferences(EVP_PKEY_id(m_key),
+ /* supports pss */ true);
}
std::string GetProviderName() override {
return "qtwebengine";
@@ -113,8 +74,6 @@ public:
private:
EVP_PKEY *m_key;
BIO *m_mem;
-
- DISALLOW_COPY_AND_ASSIGN(SSLPlatformKeyOverride);
};
scoped_refptr<net::SSLPrivateKey> wrapOpenSSLPrivateKey(const QByteArray &sslKeyInBytes)
@@ -123,7 +82,7 @@ scoped_refptr<net::SSLPrivateKey> wrapOpenSSLPrivateKey(const QByteArray &sslKey
return nullptr;
return base::MakeRefCounted<net::ThreadedSSLPrivateKey>(
- std::make_unique<SSLPlatformKeyOverride>(sslKeyInBytes),
+ std::make_unique<SSLPlatformKeyQt>(sslKeyInBytes),
net::GetSSLPlatformKeyTaskRunner());
}
@@ -138,7 +97,8 @@ void ClientCertificateStoreData::add(const QSslCertificate &certificate, const Q
Entry *data = new Entry;
data->keyPtr = wrapOpenSSLPrivateKey(sslKeyInBytes);
- data->certPtr = net::X509Certificate::CreateFromBytes(certInBytes.data(), certInBytes.length());
+ data->certPtr = net::X509Certificate::CreateFromBytes(base::make_span((const unsigned char *)certInBytes.data(),
+ (unsigned long)certInBytes.length()));
data->key = privateKey;
data->certificate = certificate;
extraCerts.append(data);
diff --git a/src/core/net/client_cert_store_data.h b/src/core/net/client_cert_store_data.h
index e47a909e4..c2e28ac18 100644
--- a/src/core/net/client_cert_store_data.h
+++ b/src/core/net/client_cert_store_data.h
@@ -1,52 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CLIENT_CERT_STORE_DATA_H
#define CLIENT_CERT_STORE_DATA_H
-#include "qtwebenginecoreglobal.h"
-#include "qtnetworkglobal.h"
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
+#include <QtNetwork/qtnetworkglobal.h>
#if QT_CONFIG(ssl)
#include "base/memory/ref_counted.h"
-#include <QtCore/qvector.h>
+#include <QtCore/qlist.h>
#include <QtNetwork/qsslcertificate.h>
#include <QtNetwork/qsslkey.h>
@@ -71,7 +35,7 @@ struct ClientCertificateStoreData
void remove(const QSslCertificate &certificate);
void clear();
- QVector<Entry *> extraCerts;
+ QList<Entry *> extraCerts;
};
} // namespace QtWebEngineCore
diff --git a/src/core/net/cookie_monster_delegate_qt.cpp b/src/core/net/cookie_monster_delegate_qt.cpp
index d3157f760..d107c520c 100644
--- a/src/core/net/cookie_monster_delegate_qt.cpp
+++ b/src/core/net/cookie_monster_delegate_qt.cpp
@@ -1,50 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "cookie_monster_delegate_qt.h"
-#include "base/bind.h"
-#include "base/memory/ptr_util.h"
-#include "base/task/post_task.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "mojo/public/cpp/bindings/binding.h"
+#include "base/functional/bind.h"
#include "net/cookies/cookie_util.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
@@ -52,6 +11,8 @@
#include "api/qwebenginecookiestore_p.h"
#include "type_conversion.h"
+#include <QNetworkCookie>
+
namespace QtWebEngineCore {
class CookieChangeListener : public network::mojom::CookieChangeListener
@@ -68,10 +29,25 @@ public:
private:
CookieMonsterDelegateQt *m_delegate;
+};
+
+class CookieAccessFilter : public network::mojom::CookieRemoteAccessFilter
+{
+public:
+ CookieAccessFilter(CookieMonsterDelegateQt *delegate) : m_delegate(delegate) { }
+ ~CookieAccessFilter() override = default;
- DISALLOW_COPY_AND_ASSIGN(CookieChangeListener);
+ void AllowedAccess(const GURL &url, const net::SiteForCookies &site_for_cookies, AllowedAccessCallback callback) override
+ {
+ bool allow = m_delegate->canGetCookies(toQt(site_for_cookies.first_party_url()), toQt(url));
+ std::move(callback).Run(allow);
+ }
+
+private:
+ CookieMonsterDelegateQt *m_delegate;
};
+
static GURL sourceUrlForCookie(const QNetworkCookie &cookie)
{
QString urlFragment = QStringLiteral("%1%2").arg(cookie.domain()).arg(cookie.path());
@@ -81,7 +57,10 @@ static GURL sourceUrlForCookie(const QNetworkCookie &cookie)
CookieMonsterDelegateQt::CookieMonsterDelegateQt()
: m_client(nullptr)
, m_listener(new CookieChangeListener(this))
+ , m_filter(new CookieAccessFilter(this))
, m_receiver(m_listener.get())
+ , m_filterReceiver(m_filter.get())
+ , m_hasFilter(false)
{
}
@@ -104,29 +83,30 @@ bool CookieMonsterDelegateQt::hasCookieMonster()
return m_mojoCookieManager.is_bound();
}
-void CookieMonsterDelegateQt::getAllCookies(quint64 callbackId)
+void CookieMonsterDelegateQt::getAllCookies()
{
- m_mojoCookieManager->GetAllCookies(base::BindOnce(&CookieMonsterDelegateQt::GetAllCookiesCallbackOnUIThread, this, callbackId));
+ m_mojoCookieManager->GetAllCookies(net::CookieStore::GetAllCookiesCallback());
}
-void CookieMonsterDelegateQt::setCookie(quint64 callbackId, const QNetworkCookie &cookie, const QUrl &origin)
+void CookieMonsterDelegateQt::setCookie(const QNetworkCookie &cookie, const QUrl &origin)
{
Q_ASSERT(hasCookieMonster());
Q_ASSERT(m_client);
- net::CookieStore::SetCookiesCallback callback;
-
GURL gurl = origin.isEmpty() ? sourceUrlForCookie(cookie) : toGurl(origin);
std::string cookie_line = cookie.toRawForm().toStdString();
- if (callbackId != CallbackDirectory::NoCallbackId)
- callback = base::BindOnce(&CookieMonsterDelegateQt::SetCookieCallbackOnUIThread, this, callbackId);
- net::CanonicalCookie::CookieInclusionStatus inclusion;
- auto canonCookie = net::CanonicalCookie::Create(gurl, cookie_line, base::Time::Now(), base::nullopt, &inclusion);
+ net::CookieInclusionStatus inclusion;
+ auto canonCookie = net::CanonicalCookie::Create(gurl, cookie_line, base::Time::Now(),
+ absl::nullopt, absl::nullopt, true, &inclusion);
+ if (!canonCookie || !inclusion.IsInclude()) {
+ LOG(WARNING) << "QWebEngineCookieStore::setCookie() - Tried to set invalid cookie";
+ return;
+ }
net::CookieOptions options;
- if (!inclusion.HasExclusionReason(net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY))
- options.set_include_httponly();
- m_mojoCookieManager->SetCanonicalCookie(*canonCookie.get(), gurl.scheme(), options, std::move(callback));
+ options.set_include_httponly();
+ options.set_same_site_cookie_context(net::CookieOptions::SameSiteCookieContext::MakeInclusiveForSet());
+ m_mojoCookieManager->SetCanonicalCookie(*canonCookie.get(), gurl, options, net::CookieStore::SetCookiesCallback());
}
void CookieMonsterDelegateQt::deleteCookie(const QNetworkCookie &cookie, const QUrl &origin)
@@ -142,30 +122,26 @@ void CookieMonsterDelegateQt::deleteCookie(const QNetworkCookie &cookie, const Q
m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback());
}
-void CookieMonsterDelegateQt::deleteSessionCookies(quint64 callbackId)
+void CookieMonsterDelegateQt::deleteSessionCookies()
{
Q_ASSERT(hasCookieMonster());
Q_ASSERT(m_client);
- network::mojom::CookieManager::DeleteCookiesCallback callback =
- base::BindOnce(&CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread, this, callbackId);
auto filter = network::mojom::CookieDeletionFilter::New();
filter->session_control = network::mojom::CookieDeletionSessionControl::SESSION_COOKIES;
- m_mojoCookieManager->DeleteCookies(std::move(filter), std::move(callback));
+ m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback());
}
-void CookieMonsterDelegateQt::deleteAllCookies(quint64 callbackId)
+void CookieMonsterDelegateQt::deleteAllCookies()
{
Q_ASSERT(hasCookieMonster());
Q_ASSERT(m_client);
- network::mojom::CookieManager::DeleteCookiesCallback callback =
- base::BindOnce(&CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread, this, callbackId);
auto filter = network::mojom::CookieDeletionFilter::New();
- m_mojoCookieManager->DeleteCookies(std::move(filter), std::move(callback));
+ m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback());
}
-void CookieMonsterDelegateQt::setMojoCookieManager(network::mojom::CookieManagerPtrInfo cookie_manager_info)
+void CookieMonsterDelegateQt::setMojoCookieManager(mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_info)
{
if (m_mojoCookieManager.is_bound())
unsetMojoCookieManager();
@@ -176,14 +152,31 @@ void CookieMonsterDelegateQt::setMojoCookieManager(network::mojom::CookieManager
m_mojoCookieManager.Bind(std::move(cookie_manager_info));
m_mojoCookieManager->AddGlobalChangeListener(m_receiver.BindNewPipeAndPassRemote());
+ if (m_hasFilter)
+ m_mojoCookieManager->SetRemoteFilter(m_filterReceiver.BindNewPipeAndPassRemote());
if (m_client)
m_client->d_func()->processPendingUserCookies();
}
+void CookieMonsterDelegateQt::setHasFilter(bool hasFilter)
+{
+ m_hasFilter = hasFilter;
+ if (!m_mojoCookieManager.is_bound())
+ return;
+ if (m_hasFilter) {
+ if (!m_filterReceiver.is_bound())
+ m_mojoCookieManager->SetRemoteFilter(m_filterReceiver.BindNewPipeAndPassRemote());
+ } else {
+ if (m_filterReceiver.is_bound())
+ m_filterReceiver.reset();
+ }
+}
+
void CookieMonsterDelegateQt::unsetMojoCookieManager()
{
m_receiver.reset();
+ m_filterReceiver.reset();
m_mojoCookieManager.reset();
}
@@ -223,23 +216,4 @@ void CookieMonsterDelegateQt::OnCookieChanged(const net::CookieChangeInfo &chang
m_client->d_func()->onCookieChanged(toQt(change.cookie), change.cause != net::CookieChangeCause::INSERTED);
}
-void CookieMonsterDelegateQt::GetAllCookiesCallbackOnUIThread(qint64 callbackId, const net::CookieList &cookies)
-{
- QByteArray rawCookies = QByteArray::fromStdString(net::CanonicalCookie::BuildCookieLine(cookies));
- if (m_client)
- m_client->d_func()->onGetAllCallbackResult(callbackId, rawCookies);
-}
-
-void CookieMonsterDelegateQt::SetCookieCallbackOnUIThread(qint64 callbackId, net::CanonicalCookie::CookieInclusionStatus status)
-{
- if (m_client)
- m_client->d_func()->onSetCallbackResult(callbackId, status.IsInclude());
-}
-
-void CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread(qint64 callbackId, uint numCookies)
-{
- if (m_client)
- m_client->d_func()->onDeleteCallbackResult(callbackId, numCookies);
-}
-
} // namespace QtWebEngineCore
diff --git a/src/core/net/cookie_monster_delegate_qt.h b/src/core/net/cookie_monster_delegate_qt.h
index bcbbe4c52..f6872323d 100644
--- a/src/core/net/cookie_monster_delegate_qt.h
+++ b/src/core/net/cookie_monster_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,11 +17,6 @@
#include "qtwebenginecoreglobal_p.h"
-QT_WARNING_PUSH
-// For some reason adding -Wno-unused-parameter to QMAKE_CXXFLAGS has no
-// effect with clang, so use a pragma for these dirty chromium headers
-QT_WARNING_DISABLE_CLANG("-Wunused-parameter")
-
// We need to work around Chromium using 'signals' as a variable name in headers:
#ifdef signals
#define StAsH_signals signals
@@ -65,7 +24,7 @@ QT_WARNING_DISABLE_CLANG("-Wunused-parameter")
#endif
#include "base/memory/ref_counted.h"
#include "mojo/public/cpp/bindings/receiver.h"
-#include "net/cookies/cookie_change_dispatcher.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "net/cookies/cookie_store.h"
#include "services/network/public/mojom/cookie_manager.mojom-forward.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
@@ -73,53 +32,51 @@ QT_WARNING_DISABLE_CLANG("-Wunused-parameter")
#define signals StAsH_signals
#undef StAsH_signals
#endif
-QT_WARNING_POP
-#include <QNetworkCookie>
#include <QPointer>
+QT_FORWARD_DECLARE_CLASS(QNetworkCookie)
QT_FORWARD_DECLARE_CLASS(QWebEngineCookieStore)
namespace QtWebEngineCore {
class CookieMonsterDelegateQtPrivate;
-class Q_WEBENGINECORE_PRIVATE_EXPORT CookieMonsterDelegateQt : public base::RefCountedThreadSafe<CookieMonsterDelegateQt>
+class Q_WEBENGINECORE_EXPORT CookieMonsterDelegateQt : public base::RefCountedThreadSafe<CookieMonsterDelegateQt>
{
QPointer<QWebEngineCookieStore> m_client;
std::vector<std::unique_ptr<net::CookieChangeSubscription>> m_subscriptions;
- network::mojom::CookieManagerPtr m_mojoCookieManager;
+ mojo::Remote<network::mojom::CookieManager> m_mojoCookieManager;
std::unique_ptr<network::mojom::CookieChangeListener> m_listener;
+ std::unique_ptr<network::mojom::CookieRemoteAccessFilter> m_filter;
mojo::Receiver<network::mojom::CookieChangeListener> m_receiver;
+ mojo::Receiver<network::mojom::CookieRemoteAccessFilter> m_filterReceiver;
+ bool m_hasFilter;
public:
CookieMonsterDelegateQt();
~CookieMonsterDelegateQt();
bool hasCookieMonster();
- void setCookie(quint64 callbackId, const QNetworkCookie &cookie, const QUrl &origin);
+ void setCookie(const QNetworkCookie &cookie, const QUrl &origin);
void deleteCookie(const QNetworkCookie &cookie, const QUrl &origin);
- void getAllCookies(quint64 callbackId);
- void deleteSessionCookies(quint64 callbackId);
- void deleteAllCookies(quint64 callbackId);
+ void getAllCookies();
+ void deleteSessionCookies();
+ void deleteAllCookies();
void setClient(QWebEngineCookieStore *client);
- void setMojoCookieManager(network::mojom::CookieManagerPtrInfo cookie_manager_info);
+ void setMojoCookieManager(mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_info);
void unsetMojoCookieManager();
+ void setHasFilter(bool b);
bool canSetCookie(const QUrl &firstPartyUrl, const QByteArray &cookieLine, const QUrl &url) const;
bool canGetCookies(const QUrl &firstPartyUrl, const QUrl &url) const;
void AddStore(net::CookieStore *store);
void OnCookieChanged(const net::CookieChangeInfo &change);
-
-private:
- void GetAllCookiesCallbackOnUIThread(qint64 callbackId, const net::CookieList &cookies);
- void SetCookieCallbackOnUIThread(qint64 callbackId, net::CanonicalCookie::CookieInclusionStatus status);
- void DeleteCookiesCallbackOnUIThread(qint64 callbackId, uint numCookies);
};
-}
+} // namespace QtWebEngineCore
#endif // COOKIE_MONSTER_DELEGATE_QT_H
diff --git a/src/core/net/custom_url_loader_factory.cpp b/src/core/net/custom_url_loader_factory.cpp
index e5f580536..4274def99 100644
--- a/src/core/net/custom_url_loader_factory.cpp
+++ b/src/core/net/custom_url_loader_factory.cpp
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "custom_url_loader_factory.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/system/data_pipe.h"
@@ -51,9 +13,13 @@
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
-#include "services/network/public/cpp/resource_response.h"
+#include "services/network/public/cpp/cors/cors.h"
+#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
+#include "services/network/public/mojom/url_response_head.mojom.h"
+#include "url/url_util.h"
+#include "url/url_util_qt.h"
#include "api/qwebengineurlscheme.h"
#include "net/url_request_custom_job_proxy.h"
@@ -66,6 +32,7 @@
#include <QtCore/qiodevice.h>
#include <QtCore/qmimedatabase.h>
#include <QtCore/qmimedata.h>
+#include <QtCore/qpointer.h>
#include <QtCore/qurl.h>
namespace QtWebEngineCore {
@@ -77,26 +44,27 @@ class CustomURLLoader : public network::mojom::URLLoader
{
public:
static void CreateAndStart(const network::ResourceRequest &request,
- network::mojom::URLLoaderRequest loader,
- network::mojom::URLLoaderClientPtrInfo client_info,
+ mojo::PendingReceiver<network::mojom::URLLoader> loader,
+ mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
QPointer<ProfileAdapter> profileAdapter)
{
// CustomURLLoader will handle its own life-cycle, and delete when
// the client lets go.
- auto *customUrlLoader = new CustomURLLoader(request, std::move(loader), std::move(client_info), profileAdapter);
+ auto *customUrlLoader = new CustomURLLoader(request, std::move(loader), std::move(client_remote), profileAdapter);
customUrlLoader->Start();
}
// network::mojom::URLLoader:
void FollowRedirect(const std::vector<std::string> &removed_headers,
const net::HttpRequestHeaders &modified_headers,
- const base::Optional<GURL> &new_url) override
+ const net::HttpRequestHeaders &modified_cors_exempt_headers, // FIXME: do something with this?
+ const absl::optional<GURL> &new_url) override
{
// We can be asked for follow our own redirect
scoped_refptr<URLRequestCustomJobProxy> proxy = new URLRequestCustomJobProxy(this, m_proxy->m_scheme, m_proxy->m_profileAdapter);
m_proxy->m_client = nullptr;
// m_taskRunner->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy));
- base::PostTask(FROM_HERE, { content::BrowserThread::UI },
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy));
m_proxy = std::move(proxy);
if (new_url)
@@ -115,24 +83,25 @@ public:
private:
CustomURLLoader(const network::ResourceRequest &request,
- network::mojom::URLLoaderRequest loader,
- network::mojom::URLLoaderClientPtrInfo client_info,
+ mojo::PendingReceiver<network::mojom::URLLoader> loader,
+ mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
QPointer<ProfileAdapter> profileAdapter)
// ### We can opt to run the url-loader on the UI thread instead
- : m_taskRunner(base::CreateSingleThreadTaskRunner({ content::BrowserThread::IO }))
+ : m_taskRunner(content::GetIOThreadTaskRunner({}))
, m_proxy(new URLRequestCustomJobProxy(this, request.url.scheme(), profileAdapter))
- , m_binding(this, std::move(loader))
- , m_client(std::move(client_info))
+ , m_receiver(this, std::move(loader))
+ , m_client(std::move(client_remote))
, m_request(request)
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
- m_binding.set_connection_error_handler(
- base::BindOnce(&CustomURLLoader::OnConnectionError, m_weakPtrFactory.GetWeakPtr()));
+ m_receiver.set_disconnect_handler(
+ base::BindOnce(&CustomURLLoader::OnConnectionError, m_weakPtrFactory.GetWeakPtr()));
m_firstBytePosition = 0;
m_device = nullptr;
m_error = 0;
QWebEngineUrlScheme scheme = QWebEngineUrlScheme::schemeByName(QByteArray::fromStdString(request.url.scheme()));
m_corsEnabled = scheme.flags().testFlag(QWebEngineUrlScheme::CorsEnabled);
+ m_isLocal = scheme.flags().testFlag(QWebEngineUrlScheme::LocalScheme);
}
~CustomURLLoader() override = default;
@@ -140,9 +109,34 @@ private:
void Start()
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
- m_head.request_start = base::TimeTicks::Now();
- if (!m_pipe.consumer_handle.is_valid())
+ if (network::cors::IsCorsEnabledRequestMode(m_request.mode)) {
+ // CORS mode requires a valid request_initiator.
+ if (!m_request.request_initiator)
+ return CompleteWithFailure(net::ERR_INVALID_ARGUMENT);
+
+ if (m_isLocal) {
+ std::string fromScheme = m_request.request_initiator->GetTupleOrPrecursorTupleIfOpaque().scheme();
+ const std::vector<std::string> &localSchemes = url::GetLocalSchemes();
+ bool fromLocal = base::Contains(localSchemes, fromScheme);
+ bool hasLocalAccess = fromLocal;
+ if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(fromScheme))
+ hasLocalAccess = cs->flags & (url::CustomScheme::LocalAccessAllowed | url::CustomScheme::Local);
+ if (!hasLocalAccess)
+ return CompleteWithFailure(net::ERR_ACCESS_DENIED);
+ } else if (!m_corsEnabled && !m_request.request_initiator->IsSameOriginWith(url::Origin::Create(m_request.url))) {
+ // Custom schemes are not covered by CorsURLLoader, so we need to reject CORS requests manually.
+ return CompleteWithFailure(network::CorsErrorStatus(network::mojom::CorsError::kCorsDisabledScheme));
+ }
+ }
+
+ if (mojo::CreateDataPipe(nullptr, m_pipeProducerHandle, m_pipeConsumerHandle) != MOJO_RESULT_OK)
+ return CompleteWithFailure(net::ERR_FAILED);
+
+ m_head = network::mojom::URLResponseHead::New();
+ m_head->request_start = base::TimeTicks::Now();
+
+ if (!m_pipeConsumerHandle.is_valid())
return CompleteWithFailure(net::ERR_FAILED);
std::map<std::string, std::string> headers;
@@ -157,9 +151,18 @@ private:
m_firstBytePosition = m_byteRange.first_byte_position();
// m_taskRunner->PostTask(FROM_HERE,
- base::PostTask(FROM_HERE, { content::BrowserThread::UI },
- base::BindOnce(&URLRequestCustomJobProxy::initialize, m_proxy,
- m_request.url, m_request.method, m_request.request_initiator, std::move(headers)));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(&URLRequestCustomJobProxy::initialize, m_proxy, m_request.url,
+ m_request.method, m_request.request_initiator, std::move(headers),
+ m_request.request_body));
+ }
+
+ void CompleteWithFailure(network::CorsErrorStatus cors_error)
+ {
+ DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
+ m_client->OnComplete(network::URLLoaderCompletionStatus(cors_error));
+ ClearProxyAndClient(false);
}
void CompleteWithFailure(net::Error net_error)
@@ -172,7 +175,7 @@ private:
void OnConnectionError()
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
- m_binding.Close();
+ m_receiver.reset();
if (m_client.is_bound())
ClearProxyAndClient(false);
else
@@ -184,7 +187,7 @@ private:
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
if (result == MOJO_RESULT_OK) {
network::URLLoaderCompletionStatus status(net::OK);
- status.encoded_data_length = m_totalBytesRead + m_head.headers->raw_headers().length();
+ status.encoded_data_length = m_totalBytesRead + m_headerBytesRead;
status.encoded_body_length = m_totalBytesRead;
status.decoded_body_length = m_totalBytesRead;
m_client->OnComplete(status);
@@ -203,9 +206,9 @@ private:
m_device->close();
m_device = nullptr;
// m_taskRunner->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy));
- base::PostTask(FROM_HERE, { content::BrowserThread::UI },
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy));
- if (!wait_for_loader_error || !m_binding.is_bound())
+ if (!wait_for_loader_error || !m_receiver.is_bound())
delete this;
}
@@ -219,17 +222,17 @@ private:
CompleteWithFailure(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE);
} else {
m_maxBytesToRead = m_byteRange.last_byte_position() - m_byteRange.first_byte_position() + 1;
- m_head.content_length = m_maxBytesToRead;
+ m_head->content_length = m_maxBytesToRead;
}
} else {
- m_head.content_length = size;
+ m_head->content_length = size;
}
}
void notifyHeadersComplete() override
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
DCHECK(!m_error);
- m_head.response_start = base::TimeTicks::Now();
+ m_head->response_start = base::TimeTicks::Now();
std::string headers;
if (!m_redirect.is_empty()) {
@@ -262,39 +265,46 @@ private:
headers += "Access-Control-Allow-Credentials: true\n";
}
}
- m_head.headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers));
- m_head.encoded_data_length = m_head.headers->raw_headers().length();
+ for (auto it = m_additionalResponseHeaders.cbegin();
+ it != m_additionalResponseHeaders.cend(); ++it) {
+ headers += it.key().toLower().toStdString() + ": " + it.value().toLower().toStdString()
+ + "\n";
+ }
+ m_head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers));
+ m_head->encoded_data_length = m_head->headers->raw_headers().length();
if (!m_redirect.is_empty()) {
- m_head.content_length = m_head.encoded_body_length = -1;
- net::URLRequest::FirstPartyURLPolicy first_party_url_policy =
- m_request.update_first_party_url_on_redirect ? net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
- : net::URLRequest::NEVER_CHANGE_FIRST_PARTY_URL;
+ m_head->content_length = {};
+ m_head->encoded_body_length = {};
+ net::RedirectInfo::FirstPartyURLPolicy first_party_url_policy =
+ m_request.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT
+ : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL;
net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo(
m_request.method, m_request.url,
m_request.site_for_cookies,
first_party_url_policy, m_request.referrer_policy,
m_request.referrer.spec(), net::HTTP_SEE_OTHER,
- m_redirect, base::nullopt, false /*insecure_scheme_was_upgraded*/);
- m_client->OnReceiveRedirect(redirectInfo, m_head);
+ m_redirect, absl::nullopt, false /*insecure_scheme_was_upgraded*/);
+ m_client->OnReceiveRedirect(redirectInfo, std::move(m_head));
+ m_head = nullptr;
// ### should m_request be updated with RedirectInfo? (see FollowRedirect)
return;
}
DCHECK(m_device);
- m_head.mime_type = m_mimeType;
- m_head.charset = m_charset;
- m_client->OnReceiveResponse(m_head);
- m_client->OnStartLoadingResponseBody(std::move(m_pipe.consumer_handle));
-
- if (readAvailableData()) // May delete this
- return;
+ m_head->mime_type = m_mimeType;
+ m_head->charset = m_charset;
+ m_headerBytesRead = m_head->headers->raw_headers().length();
+ m_client->OnReceiveResponse(std::move(m_head), std::move(m_pipeConsumerHandle), absl::nullopt);
+ m_head = nullptr;
m_watcher = std::make_unique<mojo::SimpleWatcher>(
- FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC, m_taskRunner);
- m_watcher->Watch(m_pipe.producer_handle.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
+ FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, m_taskRunner);
+ m_watcher->Watch(m_pipeProducerHandle.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(&CustomURLLoader::notifyReadyWrite,
m_weakPtrFactory.GetWeakPtr()));
+
+ readAvailableData(); // May delete this
}
void notifyCanceled() override
{
@@ -309,7 +319,7 @@ private:
void notifyStartFailure(int error) override
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
- m_head.response_start = base::TimeTicks::Now();
+ m_head->response_start = base::TimeTicks::Now();
std::string headers;
switch (error) {
case net::ERR_INVALID_URL:
@@ -331,10 +341,11 @@ private:
headers = "HTTP/1.1 500 Internal Error\n";
break;
}
- m_head.headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers));
- m_head.encoded_data_length = m_head.headers->raw_headers().length();
- m_head.content_length = m_head.encoded_body_length = -1;
- m_client->OnReceiveResponse(m_head);
+ m_head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers));
+ m_head->encoded_data_length = m_head->headers->raw_headers().length();
+ m_head->content_length = {};
+ m_head->encoded_body_length = {};
+ m_client->OnReceiveResponse(std::move(m_head), mojo::ScopedDataPipeConsumerHandle(), absl::nullopt);
CompleteWithFailure(net::Error(error));
}
void notifyReadyRead() override
@@ -360,10 +371,12 @@ private:
void *buffer = nullptr;
uint32_t bufferSize = 0;
- MojoResult beginResult = m_pipe.producer_handle->BeginWriteData(
+ MojoResult beginResult = m_pipeProducerHandle->BeginWriteData(
&buffer, &bufferSize, MOJO_BEGIN_WRITE_DATA_FLAG_NONE);
- if (beginResult == MOJO_RESULT_SHOULD_WAIT)
+ if (beginResult == MOJO_RESULT_SHOULD_WAIT) {
+ m_watcher->ArmOrNotify();
return false; // Wait for pipe watcher
+ }
if (beginResult != MOJO_RESULT_OK)
break;
if (m_maxBytesToRead > 0 && m_maxBytesToRead <= int64_t{std::numeric_limits<uint32_t>::max()})
@@ -371,17 +384,24 @@ private:
int readResult = m_device->read(static_cast<char *>(buffer), bufferSize);
uint32_t bytesRead = std::max(readResult, 0);
- m_pipe.producer_handle->EndWriteData(bytesRead);
+ m_pipeProducerHandle->EndWriteData(bytesRead);
m_totalBytesRead += bytesRead;
m_client->OnTransferSizeUpdated(m_totalBytesRead);
- if (m_device->atEnd() || (m_maxBytesToRead > 0 && m_totalBytesRead >= m_maxBytesToRead)) {
+ const bool deviceAtEnd = m_device->atEnd();
+ if ((deviceAtEnd && !m_device->isSequential())
+ || (m_maxBytesToRead > 0 && m_totalBytesRead >= m_maxBytesToRead)) {
OnTransferComplete(MOJO_RESULT_OK);
return true; // Done with reading
}
if (readResult == 0)
return false; // Wait for readyRead
+ if (readResult < 0 && deviceAtEnd && m_device->isSequential()) {
+ // Failure on read, and sequential device claiming to be at end, so treat it as a successful end-of-data.
+ OnTransferComplete(MOJO_RESULT_OK);
+ return true; // Done with reading
+ }
if (readResult < 0)
break;
}
@@ -404,7 +424,7 @@ private:
}
return false;
}
- base::TaskRunner *taskRunner() override
+ base::SequencedTaskRunner *taskRunner() override
{
DCHECK(m_taskRunner->RunsTasksInCurrentSequence());
return m_taskRunner.get();
@@ -413,36 +433,39 @@ private:
scoped_refptr<base::SequencedTaskRunner> m_taskRunner;
scoped_refptr<URLRequestCustomJobProxy> m_proxy;
- mojo::Binding<network::mojom::URLLoader> m_binding;
- network::mojom::URLLoaderClientPtr m_client;
- mojo::DataPipe m_pipe;
+ mojo::Receiver<network::mojom::URLLoader> m_receiver;
+ mojo::Remote<network::mojom::URLLoaderClient> m_client;
+ mojo::ScopedDataPipeProducerHandle m_pipeProducerHandle;
+ mojo::ScopedDataPipeConsumerHandle m_pipeConsumerHandle;
std::unique_ptr<mojo::SimpleWatcher> m_watcher;
net::HttpByteRange m_byteRange;
int64_t m_totalSize = 0;
int64_t m_maxBytesToRead = -1;
network::ResourceRequest m_request;
- network::ResourceResponseHead m_head;
+ network::mojom::URLResponseHeadPtr m_head;
+ qint64 m_headerBytesRead = 0;
qint64 m_totalBytesRead = 0;
bool m_corsEnabled;
+ bool m_isLocal;
base::WeakPtrFactory<CustomURLLoader> m_weakPtrFactory{this};
-
- DISALLOW_COPY_AND_ASSIGN(CustomURLLoader);
};
class CustomURLLoaderFactory : public network::mojom::URLLoaderFactory {
public:
- CustomURLLoaderFactory(ProfileAdapter *profileAdapter)
- : m_taskRunner(base::CreateSequencedTaskRunner({ content::BrowserThread::IO }))
+ CustomURLLoaderFactory(ProfileAdapter *profileAdapter, mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver)
+ : m_taskRunner(content::GetIOThreadTaskRunner({}))
, m_profileAdapter(profileAdapter)
{
+ m_receivers.set_disconnect_handler(base::BindRepeating(
+ &CustomURLLoaderFactory::OnDisconnect, base::Unretained(this)));
+ m_receivers.Add(this, std::move(receiver));
}
~CustomURLLoaderFactory() override = default;
// network::mojom::URLLoaderFactory:
void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader,
- int32_t routing_id,
int32_t request_id,
uint32_t options,
const network::ResourceRequest &request,
@@ -450,7 +473,6 @@ public:
const net::MutableNetworkTrafficAnnotationTag &traffic_annotation) override
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- Q_UNUSED(routing_id);
Q_UNUSED(request_id);
Q_UNUSED(options);
Q_UNUSED(traffic_annotation);
@@ -467,17 +489,29 @@ public:
m_receivers.Add(this, std::move(receiver));
}
+ void OnDisconnect()
+ {
+ if (m_receivers.empty())
+ delete this;
+ }
+
+ static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create(ProfileAdapter *profileAdapter)
+ {
+ mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
+ new CustomURLLoaderFactory(profileAdapter, pending_remote.InitWithNewPipeAndPassReceiver());
+ return pending_remote;
+ }
+
const scoped_refptr<base::SequencedTaskRunner> m_taskRunner;
mojo::ReceiverSet<network::mojom::URLLoaderFactory> m_receivers;
QPointer<ProfileAdapter> m_profileAdapter;
- DISALLOW_COPY_AND_ASSIGN(CustomURLLoaderFactory);
};
} // namespace
-std::unique_ptr<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter)
+mojo::PendingRemote<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter)
{
- return std::make_unique<CustomURLLoaderFactory>(profileAdapter);
+ return CustomURLLoaderFactory::Create(profileAdapter);
}
} // namespace QtWebEngineCore
diff --git a/src/core/net/custom_url_loader_factory.h b/src/core/net/custom_url_loader_factory.h
index 58adf4b79..fb0c74627 100644
--- a/src/core/net/custom_url_loader_factory.h
+++ b/src/core/net/custom_url_loader_factory.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,7 +15,7 @@
#ifndef CUSTOM_URL_LOADER_FACTORY_H_
#define CUSTOM_URL_LOADER_FACTORY_H_
-#include <memory>
+#include "mojo/public/cpp/bindings/pending_remote.h"
namespace network {
namespace mojom {
@@ -62,7 +26,7 @@ class URLLoaderFactory;
namespace QtWebEngineCore {
class ProfileAdapter;
-std::unique_ptr<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter);
+mojo::PendingRemote<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter);
} // namespace QtWebEngineCore
diff --git a/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp b/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp
index d854a556c..159fa28ca 100644
--- a/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp
+++ b/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp
@@ -1,135 +1,201 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.cc
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
#include "plugin_response_interceptor_url_loader_throttle.h"
-#include "base/bind.h"
-#include "base/task/post_task.h"
-#include "content/public/browser/browser_task_traits.h"
+#include "base/functional/bind.h"
+#include "base/uuid.h"
+#include "chrome/browser/extensions/api/streams_private/streams_private_api.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/download_utils.h"
-#include "content/public/common/resource_type.h"
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
+#include "extensions/common/manifest_handlers/mime_types_handler.h"
+#include "third_party/blink/public/mojom/loader/transferrable_url_loader.mojom.h"
#include "extensions/extension_system_qt.h"
-#include "profile_adapter.h"
-#include "profile_io_data_qt.h"
-#include "profile_qt.h"
#include "web_contents_delegate_qt.h"
+#include "web_engine_settings.h"
#include <string>
+#include <tuple>
-namespace QtWebEngineCore {
-
-void onPdfStreamIntercepted(const GURL &original_url, std::string extension_id, int frame_tree_node_id)
+namespace {
+void ClearAllButFrameAncestors(network::mojom::URLResponseHead *response_head)
{
- content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
- if (!web_contents)
- return;
+ response_head->headers->RemoveHeader("Content-Security-Policy");
+ response_head->headers->RemoveHeader("Content-Security-Policy-Report-Only");
- WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate());
- if (!contentsDelegate)
+ if (!response_head->parsed_headers)
return;
- WebEngineSettings *settings = contentsDelegate->webEngineSettings();
- if (!settings->testAttribute(WebEngineSettings::PdfViewerEnabled)
- || !settings->testAttribute(WebEngineSettings::PluginsEnabled)) {
- // If the applications has been set up to always download PDF files to open them in an
- // external viewer, trigger the download.
- std::unique_ptr<download::DownloadUrlParameters> params(
- content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(web_contents, original_url,
- MISSING_TRAFFIC_ANNOTATION));
- content::BrowserContext::GetDownloadManager(web_contents->GetBrowserContext())->DownloadUrl(std::move(params));
- return;
+ std::vector<network::mojom::ContentSecurityPolicyPtr> &csp =
+ response_head->parsed_headers->content_security_policy;
+ std::vector<network::mojom::ContentSecurityPolicyPtr> cleared;
+
+ for (auto &policy : csp) {
+ auto frame_ancestors = policy->directives.find(network::mojom::CSPDirectiveName::FrameAncestors);
+ if (frame_ancestors == policy->directives.end())
+ continue;
+
+ auto cleared_policy = network::mojom::ContentSecurityPolicy::New();
+ cleared_policy->self_origin = std::move(policy->self_origin);
+ cleared_policy->header = std::move(policy->header);
+ cleared_policy->header->header_value = "";
+ cleared_policy->directives[network::mojom::CSPDirectiveName::FrameAncestors] = std::move(frame_ancestors->second);
+
+ auto raw_frame_ancestors = policy->raw_directives.find(network::mojom::CSPDirectiveName::FrameAncestors);
+ DCHECK(raw_frame_ancestors != policy->raw_directives.end());
+
+ cleared_policy->header->header_value = "frame-ancestors " + raw_frame_ancestors->second;
+ response_head->headers->AddHeader(
+ cleared_policy->header->type == network::mojom::ContentSecurityPolicyType::kEnforce
+ ? "Content-Security-Policy"
+ : "Content-Security-Policy-Report-Only",
+ cleared_policy->header->header_value);
+ cleared_policy->raw_directives[network::mojom::CSPDirectiveName::FrameAncestors] =
+ std::move(raw_frame_ancestors->second);
+
+ cleared.push_back(std::move(cleared_policy));
}
- // The URL passes the original pdf resource url, that will be requested
- // by the pdf viewer extension page.
- content::NavigationController::LoadURLParams params(
- GURL(base::StringPrintf("%s://%s/index.html?%s", extensions::kExtensionScheme,
- extension_id.c_str(), original_url.spec().c_str())));
-
- params.frame_tree_node_id = frame_tree_node_id;
- web_contents->GetController().LoadURLWithParams(params);
+ csp.swap(cleared);
}
+} // namespace
-PluginResponseInterceptorURLLoaderThrottle::PluginResponseInterceptorURLLoaderThrottle(
- content::ResourceContext *resource_context, int resource_type, int frame_tree_node_id)
- : m_resource_context(resource_context), m_resource_type(resource_type), m_frame_tree_node_id(frame_tree_node_id)
-{}
+namespace QtWebEngineCore {
PluginResponseInterceptorURLLoaderThrottle::PluginResponseInterceptorURLLoaderThrottle(
- content::BrowserContext *browser_context, int resource_type, int frame_tree_node_id)
- : m_browser_context(browser_context), m_resource_type(resource_type), m_frame_tree_node_id(frame_tree_node_id)
+ network::mojom::RequestDestination request_destination,
+ int frame_tree_node_id)
+ : m_request_destination(request_destination), m_frame_tree_node_id(frame_tree_node_id)
{}
void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL &response_url,
network::mojom::URLResponseHead *response_head,
bool *defer)
{
- Q_UNUSED(defer);
- if (content::download_utils::MustDownload(response_url, response_head->headers.get(), response_head->mime_type))
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(m_frame_tree_node_id);
+ if (!web_contents)
return;
- if (m_resource_context) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- } else {
- DCHECK(m_browser_context);
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- }
+ if (content::download_utils::MustDownload(
+ web_contents->GetBrowserContext(),
+ response_url, response_head->headers.get(), response_head->mime_type))
+ return;
std::string extension_id;
- // FIXME: We should use extensions::InfoMap in the future:
if (response_head->mime_type == "application/pdf")
extension_id = extension_misc::kPdfExtensionId;
if (extension_id.empty())
return;
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&onPdfStreamIntercepted,
- response_url,
- extension_id,
- m_frame_tree_node_id));
+ WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate());
+ if (!contentsDelegate)
+ return;
+
+ WebEngineSettings *settings = contentsDelegate->webEngineSettings();
+ if (!settings->testAttribute(QWebEngineSettings::PdfViewerEnabled)
+ || !settings->testAttribute(QWebEngineSettings::PluginsEnabled)) {
+ // PluginServiceFilterQt will inform the URLLoader about the disabled state of plugins
+ // and we can expect the download to be triggered automatically. It's unnecessary to
+ // go further and start the guest view embedding process.
+ return;
+ }
+
+ // Chrome's PDF Extension does not work properly in the face of a restrictive
+ // Content-Security-Policy, and does not currently respect the policy anyway.
+ // Ignore CSP served on a PDF response. https://crbug.com/271452
+ if (extension_id == extension_misc::kPdfExtensionId && response_head->headers)
+ ClearAllButFrameAncestors(response_head);
+
+ MimeTypesHandler::ReportUsedHandler(extension_id);
+
+ std::string view_id = base::Uuid::GenerateRandomV4().AsLowercaseString();
+ // The string passed down to the original client with the response body.
+ std::string payload = view_id;
+
+ mojo::PendingRemote<network::mojom::URLLoader> dummy_new_loader;
+ std::ignore = dummy_new_loader.InitWithNewPipeAndPassReceiver();
+ mojo::Remote<network::mojom::URLLoaderClient> new_client;
+ mojo::PendingReceiver<network::mojom::URLLoaderClient> new_client_receiver =
+ new_client.BindNewPipeAndPassReceiver();
+
+
+ uint32_t data_pipe_size = 64U;
+ // Provide the MimeHandlerView code a chance to override the payload. This is
+ // the case where the resource is handled by frame-based MimeHandlerView.
+ *defer = extensions::MimeHandlerViewAttachHelper::OverrideBodyForInterceptedResponse(
+ m_frame_tree_node_id, response_url, response_head->mime_type, view_id,
+ &payload, &data_pipe_size,
+ base::BindOnce(
+ &PluginResponseInterceptorURLLoaderThrottle::ResumeLoad,
+ weak_factory_.GetWeakPtr()));
+
+ mojo::ScopedDataPipeProducerHandle producer_handle;
+ mojo::ScopedDataPipeConsumerHandle consumer_handle;
+ CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(data_pipe_size, producer_handle, consumer_handle));
+
+ uint32_t len = static_cast<uint32_t>(payload.size());
+ CHECK_EQ(MOJO_RESULT_OK,
+ producer_handle->WriteData(
+ payload.c_str(), &len, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE));
+
+ network::URLLoaderCompletionStatus status(net::OK);
+ status.decoded_body_length = len;
+ new_client->OnComplete(status);
+
+ mojo::PendingRemote<network::mojom::URLLoader> original_loader;
+ mojo::PendingReceiver<network::mojom::URLLoaderClient> original_client;
+ mojo::ScopedDataPipeConsumerHandle body = std::move(consumer_handle);
+ delegate_->InterceptResponse(std::move(dummy_new_loader),
+ std::move(new_client_receiver),
+ &original_loader, &original_client,
+ &body);
+
+ // Make a deep copy of URLResponseHead before passing it cross-thread.
+ auto deep_copied_response = response_head->Clone();
+ if (response_head->headers) {
+ deep_copied_response->headers =
+ base::MakeRefCounted<net::HttpResponseHeaders>(
+ response_head->headers->raw_headers());
+ }
+
+ auto transferrable_loader = blink::mojom::TransferrableURLLoader::New();
+ transferrable_loader->url = GURL(
+ extensions::Extension::GetBaseURLFromExtensionId(extension_id).spec() +
+ base::Uuid::GenerateRandomV4().AsLowercaseString());
+ transferrable_loader->url_loader = std::move(original_loader);
+ transferrable_loader->url_loader_client = std::move(original_client);
+ transferrable_loader->head = std::move(deep_copied_response);
+ transferrable_loader->head->intercepted_by_plugin = true;
+ transferrable_loader->body = std::move(body);
+
+ bool embedded = m_request_destination !=
+ network::mojom::RequestDestination::kDocument;
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &extensions::StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent,
+ extension_id, view_id, embedded, m_frame_tree_node_id,
+ std::move(transferrable_loader), response_url));
+}
+
+void PluginResponseInterceptorURLLoaderThrottle::ResumeLoad()
+{
+ delegate_->Resume();
}
} // namespace QtWebEngineCore
diff --git a/src/core/net/plugin_response_interceptor_url_loader_throttle.h b/src/core/net/plugin_response_interceptor_url_loader_throttle.h
index 7b9db6490..fb3918c45 100644
--- a/src/core/net/plugin_response_interceptor_url_loader_throttle.h
+++ b/src/core/net/plugin_response_interceptor_url_loader_throttle.h
@@ -1,51 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PLUGIN_RESPONSE_INTERCEPTOR_URL_LOADER_THROTTLE_H_
#define PLUGIN_RESPONSE_INTERCEPTOR_URL_LOADER_THROTTLE_H_
-#include "base/macros.h"
+#include "base/memory/weak_ptr.h"
+#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
namespace content {
class BrowserContext;
-class ResourceContext;
}
namespace QtWebEngineCore {
@@ -53,22 +17,23 @@ namespace QtWebEngineCore {
class PluginResponseInterceptorURLLoaderThrottle : public blink::URLLoaderThrottle
{
public:
- PluginResponseInterceptorURLLoaderThrottle(content::ResourceContext *resource_context,
- int resource_type, int frame_tree_node_id);
- PluginResponseInterceptorURLLoaderThrottle(content::BrowserContext *browser_context,
- int resource_type, int frame_tree_node_id);
+ PluginResponseInterceptorURLLoaderThrottle(network::mojom::RequestDestination request_destination,
+ int frame_tree_node_id);
~PluginResponseInterceptorURLLoaderThrottle() override = default;
private:
// content::URLLoaderThrottle overrides;
void WillProcessResponse(const GURL &response_url, network::mojom::URLResponseHead *response_head, bool *defer) override;
- content::ResourceContext *m_resource_context = nullptr;
- content::BrowserContext *m_browser_context = nullptr;
- const int m_resource_type;
+ // Resumes loading for an intercepted response. This would give the extension
+ // layer chance to initialize its browser side state.
+ void ResumeLoad();
+
+ const network::mojom::RequestDestination m_request_destination;
const int m_frame_tree_node_id;
- DISALLOW_COPY_AND_ASSIGN(PluginResponseInterceptorURLLoaderThrottle);
+ base::WeakPtrFactory<PluginResponseInterceptorURLLoaderThrottle>
+ weak_factory_{this};
};
} // namespace QtWebEngineCore
diff --git a/src/core/net/proxy_config_monitor.cpp b/src/core/net/proxy_config_monitor.cpp
index a0aaf0c05..8315b7bf2 100644
--- a/src/core/net/proxy_config_monitor.cpp
+++ b/src/core/net/proxy_config_monitor.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// originally based on chrome/browser/net/proxy_config_monitor.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
@@ -46,15 +10,11 @@
#include "proxy_config_monitor.h"
#include "proxy_config_service_qt.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
-#include "build/build_config.h"
-#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
#include "content/public/browser/browser_task_traits.h"
+#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
-#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
-#include "net/proxy_resolution/proxy_resolution_service.h"
+#include "net/proxy_resolution/proxy_config_with_annotation.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include <utility>
@@ -65,9 +25,7 @@ ProxyConfigMonitor::ProxyConfigMonitor(PrefService *prefs)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- proxy_config_service_.reset(
- new ProxyConfigServiceQt(
- prefs, base::CreateSingleThreadTaskRunner({ BrowserThread::UI })));
+ proxy_config_service_.reset(new ProxyConfigServiceQt(prefs, content::GetUIThreadTaskRunner({})));
proxy_config_service_->AddObserver(this);
}
diff --git a/src/core/net/proxy_config_monitor.h b/src/core/net/proxy_config_monitor.h
index fda6a6fb9..585e4b7ed 100644
--- a/src/core/net/proxy_config_monitor.h
+++ b/src/core/net/proxy_config_monitor.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// originally based on chrome/browser/net/proxy_config_monitor.h
// Copyright 2017 The Chromium Authors. All rights reserved.
@@ -46,17 +10,11 @@
#define PROXY_CONFIG_MONITOR_H
#include <memory>
-#include <string>
-#include "base/macros.h"
-#include "build/buildflag.h"
-#include "extensions/buildflags/buildflags.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote_set.h"
#include "net/proxy_resolution/proxy_config_service.h"
#include "services/network/public/mojom/network_context.mojom-forward.h"
-#include "services/network/public/mojom/network_service.mojom-forward.h"
-#include "services/network/public/mojom/proxy_config.mojom-forward.h"
#include "services/network/public/mojom/proxy_config_with_annotation.mojom.h"
namespace net {
@@ -96,8 +54,6 @@ private:
mojo::ReceiverSet<network::mojom::ProxyConfigPollerClient> poller_receiver_set_;
mojo::RemoteSet<network::mojom::ProxyConfigClient> proxy_config_client_set_;
-
- DISALLOW_COPY_AND_ASSIGN(ProxyConfigMonitor);
};
-#endif // !PROXY_CONFIG_MONITOR_H
+#endif // PROXY_CONFIG_MONITOR_H
diff --git a/src/core/net/proxy_config_service_qt.cpp b/src/core/net/proxy_config_service_qt.cpp
index 59884961d..fcce08550 100644
--- a/src/core/net/proxy_config_service_qt.cpp
+++ b/src/core/net/proxy_config_service_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//================ Based on ChromeProxyConfigService =======================
@@ -45,23 +9,22 @@
#include "proxy_config_service_qt.h"
-#include "base/bind.h"
#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
-#include "content/public/browser/browser_thread.h"
-#include "net/proxy_resolution/proxy_resolution_service.h"
+#include "net/base/proxy_server.h"
-using content::BrowserThread;
+#include <QNetworkProxy>
net::ProxyServer ProxyConfigServiceQt::fromQNetworkProxy(const QNetworkProxy &qtProxy)
{
- net::HostPortPair hostPortPair(qtProxy.hostName().toStdString(), qtProxy.port());
+ std::string host = qtProxy.hostName().toStdString();
+ uint16_t port = qtProxy.port();
switch (qtProxy.type()) {
case QNetworkProxy::Socks5Proxy:
- return net::ProxyServer(net::ProxyServer::SCHEME_SOCKS5, hostPortPair);
+ return net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_SOCKS5, host, port);
case QNetworkProxy::HttpProxy:
case QNetworkProxy::HttpCachingProxy:
case QNetworkProxy::FtpCachingProxy:
- return net::ProxyServer(net::ProxyServer::SCHEME_HTTP, hostPortPair);
+ return net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTP, host, port);
case QNetworkProxy::NoProxy:
case QNetworkProxy::DefaultProxy:
return net::ProxyServer(net::ProxyServer::SCHEME_DIRECT, net::HostPortPair());
@@ -71,8 +34,8 @@ net::ProxyServer ProxyConfigServiceQt::fromQNetworkProxy(const QNetworkProxy &qt
}
ProxyConfigServiceQt::ProxyConfigServiceQt(PrefService *prefService,
- const scoped_refptr<base::SingleThreadTaskRunner> &taskRunner)
- : m_baseService(net::ProxyResolutionService::CreateSystemProxyConfigService(taskRunner))
+ const scoped_refptr<base::SequencedTaskRunner> &taskRunner)
+ : m_baseService(net::ProxyConfigService::CreateSystemProxyConfigService(taskRunner))
, m_usesSystemConfiguration(false)
, m_registeredObserver(false)
, m_prefState(prefService
diff --git a/src/core/net/proxy_config_service_qt.h b/src/core/net/proxy_config_service_qt.h
index c0928bc03..49c9877a5 100644
--- a/src/core/net/proxy_config_service_qt.h
+++ b/src/core/net/proxy_config_service_qt.h
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PROXY_CONFIG_SERVICE_QT_H
#define PROXY_CONFIG_SERVICE_QT_H
-#include "base/memory/ref_counted.h"
#include "base/observer_list.h"
-#include "base/single_thread_task_runner.h"
-
+#include "base/task/sequenced_task_runner.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service.h"
#include "net/proxy_resolution/proxy_config_with_annotation.h"
@@ -61,7 +23,7 @@ public:
static net::ProxyServer fromQNetworkProxy(const QNetworkProxy &);
explicit ProxyConfigServiceQt(PrefService *prefService,
- const scoped_refptr<base::SingleThreadTaskRunner> &taskRunner);
+ const scoped_refptr<base::SequencedTaskRunner> &taskRunner);
~ProxyConfigServiceQt() override;
// ProxyConfigService implementation:
@@ -97,8 +59,6 @@ private:
ProxyPrefs::ConfigState m_prefState;
SEQUENCE_CHECKER(m_sequenceChecker);
-
- DISALLOW_COPY_AND_ASSIGN(ProxyConfigServiceQt);
};
#endif // PROXY_CONFIG_SERVICE_QT_H
diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.cpp b/src/core/net/proxying_restricted_cookie_manager_qt.cpp
index 7ee6c2a15..d4d5cc4ab 100644
--- a/src/core/net/proxying_restricted_cookie_manager_qt.cpp
+++ b/src/core/net/proxying_restricted_cookie_manager_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// originally based on android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc:
// Copyright 2019 The Chromium Authors. All rights reserved.
@@ -46,61 +10,27 @@
#include "api/qwebenginecookiestore.h"
#include "api/qwebenginecookiestore_p.h"
-#include "profile_adapter.h"
-#include "profile_qt.h"
+#include "profile_io_data_qt.h"
#include "type_conversion.h"
#include "base/memory/ptr_util.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
namespace QtWebEngineCore {
-class ProxyingRestrictedCookieManagerListenerQt : public network::mojom::CookieChangeListener {
-public:
- ProxyingRestrictedCookieManagerListenerQt(const GURL &url,
- const GURL &site_for_cookies,
- const url::Origin &top_frame_origin,
- base::WeakPtr<ProxyingRestrictedCookieManagerQt> restricted_cookie_manager,
- mojo::PendingRemote<network::mojom::CookieChangeListener> client_listener)
- : url_(url)
- , site_for_cookies_(site_for_cookies)
- , top_frame_origin_(top_frame_origin)
- , restricted_cookie_manager_(restricted_cookie_manager)
- , client_listener_(std::move(client_listener))
- {}
-
- void OnCookieChange(const net::CookieChangeInfo &change) override
- {
- if (restricted_cookie_manager_ && restricted_cookie_manager_->allowCookies(url_, site_for_cookies_))
- client_listener_->OnCookieChange(change);
- }
-
-private:
- const GURL url_;
- const GURL site_for_cookies_;
- const url::Origin top_frame_origin_;
- base::WeakPtr<ProxyingRestrictedCookieManagerQt> restricted_cookie_manager_;
- mojo::Remote<network::mojom::CookieChangeListener> client_listener_;
-};
-
// static
void ProxyingRestrictedCookieManagerQt::CreateAndBind(ProfileIODataQt *profileIoData,
mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm,
- bool is_service_worker,
- int process_id,
- int frame_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&ProxyingRestrictedCookieManagerQt::CreateAndBindOnIoThread,
profileIoData,
std::move(underlying_rcm),
- is_service_worker, process_id, frame_id,
std::move(receiver)));
}
@@ -108,31 +38,21 @@ void ProxyingRestrictedCookieManagerQt::CreateAndBind(ProfileIODataQt *profileIo
// static
void ProxyingRestrictedCookieManagerQt::CreateAndBindOnIoThread(ProfileIODataQt *profileIoData,
mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm,
- bool is_service_worker,
- int process_id,
- int frame_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
auto wrapper = base::WrapUnique(new ProxyingRestrictedCookieManagerQt(
profileIoData->getWeakPtrOnIOThread(),
- std::move(underlying_rcm),
- is_service_worker, process_id, frame_id));
+ std::move(underlying_rcm)));
mojo::MakeSelfOwnedReceiver(std::move(wrapper), std::move(receiver));
}
ProxyingRestrictedCookieManagerQt::ProxyingRestrictedCookieManagerQt(
base::WeakPtr<ProfileIODataQt> profileIoData,
- mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlyingRestrictedCookieManager,
- bool is_service_worker,
- int32_t process_id,
- int32_t frame_id)
+ mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlyingRestrictedCookieManager)
: m_profileIoData(std::move(profileIoData))
, underlying_restricted_cookie_manager_(std::move(underlyingRestrictedCookieManager))
- , is_service_worker_(is_service_worker)
- , process_id_(process_id)
- , frame_id_(frame_id)
, weak_factory_(this)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
@@ -144,98 +64,99 @@ ProxyingRestrictedCookieManagerQt::~ProxyingRestrictedCookieManagerQt()
}
void ProxyingRestrictedCookieManagerQt::GetAllForUrl(const GURL &url,
- const GURL &site_for_cookies,
- const url::Origin &top_frame_origin,
+ const net::SiteForCookies &site_for_cookies,
+ const url::Origin &top_frame_origin, bool has_storage_access,
network::mojom::CookieManagerGetOptionsPtr options,
GetAllForUrlCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (allowCookies(url, site_for_cookies)) {
- underlying_restricted_cookie_manager_->GetAllForUrl(url, site_for_cookies, top_frame_origin, std::move(options), std::move(callback));
+ underlying_restricted_cookie_manager_->GetAllForUrl(url, site_for_cookies, top_frame_origin, has_storage_access,
+ std::move(options), std::move(callback));
} else {
- std::move(callback).Run(std::vector<net::CanonicalCookie>());
+ std::move(callback).Run(std::vector<net::CookieWithAccessResult>());
}
}
void ProxyingRestrictedCookieManagerQt::SetCanonicalCookie(const net::CanonicalCookie &cookie,
const GURL &url,
- const GURL &site_for_cookies, const url::Origin &top_frame_origin,
+ const net::SiteForCookies &site_for_cookies,
+ const url::Origin &top_frame_origin,
+ bool has_storage_access,
+ net::CookieInclusionStatus status,
SetCanonicalCookieCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (allowCookies(url, site_for_cookies)) {
- underlying_restricted_cookie_manager_->SetCanonicalCookie(cookie, url, site_for_cookies, top_frame_origin, std::move(callback));
+ underlying_restricted_cookie_manager_->SetCanonicalCookie(cookie, url, site_for_cookies, top_frame_origin,
+ has_storage_access, status, std::move(callback));
} else {
std::move(callback).Run(false);
}
}
void ProxyingRestrictedCookieManagerQt::AddChangeListener(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
mojo::PendingRemote<network::mojom::CookieChangeListener> listener,
AddChangeListenerCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
-
- mojo::PendingRemote<network::mojom::CookieChangeListener> proxy_listener_remote;
- auto proxy_listener =
- std::make_unique<ProxyingRestrictedCookieManagerListenerQt>(
- url, site_for_cookies, top_frame_origin,
- weak_factory_.GetWeakPtr(),
- std::move(listener));
-
- mojo::MakeSelfOwnedReceiver(std::move(proxy_listener),
- proxy_listener_remote.InitWithNewPipeAndPassReceiver());
-
- underlying_restricted_cookie_manager_->AddChangeListener(url, site_for_cookies, top_frame_origin, std::move(proxy_listener_remote), std::move(callback));
+ underlying_restricted_cookie_manager_->AddChangeListener(url, site_for_cookies, top_frame_origin, has_storage_access,
+ std::move(listener), std::move(callback));
}
void ProxyingRestrictedCookieManagerQt::SetCookieFromString(const GURL &url,
- const GURL &site_for_cookies,
- const url::Origin &top_frame_origin,
+ const net::SiteForCookies &site_for_cookies,
+ const url::Origin &top_frame_origin, bool has_storage_access,
const std::string &cookie,
SetCookieFromStringCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (allowCookies(url, site_for_cookies)) {
- underlying_restricted_cookie_manager_->SetCookieFromString(url, site_for_cookies, top_frame_origin, cookie, std::move(callback));
+ underlying_restricted_cookie_manager_->SetCookieFromString(url, site_for_cookies, top_frame_origin, has_storage_access,
+ cookie, std::move(callback));
} else {
- std::move(callback).Run();
+ std::move(callback).Run(false, false); // FIXME: is true, true in aw_proxying_restricted_cookie_manager.cc though..
}
}
void ProxyingRestrictedCookieManagerQt::GetCookiesString(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access, bool get_version_shared_memory,
GetCookiesStringCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (allowCookies(url, site_for_cookies)) {
- underlying_restricted_cookie_manager_->GetCookiesString(url, site_for_cookies, top_frame_origin, std::move(callback));
+ underlying_restricted_cookie_manager_->GetCookiesString(url, site_for_cookies, top_frame_origin,
+ has_storage_access, get_version_shared_memory,
+ std::move(callback));
} else {
- std::move(callback).Run("");
+ std::move(callback).Run(network::mojom::kInvalidCookieVersion, base::ReadOnlySharedMemoryRegion(), "");
}
}
void ProxyingRestrictedCookieManagerQt::CookiesEnabledFor(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin & /*top_frame_origin*/,
+ bool /*has_storage_access*/,
CookiesEnabledForCallback callback)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(callback).Run(allowCookies(url, site_for_cookies));
}
-bool ProxyingRestrictedCookieManagerQt::allowCookies(const GURL &url, const GURL &site_for_cookies) const
+bool ProxyingRestrictedCookieManagerQt::allowCookies(const GURL &url, const net::SiteForCookies &site_for_cookies) const
{
if (!m_profileIoData)
return false;
- return m_profileIoData->canGetCookies(toQt(site_for_cookies), toQt(url));
+ return m_profileIoData->canGetCookies(toQt(site_for_cookies.first_party_url()), toQt(url));
}
} // namespace QtWebEngineCore
diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.h b/src/core/net/proxying_restricted_cookie_manager_qt.h
index b682075ed..faf0545c3 100644
--- a/src/core/net/proxying_restricted_cookie_manager_qt.h
+++ b/src/core/net/proxying_restricted_cookie_manager_qt.h
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PROXYING_RESTRICTED_COOKIE_MANAGER_QT_H
#define PROXYING_RESTRICTED_COOKIE_MANAGER_QT_H
-#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/network/public/mojom/restricted_cookie_manager.mojom.h"
@@ -56,70 +19,64 @@ public:
// Expects to be called on the UI thread.
static void CreateAndBind(ProfileIODataQt *profileIoData,
mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm,
- bool is_service_worker,
- int process_id,
- int frame_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver);
~ProxyingRestrictedCookieManagerQt() override;
// network::mojom::RestrictedCookieManager interface:
void GetAllForUrl(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
network::mojom::CookieManagerGetOptionsPtr options,
GetAllForUrlCallback callback) override;
+
void SetCanonicalCookie(const net::CanonicalCookie& cookie,
const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
+ net::CookieInclusionStatus status,
SetCanonicalCookieCallback callback) override;
void AddChangeListener(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
mojo::PendingRemote<network::mojom::CookieChangeListener> listener,
AddChangeListenerCallback callback) override;
void SetCookieFromString(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
const std::string &cookie,
SetCookieFromStringCallback callback) override;
void GetCookiesString(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access, bool get_version_shared_memory,
GetCookiesStringCallback callback) override;
void CookiesEnabledFor(const GURL &url,
- const GURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin &top_frame_origin,
+ bool has_storage_access,
CookiesEnabledForCallback callback) override;
// Internal:
- bool allowCookies(const GURL &url, const GURL &site_for_cookies) const;
+ bool allowCookies(const GURL &url, const net::SiteForCookies &site_for_cookies) const;
private:
ProxyingRestrictedCookieManagerQt(base::WeakPtr<ProfileIODataQt> profileIoData,
- mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm,
- bool is_service_worker,
- int32_t process_id,
- int32_t frame_id);
+ mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm);
static void CreateAndBindOnIoThread(ProfileIODataQt *profileIoData,
mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm,
- bool is_service_worker,
- int process_id,
- int frame_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver);
base::WeakPtr<ProfileIODataQt> m_profileIoData;
mojo::Remote<network::mojom::RestrictedCookieManager> underlying_restricted_cookie_manager_;
- bool is_service_worker_;
- int process_id_;
- int frame_id_;
base::WeakPtrFactory<ProxyingRestrictedCookieManagerQt> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(ProxyingRestrictedCookieManagerQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/net/proxying_url_loader_factory_qt.cpp b/src/core/net/proxying_url_loader_factory_qt.cpp
index b42aa64bb..3a83ed7ea 100644
--- a/src/core/net/proxying_url_loader_factory_qt.cpp
+++ b/src/core/net/proxying_url_loader_factory_qt.cpp
@@ -1,83 +1,77 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "proxying_url_loader_factory_qt.h"
#include <utility>
-#include "base/bind.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
-#include "components/safe_browsing/common/safebrowsing_constants.h"
+#include "base/functional/bind.h"
#include "content/browser/web_contents/web_contents_impl.h"
-#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/global_request_id.h"
-#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/content_constants.h"
-#include "content/public/common/url_utils.h"
-#include "net/base/load_flags.h"
+#include "content/public/common/content_switches.h"
+#include "net/base/filename_util.h"
#include "net/http/http_status_code.h"
-#include "net/http/http_util.h"
+#include "services/network/public/cpp/cors/cors.h"
+#include "services/network/public/cpp/resource_request.h"
+#include "services/network/public/mojom/early_hints.mojom.h"
+#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h"
+#include "url/url_util.h"
+#include "url/url_util_qt.h"
#include "api/qwebengineurlrequestinfo_p.h"
-#include "profile_qt.h"
#include "type_conversion.h"
+#include "web_contents_adapter.h"
#include "web_contents_adapter_client.h"
#include "web_contents_view_qt.h"
-
-#include <QVariant>
+#include "net/resource_request_body_qt.h"
// originally based on aw_proxying_url_loader_factory.cc:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+namespace {
+ network::mojom::URLResponseHeadPtr createResponse(const network::ResourceRequest &request) {
+ const bool disable_web_security = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebSecurity);
+ network::mojom::URLResponseHeadPtr response = network::mojom::URLResponseHead::New();
+ response->response_type = network::cors::CalculateResponseType(
+ request.mode, disable_web_security || (
+ request.request_initiator && request.request_initiator->IsSameOriginWith(url::Origin::Create(request.url))));
+
+ return response;
+ }
+}
+
namespace QtWebEngineCore {
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeMainFrame, blink::mojom::ResourceType::kMainFrame)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSubFrame, blink::mojom::ResourceType::kSubFrame)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeStylesheet, blink::mojom::ResourceType::kStylesheet)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeScript, blink::mojom::ResourceType::kScript)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeImage, blink::mojom::ResourceType::kImage)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeFontResource, blink::mojom::ResourceType::kFontResource)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSubResource, blink::mojom::ResourceType::kSubResource)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeObject, blink::mojom::ResourceType::kObject)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeMedia, blink::mojom::ResourceType::kMedia)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeWorker, blink::mojom::ResourceType::kWorker)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeSharedWorker, blink::mojom::ResourceType::kSharedWorker)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePrefetch, blink::mojom::ResourceType::kPrefetch)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeFavicon, blink::mojom::ResourceType::kFavicon)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeXhr, blink::mojom::ResourceType::kXhr)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePing, blink::mojom::ResourceType::kPing)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeServiceWorker, blink::mojom::ResourceType::kServiceWorker)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeCspReport, blink::mojom::ResourceType::kCspReport)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePluginResource, blink::mojom::ResourceType::kPluginResource)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadMainFrame, blink::mojom::ResourceType::kNavigationPreloadMainFrame)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadSubFrame, blink::mojom::ResourceType::kNavigationPreloadSubFrame)
+ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeLast, blink::mojom::ResourceType::kMaxValue)
+
extern WebContentsAdapterClient::NavigationType pageTransitionToNavigationType(ui::PageTransition transition);
-static QWebEngineUrlRequestInfo::ResourceType toQt(content::ResourceType resourceType)
+static QWebEngineUrlRequestInfo::ResourceType toQt(blink::mojom::ResourceType resourceType)
{
- if (resourceType >= content::ResourceType::kMainFrame && resourceType <= content::ResourceType::kMaxValue)
+ if (resourceType >= blink::mojom::ResourceType::kMinValue && resourceType <= blink::mojom::ResourceType::kMaxValue)
return static_cast<QWebEngineUrlRequestInfo::ResourceType>(resourceType);
return QWebEngineUrlRequestInfo::ResourceTypeUnknown;
}
@@ -87,17 +81,28 @@ static QWebEngineUrlRequestInfo::NavigationType toQt(WebContentsAdapterClient::N
return static_cast<QWebEngineUrlRequestInfo::NavigationType>(navigationType);
}
+static QHash<QByteArray, QByteArray> toQt(const net::HttpRequestHeaders &headers)
+{
+ const auto vector = headers.GetHeaderVector();
+ QHash<QByteArray, QByteArray> hash;
+
+ for (const auto &header : vector) {
+ hash.insert(QByteArray::fromStdString(header.key), QByteArray::fromStdString(header.value));
+ }
+
+ return hash;
+}
+
// Handles intercepted, in-progress requests/responses, so that they can be
// controlled and modified accordingly.
class InterceptedRequest : public network::mojom::URLLoader
, public network::mojom::URLLoaderClient
{
public:
- InterceptedRequest(int process_id, uint64_t request_id, int32_t routing_id, uint32_t options,
+ InterceptedRequest(ProfileAdapter *profile_adapter,
+ int frame_tree_node_id, int32_t request_id, uint32_t options,
const network::ResourceRequest &request,
const net::MutableNetworkTrafficAnnotationTag &traffic_annotation,
- QWebEngineUrlRequestInterceptor *profile_request_interceptor,
- QWebEngineUrlRequestInterceptor *page_request_interceptor,
mojo::PendingReceiver<network::mojom::URLLoader> loader,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory);
@@ -106,24 +111,24 @@ public:
void Restart();
// network::mojom::URLLoaderClient
- void OnReceiveResponse(network::mojom::URLResponseHeadPtr head) override;
+ void OnReceiveResponse(network::mojom::URLResponseHeadPtr head, mojo::ScopedDataPipeConsumerHandle, absl::optional<mojo_base::BigBuffer>) override;
void OnReceiveRedirect(const net::RedirectInfo &redirect_info, network::mojom::URLResponseHeadPtr head) override;
void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback callback) override;
- void OnReceiveCachedMetadata(mojo_base::BigBuffer data) override;
void OnTransferSizeUpdated(int32_t transfer_size_diff) override;
- void OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body) override;
void OnComplete(const network::URLLoaderCompletionStatus &status) override;
+ void OnReceiveEarlyHints(network::mojom::EarlyHintsPtr) override {}
// network::mojom::URLLoader
void FollowRedirect(const std::vector<std::string> &removed_headers,
- const net::HttpRequestHeaders &modified_headers, const base::Optional<GURL> &new_url) override;
+ const net::HttpRequestHeaders &modified_headers,
+ const net::HttpRequestHeaders &modified_cors_exempt_headers,
+ const absl::optional<GURL> &new_url) override;
void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override;
void PauseReadingBodyFromNet() override;
void ResumeReadingBodyFromNet() override;
private:
void InterceptOnUIThread();
- void InterceptOnIOThread(base::WaitableEvent *event);
void ContinueAfterIntercept();
// This is called when the original URLLoaderClient has a connection error.
@@ -139,25 +144,39 @@ private:
void SendErrorAndCompleteImmediately(int error_code);
- const int process_id_;
- const uint64_t request_id_;
- const int32_t routing_id_;
+ content::WebContents* webContents();
+ QWebEngineUrlRequestInterceptor* getProfileInterceptor();
+ QWebEngineUrlRequestInterceptor* getPageInterceptor();
+
+ QPointer<ProfileAdapter> profile_adapter_;
+ const int frame_tree_node_id_;
+ const int32_t request_id_;
const uint32_t options_;
- bool input_stream_previously_failed_ = false;
- bool request_was_redirected_ = false;
+ bool allow_local_ = false;
+ bool allow_remote_ = true;
+ bool local_access_ = false;
+ bool remote_access_ = true;
+
+ bool loader_error_seen_ = false;
// If the |target_loader_| called OnComplete with an error this stores it.
// That way the destructor can send it to OnReceivedError if safe browsing
// error didn't occur.
int error_status_ = net::OK;
network::ResourceRequest request_;
- network::ResourceResponseHead current_response_;
+ ResourceRequestBody request_body_;
+ network::mojom::URLResponseHeadPtr current_response_;
const net::MutableNetworkTrafficAnnotationTag traffic_annotation_;
- QWebEngineUrlRequestInfo request_info_;
- QPointer<QWebEngineUrlRequestInterceptor> profile_request_interceptor_;
- QPointer<QWebEngineUrlRequestInterceptor> page_request_interceptor_;
+ struct RequestInfoDeleter
+ {
+ void operator()(QWebEngineUrlRequestInfo *ptr) const
+ { delete ptr; }
+ };
+
+ std::unique_ptr<QWebEngineUrlRequestInfo, RequestInfoDeleter> request_info_;
+
mojo::Receiver<network::mojom::URLLoader> proxied_loader_receiver_;
mojo::Remote<network::mojom::URLLoaderClient> target_client_;
mojo::Receiver<network::mojom::URLLoaderClient> proxied_client_receiver_{this};
@@ -165,35 +184,52 @@ private:
mojo::Remote<network::mojom::URLLoaderFactory> target_factory_;
base::WeakPtrFactory<InterceptedRequest> weak_factory_;
- DISALLOW_COPY_AND_ASSIGN(InterceptedRequest);
};
-InterceptedRequest::InterceptedRequest(int process_id, uint64_t request_id, int32_t routing_id, uint32_t options,
+InterceptedRequest::InterceptedRequest(ProfileAdapter *profile_adapter,
+ int frame_tree_node_id, int32_t request_id, uint32_t options,
const network::ResourceRequest &request,
const net::MutableNetworkTrafficAnnotationTag &traffic_annotation,
- QWebEngineUrlRequestInterceptor *profile_request_interceptor,
- QWebEngineUrlRequestInterceptor *page_request_interceptor,
mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory)
- : process_id_(process_id)
+ : profile_adapter_(profile_adapter)
+ , frame_tree_node_id_(frame_tree_node_id)
, request_id_(request_id)
- , routing_id_(routing_id)
, options_(options)
, request_(request)
+ , request_body_(ResourceRequestBody(request_.request_body.get()))
, traffic_annotation_(traffic_annotation)
- , profile_request_interceptor_(profile_request_interceptor)
- , page_request_interceptor_(page_request_interceptor)
, proxied_loader_receiver_(this, std::move(loader_receiver))
, target_client_(std::move(client))
, target_factory_(std::move(target_factory))
, weak_factory_(this)
{
+ const bool disable_web_security = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebSecurity);
+ current_response_ = createResponse(request_);
// If there is a client error, clean up the request.
target_client_.set_disconnect_handler(
- base::BindOnce(&InterceptedRequest::OnURLLoaderClientError, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&InterceptedRequest::OnURLLoaderClientError, base::Unretained(this)));
proxied_loader_receiver_.set_disconnect_with_reason_handler(
- base::BindOnce(&InterceptedRequest::OnURLLoaderError, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&InterceptedRequest::OnURLLoaderError, base::Unretained(this)));
+ if (!disable_web_security && request_.request_initiator) {
+ const std::vector<std::string> &localSchemes = url::GetLocalSchemes();
+ const std::string fromScheme = request_.request_initiator->GetTupleOrPrecursorTupleIfOpaque().scheme();
+ const std::string toScheme = request_.url.scheme();
+ const bool fromLocal = base::Contains(localSchemes, fromScheme);
+ const bool toLocal = base::Contains(localSchemes, toScheme);
+ bool hasLocalAccess = false;
+ local_access_ = toLocal;
+ remote_access_ = !toLocal && (toScheme != "data") && (toScheme != "qrc");
+ if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(fromScheme))
+ hasLocalAccess = cs->flags & url::CustomScheme::LocalAccessAllowed;
+ if (fromLocal || toLocal) {
+ content::WebContents *wc = webContents();
+ // local schemes must have universal access, or be accessing something local and have local access.
+ allow_local_ = hasLocalAccess || (fromLocal && wc && wc->GetOrCreateWebPreferences().allow_file_access_from_file_urls);
+ allow_remote_ = !fromLocal || (wc && wc->GetOrCreateWebPreferences().allow_remote_access_from_local_urls);
+ }
+ }
}
InterceptedRequest::~InterceptedRequest()
@@ -201,115 +237,175 @@ InterceptedRequest::~InterceptedRequest()
weak_factory_.InvalidateWeakPtrs();
}
+content::WebContents* InterceptedRequest::webContents()
+{
+ if (frame_tree_node_id_ == content::RenderFrameHost::kNoFrameTreeNodeId)
+ return nullptr;
+ return content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_);
+}
+
+QWebEngineUrlRequestInterceptor* InterceptedRequest::getProfileInterceptor()
+{
+ return profile_adapter_ ? profile_adapter_->requestInterceptor() : nullptr;
+}
+
+QWebEngineUrlRequestInterceptor* InterceptedRequest::getPageInterceptor()
+{
+ if (auto wc = webContents()) {
+ auto view = static_cast<content::WebContentsImpl *>(wc)->GetView();
+ if (WebContentsAdapterClient *client = WebContentsViewQt::from(view)->client())
+ return client->webContentsAdapter()->requestInterceptor();
+ }
+ return nullptr;
+}
+
void InterceptedRequest::Restart()
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- content::ResourceType resourceType = content::ResourceType(request_.resource_type);
- WebContentsAdapterClient::NavigationType navigationType =
- pageTransitionToNavigationType(ui::PageTransition(request_.transition_type));
- const QUrl originalUrl = toQt(request_.url);
- const QUrl initiator = request_.request_initiator.has_value() ? toQt(request_.request_initiator->GetURL()) : QUrl();
+ bool granted_special_access = false;
+ auto navigationType = toQt(pageTransitionToNavigationType(ui::PageTransition(request_.transition_type)));
+ switch (navigationType) {
+ case QWebEngineUrlRequestInfo::NavigationTypeLink:
+ case QWebEngineUrlRequestInfo::NavigationTypeTyped:
+ if (blink::mojom::ResourceType(request_.resource_type) == blink::mojom::ResourceType::kMainFrame && request_.has_user_gesture)
+ granted_special_access = true; // allow normal explicit navigation
+ break;
+ case QWebEngineUrlRequestInfo::NavigationTypeBackForward:
+ case QWebEngineUrlRequestInfo::NavigationTypeReload:
+ if (blink::mojom::ResourceType(request_.resource_type) == blink::mojom::ResourceType::kMainFrame)
+ granted_special_access = true;
+ break;
+ default:
+ break;
+ }
- content::WebContents *webContents = nullptr;
- if (process_id_) {
- content::RenderFrameHost *frameHost = content::RenderFrameHost::FromID(process_id_, request_.render_frame_id);
- webContents = content::WebContents::FromRenderFrameHost(frameHost);
- } else {
- webContents = content::WebContents::FromFrameTreeNodeId(request_.render_frame_id);
+ // Check if non-local access is allowed
+ if (!allow_remote_ && remote_access_) {
+ if (!granted_special_access) {
+ target_client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_NETWORK_ACCESS_DENIED));
+ delete this;
+ return;
+ }
+ }
+
+ // Check if local access is allowed
+ if (!allow_local_ && local_access_) {
+ // Check for specifically granted file access:
+ if (auto *frame_tree = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id_)) {
+ const int renderer_id = frame_tree->current_frame_host()->GetProcess()->GetID();
+ base::FilePath file_path;
+ if (net::FileURLToFilePath(request_.url, &file_path)) {
+ if (content::ChildProcessSecurityPolicy::GetInstance()->CanReadFile(renderer_id, file_path))
+ granted_special_access = true;
+ }
+ }
+ if (!granted_special_access) {
+ target_client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED));
+ delete this;
+ return;
+ }
+ }
+
+ // MEMO since all codepatch leading to Restart scheduled and executed as asynchronous tasks in main thread,
+ // interceptors may change in meantime and also during intercept call, so they should be resolved anew.
+ // Set here only profile's interceptor since it runs first without going to user code.
+ auto profileInterceptor = getProfileInterceptor();
+ if (!profileInterceptor && !getPageInterceptor()) {
+ ContinueAfterIntercept();
+ return;
}
- GURL top_document_url = webContents ? webContents->GetLastCommittedURL() : GURL();
+ auto resourceType = toQt(blink::mojom::ResourceType(request_.resource_type));
+ const QUrl originalUrl = toQt(request_.url);
+ const QUrl initiator = request_.request_initiator.has_value() ? toQt(request_.request_initiator->GetURL()) : QUrl();
+
+ auto wc = webContents();
+ GURL top_document_url = wc ? wc->GetVisibleURL() : GURL();
QUrl firstPartyUrl;
if (!top_document_url.is_empty())
firstPartyUrl = toQt(top_document_url);
else
- firstPartyUrl = toQt(request_.site_for_cookies); // m_topDocumentUrl can be empty for the main-frame.
-
- QWebEngineUrlRequestInfoPrivate *infoPrivate =
- new QWebEngineUrlRequestInfoPrivate(toQt(resourceType), toQt(navigationType), originalUrl, firstPartyUrl,
- initiator, QByteArray::fromStdString(request_.method));
- request_info_ = QWebEngineUrlRequestInfo(infoPrivate);
-
- // TODO: remove for Qt6
- if (profile_request_interceptor_ && profile_request_interceptor_->property("deprecated").toBool()) {
- // sync call supports depracated call of an interceptor on io thread
- base::WaitableEvent event;
- base::PostTask(FROM_HERE, { content::BrowserThread::IO },
- base::BindOnce(&InterceptedRequest::InterceptOnIOThread, base::Unretained(this), &event));
- event.Wait();
- if (request_info_.changed()) {
- ContinueAfterIntercept();
- return;
- }
- }
+ firstPartyUrl = toQt(request_.site_for_cookies.first_party_url()); // m_topDocumentUrl can be empty for the main-frame.
+
+ QHash<QByteArray, QByteArray> headers = toQt(request_.headers);
+
+ if (!request_.referrer.is_empty())
+ headers.insert("Referer", toQt(request_.referrer).toEncoded());
+
+ auto info = new QWebEngineUrlRequestInfoPrivate(
+ resourceType, navigationType, originalUrl, firstPartyUrl, initiator,
+ QByteArray::fromStdString(request_.method), &request_body_, headers);
+ Q_ASSERT(!request_info_);
+ request_info_.reset(new QWebEngineUrlRequestInfo(info));
+
InterceptOnUIThread();
ContinueAfterIntercept();
}
-void InterceptedRequest::InterceptOnIOThread(base::WaitableEvent *event)
-{
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- if (profile_request_interceptor_)
- profile_request_interceptor_->interceptRequest(request_info_);
- event->Signal();
-}
-
void InterceptedRequest::InterceptOnUIThread()
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (profile_request_interceptor_)
- profile_request_interceptor_->interceptRequest(request_info_);
+ if (auto interceptor = getProfileInterceptor())
+ interceptor->interceptRequest(*request_info_);
- if (!request_info_.changed() && page_request_interceptor_)
- page_request_interceptor_->interceptRequest(request_info_);
+ if (!request_info_->changed()) {
+ if (auto interceptor = getPageInterceptor())
+ interceptor->interceptRequest(*request_info_);
+ }
}
void InterceptedRequest::ContinueAfterIntercept()
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (request_info_.changed()) {
- if (request_info_.d_ptr->shouldBlockRequest)
- return SendErrorAndCompleteImmediately(net::ERR_BLOCKED_BY_CLIENT);
- if (request_info_.d_ptr->shouldRedirectRequest) {
- net::URLRequest::FirstPartyURLPolicy first_party_url_policy =
- request_.update_first_party_url_on_redirect ? net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
- : net::URLRequest::NEVER_CHANGE_FIRST_PARTY_URL;
- net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo(
- request_.method, request_.url, request_.site_for_cookies,
- first_party_url_policy, request_.referrer_policy, request_.referrer.spec(),
- net::HTTP_TEMPORARY_REDIRECT, toGurl(request_info_.requestUrl()), base::nullopt,
- false /*insecure_scheme_was_upgraded*/);
-
- // FIXME: Should probably create a new header.
- current_response_.encoded_data_length = 0;
- request_.method = redirectInfo.new_method;
- request_.url = redirectInfo.new_url;
- request_.site_for_cookies = redirectInfo.new_site_for_cookies;
- request_.referrer = GURL(redirectInfo.new_referrer);
- request_.referrer_policy = redirectInfo.new_referrer_policy;
- if (request_.method == net::HttpRequestHeaders::kGetMethod)
- request_.request_body = nullptr;
- target_client_->OnReceiveRedirect(redirectInfo, current_response_);
- return;
+ if (request_info_) {
+ // cleanup in scope because of delete this and it's not needed else where after
+ const auto scoped_request_info = std::move(request_info_);
+ QWebEngineUrlRequestInfoPrivate &info = *scoped_request_info->d_ptr;
+
+ for (auto header = info.extraHeaders.constBegin(); header != info.extraHeaders.constEnd(); ++header) {
+ std::string h = header.key().toStdString();
+ if (base::EqualsCaseInsensitiveASCII(h, "referer"))
+ request_.referrer = GURL(header.value().toStdString());
+ else
+ request_.headers.SetHeader(h, header.value().toStdString());
}
- if (!request_info_.d_ptr->extraHeaders.isEmpty()) {
- auto end = request_info_.d_ptr->extraHeaders.constEnd();
- for (auto header = request_info_.d_ptr->extraHeaders.constBegin(); header != end; ++header) {
- std::string h = header.key().toStdString();
- if (base::LowerCaseEqualsASCII(h, "referer")) {
- request_.referrer = GURL(header.value().toStdString());
- } else {
- request_.headers.SetHeader(h, header.value().toStdString());
- }
+ if (info.changed) {
+ if (info.shouldBlockRequest)
+ return SendErrorAndCompleteImmediately(net::ERR_BLOCKED_BY_CLIENT);
+
+ if (info.shouldRedirectRequest) {
+ net::RedirectInfo::FirstPartyURLPolicy first_party_url_policy =
+ request_.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT
+ : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL;
+ net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo(
+ request_.method, request_.url, request_.site_for_cookies,
+ first_party_url_policy, request_.referrer_policy, request_.referrer.spec(),
+ net::HTTP_TEMPORARY_REDIRECT, toGurl(info.url), absl::nullopt,
+ false /*insecure_scheme_was_upgraded*/);
+ request_.method = redirectInfo.new_method;
+ request_.url = redirectInfo.new_url;
+ request_.site_for_cookies = redirectInfo.new_site_for_cookies;
+ request_.referrer = GURL(redirectInfo.new_referrer);
+ request_.referrer_policy = redirectInfo.new_referrer_policy;
+ if (request_.method == net::HttpRequestHeaders::kGetMethod)
+ request_.request_body = nullptr;
+ // In case of multiple sequential rediredts, current_response_ has previously been moved to target_client_
+ // so we create a new one using the redirect url.
+ if (!current_response_)
+ current_response_ = createResponse(request_);
+ current_response_->encoded_data_length = 0;
+ target_client_->OnReceiveRedirect(redirectInfo, std::move(current_response_));
+ return;
}
}
}
if (!target_loader_ && target_factory_) {
- target_factory_->CreateLoaderAndStart(target_loader_.BindNewPipeAndPassReceiver(), routing_id_, request_id_,
+ loader_error_seen_ = false;
+ target_factory_->CreateLoaderAndStart(target_loader_.BindNewPipeAndPassReceiver(), request_id_,
options_, request_, proxied_client_receiver_.BindNewPipeAndPassRemote(),
traffic_annotation_);
}
@@ -317,18 +413,17 @@ void InterceptedRequest::ContinueAfterIntercept()
// URLLoaderClient methods.
-void InterceptedRequest::OnReceiveResponse(network::mojom::URLResponseHeadPtr head)
+void InterceptedRequest::OnReceiveResponse(network::mojom::URLResponseHeadPtr head, mojo::ScopedDataPipeConsumerHandle handle, absl::optional<mojo_base::BigBuffer> buffer)
{
- current_response_ = head;
+ current_response_ = head.Clone();
- target_client_->OnReceiveResponse(std::move(head));
+ target_client_->OnReceiveResponse(std::move(head), std::move(handle), std::move(buffer));
}
void InterceptedRequest::OnReceiveRedirect(const net::RedirectInfo &redirect_info, network::mojom::URLResponseHeadPtr head)
{
// TODO(timvolodine): handle redirect override.
- request_was_redirected_ = true;
- current_response_ = head;
+ current_response_ = head.Clone();
target_client_->OnReceiveRedirect(redirect_info, std::move(head));
request_.url = redirect_info.new_url;
request_.method = redirect_info.new_method;
@@ -342,21 +437,11 @@ void InterceptedRequest::OnUploadProgress(int64_t current_position, int64_t tota
target_client_->OnUploadProgress(current_position, total_size, std::move(callback));
}
-void InterceptedRequest::OnReceiveCachedMetadata(mojo_base::BigBuffer data)
-{
- target_client_->OnReceiveCachedMetadata(std::move(data));
-}
-
void InterceptedRequest::OnTransferSizeUpdated(int32_t transfer_size_diff)
{
target_client_->OnTransferSizeUpdated(transfer_size_diff);
}
-void InterceptedRequest::OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body)
-{
- target_client_->OnStartLoadingResponseBody(std::move(body));
-}
-
void InterceptedRequest::OnComplete(const network::URLLoaderCompletionStatus &status)
{
// Only wait for the original loader to possibly have a custom error if the
@@ -369,10 +454,11 @@ void InterceptedRequest::OnComplete(const network::URLLoaderCompletionStatus &st
void InterceptedRequest::FollowRedirect(const std::vector<std::string> &removed_headers,
const net::HttpRequestHeaders &modified_headers,
- const base::Optional<GURL> &new_url)
+ const net::HttpRequestHeaders &modified_cors_exempt_headers,
+ const absl::optional<GURL> &new_url)
{
if (target_loader_)
- target_loader_->FollowRedirect(removed_headers, modified_headers, new_url);
+ target_loader_->FollowRedirect(removed_headers, modified_headers, modified_cors_exempt_headers, new_url);
// If |OnURLLoaderClientError| was called then we're just waiting for the
// connection error handler of |proxied_loader_binding_|. Don't restart the
@@ -414,6 +500,8 @@ void InterceptedRequest::OnURLLoaderError(uint32_t custom_reason, const std::str
// If CallOnComplete was already called, then this object is ready to be deleted.
if (!target_client_)
delete this;
+ else
+ loader_error_seen_ = true;
}
void InterceptedRequest::CallOnComplete(const network::URLLoaderCompletionStatus &status, bool wait_for_loader_error)
@@ -427,7 +515,7 @@ void InterceptedRequest::CallOnComplete(const network::URLLoaderCompletionStatus
if (target_client_)
target_client_->OnComplete(status);
- if (proxied_loader_receiver_.is_bound() && wait_for_loader_error) {
+ if (proxied_loader_receiver_.is_bound() && wait_for_loader_error && !loader_error_seen_) {
// Since the original client is gone no need to continue loading the
// request.
proxied_client_receiver_.reset();
@@ -456,10 +544,10 @@ void InterceptedRequest::SendErrorAndCompleteImmediately(int error_code)
delete this;
}
-ProxyingURLLoaderFactoryQt::ProxyingURLLoaderFactoryQt(int process_id, QWebEngineUrlRequestInterceptor *profile, QWebEngineUrlRequestInterceptor *page,
+ProxyingURLLoaderFactoryQt::ProxyingURLLoaderFactoryQt(ProfileAdapter *adapter, int frame_tree_node_id,
mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver,
mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_info)
- : m_processId(process_id), m_profileRequestInterceptor(profile), m_pageRequestInterceptor(page), m_weakFactory(this)
+ : m_profileAdapter(adapter), m_frameTreeNodeId(frame_tree_node_id), m_weakFactory(this)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (target_factory_info) {
@@ -477,8 +565,8 @@ ProxyingURLLoaderFactoryQt::~ProxyingURLLoaderFactoryQt()
m_weakFactory.InvalidateWeakPtrs();
}
-void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t routing_id,
- int32_t request_id, uint32_t options, const network::ResourceRequest &request,
+void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id,
+ uint32_t options, const network::ResourceRequest &request,
mojo::PendingRemote<network::mojom::URLLoaderClient> url_loader_client,
const net::MutableNetworkTrafficAnnotationTag &traffic_annotation)
{
@@ -488,8 +576,8 @@ void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<netw
m_targetFactory->Clone(target_factory_clone.InitWithNewPipeAndPassReceiver());
// Will manage its own lifetime
- InterceptedRequest *req = new InterceptedRequest(m_processId, request_id, routing_id, options, request, traffic_annotation,
- m_profileRequestInterceptor, m_pageRequestInterceptor, std::move(loader),
+ InterceptedRequest *req = new InterceptedRequest(m_profileAdapter, m_frameTreeNodeId, request_id, options,
+ request, traffic_annotation, std::move(loader),
std::move(url_loader_client), std::move(target_factory_clone));
req->Restart();
}
diff --git a/src/core/net/proxying_url_loader_factory_qt.h b/src/core/net/proxying_url_loader_factory_qt.h
index 3d77856cc..904a40c2d 100644
--- a/src/core/net/proxying_url_loader_factory_qt.h
+++ b/src/core/net/proxying_url_loader_factory_qt.h
@@ -1,58 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PROXYING_URL_LOADER_FACTORY_QT_H_
#define PROXYING_URL_LOADER_FACTORY_QT_H_
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/ref_counted_delete_on_sequence.h"
#include "base/memory/weak_ptr.h"
-#include "base/optional.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
-#include "services/network/public/cpp/resource_request.h"
-#include "services/network/public/cpp/resource_response.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "url/gurl.h"
#include <QPointer>
// based on aw_proxying_url_loader_factory.h:
@@ -60,26 +16,25 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-QT_FORWARD_DECLARE_CLASS(QWebEngineUrlRequestInterceptor)
-
-namespace content {
-class ResourceContext;
+namespace network {
+struct ResourceRequest;
}
namespace QtWebEngineCore {
+class ProfileAdapter;
+
class ProxyingURLLoaderFactoryQt : public network::mojom::URLLoaderFactory
{
public:
- ProxyingURLLoaderFactoryQt(int processId, QWebEngineUrlRequestInterceptor *profile,
- QWebEngineUrlRequestInterceptor *page,
+ ProxyingURLLoaderFactoryQt(ProfileAdapter *adapter, int frameTreeNodeId,
mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver,
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_target_factory_remote);
~ProxyingURLLoaderFactoryQt() override;
void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader,
- int32_t routing_id, int32_t request_id,
+ int32_t request_id,
uint32_t options, const network::ResourceRequest &request,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
const net::MutableNetworkTrafficAnnotationTag &traffic_annotation) override;
@@ -90,14 +45,11 @@ private:
void OnTargetFactoryError();
void OnProxyBindingError();
- int m_processId;
+ QPointer<ProfileAdapter> m_profileAdapter;
+ int m_frameTreeNodeId;
mojo::ReceiverSet<network::mojom::URLLoaderFactory> m_proxyReceivers;
mojo::Remote<network::mojom::URLLoaderFactory> m_targetFactory;
- QPointer<QWebEngineUrlRequestInterceptor> m_profileRequestInterceptor;
- QPointer<QWebEngineUrlRequestInterceptor> m_pageRequestInterceptor;
base::WeakPtrFactory<ProxyingURLLoaderFactoryQt> m_weakFactory;
-
- DISALLOW_COPY_AND_ASSIGN(ProxyingURLLoaderFactoryQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/net/qrc_url_scheme_handler.cpp b/src/core/net/qrc_url_scheme_handler.cpp
index 73bf24f1d..a8b4e4388 100644
--- a/src/core/net/qrc_url_scheme_handler.cpp
+++ b/src/core/net/qrc_url_scheme_handler.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qrc_url_scheme_handler.h"
@@ -46,6 +10,8 @@
#include <QMimeDatabase>
#include <QMimeType>
+#include <memory>
+
namespace QtWebEngineCore {
void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job)
@@ -58,7 +24,7 @@ void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job)
QUrl requestUrl = job->requestUrl();
QString requestPath = requestUrl.path();
- QScopedPointer<QFile> file(new QFile(':' + requestPath, job));
+ auto file = std::make_unique<QFile>(':' + requestPath, job);
if (!file->exists() || file->size() == 0) {
qWarning("QResource '%s' not found or is empty", qUtf8Printable(requestPath));
job->fail(QWebEngineUrlRequestJob::UrlNotFound);
@@ -67,7 +33,10 @@ void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job)
QFileInfo fileInfo(*file);
QMimeDatabase mimeDatabase;
QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileInfo);
- job->reply(mimeType.name().toUtf8(), file.take());
+ if (mimeType.name() == QStringLiteral("application/x-extension-html"))
+ job->reply("text/html", file.release());
+ else
+ job->reply(mimeType.name().toUtf8(), file.release());
}
} // namespace QtWebEngineCore
diff --git a/src/core/net/qrc_url_scheme_handler.h b/src/core/net/qrc_url_scheme_handler.h
index 586147cdf..96155b05b 100644
--- a/src/core/net/qrc_url_scheme_handler.h
+++ b/src/core/net/qrc_url_scheme_handler.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QRC_URL_SCHEME_HANDLER_H
#define QRC_URL_SCHEME_HANDLER_H
diff --git a/src/core/net/resource_request_body_qt.cpp b/src/core/net/resource_request_body_qt.cpp
new file mode 100644
index 000000000..d0d54784d
--- /dev/null
+++ b/src/core/net/resource_request_body_qt.cpp
@@ -0,0 +1,181 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "resource_request_body_qt.h"
+#include "type_conversion.h"
+
+#include "services/network/public/cpp/resource_request_body.h"
+#include "services/network/public/mojom/data_pipe_getter.mojom.h"
+#include "services/network/public/mojom/url_request.mojom-shared.h"
+#include "mojo/public/cpp/bindings/remote.h"
+
+namespace QtWebEngineCore {
+
+ResourceRequestBody::ResourceRequestBody(network::ResourceRequestBody *requestBody, QObject *parent)
+ : QIODevice(parent)
+ , m_requestBody(requestBody)
+ , m_dataElementsIdx(0)
+ , m_dataElementBytesIdx(0)
+ , m_dataElementFileIdx(0)
+{};
+
+ResourceRequestBody::~ResourceRequestBody(){};
+
+qint64 ResourceRequestBody::readData(char *data, qint64 maxSize)
+{
+ if (!m_requestBody)
+ return -1;
+
+ const std::size_t dataElementsSize = m_requestBody->elements()->size();
+ if (m_dataElementsIdx == dataElementsSize)
+ return -1;
+
+ qint64 bytesRead = 0;
+ const std::vector<network::DataElement> *elements = m_requestBody->elements();
+ while (bytesRead < maxSize && m_dataElementsIdx < dataElementsSize) {
+ const network::DataElement &currentDataElement = elements->at(m_dataElementsIdx);
+
+ switch (currentDataElement.type()) {
+ case network::mojom::DataElementDataView::Tag::kBytes: {
+ readDataElementBytes(currentDataElement.As<network::DataElementBytes>().bytes(),
+ bytesRead, maxSize, &data);
+ break;
+ }
+ case network::mojom::DataElementDataView::Tag::kFile: {
+ const network::DataElementFile file = currentDataElement.As<network::DataElementFile>();
+ const qint64 offset = file.offset();
+ const qint64 length = file.length();
+ readDataElementFile(file.path(), offset, length, bytesRead, maxSize, &data);
+ break;
+ }
+ case network::mojom::DataElementDataView::Tag::kDataPipe: {
+ mojo::Remote<network::mojom::DataPipeGetter> pipeGetter;
+ pipeGetter.Bind(
+ currentDataElement.As<network::DataElementDataPipe>().CloneDataPipeGetter());
+ const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> consumerHandle =
+ getConsumerHandleFromPipeGetter(pipeGetter);
+ readDataElementPipe(consumerHandle, bytesRead, maxSize, &data);
+ break;
+ }
+ case network::mojom::DataElementDataView::Tag::kChunkedDataPipe: {
+ setErrorString(QStringLiteral("Chunked data pipe is used in request body upload, which "
+ "is currently not supported"));
+ // Nothing should come before or after DataElementChunkedDataPipe
+ return -1;
+ }
+ }
+
+ if (bytesRead == maxSize || m_dataElementsIdx == dataElementsSize)
+ break;
+ }
+
+ return bytesRead;
+}
+
+// We don't want to write, ever
+qint64 ResourceRequestBody::writeData(const char *data, qint64 maxSize)
+{
+ return -1;
+}
+
+bool ResourceRequestBody::isSequential() const
+{
+ return true;
+}
+
+void ResourceRequestBody::readDataElementBytes(const std::vector<uint8_t> &dataElement,
+ qint64 &bytesRead, const qint64 &maxSize,
+ char **data)
+{
+ const std::size_t dataElementSize = dataElement.size();
+ const std::size_t bytesToRead = std::min(dataElementSize, static_cast<std::size_t>(maxSize));
+
+ std::memcpy(*data, dataElement.data(), bytesToRead);
+ *data += bytesToRead;
+ m_dataElementBytesIdx += bytesToRead;
+ bytesRead += bytesToRead;
+
+ if (m_dataElementBytesIdx == dataElementSize) {
+ m_dataElementsIdx++;
+ m_dataElementBytesIdx = 0;
+ }
+}
+
+void ResourceRequestBody::readDataElementFile(const base::FilePath &filePath, const qint64 &offset,
+ const qint64 &length, qint64 &bytesRead,
+ const qint64 &maxSize, char **data)
+{
+ QFile file(toQt(filePath.value()));
+ const qint64 realOffset = offset + m_dataElementFileIdx;
+ const std::size_t fileSize = std::min(file.size(), length) - realOffset;
+ const std::size_t bytesToRead = std::min(fileSize, static_cast<std::size_t>(maxSize));
+
+ file.open(QFile::ReadOnly);
+ file.seek(realOffset);
+
+ std::memcpy(*data, file.read(bytesToRead).data(), bytesToRead);
+ *data += bytesToRead;
+ m_dataElementFileIdx += bytesToRead;
+ bytesRead += bytesToRead;
+
+ file.close();
+
+ if (m_dataElementFileIdx == fileSize) {
+ m_dataElementsIdx++;
+ m_dataElementFileIdx = 0;
+ }
+}
+
+mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle>
+ResourceRequestBody::getConsumerHandleFromPipeGetter(
+ mojo::Remote<network::mojom::DataPipeGetter> &pipeGetter)
+{
+ mojo::ScopedHandleBase<mojo::DataPipeProducerHandle> producerHandle;
+ mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> consumerHandle;
+ mojo::CreateDataPipe(nullptr, producerHandle, consumerHandle);
+ base::WeakPtrFactory<ResourceRequestBody> weakPtrFactory{ this };
+ pipeGetter->Read(std::move(producerHandle),
+ base::BindOnce(&ResourceRequestBody::pipeGetterOnReadComplete,
+ weakPtrFactory.GetWeakPtr()));
+
+ return consumerHandle;
+}
+
+void ResourceRequestBody::readDataElementPipe(
+ const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> &consumerHandle,
+ qint64 &bytesRead, const qint64 &maxSize, char **data)
+{
+ MojoResult result;
+ do {
+ uint32_t bytesToRead = 1;
+ result = consumerHandle->ReadData(*data, &bytesToRead, MOJO_READ_DATA_FLAG_NONE);
+
+ if (result == MOJO_RESULT_OK) {
+ *data += bytesToRead;
+ bytesRead += bytesToRead;
+ } else if (result != MOJO_RESULT_SHOULD_WAIT && result != MOJO_RESULT_FAILED_PRECONDITION) {
+ setErrorString(QString::fromLatin1("Error while reading from data pipe, skipping"
+ "remaining content of data pipe. Mojo error code: ")
+ + QString::number(result));
+ }
+ } while ((result == MOJO_RESULT_SHOULD_WAIT || result == MOJO_RESULT_OK)
+ && bytesRead < maxSize);
+
+ m_dataElementsIdx++;
+}
+
+void ResourceRequestBody::pipeGetterOnReadComplete(int32_t status, uint64_t size) { }
+
+void ResourceRequestBody::appendFilesForTest(const QString &path)
+{
+ if (!m_requestBody)
+ return;
+
+ base::FilePath filePath = toFilePath(path);
+ m_requestBody->elements_mutable()->push_back(static_cast<network::DataElement>(
+ network::DataElementFile(filePath, 0, 23, base::Time())));
+ m_requestBody->elements_mutable()->push_back(static_cast<network::DataElement>(
+ network::DataElementFile(filePath, 10, 23, base::Time())));
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/net/resource_request_body_qt.h b/src/core/net/resource_request_body_qt.h
new file mode 100644
index 000000000..717885d7d
--- /dev/null
+++ b/src/core/net/resource_request_body_qt.h
@@ -0,0 +1,70 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef RESOURCEREQUESTBODY_QT_H
+#define RESOURCEREQUESTBODY_QT_H
+
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+#include <QtCore/QIODevice>
+#include <QtCore/QFile>
+#include <QtCore/QUrl>
+
+namespace network {
+class ResourceRequestBody;
+namespace mojom {
+class DataPipeGetter;
+class ChunkedDataPipeGetter;
+}
+}
+
+namespace base {
+class FilePath;
+}
+
+namespace mojo {
+template<typename T>
+class Remote;
+template<typename T>
+class ScopedHandleBase;
+class DataPipeConsumerHandle;
+}
+
+namespace QtWebEngineCore {
+
+class Q_WEBENGINECORE_EXPORT ResourceRequestBody : public QIODevice
+{
+ Q_OBJECT
+public:
+ explicit ResourceRequestBody(network::ResourceRequestBody *requestBody,
+ QObject *parent = nullptr);
+ ~ResourceRequestBody();
+
+ qint64 readData(char *data, qint64 maxSize) override;
+ qint64 writeData(const char *data, qint64 maxSize) override;
+ bool isSequential() const override;
+
+ void appendFilesForTest(const QString &path);
+
+private:
+ network::ResourceRequestBody *const m_requestBody;
+
+ std::size_t m_dataElementsIdx;
+ std::size_t m_dataElementBytesIdx;
+ std::size_t m_dataElementFileIdx;
+
+ void readDataElementBytes(const std::vector<uint8_t> &dataElement, qint64 &bytesRead,
+ const qint64 &maxSize, char **data);
+ void readDataElementFile(const base::FilePath &filePath, const qint64 &offset,
+ const qint64 &length, qint64 &bytesRead, const qint64 &maxSize,
+ char **data);
+ mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle>
+ getConsumerHandleFromPipeGetter(mojo::Remote<network::mojom::DataPipeGetter> &pipeGetter);
+ void
+ readDataElementPipe(const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> &consumerHandle,
+ qint64 &bytesRead, const qint64 &maxSize, char **data);
+ void pipeGetterOnReadComplete(int32_t status, uint64_t size);
+};
+
+} // namespace QtWebEngineCore
+
+#endif // RESOURCEREQUESTBODY_QT_H
diff --git a/src/core/net/ssl_host_state_delegate_qt.cpp b/src/core/net/ssl_host_state_delegate_qt.cpp
index 3f3f95c83..41967f14e 100644
--- a/src/core/net/ssl_host_state_delegate_qt.cpp
+++ b/src/core/net/ssl_host_state_delegate_qt.cpp
@@ -1,47 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "base/callback.h"
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "ssl_host_state_delegate_qt.h"
-#include "type_conversion.h"
+#include "base/functional/callback.h"
namespace QtWebEngineCore {
@@ -77,7 +39,7 @@ SSLHostStateDelegateQt::SSLHostStateDelegateQt() {}
SSLHostStateDelegateQt::~SSLHostStateDelegateQt() {}
-void SSLHostStateDelegateQt::AllowCert(const std::string &host, const net::X509Certificate &cert, int error)
+void SSLHostStateDelegateQt::AllowCert(const std::string &host, const net::X509Certificate &cert, int error, content::StoragePartition *)
{
m_certPolicyforHost[host].Allow(cert, error);
}
@@ -105,7 +67,7 @@ void SSLHostStateDelegateQt::Clear(base::RepeatingCallback<bool(const std::strin
// prior to this query, otherwise false.
content::SSLHostStateDelegate::CertJudgment SSLHostStateDelegateQt::QueryPolicy(const std::string &host,
const net::X509Certificate &cert,
- int error)
+ int error, content::StoragePartition *)
{
return m_certPolicyforHost[host].Check(cert, error) ? SSLHostStateDelegate::ALLOWED : SSLHostStateDelegate::DENIED;
}
@@ -121,6 +83,16 @@ bool SSLHostStateDelegateQt::DidHostRunInsecureContent(const std::string &host,
return false;
}
+void SSLHostStateDelegateQt::AllowHttpForHost(const std::string &host, content::StoragePartition *web_contents)
+{
+ // Intentional no-op see aw_ssl_host_state_delegate
+}
+
+bool SSLHostStateDelegateQt::IsHttpAllowedForHost(const std::string &host, content::StoragePartition *web_contents)
+{
+ return false;
+}
+
// Revokes all SSL certificate error allow exceptions made by the user for
// |host|.
void SSLHostStateDelegateQt::RevokeUserAllowExceptions(const std::string &host)
@@ -132,12 +104,33 @@ void SSLHostStateDelegateQt::RevokeUserAllowExceptions(const std::string &host)
// |host|. This does not mean that *all* certificate errors are allowed, just
// that there exists an exception. To see if a particular certificate and
// error combination exception is allowed, use QueryPolicy().
-bool SSLHostStateDelegateQt::HasAllowException(const std::string &host)
+bool SSLHostStateDelegateQt::HasAllowException(const std::string &host, content::StoragePartition *)
{
auto policy_iterator = m_certPolicyforHost.find(host);
return policy_iterator != m_certPolicyforHost.end() &&
policy_iterator->second.HasAllowException();
}
+bool SSLHostStateDelegateQt::HasAllowExceptionForAnyHost(content::StoragePartition *storage_partition)
+{
+ for (auto const &it : m_certPolicyforHost) {
+ if (it.second.HasAllowException()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void SSLHostStateDelegateQt::SetHttpsEnforcementForHost(const std::string &host, bool enforce,
+ content::StoragePartition *storage_partition)
+{
+ // Intentional no-op see aw_ssl_host_state_delegate
+}
+
+bool SSLHostStateDelegateQt::IsHttpsEnforcedForHost(const std::string &host, content::StoragePartition *storage_partition)
+{
+ // Intentional no-op
+ return false;
+}
} // namespace QtWebEngineCore
diff --git a/src/core/net/ssl_host_state_delegate_qt.h b/src/core/net/ssl_host_state_delegate_qt.h
index 26e503eb5..0b3d7974c 100644
--- a/src/core/net/ssl_host_state_delegate_qt.h
+++ b/src/core/net/ssl_host_state_delegate_qt.h
@@ -1,47 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SSL_HOST_STATE_DELEGATE_QT_H
#define SSL_HOST_STATE_DELEGATE_QT_H
#include "content/public/browser/ssl_host_state_delegate.h"
-#include "profile_adapter.h"
+
+#include <map>
+#include <string>
namespace QtWebEngineCore {
@@ -66,13 +32,18 @@ public:
~SSLHostStateDelegateQt();
// content::SSLHostStateDelegate implementation:
- void AllowCert(const std::string &, const net::X509Certificate &cert, int error) override;
+ void AllowCert(const std::string &, const net::X509Certificate &cert, int error, content::StoragePartition *storage_partition) override;
void Clear(base::RepeatingCallback<bool(const std::string&)> host_filter) override;
- CertJudgment QueryPolicy(const std::string &host, const net::X509Certificate &cert, int error) override;
+ CertJudgment QueryPolicy(const std::string &host, const net::X509Certificate &cert, int error, content::StoragePartition *web_contents) override;
void HostRanInsecureContent(const std::string &host, int child_id, InsecureContentType content_type) override;
bool DidHostRunInsecureContent(const std::string &host, int child_id, InsecureContentType content_type) override;
+ void AllowHttpForHost(const std::string &host, content::StoragePartition *web_contents) override;
+ bool IsHttpAllowedForHost(const std::string &host, content::StoragePartition *web_contents) override;
+ void SetHttpsEnforcementForHost(const std::string &host, bool enforce, content::StoragePartition *storage_partition) override;
+ bool IsHttpsEnforcedForHost(const std::string &host, content::StoragePartition *web_contents) override;
void RevokeUserAllowExceptions(const std::string &host) override;
- bool HasAllowException(const std::string &host) override;
+ bool HasAllowException(const std::string &host, content::StoragePartition *web_contents) override;
+ bool HasAllowExceptionForAnyHost(content::StoragePartition *storage_partition) override;
private:
std::map<std::string, CertPolicy> m_certPolicyforHost;
diff --git a/src/core/net/system_network_context_manager.cpp b/src/core/net/system_network_context_manager.cpp
index 29cc82abf..439d1066c 100644
--- a/src/core/net/system_network_context_manager.cpp
+++ b/src/core/net/system_network_context_manager.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on chrome/browser/net/system_network_context_manager.cc:
// Copyright 2017 The Chromium Authors. All rights reserved.
@@ -44,54 +8,47 @@
#include "net/system_network_context_manager.h"
-#include <set>
-#include <unordered_map>
-#include <utility>
-
-#include "base/bind.h"
#include "base/command_line.h"
-#include "base/feature_list.h"
-#include "base/logging.h"
-#include "base/sequence_checker.h"
+#include "base/functional/bind.h"
#include "base/strings/string_split.h"
-#include "base/task/post_task.h"
-#include "base/values.h"
-#include "build/build_config.h"
#include "chrome/browser/net/chrome_mojo_proxy_resolver_factory.h"
#include "chrome/common/chrome_switches.h"
#include "components/certificate_transparency/ct_known_logs.h"
-#include "components/network_session_configurator/common/network_features.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/cors_exempt_headers.h"
+#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/browser/network_service_instance.h"
-#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
-#include "content/public/common/service_names.mojom.h"
-#include "content/public/common/user_agent.h"
-#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
-#include "net/dns/public/util.h"
+#include "crypto/sha2.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "net/base/port_util.h"
#include "net/net_buildflags.h"
-#include "net/third_party/uri_template/uri_template.h"
+#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
-#include "services/network/public/mojom/host_resolver.mojom.h"
-#include "services/network/public/mojom/url_loader_factory.mojom.h"
+#include "services/network/public/mojom/cert_verifier_service.mojom.h"
+#include "services/network/public/mojom/network_context.mojom.h"
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
-#include "url/gurl.h"
+#include "api/qwebengineglobalsettings.h"
+#include "api/qwebengineglobalsettings_p.h"
-namespace {
+#if BUILDFLAG(IS_WIN)
+#include "chrome/browser/net/chrome_mojo_proxy_resolver_win.h"
+#include "components/os_crypt/sync/os_crypt.h"
+#include "content/public/browser/network_service_util.h"
+#endif
-// The global instance of the SystemNetworkContextmanager.
-SystemNetworkContextManager *g_system_network_context_manager = nullptr;
+ASSERT_ENUMS_MATCH(net::SecureDnsMode::kSecure, QWebEngineGlobalSettings::SecureDnsMode::SecureOnly)
+ASSERT_ENUMS_MATCH(net::SecureDnsMode::kAutomatic,
+ QWebEngineGlobalSettings::SecureDnsMode::SecureWithFallback)
+ASSERT_ENUMS_MATCH(net::SecureDnsMode::kOff, QWebEngineGlobalSettings::SecureDnsMode::SystemOnly)
+
+namespace {
network::mojom::HttpAuthStaticParamsPtr CreateHttpAuthStaticParams()
{
- network::mojom::HttpAuthStaticParamsPtr auth_static_params = network::mojom::HttpAuthStaticParams::New();
-
- auth_static_params->supported_schemes = { "basic", "digest", "ntlm", "negotiate" };
+ network::mojom::HttpAuthStaticParamsPtr auth_static_params =
+ network::mojom::HttpAuthStaticParams::New();
return auth_static_params;
}
@@ -100,8 +57,10 @@ network::mojom::HttpAuthDynamicParamsPtr CreateHttpAuthDynamicParams()
{
network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params = network::mojom::HttpAuthDynamicParams::New();
+ auth_dynamic_params->allowed_schemes = { "basic", "digest", "ntlm", "negotiate" };
+
auto *command_line = base::CommandLine::ForCurrentProcess();
- auth_dynamic_params->server_allowlist = command_line->GetSwitchValueASCII(switches::kAuthServerWhitelist);
+ auth_dynamic_params->server_allowlist = command_line->GetSwitchValueASCII(switches::kAuthServerAllowlist);
// auth_dynamic_params->delegate_allowlist = command_line->GetSwitchValueASCII(switches::kAuthNegotiateDelegateWhitelist);
// auth_dynamic_params->enable_negotiate_port = command_line->HasSwitch(switches::kEnableAuthNegotiatePort);
@@ -110,6 +69,11 @@ network::mojom::HttpAuthDynamicParamsPtr CreateHttpAuthDynamicParams()
} // namespace
+namespace QtWebEngineCore {
+
+// The global instance of the SystemNetworkContextmanager.
+SystemNetworkContextManager *g_system_network_context_manager = nullptr;
+
// SharedURLLoaderFactory backed by a SystemNetworkContextManager and its
// network context. Transparently handles crashes.
class SystemNetworkContextManager::URLLoaderFactoryForSystem : public network::SharedURLLoaderFactory
@@ -123,7 +87,6 @@ public:
// mojom::URLLoaderFactory implementation:
void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> receiver,
- int32_t routing_id,
int32_t request_id,
uint32_t options,
const network::ResourceRequest &url_request,
@@ -134,7 +97,7 @@ public:
if (!manager_)
return;
manager_->GetURLLoaderFactory()->CreateLoaderAndStart(
- std::move(receiver), routing_id, request_id, options, url_request,
+ std::move(receiver), request_id, options, url_request,
std::move(client), traffic_annotation);
}
@@ -160,8 +123,6 @@ private:
SEQUENCE_CHECKER(sequence_checker_);
SystemNetworkContextManager *manager_;
-
- DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForSystem);
};
network::mojom::NetworkContext *SystemNetworkContextManager::GetContext()
@@ -199,19 +160,6 @@ scoped_refptr<network::SharedURLLoaderFactory> SystemNetworkContextManager::GetS
return shared_url_loader_factory_;
}
-void SystemNetworkContextManager::SetUp(
- network::mojom::NetworkContextRequest *network_context_request,
- network::mojom::NetworkContextParamsPtr *network_context_params, bool *stub_resolver_enabled,
- base::Optional<std::vector<network::mojom::DnsOverHttpsServerPtr>> *dns_over_https_servers,
- network::mojom::HttpAuthStaticParamsPtr *http_auth_static_params,
- network::mojom::HttpAuthDynamicParamsPtr *http_auth_dynamic_params, bool *is_quic_allowed)
-{
- *is_quic_allowed = false;
- *http_auth_static_params = CreateHttpAuthStaticParams();
- *http_auth_dynamic_params = CreateHttpAuthDynamicParams();
- // GetStubResolverConfig(local_state_, stub_resolver_enabled, dns_over_https_servers);
-}
-
// static
SystemNetworkContextManager *SystemNetworkContextManager::CreateInstance()
{
@@ -245,102 +193,167 @@ SystemNetworkContextManager::~SystemNetworkContextManager()
void SystemNetworkContextManager::OnNetworkServiceCreated(network::mojom::NetworkService *network_service)
{
+ bool is_quic_force_enabled = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableQuic);
// Disable QUIC globally
- network_service->DisableQuic();
+ if (!is_quic_force_enabled)
+ network_service->DisableQuic();
network_service->SetUpHttpAuth(CreateHttpAuthStaticParams());
network_service->ConfigureHttpAuthPrefs(CreateHttpAuthDynamicParams());
- // The system NetworkContext must be created first, since it sets
- // |primary_network_context| to true.
+#if BUILDFLAG(IS_WIN)
+ if (content::IsOutOfProcessNetworkService())
+ network_service->SetEncryptionKey(OSCrypt::GetRawEncryptionKey());
+#endif
+
+ // Configure the Certificate Transparency logs.
+ std::vector<std::pair<std::string, base::Time>> disqualified_logs =
+ certificate_transparency::GetDisqualifiedLogs();
+ std::vector<network::mojom::CTLogInfoPtr> log_list_mojo;
+ for (const auto &ct_log : certificate_transparency::GetKnownLogs()) {
+ network::mojom::CTLogInfoPtr log_info = network::mojom::CTLogInfo::New();
+ log_info->public_key = std::string(ct_log.log_key, ct_log.log_key_length);
+ log_info->id = crypto::SHA256HashString(log_info->public_key);
+ log_info->name = ct_log.log_name;
+ log_info->current_operator = ct_log.current_operator;
+
+ auto it = std::lower_bound(
+ std::begin(disqualified_logs), std::end(disqualified_logs), log_info->id,
+ [](const auto& disqualified_log, const std::string& log_id) {
+ return disqualified_log.first < log_id;
+ });
+ if (it != std::end(disqualified_logs) && it->first == log_info->id)
+ log_info->disqualified_at = it->second;
+
+ for (size_t i = 0; i < ct_log.previous_operators_length; i++) {
+ const auto& op = ct_log.previous_operators[i];
+ network::mojom::PreviousOperatorEntryPtr previous_operator =
+ network::mojom::PreviousOperatorEntry::New();
+ previous_operator->name = op.name;
+ previous_operator->end_time = op.end_time;
+ log_info->previous_operators.push_back(std::move(previous_operator));
+ }
+
+ log_list_mojo.push_back(std::move(log_info));
+ }
+ network_service->UpdateCtLogList(
+ std::move(log_list_mojo),
+ certificate_transparency::GetLogListTimestamp(),
+ base::DoNothing());
+
+ // The system NetworkContext is created first
network_service_network_context_.reset();
network_service->CreateNetworkContext(
network_service_network_context_.BindNewPipeAndPassReceiver(),
CreateNetworkContextParams());
- // Configure the stub resolver. This must be done after the system
- // NetworkContext is created, but before anything has the chance to use it.
- // bool stub_resolver_enabled;
- // base::Optional<std::vector<network::mojom::DnsOverHttpsServerPtr>> dns_over_https_servers;
- // GetStubResolverConfig(local_state_, &stub_resolver_enabled, &dns_over_https_servers);
- // content::GetNetworkService()->ConfigureStubHostResolver(stub_resolver_enabled, std::move(dns_over_https_servers));
+ // Handle --explicitly-allowed-ports
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kExplicitlyAllowedPorts)) {
+ std::vector<uint16_t> explicitly_allowed_network_ports;
+ std::string switch_value =
+ base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
+ const auto split = base::SplitStringPiece(switch_value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+ for (const auto &piece : split) {
+ int port;
+ if (!base::StringToInt(piece, &port))
+ continue;
+ if (!net::IsPortValid(port))
+ continue;
+ explicitly_allowed_network_ports.push_back(static_cast<uint16_t>(port));
+ }
+
+ network_service->SetExplicitlyAllowedPorts(explicitly_allowed_network_ports);
+ }
+
+ // The network service is a singleton that can be reinstantiated for different reasons,
+ // e.g., when the network service crashes. Therefore, we configure the stub host
+ // resolver of the network service here, each time it is instantiated, with our global
+ // DNS-Over-HTTPS settings. This ensures that the global settings don't get lost
+ // on reinstantiation and are in effect upon initial instantiation.
+ QWebEngineGlobalSettingsPrivate::instance()->configureStubHostResolver();
}
void SystemNetworkContextManager::AddSSLConfigToNetworkContextParams(network::mojom::NetworkContextParams *network_context_params)
{
network_context_params->initial_ssl_config = network::mojom::SSLConfig::New();
- network_context_params->initial_ssl_config->rev_checking_enabled = true;
network_context_params->initial_ssl_config->symantec_enforcement_disabled = true;
}
-network::mojom::NetworkContextParamsPtr SystemNetworkContextManager::CreateDefaultNetworkContextParams()
+void SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(network::mojom::NetworkContextParams *network_context_params,
+ cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params)
{
- network::mojom::NetworkContextParamsPtr network_context_params = network::mojom::NetworkContextParams::New();
- content::UpdateCorsExemptHeader(network_context_params.get());
-
network_context_params->enable_brotli = true;
- // network_context_params->user_agent = GetUserAgent();
-
// Disable referrers by default. Any consumer that enables referrers should
// respect prefs::kEnableReferrers from the appropriate pref store.
network_context_params->enable_referrers = false;
- // const base::CommandLine& command_line =
- // *base::CommandLine::ForCurrentProcess();
-
- // // TODO(eroman): Figure out why this doesn't work in single-process mode,
- // // or if it does work, now.
- // // Should be possible now that a private isolate is used.
- // // http://crbug.com/474654
- // if (!command_line.HasSwitch(switches::kWinHttpProxyResolver)) {
- // if (command_line.HasSwitch(switches::kSingleProcess)) {
- // LOG(ERROR) << "Cannot use V8 Proxy resolver in single process mode.";
- // } else {
- network_context_params->proxy_resolver_factory = ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver();
- // }
- // }
-
- // network_context_params->pac_quick_check_enabled = local_state_->GetBoolean(prefs::kQuickCheckEnabled);
+ const base::CommandLine& command_line =
+ *base::CommandLine::ForCurrentProcess();
+ if (!command_line.HasSwitch(switches::kWinHttpProxyResolver)) {
+ if (command_line.HasSwitch(switches::kSingleProcess)) {
+ LOG(ERROR) << "Cannot use V8 Proxy resolver in single process mode.";
+ } else {
+ network_context_params->proxy_resolver_factory =
+ ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver();
+ }
+ }
+#if BUILDFLAG(IS_WIN)
+ if (command_line.HasSwitch(switches::kUseSystemProxyResolver)) {
+ network_context_params->windows_system_proxy_resolver =
+ ChromeMojoProxyResolverWin::CreateWithSelfOwnedReceiver();
+ }
+#endif
// Use the SystemNetworkContextManager to populate and update SSL
// configuration. The SystemNetworkContextManager is owned by the
// BrowserProcess itself, so will only be destroyed on shutdown, at which
// point, all NetworkContexts will be destroyed as well.
- AddSSLConfigToNetworkContextParams(network_context_params.get());
-
- // CT is only enabled on Desktop platforms for now.
- network_context_params->enforce_chrome_ct_policy = true;
- for (const auto &ct_log : certificate_transparency::GetKnownLogs()) {
- // TODO(rsleevi): https://crbug.com/702062 - Remove this duplication.
- network::mojom::CTLogInfoPtr log_info = network::mojom::CTLogInfo::New();
- log_info->public_key = std::string(ct_log.log_key, ct_log.log_key_length);
- log_info->name = ct_log.log_name;
- network_context_params->ct_logs.push_back(std::move(log_info));
- }
-
- return network_context_params;
+ AddSSLConfigToNetworkContextParams(network_context_params);
}
network::mojom::NetworkContextParamsPtr SystemNetworkContextManager::CreateNetworkContextParams()
{
// TODO(mmenke): Set up parameters here (in memory cookie store, etc).
- network::mojom::NetworkContextParamsPtr network_context_params = CreateDefaultNetworkContextParams();
-
- network_context_params->context_name = std::string("system");
+ network::mojom::NetworkContextParamsPtr network_context_params = network::mojom::NetworkContextParams::New();
+ cert_verifier::mojom::CertVerifierCreationParamsPtr
+ cert_verifier_creation_params = cert_verifier::mojom::CertVerifierCreationParams::New();
+ ConfigureDefaultNetworkContextParams(network_context_params.get(), cert_verifier_creation_params.get());
network_context_params->enable_referrers = false;
network_context_params->http_cache_enabled = false;
- // These are needed for PAC scripts that use FTP URLs.
-#if !BUILDFLAG(DISABLE_FTP_SUPPORT)
- network_context_params->enable_ftp_url_support = true;
-#endif
-
- network_context_params->primary_network_context = false;
-
proxy_config_monitor_.AddToNetworkContextParams(network_context_params.get());
+ network_context_params->cert_verifier_params =
+ content::GetCertVerifierParams(std::move(cert_verifier_creation_params));
return network_context_params;
}
+
+bool isValidTemplates(std::string templates)
+{
+ absl::optional<net::DnsOverHttpsConfig> dnsOverHttpsConfig =
+ net::DnsOverHttpsConfig::FromString(templates);
+ return dnsOverHttpsConfig.has_value();
+}
+
+
+void configureStubHostResolver(QWebEngineGlobalSettings::SecureDnsMode dnsMode,
+ std::string dnsOverHttpsTemplates, bool insecureDnsClientEnabled,
+ bool additionalInsecureDnsTypesEnabled)
+{
+ if (content::IsNetworkServiceCreated()) {
+ network::mojom::NetworkService *networkService = content::GetNetworkService();
+ if (networkService) {
+ absl::optional<net::DnsOverHttpsConfig> dohConfig = dnsOverHttpsTemplates.empty()
+ ? net::DnsOverHttpsConfig()
+ : net::DnsOverHttpsConfig::FromString(dnsOverHttpsTemplates);
+ networkService->ConfigureStubHostResolver(insecureDnsClientEnabled,
+ net::SecureDnsMode(dnsMode), *dohConfig,
+ additionalInsecureDnsTypesEnabled);
+ }
+ }
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/net/system_network_context_manager.h b/src/core/net/system_network_context_manager.h
index 5094008f2..d56bdab78 100644
--- a/src/core/net/system_network_context_manager.h
+++ b/src/core/net/system_network_context_manager.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on chrome/browser/net/system_network_context_manager.h:
// Copyright 2017 The Chromium Authors. All rights reserved.
@@ -46,20 +10,17 @@
#define SYSTEM_NETWORK_CONTEXT_MANAGER_H_
#include <memory>
-#include <string>
-#include <vector>
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/optional.h"
-#include "services/network/public/mojom/host_resolver.mojom-forward.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom-forward.h"
-#include "services/network/public/mojom/ssl_config.mojom-forward.h"
-#include "services/network/public/mojom/url_loader_factory.mojom-forward.h"
-
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "net/proxy_config_monitor.h"
+namespace cert_verifier {
+namespace mojom {
+class CertVerifierCreationParams;
+}}
+
namespace network {
namespace mojom {
class URLLoaderFactory;
@@ -67,9 +28,7 @@ class URLLoaderFactory;
class SharedURLLoaderFactory;
} // namespace network
-namespace net_log {
-class NetExportFileWriter;
-}
+namespace QtWebEngineCore {
// Responsible for creating and managing access to the system NetworkContext.
// Lives on the UI thread. The NetworkContext this owns is intended for requests
@@ -105,27 +64,6 @@ public:
// Destroys the global SystemNetworkContextManager instance.
static void DeleteInstance();
- // If the network service is disabled, |network_context_request| will be for
- // the NetworkContext used by the SystemNetworkContextManager and
- // |network_context_params| as needed to set up a system NetworkContext.
- // Otherwise, this method can still be used to help set up the IOThread's
- // in-process URLRequestContext.
- //
- // Must be called before the system NetworkContext is first used.
- //
- // |stub_resolver_enabled|, |dns_over_https_servers|,
- // |http_auth_static_params|, |http_auth_dynamic_params|, and
- // |is_quic_allowed| are used to pass initial NetworkService state to the
- // caller, so the NetworkService can be configured appropriately. Using
- // NetworkService's Mojo interface to set those options would lead to races
- // with other UI->IO thread network-related tasks, since Mojo doesn't preserve
- // execution order relative to PostTasks.
- void SetUp(network::mojom::NetworkContextRequest *network_context_request,
- network::mojom::NetworkContextParamsPtr *network_context_params, bool *stub_resolver_enabled,
- base::Optional<std::vector<network::mojom::DnsOverHttpsServerPtr>> *dns_over_https_servers,
- network::mojom::HttpAuthStaticParamsPtr *http_auth_static_params,
- network::mojom::HttpAuthDynamicParamsPtr *http_auth_dynamic_params, bool *is_quic_allowed);
-
// Returns the System NetworkContext. May only be called after SetUp(). Does
// any initialization of the NetworkService that may be needed when first
// called.
@@ -151,8 +89,9 @@ public:
// SSL configuration updates.
void AddSSLConfigToNetworkContextParams(network::mojom::NetworkContextParams *network_context_params);
- // Returns default set of parameters for configuring the network service.
- network::mojom::NetworkContextParamsPtr CreateDefaultNetworkContextParams();
+ // Configures the default set of parameters for the network context.
+ void ConfigureDefaultNetworkContextParams(network::mojom::NetworkContextParams *,
+ cert_verifier::mojom::CertVerifierCreationParams *);
private:
class URLLoaderFactoryForSystem;
@@ -175,8 +114,8 @@ private:
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_;
ProxyConfigMonitor proxy_config_monitor_;
-
- DISALLOW_COPY_AND_ASSIGN(SystemNetworkContextManager);
};
+} // namespace QtWebEngineCore
+
#endif // SYSTEM_NETWORK_CONTEXT_MANAGER_H_
diff --git a/src/core/net/url_request_custom_job_delegate.cpp b/src/core/net/url_request_custom_job_delegate.cpp
index ff307bede..c877de669 100644
--- a/src/core/net/url_request_custom_job_delegate.cpp
+++ b/src/core/net/url_request_custom_job_delegate.cpp
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "url_request_custom_job_delegate.h"
#include "url_request_custom_job_proxy.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
@@ -51,16 +14,16 @@
namespace QtWebEngineCore {
-URLRequestCustomJobDelegate::URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy,
- const QUrl &url,
- const QByteArray &method,
- const QUrl &initiatorOrigin,
- const QMap<QByteArray, QByteArray> &headers)
- : m_proxy(proxy),
- m_request(url),
- m_method(method),
- m_initiatorOrigin(initiatorOrigin),
- m_requestHeaders(headers)
+URLRequestCustomJobDelegate::URLRequestCustomJobDelegate(
+ URLRequestCustomJobProxy *proxy, const QUrl &url, const QByteArray &method,
+ const QUrl &initiatorOrigin, const QMap<QByteArray, QByteArray> &headers,
+ network::ResourceRequestBody *requestBody)
+ : m_proxy(proxy)
+ , m_request(url)
+ , m_method(method)
+ , m_initiatorOrigin(initiatorOrigin)
+ , m_requestHeaders(headers)
+ , m_resourceRequestBody(ResourceRequestBody(requestBody))
{
}
@@ -88,13 +51,25 @@ QMap<QByteArray, QByteArray> URLRequestCustomJobDelegate::requestHeaders() const
return m_requestHeaders;
}
+QIODevice *URLRequestCustomJobDelegate::requestBody()
+{
+ return &m_resourceRequestBody;
+}
+
+void URLRequestCustomJobDelegate::setAdditionalResponseHeaders(
+ const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders)
+{
+ m_additionalResponseHeaders = additionalResponseHeaders;
+}
+
void URLRequestCustomJobDelegate::reply(const QByteArray &contentType, QIODevice *device)
{
if (device)
QObject::connect(device, &QIODevice::readyRead, this, &URLRequestCustomJobDelegate::slotReadyRead);
m_proxy->m_ioTaskRunner->PostTask(FROM_HERE,
- base::BindOnce(&URLRequestCustomJobProxy::reply,
- m_proxy, contentType.toStdString(),device));
+ base::BindOnce(&URLRequestCustomJobProxy::reply, m_proxy,
+ contentType.toStdString(), device,
+ std::move(m_additionalResponseHeaders)));
}
void URLRequestCustomJobDelegate::slotReadyRead()
diff --git a/src/core/net/url_request_custom_job_delegate.h b/src/core/net/url_request_custom_job_delegate.h
index 93ae39e84..63db46464 100644
--- a/src/core/net/url_request_custom_job_delegate.h
+++ b/src/core/net/url_request_custom_job_delegate.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,6 +17,7 @@
#include "base/memory/ref_counted.h"
#include "qtwebenginecoreglobal_p.h"
+#include "resource_request_body_qt.h"
#include <QMap>
#include <QObject>
@@ -60,11 +25,15 @@
QT_FORWARD_DECLARE_CLASS(QIODevice)
+namespace network {
+class ResourceRequestBody;
+}
+
namespace QtWebEngineCore {
class URLRequestCustomJobProxy;
-class Q_WEBENGINECORE_PRIVATE_EXPORT URLRequestCustomJobDelegate : public QObject
+class Q_WEBENGINECORE_EXPORT URLRequestCustomJobDelegate : public QObject
{
Q_OBJECT
public:
@@ -83,7 +52,10 @@ public:
QByteArray method() const;
QUrl initiator() const;
QMap<QByteArray, QByteArray> requestHeaders() const;
+ QIODevice *requestBody();
+ void
+ setAdditionalResponseHeaders(const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders);
void reply(const QByteArray &contentType, QIODevice *device);
void redirect(const QUrl &url);
void abort();
@@ -93,11 +65,10 @@ private Q_SLOTS:
void slotReadyRead();
private:
- URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy,
- const QUrl &url,
- const QByteArray &method,
- const QUrl &initiatorOrigin,
- const QMap<QByteArray, QByteArray> &requestHeaders);
+ URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy, const QUrl &url,
+ const QByteArray &method, const QUrl &initiatorOrigin,
+ const QMap<QByteArray, QByteArray> &requestHeaders,
+ network::ResourceRequestBody *requestBody);
friend class URLRequestCustomJobProxy;
scoped_refptr<URLRequestCustomJobProxy> m_proxy;
@@ -105,6 +76,8 @@ private:
QByteArray m_method;
QUrl m_initiatorOrigin;
const QMap<QByteArray, QByteArray> m_requestHeaders;
+ QMultiMap<QByteArray, QByteArray> m_additionalResponseHeaders;
+ ResourceRequestBody m_resourceRequestBody;
};
} // namespace
diff --git a/src/core/net/url_request_custom_job_proxy.cpp b/src/core/net/url_request_custom_job_proxy.cpp
index f734db645..0f41a3670 100644
--- a/src/core/net/url_request_custom_job_proxy.cpp
+++ b/src/core/net/url_request_custom_job_proxy.cpp
@@ -1,47 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "url_request_custom_job_proxy.h"
#include "url_request_custom_job_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
+#include "services/network/public/cpp/resource_request_body.h"
#include "api/qwebengineurlrequestjob.h"
#include "profile_adapter.h"
@@ -76,27 +41,30 @@ void URLRequestCustomJobProxy::release()
}
}
-// Fix me: this is never used
-/*
-void URLRequestCustomJobProxy::setReplyCharset(const std::string &charset)
-{
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- if (!m_job)
- return;
- m_job->m_charset = charset;
-}
-*/
-void URLRequestCustomJobProxy::reply(std::string mimeType, QIODevice *device)
+void URLRequestCustomJobProxy::reply(std::string contentType, QIODevice *device,
+ QMultiMap<QByteArray, QByteArray> additionalResponseHeaders)
{
if (!m_client)
return;
DCHECK (!m_ioTaskRunner || m_ioTaskRunner->RunsTasksInCurrentSequence());
- m_client->m_mimeType = mimeType;
+ QByteArray qcontentType = QByteArray::fromStdString(contentType).toLower();
+ const int sidx = qcontentType.indexOf(';');
+ if (sidx > 0) {
+ const int cidx = qcontentType.indexOf("charset=", sidx);
+ if (cidx > 0) {
+ m_client->m_charset = qcontentType.mid(cidx + 8).trimmed().toStdString();
+ qcontentType = qcontentType.first(sidx);
+ } else {
+ qWarning() << "QWebEngineUrlRequestJob::reply(): Unrecognized content-type format with ';'" << qcontentType;
+ }
+ }
+ m_client->m_mimeType = qcontentType.trimmed().toStdString();
m_client->m_device = device;
+ m_client->m_additionalResponseHeaders = std::move(additionalResponseHeaders);
if (m_client->m_device && !m_client->m_device->isReadable())
m_client->m_device->open(QIODevice::ReadOnly);
- if (m_client->m_firstBytePosition > 0)
+ if (m_client->m_device && m_client->m_firstBytePosition > 0)
m_client->m_device->seek(m_client->m_firstBytePosition);
qint64 deviceSize = m_client->m_device ? m_client->m_device->size() : -1;
@@ -158,8 +126,9 @@ void URLRequestCustomJobProxy::readyRead()
}
void URLRequestCustomJobProxy::initialize(GURL url, std::string method,
- base::Optional<url::Origin> initiator,
- std::map<std::string, std::string> headers)
+ absl::optional<url::Origin> initiator,
+ std::map<std::string, std::string> headers,
+ scoped_refptr<network::ResourceRequestBody> requestBody)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
Q_ASSERT(!m_delegate);
@@ -177,10 +146,9 @@ void URLRequestCustomJobProxy::initialize(GURL url, std::string method,
qHeaders.insert(toQByteArray(it->first), toQByteArray(it->second));
if (schemeHandler) {
- m_delegate = new URLRequestCustomJobDelegate(this, toQt(url),
- QByteArray::fromStdString(method),
- initiatorOrigin,
- qHeaders);
+ m_delegate =
+ new URLRequestCustomJobDelegate(this, toQt(url), QByteArray::fromStdString(method),
+ initiatorOrigin, qHeaders, requestBody.get());
QWebEngineUrlRequestJob *requestJob = new QWebEngineUrlRequestJob(m_delegate);
schemeHandler->requestStarted(requestJob);
}
diff --git a/src/core/net/url_request_custom_job_proxy.h b/src/core/net/url_request_custom_job_proxy.h
index db38083dd..65c919ed0 100644
--- a/src/core/net/url_request_custom_job_proxy.h
+++ b/src/core/net/url_request_custom_job_proxy.h
@@ -1,54 +1,23 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef URL_REQUEST_CUSTOM_JOB_PROXY_H_
#define URL_REQUEST_CUSTOM_JOB_PROXY_H_
-#include "base/memory/weak_ptr.h"
-#include "base/optional.h"
-#include "base/task_runner.h"
+#include "base/task/sequenced_task_runner.h"
+#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"
#include "url/origin.h"
#include <QtCore/QPointer>
+#include <QMap>
+#include <QByteArray>
QT_FORWARD_DECLARE_CLASS(QIODevice)
+namespace network {
+class ResourceRequestBody;
+}
+
namespace QtWebEngineCore {
class URLRequestCustomJob;
@@ -65,6 +34,7 @@ public:
public:
std::string m_mimeType;
std::string m_charset;
+ QMultiMap<QByteArray, QByteArray> m_additionalResponseHeaders;
GURL m_redirect;
QIODevice *m_device;
int64_t m_firstBytePosition;
@@ -75,7 +45,7 @@ public:
virtual void notifyAborted() = 0;
virtual void notifyStartFailure(int) = 0;
virtual void notifyReadyRead() = 0;
- virtual base::TaskRunner *taskRunner() = 0;
+ virtual base::SequencedTaskRunner *taskRunner() = 0;
};
URLRequestCustomJobProxy(Client *client,
@@ -85,12 +55,15 @@ public:
// Called from URLRequestCustomJobDelegate via post:
//void setReplyCharset(const std::string &);
- void reply(std::string mimeType, QIODevice *device);
+ void reply(std::string mimeType, QIODevice *device,
+ QMultiMap<QByteArray, QByteArray> additionalResponseHeaders);
void redirect(GURL url);
void abort();
void fail(int error);
void release();
- void initialize(GURL url, std::string method, base::Optional<url::Origin> initiatorOrigin, std::map<std::string, std::string> headers);
+ void initialize(GURL url, std::string method, absl::optional<url::Origin> initiatorOrigin,
+ std::map<std::string, std::string> headers,
+ scoped_refptr<network::ResourceRequestBody> requestBody);
void readyRead();
// IO thread owned:
@@ -101,7 +74,7 @@ public:
std::string m_scheme;
URLRequestCustomJobDelegate *m_delegate;
QPointer<ProfileAdapter> m_profileAdapter;
- scoped_refptr<base::TaskRunner> m_ioTaskRunner;
+ scoped_refptr<base::SequencedTaskRunner> m_ioTaskRunner;
};
} // namespace QtWebEngineCore
diff --git a/src/core/net/version_ui_qt.cpp b/src/core/net/version_ui_qt.cpp
new file mode 100644
index 000000000..61a89596a
--- /dev/null
+++ b/src/core/net/version_ui_qt.cpp
@@ -0,0 +1,56 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "version_ui_qt.h"
+#include "api/qtwebenginecoreglobal.h"
+#include "build/build_config.h"
+#include "base/command_line.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/browser/profiles/profile.h"
+#include "qtwebengine/grit/qt_webengine_resources.h"
+#include "services/network/public/cpp/content_security_policy/content_security_policy.h"
+
+namespace {
+const char kQtWebEngineVersion[] = "qtwebengine_version";
+const char kQtWebEngineChromiumVersion[] = "qtwebengine_chromium_version";
+const char kQtWebEngineChromiumSecurityPatchVersion[] =
+ "qtwebengine_chromium_security_patch_version";
+const char kCommandLine[] = "command_line";
+const char kQtVersionCSS[] = "qt_version.css";
+const char kQtLogo[] = "images/qt.png";
+const char kQtWebEngineLogo[] = "images/qtwebengine.png";
+}
+
+VersionUIQt::VersionUIQt(content::WebUI *web_ui) : content::WebUIController(web_ui)
+{
+
+ Profile *profile = Profile::FromWebUI(web_ui);
+ content::WebUIDataSource *html_source =
+ content::WebUIDataSource::CreateAndAdd(profile, chrome::kChromeUIVersionQtHost);
+ html_source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
+ "script-src chrome://resources 'self' 'unsafe-inline';");
+ html_source->SetDefaultResource(IDR_VERSION_UI_QT_HTML);
+ html_source->AddResourcePath(kQtVersionCSS, IDR_VERSION_UI_QT_CSS);
+ html_source->AddResourcePath(kQtLogo, IDR_QT_LOGO);
+ html_source->AddResourcePath(kQtWebEngineLogo, IDR_QTWEBENGINE_LOGO);
+
+ html_source->AddString(kQtWebEngineVersion, qWebEngineVersion());
+ html_source->AddString(kQtWebEngineChromiumVersion, qWebEngineChromiumVersion());
+ html_source->AddString(kQtWebEngineChromiumSecurityPatchVersion,
+ qWebEngineChromiumSecurityPatchVersion());
+#if BUILDFLAG(IS_WIN)
+ html_source->AddString(
+ kCommandLine,
+ base::AsString16(base::CommandLine::ForCurrentProcess()->GetCommandLineString()));
+#else
+ std::string command_line;
+ typedef std::vector<std::string> ArgvList;
+ const ArgvList &argv = base::CommandLine::ForCurrentProcess()->argv();
+ for (auto iter = argv.begin(); iter != argv.end(); iter++)
+ command_line += " " + *iter;
+ html_source->AddString(kCommandLine, command_line);
+#endif
+}
+
+VersionUIQt::~VersionUIQt() { }
diff --git a/src/core/net/version_ui_qt.h b/src/core/net/version_ui_qt.h
new file mode 100644
index 000000000..1fe8ef9e0
--- /dev/null
+++ b/src/core/net/version_ui_qt.h
@@ -0,0 +1,32 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef VERSION_UI_QT_H_
+#define VERSION_UI_QT_H_
+
+#include "build/build_config.h"
+#include "content/public/browser/web_ui_controller.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+class VersionUIQt : public content::WebUIController
+{
+public:
+ explicit VersionUIQt(content::WebUI *web_ui);
+ ~VersionUIQt() override;
+
+ VersionUIQt(const VersionUIQt &) = delete;
+ VersionUIQt &operator=(const VersionUIQt &) = delete;
+};
+
+#endif // VERSION_UI_QT_H
diff --git a/src/core/net/webui_controller_factory_qt.cpp b/src/core/net/webui_controller_factory_qt.cpp
index 27e58d75f..ed35a3e36 100644
--- a/src/core/net/webui_controller_factory_qt.cpp
+++ b/src/core/net/webui_controller_factory_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Based on chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -44,39 +8,37 @@
#include "webui_controller_factory_qt.h"
-#include "base/bind.h"
-#include "base/location.h"
-#include "base/threading/thread_task_runner_handle.h"
+#include "build_config_qt.h"
+#include "devtools_frontend_qt.h"
+#include "base/functional/bind.h"
#include "build/build_config.h"
#include "chrome/browser/accessibility/accessibility_ui.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/device_log_ui.h"
#include "chrome/browser/ui/webui/devtools_ui.h"
-#include "chrome/browser/ui/webui/quota_internals/quota_internals_ui.h"
+#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h"
+#include "chrome/browser/ui/webui/user_actions/user_actions_ui.h"
#include "chrome/common/url_constants.h"
-#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
-#include "content/public/common/content_client.h"
#include "content/public/common/url_utils.h"
#include "extensions/buildflags/buildflags.h"
#include "media/media_buildflags.h"
-#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
-#include "ui/web_dialogs/web_dialog_ui.h"
#include "url/gurl.h"
+#include "version_ui_qt.h"
-#if defined(OS_LINUX) || defined(OS_ANDROID)
+#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
#include "chrome/browser/ui/webui/sandbox/sandbox_internals_ui.h"
#endif
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+#include "chrome/browser/ui/webui/media/webrtc_logs_ui.h"
+#endif
+
// The Following WebUIs are disabled because they currently doesn't build
// or doesn't work, but would be interesting for us if they did:
// #include "chrome/browser/ui/webui/inspect_ui.h"
-// #include "chrome/browser/ui/webui/user_actions/user_actions_ui.h"
-
-// #if BUILDFLAG(ENABLE_WEBRTC)
-// #include "chrome/browser/ui/webui/media/webrtc_logs_ui.h"
-// #endif
// #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
@@ -119,26 +81,35 @@ std::unique_ptr<WebUIController> NewWebUI(WebUI *web_ui, const GURL & /*url*/)
// with it.
WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, const GURL &url)
{
+ Q_UNUSED(web_ui);
+ Q_UNUSED(profile);
// This will get called a lot to check all URLs, so do a quick check of other
// schemes to filter out most URLs.
if (!content::HasWebUIScheme(url))
- return NULL;
+ return nullptr;
// We must compare hosts only since some of the Web UIs append extra stuff
// after the host name.
- if (url.host() == chrome::kChromeUIQuotaInternalsHost)
- return &NewWebUI<QuotaInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUINetInternalsHost)
+ return &NewWebUI<NetInternalsUI>;
if (url.SchemeIs(content::kChromeDevToolsScheme)) {
- // if (!DevToolsUIBindings::IsValidFrontendURL(url))
- // return nullptr;
+ if (!QtWebEngineCore::DevToolsFrontendQt::IsValidFrontendURL(url))
+ return nullptr;
return &NewWebUI<DevToolsUI>;
}
- if (url.host() == chrome::kChromeUIAccessibilityHost)
+ if (url.host_piece() == chrome::kChromeUIAccessibilityHost)
return &NewWebUI<AccessibilityUI>;
-// if (url.host_piece() == chrome::kChromeUIUserActionsHost)
-// return &NewWebUI<UserActionsUI>;
+ if (url.host_piece() == chrome::kChromeUIUserActionsHost)
+ return &NewWebUI<UserActionsUI>;
+
+ if (url.host_piece() == chrome::kChromeUIDeviceLogHost)
+ return &NewWebUI<chromeos::DeviceLogUI>;
+
+ if (url.host_piece() == chrome::kChromeUIVersionQtHost)
+ return &NewWebUI<VersionUIQt>;
+
// if (url.host_piece() == chrome::kChromeUIInspectHost)
// return &NewWebUI<InspectUI>;
//
@@ -150,21 +121,17 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co
// if (url.host_piece() == chrome::kChromeUIExtensionsFrameHost)
// return &NewWebUI<extensions::ExtensionsUI>;
//#endif
-//#if BUILDFLAG(ENABLE_PLUGINS)
-// if (url.host_piece() == chrome::kChromeUIFlashHost)
-// return &NewWebUI<FlashUI>;
-//#endif
//#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// if (url.host_piece() == chrome::kChromeUIPrintHost &&
// !profile->GetPrefs()->GetBoolean(prefs::kPrintPreviewDisabled)) {
// return &NewWebUI<PrintPreviewUI>;
// }
//#endif
-//#if BUILDFLAG(ENABLE_WEBRTC)
-// if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost)
-// return &NewWebUI<WebRtcLogsUI>;
-//#endif
-#if defined(OS_LINUX) || defined(OS_ANDROID)
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost)
+ return &NewWebUI<WebRtcLogsUI>;
+#endif
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
if (url.host_piece() == chrome::kChromeUISandboxHost)
return &NewWebUI<SandboxInternalsUI>;
#endif
@@ -187,11 +154,6 @@ bool WebUIControllerFactoryQt::UseWebUIForURL(content::BrowserContext *browser_c
return GetWebUIType(browser_context, url) != WebUI::kNoWebUI;
}
-bool WebUIControllerFactoryQt::UseWebUIBindingsForURL(content::BrowserContext *browser_context, const GURL &url)
-{
- return UseWebUIForURL(browser_context, url);
-}
-
std::unique_ptr<WebUIController> WebUIControllerFactoryQt::CreateWebUIControllerForURL(WebUI *web_ui, const GURL &url)
{
Profile *profile = Profile::FromWebUI(web_ui);
diff --git a/src/core/net/webui_controller_factory_qt.h b/src/core/net/webui_controller_factory_qt.h
index 1cc76349b..22219dd5a 100644
--- a/src/core/net/webui_controller_factory_qt.h
+++ b/src/core/net/webui_controller_factory_qt.h
@@ -1,57 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_UI_CONTROLLER_FACTORY_QT_H_
#define WEB_UI_CONTROLLER_FACTORY_QT_H_
-#include "base/macros.h"
#include "base/memory/singleton.h"
-#include "components/favicon_base/favicon_callback.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller_factory.h"
-#include "ui/base/layout.h"
-
-class Profile;
-
-namespace base {
-class RefCountedMemory;
-}
namespace QtWebEngineCore {
@@ -60,7 +15,6 @@ class WebUIControllerFactoryQt : public content::WebUIControllerFactory
public:
content::WebUI::TypeID GetWebUIType(content::BrowserContext *browserContext, const GURL &url) override;
bool UseWebUIForURL(content::BrowserContext *browserContext, const GURL &url) override;
- bool UseWebUIBindingsForURL(content::BrowserContext *browserContext, const GURL &url) override;
std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(content::WebUI *webUi, const GURL &url) override;
static WebUIControllerFactoryQt *GetInstance();
@@ -71,8 +25,6 @@ protected:
private:
friend struct base::DefaultSingletonTraits<WebUIControllerFactoryQt>;
-
- DISALLOW_COPY_AND_ASSIGN(WebUIControllerFactoryQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/ozone/BUILD.gn b/src/core/ozone/BUILD.gn
index 4d27f8877..aa7b282ae 100644
--- a/src/core/ozone/BUILD.gn
+++ b/src/core/ozone/BUILD.gn
@@ -1,6 +1,14 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import("//ui/base/ui_features.gni")
+import("//build/config/linux/pkg_config.gni")
+
+if (use_xkbcommon) {
+ pkg_config("xkb") {
+ packages = [ "xkbcommon", "xkbfile" ]
+ }
+}
source_set("qt") {
sources = [
@@ -13,9 +21,18 @@ source_set("qt") {
deps = [
"//base",
+ "//ui/base:buildflags",
"//ui/ozone:ozone_base",
"//ui/ozone/common",
]
defines = [ "OZONE_IMPLEMENTATION" ]
+ libs = []
+ if (use_xkbcommon) {
+ configs += [ ":xkb" ]
+ }
+
+ if (ozone_platform_x11) {
+ libs += [ "X11" ]
+ }
}
diff --git a/src/core/ozone/gl_context_qt.cpp b/src/core/ozone/gl_context_qt.cpp
index 10347bdc7..0042f2bce 100644
--- a/src/core/ozone/gl_context_qt.cpp
+++ b/src/core/ozone/gl_context_qt.cpp
@@ -1,59 +1,35 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "gl_context_qt.h"
#include <QGuiApplication>
#include <QOpenGLContext>
#include <QThread>
+#include <QtGui/private/qtgui-config_p.h>
#include <qpa/qplatformnativeinterface.h>
-#include "ui/gl/gl_context_egl.h"
+
#include "ui/gl/gl_implementation.h"
+#include "ui/gl/gl_surface.h"
+
+#if defined(USE_OZONE)
+#include "ui/gl/egl_util.h"
+
+#include <QOpenGLFunctions>
+#include <QOffscreenSurface>
+
+#include <vector>
+#endif
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
+#include "ui/gl/gl_context_egl.h"
#include "ui/gl/gl_context_wgl.h"
#endif
QT_BEGIN_NAMESPACE
Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
-GLContextHelper* GLContextHelper::contextHelper = 0;
+GLContextHelper* GLContextHelper::contextHelper = nullptr;
namespace {
@@ -62,7 +38,8 @@ inline void *resourceForContext(const QByteArray &resource)
#if QT_CONFIG(opengl)
QOpenGLContext *shareContext = qt_gl_global_share_context();
if (!shareContext) {
- qFatal("QWebEngine: OpenGL resource sharing is not set up in QtQuick. Please make sure to call QtWebEngine::initialize() in your main() function.");
+ qFatal("QWebEngine: OpenGL resource sharing is not set up in QtQuick. Please make sure to "
+ "call QtWebEngineQuick::initialize() in your main() function.");
}
return qApp->platformNativeInterface()->nativeResourceForContext(resource, shareContext);
#else
@@ -95,7 +72,7 @@ void GLContextHelper::initialize()
void GLContextHelper::destroy()
{
delete contextHelper;
- contextHelper = 0;
+ contextHelper = nullptr;
}
bool GLContextHelper::initializeContextOnBrowserThread(gl::GLContext* context, gl::GLSurface* surface, gl::GLContextAttribs attribs)
@@ -123,12 +100,13 @@ void* GLContextHelper::getEGLConfig()
void* GLContextHelper::getGlXConfig()
{
- return resourceForContext(QByteArrayLiteral("glxconfig"));
+ QByteArray resource = QByteArrayLiteral("glxconfig");
+ return resourceForContext(resource);
}
void* GLContextHelper::getEGLDisplay()
{
-#ifdef Q_OS_WIN
+#if BUILDFLAG(IS_WIN)
// Windows QPA plugin does not implement resourceForIntegration for "egldisplay".
// Use resourceForContext instead.
return resourceForContext(QByteArrayLiteral("egldisplay"));
@@ -139,10 +117,12 @@ void* GLContextHelper::getEGLDisplay()
void* GLContextHelper::getXDisplay()
{
- QPlatformNativeInterface *pni = QGuiApplication::platformNativeInterface();
- if (pni)
- return pni->nativeResourceForScreen(QByteArrayLiteral("display"), qApp->primaryScreen());
+#if QT_CONFIG(xcb)
+ auto *x11app = qGuiApp->nativeInterface<QNativeInterface::QX11Application>();
+ return x11app ? x11app->display() : nullptr;
+#else
return nullptr;
+#endif
}
void* GLContextHelper::getNativeDisplay()
@@ -153,7 +133,7 @@ void* GLContextHelper::getNativeDisplay()
QFunctionPointer GLContextHelper::getGlXGetProcAddress()
{
QFunctionPointer get_proc_address = nullptr;
-#if QT_CONFIG(opengl)
+#if QT_CONFIG(xcb_glx)
if (QOpenGLContext *context = qt_gl_global_share_context()) {
get_proc_address = context->getProcAddress("glXGetProcAddress");
}
@@ -172,38 +152,251 @@ QFunctionPointer GLContextHelper::getEglGetProcAddress()
return get_proc_address;
}
+void *GLContextHelper::getGlxPlatformInterface()
+{
+#if QT_CONFIG(xcb_glx)
+ if (QOpenGLContext *context = qt_gl_global_share_context())
+ return context->nativeInterface<QNativeInterface::QGLXContext>();
+#endif
+ return nullptr;
+}
+
+void *GLContextHelper::getEglPlatformInterface()
+{
+#if QT_CONFIG(opengl) && QT_CONFIG(egl)
+ if (QOpenGLContext *context = qt_gl_global_share_context())
+ return context->nativeInterface<QNativeInterface::QEGLContext>();
+#endif
+ return nullptr;
+}
+
bool GLContextHelper::isCreateContextRobustnessSupported()
{
return contextHelper->m_robustness;
}
+#if QT_CONFIG(opengl) && defined(USE_OZONE)
+class ScopedGLContext
+{
+public:
+ ScopedGLContext()
+ : m_context(new QOpenGLContext())
+ , m_previousContext(gl::GLContext::GetCurrent())
+ , m_previousSurface(gl::GLSurface::GetCurrent())
+ {
+ if (!m_context->create()) {
+ qWarning("Failed to create OpenGL context.");
+ return;
+ }
+
+ QOffscreenSurface *surface = new QOffscreenSurface(m_context->screen(), m_context.get());
+ surface->create();
+ Q_ASSERT(surface->isValid());
+
+ if (!m_context->makeCurrent(surface)) {
+ qWarning("Failed to make OpenGL context current.");
+ return;
+ }
+ }
+
+ ~ScopedGLContext()
+ {
+ if (!m_textures.empty()) {
+ auto glFun = m_context->functions();
+ glFun->glDeleteTextures(m_textures.size(), m_textures.data());
+ }
+
+ if (m_previousContext)
+ m_previousContext->MakeCurrent(m_previousSurface);
+ }
+
+ bool isValid() const { return m_context->isValid() && (m_context->surface() != nullptr); }
+
+ EGLDisplay eglDisplay() const
+ {
+ QNativeInterface::QEGLContext *nativeInterface =
+ m_context->nativeInterface<QNativeInterface::QEGLContext>();
+ return nativeInterface->display();
+ }
+
+ EGLContext eglContext() const
+ {
+ QNativeInterface::QEGLContext *nativeInterface =
+ m_context->nativeInterface<QNativeInterface::QEGLContext>();
+ return nativeInterface->nativeContext();
+ }
+
+ uint createTexture(int width, int height)
+ {
+ auto glFun = m_context->functions();
+
+ uint glTexture;
+ glFun->glGenTextures(1, &glTexture);
+ glFun->glBindTexture(GL_TEXTURE_2D, glTexture);
+ glFun->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
+ NULL);
+ glFun->glBindTexture(GL_TEXTURE_2D, 0);
+
+ m_textures.push_back(glTexture);
+ return glTexture;
+ }
+
+private:
+ QScopedPointer<QOpenGLContext> m_context;
+ gl::GLContext *m_previousContext;
+ gl::GLSurface *m_previousSurface;
+ std::vector<uint> m_textures;
+};
+
+EGLHelper::EGLFunctions::EGLFunctions()
+{
+ const static auto getProcAddress =
+ reinterpret_cast<gl::GLGetProcAddressProc>(GLContextHelper::getEglGetProcAddress());
+
+ eglCreateImage = reinterpret_cast<PFNEGLCREATEIMAGEPROC>(getProcAddress("eglCreateImage"));
+ eglDestroyImage = reinterpret_cast<PFNEGLDESTROYIMAGEPROC>(getProcAddress("eglDestroyImage"));
+ eglGetError = reinterpret_cast<PFNEGLGETERRORPROC>(getProcAddress("eglGetError"));
+ eglExportDMABUFImageMESA = reinterpret_cast<PFNEGLEXPORTDMABUFIMAGEMESAPROC>(
+ getProcAddress("eglExportDMABUFImageMESA"));
+ eglExportDMABUFImageQueryMESA = reinterpret_cast<PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC>(
+ getProcAddress("eglExportDMABUFImageQueryMESA"));
+ eglQueryString = reinterpret_cast<PFNEGLQUERYSTRINGPROC>(getProcAddress("eglQueryString"));
+}
+
+EGLHelper *EGLHelper::instance()
+{
+ static EGLHelper eglHelper;
+ return &eglHelper;
+}
+
+EGLHelper::EGLHelper() : m_functions(new EGLHelper::EGLFunctions())
+{
+ const char *extensions = m_functions->eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
+ if (!extensions) {
+ qWarning("EGL: Failed to query EGL extensions.");
+ return;
+ }
+
+ if (strstr(extensions, "EGL_KHR_base_image")) {
+ qWarning("EGL: EGL_KHR_base_image extension is not supported.");
+ return;
+ }
+
+ auto eglDisplay = GLContextHelper::getEGLDisplay();
+ if (!eglDisplay) {
+ qWarning("EGL: No EGL display.");
+ return;
+ }
+
+ const char *displayExtensions = m_functions->eglQueryString(eglDisplay, EGL_EXTENSIONS);
+ m_isDmaBufSupported = strstr(displayExtensions, "EGL_EXT_image_dma_buf_import")
+ && strstr(displayExtensions, "EGL_EXT_image_dma_buf_import_modifiers")
+ && strstr(displayExtensions, "EGL_MESA_image_dma_buf_export");
+
+ if (m_isDmaBufSupported) {
+ // FIXME: This disables GBM for nvidia. Remove this when nvidia fixes its GBM support.
+ //
+ // "Buffer allocation and submission to DRM KMS using gbm is not currently supported."
+ // See: https://download.nvidia.com/XFree86/Linux-x86_64/550.40.07/README/kms.html
+ //
+ // Chromium uses GBM to allocate scanout buffers. Scanout requires DRM KMS. If KMS is
+ // enabled, gbm_device and gbm_buffer are created without any issues but rendering to the
+ // buffer will malfunction. It is not known how to detect this problem before rendering
+ // so we just disable GBM for nvidia.
+ const char *displayVendor = m_functions->eglQueryString(eglDisplay, EGL_VENDOR);
+ m_isDmaBufSupported = !strstr(displayVendor, "NVIDIA");
+ }
+}
+
+void EGLHelper::queryDmaBuf(const int width, const int height, int *fd, int *stride, int *offset,
+ uint64_t *modifiers)
+{
+ if (!m_isDmaBufSupported)
+ return;
+
+ ScopedGLContext context;
+ if (!context.isValid())
+ return;
+
+ EGLDisplay eglDisplay = context.eglDisplay();
+ EGLContext eglContext = context.eglContext();
+ if (!eglContext) {
+ qWarning("EGL: No EGLContext.");
+ return;
+ }
+
+ uint64_t textureId = context.createTexture(width, height);
+ EGLImage eglImage = m_functions->eglCreateImage(eglDisplay, eglContext, EGL_GL_TEXTURE_2D,
+ (EGLClientBuffer)textureId, NULL);
+ if (eglImage == EGL_NO_IMAGE) {
+ qWarning() << "EGL: Failed to create EGLImage:"
+ << ui::GetEGLErrorString(m_functions->eglGetError());
+ return;
+ }
+
+ int numPlanes = 0;
+ if (!m_functions->eglExportDMABUFImageQueryMESA(eglDisplay, eglImage, nullptr, &numPlanes,
+ modifiers))
+ qWarning() << "EGL: Failed to retrieve the pixel format of the buffer:"
+ << ui::GetEGLErrorString(m_functions->eglGetError());
+ Q_ASSERT(numPlanes == 1);
+
+ if (!m_functions->eglExportDMABUFImageMESA(eglDisplay, eglImage, fd, stride, offset))
+ qWarning() << "EGL: Failed to retrieve the dma_buf file descriptor:"
+ << ui::GetEGLErrorString(m_functions->eglGetError());
+
+ m_functions->eglDestroyImage(eglDisplay, eglImage);
+}
+
+bool EGLHelper::isDmaBufSupported()
+{
+ if (!m_isDmaBufSupported)
+ return false;
+
+ int fd = -1;
+ queryDmaBuf(2, 2, &fd, nullptr, nullptr, nullptr);
+ if (fd == -1) {
+ m_isDmaBufSupported = false;
+ return false;
+ }
+
+ close(fd);
+ return true;
+}
+#endif // QT_CONFIG(opengl) && defined(USE_OZONE)
+
QT_END_NAMESPACE
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
namespace gl {
namespace init {
-scoped_refptr<GLContext> CreateGLContext(GLShareGroup* share_group,
- GLSurface* compatible_surface,
- const GLContextAttribs& attribs)
+scoped_refptr<GLContext> CreateGLContext(GLShareGroup *share_group,
+ GLSurface *compatible_surface,
+ const GLContextAttribs &attribs)
{
- scoped_refptr<GLContext> context;
- if (GetGLImplementation() == kGLImplementationDesktopGL) {
- context = new GLContextWGL(share_group);
+ switch (GetGLImplementation()) {
+ case kGLImplementationDesktopGLCoreProfile:
+ case kGLImplementationDesktopGL: {
+ scoped_refptr<GLContext> context = new GLContextWGL(share_group);
if (!context->Initialize(compatible_surface, attribs))
return nullptr;
return context;
- } else {
- context = new GLContextEGL(share_group);
}
-
- if (!GLContextHelper::initializeContext(context.get(), compatible_surface, attribs))
+ case kGLImplementationEGLANGLE:
+ case kGLImplementationEGLGLES2:
+ return InitializeGLContext(new GLContextEGL(share_group),
+ compatible_surface, attribs);
+ case kGLImplementationDisabled:
return nullptr;
-
- return context;
+ default:
+ break;
+ }
+ Q_UNREACHABLE();
+ return nullptr;
}
} // namespace init
} // namespace gl
-#endif // defined(OS_WIN)
+#endif // BUILDFLAG(IS_WIN)
diff --git a/src/core/ozone/gl_context_qt.h b/src/core/ozone/gl_context_qt.h
index cc4f6b0d1..bd1137053 100644
--- a/src/core/ozone/gl_context_qt.h
+++ b/src/core/ozone/gl_context_qt.h
@@ -1,50 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_GL_CONTEXT_QT_H_
#define GL_GL_CONTEXT_QT_H_
#include <QObject>
+#include <QtCore/qscopedpointer.h>
+#include <QtGui/qtgui-config.h>
+
#include "ui/gl/gl_context.h"
+#if QT_CONFIG(opengl) && defined(USE_OZONE)
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#endif
+
namespace gl {
-class GLContext;
class GLSurface;
}
@@ -65,6 +36,8 @@ public:
static QFunctionPointer getGlXGetProcAddress();
static QFunctionPointer getEglGetProcAddress();
static bool isCreateContextRobustnessSupported();
+ static void *getGlxPlatformInterface();
+ static void *getEglPlatformInterface();
private:
Q_INVOKABLE bool initializeContextOnBrowserThread(gl::GLContext* context, gl::GLSurface* surface, gl::GLContextAttribs attribs);
@@ -73,6 +46,44 @@ private:
bool m_robustness = false;
};
+#if QT_CONFIG(opengl) && defined(USE_OZONE)
+#undef eglCreateImage
+#undef eglDestroyImage
+#undef eglExportDMABUFImageMESA
+#undef eglExportDMABUFImageQueryMESA
+#undef eglGetError
+#undef eglQueryString
+
+class EGLHelper
+{
+public:
+ struct EGLFunctions
+ {
+ EGLFunctions();
+
+ PFNEGLCREATEIMAGEPROC eglCreateImage;
+ PFNEGLDESTROYIMAGEPROC eglDestroyImage;
+ PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA;
+ PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC eglExportDMABUFImageQueryMESA;
+ PFNEGLGETERRORPROC eglGetError;
+ PFNEGLQUERYSTRINGPROC eglQueryString;
+ };
+
+ static EGLHelper *instance();
+
+ EGLFunctions *functions() const { return m_functions.get(); }
+ void queryDmaBuf(const int width, const int height, int *fd, int *stride, int *offset,
+ uint64_t *modifiers);
+ bool isDmaBufSupported();
+
+private:
+ EGLHelper();
+
+ QScopedPointer<EGLFunctions> m_functions;
+ bool m_isDmaBufSupported = false;
+};
+#endif // QT_CONFIG(opengl) && defined(USE_OZONE)
+
QT_END_NAMESPACE
#endif
diff --git a/src/core/ozone/gl_ozone_egl_qt.cpp b/src/core/ozone/gl_ozone_egl_qt.cpp
index c692920cf..26d11df31 100644
--- a/src/core/ozone/gl_ozone_egl_qt.cpp
+++ b/src/core/ozone/gl_ozone_egl_qt.cpp
@@ -1,140 +1,70 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#if defined(USE_OZONE)
-#include "gl_ozone_egl_qt.h"
-#include "gl_context_qt.h"
-#include "gl_surface_egl_qt.h"
-#include "base/files/file_path.h"
-#include "base/native_library.h"
#include "gl_context_qt.h"
#include "gl_ozone_egl_qt.h"
-#include "ui/gl/gl_context_egl.h"
-#include "ui/gl/gl_implementation.h"
-#include "ui/gl/gl_surface.h"
-#include "ui/gl/init/gl_factory.h"
-#include "ui/gl/init/gl_initializer.h"
-
-
-#include <EGL/egl.h>
-#include <dlfcn.h>
-
-#include <QtGui/qtgui-config.h>
+#include "gl_surface_egl_qt.h"
-#if QT_CONFIG(opengl)
-#include <QOpenGLContext>
-QT_BEGIN_NAMESPACE
-Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
-QT_END_NAMESPACE
-#endif
+#include "media/gpu/buildflags.h"
+#include "ui/gl/gl_bindings.h"
+#include "ui/gl/gl_display.h"
+#include "ui/gl/gl_surface.h"
+#include "ui/gl/gl_utils.h"
+#include "ui/ozone/common/native_pixmap_egl_binding.h"
namespace ui {
-base::NativeLibrary LoadLibrary(const base::FilePath& filename) {
- base::NativeLibraryLoadError error;
- base::NativeLibrary library = base::LoadNativeLibrary(filename, &error);
- if (!library) {
- LOG(ERROR) << "Failed to load " << filename.MaybeAsASCII() << ": " << error.ToString();
- return NULL;
- }
- return library;
-}
-
-bool GLOzoneEGLQt::LoadGLES2Bindings(gl::GLImplementation /*implementation*/)
+bool LoadQtEGLBindings()
{
- base::NativeLibrary eglgles2Library = dlopen(NULL, RTLD_LAZY);
- if (!eglgles2Library) {
- LOG(ERROR) << "Failed to open EGL/GLES2 context " << dlerror();
- return false;
- }
-
- gl::GLGetProcAddressProc get_proc_address =
- reinterpret_cast<gl::GLGetProcAddressProc>(
- base::GetFunctionPointerFromNativeLibrary(eglgles2Library,
- "eglGetProcAddress"));
-#if QT_CONFIG(opengl)
- if (!get_proc_address) {
- // QTBUG-63341 most likely libgles2 not linked with libegl -> fallback to qpa
- if (QOpenGLContext *context = qt_gl_global_share_context()) {
- get_proc_address = reinterpret_cast<gl::GLGetProcAddressProc>(
- context->getProcAddress("eglGetProcAddress"));
- }
- }
-#endif
-
+ gl::GLGetProcAddressProc get_proc_address = reinterpret_cast<gl::GLGetProcAddressProc>(GLContextHelper::getEglGetProcAddress());
if (!get_proc_address) {
LOG(ERROR) << "eglGetProcAddress not found.";
- base::UnloadNativeLibrary(eglgles2Library);
return false;
}
-
gl::SetGLGetProcAddressProc(get_proc_address);
- gl::AddGLNativeLibrary(eglgles2Library);
return true;
}
-bool GLOzoneEGLQt::InitializeGLOneOffPlatform()
+bool GLOzoneEGLQt::LoadGLES2Bindings(const gl::GLImplementationParts & /*implementation*/)
{
- if (!gl::GLSurfaceEGLQt::InitializeOneOff()) {
- LOG(ERROR) << "GLOzoneEGLQt::InitializeOneOff failed.";
- return false;
+ return LoadQtEGLBindings();
+}
+
+gl::GLDisplay *GLOzoneEGLQt::InitializeGLOneOffPlatform(bool supports_angle,
+ std::vector<gl::DisplayType> init_displays,
+ gl::GpuPreference gpu_preference)
+{
+ if (auto display = gl::GLSurfaceEGLQt::InitializeOneOff(gpu_preference)) {
+ if (!static_cast<gl::GLDisplayEGL*>(display)->Initialize(supports_angle, std::move(init_displays), GetNativeDisplay())) {
+ LOG(ERROR) << "GLDisplayEGL::Initialize failed.";
+ return nullptr;
+ }
+ return display;
}
- return true;
+ return nullptr;
}
-bool GLOzoneEGLQt::InitializeExtensionSettingsOneOffPlatform()
+
+bool GLOzoneEGLQt::InitializeExtensionSettingsOneOffPlatform(gl::GLDisplay *display)
{
- return gl::GLSurfaceEGLQt::InitializeExtensionSettingsOneOff();
+ return static_cast<gl::GLDisplayEGL*>(display)->InitializeExtensionSettings();
}
-scoped_refptr<gl::GLSurface> GLOzoneEGLQt::CreateViewGLSurface(gfx::AcceleratedWidget window)
+scoped_refptr<gl::GLSurface> GLOzoneEGLQt::CreateViewGLSurface(gl::GLDisplay* display, gfx::AcceleratedWidget window)
{
+ Q_UNUSED(display);
+ Q_UNUSED(window);
return nullptr;
}
-scoped_refptr<gl::GLSurface> GLOzoneEGLQt::CreateOffscreenGLSurface(const gfx::Size &size)
+scoped_refptr<gl::GLSurface> GLOzoneEGLQt::CreateOffscreenGLSurface(gl::GLDisplay* display, const gfx::Size &size)
{
- scoped_refptr<gl::GLSurface> surface = new gl::GLSurfaceEGLQt(size);
+ scoped_refptr<gl::GLSurface> surface = new gl::GLSurfaceEGLQt(static_cast<gl::GLDisplayEGL*>(display), size);
if (surface->Initialize(gl::GLSurfaceFormat()))
return surface;
- surface = new gl::GLSurfacelessQtEGL(size);
+ surface = new gl::GLSurfacelessQtEGL(static_cast<gl::GLDisplayEGL*>(display), size);
if (surface->Initialize(gl::GLSurfaceFormat()))
return surface;
@@ -142,14 +72,29 @@ scoped_refptr<gl::GLSurface> GLOzoneEGLQt::CreateOffscreenGLSurface(const gfx::S
return nullptr;
}
-intptr_t GLOzoneEGLQt::GetNativeDisplay()
+gl::EGLDisplayPlatform GLOzoneEGLQt::GetNativeDisplay()
{
static void *display = GLContextHelper::getNativeDisplay();
+ static gl::EGLDisplayPlatform platform(display ? reinterpret_cast<intptr_t>(display) : EGL_DEFAULT_DISPLAY);
+ return platform;
+}
- if (display)
- return reinterpret_cast<intptr_t>(display);
+bool GLOzoneEGLQt::CanImportNativePixmap()
+{
+ return gl::GLSurfaceEGL::GetGLDisplayEGL()->ext->b_EGL_EXT_image_dma_buf_import;
+}
- return reinterpret_cast<intptr_t>(EGL_DEFAULT_DISPLAY);
+std::unique_ptr<NativePixmapGLBinding> GLOzoneEGLQt::ImportNativePixmap(
+ scoped_refptr<gfx::NativePixmap> pixmap,
+ gfx::BufferFormat plane_format,
+ gfx::BufferPlane plane,
+ gfx::Size plane_size,
+ const gfx::ColorSpace &color_space,
+ GLenum target,
+ GLuint texture_id)
+{
+ return NativePixmapEGLBinding::Create(pixmap, plane_format, plane, plane_size, color_space,
+ target, texture_id);
}
} // namespace ui
diff --git a/src/core/ozone/gl_ozone_egl_qt.h b/src/core/ozone/gl_ozone_egl_qt.h
index c24d03a81..7ac55979a 100644
--- a/src/core/ozone/gl_ozone_egl_qt.h
+++ b/src/core/ozone/gl_ozone_egl_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_OZONE_EGL_QT
#define GL_OZONE_EGL_QT
@@ -48,20 +12,33 @@ namespace ui {
class GLOzoneEGLQt : public GLOzoneEGL {
public:
- bool InitializeGLOneOffPlatform() override;
- bool InitializeExtensionSettingsOneOffPlatform() override;
+ gl::GLDisplay *InitializeGLOneOffPlatform(bool supports_angle,
+ std::vector<gl::DisplayType> init_displays,
+ gl::GpuPreference gpu_preference) override;
+ bool InitializeExtensionSettingsOneOffPlatform(gl::GLDisplay *display) override;
scoped_refptr<gl::GLSurface> CreateViewGLSurface(
+ gl::GLDisplay *display,
gfx::AcceleratedWidget window) override;
scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface(
- const gfx::Size& size) override;
+ gl::GLDisplay *display,
+ const gfx::Size &size) override;
+ bool CanImportNativePixmap() override;
+ std::unique_ptr<NativePixmapGLBinding> ImportNativePixmap(
+ scoped_refptr<gfx::NativePixmap> pixmap,
+ gfx::BufferFormat plane_format,
+ gfx::BufferPlane plane,
+ gfx::Size plane_size,
+ const gfx::ColorSpace &color_space,
+ GLenum target,
+ GLuint texture_id) override;
protected:
// Returns native platform display handle. This is used to obtain the EGL
// display connection for the native display.
- intptr_t GetNativeDisplay() override;
+ gl::EGLDisplayPlatform GetNativeDisplay() override;
// Sets up GL bindings for the native surface.
- bool LoadGLES2Bindings(gl::GLImplementation implementation) override;
+ bool LoadGLES2Bindings(const gl::GLImplementationParts &implementation) override;
};
} // namespace ui
diff --git a/src/core/ozone/gl_ozone_glx_qt.cpp b/src/core/ozone/gl_ozone_glx_qt.cpp
index 0c54299ba..23ba92ea4 100644
--- a/src/core/ozone/gl_ozone_glx_qt.cpp
+++ b/src/core/ozone/gl_ozone_glx_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -45,23 +9,25 @@
#include "gl_ozone_glx_qt.h"
#include "gl_surface_glx_qt.h"
#include "gl_context_qt.h"
+
+#include "media/gpu/buildflags.h"
#include "ui/gl/gl_context_glx.h"
#include "ui/gl/gl_gl_api_implementation.h"
#include "ui/gl/gl_glx_api_implementation.h"
+#include "ui/gl/presenter.h"
+
#include <dlfcn.h>
namespace ui {
-bool GLOzoneGLXQt::InitializeGLOneOffPlatform() {
- if (!gl::GLSurfaceGLXQt::InitializeOneOff()) {
- LOG(ERROR) << "GLSurfaceGLXQt::InitializeOneOff failed.";
- return false;
- }
- return true;
+gl::GLDisplay *GLOzoneGLXQt::InitializeGLOneOffPlatform(bool, std::vector<gl::DisplayType>, gl::GpuPreference preference)
+{
+ return gl::GLSurfaceGLXQt::InitializeOneOff(preference);
}
bool GLOzoneGLXQt::InitializeStaticGLBindings(
- gl::GLImplementation implementation) {
+ const gl::GLImplementationParts &implementation) {
+ Q_UNUSED(implementation);
base::NativeLibrary library = dlopen(NULL, RTLD_LAZY);
if (!library) {
@@ -95,18 +61,12 @@ bool GLOzoneGLXQt::InitializeStaticGLBindings(
return true;
}
-void GLOzoneGLXQt::InitializeLogGLBindings()
-{
- gl::InitializeLogGLBindingsGL();
- gl::InitializeLogGLBindingsGLX();
-}
-
void GLOzoneGLXQt::SetDisabledExtensionsPlatform(
const std::string& disabled_extensions) {
gl::SetDisabledExtensionsGLX(disabled_extensions);
}
-void GLOzoneGLXQt::ShutdownGL() {
+void GLOzoneGLXQt::ShutdownGL(gl::GLDisplay *) {
gl::ClearBindingsGL();
gl::ClearBindingsGLX();
}
@@ -127,16 +87,19 @@ scoped_refptr<gl::GLContext> GLOzoneGLXQt::CreateGLContext(
}
scoped_refptr<gl::GLSurface> GLOzoneGLXQt::CreateViewGLSurface(
+ gl::GLDisplay* display,
gfx::AcceleratedWidget window) {
return nullptr;
}
-scoped_refptr<gl::GLSurface> GLOzoneGLXQt::CreateSurfacelessViewGLSurface(
+scoped_refptr<gl::Presenter> GLOzoneGLXQt::CreateSurfacelessViewGLSurface(
+ gl::GLDisplay* display,
gfx::AcceleratedWidget window) {
return nullptr;
}
scoped_refptr<gl::GLSurface> GLOzoneGLXQt::CreateOffscreenGLSurface(
+ gl::GLDisplay* display,
const gfx::Size& size) {
scoped_refptr<gl::GLSurface> surface = new gl::GLSurfaceGLXQt(size);
if (surface->Initialize(gl::GLSurfaceFormat()))
@@ -145,7 +108,19 @@ scoped_refptr<gl::GLSurface> GLOzoneGLXQt::CreateOffscreenGLSurface(
return nullptr;
}
-bool GLOzoneGLXQt::InitializeExtensionSettingsOneOffPlatform()
+bool GLOzoneGLXQt::CanImportNativePixmap()
+{
+ return false;
+}
+
+std::unique_ptr<ui::NativePixmapGLBinding> GLOzoneGLXQt::ImportNativePixmap(
+ scoped_refptr<gfx::NativePixmap> pixmap, gfx::BufferFormat plane_format, gfx::BufferPlane plane,
+ gfx::Size plane_size, const gfx::ColorSpace &, GLenum target, GLuint texture_id)
+{
+ return nullptr;
+}
+
+bool GLOzoneGLXQt::InitializeExtensionSettingsOneOffPlatform(gl::GLDisplay *)
{
return gl::GLSurfaceGLXQt::InitializeExtensionSettingsOneOff();
}
diff --git a/src/core/ozone/gl_ozone_glx_qt.h b/src/core/ozone/gl_ozone_glx_qt.h
index 8f85ea23b..4df26ba71 100644
--- a/src/core/ozone/gl_ozone_glx_qt.h
+++ b/src/core/ozone/gl_ozone_glx_qt.h
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef UI_OZONE_GLX_QT_H_
-#define UI_OZONE_GLX_QT_H
+#define UI_OZONE_GLX_QT_H_
-#include "base/macros.h"
#include "ui/gl/gl_implementation.h"
#include "ui/ozone/public/gl_ozone.h"
@@ -52,35 +15,39 @@ public:
GLOzoneGLXQt() {}
~GLOzoneGLXQt() override {}
- bool InitializeGLOneOffPlatform() override;
- bool InitializeStaticGLBindings(gl::GLImplementation implementation) override;
- void InitializeLogGLBindings() override;
- bool InitializeExtensionSettingsOneOffPlatform() override;
- void ShutdownGL() override;
+ gl::GLDisplay *InitializeGLOneOffPlatform(bool, std::vector<gl::DisplayType>, gl::GpuPreference) override;
+ bool InitializeStaticGLBindings(const gl::GLImplementationParts &implementation) override;
+ bool InitializeExtensionSettingsOneOffPlatform(gl::GLDisplay *display) override;
+ void ShutdownGL(gl::GLDisplay *display) override;
void SetDisabledExtensionsPlatform(
const std::string& disabled_extensions) override;
bool GetGLWindowSystemBindingInfo(
const gl::GLVersionInfo &gl_info,
gl::GLWindowSystemBindingInfo *info) override;
+ bool CanImportNativePixmap() override;
+ std::unique_ptr<ui::NativePixmapGLBinding> ImportNativePixmap(
+ scoped_refptr<gfx::NativePixmap>, gfx::BufferFormat, gfx::BufferPlane,
+ gfx::Size, const gfx::ColorSpace &, GLenum, GLuint) override;
+
scoped_refptr<gl::GLContext> CreateGLContext(
gl::GLShareGroup* share_group,
gl::GLSurface* compatible_surface,
const gl::GLContextAttribs& attribs) override;
scoped_refptr<gl::GLSurface> CreateViewGLSurface(
+ gl::GLDisplay* display,
gfx::AcceleratedWidget window) override;
- scoped_refptr<gl::GLSurface> CreateSurfacelessViewGLSurface(
+ scoped_refptr<gl::Presenter> CreateSurfacelessViewGLSurface(
+ gl::GLDisplay* display,
gfx::AcceleratedWidget window) override;
scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface(
+ gl::GLDisplay* display,
const gfx::Size& size) override;
-
-private:
- DISALLOW_COPY_AND_ASSIGN(GLOzoneGLXQt);
};
} // namespace ui
-#endif // UI_OZONE_GLX_QT_H
+#endif // UI_OZONE_GLX_QT_H_
diff --git a/src/core/ozone/gl_share_context_qt.cpp b/src/core/ozone/gl_share_context_qt.cpp
new file mode 100644
index 000000000..b1c5e201f
--- /dev/null
+++ b/src/core/ozone/gl_share_context_qt.cpp
@@ -0,0 +1,77 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "gl_share_context_qt.h"
+#include <QtGui/qtgui-config.h>
+#include <qpa/qplatformnativeinterface.h>
+
+#include "ui/gl/gl_context_egl.h"
+#include "ui/gl/gl_implementation.h"
+
+#if QT_CONFIG(opengl)
+#include <QtGui/qopenglcontext_platform.h>
+#include <QOpenGLContext>
+#include <QOpenGLExtraFunctions>
+#endif // QT_CONFIG(opengl)
+
+namespace QtWebEngineCore {
+
+QtShareGLContext::QtShareGLContext(QOpenGLContext *context)
+ : gl::GLContext(nullptr), m_handle(nullptr)
+{
+#if QT_CONFIG(opengl)
+#if defined(Q_OS_MACOS)
+ qFatal("macOS only support using ANGLE.");
+#endif
+#if defined(Q_OS_WIN)
+ auto *win_ctx = context->nativeInterface<QNativeInterface::QWGLContext>();
+ if (win_ctx && !m_handle)
+ m_handle = (void *)win_ctx->nativeContext();
+#endif
+#if QT_CONFIG(xcb_glx_plugin)
+ auto *glx_ctx = context->nativeInterface<QNativeInterface::QGLXContext>();
+ if (glx_ctx && !m_handle)
+ m_handle = (void *)glx_ctx->nativeContext();
+#endif
+#if QT_CONFIG(egl)
+ auto *egl_ctx = context->nativeInterface<QNativeInterface::QEGLContext>();
+ if (egl_ctx && !m_handle)
+ m_handle = (void *)egl_ctx->nativeContext();
+#endif
+ if (!m_handle)
+ qFatal("Could not get handle for shared context.");
+#endif // QT_CONFIG(opengl)
+}
+
+unsigned int QtShareGLContext::CheckStickyGraphicsResetStatusImpl()
+{
+#if QT_CONFIG(opengl)
+ if (QOpenGLContext *context = QOpenGLContext::globalShareContext()) {
+ if (context->format().testOption(QSurfaceFormat::ResetNotification))
+ return context->extraFunctions()->glGetGraphicsResetStatus();
+ }
+#endif
+ return 0 /*GL_NO_ERROR*/;
+}
+
+void ShareGroupQt::AboutToAddFirstContext()
+{
+ if (gl::GetGLImplementation() == gl::kGLImplementationEGLANGLE) {
+ m_shareContextQt = new gl::GLContextEGL(nullptr);
+ return;
+ }
+
+#if QT_CONFIG(opengl)
+ // This currently has to be setup by ::main in all applications using QQuickWebEngineView with
+ // delegated rendering.
+ QOpenGLContext *shareContext = QOpenGLContext::globalShareContext();
+ if (!shareContext) {
+ qFatal("QWebEngine: OpenGL resource sharing is not set up in QtQuick. Please make sure to "
+ "call QtWebEngineQuick::initialize() in your main() function before "
+ "QCoreApplication is created.");
+ }
+ m_shareContextQt = new QtShareGLContext(shareContext);
+#endif // QT_CONFIG(opengl)
+}
+
+} // namespace
diff --git a/src/core/ozone/gl_share_context_qt.h b/src/core/ozone/gl_share_context_qt.h
new file mode 100644
index 000000000..89be00421
--- /dev/null
+++ b/src/core/ozone/gl_share_context_qt.h
@@ -0,0 +1,63 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef GL_SHARE_CONTEXT_QT
+#define GL_SHARE_CONTEXT_QT
+
+#include "ui/gl/gpu_timing.h"
+#include "ui/gl/gl_context.h"
+#include "ui/gl/gl_share_group.h"
+#include "qtwebenginecoreglobal.h"
+
+QT_FORWARD_DECLARE_CLASS(QOpenGLContext)
+
+namespace QtWebEngineCore {
+
+class QtShareGLContext : public gl::GLContext
+{
+
+public:
+ QtShareGLContext(QOpenGLContext *qtContext);
+ void *GetHandle() override { return m_handle; }
+ unsigned int CheckStickyGraphicsResetStatusImpl() override;
+ // We don't care about the rest, this context shouldn't be used except for its handle.
+ bool Initialize(gl::GLSurface *, const gl::GLContextAttribs &) override
+ {
+ Q_UNREACHABLE();
+ return false;
+ }
+ bool MakeCurrentImpl(gl::GLSurface *) override
+ {
+ Q_UNREACHABLE();
+ return false;
+ }
+ void ReleaseCurrent(gl::GLSurface *) override { Q_UNREACHABLE(); }
+ bool IsCurrent(gl::GLSurface *) override
+ {
+ Q_UNREACHABLE();
+ return false;
+ }
+ scoped_refptr<gl::GPUTimingClient> CreateGPUTimingClient() override { return nullptr; }
+ const gfx::ExtensionSet &GetExtensions() override
+ {
+ static const gfx::ExtensionSet s_emptySet;
+ return s_emptySet;
+ }
+ void ResetExtensions() override {}
+
+private:
+ void *m_handle;
+};
+
+class ShareGroupQt : public gl::GLShareGroup
+{
+
+public:
+ gl::GLContext *GetContext() override { return m_shareContextQt.get(); }
+ void AboutToAddFirstContext() override;
+
+private:
+ scoped_refptr<gl::GLContext> m_shareContextQt;
+};
+} // namespace
+#endif
diff --git a/src/core/ozone/gl_surface_egl_qt.cpp b/src/core/ozone/gl_surface_egl_qt.cpp
index ac0e79b67..a0c120ac6 100644
--- a/src/core/ozone/gl_surface_egl_qt.cpp
+++ b/src/core/ozone/gl_surface_egl_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -44,58 +8,60 @@
#include "gl_context_qt.h"
#include "ozone/gl_surface_egl_qt.h"
-#if !defined(OS_MACOSX)
#include "ui/gl/egl_util.h"
-#include "ui/gl/gl_surface_egl.h"
+#include "ui/gl/gl_bindings.h"
+#include "ui/gl/gl_display.h"
+#include "ui/gl/gl_display_manager.h"
#include "ui/gl/init/gl_factory.h"
-// From ANGLE's egl/eglext.h.
-#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle
-#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1
-#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE 0x3200
-#endif
+#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN)
using ui::GetLastEGLErrorString;
-namespace gl{
+namespace gl {
bool GLSurfaceEGLQt::g_egl_surfaceless_context_supported = false;
bool GLSurfaceEGLQt::s_initialized = false;
+GLSurfaceEGLQt::GLSurfaceEGLQt(gl::GLDisplayEGL *display, const gfx::Size& size)
+ : GLSurfaceQt(size),
+ m_surfaceBuffer(0)
+{
+}
+
GLSurfaceEGLQt::~GLSurfaceEGLQt()
{
Destroy();
}
-bool GLSurfaceEGLQt::InitializeOneOff()
+gl::GLDisplay *GLSurfaceEGLQt::InitializeOneOff(gl::GpuPreference preference)
{
if (s_initialized)
- return true;
-
- // Must be called before initializing the display.
- g_driver_egl.InitializeClientExtensionBindings();
+ return g_display;
- g_display = GLContextHelper::getEGLDisplay();
- if (!g_display) {
+ auto *egl_display = GLDisplayManagerEGL::GetInstance()->GetDisplay(preference);
+ g_display = egl_display;
+ egl_display->SetDisplay(GLContextHelper::getEGLDisplay());
+ if (!egl_display->GetDisplay()) {
LOG(ERROR) << "GLContextHelper::getEGLDisplay() failed.";
- return false;
+ return nullptr;
}
g_config = GLContextHelper::getEGLConfig();
if (!g_config) {
LOG(ERROR) << "GLContextHelper::getEGLConfig() failed.";
- return false;
+ return nullptr;
}
- if (!eglInitialize(g_display, NULL, NULL)) {
+ if (!eglInitialize(egl_display->GetDisplay(), NULL, NULL)) {
LOG(ERROR) << "eglInitialize failed with error " << GetLastEGLErrorString();
- return false;
+ return nullptr;
}
- g_extensions = eglQueryString(g_display, EGL_EXTENSIONS);
- g_egl_surfaceless_context_supported = ExtensionsContain(g_extensions, "EGL_KHR_surfaceless_context");
+ g_extensions = eglQueryString(egl_display->GetDisplay(), EGL_EXTENSIONS);
+ g_egl_surfaceless_context_supported = ExtensionsContain(g_extensions.c_str(), "EGL_KHR_surfaceless_context");
if (g_egl_surfaceless_context_supported) {
- scoped_refptr<GLSurface> surface = new GLSurfacelessQtEGL(gfx::Size(1, 1));
+ scoped_refptr<GLSurface> surface = new GLSurfacelessQtEGL(egl_display, gfx::Size(1, 1));
gl::GLContextAttribs attribs;
scoped_refptr<GLContext> context = init::CreateGLContext(
NULL, surface.get(), attribs);
@@ -111,11 +77,8 @@ bool GLSurfaceEGLQt::InitializeOneOff()
}
}
- // Must be called after initializing the display.
- g_driver_egl.InitializeExtensionBindings();
-
s_initialized = true;
- return true;
+ return egl_display;
}
bool GLSurfaceEGLQt::InitializeExtensionSettingsOneOff()
@@ -123,100 +86,12 @@ bool GLSurfaceEGLQt::InitializeExtensionSettingsOneOff()
return s_initialized;
}
-bool GLSurfaceEGL::InitializeExtensionSettingsOneOff()
-{
- return GLSurfaceEGLQt::InitializeExtensionSettingsOneOff();
-}
-
-EGLDisplay GLSurfaceEGL::GetHardwareDisplay()
-{
- return static_cast<EGLDisplay>(GLSurfaceQt::g_display);
-}
-
-bool GLSurfaceEGL::IsCreateContextRobustnessSupported()
-{
- return GLContextHelper::isCreateContextRobustnessSupported() && HasEGLExtension("EGL_EXT_create_context_robustness");
-}
-
-bool GLSurfaceEGL::IsCreateContextBindGeneratesResourceSupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsCreateContextWebGLCompatabilitySupported()
-{
- return false;
-}
-bool GLSurfaceEGL::IsEGLSurfacelessContextSupported()
-{
- return GLSurfaceEGLQt::g_egl_surfaceless_context_supported;
-}
-bool GLSurfaceEGL::IsEGLContextPrioritySupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsRobustResourceInitSupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsDisplayTextureShareGroupSupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsCreateContextClientArraysSupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsPixelFormatFloatSupported()
-{
- return false;
-}
-
-bool GLSurfaceEGL::IsANGLEFeatureControlSupported()
-{
- return false;
-}
-
-void GLSurfaceEGL::ShutdownOneOff()
-{
-}
-
-const char* GLSurfaceEGL::GetEGLExtensions()
-{
- return GLSurfaceQt::g_extensions;
-}
-
-bool GLSurfaceEGL::HasEGLExtension(const char* name)
-{
- return ExtensionsContain(GetEGLExtensions(), name);
-}
-
-bool GLSurfaceEGL::InitializeOneOff(EGLNativeDisplayType /*native_display*/)
-{
- return GLSurfaceEGLQt::InitializeOneOff();
-}
-
-bool GLSurfaceEGL::IsAndroidNativeFenceSyncSupported()
-{
- return false;
-}
-
-GLSurfaceEGLQt::GLSurfaceEGLQt(const gfx::Size& size)
- : GLSurfaceQt(size),
- m_surfaceBuffer(0)
-{
-}
-
bool GLSurfaceEGLQt::Initialize(GLSurfaceFormat format)
{
Q_ASSERT(!m_surfaceBuffer);
m_format = format;
- EGLDisplay display = g_display;
+ EGLDisplay display = GLContextHelper::getEGLDisplay();
if (!display) {
LOG(ERROR) << "Trying to create surface with invalid display.";
return false;
@@ -244,7 +119,7 @@ bool GLSurfaceEGLQt::Initialize(GLSurfaceFormat format)
void GLSurfaceEGLQt::Destroy()
{
if (m_surfaceBuffer) {
- if (!eglDestroySurface(g_display, m_surfaceBuffer))
+ if (!eglDestroySurface(GLContextHelper::getEGLDisplay(), m_surfaceBuffer))
LOG(ERROR) << "eglDestroySurface failed with error " << GetLastEGLErrorString();
m_surfaceBuffer = 0;
@@ -252,7 +127,7 @@ void GLSurfaceEGLQt::Destroy()
}
bool GLSurfaceEGLQt::Resize(const gfx::Size& size, float scale_factor,
- ColorSpace color_space, bool has_alpha)
+ const gfx::ColorSpace &color_space, bool has_alpha)
{
if (size == m_size)
return true;
@@ -282,7 +157,7 @@ void* GLSurfaceEGLQt::GetHandle()
return reinterpret_cast<void*>(m_surfaceBuffer);
}
-GLSurfacelessQtEGL::GLSurfacelessQtEGL(const gfx::Size& size)
+GLSurfacelessQtEGL::GLSurfacelessQtEGL(GLDisplayEGL *display, const gfx::Size& size)
: GLSurfaceQt(size)
{
}
@@ -303,7 +178,7 @@ bool GLSurfacelessQtEGL::IsSurfaceless() const
}
bool GLSurfacelessQtEGL::Resize(const gfx::Size& size, float scale_factor,
- ColorSpace color_space, bool has_alpha)
+ const gfx::ColorSpace &color_space, bool has_alpha)
{
m_size = size;
return true;
@@ -319,26 +194,5 @@ void* GLSurfacelessQtEGL::GetShareHandle()
return NULL;
}
-std::string DriverEGL::GetPlatformExtensions()
-{
- EGLDisplay display = GLContextHelper::getEGLDisplay();
- if (display == EGL_NO_DISPLAY)
- return "";
-
- DCHECK(g_driver_egl.fn.eglQueryStringFn);
- const char* str = g_driver_egl.fn.eglQueryStringFn(display, EGL_EXTENSIONS);
- return str ? std::string(str) : "";
-}
-} // namespace gl
-#else
-namespace gl {
-struct GL_EXPORT DriverEGL {
- static std::string GetPlatformExtensions();
-};
-
-std::string DriverEGL::GetPlatformExtensions()
-{
- return "";
-}
} // namespace gl
-#endif // !defined(OS_MACOSX)
+#endif // !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN)
diff --git a/src/core/ozone/gl_surface_egl_qt.h b/src/core/ozone/gl_surface_egl_qt.h
index ecc2327b3..d581f9079 100644
--- a/src/core/ozone/gl_surface_egl_qt.h
+++ b/src/core/ozone/gl_surface_egl_qt.h
@@ -1,63 +1,29 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_SURFACE_EGL_QT_H_
#define GL_SURFACE_EGL_QT_H_
#include "gl_surface_qt.h"
#include <EGL/egl.h>
-#include <EGL/eglext.h>
namespace gl {
+class GLDisplayEGL;
+
class GLSurfaceEGLQt: public GLSurfaceQt {
public:
- explicit GLSurfaceEGLQt(const gfx::Size& size);
+ explicit GLSurfaceEGLQt(gl::GLDisplayEGL *display, const gfx::Size& size);
- static bool InitializeOneOff();
+ static gl::GLDisplay *InitializeOneOff(gl::GpuPreference preference);
static bool InitializeExtensionSettingsOneOff();
bool Initialize(GLSurfaceFormat format) override;
void Destroy() override;
void* GetHandle() override;
bool Resize(const gfx::Size& size, float scale_factor,
- ColorSpace color_space, bool has_alpha) override;
+ const gfx::ColorSpace &color_space, bool has_alpha) override;
+
protected:
~GLSurfaceEGLQt();
@@ -68,7 +34,6 @@ public:
private:
EGLSurface m_surfaceBuffer;
static bool s_initialized;
- DISALLOW_COPY_AND_ASSIGN(GLSurfaceEGLQt);
};
// The following comment is cited from chromium/ui/gl/gl_surface_egl.cc:
@@ -78,19 +43,16 @@ private:
class GLSurfacelessQtEGL : public GLSurfaceQt {
public:
- explicit GLSurfacelessQtEGL(const gfx::Size& size);
+ explicit GLSurfacelessQtEGL(gl::GLDisplayEGL *display, const gfx::Size& size);
public:
bool Initialize(GLSurfaceFormat format) override;
void Destroy() override;
bool IsSurfaceless() const override;
bool Resize(const gfx::Size& size, float scale_factor,
- ColorSpace color_space, bool has_alpha) override;
+ const gfx::ColorSpace &color_space, bool has_alpha) override;
EGLSurface GetHandle() override;
void* GetShareHandle() override;
-
-private:
- DISALLOW_COPY_AND_ASSIGN(GLSurfacelessQtEGL);
};
}
diff --git a/src/core/ozone/gl_surface_glx_qt.cpp b/src/core/ozone/gl_surface_glx_qt.cpp
index e150c940a..61c9ef9de 100644
--- a/src/core/ozone/gl_surface_glx_qt.cpp
+++ b/src/core/ozone/gl_surface_glx_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,27 +7,23 @@
#include "gl_context_qt.h"
#include "ozone/gl_surface_glx_qt.h"
+
#include "ui/gl/gl_bindings.h"
+#include "ui/gl/gl_display.h"
+#include "ui/gl/gl_display_manager.h"
+#include "ui/gl/gl_surface.h"
#include "ui/gl/gl_surface_glx.h"
-#include <GL/glx.h>
-#include <GL/glxext.h>
namespace gl {
-bool GLSurfaceGLXQt::s_initialized = false;
-
-GLSurfaceGLXQt::~GLSurfaceGLXQt()
-{
- Destroy();
-}
-
-void GLSurfaceGLX::ShutdownOneOff()
+static bool HasGLXExtension(const char *name)
{
+ return GLSurface::ExtensionsContain(GLSurfaceQt::g_extensions.c_str(), name);
}
bool GLSurfaceGLX::IsCreateContextSupported()
{
- return ExtensionsContain(GLSurfaceQt::g_extensions, "GLX_ARB_create_context");
+ return HasGLXExtension("GLX_ARB_create_context");
}
bool GLSurfaceGLX::IsCreateContextRobustnessSupported()
@@ -71,16 +31,6 @@ bool GLSurfaceGLX::IsCreateContextRobustnessSupported()
return GLContextHelper::isCreateContextRobustnessSupported() && HasGLXExtension("GLX_ARB_create_context_robustness");
}
-bool GLSurfaceGLX::IsEXTSwapControlSupported()
-{
- return HasGLXExtension("GLX_EXT_swap_control");
-}
-
-bool GLSurfaceGLX::IsMESASwapControlSupported()
-{
- return HasGLXExtension("GLX_MESA_swap_control");
-}
-
bool GLSurfaceGLX::IsCreateContextProfileSupported()
{
return false; // ExtensionsContain(g_extensions, "GLX_ARB_create_context_profile");
@@ -88,92 +38,83 @@ bool GLSurfaceGLX::IsCreateContextProfileSupported()
bool GLSurfaceGLX::IsCreateContextES2ProfileSupported()
{
- return ExtensionsContain(GLSurfaceQt::g_extensions, "GLX_ARB_create_context_es2_profile");
+ return HasGLXExtension("GLX_ARB_create_context_es2_profile");
}
-bool GLSurfaceGLX::IsOMLSyncControlSupported()
+bool GLSurfaceGLX::IsRobustnessVideoMemoryPurgeSupported()
{
- return false; // ExtensionsContain(g_extensions, "GLX_OML_sync_control");
+ return false;
}
-bool GLSurfaceGLX::HasGLXExtension(const char *name)
-{
- return ExtensionsContain(GLSurfaceQt::g_extensions, name);
-}
-bool GLSurfaceGLX::IsTextureFromPixmapSupported()
+bool GLSurfaceGLXQt::s_initialized = false;
+
+GLSurfaceGLXQt::GLSurfaceGLXQt(const gfx::Size& size)
+ : GLSurfaceQt(size),
+ m_surfaceBuffer(0)
{
- return ExtensionsContain(GLSurfaceQt::g_extensions, "GLX_EXT_texture_from_pixmap");
}
-const char* GLSurfaceGLX::GetGLXExtensions()
+GLSurfaceGLXQt::~GLSurfaceGLXQt()
{
- return GLSurfaceQt::g_extensions;
+ Destroy();
}
-bool GLSurfaceGLXQt::InitializeOneOff()
+GLDisplay *GLSurfaceGLXQt::InitializeOneOff(gl::GpuPreference preference)
{
if (s_initialized)
- return true;
+ return g_display;
- XInitThreads();
-
- g_display = GLContextHelper::getXDisplay();
- if (!g_display) {
+ g_display = GLDisplayManagerX11::GetInstance()->GetDisplay(preference);
+ if (!g_display->GetDisplay()) {
LOG(ERROR) << "GLContextHelper::getXDisplay() failed.";
- return false;
+ return nullptr;
}
g_config = GLContextHelper::getGlXConfig();
if (!g_config) {
LOG(ERROR) << "GLContextHelper::getGlxConfig() failed.";
- return false;
+ return nullptr;
}
- Display* display = static_cast<Display*>(g_display);
+ Display* display = static_cast<Display*>(g_display->GetDisplay());
int major, minor;
if (!glXQueryVersion(display, &major, &minor)) {
LOG(ERROR) << "glxQueryVersion failed.";
- return false;
+ return nullptr;
}
if (major == 1 && minor < 3) {
LOG(ERROR) << "GLX 1.3 or later is required.";
- return false;
+ return nullptr;
}
s_initialized = true;
- return true;
+ return g_display;
}
-
bool GLSurfaceGLXQt::InitializeExtensionSettingsOneOff()
{
if (!s_initialized)
return false;
- Display* display = static_cast<Display*>(g_display);
+ Display* display = static_cast<Display*>(g_display->GetDisplay());
GLSurfaceQt::g_extensions = glXQueryExtensionsString(display, 0);
- g_driver_glx.InitializeExtensionBindings(g_extensions);
+ g_driver_glx.InitializeExtensionBindings(g_extensions.c_str());
return true;
}
-bool GLSurfaceGLX::InitializeExtensionSettingsOneOff()
-{
- return GLSurfaceGLXQt::InitializeExtensionSettingsOneOff();
-}
-
bool GLSurfaceGLXQt::Initialize(GLSurfaceFormat format)
{
Q_ASSERT(!m_surfaceBuffer);
- Display* display = static_cast<Display*>(g_display);
+ Display* display = static_cast<Display*>(g_display->GetDisplay());
const int pbuffer_attributes[] = {
GLX_PBUFFER_WIDTH, m_size.width(),
GLX_PBUFFER_HEIGHT, m_size.height(),
- GLX_LARGEST_PBUFFER, x11::False,
- GLX_PRESERVED_CONTENTS, x11::False,
- x11::None // MEMO doc: ...must be terminated with None or NULL
+ GLX_LARGEST_PBUFFER, GL_FALSE,
+ GLX_PRESERVED_CONTENTS, GL_FALSE,
+ GL_NONE // MEMO doc: ...must be terminated with None or NULL
};
m_surfaceBuffer = glXCreatePbuffer(display, static_cast<GLXFBConfig>(g_config), pbuffer_attributes);
@@ -190,17 +131,11 @@ bool GLSurfaceGLXQt::Initialize(GLSurfaceFormat format)
void GLSurfaceGLXQt::Destroy()
{
if (m_surfaceBuffer) {
- glXDestroyPbuffer(static_cast<Display*>(g_display), m_surfaceBuffer);
+ glXDestroyPbuffer(static_cast<Display*>(g_display->GetDisplay()), m_surfaceBuffer);
m_surfaceBuffer = 0;
}
}
-GLSurfaceGLXQt::GLSurfaceGLXQt(const gfx::Size& size)
- : GLSurfaceQt(size),
- m_surfaceBuffer(0)
-{
-}
-
void* GLSurfaceGLXQt::GetHandle()
{
return reinterpret_cast<void*>(m_surfaceBuffer);
diff --git a/src/core/ozone/gl_surface_glx_qt.h b/src/core/ozone/gl_surface_glx_qt.h
index 3a465f448..8cbf1fcf2 100644
--- a/src/core/ozone/gl_surface_glx_qt.h
+++ b/src/core/ozone/gl_surface_glx_qt.h
@@ -1,58 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_SURFACE_GLX_QT_H_
#define GL_SURFACE_GLX_QT_H_
#include "gl_surface_qt.h"
-extern "C" {
-#include <X11/Xlib.h>
-}
-
namespace gl {
class GLSurfaceGLXQt: public GLSurfaceQt {
public:
explicit GLSurfaceGLXQt(const gfx::Size& size);
- static bool InitializeOneOff();
+ static gl::GLDisplay *InitializeOneOff(gl::GpuPreference preference);
static bool InitializeExtensionSettingsOneOff();
bool Initialize(GLSurfaceFormat format) override;
@@ -64,8 +24,7 @@ protected:
private:
static bool s_initialized;
- XID m_surfaceBuffer;
- DISALLOW_COPY_AND_ASSIGN(GLSurfaceGLXQt);
+ int m_surfaceBuffer;
};
}
diff --git a/src/core/ozone/gl_surface_qt.cpp b/src/core/ozone/gl_surface_qt.cpp
index 4be17f12b..0cbe75cbd 100644
--- a/src/core/ozone/gl_surface_qt.cpp
+++ b/src/core/ozone/gl_surface_qt.cpp
@@ -1,84 +1,39 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
+#include "qtwebenginecoreglobal_p.h"
+
+#if !defined(Q_OS_MACOS)
+
#include "gl_surface_qt.h"
-#if !defined(OS_MACOSX)
+#include "base/logging.h"
-#include <QGuiApplication>
-#include "gl_context_qt.h"
-#include "qtwebenginecoreglobal_p.h"
+#if BUILDFLAG(IS_WIN)
#include "web_engine_context.h"
-#include "ozone/gl_surface_egl_qt.h"
+#include "ozone/gl_surface_wgl_qt.h"
-#include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
#include "gpu/ipc/service/image_transport_surface.h"
-#include "ui/gl/gl_bindings.h"
-#include "ui/gl/gl_context.h"
+#include "ui/gl/init/gl_display_initializer.h"
+#include "ui/gl/direct_composition_support.h"
+#include "ui/gl/gl_angle_util_win.h"
+#include "ui/gl/gl_display.h"
#include "ui/gl/gl_implementation.h"
-#include "ui/gl/init/gl_initializer.h"
-#include "ui/gl/init/gl_factory.h"
-#include "ui/gl/gl_gl_api_implementation.h"
-#if defined(OS_WIN)
-#include "ozone/gl_surface_wgl_qt.h"
-
-#include "ui/gl/direct_composition_surface_win.h"
+#include "ui/gl/gl_surface_egl.h"
+#include "ui/gl/gl_utils.h"
#include "ui/gl/vsync_provider_win.h"
#endif
-#include "ozone/gl_surface_egl_qt.h"
-#include "ui/gl/gl_egl_api_implementation.h"
namespace gl {
-namespace {
-bool g_initializedEGL = false;
-}
-
-void* GLSurfaceQt::g_display = nullptr;
-void* GLSurfaceQt::g_config = nullptr;
-const char* GLSurfaceQt::g_extensions = nullptr;
+GLDisplay *GLSurfaceQt::g_display = nullptr;
+void *GLSurfaceQt::g_config = nullptr;
+std::string GLSurfaceQt::g_extensions;
GLSurfaceQt::~GLSurfaceQt()
{
@@ -99,7 +54,7 @@ GLSurfaceQt::GLSurfaceQt(const gfx::Size& size)
bool GLSurfaceQt::HasEGLExtension(const char* name)
{
- return ExtensionsContain(g_extensions, name);
+ return ExtensionsContain(g_extensions.c_str(), name);
}
bool GLSurfaceQt::IsOffscreen()
@@ -107,7 +62,7 @@ bool GLSurfaceQt::IsOffscreen()
return true;
}
-gfx::SwapResult GLSurfaceQt::SwapBuffers(PresentationCallback callback)
+gfx::SwapResult GLSurfaceQt::SwapBuffers(PresentationCallback callback, gfx::FrameData data)
{
LOG(ERROR) << "Attempted to call SwapBuffers on a pbuffer.";
Q_UNREACHABLE();
@@ -124,7 +79,7 @@ GLSurfaceFormat GLSurfaceQt::GetFormat()
return m_format;
}
-void* GLSurfaceQt::GetDisplay()
+GLDisplay *GLSurfaceQt::GetGLDisplay()
{
return g_display;
}
@@ -134,35 +89,47 @@ void* GLSurfaceQt::GetConfig()
return g_config;
}
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
namespace init {
-bool InitializeGLOneOffPlatform()
+
+gl::GLDisplay *InitializeGLOneOffPlatform(gl::GpuPreference gpu_preference)
{
VSyncProviderWin::InitializeOneOff();
- if (GetGLImplementation() == kGLImplementationEGLGLES2 || GetGLImplementation() == kGLImplementationEGLANGLE)
- return GLSurfaceEGLQt::InitializeOneOff();
+ if (GetGLImplementation() == kGLImplementationDesktopGL || GetGLImplementation() == kGLImplementationDesktopGLCoreProfile)
+ return GLSurfaceWGLQt::InitializeOneOff(gpu_preference);
- if (GetGLImplementation() == kGLImplementationDesktopGL) {
- return GLSurfaceWGLQt::InitializeOneOff();
-
- // Fallback to trying EGL with desktop GL.
- if (GLSurfaceEGLQt::InitializeOneOff()) {
- g_initializedEGL = true;
- return true;
+ GLDisplayEGL *display = GetDisplayEGL(gpu_preference);
+ switch (GetGLImplementation()) {
+ case kGLImplementationEGLANGLE:
+ case kGLImplementationEGLGLES2:
+ if (!InitializeDisplay(display, EGLDisplayPlatform(GetDC(nullptr)))) {
+ LOG(ERROR) << "GLDisplayEGL::Initialize failed.";
+ return nullptr;
}
+ if (auto d3d11_device = QueryD3D11DeviceObjectFromANGLE())
+ InitializeDirectComposition(std::move(d3d11_device));
+ break;
+ case kGLImplementationMockGL:
+ case kGLImplementationStubGL:
+ break;
+ default:
+ NOTREACHED();
}
-
- return false;
+ return display;
}
bool usingSoftwareDynamicGL()
{
+#if QT_CONFIG(opengl)
return QtWebEngineCore::usingSoftwareDynamicGL();
+#else
+ return false;
+#endif // QT_CONFIG(opengl)
}
scoped_refptr<GLSurface>
-CreateOffscreenGLSurfaceWithFormat(const gfx::Size& size, GLSurfaceFormat format)
+CreateOffscreenGLSurfaceWithFormat(GLDisplay *display, const gfx::Size& size, GLSurfaceFormat format)
{
scoped_refptr<GLSurface> surface;
switch (GetGLImplementation()) {
@@ -175,21 +142,10 @@ CreateOffscreenGLSurfaceWithFormat(const gfx::Size& size, GLSurfaceFormat format
}
case kGLImplementationEGLANGLE:
case kGLImplementationEGLGLES2: {
- surface = new GLSurfaceEGLQt(size);
- if (surface->Initialize(format))
- return surface;
-
- // Surfaceless context will be used ONLY if pseudo surfaceless context
- // is not available since some implementations of surfaceless context
- // have problems. (e.g. QTBUG-57290)
- if (GLSurfaceEGLQt::g_egl_surfaceless_context_supported) {
- surface = new GLSurfacelessQtEGL(size);
- if (surface->Initialize(format))
- return surface;
- }
- LOG(ERROR) << "eglCreatePbufferSurface failed and surfaceless context not available";
- LOG(WARNING) << "Failed to create offscreen GL surface";
- break;
+ GLDisplayEGL *display_egl = display->GetAs<gl::GLDisplayEGL>();
+ if (display_egl->IsEGLSurfacelessContextSupported() && size.width() == 0 && size.height() == 0)
+ return InitializeGLSurfaceWithFormat(new SurfacelessEGL(display_egl, size), format);
+ return InitializeGLSurfaceWithFormat(new PbufferGLSurfaceEGL(display_egl, size), format);
}
default:
break;
@@ -200,49 +156,13 @@ CreateOffscreenGLSurfaceWithFormat(const gfx::Size& size, GLSurfaceFormat format
}
scoped_refptr<GLSurface>
-CreateViewGLSurface(gfx::AcceleratedWidget window)
+CreateViewGLSurface(GLDisplay *display, gfx::AcceleratedWidget window)
{
- QT_NOT_USED
return nullptr;
}
} // namespace init
-#endif // defined(OS_WIN)
+#endif // BUILDFLAG(IS_WIN)
} // namespace gl
-#if defined(OS_WIN)
-namespace gpu {
-class GpuCommandBufferStub;
-class GpuChannelManager;
-scoped_refptr<gl::GLSurface> ImageTransportSurface::CreateNativeSurface(base::WeakPtr<ImageTransportSurfaceDelegate>,
- SurfaceHandle, gl::GLSurfaceFormat)
-{
- QT_NOT_USED
- return scoped_refptr<gl::GLSurface>();
-}
-} // namespace gpu
-
-namespace gl {
-
-bool DirectCompositionSurfaceWin::IsDirectCompositionSupported()
-{
- return false;
-}
-
-bool DirectCompositionSurfaceWin::IsDecodeSwapChainSupported()
-{
- return false;
-}
-
-bool DirectCompositionSurfaceWin::IsHDRSupported()
-{
- return false;
-}
-
-bool DirectCompositionSurfaceWin::IsSwapChainTearingSupported()
-{
- return false;
-}
-} // namespace gl
-#endif
-#endif // !defined(OS_MACOSX)
+#endif // !defined(Q_OS_MACOS)
diff --git a/src/core/ozone/gl_surface_qt.h b/src/core/ozone/gl_surface_qt.h
index cbdc8876a..1ae41a078 100644
--- a/src/core/ozone/gl_surface_qt.h
+++ b/src/core/ozone/gl_surface_qt.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_SURFACE_QT_H_
#define GL_SURFACE_QT_H_
+#include <string>
+
#include "ui/gfx/geometry/size.h"
#include "ui/gl/gl_surface.h"
@@ -54,10 +18,10 @@ public:
static bool HasEGLExtension(const char* name);
// Implement GLSurface.
- void *GetDisplay() override;
+ GLDisplay *GetGLDisplay() override;
void *GetConfig() override;
bool IsOffscreen() override;
- gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
+ gfx::SwapResult SwapBuffers(PresentationCallback callback, gfx::FrameData data) override;
gfx::Size GetSize() override;
GLSurfaceFormat GetFormat() override;
@@ -70,13 +34,10 @@ protected:
public:
static void* g_config;
- static void* g_display;
- static const char* g_extensions;
-
-private:
- DISALLOW_COPY_AND_ASSIGN(GLSurfaceQt);
+ static GLDisplay *g_display;
+ static std::string g_extensions;
};
-}
+} // namespace gl
-#endif
+#endif // GL_SURFACE_QT_H_
diff --git a/src/core/ozone/gl_surface_wgl_qt.cpp b/src/core/ozone/gl_surface_wgl_qt.cpp
index ac27a9c20..db4aed884 100644
--- a/src/core/ozone/gl_surface_wgl_qt.cpp
+++ b/src/core/ozone/gl_surface_wgl_qt.cpp
@@ -1,45 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "gl_surface_wgl_qt.h"
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
+#include "ui/gl/gl_display_manager.h"
#include "ui/gl/gl_surface_wgl.h"
namespace gl {
@@ -55,9 +20,12 @@ GLSurfaceWGLQt::~GLSurfaceWGLQt()
Destroy();
}
-bool GLSurfaceWGLQt::InitializeOneOff()
+gl::GLDisplay *GLSurfaceWGLQt::InitializeOneOff(gl::GpuPreference gpu_preference)
{
- return GLSurfaceWGL::InitializeOneOff();
+ if (GLSurfaceWGL::InitializeOneOff())
+ return GLDisplayManagerWGL::GetInstance()->GetDisplay(gpu_preference);
+
+ return nullptr;
}
bool GLSurfaceWGLQt::Initialize(GLSurfaceFormat format)
@@ -77,9 +45,9 @@ void *GLSurfaceWGLQt::GetHandle()
return m_surfaceBuffer->GetHandle();
}
-void *GLSurfaceWGLQt::GetDisplay()
+GLDisplay *GLSurfaceWGLQt::GetGLDisplay()
{
- return m_surfaceBuffer->GetDisplay();
+ return m_surfaceBuffer->GetGLDisplay();
}
void *GLSurfaceWGLQt::GetConfig()
@@ -89,4 +57,4 @@ void *GLSurfaceWGLQt::GetConfig()
} //namespace gl
-#endif // defined(OS_WIN)
+#endif // BUILDFLAG(IS_WIN)
diff --git a/src/core/ozone/gl_surface_wgl_qt.h b/src/core/ozone/gl_surface_wgl_qt.h
index 2b562b61b..6c590e46c 100644
--- a/src/core/ozone/gl_surface_wgl_qt.h
+++ b/src/core/ozone/gl_surface_wgl_qt.h
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GL_SURFACE_WGL_QT_H
#define GL_SURFACE_WGL_QT_H
#include "gl_surface_qt.h"
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
namespace gl {
@@ -52,12 +16,12 @@ class GLSurfaceWGLQt: public GLSurfaceQt {
public:
explicit GLSurfaceWGLQt(const gfx::Size& size);
- static bool InitializeOneOff();
+ static gl::GLDisplay *InitializeOneOff(gl::GpuPreference gpu_preference);
bool Initialize(GLSurfaceFormat format) override;
void Destroy() override;
void *GetHandle() override;
- void *GetDisplay() override;
+ GLDisplay *GetGLDisplay() override;
void *GetConfig() override;
protected:
@@ -65,10 +29,9 @@ protected:
private:
scoped_refptr<PbufferGLSurfaceWGL> m_surfaceBuffer;
- DISALLOW_COPY_AND_ASSIGN(GLSurfaceWGLQt);
};
}
-#endif // defined(OS_WIN)
+#endif // BUILDFLAG(IS_WIN)
#endif // GL_SURFACE_WGL_QT_H
diff --git a/src/core/ozone/ozone_extra.gni b/src/core/ozone/ozone_extra.gni
index a832f741a..191bb3787 100644
--- a/src/core/ozone/ozone_extra.gni
+++ b/src/core/ozone/ozone_extra.gni
@@ -17,3 +17,17 @@ ozone_external_platform_deps = []
# so that they get included into ozone_unittests.
# ozone_external_platform_test_deps = [ "platform/foo1:foo1_unitests", ... ]
ozone_external_platform_test_deps = []
+
+# If a platform has integration tests, the corresponding source_set can be
+# listed here so that they get included into ozone_integration_tests.
+ozone_external_platform_integration_test_deps = []
+
+# If a platform has test support files for ui, the corresponding source_set can
+# be listed here so that they get included into ui_test_support.
+# ozone_external_platform_ui_test_support_deps = [ "platform/foo1:ui_test_support", ... ]
+ozone_external_platform_ui_test_support_deps = []
+
+# If a platform has a test support for interactive_ui_tests, the corresponding
+# source_set can be listed here so that they can included into
+# interactive_ui_tests.
+ozone_external_interactive_ui_tests_deps = []
diff --git a/src/core/ozone/ozone_platform_qt.cpp b/src/core/ozone/ozone_platform_qt.cpp
index fb5af18c5..e8547fa87 100644
--- a/src/core/ozone/ozone_platform_qt.cpp
+++ b/src/core/ozone/ozone_platform_qt.cpp
@@ -1,61 +1,50 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "ozone_platform_qt.h"
#if defined(USE_OZONE)
+#include "base/no_destructor.h"
+#include "base/task/thread_pool.h"
+#include "media/gpu/buildflags.h"
+#include "ui/base/buildflags.h"
#include "ui/base/ime/input_method.h"
#include "ui/display/types/native_display_delegate.h"
-#include "ui/ozone/common/stub_client_native_pixmap_factory.h"
+#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
+#include "ui/events/ozone/layout/stub/stub_keyboard_layout_engine.h"
+#include "ui/gfx/linux/client_native_pixmap_dmabuf.h"
+#include "ui/gfx/linux/client_native_pixmap_factory_dmabuf.h"
+#include "ui/ozone/common/bitmap_cursor_factory.h"
#include "ui/ozone/common/stub_overlay_manager.h"
-#include "ui/ozone/public/cursor_factory_ozone.h"
#include "ui/ozone/public/gpu_platform_support_host.h"
#include "ui/ozone/public/input_controller.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_screen.h"
#include "ui/ozone/public/system_input_injector.h"
+#include "ui/ozone/platform/wayland/gpu/wayland_gl_egl_utility.h"
#include "ui/platform_window/platform_window_delegate.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "surface_factory_qt.h"
#include "platform_window_qt.h"
+#if BUILDFLAG(USE_XKBCOMMON)
+#include "base/logging.h"
+#include "ui/events/ozone/layout/xkb/xkb_evdev_codes.h"
+#include "ui/events/ozone/layout/xkb/xkb_keyboard_layout_engine.h"
+
+#include <X11/XKBlib.h>
+#include <X11/extensions/XKBrules.h>
+#include <filesystem>
+#endif // BUILDFLAG(USE_XKBCOMMON)
+
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+#include "ui/gfx/linux/gpu_memory_buffer_support_x11.h"
+#include "ui/ozone/platform/x11/gl_egl_utility_x11.h"
+
+extern void *GetQtXDisplay();
+#endif
+
namespace ui {
namespace {
@@ -66,27 +55,48 @@ public:
~OzonePlatformQt() override;
ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override;
- ui::CursorFactoryOzone* GetCursorFactoryOzone() override;
+ ui::CursorFactory* GetCursorFactory() override;
GpuPlatformSupportHost* GetGpuPlatformSupportHost() override;
std::unique_ptr<PlatformWindow> CreatePlatformWindow(PlatformWindowDelegate* delegate, PlatformWindowInitProperties properties) override;
std::unique_ptr<display::NativeDisplayDelegate> CreateNativeDisplayDelegate() override;
ui::InputController* GetInputController() override;
std::unique_ptr<ui::SystemInputInjector> CreateSystemInputInjector() override;
ui::OverlayManagerOzone* GetOverlayManager() override;
- std::unique_ptr<InputMethod> CreateInputMethod(internal::InputMethodDelegate *delegate) override;
+ std::unique_ptr<InputMethod> CreateInputMethod(ImeKeyEventDispatcher *ime_key_event_dispatcher, gfx::AcceleratedWidget widget) override;
std::unique_ptr<ui::PlatformScreen> CreateScreen() override { return nullptr; }
+ const PlatformProperties &GetPlatformProperties() override;
+ PlatformGLEGLUtility *GetPlatformGLEGLUtility() override;
+
+ const PlatformRuntimeProperties &GetPlatformRuntimeProperties() override
+ {
+ static OzonePlatform::PlatformRuntimeProperties properties;
+ if (has_initialized_gpu()) {
+ // This property is set when the GetPlatformRuntimeProperties is
+ // called on the gpu process side.
+ properties.supports_native_pixmaps = surface_factory_ozone_->SupportsNativePixmaps();
+ }
+ return properties;
+ }
+ bool IsNativePixmapConfigSupported(gfx::BufferFormat format, gfx::BufferUsage usage) const override;
+
private:
- void InitializeUI(const ui::OzonePlatform::InitParams &) override;
+ bool InitializeUI(const ui::OzonePlatform::InitParams &) override;
void InitializeGPU(const ui::OzonePlatform::InitParams &) override;
+ void InitScreen(ui::PlatformScreen *) override {}
+
std::unique_ptr<QtWebEngineCore::SurfaceFactoryQt> surface_factory_ozone_;
- std::unique_ptr<CursorFactoryOzone> cursor_factory_ozone_;
+ std::unique_ptr<CursorFactory> cursor_factory_;
std::unique_ptr<GpuPlatformSupportHost> gpu_platform_support_host_;
std::unique_ptr<InputController> input_controller_;
std::unique_ptr<OverlayManagerOzone> overlay_manager_;
- DISALLOW_COPY_AND_ASSIGN(OzonePlatformQt);
+#if BUILDFLAG(USE_XKBCOMMON)
+ XkbEvdevCodes m_xkbEvdevCodeConverter;
+#endif
+ std::unique_ptr<KeyboardLayoutEngine> m_keyboardLayoutEngine;
+ std::unique_ptr<PlatformGLEGLUtility> gl_egl_utility_;
};
@@ -94,14 +104,29 @@ OzonePlatformQt::OzonePlatformQt() {}
OzonePlatformQt::~OzonePlatformQt() {}
+const ui::OzonePlatform::PlatformProperties &OzonePlatformQt::GetPlatformProperties()
+{
+ static base::NoDestructor<ui::OzonePlatform::PlatformProperties> properties;
+ static bool initialized = false;
+ if (!initialized) {
+ properties->fetch_buffer_formats_for_gmb_on_gpu = true;
+#if BUILDFLAG(USE_VAAPI)
+ properties->supports_vaapi = true;
+#endif
+ initialized = true;
+ }
+
+ return *properties;
+}
+
ui::SurfaceFactoryOzone* OzonePlatformQt::GetSurfaceFactoryOzone()
{
return surface_factory_ozone_.get();
}
-ui::CursorFactoryOzone* OzonePlatformQt::GetCursorFactoryOzone()
+ui::CursorFactory* OzonePlatformQt::GetCursorFactory()
{
- return cursor_factory_ozone_.get();
+ return cursor_factory_.get();
}
GpuPlatformSupportHost* OzonePlatformQt::GetGpuPlatformSupportHost()
@@ -135,32 +160,122 @@ std::unique_ptr<display::NativeDisplayDelegate> OzonePlatformQt::CreateNativeDis
return nullptr;
}
-void OzonePlatformQt::InitializeUI(const ui::OzonePlatform::InitParams &)
+#if BUILDFLAG(USE_XKBCOMMON)
+static std::string getCurrentKeyboardLayout()
{
+ Display *dpy = static_cast<Display *>(GetQtXDisplay());
+ if (dpy == nullptr)
+ return std::string();
+
+ int d;
+ if (!XkbQueryExtension(dpy, &d, &d, &d, &d, &d)) {
+ // no Xkb extension
+ return std::string();
+ }
+
+ XkbStateRec state;
+ if (XkbGetState(dpy, XkbUseCoreKbd, &state) != 0)
+ return std::string();
+
+ XkbRF_VarDefsRec vdr {}; // zero initialize it
+ struct Cleanup {
+ XkbRF_VarDefsRec &vdr;
+ Cleanup(XkbRF_VarDefsRec &vdr) : vdr(vdr) { }
+ ~Cleanup() {
+ free (vdr.model);
+ free (vdr.layout);
+ free (vdr.variant);
+ free (vdr.options);
+ }
+ } cleanup(vdr);
+ if (XkbRF_GetNamesProp(dpy, nullptr, &vdr) == 0)
+ return std::string();
+
+ if (!vdr.layout)
+ return std::string();
+
+ if (!vdr.variant)
+ return std::string(vdr.layout);
+
+ std::string layoutWithVariant = vdr.layout;
+ layoutWithVariant = layoutWithVariant.append("-");
+ layoutWithVariant = layoutWithVariant.append(vdr.variant);
+
+ return layoutWithVariant;
+}
+#endif // BUILDFLAG(USE_XKBCOMMON)
+
+bool OzonePlatformQt::InitializeUI(const ui::OzonePlatform::InitParams &)
+{
+#if BUILDFLAG(USE_XKBCOMMON)
+ std::string xkb_path("/usr/share/X11/xkb");
+ std::string layout = getCurrentKeyboardLayout();
+ if (layout.empty() || !std::filesystem::exists(xkb_path) || std::filesystem::is_empty(xkb_path)) {
+ LOG(WARNING) << "Failed to load keymap file, falling back to StubKeyboardLayoutEngine";
+ m_keyboardLayoutEngine = std::make_unique<StubKeyboardLayoutEngine>();
+ } else {
+ m_keyboardLayoutEngine = std::make_unique<XkbKeyboardLayoutEngine>(m_xkbEvdevCodeConverter);
+ m_keyboardLayoutEngine->SetCurrentLayoutByName(layout);
+ }
+#else
+ m_keyboardLayoutEngine = std::make_unique<StubKeyboardLayoutEngine>();
+#endif // BUILDFLAG(USE_XKBCOMMON)
+
+ KeyboardLayoutEngineManager::SetKeyboardLayoutEngine(m_keyboardLayoutEngine.get());
+
overlay_manager_.reset(new StubOverlayManager());
- cursor_factory_ozone_.reset(new CursorFactoryOzone());
- gpu_platform_support_host_.reset(ui::CreateStubGpuPlatformSupportHost());
input_controller_ = CreateStubInputController();
+ cursor_factory_.reset(new BitmapCursorFactory());
+ gpu_platform_support_host_.reset(ui::CreateStubGpuPlatformSupportHost());
+ return true;
}
-void OzonePlatformQt::InitializeGPU(const ui::OzonePlatform::InitParams &)
+void OzonePlatformQt::InitializeGPU(const ui::OzonePlatform::InitParams &params)
{
surface_factory_ozone_.reset(new QtWebEngineCore::SurfaceFactoryQt());
+
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (params.enable_native_gpu_memory_buffers) {
+ base::ThreadPool::PostTask(FROM_HERE,
+ base::BindOnce([]()
+ {
+ ui::GpuMemoryBufferSupportX11::GetInstance();
+ }));
+ }
+#endif
}
-std::unique_ptr<InputMethod> OzonePlatformQt::CreateInputMethod(internal::InputMethodDelegate *)
+std::unique_ptr<InputMethod> OzonePlatformQt::CreateInputMethod(ImeKeyEventDispatcher *, gfx::AcceleratedWidget)
{
NOTREACHED();
return nullptr;
}
+bool OzonePlatformQt::IsNativePixmapConfigSupported(gfx::BufferFormat format, gfx::BufferUsage usage) const
+{
+ return gfx::ClientNativePixmapDmaBuf::IsConfigurationSupported(format, usage);
+}
+
+PlatformGLEGLUtility *OzonePlatformQt::GetPlatformGLEGLUtility()
+{
+ if (!gl_egl_utility_) {
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GetQtXDisplay())
+ gl_egl_utility_ = std::make_unique<GLEGLUtilityX11>();
+ else
+#endif
+ gl_egl_utility_ = std::make_unique<WaylandGLEGLUtility>();
+ }
+ return gl_egl_utility_.get();
+}
+
} // namespace
OzonePlatform* CreateOzonePlatformQt() { return new OzonePlatformQt; }
-gfx::ClientNativePixmapFactory* CreateClientNativePixmapFactoryQt()
+gfx::ClientNativePixmapFactory *CreateClientNativePixmapFactoryQt()
{
- return CreateStubClientNativePixmapFactory();
+ return gfx::CreateClientNativePixmapFactoryDmabuf();
}
} // namespace ui
diff --git a/src/core/ozone/ozone_platform_qt.h b/src/core/ozone/ozone_platform_qt.h
index dee66beb3..23629b2eb 100644
--- a/src/core/ozone/ozone_platform_qt.h
+++ b/src/core/ozone/ozone_platform_qt.h
@@ -1,55 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef OZONE_PLATFORM_QT_H
#define OZONE_PLATFORM_QT_H
-#if defined(USE_OZONE)
-
-#include "ui/ozone/public/ozone_platform.h"
-
namespace ui {
+class OzonePlatform;
// Constructor hook for use in ozone_platform_list.cc
-OzonePlatform* CreateOzonePlatformQt();
+OzonePlatform *CreateOzonePlatformQt();
} // namespace ui
-#endif // defined(USE_OZONE)
#endif // OZONE_PLATFORM_QT_H
diff --git a/src/core/ozone/platform_window_qt.cpp b/src/core/ozone/platform_window_qt.cpp
index 757c042f0..4923f0f88 100644
--- a/src/core/ozone/platform_window_qt.cpp
+++ b/src/core/ozone/platform_window_qt.cpp
@@ -1,46 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#if defined(USE_OZONE)
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "ozone/platform_window_qt.h"
+#include "ui/base/cursor/platform_cursor.h"
#include "ui/events/ozone/events_ozone.h"
#include "ui/events/platform/platform_event_source.h"
#include "ui/platform_window/platform_window_delegate.h"
@@ -59,17 +24,24 @@ PlatformWindowQt::~PlatformWindowQt()
ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this);
}
-gfx::Rect PlatformWindowQt::GetBounds()
+gfx::Rect PlatformWindowQt::GetBoundsInPixels() const
{
return bounds_;
}
-void PlatformWindowQt::SetBounds(const gfx::Rect& bounds)
+void PlatformWindowQt::Close()
+{
+ delegate_->OnClosed();
+}
+
+void PlatformWindowQt::SetBoundsInPixels(const gfx::Rect& bounds)
{
if (bounds == bounds_)
return;
+ const bool origin_changed = (bounds_.origin() != bounds.origin());
+
bounds_ = bounds;
- delegate_->OnBoundsChanged(bounds);
+ delegate_->OnBoundsChanged({origin_changed});
}
bool PlatformWindowQt::CanDispatchEvent(const ui::PlatformEvent& /*ne*/)
@@ -77,11 +49,21 @@ bool PlatformWindowQt::CanDispatchEvent(const ui::PlatformEvent& /*ne*/)
return true;
}
+gfx::Rect PlatformWindowQt::GetBoundsInDIP() const
+{
+ return delegate_->ConvertRectToDIP(bounds_);
+}
+
+void PlatformWindowQt::SetBoundsInDIP(const gfx::Rect &bounds_in_dip)
+{
+ SetBoundsInPixels(delegate_->ConvertRectToPixels(bounds_in_dip));
+}
+
uint32_t PlatformWindowQt::DispatchEvent(const ui::PlatformEvent& native_event)
{
DispatchEventFromNativeUiEvent(
- native_event, base::Bind(&PlatformWindowDelegate::DispatchEvent,
- base::Unretained(delegate_)));
+ native_event, base::BindOnce(&PlatformWindowDelegate::DispatchEvent,
+ base::Unretained(delegate_)));
return ui::POST_DISPATCH_STOP_PROPAGATION;
}
diff --git a/src/core/ozone/platform_window_qt.h b/src/core/ozone/platform_window_qt.h
index b1021df9d..c025102bb 100644
--- a/src/core/ozone/platform_window_qt.h
+++ b/src/core/ozone/platform_window_qt.h
@@ -1,47 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PLATFORM_WINDOW_QT_H
#define PLATFORM_WINDOW_QT_H
#if defined(USE_OZONE)
+#include "ui/base/cursor/platform_cursor.h"
#include "ui/events/platform/platform_event_dispatcher.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
@@ -56,26 +21,28 @@ public:
PlatformWindowQt(PlatformWindowDelegate* delegate, const gfx::Rect& bounds);
~PlatformWindowQt() override;
// PlatformWindow:
- gfx::Rect GetBounds() override;
- void SetBounds(const gfx::Rect& bounds) override;
+ gfx::Rect GetBoundsInPixels() const override;
+ void SetBoundsInPixels(const gfx::Rect& bounds) override;
+ gfx::Rect GetBoundsInDIP() const override;
+ void SetBoundsInDIP(const gfx::Rect& bounds) override;
void Show(bool inactive = false) override { }
void Hide() override { }
- void Close() override { }
- bool IsVisible() const { return true; }
- void SetTitle(const base::string16&) override { }
+ void Close() override;
+ bool IsVisible() const override { return true; }
+ void SetTitle(const std::u16string&) override { }
void SetCapture() override { }
void ReleaseCapture() override { }
bool HasCapture() const override { return false; }
- void ToggleFullscreen() override { }
+ void SetFullscreen(bool, int64_t) override { }
void Maximize() override { }
void Minimize() override { }
void Restore() override { }
PlatformWindowState GetPlatformWindowState() const override { return PlatformWindowState::kUnknown; }
- void SetCursor(PlatformCursor) override { }
+ void SetCursor(scoped_refptr<PlatformCursor>) override { }
void MoveCursorTo(const gfx::Point&) override { }
void ConfineCursorToBounds(const gfx::Rect&) override { }
- void SetRestoredBoundsInPixels(const gfx::Rect& bounds) override { }
- gfx::Rect GetRestoredBoundsInPixels() const override { return gfx::Rect(); }
+ void SetRestoredBoundsInDIP(const gfx::Rect& bounds) override { }
+ gfx::Rect GetRestoredBoundsInDIP() const override { return gfx::Rect(); }
void Activate() override { }
void Deactivate() override { }
void SetUseNativeFrame(bool use_native_frame) override { }
@@ -92,8 +59,6 @@ public:
private:
PlatformWindowDelegate* delegate_;
gfx::Rect bounds_;
-
- DISALLOW_COPY_AND_ASSIGN(PlatformWindowQt);
};
}
diff --git a/src/core/ozone/surface_factory_qt.cpp b/src/core/ozone/surface_factory_qt.cpp
index 5420b4809..204f4d62d 100644
--- a/src/core/ozone/surface_factory_qt.cpp
+++ b/src/core/ozone/surface_factory_qt.cpp
@@ -1,85 +1,260 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2024 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#if defined(USE_OZONE)
#include "surface_factory_qt.h"
-#include "gl_context_qt.h"
-#include "gl_ozone_egl_qt.h"
-#if defined(USE_GLX)
-#include "gl_ozone_glx_qt.h"
-#endif
-#include "ui/gl/gl_surface.h"
-#include <QGuiApplication>
+#include "qtwebenginecoreglobal_p.h"
+#include "ozone/gl_context_qt.h"
+#include "ozone/gl_ozone_egl_qt.h"
-#if defined(USE_OZONE)
+#include "media/gpu/buildflags.h"
+#include "ui/gfx/linux/drm_util_linux.h"
+#include "ui/gfx/linux/gbm_buffer.h"
+#include "ui/gfx/linux/native_pixmap_dmabuf.h"
+#include "ui/gl/egl_util.h"
+#include "ui/ozone/buildflags.h"
+
+#include <QDebug>
+#include <QtGui/qtgui-config.h>
+
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+#include "ozone/gl_ozone_glx_qt.h"
+
+#include "ui/gfx/linux/gpu_memory_buffer_support_x11.h"
+#endif
+
+#if QT_CONFIG(webengine_vulkan)
+#include "compositor/vulkan_implementation_qt.h"
+#endif
-#include "ozone/gl_ozone_egl_qt.h"
-#include "ozone/surface_factory_qt.h"
-#include "ui/gl/gl_surface.h"
namespace QtWebEngineCore {
SurfaceFactoryQt::SurfaceFactoryQt()
{
- Q_ASSERT(qApp);
-#if defined(USE_GLX)
- if (GLContextHelper::getGlXConfig()) {
- m_impl = gl::kGLImplementationDesktopGL;
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GLContextHelper::getGlxPlatformInterface()) {
+ m_impl = { gl::GLImplementationParts(gl::kGLImplementationDesktopGL),
+ gl::GLImplementationParts(gl::kGLImplementationDisabled) };
m_ozone.reset(new ui::GLOzoneGLXQt());
} else
#endif
- if (GLContextHelper::getEGLConfig()) {
- m_impl = gl::kGLImplementationEGLGLES2;
+ if (GLContextHelper::getEglPlatformInterface()) {
+ m_impl = { gl::GLImplementationParts(gl::kGLImplementationEGLGLES2),
+ gl::GLImplementationParts(gl::kGLImplementationDesktopGL),
+ gl::GLImplementationParts(gl::kGLImplementationDisabled) };
m_ozone.reset(new ui::GLOzoneEGLQt());
} else {
- qFatal("No suitable graphics backend found\n");
+ m_impl = { gl::GLImplementationParts(gl::kGLImplementationDisabled) };
}
}
-std::vector<gl::GLImplementation> SurfaceFactoryQt::GetAllowedGLImplementations()
+std::vector<gl::GLImplementationParts> SurfaceFactoryQt::GetAllowedGLImplementations()
{
- return { m_impl };
+ return m_impl;
}
-ui::GLOzone* SurfaceFactoryQt::GetGLOzone(gl::GLImplementation implementation)
+ui::GLOzone *SurfaceFactoryQt::GetGLOzone(const gl::GLImplementationParts &implementation)
{
return m_ozone.get();
}
+#if BUILDFLAG(ENABLE_VULKAN)
+std::unique_ptr<gpu::VulkanImplementation>
+SurfaceFactoryQt::CreateVulkanImplementation(bool /*allow_protected_memory*/,
+ bool /*enforce_protected_memory*/)
+{
+#if QT_CONFIG(webengine_vulkan)
+ return std::make_unique<gpu::VulkanImplementationQt>();
+#else
+ return nullptr;
+#endif
+}
+#endif
+
+bool SurfaceFactoryQt::CanCreateNativePixmapForFormat(gfx::BufferFormat format)
+{
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GLContextHelper::getGlxPlatformInterface())
+ return ui::GpuMemoryBufferSupportX11::GetInstance()->CanCreateNativePixmapForFormat(format);
+#endif
+
+ if (GLContextHelper::getEglPlatformInterface())
+ return ui::SurfaceFactoryOzone::CanCreateNativePixmapForFormat(format);
+
+ return false;
+}
+
+scoped_refptr<gfx::NativePixmap> SurfaceFactoryQt::CreateNativePixmap(
+ gfx::AcceleratedWidget widget,
+ gpu::VulkanDeviceQueue *device_queue,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::BufferUsage usage,
+ absl::optional<gfx::Size> framebuffer_size)
+{
+ Q_ASSERT(SupportsNativePixmaps());
+
+#if QT_CONFIG(opengl)
+ if (framebuffer_size && !gfx::Rect(size).Contains(gfx::Rect(*framebuffer_size)))
+ return nullptr;
+
+ gfx::NativePixmapHandle handle;
+
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GLContextHelper::getGlxPlatformInterface()) {
+ auto gbmBuffer =
+ ui::GpuMemoryBufferSupportX11::GetInstance()->CreateBuffer(format, size, usage);
+ if (!gbmBuffer)
+ qFatal("Failed to create GBM buffer for GLX.");
+ handle = gbmBuffer->ExportHandle();
+ }
+#endif
+
+ if (GLContextHelper::getEglPlatformInterface()) {
+ int fd = -1;
+ int stride;
+ int offset;
+ uint64_t modifiers;
+ EGLHelper::instance()->queryDmaBuf(size.width(), size.height(), &fd, &stride, &offset,
+ &modifiers);
+ if (fd == -1)
+ qFatal("Failed to query DRM FD for EGL.");
+
+ const uint64_t planeSize = uint64_t(size.width()) * size.height() * 4;
+ gfx::NativePixmapPlane plane(stride, offset, planeSize, base::ScopedFD(::dup(fd)));
+
+ handle.planes.push_back(std::move(plane));
+ handle.modifier = modifiers;
+ }
+
+ return base::MakeRefCounted<gfx::NativePixmapDmaBuf>(size, format, std::move(handle));
+#else
+ return nullptr;
+#endif // QT_CONFIG(opengl)
+}
+
+void SurfaceFactoryQt::CreateNativePixmapAsync(
+ gfx::AcceleratedWidget widget,
+ gpu::VulkanDeviceQueue *device_queue,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::BufferUsage usage,
+ NativePixmapCallback callback)
+{
+ Q_ASSERT(SupportsNativePixmaps());
+ // CreateNativePixmap is non-blocking operation. Thus, it is safe to call it
+ // and return the result with the provided callback.
+ std::move(callback).Run(CreateNativePixmap(widget, device_queue, size, format, usage));
+}
+
+scoped_refptr<gfx::NativePixmap>
+SurfaceFactoryQt::CreateNativePixmapFromHandle(
+ gfx::AcceleratedWidget /*widget*/,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::NativePixmapHandle handle)
+{
+ Q_ASSERT(SupportsNativePixmaps());
+
+#if QT_CONFIG(opengl)
+ gfx::NativePixmapHandle bufferHandle;
+
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GLContextHelper::getGlxPlatformInterface()) {
+ auto gbmBuffer = ui::GpuMemoryBufferSupportX11::GetInstance()->CreateBufferFromHandle(
+ size, format, std::move(handle));
+ if (!gbmBuffer)
+ qFatal("Failed to create GBM buffer for GLX.");
+ bufferHandle = gbmBuffer->ExportHandle();
+ }
+#endif
+
+ if (GLContextHelper::getEglPlatformInterface()) {
+ const size_t numPlanes = handle.planes.size();
+ const uint32_t fourccFormat = ui::GetFourCCFormatFromBufferFormat(format);
+
+ std::vector<EGLAttrib> attrs;
+ attrs.push_back(EGL_WIDTH);
+ attrs.push_back(size.width());
+ attrs.push_back(EGL_HEIGHT);
+ attrs.push_back(size.height());
+ attrs.push_back(EGL_LINUX_DRM_FOURCC_EXT);
+ attrs.push_back(fourccFormat);
+ for (size_t planeIndex = 0; planeIndex < numPlanes; ++planeIndex) {
+ attrs.push_back(EGL_DMA_BUF_PLANE0_FD_EXT + planeIndex * 3);
+ attrs.push_back(handle.planes[planeIndex].fd.get());
+ attrs.push_back(EGL_DMA_BUF_PLANE0_OFFSET_EXT + planeIndex * 3);
+ attrs.push_back(handle.planes[planeIndex].offset);
+ attrs.push_back(EGL_DMA_BUF_PLANE0_PITCH_EXT + planeIndex * 3);
+ attrs.push_back(handle.planes[planeIndex].stride);
+ attrs.push_back(EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT + planeIndex * 2);
+ attrs.push_back(handle.modifier & 0xffffffff);
+ attrs.push_back(EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT + planeIndex * 2);
+ attrs.push_back(handle.modifier >> 32);
+ }
+ attrs.push_back(EGL_NONE);
+
+ EGLDisplay eglDisplay = GLContextHelper::getEGLDisplay();
+ EGLHelper *eglHelper = EGLHelper::instance();
+ auto *eglFun = eglHelper->functions();
+
+ EGLImage eglImage =
+ eglFun->eglCreateImage(eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT,
+ (EGLClientBuffer)NULL, attrs.data());
+ if (eglImage == EGL_NO_IMAGE_KHR) {
+ qFatal() << "Failed to import EGLImage:"
+ << ui::GetEGLErrorString(eglFun->eglGetError());
+ }
+
+ Q_ASSERT(numPlanes <= 3);
+ int fds[3];
+ int strides[3];
+ int offsets[3];
+ if (!eglFun->eglExportDMABUFImageMESA(eglDisplay, eglImage, fds, strides, offsets)) {
+ qFatal() << "Failed to export EGLImage:"
+ << ui::GetEGLErrorString(eglFun->eglGetError());
+ }
+
+ bufferHandle.modifier = handle.modifier;
+ for (size_t i = 0; i < numPlanes; ++i) {
+ int fd = fds[i];
+ int stride = strides[i];
+ int offset = offsets[i];
+ int size = handle.planes[i].size;
+
+ if (fd == -1) {
+ fd = fds[0];
+ stride = handle.planes[i].stride;
+ offset = handle.planes[i].offset;
+ }
+
+ gfx::NativePixmapPlane plane(stride, offset, size, base::ScopedFD(::dup(fd)));
+ bufferHandle.planes.push_back(std::move(plane));
+ }
+
+ eglFun->eglDestroyImage(eglDisplay, eglImage);
+ }
+
+ return base::MakeRefCounted<gfx::NativePixmapDmaBuf>(size, format, std::move(bufferHandle));
+#else
+ return nullptr;
+#endif // QT_CONFIG(opengl)
+}
+
+bool SurfaceFactoryQt::SupportsNativePixmaps() const
+{
+#if QT_CONFIG(opengl)
+#if BUILDFLAG(OZONE_PLATFORM_X11)
+ if (GLContextHelper::getGlxPlatformInterface())
+ return ui::GpuMemoryBufferSupportX11::GetInstance()->has_gbm_device();
+#endif // BUILDFLAG(OZONE_PLATFORM_X11)
+
+ if (GLContextHelper::getEglPlatformInterface())
+ return EGLHelper::instance()->isDmaBufSupported();
+#endif // QT_CONFIG(opengl)
+
+ return false;
+}
} // namespace QtWebEngineCore
#endif // defined(USE_OZONE)
diff --git a/src/core/ozone/surface_factory_qt.h b/src/core/ozone/surface_factory_qt.h
index dee41d948..07d7337ac 100644
--- a/src/core/ozone/surface_factory_qt.h
+++ b/src/core/ozone/surface_factory_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SURFACE_FACTORY_QT
#define SURFACE_FACTORY_QT
@@ -50,10 +14,36 @@ class SurfaceFactoryQt : public ui::SurfaceFactoryOzone
{
public:
SurfaceFactoryQt();
- std::vector<gl::GLImplementation> GetAllowedGLImplementations() override;
- ui::GLOzone* GetGLOzone(gl::GLImplementation implementation) override;
+ std::vector<gl::GLImplementationParts> GetAllowedGLImplementations() override;
+ ui::GLOzone *GetGLOzone(const gl::GLImplementationParts &implementation) override;
+#if BUILDFLAG(ENABLE_VULKAN)
+ std::unique_ptr<gpu::VulkanImplementation>
+ CreateVulkanImplementation(bool allow_protected_memory, bool enforce_protected_memory) override;
+#endif
+ bool CanCreateNativePixmapForFormat(gfx::BufferFormat format) override;
+ scoped_refptr<gfx::NativePixmap> CreateNativePixmap(
+ gfx::AcceleratedWidget widget,
+ gpu::VulkanDeviceQueue* device_queue,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::BufferUsage usage,
+ absl::optional<gfx::Size> framebuffer_size = absl::nullopt) override;
+ void CreateNativePixmapAsync(gfx::AcceleratedWidget widget,
+ gpu::VulkanDeviceQueue* device_queue,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::BufferUsage usage,
+ NativePixmapCallback callback) override;
+ scoped_refptr<gfx::NativePixmap> CreateNativePixmapFromHandle(
+ gfx::AcceleratedWidget widget,
+ gfx::Size size,
+ gfx::BufferFormat format,
+ gfx::NativePixmapHandle handle) override;
+
+ bool SupportsNativePixmaps() const;
+
private:
- gl::GLImplementation m_impl;
+ std::vector<gl::GLImplementationParts> m_impl;
std::unique_ptr<ui::GLOzone> m_ozone;
};
diff --git a/src/core/pdf_util_qt.cpp b/src/core/pdf_util_qt.cpp
new file mode 100644
index 000000000..9503f5910
--- /dev/null
+++ b/src/core/pdf_util_qt.cpp
@@ -0,0 +1,92 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE.Chromium file.
+
+#include "pdf_util_qt.h"
+
+#include <QtGlobal>
+
+#include "base/check.h"
+#include "chrome/common/webui_url_constants.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
+#include "extensions/buildflags/buildflags.h"
+#include "url/gurl.h"
+#include "url/origin.h"
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
+#include "extensions/common/constants.h"
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+namespace QtWebEngineCore {
+
+bool IsPdfExtensionOrigin(const url::Origin &origin)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ return origin.scheme() == extensions::kExtensionScheme
+ && origin.host() == extension_misc::kPdfExtensionId;
+#else
+ Q_UNUSED(origin);
+ return false;
+#endif
+}
+
+bool IsPdfInternalPluginAllowedOrigin(const url::Origin &origin)
+{
+ if (IsPdfExtensionOrigin(origin))
+ return true;
+
+ // Allow embedding the internal PDF plugin in chrome://print.
+ if (origin == url::Origin::Create(GURL(chrome::kChromeUIPrintURL)))
+ return true;
+
+ // Only allow the PDF plugin in the known, trustworthy origins that are
+ // allowlisted above. See also https://crbug.com/520422 and
+ // https://crbug.com/1027173.
+ return false;
+}
+
+content::RenderFrameHost *GetFullPagePlugin(content::WebContents *contents)
+{
+ content::RenderFrameHost *full_page_plugin = nullptr;
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ contents->ForEachRenderFrameHostWithAction([&full_page_plugin](content::RenderFrameHost *rfh) {
+ auto* guest_view = extensions::MimeHandlerViewGuest::FromRenderFrameHost(rfh);
+ if (guest_view && guest_view->is_full_page_plugin()) {
+ DCHECK_EQ(guest_view->GetGuestMainFrame(), rfh);
+ full_page_plugin = rfh;
+ return content::RenderFrameHost::FrameIterationAction::kStop;
+ }
+ return content::RenderFrameHost::FrameIterationAction::kContinue;
+ });
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+ return full_page_plugin;
+}
+
+content::RenderFrameHost *FindPdfChildFrame(content::RenderFrameHost *rfh)
+{
+ if (!rfh)
+ return nullptr;
+
+ if (!IsPdfExtensionOrigin(rfh->GetLastCommittedOrigin()))
+ return nullptr;
+
+ content::RenderFrameHost *pdf_rfh = nullptr;
+ rfh->ForEachRenderFrameHost([&pdf_rfh](content::RenderFrameHost *rfh) {
+ if (!rfh->GetProcess()->IsPdf())
+ return;
+
+ DCHECK(IsPdfExtensionOrigin(rfh->GetParent()->GetLastCommittedOrigin()));
+ DCHECK(!pdf_rfh);
+ pdf_rfh = rfh;
+ });
+
+ return pdf_rfh;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/pdf_util_qt.h b/src/core/pdf_util_qt.h
new file mode 100644
index 000000000..5ee211800
--- /dev/null
+++ b/src/core/pdf_util_qt.h
@@ -0,0 +1,34 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE.Chromium file.
+
+#ifndef PDF_UTIL_QT_H
+#define PDF_UTIL_QT_H
+
+namespace content {
+class RenderFrameHost;
+class WebContents;
+} // namespace content
+
+namespace url {
+class Origin;
+} // namespace url
+
+namespace QtWebEngineCore {
+
+// from chrome/common/pdf_util.cc:
+constexpr char kPDFMimeType[] = "application/pdf";
+
+bool IsPdfExtensionOrigin(const url::Origin &origin);
+bool IsPdfInternalPluginAllowedOrigin(const url::Origin &origin);
+
+// from chrome/browser/pdf/pdf_frame_util.cc:
+content::RenderFrameHost *GetFullPagePlugin(content::WebContents *contents);
+content::RenderFrameHost *FindPdfChildFrame(content::RenderFrameHost *rfh);
+
+} // namespace QtWebEngineCore
+
+#endif // PDF_UTIL_QT_H
diff --git a/src/core/permission_manager_qt.cpp b/src/core/permission_manager_qt.cpp
index 862a1c262..b6e727ef8 100644
--- a/src/core/permission_manager_qt.cpp
+++ b/src/core/permission_manager_qt.cpp
@@ -1,50 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "permission_manager_qt.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/permission_controller.h"
-#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
+#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "type_conversion.h"
#include "web_contents_delegate_qt.h"
@@ -52,39 +16,48 @@
namespace QtWebEngineCore {
-static ProfileAdapter::PermissionType toQt(content::PermissionType type)
+static ProfileAdapter::PermissionType toQt(blink::PermissionType type)
{
switch (type) {
- case content::PermissionType::GEOLOCATION:
+ case blink::PermissionType::GEOLOCATION:
return ProfileAdapter::GeolocationPermission;
- case content::PermissionType::AUDIO_CAPTURE:
+ case blink::PermissionType::AUDIO_CAPTURE:
return ProfileAdapter::AudioCapturePermission;
- case content::PermissionType::VIDEO_CAPTURE:
+ case blink::PermissionType::VIDEO_CAPTURE:
return ProfileAdapter::VideoCapturePermission;
- case content::PermissionType::CLIPBOARD_READ:
- return ProfileAdapter::ClipboardRead;
- case content::PermissionType::CLIPBOARD_WRITE:
- return ProfileAdapter::ClipboardWrite;
- case content::PermissionType::NOTIFICATIONS:
+ // We treat these both as read/write since we do not currently have a
+ // ClipboardSanitizedWrite feature.
+ case blink::PermissionType::CLIPBOARD_READ_WRITE:
+ case blink::PermissionType::CLIPBOARD_SANITIZED_WRITE:
+ return ProfileAdapter::ClipboardReadWrite;
+ case blink::PermissionType::NOTIFICATIONS:
return ProfileAdapter::NotificationPermission;
- case content::PermissionType::ACCESSIBILITY_EVENTS:
+ case blink::PermissionType::LOCAL_FONTS:
+ return ProfileAdapter::LocalFontsPermission;
+ case blink::PermissionType::ACCESSIBILITY_EVENTS:
+ case blink::PermissionType::CAMERA_PAN_TILT_ZOOM:
+ case blink::PermissionType::WINDOW_MANAGEMENT:
return ProfileAdapter::UnsupportedPermission;
- case content::PermissionType::FLASH:
- case content::PermissionType::MIDI_SYSEX:
- case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
- case content::PermissionType::MIDI:
- case content::PermissionType::DURABLE_STORAGE:
- case content::PermissionType::BACKGROUND_SYNC:
- case content::PermissionType::SENSORS:
- case content::PermissionType::PAYMENT_HANDLER:
- case content::PermissionType::BACKGROUND_FETCH:
- case content::PermissionType::IDLE_DETECTION:
- case content::PermissionType::PERIODIC_BACKGROUND_SYNC:
- case content::PermissionType::WAKE_LOCK_SCREEN:
- case content::PermissionType::WAKE_LOCK_SYSTEM:
- case content::PermissionType::NFC:
- case content::PermissionType::NUM:
- NOTIMPLEMENTED() << "Unsupported permission type: " << static_cast<int>(type);
+ case blink::PermissionType::MIDI_SYSEX:
+ case blink::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
+ case blink::PermissionType::MIDI:
+ case blink::PermissionType::DURABLE_STORAGE:
+ case blink::PermissionType::BACKGROUND_SYNC:
+ case blink::PermissionType::SENSORS:
+ case blink::PermissionType::PAYMENT_HANDLER:
+ case blink::PermissionType::BACKGROUND_FETCH:
+ case blink::PermissionType::IDLE_DETECTION:
+ case blink::PermissionType::PERIODIC_BACKGROUND_SYNC:
+ case blink::PermissionType::WAKE_LOCK_SCREEN:
+ case blink::PermissionType::WAKE_LOCK_SYSTEM:
+ case blink::PermissionType::NFC:
+ case blink::PermissionType::AR:
+ case blink::PermissionType::VR:
+ case blink::PermissionType::STORAGE_ACCESS_GRANT:
+ case blink::PermissionType::DISPLAY_CAPTURE:
+ case blink::PermissionType::TOP_LEVEL_STORAGE_ACCESS:
+ case blink::PermissionType::NUM:
+ LOG(INFO) << "Unexpected unsupported permission type: " << static_cast<int>(type);
break;
}
return ProfileAdapter::UnsupportedPermission;
@@ -95,6 +68,8 @@ static bool canRequestPermissionFor(ProfileAdapter::PermissionType type)
switch (type) {
case ProfileAdapter::GeolocationPermission:
case ProfileAdapter::NotificationPermission:
+ case ProfileAdapter::ClipboardReadWrite:
+ case ProfileAdapter::LocalFontsPermission:
return true;
default:
break;
@@ -114,9 +89,22 @@ static blink::mojom::PermissionStatus toBlink(ProfileAdapter::PermissionState re
}
}
+static blink::mojom::PermissionStatus getStatusFromSettings(blink::PermissionType type, WebEngineSettings *settings)
+{
+ switch (type) {
+ case blink::PermissionType::CLIPBOARD_READ_WRITE:
+ case blink::PermissionType::CLIPBOARD_SANITIZED_WRITE:
+ if (settings->testAttribute(QWebEngineSettings::JavascriptCanPaste)
+ && settings->testAttribute(QWebEngineSettings::JavascriptCanAccessClipboard))
+ return blink::mojom::PermissionStatus::GRANTED;
+ return blink::mojom::PermissionStatus::ASK;
+ default:
+ return blink::mojom::PermissionStatus::ASK;
+ }
+}
+
PermissionManagerQt::PermissionManagerQt()
: m_requestIdCount(0)
- , m_subscriberIdCount(0)
{
}
@@ -126,8 +114,8 @@ PermissionManagerQt::~PermissionManagerQt()
void PermissionManagerQt::permissionRequestReply(const QUrl &url, ProfileAdapter::PermissionType type, ProfileAdapter::PermissionState reply)
{
- // Normalize the QUrl to GURL origin form.
- const GURL gorigin = toGurl(url).GetOrigin();
+ // Normalize the QUrl to Chromium origin form.
+ const GURL gorigin = toGurl(url).DeprecatedGetOriginAsURL();
const QUrl origin = gorigin.is_empty() ? url : toQt(gorigin);
if (origin.isEmpty())
return;
@@ -161,7 +149,7 @@ void PermissionManagerQt::permissionRequestReply(const QUrl &url, ProfileAdapter
bool answerable = true;
std::vector<blink::mojom::PermissionStatus> result;
result.reserve(it->types.size());
- for (content::PermissionType permission : it->types) {
+ for (blink::PermissionType permission : it->types) {
const ProfileAdapter::PermissionType permissionType = toQt(permission);
if (permissionType == ProfileAdapter::UnsupportedPermission) {
result.push_back(blink::mojom::PermissionStatus::DENIED);
@@ -194,84 +182,61 @@ bool PermissionManagerQt::checkPermission(const QUrl &origin, ProfileAdapter::Pe
return m_permissions.contains(key) && m_permissions[key];
}
-int PermissionManagerQt::RequestPermission(content::PermissionType permission,
- content::RenderFrameHost *frameHost,
- const GURL& requesting_origin,
- bool /*user_gesture*/,
- base::OnceCallback<void(blink::mojom::PermissionStatus)> callback)
+void PermissionManagerQt::RequestPermissions(content::RenderFrameHost *frameHost,
+ const content::PermissionRequestDescription &requestDescription,
+ base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback)
{
- WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(
- content::WebContents::FromRenderFrameHost(frameHost)->GetDelegate());
- Q_ASSERT(contentsDelegate);
-
- ProfileAdapter::PermissionType permissionType = toQt(permission);
- if (permissionType == ProfileAdapter::ClipboardRead) {
- WebEngineSettings *settings = contentsDelegate->webEngineSettings();
- if (settings->testAttribute(WebEngineSettings::JavascriptCanAccessClipboard)
- && settings->testAttribute(WebEngineSettings::JavascriptCanPaste))
- std::move(callback).Run(blink::mojom::PermissionStatus::GRANTED);
- else
- std::move(callback).Run(blink::mojom::PermissionStatus::DENIED);
- return content::PermissionController::kNoPendingOperation;
- } else if (!canRequestPermissionFor(permissionType)) {
- std::move(callback).Run(blink::mojom::PermissionStatus::DENIED);
- return content::PermissionController::kNoPendingOperation;
+ if (requestDescription.requesting_origin.is_empty()) {
+ std::move(callback).Run(std::vector<content::PermissionStatus>(requestDescription.permissions.size(), blink::mojom::PermissionStatus::DENIED));
+ return;
}
- int request_id = ++m_requestIdCount;
- auto requestOrigin = toQt(requesting_origin);
- m_requests.push_back({ request_id, permissionType, requestOrigin, std::move(callback) });
- contentsDelegate->requestFeaturePermission(permissionType, requestOrigin);
- return request_id;
-}
-
-int PermissionManagerQt::RequestPermissions(const std::vector<content::PermissionType>& permissions,
- content::RenderFrameHost* frameHost,
- const GURL& requesting_origin,
- bool /*user_gesture*/,
- base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback)
-{
WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(
content::WebContents::FromRenderFrameHost(frameHost)->GetDelegate());
Q_ASSERT(contentsDelegate);
bool answerable = true;
- std::vector<blink::mojom::PermissionStatus> result;
- result.reserve(permissions.size());
- for (content::PermissionType permission : permissions) {
+ std::vector<content::PermissionStatus> result;
+ result.reserve(requestDescription.permissions.size());
+ for (blink::PermissionType permission : requestDescription.permissions) {
const ProfileAdapter::PermissionType permissionType = toQt(permission);
- if (permissionType == ProfileAdapter::UnsupportedPermission)
+ if (permissionType == ProfileAdapter::UnsupportedPermission) {
result.push_back(blink::mojom::PermissionStatus::DENIED);
- else if (permissionType == ProfileAdapter::ClipboardRead) {
- WebEngineSettings *settings = contentsDelegate->webEngineSettings();
- if (settings->testAttribute(WebEngineSettings::JavascriptCanAccessClipboard)
- && settings->testAttribute(WebEngineSettings::JavascriptCanPaste))
- result.push_back(blink::mojom::PermissionStatus::GRANTED);
- else
- result.push_back(blink::mojom::PermissionStatus::DENIED);
- } else {
+ continue;
+ }
+
+ auto status = getStatusFromSettings(permission, contentsDelegate->webEngineSettings());
+ if (status == blink::mojom::PermissionStatus::ASK) {
answerable = false;
break;
- }
+ } else
+ result.push_back(status);
}
if (answerable) {
std::move(callback).Run(result);
- return content::PermissionController::kNoPendingOperation;
+ return;
}
int request_id = ++m_requestIdCount;
- auto requestOrigin = toQt(requesting_origin);
- m_multiRequests.push_back({ request_id, permissions, requestOrigin, std::move(callback) });
- for (content::PermissionType permission : permissions) {
+ auto requestOrigin = toQt(requestDescription.requesting_origin);
+ m_multiRequests.push_back({ request_id, requestDescription.permissions, requestOrigin, std::move(callback) });
+ for (blink::PermissionType permission : requestDescription.permissions) {
const ProfileAdapter::PermissionType permissionType = toQt(permission);
if (canRequestPermissionFor(permissionType))
contentsDelegate->requestFeaturePermission(permissionType, requestOrigin);
}
- return request_id;
+}
+
+void PermissionManagerQt::RequestPermissionsFromCurrentDocument(content::RenderFrameHost *frameHost,
+ const content::PermissionRequestDescription &requestDescription,
+ base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback)
+{
+
+ RequestPermissions(frameHost, requestDescription, std::move(callback));
}
blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatus(
- content::PermissionType permission,
+ blink::PermissionType permission,
const GURL& requesting_origin,
const GURL& /*embedding_origin*/)
{
@@ -287,31 +252,56 @@ blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatus(
return blink::mojom::PermissionStatus::DENIED;
}
-blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatusForFrame(
- content::PermissionType permission,
- content::RenderFrameHost *render_frame_host,
- const GURL &requesting_origin)
+blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatusForCurrentDocument(
+ blink::PermissionType permission,
+ content::RenderFrameHost *render_frame_host)
{
- if (permission == content::PermissionType::CLIPBOARD_READ ||
- permission == content::PermissionType::CLIPBOARD_WRITE) {
+ if (permission == blink::PermissionType::CLIPBOARD_READ_WRITE ||
+ permission == blink::PermissionType::CLIPBOARD_SANITIZED_WRITE) {
WebContentsDelegateQt *delegate = static_cast<WebContentsDelegateQt *>(
content::WebContents::FromRenderFrameHost(render_frame_host)->GetDelegate());
- if (!delegate->webEngineSettings()->testAttribute(WebEngineSettings::JavascriptCanAccessClipboard))
- return blink::mojom::PermissionStatus::DENIED;
- if (permission == content::PermissionType::CLIPBOARD_READ &&
- !delegate->webEngineSettings()->testAttribute(WebEngineSettings::JavascriptCanPaste))
- return blink::mojom::PermissionStatus::DENIED;
- return blink::mojom::PermissionStatus::GRANTED;
+ Q_ASSERT(delegate);
+ auto status = getStatusFromSettings(permission, delegate->webEngineSettings());
+ if (status != blink::mojom::PermissionStatus::ASK)
+ return status;
}
return GetPermissionStatus(
permission,
- requesting_origin,
- content::WebContents::FromRenderFrameHost(render_frame_host)->GetLastCommittedURL().GetOrigin());
+ render_frame_host->GetLastCommittedOrigin().GetURL(),
+ render_frame_host->GetLastCommittedOrigin().GetURL());
+}
+
+blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatusForWorker(
+ blink::PermissionType permission,
+ content::RenderProcessHost *render_process_host,
+ const GURL &url)
+{
+ return GetPermissionStatus(permission, url, url);
+}
+
+blink::mojom::PermissionStatus PermissionManagerQt::GetPermissionStatusForEmbeddedRequester(
+ blink::PermissionType permission,
+ content::RenderFrameHost *render_frame_host,
+ const url::Origin &requesting_origin)
+{
+ return GetPermissionStatus(permission, requesting_origin.GetURL(),
+ render_frame_host->GetLastCommittedOrigin().GetURL());
+}
+
+content::PermissionResult PermissionManagerQt::GetPermissionResultForOriginWithoutContext(
+ blink::PermissionType permission,
+ const url::Origin &requesting_origin,
+ const url::Origin &embedding_origin)
+{
+ blink::mojom::PermissionStatus status =
+ GetPermissionStatus(permission, requesting_origin.GetURL(), embedding_origin.GetURL());
+
+ return content::PermissionResult(status, content::PermissionStatusSource::UNSPECIFIED);
}
void PermissionManagerQt::ResetPermission(
- content::PermissionType permission,
+ blink::PermissionType permission,
const GURL& requesting_origin,
const GURL& /*embedding_origin*/)
{
@@ -323,19 +313,20 @@ void PermissionManagerQt::ResetPermission(
m_permissions.remove(key);
}
-int PermissionManagerQt::SubscribePermissionStatusChange(
- content::PermissionType permission,
+content::PermissionControllerDelegate::SubscriptionId PermissionManagerQt::SubscribePermissionStatusChange(
+ blink::PermissionType permission,
+ content::RenderProcessHost * /*render_process_host*/,
content::RenderFrameHost * /* render_frame_host */,
const GURL& requesting_origin,
base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback)
{
- int subscriber_id = ++m_subscriberIdCount;
+ auto subscriber_id = subscription_id_generator_.GenerateNextId();
m_subscribers.insert( { subscriber_id,
Subscription { toQt(permission), toQt(requesting_origin), std::move(callback) } });
return subscriber_id;
}
-void PermissionManagerQt::UnsubscribePermissionStatusChange(int subscription_id)
+void PermissionManagerQt::UnsubscribePermissionStatusChange(content::PermissionControllerDelegate::SubscriptionId subscription_id)
{
if (!m_subscribers.erase(subscription_id))
LOG(WARNING) << "PermissionManagerQt::UnsubscribePermissionStatusChange called on unknown subscription id" << subscription_id;
diff --git a/src/core/permission_manager_qt.h b/src/core/permission_manager_qt.h
index e046174df..b91498d3d 100644
--- a/src/core/permission_manager_qt.h
+++ b/src/core/permission_manager_qt.h
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PERMISSION_MANAGER_QT_H
#define PERMISSION_MANAGER_QT_H
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "content/public/browser/permission_controller_delegate.h"
#include "profile_adapter.h"
@@ -49,8 +13,8 @@
namespace QtWebEngineCore {
-class PermissionManagerQt : public content::PermissionControllerDelegate {
-
+class PermissionManagerQt : public content::PermissionControllerDelegate
+{
public:
PermissionManagerQt();
~PermissionManagerQt();
@@ -59,43 +23,42 @@ public:
bool checkPermission(const QUrl &origin, ProfileAdapter::PermissionType type);
// content::PermissionManager implementation:
- int RequestPermission(
- content::PermissionType permission,
- content::RenderFrameHost* render_frame_host,
- const GURL& requesting_origin,
- bool user_gesture,
- base::OnceCallback<void(blink::mojom::PermissionStatus)> callback) override;
-
blink::mojom::PermissionStatus GetPermissionStatus(
- content::PermissionType permission,
+ blink::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) override;
- blink::mojom::PermissionStatus GetPermissionStatusForFrame(
- content::PermissionType permission,
- content::RenderFrameHost *render_frame_host,
- const GURL& requesting_origin) override;
+ blink::mojom::PermissionStatus GetPermissionStatusForCurrentDocument(blink::PermissionType, content::RenderFrameHost *) override;
+
+ blink::mojom::PermissionStatus GetPermissionStatusForWorker(blink::PermissionType, content::RenderProcessHost *, const GURL &) override;
+
+ blink::mojom::PermissionStatus GetPermissionStatusForEmbeddedRequester(blink::PermissionType, content::RenderFrameHost*, const url::Origin&) override;
+
+ content::PermissionResult GetPermissionResultForOriginWithoutContext(blink::PermissionType, const url::Origin&, const url::Origin&) override;
void ResetPermission(
- content::PermissionType permission,
+ blink::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) override;
- int RequestPermissions(
- const std::vector<content::PermissionType>& permission,
- content::RenderFrameHost* render_frame_host,
- const GURL& requesting_origin,
- bool user_gesture,
- base::OnceCallback<void(
- const std::vector<blink::mojom::PermissionStatus>&)> callback) override;
+ void RequestPermissions(
+ content::RenderFrameHost *render_frame_host,
+ const content::PermissionRequestDescription &request_description,
+ base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback) override;
+
+ void RequestPermissionsFromCurrentDocument(
+ content::RenderFrameHost *render_frame_host,
+ const content::PermissionRequestDescription &request_description,
+ base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus> &)> callback) override;
- int SubscribePermissionStatusChange(
- content::PermissionType permission,
+ content::PermissionControllerDelegate::SubscriptionId SubscribePermissionStatusChange(
+ blink::PermissionType permission,
+ content::RenderProcessHost* render_process_host,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback) override;
- void UnsubscribePermissionStatusChange(int subscription_id) override;
+ void UnsubscribePermissionStatusChange(content::PermissionControllerDelegate::SubscriptionId subscription_id) override;
private:
QHash<QPair<QUrl, ProfileAdapter::PermissionType>, bool> m_permissions;
@@ -107,7 +70,7 @@ private:
};
struct MultiRequest {
int id;
- std::vector<content::PermissionType> types;
+ std::vector<blink::PermissionType> types;
QUrl origin;
base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback;
};
@@ -118,9 +81,9 @@ private:
};
std::vector<Request> m_requests;
std::vector<MultiRequest> m_multiRequests;
- std::map<int, Subscription> m_subscribers;
+ std::map<content::PermissionControllerDelegate::SubscriptionId, Subscription> m_subscribers;
+ content::PermissionControllerDelegate::SubscriptionId::Generator subscription_id_generator_;
int m_requestIdCount;
- int m_subscriberIdCount;
};
diff --git a/src/core/platform_notification_service_qt.cpp b/src/core/platform_notification_service_qt.cpp
index 5f3017dcf..182a5ad84 100644
--- a/src/core/platform_notification_service_qt.cpp
+++ b/src/core/platform_notification_service_qt.cpp
@@ -1,48 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "platform_notification_service_qt.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/permission_type.h"
#include "content/public/browser/notification_event_dispatcher.h"
#include "ui/message_center/public/cpp/notification_delegate.h"
@@ -50,7 +13,6 @@
#include "profile_adapter_client.h"
#include "profile_qt.h"
#include "user_notification_controller.h"
-#include "resource_context_qt.h"
#include "type_conversion.h"
#include <QSharedPointer>
@@ -90,7 +52,7 @@ struct PersistentNotificationDelegate : UserNotificationController::Delegate {
virtual void clicked() override {
Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (auto inst = content::NotificationEventDispatcher::GetInstance())
- inst->DispatchNotificationClickEvent(browser_context, notification_id, origin, base::nullopt, base::nullopt, base::DoNothing());
+ inst->DispatchNotificationClickEvent(browser_context, notification_id, origin, absl::nullopt, absl::nullopt, base::DoNothing());
}
virtual void closed(bool by_user) override {
@@ -114,6 +76,7 @@ PlatformNotificationServiceQt::~PlatformNotificationServiceQt() {}
void PlatformNotificationServiceQt::DisplayNotification(
const std::string &notification_id,
const GURL &origin,
+ const GURL &document_url,
const blink::PlatformNotificationData &notificationData,
const blink::NotificationResources &notificationResources)
{
diff --git a/src/core/platform_notification_service_qt.h b/src/core/platform_notification_service_qt.h
index 12aa2619b..bf8fcca04 100644
--- a/src/core/platform_notification_service_qt.h
+++ b/src/core/platform_notification_service_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PLATFORM_NOTIFICATION_SERVICE_QT_H
#define PLATFORM_NOTIFICATION_SERVICE_QT_H
@@ -58,6 +22,7 @@ public:
// |cancel_callback| argument. This method must be called on the UI thread.
void DisplayNotification(const std::string& notification_id,
const GURL& origin,
+ const GURL& document_url,
const blink::PlatformNotificationData& notificationData,
const blink::NotificationResources& notificationResources) override;
diff --git a/src/core/pointer_device_qt.cpp b/src/core/pointer_device_qt.cpp
new file mode 100644
index 000000000..a3d7f3d37
--- /dev/null
+++ b/src/core/pointer_device_qt.cpp
@@ -0,0 +1,102 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chromium/ui/base/pointer/pointer_device_linux.cc
+// Copyright (c) 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "ui/base/pointer/pointer_device.h"
+
+#include <algorithm>
+#include <QPointingDevice>
+
+namespace ui {
+
+namespace {
+
+bool IsTouchScreen(const QInputDevice *device)
+{
+ return device->type() & QPointingDevice::DeviceType::TouchScreen;
+}
+
+bool IsMouseOrTouchpad(const QInputDevice *device)
+{
+ return device->type()
+ & (QPointingDevice::DeviceType::TouchPad | QPointingDevice::DeviceType::Mouse);
+}
+
+bool IsTouchDevicePresent()
+{
+ QList<const QInputDevice *> devices = QInputDevice::devices();
+ return std::any_of(devices.constBegin(), devices.constEnd(), IsTouchScreen);
+}
+
+bool IsMouseOrTouchpadPresent()
+{
+ QList<const QInputDevice *> devices = QInputDevice::devices();
+ return std::any_of(devices.constBegin(), devices.constEnd(), IsMouseOrTouchpad);
+}
+
+} // namespace
+
+int GetAvailablePointerTypes()
+{
+ int available_pointer_types = POINTER_TYPE_NONE;
+ if (IsMouseOrTouchpadPresent())
+ available_pointer_types |= POINTER_TYPE_FINE;
+
+ if (IsTouchDevicePresent())
+ available_pointer_types |= POINTER_TYPE_COARSE;
+
+ return available_pointer_types;
+}
+
+int GetAvailableHoverTypes()
+{
+ if (IsMouseOrTouchpadPresent())
+ return HOVER_TYPE_HOVER;
+
+ return HOVER_TYPE_NONE;
+}
+
+TouchScreensAvailability GetTouchScreensAvailability()
+{
+ if (!IsTouchDevicePresent())
+ return TouchScreensAvailability::NONE;
+
+ return TouchScreensAvailability::ENABLED;
+}
+
+int MaxTouchPoints()
+{
+ int max_touch = 0;
+ for (const auto *device : QInputDevice::devices()) {
+ if (IsTouchScreen(device)) {
+ int points = static_cast<const QPointingDevice *>(device)->maximumPoints();
+ max_touch = points > max_touch ? points : max_touch;
+ }
+ }
+
+ return max_touch;
+}
+
+PointerType GetPrimaryPointerType(int available_pointer_types)
+{
+ if (available_pointer_types & POINTER_TYPE_FINE)
+ return POINTER_TYPE_FINE;
+ if (available_pointer_types & POINTER_TYPE_COARSE)
+ return POINTER_TYPE_COARSE;
+ Q_ASSERT(available_pointer_types == POINTER_TYPE_NONE);
+ return POINTER_TYPE_NONE;
+}
+
+HoverType GetPrimaryHoverType(int available_hover_types)
+{
+ if (available_hover_types & HOVER_TYPE_HOVER)
+ return HOVER_TYPE_HOVER;
+ Q_ASSERT(available_hover_types == HOVER_TYPE_NONE);
+ return HOVER_TYPE_NONE;
+}
+
+} // namespace ui
diff --git a/src/core/pref_service_adapter.cpp b/src/core/pref_service_adapter.cpp
index 4ded70d07..544a84de1 100644
--- a/src/core/pref_service_adapter.cpp
+++ b/src/core/pref_service_adapter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "pref_service_adapter.h"
@@ -43,8 +7,10 @@
#include "type_conversion.h"
#include "web_engine_context.h"
+#include "base/threading/thread_restrictions.h"
#include "chrome/browser/prefs/chrome_command_line_pref_store.h"
#include "content/public/browser/browser_thread.h"
+#include "components/autofill/core/common/autofill_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/in_memory_pref_store.h"
@@ -52,12 +18,17 @@
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/pref_registry_simple.h"
+#include "components/signin/internal/identity_manager/account_tracker_service.h"
+#include "components/signin/public/base/signin_pref_names.h"
#include "components/user_prefs/user_prefs.h"
#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
#include "chrome/common/pref_names.h"
#include "extensions/buildflags/buildflags.h"
#include "content/public/browser/browser_context.h"
+#include "components/pref_registry/pref_registry_syncable.h"
+#include "chrome/browser/devtools/devtools_settings.h"
+
#if QT_CONFIG(webengine_spellchecker)
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "components/spellcheck/browser/pref_names.h"
@@ -71,6 +42,10 @@
#include "extensions/common/constants.h"
#endif
+#if defined(Q_OS_WIN)
+#include "components/os_crypt/sync/os_crypt.h"
+#endif
+
namespace {
static const char kPrefMediaDeviceIDSalt[] = "qtwebengine.media_device_salt_id";
}
@@ -82,15 +57,16 @@ void PrefServiceAdapter::setup(const ProfileAdapter &profileAdapter)
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
PrefServiceFactory factory;
factory.set_command_line_prefs(base::MakeRefCounted<ChromeCommandLinePrefStore>(
- WebEngineContext::commandLine()));
+ base::CommandLine::ForCurrentProcess()));
QString userPrefStorePath = profileAdapter.dataPath();
- if (userPrefStorePath.isEmpty() || profileAdapter.isOffTheRecord()) {
- factory.set_user_prefs(new InMemoryPrefStore);
- } else {
+ if (!profileAdapter.isOffTheRecord() && !userPrefStorePath.isEmpty() &&
+ const_cast<ProfileAdapter *>(&profileAdapter)->ensureDataPathExists()) {
userPrefStorePath += QDir::separator();
userPrefStorePath += QStringLiteral("user_prefs.json");
factory.set_user_prefs(base::MakeRefCounted<JsonPrefStore>(toFilePath(userPrefStorePath)));
+ } else {
+ factory.set_user_prefs(new InMemoryPrefStore);
}
auto registry = base::MakeRefCounted<PrefRegistrySimple>();
@@ -101,7 +77,7 @@ void PrefServiceAdapter::setup(const ProfileAdapter &profileAdapter)
registry->RegisterStringPref(language::prefs::kAcceptLanguages, std::string());
registry->RegisterListPref(spellcheck::prefs::kSpellCheckDictionaries);
registry->RegisterListPref(spellcheck::prefs::kSpellCheckForcedDictionaries);
- registry->RegisterListPref(spellcheck::prefs::kSpellCheckBlacklistedDictionaries);
+ registry->RegisterListPref(spellcheck::prefs::kSpellCheckBlocklistedDictionaries);
registry->RegisterStringPref(spellcheck::prefs::kSpellCheckDictionary, std::string());
registry->RegisterBooleanPref(spellcheck::prefs::kSpellCheckEnable, false);
registry->RegisterBooleanPref(spellcheck::prefs::kSpellCheckUseSpellingService, false);
@@ -109,20 +85,33 @@ void PrefServiceAdapter::setup(const ProfileAdapter &profileAdapter)
registry->RegisterBooleanPref(prefs::kShowInternalAccessibilityTree, false);
registry->RegisterBooleanPref(prefs::kAccessibilityImageLabelsEnabled, false);
registry->RegisterIntegerPref(prefs::kNotificationNextPersistentId, 10000);
+ registry->RegisterDictionaryPref(prefs::kPushMessagingAppIdentifierMap);
+ registry->RegisterListPref(prefs::kAccountInfo);
+ registry->RegisterStringPref(prefs::kGoogleServicesLastUsername,
+ std::string());
+ registry->RegisterStringPref(prefs::kGoogleServicesAccountId, std::string());
+ registry->RegisterBooleanPref(prefs::kGoogleServicesConsentedToSync, false);
+ registry->RegisterBooleanPref(prefs::kAutologinEnabled, true);
+ registry->RegisterListPref(prefs::kReverseAutologinRejectedEmailList);
+ registry->RegisterBooleanPref(prefs::kSigninAllowed, true);
+ registry->RegisterBooleanPref(prefs::kSignedInWithCredentialProvider, false);
+#if defined(Q_OS_WIN)
+ OSCrypt::RegisterLocalPrefs(registry.get());
+#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
registry->RegisterDictionaryPref(extensions::pref_names::kExtensions);
registry->RegisterListPref(extensions::pref_names::kInstallAllowList);
registry->RegisterListPref(extensions::pref_names::kInstallDenyList);
registry->RegisterDictionaryPref(extensions::pref_names::kInstallForceList);
- registry->RegisterDictionaryPref(extensions::pref_names::kLoginScreenExtensions);
registry->RegisterListPref(extensions::pref_names::kAllowedTypes);
registry->RegisterBooleanPref(extensions::pref_names::kStorageGarbageCollect, false);
registry->RegisterListPref(extensions::pref_names::kAllowedInstallSites);
registry->RegisterStringPref(extensions::pref_names::kLastChromeVersion, std::string());
- registry->RegisterListPref(extensions::pref_names::kNativeMessagingBlacklist);
- registry->RegisterListPref(extensions::pref_names::kNativeMessagingWhitelist);
+ registry->RegisterListPref(extensions::pref_names::kNativeMessagingBlocklist);
+ registry->RegisterListPref(extensions::pref_names::kNativeMessagingAllowlist);
registry->RegisterBooleanPref(extensions::pref_names::kNativeMessagingUserLevelHosts, true);
+ registry->RegisterListPref(extensions::pref_names::kExtendedBackgroundLifetimeForPortConnectionsToUrls);
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
// Media device salt id key
@@ -130,12 +119,28 @@ void PrefServiceAdapter::setup(const ProfileAdapter &profileAdapter)
// default value will be different. We'll need to initialize it later.
registry->RegisterStringPref(kPrefMediaDeviceIDSalt, std::string());
- m_prefService = factory.Create(registry);
-
- // Initialize salt value if none was stored before
- if (m_prefService->GetString(kPrefMediaDeviceIDSalt).empty()) {
- m_prefService->SetString(kPrefMediaDeviceIDSalt,
- content::BrowserContext::CreateRandomMediaDeviceIDSalt());
+ registry->RegisterBooleanPref(autofill::prefs::kAutofillEnabledDeprecated, false);
+ registry->RegisterBooleanPref(autofill::prefs::kAutofillProfileEnabled, false);
+ registry->RegisterBooleanPref(autofill::prefs::kAutofillCreditCardEnabled, false);
+ registry->RegisterBooleanPref(autofill::prefs::kAutofillCreditCardFidoAuthEnabled, false);
+
+ // devtools
+ registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);
+ registry->RegisterDictionaryPref(prefs::kDevToolsEditedFiles);
+ registry->RegisterDictionaryPref(prefs::kDevToolsPreferences);
+ registry->RegisterBooleanPref(prefs::kDevToolsSyncPreferences, false);
+ // even if kDevToolsSyncPreferences is disabled, the js frontend tries to access
+ // these two. E.g.: 'clearPreferences', that is overridden by devtools_compatibility.js
+ registry->RegisterDictionaryPref(prefs::kDevToolsSyncedPreferencesSyncDisabled);
+ registry->RegisterDictionaryPref(prefs::kDevToolsSyncedPreferencesSyncEnabled);
+
+ registry->RegisterStringPref(prefs::kGoogleServicesSigninScopedDeviceId, std::string());
+ registry->RegisterStringPref(prefs::kGaiaCookieLastListAccountsData, std::string());
+ registry->RegisterStringPref(prefs::kGCMProductCategoryForSubtypes, std::string());
+
+ {
+ base::ScopedAllowBlocking allowBlock;
+ m_prefService = factory.Create(registry);
}
#if QT_CONFIG(webengine_spellchecker)
@@ -183,10 +188,9 @@ void PrefServiceAdapter::setSpellCheckLanguages(const QStringList &languages)
QStringList PrefServiceAdapter::spellCheckLanguages() const
{
QStringList spellcheck_dictionaries;
- for (const auto &value : *m_prefService->GetList(spellcheck::prefs::kSpellCheckDictionaries)) {
- std::string dictionary;
- if (value.GetAsString(&dictionary))
- spellcheck_dictionaries.append(QString::fromStdString(dictionary));
+ const auto &list = m_prefService->GetList(spellcheck::prefs::kSpellCheckDictionaries);
+ for (const auto &dictionary : list) {
+ spellcheck_dictionaries.append(QString::fromStdString(dictionary.GetString()));
}
return spellcheck_dictionaries;
diff --git a/src/core/pref_service_adapter.h b/src/core/pref_service_adapter.h
index 1c7c44a96..efa83a72c 100644
--- a/src/core/pref_service_adapter.h
+++ b/src/core/pref_service_adapter.h
@@ -1,42 +1,5 @@
-
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PREF_SERVICE_ADAPTER_H
#define PREF_SERVICE_ADAPTER_H
@@ -44,12 +7,6 @@
#include "components/prefs/pref_service.h"
#include "qtwebenginecoreglobal_p.h"
-QT_BEGIN_NAMESPACE
-class QStringList;
-QT_END_NAMESPACE
-
-class ProfileAdapter;
-
namespace QtWebEngineCore {
class ProfileAdapter;
diff --git a/src/core/printing/pdf_document_helper_client_qt.cpp b/src/core/printing/pdf_document_helper_client_qt.cpp
new file mode 100644
index 000000000..be1cc2e4c
--- /dev/null
+++ b/src/core/printing/pdf_document_helper_client_qt.cpp
@@ -0,0 +1,33 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/ui/pdf/chrome_pdf_document_helper_client.cc:
+
+#include "pdf_document_helper_client_qt.h"
+
+#include "content/public/browser/render_process_host.h"
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
+#include "extensions/common/constants.h"
+
+#include "pdf_util_qt.h"
+
+PDFDocumentHelperClientQt::PDFDocumentHelperClientQt() = default;
+PDFDocumentHelperClientQt::~PDFDocumentHelperClientQt() = default;
+
+content::RenderFrameHost *PDFDocumentHelperClientQt::FindPdfFrame(content::WebContents *contents)
+{
+ content::RenderFrameHost *main_frame = contents->GetPrimaryMainFrame();
+ content::RenderFrameHost *pdf_frame = QtWebEngineCore::FindPdfChildFrame(main_frame);
+ return pdf_frame ? pdf_frame : main_frame;
+}
+
+void PDFDocumentHelperClientQt::SetPluginCanSave(content::RenderFrameHost *render_frame_host, bool can_save)
+{
+ auto *guest_view = extensions::MimeHandlerViewGuest::FromRenderFrameHost(render_frame_host);
+ if (guest_view)
+ guest_view->SetPluginCanSave(can_save);
+}
+
+void PDFDocumentHelperClientQt::UpdateContentRestrictions(content::RenderFrameHost *, int)
+{
+}
diff --git a/src/core/printing/pdf_document_helper_client_qt.h b/src/core/printing/pdf_document_helper_client_qt.h
new file mode 100644
index 000000000..af58c7794
--- /dev/null
+++ b/src/core/printing/pdf_document_helper_client_qt.h
@@ -0,0 +1,27 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef PDF_DOCUMENT_HELPER_CLIENT_QT_H
+#define PDF_DOCUMENT_HELPER_CLIENT_QT_H
+
+#include "components/pdf/browser/pdf_document_helper_client.h"
+
+// based on chrome/browser/ui/pdf/chrome_pdf_document_helper_client.h:
+class PDFDocumentHelperClientQt : public pdf::PDFDocumentHelperClient // FIXME: rename
+{
+public:
+ PDFDocumentHelperClientQt();
+ PDFDocumentHelperClientQt(const PDFDocumentHelperClientQt&) = delete;
+ PDFDocumentHelperClientQt& operator=(const PDFDocumentHelperClientQt&) = delete;
+ ~PDFDocumentHelperClientQt() override;
+
+private:
+ // pdf::PDFDocumentHelperClient:
+ content::RenderFrameHost* FindPdfFrame(content::WebContents *contents) override;
+ void OnPDFHasUnsupportedFeature(content::WebContents *contents) override {}
+ void OnSaveURL(content::WebContents *contents) override {}
+ void SetPluginCanSave(content::RenderFrameHost *render_frame_host, bool can_save) override;
+ void UpdateContentRestrictions(content::RenderFrameHost *, int) override;
+};
+
+#endif // PDF_DOCUMENT_HELPER_CLIENT_QT_H
diff --git a/src/core/printing/pdf_stream_delegate_qt.cpp b/src/core/printing/pdf_stream_delegate_qt.cpp
new file mode 100644
index 000000000..8677c82bd
--- /dev/null
+++ b/src/core/printing/pdf_stream_delegate_qt.cpp
@@ -0,0 +1,99 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/pdf/chrome_pdf_stream_delegate.cc:
+
+#include "pdf_stream_delegate_qt.h"
+
+#include "base/no_destructor.h"
+#include "chrome/grit/pdf_resources.h"
+#include "content/public/browser/document_user_data.h"
+#include "content/public/browser/navigation_handle.h"
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
+#include "extensions/common/constants.h"
+#include "ui/base/resource/resource_bundle.h"
+
+// Associates a `pdf::PdfStreamDelegate::StreamInfo` with the PDF extension's
+// or Print Preview's `blink::Document`.
+// `ChromePdfStreamDelegate::MapToOriginalUrl()` initializes this in
+// `PdfNavigationThrottle`, and then `ChromePdfStreamDelegate::GetStreamInfo()`
+// returns the stashed result to `PdfURLLoaderRequestInterceptor`.
+class StreamInfoHelper : public content::DocumentUserData<StreamInfoHelper>
+{
+public:
+ absl::optional<pdf::PdfStreamDelegate::StreamInfo> TakeStreamInfo()
+ { return std::move(stream_info_); }
+
+private:
+ friend class content::DocumentUserData<StreamInfoHelper>;
+ DOCUMENT_USER_DATA_KEY_DECL();
+
+ StreamInfoHelper(content::RenderFrameHost* embedder_frame,
+ pdf::PdfStreamDelegate::StreamInfo stream_info)
+ : content::DocumentUserData<StreamInfoHelper>(embedder_frame),
+ stream_info_(std::move(stream_info)) {}
+
+ absl::optional<pdf::PdfStreamDelegate::StreamInfo> stream_info_;
+};
+
+DOCUMENT_USER_DATA_KEY_IMPL(StreamInfoHelper);
+
+PdfStreamDelegateQt::PdfStreamDelegateQt() = default;
+PdfStreamDelegateQt::~PdfStreamDelegateQt() = default;
+
+absl::optional<GURL> PdfStreamDelegateQt::MapToOriginalUrl(content::NavigationHandle &navigation_handle)
+{
+ content::RenderFrameHost *embedder_frame = navigation_handle.GetParentFrame();
+ StreamInfoHelper *helper = StreamInfoHelper::GetForCurrentDocument(embedder_frame);
+ if (helper) {
+ // PDF viewer and Print Preview only do this once per WebContents.
+ return absl::nullopt;
+ }
+
+ GURL original_url;
+ StreamInfo info;
+
+ content::WebContents* contents = navigation_handle.GetWebContents();
+ extensions::MimeHandlerViewGuest *guest =
+ extensions::MimeHandlerViewGuest::FromWebContents(contents);
+ if (guest) {
+ base::WeakPtr<extensions::StreamContainer> stream = guest->GetStreamWeakPtr();
+ if (!stream || stream->extension_id() != extension_misc::kPdfExtensionId ||
+ stream->stream_url() != navigation_handle.GetURL() ||
+ !stream->pdf_plugin_attributes()) {
+ return absl::nullopt;
+ }
+
+ original_url = stream->original_url();
+ info.background_color = base::checked_cast<SkColor>(stream->pdf_plugin_attributes()->background_color);
+ info.full_frame = !stream->embedded();
+ info.allow_javascript = stream->pdf_plugin_attributes()->allow_javascript;
+ } else {
+ return absl::nullopt;
+ }
+
+ static const base::NoDestructor<std::string> injected_script(
+ ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
+ IDR_PDF_PDF_INTERNAL_PLUGIN_WRAPPER_ROLLUP_JS));
+
+ info.stream_url = navigation_handle.GetURL();
+ info.original_url = original_url;
+ info.injected_script = injected_script.get();
+ StreamInfoHelper::CreateForCurrentDocument(embedder_frame, std::move(info));
+ return original_url;
+}
+
+absl::optional<pdf::PdfStreamDelegate::StreamInfo>
+PdfStreamDelegateQt::GetStreamInfo(content::RenderFrameHost* embedder_frame)
+{
+ if (!embedder_frame)
+ return absl::nullopt;
+
+ StreamInfoHelper *helper = StreamInfoHelper::GetForCurrentDocument(embedder_frame);
+ if (!helper)
+ return absl::nullopt;
+
+ // Only the call immediately following `MapToOriginalUrl()` requires a valid
+ // `StreamInfo`; subsequent calls should just get nothing.
+ return helper->TakeStreamInfo();
+}
diff --git a/src/core/printing/pdf_stream_delegate_qt.h b/src/core/printing/pdf_stream_delegate_qt.h
new file mode 100644
index 000000000..fd279af72
--- /dev/null
+++ b/src/core/printing/pdf_stream_delegate_qt.h
@@ -0,0 +1,23 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef PDF_STREAM_DELEGATE_QT_H
+#define PDF_STREAM_DELEGATE_QT_H
+
+#include "components/pdf/browser/pdf_stream_delegate.h"
+
+// based on chrome/browser/pdf/chrome_pdf_stream_delegate.h:
+class PdfStreamDelegateQt : public pdf::PdfStreamDelegate
+{
+public:
+ PdfStreamDelegateQt();
+ PdfStreamDelegateQt(const PdfStreamDelegateQt &) = delete;
+ PdfStreamDelegateQt operator=(const PdfStreamDelegateQt &) = delete;
+ ~PdfStreamDelegateQt() override;
+
+ // pdf::PdfStreamDelegate:
+ absl::optional<GURL> MapToOriginalUrl(content::NavigationHandle &navigation_handle) override;
+ absl::optional<StreamInfo> GetStreamInfo(content::RenderFrameHost *embedder_frame) override;
+};
+
+#endif // PDF_STREAM_DELEGATE_QT_H
diff --git a/src/core/printing/pdfium_document_wrapper_qt.cpp b/src/core/printing/pdfium_document_wrapper_qt.cpp
index dae6ec44b..56588620d 100644
--- a/src/core/printing/pdfium_document_wrapper_qt.cpp
+++ b/src/core/printing/pdfium_document_wrapper_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "pdfium_document_wrapper_qt.h"
#include <QtCore/qhash.h>
diff --git a/src/core/printing/pdfium_document_wrapper_qt.h b/src/core/printing/pdfium_document_wrapper_qt.h
index e0778c32b..feb34e36a 100644
--- a/src/core/printing/pdfium_document_wrapper_qt.h
+++ b/src/core/printing/pdfium_document_wrapper_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -57,7 +21,7 @@
namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT PdfiumDocumentWrapperQt
+class Q_WEBENGINECORE_EXPORT PdfiumDocumentWrapperQt
{
public:
PdfiumDocumentWrapperQt(const void *pdfData, size_t size, const char *password = nullptr);
diff --git a/src/core/printing/print_view_manager_base_qt.cpp b/src/core/printing/print_view_manager_base_qt.cpp
index 34c86e506..b2b8e34fc 100644
--- a/src/core/printing/print_view_manager_base_qt.cpp
+++ b/src/core/printing/print_view_manager_base_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// This is based on chrome/browser/printing/print_view_manager_base.cc:
// Copyright 2013 The Chromium Authors. All rights reserved.
@@ -48,21 +12,21 @@
#include "web_engine_context.h"
#include "base/memory/ref_counted_memory.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_loop_current.h"
#include "base/run_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task/post_task.h"
+#include "base/task/current_thread.h"
+#include "base/task/thread_pool.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/printer_query.h"
-#include "components/printing/common/print_messages.h"
+#include "components/printing/browser/print_manager_utils.h"
+#include "components/printing/common/print.mojom.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
@@ -72,16 +36,90 @@
namespace QtWebEngineCore {
+namespace {
+
+// Runs |callback| with |params| to reply to
+// mojom::PrintManagerHost::GetDefaultPrintSettings.
+void GetDefaultPrintSettingsReply(printing::mojom::PrintManagerHost::GetDefaultPrintSettingsCallback callback,
+ printing::mojom::PrintParamsPtr params)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ std::move(callback).Run(std::move(params));
+}
+
+void OnDidGetDefaultPrintSettings(scoped_refptr<printing::PrintQueriesQueue> queue,
+ std::unique_ptr<printing::PrinterQuery> printer_query,
+ printing::mojom::PrintManagerHost::GetDefaultPrintSettingsCallback callback)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ printing::mojom::PrintParamsPtr params = printing::mojom::PrintParams::New();
+ if (printer_query && printer_query->last_status() == printing::mojom::ResultCode::kSuccess) {
+ RenderParamsFromPrintSettings(printer_query->settings(), params.get());
+ params->document_cookie = printer_query->cookie();
+ }
+
+ GetDefaultPrintSettingsReply(std::move(callback), std::move(params));
+
+ // If printing was enabled.
+ if (printer_query) {
+ // If user hasn't cancelled.
+ if (printer_query->cookie() && printer_query->settings().dpi()) {
+ queue->QueuePrinterQuery(std::move(printer_query));
+ }
+ }
+}
+
+void OnDidUpdatePrintSettings(scoped_refptr<printing::PrintQueriesQueue> queue,
+ std::unique_ptr<printing::PrinterQuery> printer_query,
+ printing::mojom::PrintManagerHost::UpdatePrintSettingsCallback callback,
+ int process_id, int routing_id)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK(printer_query);
+ auto params = printing::mojom::PrintPagesParams::New();
+ params->params = printing::mojom::PrintParams::New();
+ if (printer_query->last_status() == printing::mojom::ResultCode::kSuccess) {
+ RenderParamsFromPrintSettings(printer_query->settings(), params->params.get());
+ params->params->document_cookie = printer_query->cookie();
+ params->pages = printer_query->settings().ranges();
+ }
+
+ std::move(callback).Run(std::move(params));
+
+ if (printer_query->cookie() && printer_query->settings().dpi()) {
+ queue->QueuePrinterQuery(std::move(printer_query));
+ }
+}
+
+void OnDidScriptedPrint(scoped_refptr<printing::PrintQueriesQueue> queue,
+ std::unique_ptr<printing::PrinterQuery> printer_query,
+ printing::mojom::PrintManagerHost::ScriptedPrintCallback callback)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ auto params = printing::mojom::PrintPagesParams::New();
+ params->params = printing::mojom::PrintParams::New();
+ if (printer_query->last_status() == printing::mojom::ResultCode::kSuccess && printer_query->settings().dpi()) {
+ RenderParamsFromPrintSettings(printer_query->settings(), params->params.get());
+ params->params->document_cookie = printer_query->cookie();
+ params->pages = printer_query->settings().ranges();
+ }
+ bool has_valid_cookie = params->params->document_cookie;
+ bool has_dpi = !params->params->dpi.IsEmpty();
+ std::move(callback).Run(std::move(params));
+
+ if (has_dpi && has_valid_cookie) {
+ queue->QueuePrinterQuery(std::move(printer_query));
+ }
+}
+
+} // namespace
+
PrintViewManagerBaseQt::PrintViewManagerBaseQt(content::WebContents *contents)
: printing::PrintManager(contents)
- , m_isInsideInnerMessageLoop(false)
+ , m_printingRFH(nullptr)
, m_didPrintingSucceed(false)
, m_printerQueriesQueue(WebEngineContext::current()->getPrintJobManager()->queue())
- , m_printingRFH(nullptr)
{
- // FIXME: Check if this needs to be executed async:
- // TODO: Add isEnabled to profile
- PrintViewManagerBaseQt::UpdatePrintingEnabled();
}
PrintViewManagerBaseQt::~PrintViewManagerBaseQt()
@@ -96,16 +134,23 @@ void PrintViewManagerBaseQt::SetPrintingRFH(content::RenderFrameHost *rfh)
m_printingRFH = rfh;
}
-void PrintViewManagerBaseQt::UpdatePrintingEnabled()
-{
+void PrintViewManagerBaseQt::ScriptedPrintReply(ScriptedPrintCallback callback,
+ int process_id,
+ printing::mojom::PrintPagesParamsPtr params) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- bool enabled = false;
-#if QT_CONFIG(webengine_printing_and_pdf)
- enabled = true;
+
+#if BUILDFLAG(ENABLE_OOP_PRINTING)
+ // Finished getting all settings (defaults and from user), no further need
+ // to be registered as a system print client.
+ UnregisterSystemPrintClient();
#endif
- web_contents()->ForEachFrame(
- base::Bind(&PrintViewManagerBaseQt::SendPrintingEnabled,
- base::Unretained(this), enabled));
+ if (!content::RenderProcessHost::FromID(process_id)) {
+ // Early return if the renderer is not alive.
+ return;
+ }
+
+// set_cookie(params->params->document_cookie);
+ std::move(callback).Run(std::move(params));
}
void PrintViewManagerBaseQt::NavigationStopped()
@@ -114,53 +159,56 @@ void PrintViewManagerBaseQt::NavigationStopped()
TerminatePrintJob(true);
}
-base::string16 PrintViewManagerBaseQt::RenderSourceName()
+std::u16string PrintViewManagerBaseQt::RenderSourceName()
{
return toString16(QLatin1String(""));
}
-void PrintViewManagerBaseQt::PrintDocument(printing::PrintedDocument *document,
- const scoped_refptr<base::RefCountedMemory> &print_data,
+void PrintViewManagerBaseQt::PrintDocument(scoped_refptr<base::RefCountedMemory> print_data,
const gfx::Size &page_size,
const gfx::Rect &content_area,
const gfx::Point &offsets)
{
std::unique_ptr<printing::MetafileSkia> metafile =
std::make_unique<printing::MetafileSkia>();
- CHECK(metafile->InitFromData(print_data->front(), print_data->size()));
+ CHECK(metafile->InitFromData(*print_data));
// Update the rendered document. It will send notifications to the listener.
- document->SetDocument(std::move(metafile), page_size, content_area);
+ printing::PrintedDocument* document = m_printJob->document();
+ document->SetDocument(std::move(metafile));
ShouldQuitFromInnerMessageLoop();
}
-printing::PrintedDocument *PrintViewManagerBaseQt::GetDocument(int cookie)
+void PrintViewManagerBaseQt::DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages)
+{
+ PrintManager::DidGetPrintedPagesCount(cookie, number_pages);
+ OpportunisticallyCreatePrintJob(cookie);
+}
+
+bool PrintViewManagerBaseQt::PrintJobHasDocument(int cookie)
{
if (!OpportunisticallyCreatePrintJob(cookie))
- return nullptr;
+ return false;
+ // These checks may fail since we are completely asynchronous. Old spurious
+ // messages can be received if one of the processes is overloaded.
printing::PrintedDocument* document = m_printJob->document();
- if (!document || cookie != document->cookie()) {
- // Out of sync. It may happen since we are completely asynchronous. Old
- // spurious messages can be received if one of the processes is overloaded.
- return nullptr;
- }
- return document;
+ return document && document->cookie() == cookie;
}
-// IPC handlers
-void PrintViewManagerBaseQt::OnDidPrintDocument(content::RenderFrameHost* /*render_frame_host*/,
- const PrintHostMsg_DidPrintDocument_Params &params,
- std::unique_ptr<DelayedFrameDispatchHelper> helper)
+void PrintViewManagerBaseQt::DidPrintDocument(printing::mojom::DidPrintDocumentParamsPtr params,
+ DidPrintDocumentCallback callback)
{
- printing::PrintedDocument *document = GetDocument(params.document_cookie);
- if (!document)
+ if (!PrintJobHasDocument(params->document_cookie)) {
+ std::move(callback).Run(false);
return;
+ }
- const PrintHostMsg_DidPrintContent_Params &content = params.content;
+ const printing::mojom::DidPrintContentParams &content = *params->content;
if (!content.metafile_data_region.IsValid()) {
NOTREACHED() << "invalid memory handle";
web_contents()->Stop();
+ std::move(callback).Run(false);
return;
}
@@ -168,41 +216,91 @@ void PrintViewManagerBaseQt::OnDidPrintDocument(content::RenderFrameHost* /*rend
if (!data) {
NOTREACHED() << "couldn't map";
web_contents()->Stop();
+ std::move(callback).Run(false);
return;
}
- PrintDocument(document, data, params.page_size, params.content_area,
- params.physical_offsets);
- if (helper)
- helper->SendCompleted();
+ PrintDocument(data, params->page_size, params->content_area,
+ params->physical_offsets);
+ std::move(callback).Run(true);
}
-void PrintViewManagerBaseQt::OnGetDefaultPrintSettings(content::RenderFrameHost *render_frame_host,
- IPC::Message *reply_msg)
+void PrintViewManagerBaseQt::GetDefaultPrintSettings(GetDefaultPrintSettingsCallback callback)
{
- NOTREACHED() << "should be handled by printing::PrintingMessageFilter";
+ content::RenderFrameHost *render_frame_host =
+ print_manager_host_receivers_.GetCurrentTargetFrame();
+ content::RenderProcessHost *render_process_host =
+ render_frame_host->GetProcess();
+
+ auto callback_wrapper =
+ base::BindOnce(&GetDefaultPrintSettingsReply, std::move(callback));
+ std::unique_ptr<printing::PrinterQuery> printer_query = m_printerQueriesQueue->PopPrinterQuery(0);
+ if (!printer_query)
+ printer_query = m_printerQueriesQueue->CreatePrinterQuery(render_frame_host->GetGlobalId());
+
+ // Loads default settings. This is asynchronous, only the mojo message sender
+ // will hang until the settings are retrieved.
+ auto *printer_query_ptr = printer_query.get();
+ printer_query_ptr->GetDefaultSettings(
+ base::BindOnce(&OnDidGetDefaultPrintSettings, m_printerQueriesQueue,
+ std::move(printer_query), std::move(callback_wrapper)),
+ false,
+ !render_process_host->IsPdf());
}
-void PrintViewManagerBaseQt::OnScriptedPrint(content::RenderFrameHost *render_frame_host,
- const PrintHostMsg_ScriptedPrint_Params &params,
- IPC::Message *reply_msg)
+void PrintViewManagerBaseQt::PrintingFailed(int32_t cookie, printing::mojom::PrintFailureReason reason)
{
- NOTREACHED() << "should be handled by printing::PrintingMessageFilter";
-}
+ // Note: Not redundant with cookie checks in the same method in other parts of
+ // the class hierarchy.
+ if (!IsValidCookie(cookie))
+ return;
-void PrintViewManagerBaseQt::OnShowInvalidPrinterSettingsError()
+ PrintManager::PrintingFailed(cookie, reason);
+
+ ReleasePrinterQuery();
+}
+void PrintViewManagerBaseQt::IsPrintingEnabled(IsPrintingEnabledCallback callback)
{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ bool enabled = false;
+#if QT_CONFIG(webengine_printing_and_pdf)
+ enabled = true;
+#endif
+ std::move(callback).Run(enabled);
}
-void PrintViewManagerBaseQt::DidStartLoading()
+void PrintViewManagerBaseQt::ScriptedPrint(printing::mojom::ScriptedPrintParamsPtr params,
+ printing::mojom::PrintManagerHost::ScriptedPrintCallback callback)
{
- UpdatePrintingEnabled();
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ content::RenderFrameHost *render_frame_host =
+ print_manager_host_receivers_.GetCurrentTargetFrame();
+ content::RenderProcessHost *render_process_host =
+ render_frame_host->GetProcess();
+
+ auto callback_wrapper = base::BindOnce(
+ &PrintViewManagerBaseQt::ScriptedPrintReply, weak_ptr_factory_.GetWeakPtr(),
+ std::move(callback), render_process_host->GetID());
+
+ std::unique_ptr<printing::PrinterQuery> printer_query =
+ m_printerQueriesQueue->PopPrinterQuery(params->cookie);
+ if (!printer_query)
+ printer_query = m_printerQueriesQueue->CreatePrinterQuery(render_frame_host->GetGlobalId());
+
+ auto *printer_query_ptr = printer_query.get();
+ printer_query_ptr->GetSettingsFromUser(
+ params->expected_pages_count, params->has_selection, params->margin_type,
+ params->is_scripted, !render_process_host->IsPdf(),
+ base::BindOnce(&OnDidScriptedPrint, m_printerQueriesQueue, std::move(printer_query), std::move(callback_wrapper)));
}
-// Note: In PrintViewManagerQt we always initiate printing with PrintMsg_InitiatePrintPreview
+// Note: In PrintViewManagerQt we always initiate printing with
+// printing::mojom::PrintRenderFrame::InitiatePrintPreview()
// so m_printingRFH is never set and used at the moment.
void PrintViewManagerBaseQt::RenderFrameDeleted(content::RenderFrameHost *render_frame_host)
{
+ PrintManager::RenderFrameDeleted(render_frame_host);
+
// Terminates or cancels the print job if one was pending.
if (render_frame_host != m_printingRFH)
return;
@@ -216,7 +314,7 @@ void PrintViewManagerBaseQt::RenderFrameDeleted(content::RenderFrameHost *render
return;
scoped_refptr<printing::PrintedDocument> document(m_printJob->document());
- if (document.get()) {
+ if (document) {
// If IsComplete() returns false, the document isn't completely rendered.
// Since our renderer is gone, there's nothing to do, cancel it. Otherwise,
// the print job may finish without problem.
@@ -224,73 +322,22 @@ void PrintViewManagerBaseQt::RenderFrameDeleted(content::RenderFrameHost *render
}
}
-bool PrintViewManagerBaseQt::OnMessageReceived(const IPC::Message& message,
- content::RenderFrameHost* render_frame_host)
+void PrintViewManagerBaseQt::OnDocDone(int /*job_id*/, printing::PrintedDocument * /*document*/)
{
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(PrintViewManagerBaseQt, message)
- IPC_MESSAGE_HANDLER(PrintHostMsg_ShowInvalidPrinterSettingsError,
- OnShowInvalidPrinterSettingsError);
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled || PrintManager::OnMessageReceived(message, render_frame_host);
}
-void PrintViewManagerBaseQt::Observe(int type,
- const content::NotificationSource& /*source*/,
- const content::NotificationDetails& details)
+void PrintViewManagerBaseQt::OnJobDone()
{
- DCHECK_EQ(chrome::NOTIFICATION_PRINT_JOB_EVENT, type);
- OnNotifyPrintJobEvent(*content::Details<printing::JobEventDetails>(details).ptr());
+ // Printing is done, we don't need it anymore.
+ // print_job_->is_job_pending() may still be true, depending on the order
+ // of object registration.
+ m_didPrintingSucceed = true;
+ ReleasePrintJob();
}
-void PrintViewManagerBaseQt::OnNotifyPrintJobEvent(const printing::JobEventDetails& event_details)
+void PrintViewManagerBaseQt::OnFailed()
{
- switch (event_details.type()) {
- case printing::JobEventDetails::FAILED: {
- TerminatePrintJob(true);
-
- content::NotificationService::current()->Notify(
- chrome::NOTIFICATION_PRINT_JOB_RELEASED,
- content::Source<content::WebContents>(web_contents()),
- content::NotificationService::NoDetails());
- break;
- }
- case printing::JobEventDetails::USER_INIT_DONE:
- case printing::JobEventDetails::DEFAULT_INIT_DONE:
- case printing::JobEventDetails::USER_INIT_CANCELED: {
- NOTREACHED();
- break;
- }
- case printing::JobEventDetails::ALL_PAGES_REQUESTED: {
- ShouldQuitFromInnerMessageLoop();
- break;
- }
- case printing::JobEventDetails::NEW_DOC:
-#if defined(OS_WIN)
- case printing::JobEventDetails::PAGE_DONE:
-#endif
- case printing::JobEventDetails::DOC_DONE: {
- // Don't care about the actual printing process.
- break;
- }
- case printing::JobEventDetails::JOB_DONE: {
- // Printing is done, we don't need it anymore.
- // print_job_->is_job_pending() may still be true, depending on the order
- // of object registration.
- m_didPrintingSucceed = true;
- ReleasePrintJob();
-
- content::NotificationService::current()->Notify(
- chrome::NOTIFICATION_PRINT_JOB_RELEASED,
- content::Source<content::WebContents>(web_contents()),
- content::NotificationService::NoDetails());
- break;
- }
- default:
- NOTREACHED();
- break;
- }
+ TerminatePrintJob(true);
}
// Requests the RenderView to render all the missing pages for the print job.
@@ -309,8 +356,8 @@ bool PrintViewManagerBaseQt::RenderAllMissingPagesNow()
// We can't print if there is no renderer.
if (!web_contents() ||
- !web_contents()->GetRenderViewHost() ||
- !web_contents()->GetRenderViewHost()->IsRenderViewLive()) {
+ !web_contents()->GetPrimaryMainFrame() ||
+ !web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) {
return false;
}
@@ -319,11 +366,9 @@ bool PrintViewManagerBaseQt::RenderAllMissingPagesNow()
// pages in an hurry if a print_job_ is still pending. No need to wait for it
// to actually spool the pages, only to have the renderer generate them. Run
// a message loop until we get our signal that the print job is satisfied.
- // PrintJob will send a ALL_PAGES_REQUESTED after having received all the
- // pages it needs. MessageLoop::current()->Quit() will be called as soon as
- // print_job_->document()->IsComplete() is true on either ALL_PAGES_REQUESTED
- // or in DidPrintPage(). The check is done in
- // ShouldQuitFromInnerMessageLoop().
+ // |quit_inner_loop_| will be called as soon as
+ // print_job_->document()->IsComplete() is true in DidPrintDocument(). The
+ // check is done in ShouldQuitFromInnerMessageLoop().
// BLOCKS until all the pages are received. (Need to enable recursive task)
if (!RunInnerMessageLoop()) {
// This function is always called from DisconnectFromCurrentPrintJob() so we
@@ -333,36 +378,32 @@ bool PrintViewManagerBaseQt::RenderAllMissingPagesNow()
return true;
}
-// Quits the current message loop if these conditions hold true: a document is
-// loaded and is complete and waiting_for_pages_to_be_rendered_ is true. This
-// function is called in DidPrintPage() or on ALL_PAGES_REQUESTED
-// notification. The inner message loop is created was created by
-// RenderAllMissingPagesNow().
void PrintViewManagerBaseQt::ShouldQuitFromInnerMessageLoop()
{
// Look at the reason.
DCHECK(m_printJob->document());
- if (m_printJob->document() &&
- m_printJob->document()->IsComplete() &&
- m_isInsideInnerMessageLoop) {
- // We are in a message loop created by RenderAllMissingPagesNow. Quit from
- // it.
- base::RunLoop::QuitCurrentWhenIdleDeprecated();
- m_isInsideInnerMessageLoop = false;
+ if (m_printJob->document() && m_printJob->document()->IsComplete() && m_quitInnerLoop) {
+ // We are in a message loop created by RenderAllMissingPagesNow. Quit from
+ // it.
+ std::move(m_quitInnerLoop).Run();
}
}
bool PrintViewManagerBaseQt::CreateNewPrintJob(std::unique_ptr<printing::PrinterQuery> query)
{
- DCHECK(!m_isInsideInnerMessageLoop);
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK(!m_quitInnerLoop);
DCHECK(query);
// Disconnect the current |m_printJob|.
+ auto weak_this = weak_ptr_factory_.GetWeakPtr();
DisconnectFromCurrentPrintJob();
+ if (!weak_this)
+ return false;
// We can't print if there is no renderer.
- if (!web_contents()->GetRenderViewHost() ||
- !web_contents()->GetRenderViewHost()->IsRenderViewLive()) {
+ if (!web_contents()->GetPrimaryMainFrame() ||
+ !web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) {
return false;
}
@@ -370,10 +411,9 @@ bool PrintViewManagerBaseQt::CreateNewPrintJob(std::unique_ptr<printing::Printer
// view and switch to it, initialize the printer and show the print dialog.
DCHECK(!m_printJob.get());
- m_printJob = base::MakeRefCounted<printing::PrintJob>();
+ m_printJob = base::MakeRefCounted<printing::PrintJob>(nullptr /*g_browser_process->print_job_manager()*/);
m_printJob->Initialize(std::move(query), RenderSourceName(), number_pages_);
- m_registrar.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
- content::Source<printing::PrintJob>(m_printJob.get()));
+ m_printJob->AddObserver(*this);
m_didPrintingSucceed = false;
return true;
}
@@ -405,9 +445,9 @@ void PrintViewManagerBaseQt::TerminatePrintJob(bool cancel)
if (cancel) {
// We don't need the metafile data anymore because the printing is canceled.
m_printJob->Cancel();
- m_isInsideInnerMessageLoop = false;
+ m_quitInnerLoop.Reset();
} else {
- DCHECK(!m_isInsideInnerMessageLoop);
+ DCHECK(!m_quitInnerLoop);
DCHECK(!m_printJob->document() || m_printJob->document()->IsComplete());
// WebContents is either dying or navigating elsewhere. We need to render
@@ -429,13 +469,14 @@ void PrintViewManagerBaseQt::ReleasePrintJob()
if (rfh)
GetPrintRenderFrame(rfh)->PrintingDone(m_didPrintingSucceed);
- m_registrar.Remove(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
- content::Source<printing::PrintJob>(m_printJob.get()));
+ m_printJob->RemoveObserver(*this);
+
// Don't close the worker thread.
m_printJob = nullptr;
}
-bool PrintViewManagerBaseQt::RunInnerMessageLoop() {
+bool PrintViewManagerBaseQt::RunInnerMessageLoop()
+{
// This value may actually be too low:
//
// - If we're looping because of printer settings initialization, the premise
@@ -451,23 +492,18 @@ bool PrintViewManagerBaseQt::RunInnerMessageLoop() {
base::OneShotTimer quit_timer;
base::RunLoop run_loop;
quit_timer.Start(FROM_HERE,
- base::TimeDelta::FromMilliseconds(kPrinterSettingsTimeout),
+ base::Milliseconds(kPrinterSettingsTimeout),
run_loop.QuitWhenIdleClosure());
- m_isInsideInnerMessageLoop = true;
+ m_quitInnerLoop = run_loop.QuitClosure();
- // Need to enable recursive task.
- {
- base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
- run_loop.Run();
- }
+ auto weak_this = weak_ptr_factory_.GetWeakPtr();
+ run_loop.Run();
+ if (!weak_this)
+ return false;
- bool success = true;
- if (m_isInsideInnerMessageLoop) {
- // Ok we timed out. That's sad.
- m_isInsideInnerMessageLoop = false;
- success = false;
- }
+ bool success = !m_quitInnerLoop;
+ m_quitInnerLoop.Reset();
return success;
}
@@ -515,12 +551,8 @@ void PrintViewManagerBaseQt::ReleasePrinterQuery()
if (!printJobManager)
return;
- std::unique_ptr<printing::PrinterQuery> printerQuery;
- printerQuery = m_printerQueriesQueue->PopPrinterQuery(cookie);
- if (!printerQuery)
- return;
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&printing::PrinterQuery::StopWorker, std::move(printerQuery)));
+ std::unique_ptr<printing::PrinterQuery> printerQuery =
+ m_printerQueriesQueue->PopPrinterQuery(cookie);
}
// Originally from print_preview_message_handler.cc:
@@ -528,17 +560,31 @@ void PrintViewManagerBaseQt::StopWorker(int documentCookie)
{
if (documentCookie <= 0)
return;
- std::unique_ptr<printing::PrinterQuery> printer_query =
+ std::unique_ptr<printing::PrinterQuery> printerQuery =
m_printerQueriesQueue->PopPrinterQuery(documentCookie);
- if (printer_query.get()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&printing::PrinterQuery::StopWorker, std::move(printer_query)));
- }
}
-void PrintViewManagerBaseQt::SendPrintingEnabled(bool enabled, content::RenderFrameHost* rfh)
+void PrintViewManagerBaseQt::UpdatePrintSettings(base::Value::Dict job_settings,
+ UpdatePrintSettingsCallback callback)
{
- GetPrintRenderFrame(rfh)->SetPrintingEnabled(enabled);
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ if (!job_settings.FindInt(printing::kSettingPrinterType)) {
+ std::move(callback).Run(nullptr);
+ return;
+ }
+
+ content::RenderFrameHost *render_frame_host =
+ print_manager_host_receivers_.GetCurrentTargetFrame();
+ std::unique_ptr<printing::PrinterQuery> printer_query =
+ m_printerQueriesQueue->CreatePrinterQuery(content::GlobalRenderFrameHostId());
+
+ auto *printer_query_ptr = printer_query.get();
+ printer_query_ptr->SetSettings(
+ std::move(job_settings),
+ base::BindOnce(&OnDidUpdatePrintSettings,
+ m_printerQueriesQueue, std::move(printer_query), std::move(callback),
+ render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()));
}
} // namespace QtWebEngineCore
diff --git a/src/core/printing/print_view_manager_base_qt.h b/src/core/printing/print_view_manager_base_qt.h
index 1217e8c11..d4b5bfe82 100644
--- a/src/core/printing/print_view_manager_base_qt.h
+++ b/src/core/printing/print_view_manager_base_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -45,134 +9,138 @@
#define PRINT_VIEW_MANAGER_BASE_QT_H
#include "base/memory/ref_counted_memory.h"
-#include "base/strings/string16.h"
+#include "chrome/browser/printing/print_job.h"
#include "components/prefs/pref_member.h"
#include "components/printing/browser/print_manager.h"
+#include "components/printing/common/print.mojom-forward.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
-struct PrintHostMsg_DidPrintDocument_Params;
-
namespace base {
class RefCountedBytes;
}
namespace content {
class RenderFrameHost;
-class RenderViewHost;
}
namespace printing {
-class JobEventDetails;
-class MetafilePlayer;
-class PrintJob;
-class PrintJobWorkerOwner;
class PrintQueriesQueue;
-class PrintedDocument;
class PrinterQuery;
}
namespace QtWebEngineCore {
-class PrintViewManagerBaseQt : public content::NotificationObserver
- , public printing::PrintManager
+class PrintViewManagerBaseQt : public printing::PrintManager
+ , public printing::PrintJob::Observer
{
public:
~PrintViewManagerBaseQt() override;
- // Whether printing is enabled or not.
- void UpdatePrintingEnabled();
+ std::u16string RenderSourceName();
- virtual base::string16 RenderSourceName();
+ // mojom::PrintManagerHost:
+ void DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages) override;
+ void DidPrintDocument(printing::mojom::DidPrintDocumentParamsPtr params,
+ DidPrintDocumentCallback callback) override;
+ void GetDefaultPrintSettings(GetDefaultPrintSettingsCallback callback) override;
+ void UpdatePrintSettings(base::Value::Dict, UpdatePrintSettingsCallback) override;
+ void IsPrintingEnabled(IsPrintingEnabledCallback callback) override;
+ void ScriptedPrint(printing::mojom::ScriptedPrintParamsPtr,
+ printing::mojom::PrintManagerHost::ScriptedPrintCallback) override;
+ void PrintingFailed(int32_t cookie,
+ printing::mojom::PrintFailureReason reason) override;
protected:
explicit PrintViewManagerBaseQt(content::WebContents*);
void SetPrintingRFH(content::RenderFrameHost* rfh);
- // content::WebContentsObserver implementation.
// Cancels the print job.
void NavigationStopped() override;
// content::WebContentsObserver implementation.
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
- bool OnMessageReceived(const IPC::Message& message,
- content::RenderFrameHost* render_frame_host) override;
-
- // printing::PrintManager implementation:
- void OnDidPrintDocument(content::RenderFrameHost *render_frame_host,
- const PrintHostMsg_DidPrintDocument_Params &params,
- std::unique_ptr<DelayedFrameDispatchHelper> helper) override;
- void OnGetDefaultPrintSettings(content::RenderFrameHost* render_frame_host,
- IPC::Message* reply_msg) override;
- void OnScriptedPrint(content::RenderFrameHost* render_frame_host,
- const PrintHostMsg_ScriptedPrint_Params& params,
- IPC::Message* reply_msg) override;
-
- void OnShowInvalidPrinterSettingsError();
-
- // Processes a NOTIFY_PRINT_JOB_EVENT notification.
- void OnNotifyPrintJobEvent(const printing::JobEventDetails& event_details);
-
- // content::NotificationObserver implementation.
- void Observe(int,
- const content::NotificationSource&,
- const content::NotificationDetails&) override;
- void StopWorker(int document_cookie);
- // In the case of Scripted Printing, where the renderer is controlling the
- // control flow, print_job_ is initialized whenever possible. No-op is
- // print_job_ is initialized.
- bool OpportunisticallyCreatePrintJob(int cookie);
+ // Creates a new empty print job. It has no settings loaded. If there is
+ // currently a print job, safely disconnect from it. Returns false if it is
+ // impossible to safely disconnect from the current print job or it is
+ // impossible to create a new print job.
+ virtual bool CreateNewPrintJob(std::unique_ptr<printing::PrinterQuery> query);
+
+ // Makes sure the current print_job_ has all its data before continuing, and
+ // disconnect from it.
+ void DisconnectFromCurrentPrintJob();
+ // PrintJob::Observer overrides:
+ void OnDocDone(int job_id, printing::PrintedDocument *document) override;
+ void OnJobDone() override;
+ void OnFailed() override;
+
+ void StopWorker(int documentCookie);
+
+private:
// Requests the RenderView to render all the missing pages for the print job.
// No-op if no print job is pending. Returns true if at least one page has
// been requested to the renderer.
bool RenderAllMissingPagesNow();
- // Checks that synchronization is correct and a print query exists for
- // |cookie|. If so, returns the document associated with the cookie.
- printing::PrintedDocument* GetDocument(int cookie);
+ // Runs `callback` with `params` to reply to ScriptedPrint().
+ void ScriptedPrintReply(ScriptedPrintCallback callback,
+ int process_id,
+ printing::mojom::PrintPagesParamsPtr params);
+
+ // Checks that synchronization is correct with |print_job_| based on |cookie|.
+ bool PrintJobHasDocument(int cookie);
- // Starts printing a document with data given in |print_data|. |print_data|
- // must successfully initialize a metafile. |document| is the printed
- // document associated with the print job. Returns true if successful.
- void PrintDocument(printing::PrintedDocument *document,
- const scoped_refptr<base::RefCountedMemory> &print_data,
+ // Starts printing the |document| in |print_job_| with the given |print_data|.
+ // This method assumes PrintJobHasDocument() has been called, and |print_data|
+ // contains valid data.
+ void PrintDocument(scoped_refptr<base::RefCountedMemory> print_data,
const gfx::Size &page_size,
const gfx::Rect &content_area,
const gfx::Point &offsets);
// Quits the current message loop if these conditions hold true: a document is
// loaded and is complete and waiting_for_pages_to_be_rendered_ is true. This
- // function is called in DidPrintDocument() or on ALL_PAGES_REQUESTED
- // notification. The inner message loop is created was created by
- // RenderAllMissingPagesNow().
+ // function is called in DidPrintDocument(). The inner message loop was
+ // created by RenderAllMissingPagesNow().
void ShouldQuitFromInnerMessageLoop();
- bool RunInnerMessageLoop();
-
+ // Terminates the print job. No-op if no print job has been created. If
+ // |cancel| is true, cancel it instead of waiting for the job to finish. Will
+ // call ReleasePrintJob().
void TerminatePrintJob(bool cancel);
- void DisconnectFromCurrentPrintJob();
- bool CreateNewPrintJob(std::unique_ptr<printing::PrinterQuery> query);
+ // Releases print_job_. Correctly deregisters from notifications. No-op if
+ // no print job has been created.
void ReleasePrintJob();
- void ReleasePrinterQuery();
-private:
- // Helper method for UpdatePrintingEnabled().
- void SendPrintingEnabled(bool enabled, content::RenderFrameHost* rfh);
- // content::WebContentsObserver implementation.
- void DidStartLoading() override;
+ // Runs an inner message loop. It will set inside_inner_message_loop_ to true
+ // while the blocking inner message loop is running. This is useful in cases
+ // where the RenderView is about to be destroyed while a printing job isn't
+ // finished.
+ bool RunInnerMessageLoop();
+
+ // In the case of Scripted Printing, where the renderer is controlling the
+ // control flow, print_job_ is initialized whenever possible. No-op is
+ // print_job_ is initialized.
+ bool OpportunisticallyCreatePrintJob(int cookie);
+
+ // Release the PrinterQuery associated with our |cookie_|.
+ void ReleasePrinterQuery();
private:
content::NotificationRegistrar m_registrar;
scoped_refptr<printing::PrintJob> m_printJob;
- bool m_isInsideInnerMessageLoop;
+ content::RenderFrameHost *m_printingRFH;
bool m_didPrintingSucceed;
+ // Set while running an inner message loop inside RenderAllMissingPagesNow().
+ // This means we are _blocking_ until all the necessary pages have been
+ // rendered or the print settings are being loaded.
+ base::OnceClosure m_quitInnerLoop;
scoped_refptr<printing::PrintQueriesQueue> m_printerQueriesQueue;
- // The current RFH that is printing with a system printing dialog.
- content::RenderFrameHost *m_printingRFH;
- DISALLOW_COPY_AND_ASSIGN(PrintViewManagerBaseQt);
+
+ base::WeakPtrFactory<PrintViewManagerBaseQt> weak_ptr_factory_{this};
};
} // namespace QtWebEngineCore
diff --git a/src/core/printing/print_view_manager_qt.cpp b/src/core/printing/print_view_manager_qt.cpp
index 79e92fd6a..1d21c2fb9 100644
--- a/src/core/printing/print_view_manager_qt.cpp
+++ b/src/core/printing/print_view_manager_qt.cpp
@@ -1,69 +1,36 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+// Loosely based on print_view_manager.cc and print_preview_message_handler.cc
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
#include "print_view_manager_qt.h"
+#include "pdf_util_qt.h"
#include "type_conversion.h"
#include "web_contents_adapter_client.h"
#include "web_contents_view_qt.h"
#include "web_engine_context.h"
#include <QtGui/qpagelayout.h>
+#include <QtGui/qpageranges.h>
#include <QtGui/qpagesize.h>
#include "base/values.h"
#include "base/memory/ref_counted_memory.h"
-#include "base/task/post_task.h"
+#include "base/task/thread_pool.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/printer_query.h"
-#include "components/printing/common/print_messages.h"
+#include "components/printing/common/print.mojom.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
-#include "content/public/common/web_preferences.h"
#include "printing/metafile_skia.h"
+#include "printing/mojom/print.mojom-shared.h"
#include "printing/print_job_constants.h"
#include "printing/units.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
@@ -97,57 +64,57 @@ GetBytesFromHandle(const base::ReadOnlySharedMemoryRegion &handle)
// Write the PDF file to disk.
static void SavePdfFile(scoped_refptr<base::RefCountedBytes> data,
const base::FilePath &path,
- const QtWebEngineCore::PrintViewManagerQt::PrintToPDFFileCallback &saveCallback)
+ QtWebEngineCore::PrintViewManagerQt::PrintToPDFFileCallback saveCallback)
{
DCHECK_GT(data->size(), 0U);
printing::MetafileSkia metafile;
- metafile.InitFromData(static_cast<const void*>(data->front()), data->size());
+ metafile.InitFromData(base::as_bytes(base::make_span(data->front(), data->size())));
base::File file(path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
bool success = file.IsValid() && metafile.SaveTo(&file);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(saveCallback, success));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(saveCallback), success));
}
-static base::DictionaryValue *createPrintSettings()
+static base::Value::Dict createPrintSettings()
{
- base::DictionaryValue *printSettings = new base::DictionaryValue();
+ base::Value::Dict printSettings;
// TO DO: Check if we can use the request ID from Qt here somehow.
static int internalRequestId = 0;
- printSettings->SetBoolean(printing::kIsFirstRequest, internalRequestId++ == 0);
- printSettings->SetInteger(printing::kPreviewRequestID, internalRequestId);
+ printSettings.Set(printing::kIsFirstRequest, internalRequestId++ == 0);
+ printSettings.Set(printing::kPreviewRequestID, internalRequestId);
// The following are standard settings that Chromium expects to be set.
- printSettings->SetInteger(printing::kSettingPrinterType, printing::kPdfPrinter);
+ printSettings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kPdf));
- printSettings->SetInteger(printing::kSettingDpiHorizontal, printing::kPointsPerInch);
- printSettings->SetInteger(printing::kSettingDpiVertical, printing::kPointsPerInch);
+ printSettings.Set(printing::kSettingDpiHorizontal, printing::kPointsPerInch);
+ printSettings.Set(printing::kSettingDpiVertical, printing::kPointsPerInch);
- printSettings->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
- printSettings->SetInteger(printing::kSettingCopies, 1);
- printSettings->SetInteger(printing::kSettingPagesPerSheet, 1);
- printSettings->SetBoolean(printing::kSettingCollate, false);
+ printSettings.Set(printing::kSettingDuplexMode, static_cast<int>(printing::mojom::DuplexMode::kSimplex));
+ printSettings.Set(printing::kSettingCopies, 1);
+ printSettings.Set(printing::kSettingPagesPerSheet, 1);
+ printSettings.Set(printing::kSettingCollate, false);
// printSettings->SetBoolean(printing::kSettingGenerateDraftData, false);
- printSettings->SetBoolean(printing::kSettingPreviewModifiable, false);
+ printSettings.Set(printing::kSettingPreviewModifiable, false);
- printSettings->SetKey(printing::kSettingShouldPrintSelectionOnly, base::Value(false));
- printSettings->SetKey(printing::kSettingShouldPrintBackgrounds, base::Value(true));
- printSettings->SetKey(printing::kSettingHeaderFooterEnabled, base::Value(false));
- printSettings->SetKey(printing::kSettingRasterizePdf, base::Value(false));
- printSettings->SetInteger(printing::kSettingScaleFactor, 100);
- printSettings->SetString(printing::kSettingDeviceName, "");
- printSettings->SetInteger(printing::kPreviewUIID, 12345678);
+ printSettings.Set(printing::kSettingShouldPrintSelectionOnly, base::Value(false));
+ printSettings.Set(printing::kSettingShouldPrintBackgrounds, base::Value(true));
+ printSettings.Set(printing::kSettingHeaderFooterEnabled, base::Value(false));
+ printSettings.Set(printing::kSettingRasterizePdf, base::Value(false));
+ printSettings.Set(printing::kSettingScaleFactor, 100);
+ printSettings.Set(printing::kSettingDeviceName, "");
+ printSettings.Set(printing::kPreviewUIID, 12345678);
return printSettings;
}
-static base::DictionaryValue *createPrintSettingsFromQPageLayout(const QPageLayout &pageLayout,
+static base::Value::Dict createPrintSettingsFromQPageLayout(const QPageLayout &pageLayout,
bool useCustomMargins)
{
- base::DictionaryValue *printSettings = createPrintSettings();
+ base::Value::Dict printSettings = createPrintSettings();
QRectF pageSizeInMillimeter;
if (useCustomMargins) {
@@ -155,185 +122,154 @@ static base::DictionaryValue *createPrintSettingsFromQPageLayout(const QPageLayo
pageSizeInMillimeter = pageLayout.pageSize().rect(QPageSize::Millimeter);
QMargins pageMarginsInPoints = pageLayout.marginsPoints();
- std::unique_ptr<base::DictionaryValue> marginsDict(new base::DictionaryValue);
- marginsDict->SetInteger(printing::kSettingMarginTop, pageMarginsInPoints.top());
- marginsDict->SetInteger(printing::kSettingMarginBottom, pageMarginsInPoints.bottom());
- marginsDict->SetInteger(printing::kSettingMarginLeft, pageMarginsInPoints.left());
- marginsDict->SetInteger(printing::kSettingMarginRight, pageMarginsInPoints.right());
+ base::Value::Dict marginsDict;
+ marginsDict.Set(printing::kSettingMarginTop, pageMarginsInPoints.top());
+ marginsDict.Set(printing::kSettingMarginBottom, pageMarginsInPoints.bottom());
+ marginsDict.Set(printing::kSettingMarginLeft, pageMarginsInPoints.left());
+ marginsDict.Set(printing::kSettingMarginRight, pageMarginsInPoints.right());
- printSettings->Set(printing::kSettingMarginsCustom, std::move(marginsDict));
- printSettings->SetInteger(printing::kSettingMarginsType, printing::CUSTOM_MARGINS);
+ printSettings.Set(printing::kSettingMarginsCustom, std::move(marginsDict));
+ printSettings.Set(printing::kSettingMarginsType, (int)printing::mojom::MarginType::kCustomMargins);
// pageSizeInMillimeter is in portrait orientation. Transpose it if necessary.
- printSettings->SetBoolean(printing::kSettingLandscape, pageLayout.orientation() == QPageLayout::Landscape);
+ printSettings.Set(printing::kSettingLandscape, pageLayout.orientation() == QPageLayout::Landscape);
} else {
// QPrinter will handle margins
pageSizeInMillimeter = pageLayout.paintRect(QPageLayout::Millimeter);
- printSettings->SetInteger(printing::kSettingMarginsType, printing::NO_MARGINS);
+ printSettings.Set(printing::kSettingMarginsType, (int)printing::mojom::MarginType::kNoMargins);
// pageSizeInMillimeter already contains the orientation.
- printSettings->SetBoolean(printing::kSettingLandscape, false);
+ printSettings.Set(printing::kSettingLandscape, false);
}
//Set page size attributes, chromium expects these in micrometers
- std::unique_ptr<base::DictionaryValue> sizeDict(new base::DictionaryValue);
- sizeDict->SetInteger(printing::kSettingMediaSizeWidthMicrons, pageSizeInMillimeter.width() * kMicronsToMillimeter);
- sizeDict->SetInteger(printing::kSettingMediaSizeHeightMicrons, pageSizeInMillimeter.height() * kMicronsToMillimeter);
- printSettings->Set(printing::kSettingMediaSize, std::move(sizeDict));
+ base::Value::Dict sizeDict;
+ sizeDict.Set(printing::kSettingMediaSizeWidthMicrons, int(pageSizeInMillimeter.width() * kMicronsToMillimeter));
+ sizeDict.Set(printing::kSettingMediaSizeHeightMicrons, int(pageSizeInMillimeter.height() * kMicronsToMillimeter));
+ printSettings.Set(printing::kSettingMediaSize, std::move(sizeDict));
return printSettings;
}
+static base::Value::List createPageRangeSettings(const QList<QPageRanges::Range> &ranges)
+{
+ base::Value::List pageRangeArray;
+ for (int i = 0; i < ranges.count(); i++) {
+ base::Value::Dict pageRange;
+ pageRange.Set(printing::kSettingPageRangeFrom, ranges.at(i).from);
+ pageRange.Set(printing::kSettingPageRangeTo, ranges.at(i).to);
+ pageRangeArray.Append(std::move(pageRange));
+ }
+ return pageRangeArray;
+}
+
} // namespace
namespace QtWebEngineCore {
-struct PrintViewManagerQt::FrameDispatchHelper {
- PrintViewManagerQt* m_manager;
- content::RenderFrameHost* m_renderFrameHost;
-
- bool Send(IPC::Message* msg) {
- return m_renderFrameHost->Send(msg);
- }
-
- void OnSetupScriptedPrintPreview(IPC::Message* reply_msg) {
- m_manager->OnSetupScriptedPrintPreview(m_renderFrameHost, reply_msg);
- }
-};
-
PrintViewManagerQt::~PrintViewManagerQt()
{
}
void PrintViewManagerQt::PrintToPDFFileWithCallback(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
bool printInColor,
const QString &filePath,
- const PrintToPDFFileCallback& callback)
+ PrintToPDFFileCallback callback)
{
if (callback.is_null())
return;
- if (m_printSettings || !filePath.length()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(callback, false));
+ if (!m_printSettings.empty() || !filePath.length()) {
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), false));
return;
}
m_pdfOutputPath = toFilePath(filePath);
- m_pdfSaveCallback = callback;
- if (!PrintToPDFInternal(pageLayout, printInColor)) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(callback, false));
+ m_pdfSaveCallback = std::move(callback);
+ if (!PrintToPDFInternal(pageLayout, pageRanges, printInColor)) {
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(m_pdfSaveCallback), false));
resetPdfState();
}
}
void PrintViewManagerQt::PrintToPDFWithCallback(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
bool printInColor,
bool useCustomMargins,
- const PrintToPDFCallback& callback)
+ PrintToPDFCallback callback)
{
if (callback.is_null())
return;
// If there already is a pending print in progress, don't try starting another one.
- if (m_printSettings) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(callback, QSharedPointer<QByteArray>()));
+ if (!m_printSettings.empty()) {
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), QSharedPointer<QByteArray>()));
return;
}
- m_pdfPrintCallback = callback;
- if (!PrintToPDFInternal(pageLayout, printInColor, useCustomMargins)) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(callback, QSharedPointer<QByteArray>()));
+ m_pdfPrintCallback = std::move(callback);
+ if (!PrintToPDFInternal(pageLayout, pageRanges, printInColor, useCustomMargins)) {
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(m_pdfPrintCallback), QSharedPointer<QByteArray>()));
resetPdfState();
}
}
bool PrintViewManagerQt::PrintToPDFInternal(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
const bool printInColor,
const bool useCustomMargins)
{
if (!pageLayout.isValid())
return false;
- m_printSettings.reset(createPrintSettingsFromQPageLayout(pageLayout, useCustomMargins));
- m_printSettings->SetBoolean(printing::kSettingShouldPrintBackgrounds,
- web_contents()->GetRenderViewHost()->
- GetWebkitPreferences().should_print_backgrounds);
- m_printSettings->SetInteger(printing::kSettingColor,
- printInColor ? printing::COLOR : printing::GRAYSCALE);
+ m_printSettings = createPrintSettingsFromQPageLayout(pageLayout, useCustomMargins);
+ m_printSettings.Set(printing::kSettingShouldPrintBackgrounds,
+ web_contents()->GetOrCreateWebPreferences().should_print_backgrounds);
+ m_printSettings.Set(printing::kSettingColor,
+ int(printInColor ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGrayscale));
+ if (!pageRanges.isEmpty())
+ m_printSettings.Set(printing::kSettingPageRange, createPageRangeSettings(pageRanges.toRangeList()));
- if (web_contents()->ShowingInterstitialPage() || web_contents()->IsCrashed())
+ if (web_contents()->IsCrashed())
return false;
- content::RenderFrameHost* rfh = web_contents()->GetMainFrame();
- GetPrintRenderFrame(rfh)->InitiatePrintPreview(mojo::PendingAssociatedRemote<printing::mojom::PrintRenderer>(), false);
+ content::RenderFrameHost *rfh = web_contents()->GetPrimaryMainFrame();
+ // Use the plugin frame for printing if web_contents() is a PDF viewer guest
+ content::RenderFrameHost *full_page_plugin = GetFullPagePlugin(web_contents());
+ if (content::RenderFrameHost *pdf_rfh = FindPdfChildFrame(full_page_plugin ? full_page_plugin : rfh))
+ rfh = pdf_rfh;
+ GetPrintRenderFrame(rfh)->InitiatePrintPreview(false);
DCHECK(!m_printPreviewRfh);
m_printPreviewRfh = rfh;
return true;
}
-// PrintedPagesSource implementation.
-base::string16 PrintViewManagerQt::RenderSourceName()
-{
- return base::string16();
-}
-
PrintViewManagerQt::PrintViewManagerQt(content::WebContents *contents)
: PrintViewManagerBaseQt(contents)
+ , content::WebContentsUserData<PrintViewManagerQt>(*contents)
, m_printPreviewRfh(nullptr)
{
}
-// content::WebContentsObserver implementation.
-bool PrintViewManagerQt::OnMessageReceived(const IPC::Message& message,
- content::RenderFrameHost* render_frame_host)
-{
- FrameDispatchHelper helper = {this, render_frame_host};
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintViewManagerQt, message, render_frame_host);
- IPC_MESSAGE_HANDLER(PrintHostMsg_DidShowPrintDialog, OnDidShowPrintDialog)
- IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview, OnRequestPrintPreview)
- IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting, OnMetafileReadyForPrinting);
- IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage, OnDidPreviewPage)
- IPC_MESSAGE_FORWARD_DELAY_REPLY(
- PrintHostMsg_SetupScriptedPrintPreview, &helper,
- FrameDispatchHelper::OnSetupScriptedPrintPreview)
- IPC_MESSAGE_HANDLER(PrintHostMsg_ShowScriptedPrintPreview,
- OnShowScriptedPrintPreview)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled || PrintViewManagerBaseQt::OnMessageReceived(message, render_frame_host);
-}
-
-void PrintViewManagerQt::RenderFrameDeleted(content::RenderFrameHost *render_frame_host)
+// static
+void PrintViewManagerQt::BindPrintManagerHost(mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver,
+ content::RenderFrameHost *rfh)
{
- if (render_frame_host == m_printPreviewRfh)
- PrintPreviewDone();
- PrintViewManagerBaseQt::RenderFrameDeleted(render_frame_host);
- m_printRenderFrames.erase(render_frame_host);
-}
-
-const mojo::AssociatedRemote<printing::mojom::PrintRenderFrame> &PrintViewManagerQt::GetPrintRenderFrame(content::RenderFrameHost *rfh)
-{
- auto it = m_printRenderFrames.find(rfh);
- if (it == m_printRenderFrames.end()) {
- mojo::AssociatedRemote<printing::mojom::PrintRenderFrame> remote;
- rfh->GetRemoteAssociatedInterfaces()->GetInterface(&remote);
- it = m_printRenderFrames.insert(std::make_pair(rfh, std::move(remote))).first;
- } else if (it->second.is_bound() && !it->second.is_connected()) {
- // When print preview is closed, the remote is disconnected from the
- // receiver. Reset and bind the remote before using it again.
- it->second.reset();
- rfh->GetRemoteAssociatedInterfaces()->GetInterface(&it->second);
- }
-
- return it->second;
+ auto *web_contents = content::WebContents::FromRenderFrameHost(rfh);
+ if (!web_contents)
+ return;
+ auto *print_manager = PrintViewManagerQt::FromWebContents(web_contents);
+ if (!print_manager)
+ return;
+ print_manager->BindReceiver(std::move(receiver), rfh);
}
void PrintViewManagerQt::resetPdfState()
@@ -341,50 +277,14 @@ void PrintViewManagerQt::resetPdfState()
m_pdfOutputPath.clear();
m_pdfPrintCallback.Reset();
m_pdfSaveCallback.Reset();
- m_printSettings.reset();
-}
-
-// IPC handlers
-
-void PrintViewManagerQt::OnRequestPrintPreview(
- const PrintHostMsg_RequestPrintPreview_Params &/*params*/)
-{
- m_printPreviewRfh->Send(new PrintMsg_PrintPreview(m_printPreviewRfh->GetRoutingID(),
- *m_printSettings));
- PrintPreviewDone();
-}
-
-void PrintViewManagerQt::OnMetafileReadyForPrinting(content::RenderFrameHost* rfh,
- const PrintHostMsg_DidPreviewDocument_Params& params,
- const PrintHostMsg_PreviewIds &ids)
-{
- StopWorker(params.document_cookie);
-
- // Create local copies so we can reset the state and take a new pdf print job.
- PrintToPDFCallback pdf_print_callback = std::move(m_pdfPrintCallback);
- PrintToPDFFileCallback pdf_save_callback = std::move(m_pdfSaveCallback);
- base::FilePath pdfOutputPath = m_pdfOutputPath;
-
- resetPdfState();
-
- if (!pdf_print_callback.is_null()) {
- QSharedPointer<QByteArray> data_array = GetStdVectorFromHandle(params.content.metafile_data_region);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(pdf_print_callback, data_array));
- } else {
- scoped_refptr<base::RefCountedBytes> data_bytes = GetBytesFromHandle(params.content.metafile_data_region);
- base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()},
- base::BindOnce(&SavePdfFile, data_bytes, pdfOutputPath, pdf_save_callback));
- }
+ m_printSettings.clear();
}
-void PrintViewManagerQt::OnDidShowPrintDialog()
-{
-}
-
-// content::WebContentsObserver implementation.
-void PrintViewManagerQt::DidStartLoading()
+void PrintViewManagerQt::PrintPreviewDone()
{
+ if (m_printPreviewRfh->IsRenderFrameLive() && IsPrintRenderFrameConnected(m_printPreviewRfh))
+ GetPrintRenderFrame(m_printPreviewRfh)->OnPrintPreviewDialogClosed();
+ m_printPreviewRfh = nullptr;
}
// content::WebContentsObserver implementation.
@@ -392,59 +292,116 @@ void PrintViewManagerQt::DidStartLoading()
void PrintViewManagerQt::NavigationStopped()
{
if (!m_pdfPrintCallback.is_null()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(m_pdfPrintCallback, QSharedPointer<QByteArray>()));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(m_pdfPrintCallback), QSharedPointer<QByteArray>()));
}
resetPdfState();
PrintViewManagerBaseQt::NavigationStopped();
}
-void PrintViewManagerQt::RenderProcessGone(base::TerminationStatus status)
+void PrintViewManagerQt::PrimaryMainFrameRenderProcessGone(base::TerminationStatus status)
{
- PrintViewManagerBaseQt::RenderProcessGone(status);
+ PrintViewManagerBaseQt::PrimaryMainFrameRenderProcessGone(status);
if (!m_pdfPrintCallback.is_null()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(m_pdfPrintCallback, QSharedPointer<QByteArray>()));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(m_pdfPrintCallback), QSharedPointer<QByteArray>()));
}
resetPdfState();
}
-void PrintViewManagerQt::OnDidPreviewPage(content::RenderFrameHost* rfh,
- const PrintHostMsg_DidPreviewPage_Params& params,
- const PrintHostMsg_PreviewIds& ids)
+void PrintViewManagerQt::RenderFrameDeleted(content::RenderFrameHost *render_frame_host)
{
- // just consume the message, this is just for sending 'page-preview-ready' for webui
+ if (render_frame_host == m_printPreviewRfh)
+ PrintPreviewDone();
+ PrintViewManagerBaseQt::RenderFrameDeleted(render_frame_host);
}
-void PrintViewManagerQt::OnSetupScriptedPrintPreview(content::RenderFrameHost* rfh,
- IPC::Message* reply_msg)
+// mojom::PrintManagerHost:
+void PrintViewManagerQt::SetupScriptedPrintPreview(SetupScriptedPrintPreviewCallback callback)
{
// ignore the scripted print
- rfh->Send(reply_msg);
+ std::move(callback).Run();
content::WebContentsView *view = static_cast<content::WebContentsImpl*>(web_contents())->GetView();
WebContentsAdapterClient *client = WebContentsViewQt::from(view)->client();
-
+ content::RenderFrameHost *rfh =
+ print_manager_host_receivers_.GetCurrentTargetFrame();
if (!client)
return;
// close preview
- GetPrintRenderFrame(rfh)->OnPrintPreviewDialogClosed();
+ if (rfh)
+ GetPrintRenderFrame(rfh)->OnPrintPreviewDialogClosed();
client->printRequested();
}
-void PrintViewManagerQt::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
- bool source_is_modifiable)
+void PrintViewManagerQt::ShowScriptedPrintPreview(bool /*source_is_modifiable*/)
{
// ignore for now
}
-void PrintViewManagerQt::PrintPreviewDone() {
- GetPrintRenderFrame(m_printPreviewRfh)->OnPrintPreviewDialogClosed();
- m_printPreviewRfh = nullptr;
+void PrintViewManagerQt::RequestPrintPreview(printing::mojom::RequestPrintPreviewParamsPtr params)
+{
+ if (!m_printPreviewRfh && params->webnode_only) {
+ // The preview was requested by the print button of PDF viewer plugin. The code path ends up here, because
+ // Chromium automatically initiated a preview generation. We don't want that, just notify our embedder
+ // like we do in SetupScriptedPrintPreview() after window.print() and let them decide what to do.
+ content::WebContentsView *view = static_cast<content::WebContentsImpl*>(web_contents()->GetOutermostWebContents())->GetView();
+ if (WebContentsAdapterClient *client = WebContentsViewQt::from(view)->client())
+ client->printRequested();
+ return;
+ }
+
+ if (m_printSettings.empty()) {
+ PrintPreviewDone();
+ return;
+ }
+
+ mojo::AssociatedRemote<printing::mojom::PrintRenderFrame> printRenderFrame;
+ m_printPreviewRfh->GetRemoteAssociatedInterfaces()->GetInterface(&printRenderFrame);
+ printRenderFrame->PrintPreview(m_printSettings.Clone());
+ PrintPreviewDone();
+}
+
+void PrintViewManagerQt::CheckForCancel(int32_t preview_ui_id,
+ int32_t request_id,
+ CheckForCancelCallback callback)
+{
+ Q_UNUSED(preview_ui_id);
+ Q_UNUSED(request_id);
+ std::move(callback).Run(false);
+}
+
+void PrintViewManagerQt::SetAccessibilityTree(int32_t, const ui::AXTreeUpdate &)
+{
+ // FIXME!
+}
+
+void PrintViewManagerQt::MetafileReadyForPrinting(printing::mojom::DidPreviewDocumentParamsPtr params,
+ int32_t preview_ui_id)
+{
+ Q_UNUSED(preview_ui_id);
+ StopWorker(params->document_cookie);
+
+ // Create local copies so we can reset the state and take a new pdf print job.
+ PrintToPDFCallback pdf_print_callback = std::move(m_pdfPrintCallback);
+ PrintToPDFFileCallback pdf_save_callback = std::move(m_pdfSaveCallback);
+ base::FilePath pdfOutputPath = m_pdfOutputPath;
+
+ resetPdfState();
+
+ if (!pdf_print_callback.is_null()) {
+ QSharedPointer<QByteArray> data_array = GetStdVectorFromHandle(params->content->metafile_data_region);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ base::BindOnce(std::move(pdf_print_callback), data_array));
+ } else {
+ scoped_refptr<base::RefCountedBytes> data_bytes = GetBytesFromHandle(params->content->metafile_data_region);
+ base::ThreadPool::PostTask(FROM_HERE, { base::MayBlock() },
+ base::BindOnce(&SavePdfFile, data_bytes, pdfOutputPath, std::move(pdf_save_callback)));
+ }
}
-WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerQt)
+WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerQt);
} // namespace QtWebEngineCore
diff --git a/src/core/printing/print_view_manager_qt.h b/src/core/printing/print_view_manager_qt.h
index 06c2f47ea..956849ef9 100644
--- a/src/core/printing/print_view_manager_qt.h
+++ b/src/core/printing/print_view_manager_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -49,35 +13,16 @@
#include "qtwebenginecoreglobal_p.h"
#include "base/memory/ref_counted.h"
-#include "base/strings/string16.h"
#include "components/prefs/pref_member.h"
-#include "components/printing/browser/print_manager.h"
#include "components/printing/common/print.mojom.h"
-#include "components/printing/common/print_messages.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/web_contents_user_data.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include <QSharedPointer>
-struct PrintHostMsg_RequestPrintPreview_Params;
-struct PrintHostMsg_DidPreviewDocument_Params;
-
-namespace content {
-class RenderViewHost;
-}
-
-namespace printing {
-class JobEventDetails;
-class MetafilePlayer;
-class PrintJob;
-class PrintJobWorkerOwner;
-class PrintQueriesQueue;
-}
-
QT_BEGIN_NAMESPACE
class QPageLayout;
+class QPageRanges;
class QString;
QT_END_NAMESPACE
@@ -88,60 +33,52 @@ class PrintViewManagerQt
{
public:
~PrintViewManagerQt() override;
- typedef base::Callback<void(QSharedPointer<QByteArray> result)> PrintToPDFCallback;
- typedef base::Callback<void(bool success)> PrintToPDFFileCallback;
+
+ static void BindPrintManagerHost(mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver,
+ content::RenderFrameHost *rfh);
+
+ typedef base::OnceCallback<void(QSharedPointer<QByteArray> result)> PrintToPDFCallback;
+ typedef base::OnceCallback<void(bool success)> PrintToPDFFileCallback;
// Method to print a page to a Pdf document with page size \a pageSize in location \a filePath.
void PrintToPDFFileWithCallback(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
bool printInColor,
const QString &filePath,
- const PrintToPDFFileCallback& callback);
+ PrintToPDFFileCallback callback);
void PrintToPDFWithCallback(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
bool printInColor,
bool useCustomMargins,
- const PrintToPDFCallback &callback);
-
- base::string16 RenderSourceName() override;
+ PrintToPDFCallback callback);
protected:
explicit PrintViewManagerQt(content::WebContents*);
+ bool PrintToPDFInternal(const QPageLayout &, const QPageRanges &, bool printInColor, bool useCustomMargins = true);
+
// content::WebContentsObserver implementation.
// Cancels the print job.
void NavigationStopped() override;
// Terminates or cancels the print job if one was pending.
- void RenderProcessGone(base::TerminationStatus status) override;
+ void PrimaryMainFrameRenderProcessGone(base::TerminationStatus status) override;
- // content::WebContentsObserver implementation.
- bool OnMessageReceived(const IPC::Message& message,
- content::RenderFrameHost* render_frame_host) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
- // IPC handlers
- void OnDidShowPrintDialog();
- void OnRequestPrintPreview(const PrintHostMsg_RequestPrintPreview_Params&);
- void OnMetafileReadyForPrinting(content::RenderFrameHost* rfh,
- const PrintHostMsg_DidPreviewDocument_Params& params,
- const PrintHostMsg_PreviewIds &ids);
- void OnSetupScriptedPrintPreview(content::RenderFrameHost* rfh,
- IPC::Message* reply_msg);
- void OnDidPreviewPage(content::RenderFrameHost* rfh,
- const PrintHostMsg_DidPreviewPage_Params& params,
- const PrintHostMsg_PreviewIds& ids);
- void OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
- bool source_is_modifiable);
- bool PrintToPDFInternal(const QPageLayout &, bool printInColor, bool useCustomMargins = true);
-
+ // mojom::PrintManagerHost:
+ void SetupScriptedPrintPreview(SetupScriptedPrintPreviewCallback callback) override;
+ void ShowScriptedPrintPreview(bool source_is_modifiable) override;
+ void RequestPrintPreview(printing::mojom::RequestPrintPreviewParamsPtr params) override;
+ void CheckForCancel(int32_t preview_ui_id,
+ int32_t request_id,
+ CheckForCancelCallback callback) override;
+ void MetafileReadyForPrinting(printing::mojom::DidPreviewDocumentParamsPtr params,
+ int32_t preview_ui_id) override;
+ void SetAccessibilityTree(int32_t, const ui::AXTreeUpdate &) override;
private:
void resetPdfState();
- // Helper method to fetch the PrintRenderFrame associated remote interface
- // pointer.
- const mojo::AssociatedRemote<printing::mojom::PrintRenderFrame> &GetPrintRenderFrame(content::RenderFrameHost *rfh);
-
- // content::WebContentsObserver implementation.
- void DidStartLoading() override;
void PrintPreviewDone();
private:
@@ -150,13 +87,9 @@ private:
base::FilePath m_pdfOutputPath;
PrintToPDFCallback m_pdfPrintCallback;
PrintToPDFFileCallback m_pdfSaveCallback;
- std::unique_ptr<base::DictionaryValue> m_printSettings;
-
- std::map<content::RenderFrameHost*,mojo::AssociatedRemote<printing::mojom::PrintRenderFrame>> m_printRenderFrames;
+ base::Value::Dict m_printSettings;
friend class content::WebContentsUserData<PrintViewManagerQt>;
- DISALLOW_COPY_AND_ASSIGN(PrintViewManagerQt);
- struct FrameDispatchHelper;
};
} // namespace QtWebEngineCore
diff --git a/src/core/printing/printer_worker.cpp b/src/core/printing/printer_worker.cpp
new file mode 100644
index 000000000..6032f2211
--- /dev/null
+++ b/src/core/printing/printer_worker.cpp
@@ -0,0 +1,87 @@
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "printer_worker.h"
+
+#include "printing/pdfium_document_wrapper_qt.h"
+
+#include <QPainter>
+#include <QPagedPaintDevice>
+
+namespace QtWebEngineCore {
+
+PrinterWorker::PrinterWorker(QSharedPointer<QByteArray> data, QPagedPaintDevice *device)
+ : m_data(data), m_device(device)
+{
+}
+
+PrinterWorker::~PrinterWorker() { }
+
+void PrinterWorker::print()
+{
+ if (!m_data->size()) {
+ qWarning("Failed to print: Print result data is empty.");
+ Q_EMIT resultReady(false);
+ return;
+ }
+
+ PdfiumDocumentWrapperQt pdfiumWrapper(m_data->constData(), m_data->size());
+
+ const int fromPage = m_firstPageFirst ? 0 : pdfiumWrapper.pageCount() - 1;
+ const int toPage = m_firstPageFirst ? pdfiumWrapper.pageCount() : -1;
+
+ int pageCopies = 1;
+ if (m_collateCopies) {
+ pageCopies = m_documentCopies;
+ m_documentCopies = 1;
+ }
+
+ qreal resolution = m_deviceResolution / 72.0; // pdfium uses points so 1/72 inch
+
+ QPainter painter;
+
+ for (int printedDocuments = 0; printedDocuments < m_documentCopies; printedDocuments++) {
+ if (printedDocuments > 0)
+ m_device->newPage();
+
+ for (int i = fromPage; i != toPage; m_firstPageFirst ? i++ : i--) {
+ QSizeF documentSize = (pdfiumWrapper.pageSize(i) * resolution);
+ bool isLandscape = documentSize.width() > documentSize.height();
+ m_device->setPageOrientation(isLandscape ? QPageLayout::Landscape
+ : QPageLayout::Portrait);
+ QRectF paintRect = m_device->pageLayout().paintRectPixels(m_deviceResolution);
+ documentSize = documentSize.scaled(paintRect.size(), Qt::KeepAspectRatio);
+
+ // setPageOrientation has to be called before qpainter.begin() or before
+ // qprinter.newPage() so correct metrics is used, therefore call begin now for only
+ // first page
+ if (!painter.isActive() && !painter.begin(m_device)) {
+ qWarning("Failure to print on device: Could not open printer for painting.");
+ Q_EMIT resultReady(false);
+ return;
+ }
+
+ if (i != fromPage)
+ m_device->newPage();
+
+ for (int printedPages = 0; printedPages < pageCopies; printedPages++) {
+ if (printedPages > 0)
+ m_device->newPage();
+
+ QImage currentImage =
+ pdfiumWrapper.pageAsQImage(i, documentSize.width(), documentSize.height());
+ if (currentImage.isNull()) {
+ Q_EMIT resultReady(false);
+ return;
+ }
+ painter.drawImage(0, 0, currentImage);
+ }
+ }
+ }
+ painter.end();
+
+ Q_EMIT resultReady(true);
+ return;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/printing/printer_worker.h b/src/core/printing/printer_worker.h
new file mode 100644
index 000000000..0d2454fa0
--- /dev/null
+++ b/src/core/printing/printer_worker.h
@@ -0,0 +1,58 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef PRINTER_WORKER_H
+#define PRINTER_WORKER_H
+
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qsharedpointer.h>
+
+QT_BEGIN_NAMESPACE
+class QPagedPaintDevice;
+QT_END_NAMESPACE
+
+namespace QtWebEngineCore {
+
+class Q_WEBENGINECORE_EXPORT PrinterWorker : public QObject
+{
+ Q_OBJECT
+public:
+ PrinterWorker(QSharedPointer<QByteArray> data, QPagedPaintDevice *device);
+ virtual ~PrinterWorker();
+
+ int m_deviceResolution;
+ bool m_firstPageFirst;
+ int m_documentCopies;
+ bool m_collateCopies;
+
+public Q_SLOTS:
+ void print();
+
+Q_SIGNALS:
+ void resultReady(bool success);
+
+private:
+ Q_DISABLE_COPY(PrinterWorker)
+
+ QSharedPointer<QByteArray> m_data;
+ QPagedPaintDevice *m_device;
+};
+
+} // namespace QtWebEngineCore
+
+Q_DECLARE_METATYPE(QtWebEngineCore::PrinterWorker *)
+
+#endif // PRINTER_WORKER_H
diff --git a/src/core/printing/printing_message_filter_qt.cpp b/src/core/printing/printing_message_filter_qt.cpp
deleted file mode 100644
index 5b9228d20..000000000
--- a/src/core/printing/printing_message_filter_qt.cpp
+++ /dev/null
@@ -1,234 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Based on chrome/browser/printing/printing_message_filter.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#include "printing_message_filter_qt.h"
-
-#include "web_engine_context.h"
-
-#include <string>
-
-#include "base/bind.h"
-#include "chrome/browser/printing/print_job_manager.h"
-#include "chrome/browser/printing/printer_query.h"
-#include "components/printing/browser/print_manager_utils.h"
-#include "components/printing/common/print_messages.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/child_process_host.h"
-
-using content::BrowserThread;
-
-namespace QtWebEngineCore {
-
-PrintingMessageFilterQt::PrintingMessageFilterQt(int render_process_id)
- : BrowserMessageFilter(PrintMsgStart),
- render_process_id_(render_process_id),
- queue_(WebEngineContext::current()->getPrintJobManager()->queue()) {
- DCHECK(queue_.get());
-}
-
-PrintingMessageFilterQt::~PrintingMessageFilterQt() {
-}
-
-void PrintingMessageFilterQt::OverrideThreadForMessage(
- const IPC::Message& message, BrowserThread::ID* thread) {
-}
-
-bool PrintingMessageFilterQt::OnMessageReceived(const IPC::Message& message) {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilterQt, message)
- IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,
- OnGetDefaultPrintSettings)
- IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
- IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_UpdatePrintSettings,
- OnUpdatePrintSettings)
- IPC_MESSAGE_HANDLER(PrintHostMsg_CheckForCancel, OnCheckForCancel)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
-void PrintingMessageFilterQt::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- std::unique_ptr<printing::PrinterQuery> printer_query;
-
- printer_query = queue_->PopPrinterQuery(0);
- if (!printer_query) {
- printer_query =
- queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
- }
-
- // Loads default settings. This is asynchronous, only the IPC message sender
- // will hang until the settings are retrieved.
- printer_query->GetSettings(
- printing::PrinterQuery::GetSettingsAskParam::DEFAULTS,
- 0,
- false,
- printing::DEFAULT_MARGINS,
- false,
- false,
- base::BindOnce(&PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply,
- this,
- std::move(printer_query),
- reply_msg));
-}
-
-void PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply(
- std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg) {
- PrintMsg_Print_Params params;
- if (!printer_query.get() ||
- printer_query->last_status() != printing::PrintingContext::OK) {
- params.Reset();
- } else {
- RenderParamsFromPrintSettings(printer_query->settings(), &params);
- params.document_cookie = printer_query->cookie();
- }
- PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
- Send(reply_msg);
- // If printing was enabled.
- if (printer_query.get()) {
- // If user hasn't cancelled.
- if (printer_query->cookie() && printer_query->settings().dpi()) {
- queue_->QueuePrinterQuery(std::move(printer_query));
- } else {
- printer_query->StopWorker();
- }
- }
-}
-
-void PrintingMessageFilterQt::OnScriptedPrint(
- const PrintHostMsg_ScriptedPrint_Params& params,
- IPC::Message* reply_msg) {
- std::unique_ptr<printing::PrinterQuery> printer_query =
- queue_->PopPrinterQuery(params.cookie);
- if (!printer_query.get()) {
- printer_query =
- queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
- }
- printer_query->GetSettings(
- printing::PrinterQuery::GetSettingsAskParam::ASK_USER,
- params.expected_pages_count,
- params.has_selection,
- params.margin_type,
- params.is_scripted,
- params.is_modifiable,
- base::BindOnce(&PrintingMessageFilterQt::OnScriptedPrintReply,
- this,
- std::move(printer_query),
- reply_msg));
-}
-
-void PrintingMessageFilterQt::OnScriptedPrintReply(
- std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg) {
- PrintMsg_PrintPages_Params params;
-
- if (printer_query->last_status() != printing::PrintingContext::OK ||
- !printer_query->settings().dpi()) {
- params.Reset();
- } else {
- RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
- params.params.document_cookie = printer_query->cookie();
- params.pages = printing::PageRange::GetPages(printer_query->settings().ranges());
- }
- PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
- Send(reply_msg);
- if (!params.params.dpi.IsEmpty() && params.params.document_cookie) {
- queue_->QueuePrinterQuery(std::move(printer_query));
- } else {
- printer_query->StopWorker();
- }
-}
-
-void PrintingMessageFilterQt::OnUpdatePrintSettings(int document_cookie,
- base::Value job_settings,
- IPC::Message* reply_msg) {
- std::unique_ptr<printing::PrinterQuery> printer_query;
- printer_query = queue_->PopPrinterQuery(document_cookie);
- if (!printer_query.get()) {
- printer_query = queue_->CreatePrinterQuery(
- content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE);
- }
- printer_query->SetSettings(
- std::move(job_settings),
- base::BindOnce(&PrintingMessageFilterQt::OnUpdatePrintSettingsReply, this,
- std::move(printer_query), reply_msg));
-}
-
-void PrintingMessageFilterQt::OnUpdatePrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg) {
- PrintMsg_PrintPages_Params params;
- if (!printer_query.get() ||
- printer_query->last_status() != printing::PrintingContext::OK) {
- params.Reset();
- } else {
- RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
- params.params.document_cookie = printer_query->cookie();
- params.pages = printing::PageRange::GetPages(printer_query->settings().ranges());
- }
-
- PrintHostMsg_UpdatePrintSettings::WriteReplyParams(
- reply_msg,
- params,
- printer_query.get() &&
- (printer_query->last_status() == printing::PrintingContext::CANCEL));
- Send(reply_msg);
- // If user hasn't cancelled.
- if (printer_query) {
- if (printer_query->cookie() && printer_query->settings().dpi()) {
- queue_->QueuePrinterQuery(std::move(printer_query));
- } else {
- printer_query->StopWorker();
- }
- }
-}
-
-void PrintingMessageFilterQt::OnCheckForCancel(const PrintHostMsg_PreviewIds& ids,
- bool* cancel) {
- *cancel = false;
-}
-
-} // namespace printing
diff --git a/src/core/printing/printing_message_filter_qt.h b/src/core/printing/printing_message_filter_qt.h
deleted file mode 100644
index 89e473dcf..000000000
--- a/src/core/printing/printing_message_filter_qt.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#ifndef PRINTING_PRINTING_MESSAGE_FILTER_QT_H_
-#define PRINTING_PRINTING_MESSAGE_FILTER_QT_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "components/prefs/pref_member.h"
-#include "content/public/browser/browser_message_filter.h"
-
-struct PrintHostMsg_PreviewIds;
-struct PrintHostMsg_ScriptedPrint_Params;
-
-namespace base {
-class DictionaryValue;
-class FilePath;
-}
-
-namespace content {
-class WebContents;
-}
-
-namespace printing {
-class PrintJobManager;
-class PrintQueriesQueue;
-class PrinterQuery;
-}
-
-namespace QtWebEngineCore {
-// This class filters out incoming printing related IPC messages for the
-// renderer process on the IPC thread.
-class PrintingMessageFilterQt : public content::BrowserMessageFilter {
- public:
- PrintingMessageFilterQt(int render_process_id);
-
- // content::BrowserMessageFilter methods.
- void OverrideThreadForMessage(const IPC::Message& message,
- content::BrowserThread::ID* thread) override;
- bool OnMessageReceived(const IPC::Message& message) override;
-
- private:
- ~PrintingMessageFilterQt() override;
-
- // GetPrintSettingsForRenderView must be called via PostTask and
- // base::Bind. Collapse the settings-specific params into a
- // struct to avoid running into issues with too many params
- // to base::Bind.
- struct GetPrintSettingsForRenderViewParams;
-
- // Get the default print setting.
- void OnGetDefaultPrintSettings(IPC::Message* reply_msg);
- void OnGetDefaultPrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg);
-
- // The renderer host have to show to the user the print dialog and returns
- // the selected print settings. The task is handled by the print worker
- // thread and the UI thread. The reply occurs on the IO thread.
- void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params,
- IPC::Message* reply_msg);
- void OnScriptedPrintReply(std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg);
-
- // Modify the current print settings based on |job_settings|. The task is
- // handled by the print worker thread and the UI thread. The reply occurs on
- // the IO thread.
- void OnUpdatePrintSettings(int document_cookie,
- base::Value job_settings,
- IPC::Message* reply_msg);
- void OnUpdatePrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query,
- IPC::Message* reply_msg);
-
- // Check to see if print preview has been cancelled.
- void OnCheckForCancel(const PrintHostMsg_PreviewIds& ids, bool* cancel);
-
- const int render_process_id_;
-
- scoped_refptr<printing::PrintQueriesQueue> queue_;
-
- DISALLOW_COPY_AND_ASSIGN(PrintingMessageFilterQt);
-};
-
-} // namespace printing
-
-#endif // PRINTING_PRINTING_MESSAGE_FILTER_QT_H_
diff --git a/src/core/process_main.cpp b/src/core/process_main.cpp
index ade0f6e99..6a7d26ffd 100644
--- a/src/core/process_main.cpp
+++ b/src/core/process_main.cpp
@@ -1,70 +1,28 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "process_main.h"
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "qtwebenginecoreglobal_p.h"
#include "content_main_delegate_qt.h"
#include "content/public/app/content_main.h"
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
#include "sandbox/win/src/sandbox_types.h"
#include "content/public/app/sandbox_helper_win.h"
-#elif defined(OS_MACOSX)
-#include "base/logging.h"
+#elif BUILDFLAG(IS_MAC)
#include "sandbox/mac/seatbelt_exec.h"
#endif
namespace QtWebEngineCore {
-#if defined(OS_WIN)
-extern sandbox::SandboxInterfaceInfo *staticSandboxInterfaceInfo(sandbox::SandboxInterfaceInfo *info = nullptr);
-#endif
-
/*! \internal */
int processMain(int argc, const char **argv)
{
ContentMainDelegateQt delegate;
content::ContentMainParams params(&delegate);
-#if defined(OS_WIN)
+#if BUILDFLAG(IS_WIN)
HINSTANCE instance_handle = NULL;
- params.sandbox_info = staticSandboxInterfaceInfo();
- sandbox::SandboxInterfaceInfo sandbox_info = {0};
+ params.sandbox_info = QtWebEngineSandbox::staticSandboxInterfaceInfo();
+ sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
if (!params.sandbox_info) {
content::InitializeSandboxInfo(&sandbox_info);
params.sandbox_info = &sandbox_info;
@@ -73,16 +31,15 @@ int processMain(int argc, const char **argv)
#else
params.argc = argc;
params.argv = argv;
-#endif // OS_WIN
-#if defined(OS_MACOSX)
+#endif // IS_WIN
+#if BUILDFLAG(IS_MAC)
sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
sandbox::SeatbeltExecServer::CreateFromArguments(argv[0], argc, const_cast<char**>(argv));
if (seatbelt.sandbox_required) {
CHECK(seatbelt.server->InitializeSandbox());
}
-#endif // defined(OS_MACOSX)
-
- return content::ContentMain(params);
+#endif // IS_MAC
+ return content::ContentMain(std::move(params));
}
} // namespace QtWebEngineCore
diff --git a/src/core/process_main.h b/src/core/process_main.h
deleted file mode 100644
index fed2f3064..000000000
--- a/src/core/process_main.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
-
-namespace QtWebEngineCore {
-
-Q_WEBENGINECORE_PRIVATE_EXPORT int processMain(int argc, const char **argv);
-
-} // namespace
diff --git a/src/core/profile_adapter.cpp b/src/core/profile_adapter.cpp
index 4557ad7a4..b26f9b1de 100644
--- a/src/core/profile_adapter.cpp
+++ b/src/core/profile_adapter.cpp
@@ -1,56 +1,29 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "profile_adapter.h"
+#include "base/files/file_util.h"
+#include "base/task/cancelable_task_tracker.h"
+#include "base/threading/thread_restrictions.h"
+#include "base/time/time_to_iso8601.h"
+#include "components/embedder_support/user_agent_utils.h"
+#include "components/favicon/core/favicon_service.h"
+#include "components/history/content/browser/history_database_helper.h"
+#include "components/history/core/browser/history_database_params.h"
+#include "components/history/core/browser/history_service.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/download_manager.h"
-#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
-#include "services/network/public/cpp/cors/origin_access_list.h"
+#include "services/network/public/mojom/network_context.mojom.h"
#include "url/url_util.h"
#include "api/qwebengineurlscheme.h"
#include "content_browser_client_qt.h"
#include "download_manager_delegate_qt.h"
+#include "favicon_service_factory_qt.h"
#include "permission_manager_qt.h"
#include "profile_adapter_client.h"
#include "profile_io_data_qt.h"
@@ -58,12 +31,8 @@
#include "renderer_host/user_resource_controller_host.h"
#include "type_conversion.h"
#include "visited_links_manager_qt.h"
-#include "web_engine_context.h"
#include "web_contents_adapter_client.h"
-
-#include "base/files/file_util.h"
-#include "base/time/time_to_iso8601.h"
-#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "web_engine_context.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/browser/extension_system.h"
@@ -71,6 +40,8 @@
#include <QCoreApplication>
#include <QDir>
+#include <QJsonObject>
+#include <QSet>
#include <QString>
#include <QStandardPaths>
@@ -94,12 +65,13 @@ ProfileAdapter::ProfileAdapter(const QString &storageName):
, m_httpCacheType(DiskHttpCache)
, m_persistentCookiesPolicy(AllowPersistentCookies)
, m_visitedLinksPolicy(TrackVisitedLinksOnDisk)
+ , m_clientHintsEnabled(true)
+ , m_pushServiceEnabled(false)
, m_httpCacheMaxSize(0)
{
WebEngineContext::current()->addProfileAdapter(this);
// creation of profile requires webengine context
m_profile.reset(new ProfileQt(this));
- content::BrowserContext::Initialize(m_profile.data(), toFilePath(dataPath()));
// fixme: this should not be here
m_profile->m_profileIOData->initializeOnUIThread();
m_customUrlSchemeHandlers.insert(QByteArrayLiteral("qrc"), &m_qrcHandler);
@@ -107,32 +79,27 @@ ProfileAdapter::ProfileAdapter(const QString &storageName):
if (!storageName.isEmpty())
extensions::ExtensionSystem::Get(m_profile.data())->InitForRegularProfile(true);
#endif
+ m_cancelableTaskTracker.reset(new base::CancelableTaskTracker());
- // Allow XMLHttpRequests from qrc to file.
- // ### consider removing for Qt6
- url::Origin qrc = url::Origin::Create(GURL("qrc://"));
- auto pattern = network::mojom::CorsOriginPattern::New("file", "", 0,
- network::mojom::CorsDomainMatchMode::kAllowSubdomains,
- network::mojom::CorsPortMatchMode::kAllowAnyPort,
- network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
- std::vector<network::mojom::CorsOriginPatternPtr> list;
- list.push_back(std::move(pattern));
- m_profile->GetSharedCorsOriginAccessList()->SetForOrigin(qrc, std::move(list), {}, base::BindOnce([]{}));
+ m_profile->DoFinalInit();
}
ProfileAdapter::~ProfileAdapter()
{
- while (!m_webContentsAdapterClients.isEmpty()) {
- m_webContentsAdapterClients.first()->releaseProfile();
- }
+ m_cancelableTaskTracker->TryCancelAll();
+ m_profile->NotifyWillBeDestroyed();
+ releaseAllWebContentsAdapterClients();
+
WebEngineContext::current()->removeProfileAdapter(this);
if (m_downloadManagerDelegate) {
- m_profile->GetDownloadManager(m_profile.data())->Shutdown();
+ m_profile->GetDownloadManager()->Shutdown();
m_downloadManagerDelegate.reset();
}
#if QT_CONFIG(ssl)
delete m_clientCertificateStore;
+ m_clientCertificateStore = nullptr;
#endif
+ WebEngineContext::flushMessages();
}
void ProfileAdapter::setStorageName(const QString &storageName)
@@ -146,6 +113,8 @@ void ProfileAdapter::setStorageName(const QString &storageName)
m_profile->m_profileIOData->resetNetworkContext();
if (m_visitedLinksManager)
resetVisitedLinksManager();
+
+ reinitializeHistoryService();
}
}
@@ -159,6 +128,14 @@ void ProfileAdapter::setOffTheRecord(bool offTheRecord)
m_profile->m_profileIOData->resetNetworkContext();
if (m_visitedLinksManager)
resetVisitedLinksManager();
+
+ if (offTheRecord) {
+ favicon::FaviconService *faviconService =
+ FaviconServiceFactoryQt::GetForBrowserContext(m_profile.data());
+ faviconService->SetHistoryService(nullptr);
+ } else if (!m_name.isEmpty()) {
+ reinitializeHistoryService();
+ }
}
ProfileQt *ProfileAdapter::profile()
@@ -166,6 +143,26 @@ ProfileQt *ProfileAdapter::profile()
return m_profile.data();
}
+bool ProfileAdapter::ensureDataPathExists()
+{
+ Q_ASSERT(!m_offTheRecord);
+ base::ScopedAllowBlocking allowBlock;
+ const base::FilePath &path = toFilePath(dataPath());
+ if (path.empty())
+ return false;
+ if (base::DirectoryExists(path))
+ return true;
+
+ base::File::Error error;
+ if (base::CreateDirectoryAndGetError(path, &error))
+ return true;
+
+ std::string errorstr = base::File::ErrorToString(error);
+ qWarning("Cannot create directory %s. Error: %s.", path.AsUTF8Unsafe().c_str(),
+ errorstr.c_str());
+ return false;
+}
+
VisitedLinksManagerQt *ProfileAdapter::visitedLinksManager()
{
if (!m_visitedLinksManager)
@@ -207,9 +204,9 @@ void ProfileAdapter::removeClient(ProfileAdapterClient *adapterClient)
m_clients.removeOne(adapterClient);
}
-void ProfileAdapter::cancelDownload(quint32 downloadId)
+bool ProfileAdapter::cancelDownload(quint32 downloadId)
{
- downloadManagerDelegate()->cancelDownload(downloadId);
+ return downloadManagerDelegate()->cancelDownload(downloadId);
}
void ProfileAdapter::pauseDownload(quint32 downloadId)
@@ -245,13 +242,17 @@ QObject* ProfileAdapter::globalQObjectRoot()
QString ProfileAdapter::dataPath() const
{
- if (m_offTheRecord)
- return QString();
if (!m_dataPath.isEmpty())
return m_dataPath;
- if (!m_name.isNull())
- return buildLocationFromStandardPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation), m_name);
- return QString();
+ // And off-the-record or memory-only profile should not write to disk
+ // but Chromium often creates temporary directories anyway, so given them
+ // a location to do so.
+ QString name = m_name;
+ if (m_offTheRecord)
+ name = QStringLiteral("OffTheRecord");
+ else if (m_name.isEmpty())
+ name = QStringLiteral("UnknownProfile");
+ return buildLocationFromStandardPath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), name);
}
void ProfileAdapter::setDataPath(const QString &path)
@@ -259,13 +260,14 @@ void ProfileAdapter::setDataPath(const QString &path)
if (m_dataPath == path)
return;
m_dataPath = path;
- if (!m_offTheRecord) {
- m_profile->setupPrefService();
- if (!m_profile->m_profileIOData->isClearHttpCacheInProgress())
- m_profile->m_profileIOData->resetNetworkContext();
- if (m_visitedLinksManager)
- resetVisitedLinksManager();
- }
+ m_profile->setupPrefService();
+ if (!m_profile->m_profileIOData->isClearHttpCacheInProgress())
+ m_profile->m_profileIOData->resetNetworkContext();
+ if (!m_offTheRecord && m_visitedLinksManager)
+ resetVisitedLinksManager();
+
+ if (!m_offTheRecord)
+ reinitializeHistoryService();
}
void ProfileAdapter::setDownloadPath(const QString &path)
@@ -320,13 +322,16 @@ void ProfileAdapter::setHttpUserAgent(const QString &userAgent)
std::vector<content::WebContentsImpl *> list = content::WebContentsImpl::GetAllWebContents();
for (content::WebContentsImpl *web_contents : list)
- if (web_contents->GetBrowserContext() == m_profile.data())
- web_contents->SetUserAgentOverride(stdUserAgent, true);
+ if (web_contents->GetBrowserContext() == m_profile.data()) {
+ auto userAgentOverride = blink::UserAgentOverride::UserAgentOnly(stdUserAgent);
+ userAgentOverride.ua_metadata_override = m_profile->m_userAgentMetadata;
+ web_contents->SetUserAgentOverride(userAgentOverride, true);
+ }
- content::BrowserContext::ForEachStoragePartition(
- m_profile.get(), base::BindRepeating([](const std::string &user_agent, content::StoragePartition *storage_partition) {
- storage_partition->GetNetworkContext()->SetUserAgent(user_agent);
- }, stdUserAgent));
+ m_profile->ForEachLoadedStoragePartition(
+ base::BindRepeating([](const std::string &user_agent, content::StoragePartition *storage_partition) {
+ storage_partition->GetNetworkContext()->SetUserAgent(user_agent);
+ }, stdUserAgent));
}
ProfileAdapter::HttpCacheType ProfileAdapter::httpCacheType() const
@@ -346,14 +351,12 @@ void ProfileAdapter::setHttpCacheType(ProfileAdapter::HttpCacheType newhttpCache
return;
if (!m_offTheRecord && !m_profile->m_profileIOData->isClearHttpCacheInProgress()) {
m_profile->m_profileIOData->resetNetworkContext();
- if (m_httpCacheType == NoCache)
- clearHttpCache();
}
}
ProfileAdapter::PersistentCookiesPolicy ProfileAdapter::persistentCookiesPolicy() const
{
- if (isOffTheRecord() || dataPath().isEmpty())
+ if (isOffTheRecord() || m_name.isEmpty())
return NoPersistentCookies;
return m_persistentCookiesPolicy;
}
@@ -372,7 +375,7 @@ ProfileAdapter::VisitedLinksPolicy ProfileAdapter::visitedLinksPolicy() const
{
if (isOffTheRecord() || m_visitedLinksPolicy == DoNotTrackVisitedLinks)
return DoNotTrackVisitedLinks;
- if (dataPath().isEmpty())
+ if (m_name.isEmpty())
return TrackVisitedLinksInMemory;
return m_visitedLinksPolicy;
}
@@ -465,10 +468,10 @@ const QList<QByteArray> ProfileAdapter::customUrlSchemes() const
void ProfileAdapter::updateCustomUrlSchemeHandlers()
{
- content::BrowserContext::ForEachStoragePartition(
- m_profile.get(), base::BindRepeating([](content::StoragePartition *storage_partition) {
- storage_partition->ResetURLLoaderFactories();
- }));
+ m_profile->ForEachLoadedStoragePartition(
+ base::BindRepeating([](content::StoragePartition *storage_partition) {
+ storage_partition->ResetURLLoaderFactories();
+ }));
}
void ProfileAdapter::removeUrlSchemeHandler(QWebEngineUrlSchemeHandler *handler)
@@ -581,16 +584,120 @@ void ProfileAdapter::setHttpAcceptLanguage(const QString &httpAcceptLanguage)
std::vector<content::WebContentsImpl *> list = content::WebContentsImpl::GetAllWebContents();
for (content::WebContentsImpl *web_contents : list) {
if (web_contents->GetBrowserContext() == m_profile.data()) {
- blink::mojom::RendererPreferences *rendererPrefs = web_contents->GetMutableRendererPrefs();
+ blink::RendererPreferences *rendererPrefs = web_contents->GetMutableRendererPrefs();
rendererPrefs->accept_languages = http_accept_language;
web_contents->SyncRendererPrefs();
}
}
- content::BrowserContext::ForEachStoragePartition(
- m_profile.get(), base::BindRepeating([](std::string accept_language, content::StoragePartition *storage_partition) {
- storage_partition->GetNetworkContext()->SetAcceptLanguage(accept_language);
- }, http_accept_language));
+ m_profile->ForEachLoadedStoragePartition(
+ base::BindRepeating([](std::string accept_language, content::StoragePartition *storage_partition) {
+ storage_partition->GetNetworkContext()->SetAcceptLanguage(accept_language);
+ }, http_accept_language));
+}
+
+QVariant ProfileAdapter::clientHint(ClientHint clientHint) const
+{
+ blink::UserAgentMetadata &userAgentMetadata = m_profile->m_userAgentMetadata;
+ switch (clientHint) {
+ case ProfileAdapter::UAArchitecture:
+ return QVariant(toQString(userAgentMetadata.architecture));
+ case ProfileAdapter::UAPlatform:
+ return QVariant(toQString(userAgentMetadata.platform));
+ case ProfileAdapter::UAModel:
+ return QVariant(toQString(userAgentMetadata.model));
+ case ProfileAdapter::UAMobile:
+ return QVariant(userAgentMetadata.mobile);
+ case ProfileAdapter::UAFullVersion:
+ return QVariant(toQString(userAgentMetadata.full_version));
+ case ProfileAdapter::UAPlatformVersion:
+ return QVariant(toQString(userAgentMetadata.platform_version));
+ case ProfileAdapter::UABitness:
+ return QVariant(toQString(userAgentMetadata.bitness));
+ case ProfileAdapter::UAFullVersionList: {
+ QJsonObject ret;
+ for (const auto &value : userAgentMetadata.brand_full_version_list)
+ ret.insert(toQString(value.brand), QJsonValue(toQString(value.version)));
+ return QVariant(ret);
+ }
+ case ProfileAdapter::UAWOW64:
+ return QVariant(userAgentMetadata.wow64);
+ default:
+ return QVariant();
+ }
+}
+
+void ProfileAdapter::setClientHint(ClientHint clientHint, const QVariant &value)
+{
+ blink::UserAgentMetadata &userAgentMetadata = m_profile->m_userAgentMetadata;
+ switch (clientHint) {
+ case ProfileAdapter::UAArchitecture:
+ userAgentMetadata.architecture = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UAPlatform:
+ userAgentMetadata.platform = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UAModel:
+ userAgentMetadata.model = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UAMobile:
+ userAgentMetadata.mobile = value.toBool();
+ break;
+ case ProfileAdapter::UAFullVersion:
+ userAgentMetadata.full_version = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UAPlatformVersion:
+ userAgentMetadata.platform_version = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UABitness:
+ userAgentMetadata.bitness = value.toString().toStdString();
+ break;
+ case ProfileAdapter::UAFullVersionList: {
+ userAgentMetadata.brand_full_version_list.clear();
+ QJsonObject fullVersionList = value.toJsonObject();
+ for (const QString &key : fullVersionList.keys())
+ userAgentMetadata.brand_full_version_list.push_back({
+ key.toStdString(),
+ fullVersionList.value(key).toString().toStdString()
+ });
+ break;
+ }
+ case ProfileAdapter::UAWOW64:
+ userAgentMetadata.wow64 = value.toBool();
+ break;
+ default:
+ break;
+ }
+
+ std::vector<content::WebContentsImpl *> list = content::WebContentsImpl::GetAllWebContents();
+ for (content::WebContentsImpl *web_contents : list) {
+ if (web_contents->GetBrowserContext() == m_profile.data()) {
+ web_contents->GetMutableRendererPrefs()->user_agent_override.ua_metadata_override = userAgentMetadata;
+ web_contents->SyncRendererPrefs();
+ }
+ }
+}
+
+bool ProfileAdapter::clientHintsEnabled()
+{
+ return m_clientHintsEnabled;
+}
+
+void ProfileAdapter::setClientHintsEnabled(bool enabled)
+{
+ m_clientHintsEnabled = enabled;
+}
+
+void ProfileAdapter::resetClientHints()
+{
+ m_profile->m_userAgentMetadata = embedder_support::GetUserAgentMetadata();
+ std::vector<content::WebContentsImpl *> list = content::WebContentsImpl::GetAllWebContents();
+ for (content::WebContentsImpl *web_contents : list) {
+ if (web_contents->GetBrowserContext() == m_profile.data()) {
+ web_contents->GetMutableRendererPrefs()->user_agent_override.ua_metadata_override = m_profile->m_userAgentMetadata;
+ web_contents->SyncRendererPrefs();
+ }
+ }
}
void ProfileAdapter::clearHttpCache()
@@ -630,6 +737,16 @@ bool ProfileAdapter::isSpellCheckEnabled() const
#endif
}
+bool ProfileAdapter::pushServiceEnabled() const
+{
+ return m_pushServiceEnabled;
+}
+
+void ProfileAdapter::setPushServiceEnabled(bool enabled)
+{
+ m_pushServiceEnabled = enabled;
+}
+
void ProfileAdapter::addWebContentsAdapterClient(WebContentsAdapterClient *client)
{
m_webContentsAdapterClients.append(client);
@@ -640,41 +757,30 @@ void ProfileAdapter::removeWebContentsAdapterClient(WebContentsAdapterClient *cl
m_webContentsAdapterClients.removeAll(client);
}
+void ProfileAdapter::releaseAllWebContentsAdapterClients()
+{
+ while (!m_webContentsAdapterClients.isEmpty())
+ m_webContentsAdapterClients.first()->releaseProfile();
+}
+
void ProfileAdapter::resetVisitedLinksManager()
{
m_visitedLinksManager.reset(new VisitedLinksManagerQt(m_profile.data(), persistVisitedLinks()));
}
-void ProfileAdapter::setUseForGlobalCertificateVerification(bool enable)
+void ProfileAdapter::reinitializeHistoryService()
{
- if (m_usedForGlobalCertificateVerification == enable)
- return;
-
- static QPointer<ProfileAdapter> profileForglobalCertificateVerification;
-
- m_usedForGlobalCertificateVerification = enable;
- if (enable) {
- if (profileForglobalCertificateVerification) {
- profileForglobalCertificateVerification->m_usedForGlobalCertificateVerification = false;
- if (!m_profile->m_profileIOData->isClearHttpCacheInProgress())
- profileForglobalCertificateVerification->m_profile->m_profileIOData->resetNetworkContext();
- for (auto *client : qAsConst(profileForglobalCertificateVerification->m_clients))
- client->useForGlobalCertificateVerificationChanged();
- }
- profileForglobalCertificateVerification = this;
+ Q_ASSERT(!m_offTheRecord);
+ if (ensureDataPathExists()) {
+ favicon::FaviconService *faviconService =
+ FaviconServiceFactoryQt::GetForBrowserContext(m_profile.data());
+ history::HistoryService *historyService = static_cast<history::HistoryService *>(
+ HistoryServiceFactoryQt::GetInstance()->GetForBrowserContext(m_profile.data()));
+ Q_ASSERT(historyService);
+ faviconService->SetHistoryService(historyService);
} else {
- Q_ASSERT(profileForglobalCertificateVerification);
- Q_ASSERT(profileForglobalCertificateVerification == this);
- profileForglobalCertificateVerification = nullptr;
+ qWarning("Favicon database is not available for this profile.");
}
-
- if (!m_profile->m_profileIOData->isClearHttpCacheInProgress())
- m_profile->m_profileIOData->resetNetworkContext();
-}
-
-bool ProfileAdapter::isUsedForGlobalCertificateVerification() const
-{
- return m_usedForGlobalCertificateVerification;
}
QString ProfileAdapter::determineDownloadPath(const QString &downloadDirectory, const QString &suggestedFilename, const time_t &startTime)
@@ -683,7 +789,11 @@ QString ProfileAdapter::determineDownloadPath(const QString &downloadDirectory,
QString suggestedFilePath = suggestedFile.absoluteFilePath();
base::FilePath tmpFilePath(toFilePath(suggestedFilePath).NormalizePathSeparatorsTo('/'));
- int uniquifier = base::GetUniquePathNumber(tmpFilePath);
+ int uniquifier = 0;
+ {
+ base::ScopedAllowBlocking allowBlock;
+ uniquifier = base::GetUniquePathNumber(tmpFilePath);
+ }
if (uniquifier > 0)
suggestedFilePath = toQt(tmpFilePath.InsertBeforeExtensionASCII(base::StringPrintf(" (%d)", uniquifier)).AsUTF8Unsafe());
else if (uniquifier == -1) {
@@ -707,4 +817,101 @@ QWebEngineClientCertificateStore *ProfileAdapter::clientCertificateStore()
}
#endif
+static void callbackOnIconAvailableForPageURL(std::function<void (const QIcon &, const QUrl &, const QUrl &)> iconAvailableCallback,
+ const QUrl &pageUrl,
+ const favicon_base::FaviconRawBitmapResult &result)
+{
+ if (!result.is_valid()) {
+ iconAvailableCallback(QIcon(), toQt(result.icon_url), pageUrl);
+ return;
+ }
+ QPixmap pixmap(toQt(result.pixel_size));
+ pixmap.loadFromData(result.bitmap_data->data(), result.bitmap_data->size());
+ iconAvailableCallback(QIcon(pixmap), toQt(result.icon_url), pageUrl);
+}
+
+void ProfileAdapter::requestIconForPageURL(const QUrl &pageUrl,
+ int desiredSizeInPixel,
+ bool touchIconsEnabled,
+ std::function<void (const QIcon &, const QUrl &, const QUrl &)> iconAvailableCallback)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ favicon::FaviconService *service = FaviconServiceFactoryQt::GetForBrowserContext(m_profile.data());
+
+ if (!service->HistoryService()) {
+ callbackOnIconAvailableForPageURL(iconAvailableCallback, pageUrl,
+ favicon_base::FaviconRawBitmapResult());
+ return;
+ }
+
+ favicon_base::IconTypeSet types = { favicon_base::IconType::kFavicon };
+ if (touchIconsEnabled) {
+ types.insert(favicon_base::IconType::kTouchIcon);
+ types.insert(favicon_base::IconType::kTouchPrecomposedIcon);
+ types.insert(favicon_base::IconType::kWebManifestIcon);
+ }
+ service->GetRawFaviconForPageURL(
+ toGurl(pageUrl), types, desiredSizeInPixel, true /* fallback_to_host */,
+ base::BindOnce(&callbackOnIconAvailableForPageURL, iconAvailableCallback, pageUrl),
+ m_cancelableTaskTracker.get());
+}
+
+static void callbackOnIconAvailableForIconURL(std::function<void (const QIcon &, const QUrl &)> iconAvailableCallback,
+ ProfileAdapter *profileAdapter,
+ const QUrl &iconUrl, int iconType,
+ int desiredSizeInPixel,
+ bool touchIconsEnabled,
+ const favicon_base::FaviconRawBitmapResult &result)
+{
+ if (!result.is_valid()) {
+ // If touch icons are disabled there is no need to try further icon types.
+ if (!touchIconsEnabled) {
+ iconAvailableCallback(QIcon(), iconUrl);
+ return;
+ }
+ if (static_cast<favicon_base::IconType>(iconType) != favicon_base::IconType::kMax) {
+ //Q_ASSERT(profileAdapter->profile());
+ favicon::FaviconService *service = FaviconServiceFactoryQt::GetForBrowserContext(profileAdapter->profile());
+ service->GetRawFavicon(toGurl(iconUrl),
+ static_cast<favicon_base::IconType>(iconType + 1),
+ desiredSizeInPixel,
+ base::BindOnce(&callbackOnIconAvailableForIconURL, iconAvailableCallback,
+ profileAdapter, iconUrl, iconType + 1, desiredSizeInPixel,
+ touchIconsEnabled),
+ profileAdapter->cancelableTaskTracker());
+ return;
+ }
+ iconAvailableCallback(QIcon(), iconUrl);
+ return;
+ }
+ QPixmap pixmap(toQt(result.pixel_size));
+ pixmap.loadFromData(result.bitmap_data->data(), result.bitmap_data->size());
+ iconAvailableCallback(QIcon(pixmap), toQt(result.icon_url));
+}
+
+void ProfileAdapter::requestIconForIconURL(const QUrl &iconUrl,
+ int desiredSizeInPixel,
+ bool touchIconsEnabled,
+ std::function<void (const QIcon &, const QUrl &)> iconAvailableCallback)
+{
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ favicon::FaviconService *service = FaviconServiceFactoryQt::GetForBrowserContext(m_profile.data());
+
+ if (!service->HistoryService()) {
+ callbackOnIconAvailableForIconURL(iconAvailableCallback,
+ this,
+ iconUrl,
+ static_cast<int>(favicon_base::IconType::kMax), 0,
+ touchIconsEnabled,
+ favicon_base::FaviconRawBitmapResult());
+ return;
+ }
+ service->GetRawFavicon(
+ toGurl(iconUrl), favicon_base::IconType::kFavicon, desiredSizeInPixel,
+ base::BindOnce(&callbackOnIconAvailableForIconURL, iconAvailableCallback, this, iconUrl,
+ static_cast<int>(favicon_base::IconType::kFavicon), desiredSizeInPixel,
+ touchIconsEnabled),
+ m_cancelableTaskTracker.get());
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/profile_adapter.h b/src/core/profile_adapter.h
index efd56e50e..4be0ea51e 100644
--- a/src/core/profile_adapter.h
+++ b/src/core/profile_adapter.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,23 +15,27 @@
#ifndef PROFILE_ADAPTER_H
#define PROFILE_ADAPTER_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
-#include <QEnableSharedFromThis>
+#include <QHash>
#include <QList>
#include <QPointer>
#include <QScopedPointer>
+#include <QSharedPointer>
#include <QString>
-#include <QVector>
-#include "api/qwebengineclientcertificatestore.h"
-#include "api/qwebenginecookiestore.h"
-#include "api/qwebengineurlrequestinterceptor.h"
-#include "api/qwebengineurlschemehandler.h"
+#include <QtWebEngineCore/qwebengineclientcertificatestore.h>
+#include <QtWebEngineCore/qwebenginecookiestore.h>
+#include <QtWebEngineCore/qwebengineurlrequestinterceptor.h>
+#include <QtWebEngineCore/qwebengineurlschemehandler.h>
#include "net/qrc_url_scheme_handler.h"
QT_FORWARD_DECLARE_CLASS(QObject)
+namespace base {
+class CancelableTaskTracker;
+}
+
namespace QtWebEngineCore {
class UserNotificationController;
@@ -78,7 +46,7 @@ class UserResourceControllerHost;
class VisitedLinksManagerQt;
class WebContentsAdapterClient;
-class Q_WEBENGINECORE_PRIVATE_EXPORT ProfileAdapter : public QObject
+class Q_WEBENGINECORE_EXPORT ProfileAdapter : public QObject
{
public:
explicit ProfileAdapter(const QString &storagePrefix = QString());
@@ -100,12 +68,13 @@ public:
void addClient(ProfileAdapterClient *adapterClient);
void removeClient(ProfileAdapterClient *adapterClient);
- void cancelDownload(quint32 downloadId);
+ bool cancelDownload(quint32 downloadId);
void pauseDownload(quint32 downloadId);
void resumeDownload(quint32 downloadId);
void removeDownload(quint32 downloadId);
ProfileQt *profile();
+ bool ensureDataPathExists();
QString storageName() const { return m_name; }
void setStorageName(const QString &storageName);
@@ -132,8 +101,12 @@ public:
void setSpellCheckEnabled(bool enabled);
bool isSpellCheckEnabled() const;
+ bool pushServiceEnabled() const;
+ void setPushServiceEnabled(bool enabled);
+
void addWebContentsAdapterClient(WebContentsAdapterClient *client);
void removeWebContentsAdapterClient(WebContentsAdapterClient *client);
+ void releaseAllWebContentsAdapterClients();
// KEEP IN SYNC with API or add mapping layer
enum HttpCacheType {
@@ -160,8 +133,8 @@ public:
NotificationPermission = 2,
AudioCapturePermission = 3,
VideoCapturePermission = 4,
- ClipboardRead = 5,
- ClipboardWrite = 6,
+ ClipboardReadWrite = 5,
+ LocalFontsPermission = 6,
};
enum PermissionState {
@@ -170,6 +143,18 @@ public:
DeniedPermission = 2
};
+ enum ClientHint : uchar {
+ UAArchitecture,
+ UAPlatform,
+ UAModel,
+ UAMobile,
+ UAFullVersion,
+ UAPlatformVersion,
+ UABitness,
+ UAFullVersionList,
+ UAWOW64,
+ };
+
HttpCacheType httpCacheType() const;
void setHttpCacheType(ProfileAdapter::HttpCacheType);
@@ -200,10 +185,13 @@ public:
QString httpAcceptLanguage() const;
void setHttpAcceptLanguage(const QString &httpAcceptLanguage);
- void clearHttpCache();
+ QVariant clientHint(ClientHint clientHint) const;
+ void setClientHint(ClientHint clientHint, const QVariant &value);
+ bool clientHintsEnabled();
+ void setClientHintsEnabled(bool enabled);
+ void resetClientHints();
- void setUseForGlobalCertificateVerification(bool enable = true);
- bool isUsedForGlobalCertificateVerification() const;
+ void clearHttpCache();
#if QT_CONFIG(ssl)
QWebEngineClientCertificateStore *clientCertificateStore();
@@ -216,14 +204,20 @@ public:
QString determineDownloadPath(const QString &downloadDirectory, const QString &suggestedFilename, const time_t &startTime);
+ void requestIconForPageURL(const QUrl &pageUrl, int desiredSizeInPixel, bool touchIconsEnabled,
+ std::function<void (const QIcon &, const QUrl &, const QUrl &)> iconAvailableCallback);
+ void requestIconForIconURL(const QUrl &iconUrl, int desiredSizeInPixel, bool touchIconsEnabled,
+ std::function<void (const QIcon &, const QUrl &)> iconAvailableCallback);
+ base::CancelableTaskTracker *cancelableTaskTracker() { return m_cancelableTaskTracker.get(); }
+
private:
void updateCustomUrlSchemeHandlers();
void resetVisitedLinksManager();
bool persistVisitedLinks() const;
+ void reinitializeHistoryService();
QString m_name;
bool m_offTheRecord;
- bool m_usedForGlobalCertificateVerification = false;
QScopedPointer<ProfileQt> m_profile;
QScopedPointer<VisitedLinksManagerQt> m_visitedLinksManager;
QScopedPointer<DownloadManagerDelegateQt> m_downloadManagerDelegate;
@@ -245,11 +239,14 @@ private:
QHash<QByteArray, QPointer<QWebEngineUrlSchemeHandler>> m_customUrlSchemeHandlers;
QHash<QByteArray, QWeakPointer<UserNotificationController>> m_ephemeralNotifications;
QHash<QByteArray, QSharedPointer<UserNotificationController>> m_persistentNotifications;
+ bool m_clientHintsEnabled;
QList<ProfileAdapterClient*> m_clients;
- QVector<WebContentsAdapterClient *> m_webContentsAdapterClients;
+ QList<WebContentsAdapterClient *> m_webContentsAdapterClients;
+ bool m_pushServiceEnabled;
int m_httpCacheMaxSize;
QrcUrlSchemeHandler m_qrcHandler;
+ std::unique_ptr<base::CancelableTaskTracker> m_cancelableTaskTracker;
Q_DISABLE_COPY(ProfileAdapter)
};
diff --git a/src/core/profile_adapter_client.cpp b/src/core/profile_adapter_client.cpp
index 9aa084da9..b6a16c21a 100644
--- a/src/core/profile_adapter_client.cpp
+++ b/src/core/profile_adapter_client.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "profile_adapter_client.h"
#include "components/download/public/common/download_item.h"
diff --git a/src/core/profile_adapter_client.h b/src/core/profile_adapter_client.h
index 394f92270..06ac0de8b 100644
--- a/src/core/profile_adapter_client.h
+++ b/src/core/profile_adapter_client.h
@@ -1,41 +1,5 @@
- /****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,7 +15,7 @@
#ifndef PROFILE_ADAPTER_CLIENT_H
#define PROFILE_ADAPTER_CLIENT_H
-#include "qtwebenginecoreglobal_p.h"
+#include "api/qtwebenginecoreglobal_p.h"
#include <QSharedPointer>
#include <QString>
#include <QUrl>
@@ -60,9 +24,10 @@
namespace QtWebEngineCore {
class WebContentsAdapterClient;
+class WebEngineSettings;
class UserNotificationController;
-class Q_WEBENGINECORE_PRIVATE_EXPORT ProfileAdapterClient
+class Q_WEBENGINECORE_EXPORT ProfileAdapterClient
{
public:
// Keep in sync with content::DownloadItem::DownloadState
@@ -85,13 +50,6 @@ public:
MimeHtmlSaveFormat
};
- enum DownloadType {
- Attachment = 0,
- DownloadAttribute,
- UserRequested,
- SavePage
- };
-
// Keep in sync with content::DownloadInterruptReason
enum DownloadInterruptReason {
NoReason = 0,
@@ -136,7 +94,7 @@ public:
bool accepted;
bool paused;
bool done;
- int downloadType;
+ bool isSavePageDownload;
int downloadInterruptReason;
WebContentsAdapterClient *page;
QString suggestedFileName;
@@ -147,11 +105,13 @@ public:
virtual void downloadRequested(DownloadItemInfo &info) = 0;
virtual void downloadUpdated(const DownloadItemInfo &info) = 0;
- virtual void useForGlobalCertificateVerificationChanged() {}
virtual void showNotification(QSharedPointer<UserNotificationController> &) { }
virtual void addWebContentsAdapterClient(WebContentsAdapterClient *adapter) = 0;
virtual void removeWebContentsAdapterClient(WebContentsAdapterClient *adapter) = 0;
+ virtual WebEngineSettings *coreSettings() const = 0;
+ virtual void clearHttpCacheCompleted() = 0;
+
static QString downloadInterruptReasonToString(DownloadInterruptReason reason);
};
diff --git a/src/core/profile_io_data_qt.cpp b/src/core/profile_io_data_qt.cpp
index ecebbdaa7..859aff8d4 100644
--- a/src/core/profile_io_data_qt.cpp
+++ b/src/core/profile_io_data_qt.cpp
@@ -1,65 +1,24 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "profile_io_data_qt.h"
-#include "base/task/post_task.h"
#include "content/browser/storage_partition_impl.h"
-#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
+#include "content/public/browser/resource_context.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
-#include "content/public/common/content_features.h"
-#include "net/ssl/ssl_config_service_defaults.h"
+#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/public/cpp/cors/origin_access_list.h"
-#include "net/client_cert_override.h"
+#include "net/client_cert_qt.h"
#include "net/client_cert_store_data.h"
#include "net/cookie_monster_delegate_qt.h"
#include "net/system_network_context_manager.h"
+#include "profile_adapter_client.h"
#include "profile_qt.h"
-#include "resource_context_qt.h"
#include "type_conversion.h"
-#include <QDebug>
-#include <mutex>
-
namespace QtWebEngineCore {
ProfileIODataQt::ProfileIODataQt(ProfileQt *profile)
@@ -97,6 +56,12 @@ void ProfileIODataQt::shutdownOnUIThread()
if (m_cookieDelegate)
m_cookieDelegate->unsetMojoCookieManager();
m_proxyConfigMonitor.reset();
+
+ if (m_clearHttpCacheState == Removing) {
+ m_clearHttpCacheState = Completed;
+ removeBrowsingDataRemoverObserver();
+ }
+
bool posted = content::BrowserThread::DeleteSoon(content::BrowserThread::IO, FROM_HERE, this);
if (!posted) {
qWarning() << "Could not delete ProfileIODataQt on io thread !";
@@ -126,7 +91,7 @@ void ProfileIODataQt::initializeOnUIThread()
{
m_profileAdapter = m_profile->profileAdapter();
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- m_resourceContext.reset(new ResourceContextQt(this));
+ m_resourceContext.reset(new content::ResourceContext());
m_cookieDelegate = new CookieMonsterDelegateQt();
m_cookieDelegate->setClient(m_profile->profileAdapter()->cookieStore());
m_proxyConfigMonitor.reset(new ProxyConfigMonitor(m_profile->GetPrefs()));
@@ -135,10 +100,10 @@ void ProfileIODataQt::initializeOnUIThread()
void ProfileIODataQt::clearHttpCache()
{
Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
- if (!m_clearHttpCacheInProgress) {
- m_clearHttpCacheInProgress = true;
+ if (m_clearHttpCacheState == Completed) {
+ m_clearHttpCacheState = Removing;
content::BrowsingDataRemover *remover =
- content::BrowserContext::GetBrowsingDataRemover(m_profileAdapter->profile());
+ m_profileAdapter->profile()->GetBrowsingDataRemover();
remover->AddObserver(&m_removerObserver);
remover->RemoveAndReply(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
@@ -151,7 +116,7 @@ void ProfileIODataQt::clearHttpCache()
void ProfileIODataQt::removeBrowsingDataRemoverObserver()
{
content::BrowsingDataRemover *remover =
- content::BrowserContext::GetBrowsingDataRemover(m_profileAdapter->profile());
+ m_profileAdapter->profile()->GetBrowsingDataRemover();
remover->RemoveObserver(&m_removerObserver);
}
@@ -160,11 +125,11 @@ BrowsingDataRemoverObserverQt::BrowsingDataRemoverObserverQt(ProfileIODataQt *pr
{
}
-void BrowsingDataRemoverObserverQt::OnBrowsingDataRemoverDone()
+void BrowsingDataRemoverObserverQt::OnBrowsingDataRemoverDone(uint64_t)
{
- Q_ASSERT(m_profileIOData->m_clearHttpCacheInProgress);
+ Q_ASSERT(m_profileIOData->m_clearHttpCacheState == ProfileIODataQt::Removing);
m_profileIOData->removeBrowsingDataRemoverObserver();
- m_profileIOData->m_clearHttpCacheInProgress = false;
+ m_profileIOData->m_clearHttpCacheState = ProfileIODataQt::Resetting;
m_profileIOData->resetNetworkContext();
}
@@ -177,20 +142,52 @@ void ProfileIODataQt::setFullConfiguration()
m_httpCacheType = m_profileAdapter->httpCacheType();
m_httpCachePath = m_profileAdapter->httpCachePath();
m_httpCacheMaxSize = m_profileAdapter->httpCacheMaxSize();
- m_useForGlobalCertificateVerification = m_profileAdapter->isUsedForGlobalCertificateVerification();
m_dataPath = m_profileAdapter->dataPath();
+ m_storageName = m_profileAdapter->storageName();
+ m_inMemoryOnly = m_profileAdapter->isOffTheRecord() || m_storageName.isEmpty();
}
void ProfileIODataQt::resetNetworkContext()
{
Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
+ Q_ASSERT(m_clearHttpCacheState != Removing);
setFullConfiguration();
- content::BrowserContext::ForEachStoragePartition(
- m_profile, base::BindRepeating([](content::StoragePartition *storage) {
+ m_profile->ForEachLoadedStoragePartition(
+ base::BindRepeating([](ProfileIODataQt *profileData,
+ content::StoragePartition *storage) {
+ storage->SetNetworkContextCreatedObserver(profileData);
+
auto storage_impl = static_cast<content::StoragePartitionImpl *>(storage);
storage_impl->ResetURLLoaderFactories();
storage_impl->ResetNetworkContext();
- }));
+ }, this));
+}
+
+void ProfileIODataQt::OnNetworkContextCreated(content::StoragePartition *storage)
+{
+ Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
+
+ storage->SetNetworkContextCreatedObserver(nullptr);
+
+ if (m_clearHttpCacheState != Resetting)
+ return;
+
+ bool pendingReset = false;
+ m_profile->ForEachLoadedStoragePartition(
+ base::BindRepeating([](bool *pendingReset,
+ ProfileIODataQt *profileData,
+ content::StoragePartition *storage) {
+ if (storage->GetNetworkContextCreatedObserver() == profileData)
+ *pendingReset = true;
+ }, &pendingReset, this));
+
+ if (pendingReset)
+ return;
+
+ m_clearHttpCacheState = Completed;
+
+ for (ProfileAdapterClient *client : m_profileAdapter->clients())
+ client->clearHttpCacheCompleted();
}
bool ProfileIODataQt::canGetCookies(const QUrl &firstPartyUrl, const QUrl &url) const
@@ -208,20 +205,21 @@ ClientCertificateStoreData *ProfileIODataQt::clientCertificateStoreData()
std::unique_ptr<net::ClientCertStore> ProfileIODataQt::CreateClientCertStore()
{
#if QT_CONFIG(ssl)
- return std::unique_ptr<net::ClientCertStore>(new ClientCertOverrideStore(m_clientCertificateStoreData));
+ return std::unique_ptr<net::ClientCertStore>(new ClientCertStoreQt(m_clientCertificateStoreData));
#else
- return nullptr;
+ return std::unique_ptr<net::ClientCertStore>(new ClientCertStoreQt(nullptr));
#endif
}
-network::mojom::NetworkContextParamsPtr ProfileIODataQt::CreateNetworkContextParams()
+void ProfileIODataQt::ConfigureNetworkContextParams(bool in_memory,
+ const base::FilePath &relative_partition_path,
+ network::mojom::NetworkContextParams *network_context_params,
+ cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params)
{
setFullConfiguration();
- network::mojom::NetworkContextParamsPtr network_context_params =
- SystemNetworkContextManager::GetInstance()->CreateDefaultNetworkContextParams();
+ SystemNetworkContextManager::GetInstance()->ConfigureDefaultNetworkContextParams(network_context_params, cert_verifier_creation_params);
- network_context_params->context_name = m_profile->profileAdapter()->storageName().toStdString();
network_context_params->user_agent = m_httpUserAgent.toStdString();
network_context_params->accept_language = m_httpAcceptLanguage.toStdString();
@@ -231,38 +229,31 @@ network::mojom::NetworkContextParamsPtr ProfileIODataQt::CreateNetworkContextPar
network_context_params->http_cache_enabled = m_httpCacheType != ProfileAdapter::NoCache;
network_context_params->http_cache_max_size = m_httpCacheMaxSize;
- if (m_httpCacheType == ProfileAdapter::DiskHttpCache && !m_httpCachePath.isEmpty())
- network_context_params->http_cache_path = toFilePath(m_httpCachePath);
- if (m_persistentCookiesPolicy != ProfileAdapter::NoPersistentCookies && !m_dataPath.isEmpty()) {
- base::FilePath cookie_path = toFilePath(m_dataPath);
- cookie_path = cookie_path.AppendASCII("Cookies");
- network_context_params->cookie_path = cookie_path;
-
- network_context_params->restore_old_session_cookies = m_persistentCookiesPolicy == ProfileAdapter::ForcePersistentCookies;
- network_context_params->persist_session_cookies = m_persistentCookiesPolicy != ProfileAdapter::NoPersistentCookies;
- }
- if (!m_dataPath.isEmpty()) {
- network_context_params->http_server_properties_path = toFilePath(m_dataPath).AppendASCII("Network Persistent State");
- network_context_params->transport_security_persister_path = toFilePath(m_dataPath);
+ network_context_params->persist_session_cookies = false;
+ if (!m_inMemoryOnly && !in_memory) {
+ network_context_params->file_paths =
+ network::mojom::NetworkContextFilePaths::New();
+ network_context_params->file_paths->data_directory = toFilePath(m_dataPath);
+ network_context_params->file_paths->http_server_properties_file_name = base::FilePath::FromASCII("Network Persistent State");
+ network_context_params->file_paths->transport_security_persister_file_name = base::FilePath::FromASCII("TransportSecurity");
+ network_context_params->file_paths->trust_token_database_name = base::FilePath::FromASCII("Trust Tokens");
+ if (m_httpCacheType == ProfileAdapter::DiskHttpCache && !m_httpCachePath.isEmpty())
+ network_context_params->file_paths->http_cache_directory = toFilePath(m_httpCachePath);
+ if (m_persistentCookiesPolicy != ProfileAdapter::NoPersistentCookies) {
+ network_context_params->file_paths->cookie_database_name = base::FilePath::FromASCII("Cookies");
+ network_context_params->restore_old_session_cookies = m_persistentCookiesPolicy == ProfileAdapter::ForcePersistentCookies;
+ network_context_params->persist_session_cookies = m_persistentCookiesPolicy != ProfileAdapter::NoPersistentCookies;
+ }
}
-#if !BUILDFLAG(DISABLE_FTP_SUPPORT)
- network_context_params->enable_ftp_url_support = true;
-#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
-
-// network_context_params->enable_certificate_reporting = true;
-// network_context_params->enable_expect_ct_reporting = true;
network_context_params->enforce_chrome_ct_policy = false;
- network_context_params->primary_network_context = m_useForGlobalCertificateVerification;
// Should be initialized with existing per-profile CORS access lists.
network_context_params->cors_origin_access_list =
m_profile->GetSharedCorsOriginAccessList()->GetOriginAccessList().CreateCorsOriginAccessPatternsList();
- m_proxyConfigMonitor->AddToNetworkContextParams(network_context_params.get());
-
- return network_context_params;
+ m_proxyConfigMonitor->AddToNetworkContextParams(network_context_params);
}
// static
@@ -272,11 +263,4 @@ ProfileIODataQt *ProfileIODataQt::FromBrowserContext(content::BrowserContext *br
return static_cast<ProfileQt *>(browser_context)->m_profileIOData.get();
}
-// static
-ProfileIODataQt *ProfileIODataQt::FromResourceContext(content::ResourceContext *resource_context)
-{
- Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
- return static_cast<ResourceContextQt *>(resource_context)->m_io_data;
-}
-
} // namespace QtWebEngineCore
diff --git a/src/core/profile_io_data_qt.h b/src/core/profile_io_data_qt.h
index b0567dead..0d032e4dc 100644
--- a/src/core/profile_io_data_qt.h
+++ b/src/core/profile_io_data_qt.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PROFILE_IO_DATA_QT_H
#define PROFILE_IO_DATA_QT_H
#include "content/public/browser/browsing_data_remover.h"
-#include "chrome/browser/profiles/profile.h"
+#include "content/public/browser/storage_partition.h"
#include "extensions/buildflags/buildflags.h"
#include "net/proxy_config_monitor.h"
@@ -49,20 +13,29 @@
#include <QtCore/QString>
#include <QtCore/QPointer>
-#include <QtCore/QMutex>
+#include <QtCore/QRecursiveMutex>
-namespace net {
-class ClientCertStore;
-class URLRequestContext;
+namespace cert_verifier {
+namespace mojom {
+class CertVerifierCreationParams;
+}}
+
+namespace content {
+class ResourceContext;
}
namespace extensions {
class ExtensionSystemQt;
}
+namespace net {
+class ClientCertStore;
+}
+
namespace QtWebEngineCore {
struct ClientCertificateStoreData;
+class CookieMonsterDelegateQt;
class ProfileIODataQt;
class ProfileQt;
@@ -70,7 +43,7 @@ class BrowsingDataRemoverObserverQt : public content::BrowsingDataRemover::Obser
public:
BrowsingDataRemoverObserverQt(ProfileIODataQt *profileIOData);
- void OnBrowsingDataRemoverDone() override;
+ void OnBrowsingDataRemoverDone(uint64_t) override;
private:
ProfileIODataQt *m_profileIOData;
@@ -80,9 +53,15 @@ private:
// we still use shared memebers and use mutex which breaks
// idea for this object, but this is wip.
-class ProfileIODataQt {
+class ProfileIODataQt : public content::StoragePartition::NetworkContextCreatedObserver {
public:
+ enum ClearHttpCacheState {
+ Completed = 0,
+ Removing,
+ Resetting
+ };
+
ProfileIODataQt(ProfileQt *profile); // runs on ui thread
virtual ~ProfileIODataQt();
@@ -97,25 +76,30 @@ public:
bool canGetCookies(const QUrl &firstPartyUrl, const QUrl &url) const;
- // Used in NetworkDelegateQt::OnBeforeURLRequest.
void setFullConfiguration(); // runs on ui thread
void resetNetworkContext(); // runs on ui thread
+
void clearHttpCache(); // runs on ui thread
- bool isClearHttpCacheInProgress() { return m_clearHttpCacheInProgress; }
+ bool isClearHttpCacheInProgress() const { return m_clearHttpCacheState != Completed; }
- network::mojom::NetworkContextParamsPtr CreateNetworkContextParams();
+ void ConfigureNetworkContextParams(bool in_memory,
+ const base::FilePath &relative_partition_path,
+ network::mojom::NetworkContextParams *network_context_params,
+ cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params);
#if QT_CONFIG(ssl)
ClientCertificateStoreData *clientCertificateStoreData();
#endif
std::unique_ptr<net::ClientCertStore> CreateClientCertStore();
static ProfileIODataQt *FromBrowserContext(content::BrowserContext *browser_context);
- static ProfileIODataQt *FromResourceContext(content::ResourceContext *resource_context);
base::WeakPtr<ProfileIODataQt> getWeakPtrOnIOThread();
CookieMonsterDelegateQt *cookieDelegate() const { return m_cookieDelegate.get(); }
+ // content::StoragePartition::NetworkContextCreatedObserver overrides:
+ void OnNetworkContextCreated(content::StoragePartition *storage) override; // runs on ui thread
+
private:
void removeBrowsingDataRemoverObserver();
@@ -133,19 +117,14 @@ private:
QString m_httpUserAgent;
ProfileAdapter::HttpCacheType m_httpCacheType;
QString m_httpCachePath;
-#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
- QMutex m_mutex{QMutex::Recursive};
- using QRecursiveMutex = QMutex;
-#else
+ QString m_storageName;
+ bool m_inMemoryOnly;
QRecursiveMutex m_mutex;
-#endif
int m_httpCacheMaxSize = 0;
- bool m_useForGlobalCertificateVerification = false;
BrowsingDataRemoverObserverQt m_removerObserver;
QString m_dataPath;
- bool m_clearHttpCacheInProgress = false;
+ ClearHttpCacheState m_clearHttpCacheState = Completed;
base::WeakPtrFactory<ProfileIODataQt> m_weakPtrFactory; // this should be always the last member
- DISALLOW_COPY_AND_ASSIGN(ProfileIODataQt);
friend class BrowsingDataRemoverObserverQt;
};
diff --git a/src/core/profile_qt.cpp b/src/core/profile_qt.cpp
index 748104312..293e8d557 100644
--- a/src/core/profile_qt.cpp
+++ b/src/core/profile_qt.cpp
@@ -1,84 +1,40 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "profile_qt.h"
#include "profile_adapter.h"
#include "browsing_data_remover_delegate_qt.h"
+#include "client_hints.h"
#include "download_manager_delegate_qt.h"
+#include "file_system_access/file_system_access_permission_context_factory_qt.h"
#include "net/ssl_host_state_delegate_qt.h"
#include "permission_manager_qt.h"
+#include "profile_io_data_qt.h"
#include "platform_notification_service_qt.h"
#include "qtwebenginecoreglobal_p.h"
#include "type_conversion.h"
#include "web_engine_library_info.h"
#include "web_engine_context.h"
-#include "base/barrier_closure.h"
-#include "base/time/time.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/cors_origin_pattern_setter.h"
-#include "content/public/browser/shared_cors_origin_access_list.h"
-#include "content/public/browser/storage_partition.h"
-
#include "base/base_paths.h"
+#include "base/files/file_util.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
-#include "components/prefs/pref_member.h"
#include "components/prefs/pref_service.h"
-#include "components/prefs/in_memory_pref_store.h"
-#include "components/prefs/json_pref_store.h"
-#include "components/prefs/pref_service.h"
-#include "components/prefs/pref_service_factory.h"
-#include "components/prefs/pref_registry_simple.h"
#include "components/user_prefs/user_prefs.h"
-#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
-#include "chrome/common/pref_names.h"
-#if QT_CONFIG(webengine_spellchecker)
-#include "chrome/browser/spellchecker/spellcheck_service.h"
-#include "components/spellcheck/browser/pref_names.h"
-#endif
+#include "components/profile_metrics/browser_profile_type.h"
+#include "content/public/browser/browser_thread.h"
+#include "chrome/browser/push_messaging/push_messaging_app_identifier.h"
+#include "chrome/browser/push_messaging/push_messaging_service_factory.h"
+#include "chrome/browser/push_messaging/push_messaging_service_impl.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
+#include "base/command_line.h"
#include "components/guest_view/browser/guest_view_manager.h"
-#include "extensions/browser/pref_names.h"
-#include "extensions/browser/process_manager.h"
-#include "extensions/common/constants.h"
+#include "extensions/browser/extension_pref_value_map_factory.h"
+#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_prefs_factory.h"
+#include "extensions/browser/extensions_browser_client.h"
#include "extensions/extension_system_qt.h"
#endif
@@ -86,13 +42,17 @@
namespace QtWebEngineCore {
ProfileQt::ProfileQt(ProfileAdapter *profileAdapter)
- : m_sharedCorsOriginAccessList(content::SharedCorsOriginAccessList::Create())
- , m_profileIOData(new ProfileIODataQt(this))
+ : m_profileIOData(new ProfileIODataQt(this))
, m_profileAdapter(profileAdapter)
+ , m_userAgentMetadata(embedder_support::GetUserAgentMetadata())
#if BUILDFLAG(ENABLE_EXTENSIONS)
, m_extensionSystem(nullptr)
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
{
+ profile_metrics::SetBrowserProfileType(this, IsOffTheRecord()
+ ? profile_metrics::BrowserProfileType::kIncognito
+ : profile_metrics::BrowserProfileType::kRegular);
+
setupPrefService();
// Mark the context as live. This prevents the use-after-free DCHECK in
@@ -111,14 +71,21 @@ ProfileQt::~ProfileQt()
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
m_prefServiceAdapter.commit();
- content::BrowserContext::NotifyWillBeDestroyed(this);
BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(this);
+ // Remembering push subscriptions and not persisting notification permissions would
+ // confuse most of web applications.
+ PushMessagingAppIdentifier::DeleteAllFromPrefs(this);
ShutdownStoragePartitions();
m_profileIOData->shutdownOnUIThread();
//Should be deleted by IO Thread
m_profileIOData.release();
}
+void ProfileQt::DoFinalInit()
+{
+ PushMessagingServiceImpl::InitializeForProfile(this);
+}
+
PrefService* ProfileQt::GetPrefs()
{
return m_prefServiceAdapter.prefService();
@@ -129,6 +96,11 @@ const PrefService* ProfileQt::GetPrefs() const
return m_prefServiceAdapter.prefService();
}
+bool ProfileQt::IsNewProfile() const
+{
+ return GetPrefs()->GetInitializationStatus() == PrefService::INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE;
+}
+
base::FilePath ProfileQt::GetPath()
{
return toFilePath(m_profileAdapter->dataPath());
@@ -171,7 +143,10 @@ storage::SpecialStoragePolicy *ProfileQt::GetSpecialStoragePolicy()
content::PushMessagingService *ProfileQt::GetPushMessagingService()
{
- return nullptr;
+ if (m_profileAdapter->pushServiceEnabled())
+ return PushMessagingServiceFactory::GetForProfile(this);
+ else
+ return nullptr;
}
content::SSLHostStateDelegate* ProfileQt::GetSSLHostStateDelegate()
@@ -212,7 +187,7 @@ content::PermissionControllerDelegate *ProfileQt::GetPermissionControllerDelegat
content::ClientHintsControllerDelegate *ProfileQt::GetClientHintsControllerDelegate()
{
- return nullptr;
+ return ClientHintsFactory::GetForBrowserContext(this);
}
content::StorageNotificationService *ProfileQt::GetStorageNotificationService()
@@ -220,32 +195,9 @@ content::StorageNotificationService *ProfileQt::GetStorageNotificationService()
return nullptr;
}
-void ProfileQt::SetCorsOriginAccessListForOrigin(const url::Origin &source_origin,
- std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,
- std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,
- base::OnceClosure closure)
+content::ReduceAcceptLanguageControllerDelegate *ProfileQt::GetReduceAcceptLanguageControllerDelegate()
{
- auto barrier_closure = base::BarrierClosure(2, std::move(closure));
-
- // Keep profile storage partitions' NetworkContexts synchronized.
- auto profile_setter = base::MakeRefCounted<content::CorsOriginPatternSetter>(
- source_origin,
- content::CorsOriginPatternSetter::ClonePatterns(allow_patterns),
- content::CorsOriginPatternSetter::ClonePatterns(block_patterns),
- barrier_closure);
- ForEachStoragePartition(this,
- base::BindRepeating(&content::CorsOriginPatternSetter::SetLists,
- base::RetainedRef(profile_setter.get())));
-
- m_sharedCorsOriginAccessList->SetForOrigin(source_origin,
- std::move(allow_patterns),
- std::move(block_patterns),
- barrier_closure);
-}
-
-content::SharedCorsOriginAccessList *ProfileQt::GetSharedCorsOriginAccessList()
-{
- return m_sharedCorsOriginAccessList.get();
+ return nullptr;
}
#if QT_CONFIG(webengine_spellchecker)
@@ -269,16 +221,43 @@ std::string ProfileQt::GetMediaDeviceIDSalt()
return m_prefServiceAdapter.mediaDeviceIdSalt();
}
+content::FileSystemAccessPermissionContext *ProfileQt::GetFileSystemAccessPermissionContext()
+{
+ return FileSystemAccessPermissionContextFactoryQt::GetForProfile(this);
+}
+
void ProfileQt::setupPrefService()
{
+ const bool recreation = m_prefServiceAdapter.prefService() != nullptr;
+ profile_metrics::SetBrowserProfileType(this,
+ IsOffTheRecord()
+ ? profile_metrics::BrowserProfileType::kIncognito
+ : profile_metrics::BrowserProfileType::kRegular);
+
// Remove previous handler before we set a new one or we will assert
// TODO: Remove in Qt6
- if (m_prefServiceAdapter.prefService() != nullptr) {
+ if (recreation) {
user_prefs::UserPrefs::Remove(this);
m_prefServiceAdapter.commit();
}
m_prefServiceAdapter.setup(*m_profileAdapter);
user_prefs::UserPrefs::Set(this, m_prefServiceAdapter.prefService());
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ if (recreation) {
+ // Recreate ExtensionPrefs to update its pointer to the new PrefService
+ extensions::ExtensionsBrowserClient *client = extensions::ExtensionsBrowserClient::Get();
+ std::vector<extensions::EarlyExtensionPrefsObserver *> prefsObservers;
+ client->GetEarlyExtensionPrefsObservers(this, &prefsObservers);
+ auto extensionPrefs = extensions::ExtensionPrefs::Create(
+ this, client->GetPrefServiceForContext(this),
+ this->GetPath().AppendASCII(extensions::kInstallDirectoryName),
+ ExtensionPrefValueMapFactory::GetForBrowserContext(this),
+ client->AreExtensionsDisabled(*base::CommandLine::ForCurrentProcess(), this),
+ prefsObservers);
+ extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(this, std::move(extensionPrefs));
+ }
+#endif
}
PrefServiceAdapter &ProfileQt::prefServiceAdapter()
@@ -291,8 +270,12 @@ const PrefServiceAdapter &ProfileQt::prefServiceAdapter() const
return m_prefServiceAdapter;
}
+const blink::UserAgentMetadata &ProfileQt::userAgentMetadata()
+{
+ return m_userAgentMetadata;
+}
-content::PlatformNotificationService *ProfileQt::platformNotificationService()
+content::PlatformNotificationService *ProfileQt::GetPlatformNotificationService()
{
if (!m_platformNotificationService)
m_platformNotificationService = std::make_unique<PlatformNotificationServiceQt>(this);
diff --git a/src/core/profile_qt.h b/src/core/profile_qt.h
index 59f5a8c21..b5cd08db1 100644
--- a/src/core/profile_qt.h
+++ b/src/core/profile_qt.h
@@ -1,59 +1,20 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PROFILE_QT_H
#define PROFILE_QT_H
#include "chrome/browser/profiles/profile.h"
-#include "content/public/browser/content_browser_client.h"
-#include "content/public/browser/resource_context.h"
+#include "components/embedder_support/user_agent_utils.h"
#include "extensions/buildflags/buildflags.h"
#include "pref_service_adapter.h"
-#include "profile_io_data_qt.h"
-#include <QtGlobal>
-QT_BEGIN_NAMESPACE
-class QStringList;
-QT_END_NAMESPACE
-class InMemoryPrefStore;
class PrefService;
+namespace content {
+class ResourceContext;
+}
+
namespace extensions {
class ExtensionSystemQt;
}
@@ -61,8 +22,9 @@ class ExtensionSystemQt;
namespace QtWebEngineCore {
class BrowsingDataRemoverDelegateQt;
-class ProfileAdapter;
class PermissionManagerQt;
+class ProfileAdapter;
+class ProfileIODataQt;
class SSLHostStateDelegateQt;
class ProfileQt : public Profile
@@ -92,21 +54,18 @@ public:
content::BrowsingDataRemoverDelegate *GetBrowsingDataRemoverDelegate() override;
content::ClientHintsControllerDelegate *GetClientHintsControllerDelegate() override;
content::StorageNotificationService *GetStorageNotificationService() override;
- void SetCorsOriginAccessListForOrigin(const url::Origin &source_origin,
- std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,
- std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,
- base::OnceClosure closure) override;
- content::SharedCorsOriginAccessList *GetSharedCorsOriginAccessList() override;
- std::string GetMediaDeviceIDSalt() override;
+ content::PlatformNotificationService *GetPlatformNotificationService() override;
+ content::FileSystemAccessPermissionContext *GetFileSystemAccessPermissionContext() override;
+ content::ReduceAcceptLanguageControllerDelegate *GetReduceAcceptLanguageControllerDelegate() override;
// Profile implementation:
PrefService *GetPrefs() override;
const PrefService *GetPrefs() const override;
+ bool IsNewProfile() const override;
- void Initialize();
+ void DoFinalInit();
ProfileAdapter *profileAdapter() { return m_profileAdapter; }
-
- content::PlatformNotificationService *platformNotificationService();
+ std::string GetMediaDeviceIDSalt();
#if QT_CONFIG(webengine_spellchecker)
void FailedToLoadDictionary(const std::string &language) override;
@@ -120,29 +79,26 @@ public:
void setupPrefService();
PrefServiceAdapter &prefServiceAdapter();
-
const PrefServiceAdapter &prefServiceAdapter() const;
+ const blink::UserAgentMetadata &userAgentMetadata();
+
private:
- friend class ContentBrowserClientQt;
- friend class ProfileIODataQt;
- friend class WebContentsAdapter;
std::unique_ptr<BrowsingDataRemoverDelegateQt> m_removerDelegate;
std::unique_ptr<PermissionManagerQt> m_permissionManager;
std::unique_ptr<SSLHostStateDelegateQt> m_sslHostStateDelegate;
- scoped_refptr<content::SharedCorsOriginAccessList> m_sharedCorsOriginAccessList;
std::unique_ptr<ProfileIODataQt> m_profileIOData;
std::unique_ptr<content::PlatformNotificationService> m_platformNotificationService;
ProfileAdapter *m_profileAdapter;
PrefServiceAdapter m_prefServiceAdapter;
+ blink::UserAgentMetadata m_userAgentMetadata;
- friend class ProfileAdapter;
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::ExtensionSystemQt *m_extensionSystem;
#endif //ENABLE_EXTENSIONS
- friend class BrowserContextAdapter;
- DISALLOW_COPY_AND_ASSIGN(ProfileQt);
+ friend class ProfileAdapter;
+ friend class ProfileIODataQt;
};
} // namespace QtWebEngineCore
diff --git a/src/core/qtwebengine.gni b/src/core/qtwebengine.gni
deleted file mode 100644
index a5628bb88..000000000
--- a/src/core/qtwebengine.gni
+++ /dev/null
@@ -1,75 +0,0 @@
-import("//build/config/ui.gni")
-import("//media/media_options.gni")
-import("//extensions/buildflags/buildflags.gni")
-import("//third_party/widevine/cdm/widevine.gni")
-import("//ui/ozone/ozone.gni")
-
-chromium_version = exec_script("//build/util/version.py", [ "-f", rebase_path("//chrome/VERSION"),
- "-t", "@MAJOR@.@MINOR@.@BUILD@.@PATCH@"],
- "list lines")
-
-include_dirs = [
- "//skia/config",
- "//third_party",
- "//third_party/boringssl/src/include",
- "//third_party/skia/include/core"
-]
-
-deps = [
- "//base",
- "//components/cdm/renderer",
- "//components/error_page/common",
- "//components/keyed_service/content",
- "//components/navigation_interception",
- "//components/network_hints/browser",
- "//components/network_hints/common:mojo_bindings",
- "//components/network_hints/renderer",
- "//components/visitedlink/browser",
- "//components/visitedlink/renderer",
- "//components/web_cache/browser",
- "//components/web_cache/renderer",
- "//components/spellcheck:buildflags",
- "//components/proxy_config",
- "//components/user_prefs",
- "//content/public/app:browser",
- "//content",
- "//media:media_buildflags",
- "//net",
- "//services/proxy_resolver:lib",
- "//skia",
- "//third_party/blink/public:blink",
- "//ui/accessibility",
- "//ui/gl",
- "//qtwebengine/browser:interfaces",
- "//qtwebengine/browser:service_manifests",
- "//qtwebengine/common:mojo_bindings",
- ":qtwebengine_sources",
- ":qtwebengine_resources",
-]
-
-if (enable_webrtc) {
- deps += [ "//third_party/webrtc_overrides:webrtc_component" ]
-}
-
-if (use_ozone) {
- _ozone_extra_directory = get_path_info(ozone_extra_path, "dir")
- deps += [ "$_ozone_extra_directory:qt" ]
-}
-
-if (use_xscrnsaver) {
- deps += [ "//ui/base/x" ]
-}
-
-if (enable_extensions) {
- deps += [
- ":qtwebengine_extensions_features"
- ]
-}
-
-if (is_win) {
- data_deps = [ ":qtwebengine_sandbox_win" ]
-}
-
-defines = [
- "CHROMIUM_VERSION=\"" + chromium_version[0] + "\""
-]
diff --git a/src/core/qtwebengine_resources.gni b/src/core/qtwebengine_resources.gni
deleted file mode 100644
index 4f6c51d81..000000000
--- a/src/core/qtwebengine_resources.gni
+++ /dev/null
@@ -1,140 +0,0 @@
-import("//tools/grit/repack.gni")
-import("//build/config/locales.gni")
-import("//chrome/chrome_repack_locales.gni")
-import("//extensions/buildflags/buildflags.gni")
-
-group("qtwebengine_resources") {
- deps = [
- "//chrome/app:generated_resources",
- "//chrome/browser:resources",
- "//chrome/browser/resources:component_extension_resources",
- "//chrome/common:resources",
- "//components/resources:components_resources",
- ":qtwebengine_repack_resources",
- ":qtwebengine_repack_resources_100",
- ":qtwebengine_repack_resources_200",
- ":qtwebengine_repack_resources_devtools",
- ":qtwebengine_repack_locales_pack"
- ]
-}
-
-repack("qtwebengine_repack_resources") {
- sources = [
- "$root_gen_dir/qtwebengine/qt_webengine_resources.pak",
- "$root_gen_dir/chrome/browser_resources.pak",
- "$root_gen_dir/chrome/common_resources.pak",
- "$root_gen_dir/chrome/quota_internals_resources.pak",
- "$root_gen_dir/components/components_resources.pak",
- "$root_gen_dir/content/browser/resources/media/media_internals_resources.pak",
- "$root_gen_dir/content/content_resources.pak",
- "$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak",
- "$root_gen_dir/net/net_resources.pak",
- "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak",
- "$root_gen_dir/ui/resources/webui_resources.pak",
- ]
- output = "$root_out_dir/qtwebengine_resources.pak"
- deps = [
- "//qtwebengine/browser:qt_webengine_resources",
- "//chrome/browser/resources/quota_internals:quota_internals_resources",
- "//chrome/browser:resources_grit",
- "//chrome/common:resources_grit",
- "//components/resources:components_resources_grit",
- "//content/browser/resources/media:media_internals_resources",
- "//content:resources_grit",
- "//mojo/public/js:resources",
- "//net:net_resources_grit",
- "//third_party/blink/public:resources_grit",
- "//ui/resources:webui_resources_grd_grit",
- ]
-
- if (enable_extensions) {
- sources += [
- "$root_gen_dir/chrome/component_extension_resources.pak",
- "$root_gen_dir/extensions/extensions_renderer_resources.pak",
- "$root_gen_dir/extensions/extensions_resources.pak",
- ]
- deps += [
- "//chrome/browser/resources:component_extension_resources_grit",
- "//extensions:extensions_renderer_resources_grit",
- "//extensions:extensions_resources_grd_grit",
- ]
- }
-
- if (enable_webrtc) {
- sources += [
- "$root_gen_dir/content/browser/webrtc/resources/webrtc_internals_resources.pak",
- ]
- deps += [
- "//content/browser/webrtc/resources",
- ]
- }
-}
-
-repack("qtwebengine_repack_resources_100") {
- sources = [
- "$root_gen_dir/components/components_resources_100_percent.pak",
- "$root_gen_dir/content/app/resources/content_resources_100_percent.pak",
- "$root_gen_dir/chrome/renderer_resources_100_percent.pak",
- "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_100_percent.pak",
- "$root_gen_dir/ui/resources/ui_resources_100_percent.pak",
- ]
- output = "$root_out_dir/qtwebengine_resources_100p.pak"
- deps = [
- "//chrome/renderer:resources_grit",
- "//components/resources:components_scaled_resources_grit",
- "//content/app/resources:resources_grit",
- "//third_party/blink/public:scaled_resources_100_percent",
- "//ui/resources:ui_resources_grd_grit"
- ]
- if (enable_extensions) {
- sources += [
- "$root_gen_dir/extensions/extensions_browser_resources_100_percent.pak"
- ]
- deps += [
- "//extensions:extensions_browser_resources_grit"
- ]
- }
-}
-
-repack("qtwebengine_repack_resources_200") {
- sources = [
- "$root_gen_dir/components/components_resources_200_percent.pak",
- "$root_gen_dir/content/app/resources/content_resources_200_percent.pak",
- "$root_gen_dir/chrome/renderer_resources_200_percent.pak",
- "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_200_percent.pak",
- "$root_gen_dir/ui/resources/ui_resources_200_percent.pak",
- ]
- output = "$root_out_dir/qtwebengine_resources_200p.pak"
- deps = [
- "//chrome/renderer:resources_grit",
- "//components/resources:components_scaled_resources_grit",
- "//content/app/resources:resources_grit",
- "//third_party/blink/public:scaled_resources_200_percent",
- "//ui/resources:ui_resources_grd_grit"
- ]
- if (enable_extensions) {
- sources += [
- "$root_gen_dir/extensions/extensions_browser_resources_200_percent.pak"
- ]
- deps += [
- "//extensions:extensions_browser_resources_grit"
- ]
- }
-}
-
-repack("qtwebengine_repack_resources_devtools") {
- sources = [
- "$root_gen_dir/content/browser/devtools/devtools_resources.pak",
- ]
- output = "$root_out_dir/qtwebengine_devtools_resources.pak"
- deps = [
- "//content/browser/devtools:devtools_resources_grit",
- ]
-}
-
-chrome_repack_locales("qtwebengine_repack_locales_pack") {
- input_locales = locales
- output_dir = "$root_out_dir/qtwebengine_locales"
- output_locales = locales
-}
-
diff --git a/src/core/qtwebengine_sources.gni b/src/core/qtwebengine_sources.gni
deleted file mode 100644
index 3a39455c3..000000000
--- a/src/core/qtwebengine_sources.gni
+++ /dev/null
@@ -1,194 +0,0 @@
-import("//build/config/features.gni")
-import("//build/config/ui.gni")
-import("//chrome/common/features.gni")
-import("//components/spellcheck/spellcheck_build_features.gni")
-import("//pdf/features.gni")
-import("//ppapi/buildflags/buildflags.gni")
-import("//printing/buildflags/buildflags.gni")
-import("//extensions/buildflags/buildflags.gni")
-
-source_set("qtwebengine_spellcheck_sources") {
- include_dirs = core_include_dirs
- configs += [
- "//third_party/boringssl:external_config",
- ]
- sources = [
- "//chrome/browser/spellchecker/spell_check_host_chrome_impl.cc",
- "//chrome/browser/spellchecker/spell_check_host_chrome_impl.h",
- "//chrome/browser/spellchecker/spellcheck_custom_dictionary.cc",
- "//chrome/browser/spellchecker/spellcheck_custom_dictionary.h",
- "//chrome/browser/spellchecker/spellcheck_factory.cc",
- "//chrome/browser/spellchecker/spellcheck_factory.h",
- "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc",
- "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h",
- "//chrome/browser/spellchecker/spellcheck_service.cc",
- "//chrome/browser/spellchecker/spellcheck_service.h",
- "//components/language/core/browser/pref_names.cc",
- "//components/language/core/browser/pref_names.h",
- ]
- deps = [
- "//components/spellcheck/browser",
- "//components/spellcheck/renderer",
- "//third_party/blink/public:blink",
- "//third_party/hunspell",
- ]
- if (is_mac && use_browser_spellchecker) {
- sources += [
- "//chrome/browser/spellchecker/spell_check_host_chrome_impl_mac.cc",
- ]
- }
-}
-
-source_set("qtwebengine_sources") {
- configs += [
- "//skia:skia_config",
- "//third_party/boringssl:external_config",
- ]
-
- deps = [
- "//build:branding_buildflags",
- "//chrome/browser/resources/quota_internals:quota_internals_resources",
- "//chrome/common:buildflags",
- "//components/nacl/common:buildflags",
- "//components/plugins/renderer/",
- "//extensions/buildflags:buildflags",
- "//rlz/buildflags:buildflags",
- "//third_party/blink/public/mojom:mojom_platform",
- ]
-
- sources = [
- "//chrome/browser/accessibility/accessibility_ui.cc",
- "//chrome/browser/accessibility/accessibility_ui.h",
- "//chrome/browser/custom_handlers/protocol_handler_registry.cc",
- "//chrome/browser/custom_handlers/protocol_handler_registry.h",
- "//chrome/browser/custom_handlers/protocol_handler_registry_factory.cc",
- "//chrome/browser/custom_handlers/protocol_handler_registry_factory.h",
- "//chrome/browser/media/webrtc/desktop_media_list.h",
- "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc",
- "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.h",
- "//chrome/browser/prefs/chrome_command_line_pref_store.cc",
- "//chrome/browser/prefs/chrome_command_line_pref_store.h",
- "//chrome/browser/profiles/profile.cc",
- "//chrome/browser/profiles/profile.h",
- "//chrome/browser/ui/webui/devtools_ui.cc",
- "//chrome/browser/ui/webui/devtools_ui.h",
- "//chrome/browser/ui/webui/devtools_ui_data_source.cc",
- "//chrome/browser/ui/webui/devtools_ui_data_source.h",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_handler.h",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_types.cc",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_types.h",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc",
- "//chrome/browser/ui/webui/quota_internals/quota_internals_ui.h",
- "//chrome/common/custom_handlers/protocol_handler.cc",
- "//chrome/common/custom_handlers/protocol_handler.h",
- "//chrome/common/chrome_switches.cc",
- "//chrome/common/chrome_switches.h",
- "//chrome/common/pref_names.cc",
- "//chrome/common/pref_names.h",
- "//chrome/common/url_constants.cc",
- "//chrome/common/url_constants.h",
- "//chrome/common/webui_url_constants.cc",
- "//chrome/common/webui_url_constants.h",
- ]
-
- if (enable_extensions) {
- deps += [
- ":qtwebengine_extensions_features",
- "//chrome/app:generated_resources",
- "//chrome/browser/resources:component_extension_resources_grit",
- "//chrome/common/extensions/api",
- "//chrome/common/extensions/api:extensions_features",
- "//components/crx_file",
- "//components/crx_file:crx_creator",
- "//components/spellcheck:buildflags",
- "//extensions/buildflags:buildflags",
- "//extensions/common",
- "//extensions/common/api",
- "//extensions/common:core_api_provider",
- "//extensions/browser",
- "//extensions/browser/api",
- "//extensions/browser:core_api_provider",
- "//extensions/renderer",
- "//extensions:extensions_resources",
- "//extensions/strings",
- ]
- sources += [
- "//chrome/common/extensions/permissions/chrome_api_permissions.cc",
- "//chrome/common/extensions/permissions/chrome_api_permissions.h",
- "//chrome/common/extensions/permissions/chrome_permission_message_provider.cc",
- "//chrome/common/extensions/permissions/chrome_permission_message_provider.h",
- "//chrome/common/extensions/permissions/chrome_permission_message_rules.cc",
- "//chrome/common/extensions/permissions/chrome_permission_message_rules.h",
- ]
- } else {
- deps += [
- "//extensions/common:common_constants",
- ]
- sources += [
- "//extensions/common/url_pattern.cc",
- "//extensions/common/url_pattern.h",
- ]
- }
-
- if (is_linux) {
- sources += [
- "//chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc",
- "//chrome/browser/ui/webui/sandbox/sandbox_internals_ui.h",
- ]
- }
-
- if (enable_spellcheck) {
- deps += [
- ":qtwebengine_spellcheck_sources",
- "//chrome/tools/convert_dict",
- ]
- }
-
- if (enable_plugins) {
- sources += [
- "//chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc",
- "//chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h",
- "//chrome/renderer/pepper/pepper_flash_font_file_host.cc",
- "//chrome/renderer/pepper/pepper_flash_font_file_host.h",
- "//chrome/renderer/pepper/pepper_shared_memory_message_filter.cc",
- "//chrome/renderer/pepper/pepper_shared_memory_message_filter.h",
- ]
- }
-
- if (enable_basic_printing || enable_print_preview) {
- sources += [
- "//chrome/browser/printing/printer_query.cc",
- "//chrome/browser/printing/printer_query.h",
- "//chrome/browser/printing/print_job.cc",
- "//chrome/browser/printing/print_job.h",
- "//chrome/browser/printing/print_job_manager.cc",
- "//chrome/browser/printing/print_job_manager.h",
- "//chrome/browser/printing/print_job_worker.cc",
- "//chrome/browser/printing/print_job_worker.h",
- ]
- deps += [
- "//printing/buildflags:buildflags",
- ]
- }
-
- if (enable_pdf) {
- deps += [
- "//pdf",
- "//pdf:buildflags",
- "//components/pdf/browser:browser",
- "//components/pdf/renderer:renderer",
- "//components/printing/browser",
- "//components/printing/renderer",
- ]
- }
-}
-
-if (is_win) {
- shared_library("qtwebengine_sandbox_win") {
- create_pri_file = true
- public_deps = [ "//sandbox/win:sandbox" ]
- }
-}
diff --git a/src/core/quota_permission_context_qt.cpp b/src/core/quota_permission_context_qt.cpp
deleted file mode 100644
index 94645b237..000000000
--- a/src/core/quota_permission_context_qt.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "quota_permission_context_qt.h"
-
-#include "base/task/post_task.h"
-#include "content/browser/web_contents/web_contents_impl.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_frame_host.h"
-#include "quota_request_controller_impl.h"
-#include "qwebenginequotarequest.h"
-#include "web_contents_delegate_qt.h"
-#include "web_contents_view_qt.h"
-
-using content::QuotaPermissionContext;
-using content::RenderFrameHost;
-using content::StorageQuotaParams;
-using content::WebContents;
-
-namespace QtWebEngineCore {
-
-void QuotaPermissionContextQt::RequestQuotaPermission(const StorageQuotaParams &params, int render_process_id, const PermissionCallback &callback)
-{
- if (params.storage_type != blink::mojom::StorageType::kPersistent) {
- // For now we only support requesting quota with this interface
- // for Persistent storage type.
- callback.Run(QUOTA_PERMISSION_RESPONSE_DISALLOW);
- return;
- }
-
- if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&QuotaPermissionContextQt::RequestQuotaPermission, this,
- params, render_process_id, callback));
- return;
- }
-
- RenderFrameHost *renderFrameHost = RenderFrameHost::FromID(render_process_id, params.render_frame_id);
- if (!renderFrameHost)
- return;
-
- WebContents *webContents = WebContents::FromRenderFrameHost(renderFrameHost);
- if (!webContents)
- return;
-
- WebContentsAdapterClient *client = WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(webContents)->GetView())->client();
- if (!client)
- return;
-
- QWebEngineQuotaRequest request(
- QSharedPointer<QuotaRequestControllerImpl>::create(this, params, callback));
- client->runQuotaRequest(std::move(request));
-}
-
-void QuotaPermissionContextQt::dispatchCallbackOnIOThread(const PermissionCallback &callback,
- QuotaPermissionContext::QuotaPermissionResponse response)
-{
- if (callback.is_null())
- return;
-
- if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&QuotaPermissionContextQt::dispatchCallbackOnIOThread,
- this, callback, response));
- return;
- }
-
- callback.Run(response);
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/quota_permission_context_qt.h b/src/core/quota_permission_context_qt.h
deleted file mode 100644
index 99e07eec7..000000000
--- a/src/core/quota_permission_context_qt.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QUOTA_PERMISSION_CONTEXT_QT_H
-#define QUOTA_PERMISSION_CONTEXT_QT_H
-
-#include "content/public/browser/quota_permission_context.h"
-
-#include <QtCore/qcompilerdetection.h> // Needed for override
-
-namespace QtWebEngineCore {
-
-class QuotaPermissionContextQt : public content::QuotaPermissionContext {
-public:
- void RequestQuotaPermission(const content::StorageQuotaParams &params,
- int render_process_id,
- const PermissionCallback &callback) override;
-
- void dispatchCallbackOnIOThread(const PermissionCallback &callback,
- QuotaPermissionContext::QuotaPermissionResponse response);
-};
-
-} // namespace QtWebEngineCore
-
-#endif // QUOTA_PERMISSION_CONTEXT_QT_H
diff --git a/src/core/quota_request_controller.h b/src/core/quota_request_controller.h
deleted file mode 100644
index 0bb0cbff3..000000000
--- a/src/core/quota_request_controller.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QUOTA_REQUEST_CONTROLLER_H
-#define QUOTA_REQUEST_CONTROLLER_H
-
-#include "request_controller.h"
-
-namespace QtWebEngineCore {
-
-class QuotaRequestController : public RequestController {
-public:
- QuotaRequestController(QUrl origin, qint64 requestedSize)
- : RequestController(std::move(origin))
- , m_requestedSize(requestedSize)
- {}
-
- qint64 requestedSize() const { return m_requestedSize; }
-
-private:
- qint64 m_requestedSize;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // QUOTA_REQUEST_CONTROLLER_H
diff --git a/src/core/quota_request_controller_impl.cpp b/src/core/quota_request_controller_impl.cpp
deleted file mode 100644
index a18ad761d..000000000
--- a/src/core/quota_request_controller_impl.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "quota_request_controller_impl.h"
-
-#include "type_conversion.h"
-
-namespace QtWebEngineCore {
-
-QuotaRequestControllerImpl::QuotaRequestControllerImpl(
- QuotaPermissionContextQt *context,
- const content::StorageQuotaParams &params,
- const content::QuotaPermissionContext::PermissionCallback &callback)
- : QuotaRequestController(
- toQt(params.origin_url),
- params.requested_size)
- , m_context(context)
- , m_callback(callback)
-{}
-
-QuotaRequestControllerImpl::~QuotaRequestControllerImpl()
-{
- reject();
-}
-
-void QuotaRequestControllerImpl::accepted()
-{
- m_context->dispatchCallbackOnIOThread(m_callback, QuotaPermissionContextQt::QUOTA_PERMISSION_RESPONSE_ALLOW);
-}
-
-void QuotaRequestControllerImpl::rejected()
-{
- m_context->dispatchCallbackOnIOThread(m_callback, QuotaPermissionContextQt::QUOTA_PERMISSION_RESPONSE_DISALLOW);
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/quota_request_controller_impl.h b/src/core/quota_request_controller_impl.h
deleted file mode 100644
index 5814895f3..000000000
--- a/src/core/quota_request_controller_impl.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QUOTA_REQUEST_CONTROLLER_IMPL_H
-#define QUOTA_REQUEST_CONTROLLER_IMPL_H
-
-#include "quota_permission_context_qt.h"
-#include "quota_request_controller.h"
-
-namespace QtWebEngineCore {
-
-class QuotaRequestControllerImpl final : public QuotaRequestController {
-public:
- QuotaRequestControllerImpl(
- QuotaPermissionContextQt *context,
- const content::StorageQuotaParams &params,
- const content::QuotaPermissionContext::PermissionCallback &callback);
-
- ~QuotaRequestControllerImpl();
-
-protected:
- void accepted() override;
- void rejected() override;
-
-private:
- scoped_refptr<QuotaPermissionContextQt> m_context;
- content::QuotaPermissionContext::PermissionCallback m_callback;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // QUOTA_REQUEST_CONTROLLER_IMPL_H
diff --git a/src/core/register_protocol_handler_request_controller.h b/src/core/register_protocol_handler_request_controller.h
deleted file mode 100644
index 2f9c9fc49..000000000
--- a/src/core/register_protocol_handler_request_controller.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
-#define REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
-
-#include "request_controller.h"
-
-namespace QtWebEngineCore {
-
-class RegisterProtocolHandlerRequestController : public RequestController {
-public:
- RegisterProtocolHandlerRequestController(QUrl origin, QString scheme)
- : RequestController(std::move(origin))
- , m_scheme(std::move(scheme))
- {}
-
- QString scheme() const { return m_scheme; }
-
-private:
- QString m_scheme;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_H
diff --git a/src/core/register_protocol_handler_request_controller_impl.cpp b/src/core/register_protocol_handler_request_controller_impl.cpp
deleted file mode 100644
index 0f24d8812..000000000
--- a/src/core/register_protocol_handler_request_controller_impl.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "register_protocol_handler_request_controller_impl.h"
-
-#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
-#include "content/public/browser/web_contents.h"
-#include "type_conversion.h"
-
-namespace QtWebEngineCore {
-
-RegisterProtocolHandlerRequestControllerImpl::RegisterProtocolHandlerRequestControllerImpl(
- content::WebContents *webContents,
- ProtocolHandler handler)
- : RegisterProtocolHandlerRequestController(
- toQt(handler.url()),
- toQt(handler.protocol()))
- , content::WebContentsObserver(webContents)
- , m_handler(handler)
-{}
-
-RegisterProtocolHandlerRequestControllerImpl::~RegisterProtocolHandlerRequestControllerImpl()
-{
- reject();
-}
-
-ProtocolHandlerRegistry *RegisterProtocolHandlerRequestControllerImpl::protocolHandlerRegistry()
-{
- content::WebContents *webContents = web_contents();
- if (!webContents)
- return nullptr;
- content::BrowserContext *context = webContents->GetBrowserContext();
- return ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
-}
-
-void RegisterProtocolHandlerRequestControllerImpl::accepted()
-{
- if (ProtocolHandlerRegistry *registry = protocolHandlerRegistry())
- registry->OnAcceptRegisterProtocolHandler(m_handler);
-}
-
-void RegisterProtocolHandlerRequestControllerImpl::rejected()
-{
- if (ProtocolHandlerRegistry *registry = protocolHandlerRegistry())
- registry->OnIgnoreRegisterProtocolHandler(m_handler);
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/register_protocol_handler_request_controller_impl.h b/src/core/register_protocol_handler_request_controller_impl.h
deleted file mode 100644
index 64f229ac4..000000000
--- a/src/core/register_protocol_handler_request_controller_impl.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
-#define REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
-
-#include "register_protocol_handler_request_controller.h"
-
-#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
-#include "chrome/common/custom_handlers/protocol_handler.h"
-#include "content/public/browser/web_contents_observer.h"
-
-class ProtocolHandlerRegistry;
-
-namespace QtWebEngineCore {
-
-class RegisterProtocolHandlerRequestControllerImpl final : public RegisterProtocolHandlerRequestController,
- private content::WebContentsObserver {
-public:
- RegisterProtocolHandlerRequestControllerImpl(
- content::WebContents *webContents,
- ProtocolHandler handler);
-
- ~RegisterProtocolHandlerRequestControllerImpl();
-
-protected:
- void accepted() override;
- void rejected() override;
-
-private:
- ProtocolHandlerRegistry *protocolHandlerRegistry();
- ProtocolHandler m_handler;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // REGISTER_PROTOCOL_HANDLER_REQUEST_CONTROLLER_IMPL_H
diff --git a/src/core/render_view_context_menu_qt.cpp b/src/core/render_view_context_menu_qt.cpp
index 4e182973c..b7aabfd5b 100644
--- a/src/core/render_view_context_menu_qt.cpp
+++ b/src/core/render_view_context_menu_qt.cpp
@@ -1,44 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include <QtCore/QCoreApplication>
#include "render_view_context_menu_qt.h"
+#include "qwebenginecontextmenurequest.h"
namespace QtWebEngineCore {
@@ -74,8 +39,8 @@ namespace QtWebEngineCore {
return QCoreApplication::translate("RenderViewContextMenuQt", qUtf8Printable(names[menuItem]));
}
- RenderViewContextMenuQt::RenderViewContextMenuQt(const WebEngineContextMenuData &data)
- : m_contextData(data)
+ RenderViewContextMenuQt::RenderViewContextMenuQt(QWebEngineContextMenuRequest *request)
+ : m_contextData(request)
{
}
@@ -86,41 +51,47 @@ namespace QtWebEngineCore {
appendSeparatorItem();
}
- if (m_contextData.isEditable() && !m_contextData.spellCheckerSuggestions().isEmpty()) {
+ if (m_contextData->isContentEditable()
+ && !m_contextData->spellCheckerSuggestions().isEmpty()) {
appendSpellingSuggestionItems();
appendSeparatorItem();
}
- if (m_contextData.linkText().isEmpty() && !m_contextData.linkUrl().isValid() && !m_contextData.mediaUrl().isValid()) {
- if (m_contextData.isEditable())
+ if (m_contextData->linkText().isEmpty() && !m_contextData->filteredLinkUrl().isValid()
+ && !m_contextData->mediaUrl().isValid()) {
+ if (m_contextData->isContentEditable())
appendEditableItems();
- else if (!m_contextData.selectedText().isEmpty())
+ else if (!m_contextData->selectedText().isEmpty())
appendCopyItem();
else
appendPageItems();
+ } else {
+ appendPageItems();
}
- if (m_contextData.linkUrl().isValid() || !m_contextData.unfilteredLinkUrl().isEmpty() || !m_contextData.linkUrl().isEmpty())
+ if (m_contextData->filteredLinkUrl().isValid()
+ || !m_contextData->linkUrl().isEmpty()
+ || !m_contextData->filteredLinkUrl().isEmpty())
appendLinkItems();
- if (m_contextData.mediaUrl().isValid()) {
- switch (m_contextData.mediaType()) {
- case WebEngineContextMenuData::MediaTypeImage:
+ if (m_contextData->mediaUrl().isValid()) {
+ switch (m_contextData->mediaType()) {
+ case QWebEngineContextMenuRequest::MediaTypeImage:
appendSeparatorItem();
appendImageItems();
break;
- case WebEngineContextMenuData::MediaTypeCanvas:
+ case QWebEngineContextMenuRequest::MediaTypeCanvas:
Q_UNREACHABLE(); // mediaUrl is invalid for canvases
break;
- case WebEngineContextMenuData::MediaTypeAudio:
- case WebEngineContextMenuData::MediaTypeVideo:
+ case QWebEngineContextMenuRequest::MediaTypeAudio:
+ case QWebEngineContextMenuRequest::MediaTypeVideo:
appendSeparatorItem();
appendMediaItems();
break;
default:
break;
}
- } else if (m_contextData.mediaType() == WebEngineContextMenuData::MediaTypeCanvas) {
+ } else if (m_contextData->mediaType() == QWebEngineContextMenuRequest::MediaTypeCanvas) {
appendSeparatorItem();
appendCanvasItems();
}
@@ -158,7 +129,7 @@ namespace QtWebEngineCore {
addMenuItem(RenderViewContextMenuQt::Cut);
addMenuItem(RenderViewContextMenuQt::Copy);
addMenuItem(RenderViewContextMenuQt::Paste);
- if (m_contextData.misspelledWord().isEmpty()) {
+ if (m_contextData->misspelledWord().isEmpty()) {
addMenuItem(RenderViewContextMenuQt::PasteAndMatchStyle);
addMenuItem(RenderViewContextMenuQt::SelectAll);
}
@@ -188,7 +159,7 @@ namespace QtWebEngineCore {
void RenderViewContextMenuQt::appendMediaItems()
{
addMenuItem(RenderViewContextMenuQt::ToggleMediaLoop);
- if (m_contextData.mediaFlags() & QtWebEngineCore::WebEngineContextMenuData::MediaCanToggleControls)
+ if (m_contextData->mediaFlags() & QWebEngineContextMenuRequest::MediaCanToggleControls)
addMenuItem(RenderViewContextMenuQt::ToggleMediaControls);
addMenuItem(RenderViewContextMenuQt::DownloadMediaToDisk);
addMenuItem(RenderViewContextMenuQt::CopyMediaUrlToClipboard);
@@ -215,10 +186,8 @@ namespace QtWebEngineCore {
bool RenderViewContextMenuQt::canViewSource()
{
- return m_contextData.linkText().isEmpty()
- && !m_contextData.linkUrl().isValid()
- && !m_contextData.mediaUrl().isValid()
- && !m_contextData.isEditable()
- && m_contextData.selectedText().isEmpty();
+ return m_contextData->linkText().isEmpty() && !m_contextData->filteredLinkUrl().isValid()
+ && !m_contextData->mediaUrl().isValid() && !m_contextData->isContentEditable()
+ && m_contextData->selectedText().isEmpty();
}
}
diff --git a/src/core/render_view_context_menu_qt.h b/src/core/render_view_context_menu_qt.h
index e1ee301fc..1188f6cd4 100644
--- a/src/core/render_view_context_menu_qt.h
+++ b/src/core/render_view_context_menu_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,11 +15,13 @@
#ifndef RENDER_VIEW_CONTEXT_MENU_QT_H
#define RENDER_VIEW_CONTEXT_MENU_QT_H
-#include "web_contents_adapter_client.h"
+#include "qtwebenginecoreglobal.h"
+
+QT_FORWARD_DECLARE_CLASS(QWebEngineContextMenuRequest)
namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT RenderViewContextMenuQt
+class Q_WEBENGINECORE_EXPORT RenderViewContextMenuQt
{
public:
enum ContextMenuItem {
@@ -99,7 +65,7 @@ public:
static const QString getMenuItemName(RenderViewContextMenuQt::ContextMenuItem menuItem);
- RenderViewContextMenuQt(const WebEngineContextMenuData &data);
+ RenderViewContextMenuQt(QWebEngineContextMenuRequest *data);
void initMenu();
protected:
@@ -109,7 +75,7 @@ protected:
virtual void addMenuItem(ContextMenuItem menuItem) = 0;
virtual bool isMenuItemEnabled(ContextMenuItem menuItem) = 0;
- const WebEngineContextMenuData &m_contextData;
+ QWebEngineContextMenuRequest *m_contextData;
private:
void appendCanvasItems();
diff --git a/src/core/render_widget_host_view_qt.cpp b/src/core/render_widget_host_view_qt.cpp
index 9be6fac9a..888043fda 100644
--- a/src/core/render_widget_host_view_qt.cpp
+++ b/src/core/render_widget_host_view_qt.cpp
@@ -1,47 +1,8 @@
-
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "render_widget_host_view_qt.h"
-#include "browser_accessibility_manager_qt.h"
-#include "common/qt_messages.h"
#include "qtwebenginecoreglobal_p.h"
#include "render_widget_host_view_qt_delegate.h"
#include "render_widget_host_view_qt_delegate_client.h"
@@ -51,26 +12,33 @@
#include "web_contents_adapter_client.h"
#include "web_event_factory.h"
-#include "base/threading/thread_task_runner_handle.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/common/surfaces/frame_sink_id_allocator.h"
#include "components/viz/host/host_frame_sink_manager.h"
-#include "content/browser/frame_host/frame_tree.h"
-#include "content/browser/frame_host/render_frame_host_impl.h"
+#include "content/browser/compositor/image_transport_factory.h"
+#include "content/browser/renderer_host/render_frame_host_impl.h"
+#include "content/browser/renderer_host/frame_tree.h"
+#include "content/browser/renderer_host/frame_tree_node.h"
+#include "content/browser/renderer_host/cursor_manager.h"
#include "content/browser/renderer_host/input/synthetic_gesture_target.h"
+#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
-#include "content/common/content_switches_internal.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
+#include "content/browser/renderer_host/ui_events_helper.h"
+#include "content/common/content_switches_internal.h"
#include "content/common/cursors/webcursor.h"
-#include "content/common/input_messages.h"
+#include "content/public/browser/web_contents.h"
#include "third_party/skia/include/core/SkColor.h"
-#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "ui/base/cursor/cursor.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/display/display_util.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/event.h"
#include "ui/events/gesture_detection/gesture_configuration.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
+#include "ui/events/keycodes/dom/dom_keyboard_layout_map.h"
#include "ui/gfx/image/image_skia.h"
#if defined(USE_OZONE)
@@ -78,13 +46,17 @@
#endif
#if defined(USE_AURA)
-#include "ui/base/cursor/cursor.h"
-#include "ui/base/cursor/cursors_aura.h"
-#include "ui/base/resource/resource_bundle.h"
+#include "ui/wm/core/cursor_util.h"
+#include "ui/base/cursor/cursor_size.h"
+#endif
+
+#if defined(Q_OS_MACOS)
+#include "ui/resources/grit/ui_resources.h"
#endif
#include <QGuiApplication>
#include <QPixmap>
+#include <QScopeGuard>
#include <QScreen>
#include <QWindow>
@@ -118,9 +90,61 @@ static inline ui::GestureProvider::Config QtGestureProviderConfig() {
return config;
}
+extern display::Display toDisplayDisplay(int id, const QScreen *screen);
+
+static display::ScreenInfos screenInfosFromQtForUpdate(QScreen *currentScreen)
+{
+ display::ScreenInfo screenInfo;
+ const auto &screens = qApp->screens();
+ if (screens.isEmpty()) {
+ screenInfo.device_scale_factor = qGuiApp->devicePixelRatio();
+ return display::ScreenInfos(screenInfo);
+ }
+
+ Q_ASSERT(qApp->primaryScreen() == screens.first());
+ display::ScreenInfos result;
+ for (int i = 0; i < screens.length(); ++i) {
+ display::DisplayUtil::DisplayToScreenInfo(&screenInfo, toDisplayDisplay(i, screens.at(i)));
+ result.screen_infos.push_back(screenInfo);
+ if (currentScreen == screens.at(i))
+ result.current_display_id = i;
+ }
+
+ Q_ASSERT(result.current_display_id != display::kInvalidDisplayId);
+
+ return result;
+}
+
+// An minimal override to support progressing flings
+class FlingingCompositor : public ui::Compositor
+{
+ RenderWidgetHostViewQt *m_rwhv;
+public:
+ FlingingCompositor(RenderWidgetHostViewQt *rwhv,
+ const viz::FrameSinkId &frame_sink_id,
+ ui::ContextFactory *context_factory,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner,
+ bool enable_pixel_canvas,
+ bool use_external_begin_frame_control = false,
+ bool force_software_compositor = false)
+ : ui::Compositor(frame_sink_id, context_factory,
+ task_runner, enable_pixel_canvas,
+ use_external_begin_frame_control,
+ force_software_compositor)
+ , m_rwhv(rwhv)
+ {}
+
+ void BeginMainFrame(const viz::BeginFrameArgs &args) override
+ {
+ if (args.type != viz::BeginFrameArgs::MISSED && !m_rwhv->is_currently_scrolling_viewport())
+ m_rwhv->host()->ProgressFlingIfNeeded(args.frame_time);
+ ui::Compositor::BeginMainFrame(args);
+ }
+};
+
RenderWidgetHostViewQt::RenderWidgetHostViewQt(content::RenderWidgetHost *widget)
: content::RenderWidgetHostViewBase::RenderWidgetHostViewBase(widget)
- , m_taskRunner(base::ThreadTaskRunnerHandle::Get())
+ , m_taskRunner(base::SingleThreadTaskRunner::GetCurrentDefault())
, m_gestureProvider(QtGestureProviderConfig(), this)
, m_frameSinkId(host()->GetFrameSinkId())
, m_delegateClient(new RenderWidgetHostViewQtDelegateClient(this))
@@ -138,11 +162,10 @@ RenderWidgetHostViewQt::RenderWidgetHostViewQt(content::RenderWidgetHost *widget
content::ImageTransportFactory *imageTransportFactory = content::ImageTransportFactory::GetInstance();
ui::ContextFactory *contextFactory = imageTransportFactory->GetContextFactory();
- ui::ContextFactoryPrivate *contextFactoryPrivate = imageTransportFactory->GetContextFactoryPrivate();
- m_uiCompositor.reset(new ui::Compositor(
- contextFactoryPrivate->AllocateFrameSinkId(),
+ m_uiCompositor.reset(new FlingingCompositor(
+ this,
+ contextFactory->AllocateFrameSinkId(),
contextFactory,
- contextFactoryPrivate,
m_taskRunner,
false /* enable_pixel_canvas */));
m_uiCompositor->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); // null means offscreen
@@ -151,13 +174,12 @@ RenderWidgetHostViewQt::RenderWidgetHostViewQt(content::RenderWidgetHost *widget
if (host()->delegate() && host()->delegate()->GetInputEventRouter())
host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(GetFrameSinkId(), this);
+ m_cursorManager.reset(new content::CursorManager(this));
+
m_touchSelectionControllerClient.reset(new TouchSelectionControllerClientQt(this));
- ui::TouchSelectionController::Config config;
- config.max_tap_duration = base::TimeDelta::FromMilliseconds(ui::GestureConfiguration::GetInstance()->long_press_time_in_ms());
- config.tap_slop = ui::GestureConfiguration::GetInstance()->max_touch_move_in_pixels_for_click();
- config.enable_longpress_drag_selection = false;
- m_touchSelectionController.reset(new ui::TouchSelectionController(m_touchSelectionControllerClient.get(), config));
+ resetTouchSelectionController();
+ host()->render_frame_metadata_provider()->AddObserver(this);
host()->render_frame_metadata_provider()->ReportAllFrameSubmissionsForTesting(true);
host()->SetView(this);
@@ -172,8 +194,14 @@ RenderWidgetHostViewQt::~RenderWidgetHostViewQt()
if (text_input_manager_)
text_input_manager_->RemoveObserver(this);
+ if (host()->delegate())
+ m_touchSelectionControllerClient->resetControls();
+
m_touchSelectionController.reset();
m_touchSelectionControllerClient.reset();
+
+ host()->render_frame_metadata_provider()->RemoveObserver(this);
+ host()->ViewDestroyed();
}
void RenderWidgetHostViewQt::setDelegate(RenderWidgetHostViewQtDelegate* delegate)
@@ -197,21 +225,51 @@ void RenderWidgetHostViewQt::setAdapterClient(WebContentsAdapterClient *adapterC
m_adapterClient = nullptr; });
}
-void RenderWidgetHostViewQt::InitAsChild(gfx::NativeView)
+void RenderWidgetHostViewQt::OnInputEventAck(blink::mojom::InputEventResultSource,
+ blink::mojom::InputEventResultState state,
+ const blink::WebInputEvent &event)
{
+ if (event.GetType() == blink::WebInputEvent::Type::kMouseWheel)
+ WheelEventAck(static_cast<const blink::WebMouseWheelEvent &>(event), state);
}
-void RenderWidgetHostViewQt::InitAsPopup(content::RenderWidgetHostView*, const gfx::Rect& rect)
+// static
+// Called when new child/guest renderframes created.
+void RenderWidgetHostViewQt::registerInputEventObserver(content::WebContents *webContents,
+ content::RenderFrameHost *rfh)
{
- m_delegate->initAsPopup(toQt(rect));
+ if (static_cast<content::RenderFrameHostImpl *>(rfh)->is_local_root_subframe()) {
+ content::WebContents *parent = webContents->GetOutermostWebContents();
+ QtWebEngineCore::RenderWidgetHostViewQt *mainRwhv =
+ static_cast<QtWebEngineCore::RenderWidgetHostViewQt *>(
+ parent->GetRenderWidgetHostView());
+ // Child (originAgentCluster) or guest (pdf) frame that is embedded into the main frame
+ content::RenderWidgetHost *childFrame = rfh->GetRenderWidgetHost();
+ childFrame->AddInputEventObserver(mainRwhv);
+
+ if (webContents->IsInnerWebContentsForGuest()) {
+ // The frame which holds the actual PDF content inside the guest
+ content::RenderWidgetHost *guestFrame = webContents->GetRenderViewHost()->GetWidget();
+ guestFrame->AddInputEventObserver(mainRwhv);
+ }
+ }
}
-void RenderWidgetHostViewQt::InitAsFullscreen(content::RenderWidgetHostView*)
+void RenderWidgetHostViewQt::InitAsChild(gfx::NativeView)
{
}
+void RenderWidgetHostViewQt::InitAsPopup(content::RenderWidgetHostView*, const gfx::Rect& rect, const gfx::Rect& anchorRect)
+{
+ Q_UNUSED(anchorRect);
+ m_delegate->initAsPopup(toQt(rect));
+}
+
void RenderWidgetHostViewQt::SetSize(const gfx::Size &sizeInDips)
{
+ if (!m_delegate)
+ return;
+
m_delegate->resize(sizeInDips.width(), sizeInDips.height());
}
@@ -233,22 +291,16 @@ gfx::NativeView RenderWidgetHostViewQt::GetNativeView()
return gfx::NativeView();
}
-gfx::NativeViewAccessible RenderWidgetHostViewQt::GetNativeViewAccessible()
+content::WebContentsAccessibility *RenderWidgetHostViewQt::GetWebContentsAccessibility()
{
- return 0;
+ if (!m_webContentsAccessibility)
+ m_webContentsAccessibility.reset(new WebContentsAccessibilityQt(this));
+ return m_webContentsAccessibility.get();
}
-content::BrowserAccessibilityManager* RenderWidgetHostViewQt::CreateBrowserAccessibilityManager(content::BrowserAccessibilityDelegate* delegate, bool for_root_frame)
+QObject *WebContentsAccessibilityQt::accessibilityParentObject() const
{
- Q_UNUSED(for_root_frame); // FIXME
-#if QT_CONFIG(accessibility)
- return new content::BrowserAccessibilityManagerQt(
- m_adapterClient->accessibilityParentObject(),
- content::BrowserAccessibilityManagerQt::GetEmptyDocument(),
- delegate);
-#else
- return 0;
-#endif // QT_CONFIG(accessibility)
+ return m_rwhv->m_adapterClient->accessibilityParentObject();
}
// Set focus to the associated View component.
@@ -269,6 +321,11 @@ bool RenderWidgetHostViewQt::IsMouseLocked()
return m_isMouseLocked;
}
+viz::FrameSinkId RenderWidgetHostViewQt::GetRootFrameSinkId()
+{
+ return m_uiCompositor->frame_sink_id();
+}
+
bool RenderWidgetHostViewQt::IsSurfaceAvailableForCopy()
{
return m_delegatedFrameHost->CanCopyFromCompositingSurface();
@@ -281,8 +338,9 @@ void RenderWidgetHostViewQt::CopyFromSurface(const gfx::Rect &src_rect,
m_delegatedFrameHost->CopyFromCompositingSurface(src_rect, output_size, std::move(callback));
}
-void RenderWidgetHostViewQt::Show()
+void RenderWidgetHostViewQt::ShowWithVisibility(content::PageVisibilityState page_visibility)
{
+ Q_ASSERT(page_visibility != content::PageVisibilityState::kHidden);
if (m_delegate)
m_delegate->show();
else
@@ -309,6 +367,9 @@ gfx::Rect RenderWidgetHostViewQt::GetViewBounds()
void RenderWidgetHostViewQt::UpdateBackgroundColor()
{
+ if (!m_delegate)
+ return;
+
DCHECK(GetBackgroundColor());
SkColor color = *GetBackgroundColor();
@@ -319,18 +380,28 @@ void RenderWidgetHostViewQt::UpdateBackgroundColor()
m_rootLayer->SetColor(color);
m_uiCompositor->SetBackgroundColor(color);
- content::RenderViewHost *rvh = content::RenderViewHost::From(host());
- host()->Send(new RenderViewObserverQt_SetBackgroundColor(rvh->GetRoutingID(), color));
+ if (color == SK_ColorTRANSPARENT)
+ host()->owner_delegate()->SetBackgroundOpaque(false);
}
// Return value indicates whether the mouse is locked successfully or not.
-bool RenderWidgetHostViewQt::LockMouse(bool)
+blink::mojom::PointerLockResult RenderWidgetHostViewQt::LockMouse(bool request_unadjusted_movement)
{
+ if (request_unadjusted_movement)
+ return blink::mojom::PointerLockResult::kUnsupportedOptions;
+
delegateClient()->resetPreviousMousePosition();
m_delegate->lockMouse();
m_isMouseLocked = true;
qApp->setOverrideCursor(Qt::BlankCursor);
- return true;
+ return blink::mojom::PointerLockResult::kSuccess;
+}
+
+blink::mojom::PointerLockResult RenderWidgetHostViewQt::ChangeMouseLock(bool request_unadjusted_movement)
+{
+ if (request_unadjusted_movement)
+ return blink::mojom::PointerLockResult::kUnsupportedOptions;
+ return blink::mojom::PointerLockResult::kSuccess;
}
void RenderWidgetHostViewQt::UnlockMouse()
@@ -341,169 +412,199 @@ void RenderWidgetHostViewQt::UnlockMouse()
host()->LostMouseLock();
}
-void RenderWidgetHostViewQt::UpdateCursor(const content::WebCursor &webCursor)
+bool RenderWidgetHostViewQt::updateCursorFromResource(ui::mojom::CursorType type)
+{
+ int resourceId;
+ // GetCursorDataFor only knows hotspots for 1x and 2x cursor images, in physical pixels.
+ qreal hotspotDpr = GetScreenInfo().device_scale_factor <= 1.0f ? 1.0f : 2.0f;
+ qreal hotX;
+ qreal hotY;
+
+#if defined(USE_AURA)
+ gfx::Point hotspot;
+ if (!wm::GetCursorDataFor(ui::CursorSize::kNormal, type, hotspotDpr, &resourceId, &hotspot))
+ return false;
+ hotX = hotspot.x();
+ hotY = hotspot.y();
+#elif defined(Q_OS_MACOS)
+ // See chromium/content/common/cursors/webcursor_mac.mm
+ switch (type) {
+ case ui::mojom::CursorType::kVerticalText:
+ // TODO: [NSCursor IBeamCursorForVerticalLayout]
+ return false;
+ case ui::mojom::CursorType::kCell:
+ resourceId = IDR_CELL_CURSOR;
+ hotX = 7;
+ hotY = 7;
+ break;
+ case ui::mojom::CursorType::kContextMenu:
+ // TODO: [NSCursor contextualMenuCursor]
+ return false;
+ case ui::mojom::CursorType::kZoomIn:
+ resourceId = IDR_ZOOMIN_CURSOR;
+ hotX = 7;
+ hotY = 7;
+ break;
+ case ui::mojom::CursorType::kZoomOut:
+ resourceId = IDR_ZOOMOUT_CURSOR;
+ hotX = 7;
+ hotY = 7;
+ break;
+ default:
+ Q_UNREACHABLE();
+ return false;
+ }
+#else
+ Q_UNREACHABLE();
+ return false;
+#endif
+
+ const gfx::ImageSkia *imageSkia = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resourceId);
+ if (!imageSkia)
+ return false;
+
+ QImage imageQt = toQImage(imageSkia->GetRepresentation(GetScreenInfo().device_scale_factor));
+
+ // Convert hotspot coordinates into device-independent pixels.
+ hotX /= hotspotDpr;
+ hotY /= hotspotDpr;
+
+#if defined(Q_OS_LINUX)
+ // QTBUG-68571: On Linux (xcb, wayland, eglfs), hotspot coordinates must be in physical pixels.
+ qreal imageDpr = imageQt.devicePixelRatio();
+ hotX *= imageDpr;
+ hotY *= imageDpr;
+#endif
+
+ m_delegate->updateCursor(QCursor(QPixmap::fromImage(std::move(imageQt)), qRound(hotX), qRound(hotY)));
+ return true;
+}
+
+void RenderWidgetHostViewQt::UpdateCursor(const ui::Cursor &webCursor)
{
DisplayCursor(webCursor);
}
-void RenderWidgetHostViewQt::DisplayCursor(const content::WebCursor &webCursor)
+void RenderWidgetHostViewQt::DisplayCursor(const ui::Cursor &cursorInfo)
{
- const content::CursorInfo &cursorInfo = webCursor.info();
Qt::CursorShape shape = Qt::ArrowCursor;
-#if defined(USE_AURA)
- ui::CursorType auraType = ui::CursorType::kNull;
-#endif
- switch (cursorInfo.type) {
- case ui::CursorType::kNull:
- case ui::CursorType::kPointer:
+ switch (cursorInfo.type()) {
+ case ui::mojom::CursorType::kNull:
+ case ui::mojom::CursorType::kPointer:
shape = Qt::ArrowCursor;
break;
- case ui::CursorType::kCross:
+ case ui::mojom::CursorType::kCross:
shape = Qt::CrossCursor;
break;
- case ui::CursorType::kHand:
+ case ui::mojom::CursorType::kHand:
shape = Qt::PointingHandCursor;
break;
- case ui::CursorType::kIBeam:
+ case ui::mojom::CursorType::kIBeam:
shape = Qt::IBeamCursor;
break;
- case ui::CursorType::kWait:
+ case ui::mojom::CursorType::kWait:
shape = Qt::WaitCursor;
break;
- case ui::CursorType::kHelp:
+ case ui::mojom::CursorType::kHelp:
shape = Qt::WhatsThisCursor;
break;
- case ui::CursorType::kEastResize:
- case ui::CursorType::kWestResize:
- case ui::CursorType::kEastWestResize:
- case ui::CursorType::kEastPanning:
- case ui::CursorType::kWestPanning:
- case ui::CursorType::kMiddlePanningHorizontal:
+ case ui::mojom::CursorType::kEastResize:
+ case ui::mojom::CursorType::kWestResize:
+ case ui::mojom::CursorType::kEastWestResize:
+ case ui::mojom::CursorType::kEastPanning:
+ case ui::mojom::CursorType::kWestPanning:
+ case ui::mojom::CursorType::kMiddlePanningHorizontal:
shape = Qt::SizeHorCursor;
break;
- case ui::CursorType::kNorthResize:
- case ui::CursorType::kSouthResize:
- case ui::CursorType::kNorthSouthResize:
- case ui::CursorType::kNorthPanning:
- case ui::CursorType::kSouthPanning:
- case ui::CursorType::kMiddlePanningVertical:
+ case ui::mojom::CursorType::kNorthResize:
+ case ui::mojom::CursorType::kSouthResize:
+ case ui::mojom::CursorType::kNorthSouthResize:
+ case ui::mojom::CursorType::kNorthPanning:
+ case ui::mojom::CursorType::kSouthPanning:
+ case ui::mojom::CursorType::kMiddlePanningVertical:
shape = Qt::SizeVerCursor;
break;
- case ui::CursorType::kNorthEastResize:
- case ui::CursorType::kSouthWestResize:
- case ui::CursorType::kNorthEastSouthWestResize:
- case ui::CursorType::kNorthEastPanning:
- case ui::CursorType::kSouthWestPanning:
+ case ui::mojom::CursorType::kNorthEastResize:
+ case ui::mojom::CursorType::kSouthWestResize:
+ case ui::mojom::CursorType::kNorthEastSouthWestResize:
+ case ui::mojom::CursorType::kNorthEastPanning:
+ case ui::mojom::CursorType::kSouthWestPanning:
shape = Qt::SizeBDiagCursor;
break;
- case ui::CursorType::kNorthWestResize:
- case ui::CursorType::kSouthEastResize:
- case ui::CursorType::kNorthWestSouthEastResize:
- case ui::CursorType::kNorthWestPanning:
- case ui::CursorType::kSouthEastPanning:
+ case ui::mojom::CursorType::kNorthWestResize:
+ case ui::mojom::CursorType::kSouthEastResize:
+ case ui::mojom::CursorType::kNorthWestSouthEastResize:
+ case ui::mojom::CursorType::kNorthWestPanning:
+ case ui::mojom::CursorType::kSouthEastPanning:
shape = Qt::SizeFDiagCursor;
break;
- case ui::CursorType::kColumnResize:
+ case ui::mojom::CursorType::kColumnResize:
shape = Qt::SplitHCursor;
break;
- case ui::CursorType::kRowResize:
+ case ui::mojom::CursorType::kRowResize:
shape = Qt::SplitVCursor;
break;
- case ui::CursorType::kMiddlePanning:
- case ui::CursorType::kMove:
+ case ui::mojom::CursorType::kMiddlePanning:
+ case ui::mojom::CursorType::kMove:
shape = Qt::SizeAllCursor;
break;
- case ui::CursorType::kProgress:
+ case ui::mojom::CursorType::kProgress:
shape = Qt::BusyCursor;
break;
- case ui::CursorType::kDndNone:
- case ui::CursorType::kDndMove:
+ case ui::mojom::CursorType::kDndNone:
+ case ui::mojom::CursorType::kDndMove:
shape = Qt::DragMoveCursor;
break;
- case ui::CursorType::kDndCopy:
- case ui::CursorType::kCopy:
+ case ui::mojom::CursorType::kDndCopy:
+ case ui::mojom::CursorType::kCopy:
shape = Qt::DragCopyCursor;
break;
- case ui::CursorType::kDndLink:
- case ui::CursorType::kAlias:
+ case ui::mojom::CursorType::kDndLink:
+ case ui::mojom::CursorType::kAlias:
shape = Qt::DragLinkCursor;
break;
-#if defined(USE_AURA)
- case ui::CursorType::kVerticalText:
- auraType = ui::CursorType::kVerticalText;
- break;
- case ui::CursorType::kCell:
- auraType = ui::CursorType::kCell;
- break;
- case ui::CursorType::kContextMenu:
- auraType = ui::CursorType::kContextMenu;
- break;
- case ui::CursorType::kZoomIn:
- auraType = ui::CursorType::kZoomIn;
- break;
- case ui::CursorType::kZoomOut:
- auraType = ui::CursorType::kZoomOut;
- break;
-#else
- case ui::CursorType::kVerticalText:
- case ui::CursorType::kCell:
- case ui::CursorType::kContextMenu:
- case ui::CursorType::kZoomIn:
- case ui::CursorType::kZoomOut:
- // FIXME: Support on OS X
+ case ui::mojom::CursorType::kVerticalText:
+ case ui::mojom::CursorType::kCell:
+ case ui::mojom::CursorType::kContextMenu:
+ case ui::mojom::CursorType::kZoomIn:
+ case ui::mojom::CursorType::kZoomOut:
+ if (updateCursorFromResource(cursorInfo.type()))
+ return;
break;
-#endif
- case ui::CursorType::kNoDrop:
- case ui::CursorType::kNotAllowed:
+ case ui::mojom::CursorType::kEastWestNoResize:
+ case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
+ case ui::mojom::CursorType::kNorthSouthNoResize:
+ case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
+ // Use forbidden cursor matching webcursor_mac.mm and win_cursor_factory.cc
+ case ui::mojom::CursorType::kNoDrop:
+ case ui::mojom::CursorType::kNotAllowed:
shape = Qt::ForbiddenCursor;
break;
- case ui::CursorType::kNone:
+ case ui::mojom::CursorType::kNone:
shape = Qt::BlankCursor;
break;
- case ui::CursorType::kGrab:
+ case ui::mojom::CursorType::kGrab:
shape = Qt::OpenHandCursor;
break;
- case ui::CursorType::kGrabbing:
+ case ui::mojom::CursorType::kGrabbing:
shape = Qt::ClosedHandCursor;
break;
- case ui::CursorType::kCustom:
- if (cursorInfo.custom_image.colorType() == SkColorType::kN32_SkColorType) {
- QImage cursor = toQImage(cursorInfo.custom_image, QImage::Format_ARGB32);
- m_delegate->updateCursor(QCursor(QPixmap::fromImage(cursor), cursorInfo.hotspot.x(), cursorInfo.hotspot.y()));
+ case ui::mojom::CursorType::kCustom:
+ if (cursorInfo.custom_bitmap().colorType() == SkColorType::kN32_SkColorType) {
+ QImage cursor = toQImage(cursorInfo.custom_bitmap(), QImage::Format_ARGB32);
+ m_delegate->updateCursor(QCursor(QPixmap::fromImage(cursor), cursorInfo.custom_hotspot().x(), cursorInfo.custom_hotspot().y()));
return;
}
break;
}
-#if defined(USE_AURA)
- if (auraType != ui::CursorType::kNull) {
- int resourceId;
- gfx::Point hotspot;
- // GetCursorDataFor only knows hotspots for 1x and 2x cursor images, in physical pixels.
- qreal hotspotDpr = m_screenInfo.device_scale_factor <= 1.0f ? 1.0f : 2.0f;
- if (ui::GetCursorDataFor(ui::CursorSize::kNormal, auraType, hotspotDpr, &resourceId, &hotspot)) {
- if (const gfx::ImageSkia *imageSkia = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resourceId)) {
- QImage imageQt = toQImage(imageSkia->GetRepresentation(m_screenInfo.device_scale_factor));
-
- // Convert hotspot coordinates into device-independent pixels.
- qreal hotX = hotspot.x() / hotspotDpr;
- qreal hotY = hotspot.y() / hotspotDpr;
-
-#if defined(Q_OS_LINUX)
- // QTBUG-68571: On Linux (xcb, wayland, eglfs), hotspot coordinates must be in physical pixels.
- qreal imageDpr = imageQt.devicePixelRatio();
- hotX *= imageDpr;
- hotY *= imageDpr;
-#endif
-
- m_delegate->updateCursor(QCursor(QPixmap::fromImage(std::move(imageQt)), qRound(hotX), qRound(hotY)));
- return;
- }
- }
- }
-#endif
m_delegate->updateCursor(QCursor(shape));
}
+content::CursorManager *RenderWidgetHostViewQt::GetCursorManager()
+{
+ return m_cursorManager.get();
+}
+
void RenderWidgetHostViewQt::SetIsLoading(bool)
{
// We use WebContentsDelegateQt::LoadingStateChanged to notify about loading state.
@@ -514,7 +615,9 @@ void RenderWidgetHostViewQt::ImeCancelComposition()
qApp->inputMethod()->reset();
}
-void RenderWidgetHostViewQt::ImeCompositionRangeChanged(const gfx::Range&, const std::vector<gfx::Rect>&)
+void RenderWidgetHostViewQt::ImeCompositionRangeChanged(const gfx::Range &,
+ const absl::optional<std::vector<gfx::Rect>> &,
+ const absl::optional<std::vector<gfx::Rect>> &)
{
// FIXME: not implemented?
QT_NOT_YET_IMPLEMENTED
@@ -525,37 +628,32 @@ void RenderWidgetHostViewQt::RenderProcessGone()
Destroy();
}
-void RenderWidgetHostViewQt::Destroy()
+bool RenderWidgetHostViewQt::TransformPointToCoordSpaceForView(const gfx::PointF &point,
+ content::RenderWidgetHostViewBase *target_view,
+ gfx::PointF *transformed_point)
{
- delete this;
-}
-
-void RenderWidgetHostViewQt::SetTooltipText(const base::string16 &tooltip_text)
-{
- DisplayTooltipText(tooltip_text);
-}
+ if (target_view == this) {
+ *transformed_point = point;
+ return true;
+ }
-void RenderWidgetHostViewQt::DisplayTooltipText(const base::string16 &tooltip_text)
-{
- if (m_adapterClient)
- m_adapterClient->setToolTip(toQt(tooltip_text));
+ return target_view->TransformPointToLocalCoordSpace(point, GetCurrentSurfaceId(), transformed_point);
}
-void RenderWidgetHostViewQt::DidCreateNewRendererCompositorFrameSink(viz::mojom::CompositorFrameSinkClient *frameSinkClient)
+void RenderWidgetHostViewQt::Destroy()
{
- // Not used with viz
- NOTREACHED();
+ delete this;
}
-void RenderWidgetHostViewQt::SubmitCompositorFrame(const viz::LocalSurfaceId &local_surface_id, viz::CompositorFrame frame, base::Optional<viz::HitTestRegionList> hit_test_region_list)
+void RenderWidgetHostViewQt::UpdateTooltipUnderCursor(const std::u16string &tooltip_text)
{
- // Not used with viz
- NOTREACHED();
+ UpdateTooltip(tooltip_text);
}
-void RenderWidgetHostViewQt::GetScreenInfo(content::ScreenInfo *results)
+void RenderWidgetHostViewQt::UpdateTooltip(const std::u16string &tooltip_text)
{
- *results = m_screenInfo;
+ if (host()->delegate() && m_adapterClient)
+ m_adapterClient->setToolTip(toQt(tooltip_text));
}
gfx::Rect RenderWidgetHostViewQt::GetBoundsInRootWindow()
@@ -569,31 +667,29 @@ void RenderWidgetHostViewQt::OnUpdateTextInputStateCalled(content::TextInputMana
Q_UNUSED(updated_view);
Q_UNUSED(did_update_state);
- const content::TextInputState *state = text_input_manager_->GetTextInputState();
+ const ui::mojom::TextInputState *state = text_input_manager_->GetTextInputState();
if (!state) {
- m_delegate->inputMethodStateChanged(false /*editorVisible*/, false /*passwordInput*/);
- m_delegate->setInputMethodHints(Qt::ImhNone);
+ // Do not reset input method state here because an editable node might be still focused and
+ // this would hide the virtual keyboard if a child of the focused node is removed.
return;
}
ui::TextInputType type = getTextInputType();
-#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
m_delegate->setInputMethodHints(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText | Qt::ImhNoTextHandles | Qt::ImhNoEditMenu);
-#else
- m_delegate->setInputMethodHints(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText);
-#endif
QString surroundingText = toQt(state->value);
// Remove IME composition text from the surrounding text
- if (state->composition_start != -1 && state->composition_end != -1)
- surroundingText.remove(state->composition_start,
- state->composition_end - state->composition_start);
+ if (state->composition.has_value())
+ surroundingText.remove(state->composition->start(),
+ state->composition->end() - state->composition->start());
delegateClient()->setSurroundingText(surroundingText);
// In case of text selection, the update is expected in RenderWidgetHostViewQt::selectionChanged().
if (GetSelectedText().empty()) {
- // At this point it is unknown whether the text input state has been updated due to a text selection.
- // Keep the cursor position updated for cursor movements too.
- delegateClient()->setCursorPosition(state->selection_start);
+ if (state->composition.has_value()) {
+ delegateClient()->setCursorPosition(state->composition->start());
+ } else {
+ delegateClient()->setCursorPosition(state->selection.start());
+ }
m_delegate->inputMethodStateChanged(type != ui::TEXT_INPUT_TYPE_NONE, type == ui::TEXT_INPUT_TYPE_PASSWORD);
}
@@ -603,7 +699,7 @@ void RenderWidgetHostViewQt::OnUpdateTextInputStateCalled(content::TextInputMana
}
// Ignore selection change triggered by ime composition unless it clears an actual text selection
- if (state->composition_start != -1 && delegateClient()->isPreviousSelectionEmpty()) {
+ if (state->composition.has_value() && delegateClient()->isPreviousSelectionEmpty()) {
m_imState = 0;
return;
}
@@ -630,15 +726,22 @@ void RenderWidgetHostViewQt::OnTextSelectionChanged(content::TextInputManager *t
Q_UNUSED(text_input_manager);
Q_UNUSED(updated_view);
- const content::TextInputManager::TextSelection *selection = GetTextInputManager()->GetTextSelection(updated_view);
- if (!selection)
- return;
+ // We obtain the TextSelection from focused RWH which is obtained from the
+ // frame tree.
+ content::RenderWidgetHostViewBase *focused_view =
+ GetFocusedWidget() ? GetFocusedWidget()->GetView() : nullptr;
+
+ if (!focused_view)
+ return;
#if defined(USE_OZONE)
- if (!selection->selected_text().empty() && selection->user_initiated()) {
- // Set the CLIPBOARD_TYPE_SELECTION to the ui::Clipboard.
- ui::ScopedClipboardWriter clipboard_writer(ui::ClipboardBuffer::kSelection);
- clipboard_writer.WriteText(selection->selected_text());
+ if (ui::Clipboard::IsSupportedClipboardBuffer(ui::ClipboardBuffer::kSelection)) {
+ const content::TextInputManager::TextSelection *selection = GetTextInputManager()->GetTextSelection(focused_view);
+ if (selection->selected_text().length() && selection->user_initiated()) {
+ // Set the ClipboardBuffer::kSelection to the ui::Clipboard.
+ ui::ScopedClipboardWriter clipboard_writer(ui::ClipboardBuffer::kSelection);
+ clipboard_writer.WriteText(selection->selected_text());
+ }
}
#endif // defined(USE_OZONE)
@@ -662,16 +765,16 @@ void RenderWidgetHostViewQt::OnGestureEvent(const ui::GestureEventData& gesture)
if (m_touchSelectionController && m_touchSelectionControllerClient) {
switch (event.GetType()) {
- case blink::WebInputEvent::kGestureLongPress:
+ case blink::WebInputEvent::Type::kGestureLongPress:
m_touchSelectionController->HandleLongPressEvent(event.TimeStamp(), event.PositionInWidget());
break;
- case blink::WebInputEvent::kGestureTap:
+ case blink::WebInputEvent::Type::kGestureTap:
m_touchSelectionController->HandleTapEvent(event.PositionInWidget(), event.data.tap.tap_count);
break;
- case blink::WebInputEvent::kGestureScrollBegin:
+ case blink::WebInputEvent::Type::kGestureScrollBegin:
m_touchSelectionControllerClient->onScrollBegin();
break;
- case blink::WebInputEvent::kGestureScrollEnd:
+ case blink::WebInputEvent::Type::kGestureScrollEnd:
m_touchSelectionControllerClient->onScrollEnd();
break;
default:
@@ -679,7 +782,8 @@ void RenderWidgetHostViewQt::OnGestureEvent(const ui::GestureEventData& gesture)
}
}
- host()->ForwardGestureEvent(event);
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter())
+ host()->delegate()->GetInputEventRouter()->RouteGestureEvent(this, &event, ui::LatencyInfo());
}
void RenderWidgetHostViewQt::DidStopFlinging()
@@ -697,12 +801,7 @@ viz::ScopedSurfaceIdAllocator RenderWidgetHostViewQt::DidUpdateVisualProperties(
void RenderWidgetHostViewQt::OnDidUpdateVisualPropertiesComplete(const cc::RenderFrameMetadata &metadata)
{
- synchronizeVisualProperties(metadata.local_surface_id_allocation);
-}
-
-void RenderWidgetHostViewQt::OnDidFirstVisuallyNonEmptyPaint()
-{
- m_adapterClient->didFirstVisuallyNonEmptyPaint();
+ synchronizeVisualProperties(metadata.local_surface_id);
}
Compositor::Id RenderWidgetHostViewQt::compositorId()
@@ -713,17 +812,18 @@ Compositor::Id RenderWidgetHostViewQt::compositorId()
void RenderWidgetHostViewQt::notifyShown()
{
// Handle possible frame eviction:
- if (!m_dfhLocalSurfaceIdAllocator.HasValidLocalSurfaceIdAllocation())
+ if (!m_dfhLocalSurfaceIdAllocator.HasValidLocalSurfaceId())
m_dfhLocalSurfaceIdAllocator.GenerateId();
if (m_visible)
return;
m_visible = true;
- host()->WasShown(base::nullopt);
+ host()->WasShown(nullptr);
m_delegatedFrameHost->AttachToCompositor(m_uiCompositor.get());
- m_delegatedFrameHost->WasShown(GetLocalSurfaceIdAllocation().local_surface_id(),
- toGfx(delegateClient()->viewRectInDips().size()), base::nullopt);
+ m_delegatedFrameHost->WasShown(GetLocalSurfaceId(),
+ toGfx(delegateClient()->viewRectInDips().size()),
+ nullptr);
}
void RenderWidgetHostViewQt::notifyHidden()
@@ -736,10 +836,11 @@ void RenderWidgetHostViewQt::notifyHidden()
m_delegatedFrameHost->DetachFromCompositor();
}
-void RenderWidgetHostViewQt::ProcessAckedTouchEvent(const content::TouchEventWithLatencyInfo &touch, content::InputEventAckState ack_result) {
- Q_UNUSED(touch);
- const bool eventConsumed = ack_result == content::INPUT_EVENT_ACK_STATE_CONSUMED;
- m_gestureProvider.OnTouchEventAck(touch.event.unique_touch_event_id, eventConsumed, /*fixme: ?? */false);
+void RenderWidgetHostViewQt::ProcessAckedTouchEvent(const content::TouchEventWithLatencyInfo &touch, blink::mojom::InputEventResultState ack_result)
+{
+ const bool eventConsumed = (ack_result == blink::mojom::InputEventResultState::kConsumed);
+ const bool isSetBlocking = content::InputEventResultStateIsSetBlocking(ack_result);
+ m_gestureProvider.OnTouchEventAck(touch.event.unique_touch_event_id, eventConsumed, isSetBlocking);
}
void RenderWidgetHostViewQt::processMotionEvent(const ui::MotionEvent &motionEvent)
@@ -747,11 +848,11 @@ void RenderWidgetHostViewQt::processMotionEvent(const ui::MotionEvent &motionEve
auto result = m_gestureProvider.OnTouchEvent(motionEvent);
if (!result.succeeded)
return;
-
blink::WebTouchEvent touchEvent = ui::CreateWebTouchEventFromMotionEvent(motionEvent,
result.moved_beyond_slop_region,
false /*hovering, FIXME ?*/);
- host()->ForwardTouchEventWithLatencyInfo(touchEvent, CreateLatencyInfo(touchEvent));
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter())
+ host()->delegate()->GetInputEventRouter()->RouteTouchEvent(this, &touchEvent, CreateLatencyInfo(touchEvent));
}
bool RenderWidgetHostViewQt::isPopup() const
@@ -761,21 +862,17 @@ bool RenderWidgetHostViewQt::isPopup() const
bool RenderWidgetHostViewQt::updateScreenInfo()
{
- content::ScreenInfo oldScreenInfo = m_screenInfo;
- QScreen *screen = m_delegate->window() ? m_delegate->window()->screen() : nullptr;
-
- if (screen) {
- m_screenInfo.device_scale_factor = screen->devicePixelRatio();
- m_screenInfo.depth_per_component = 8;
- m_screenInfo.depth = screen->depth();
- m_screenInfo.is_monochrome = (m_screenInfo.depth == 1);
- m_screenInfo.rect = toGfx(screen->geometry());
- m_screenInfo.available_rect = toGfx(screen->availableGeometry());
- } else {
- m_screenInfo.device_scale_factor = qGuiApp->devicePixelRatio();
- }
- return (m_screenInfo != oldScreenInfo);
+ QWindow *window = m_delegate->Window();
+ if (!window)
+ return false;
+
+ display::ScreenInfos newScreenInfos = screenInfosFromQtForUpdate(window->screen());
+ if (screen_infos_ == newScreenInfos)
+ return false;
+
+ screen_infos_ = std::move(newScreenInfos);
+ return true;
}
void RenderWidgetHostViewQt::handleWheelEvent(QWheelEvent *event)
@@ -784,8 +881,9 @@ void RenderWidgetHostViewQt::handleWheelEvent(QWheelEvent *event)
Q_ASSERT(m_pendingWheelEvents.isEmpty());
blink::WebMouseWheelEvent webEvent = WebEventFactory::toWebWheelEvent(event);
m_wheelAckPending = (webEvent.phase != blink::WebMouseWheelEvent::kPhaseEnded);
- GetMouseWheelPhaseHandler()->AddPhaseIfNeededAndScheduleEndEvent(webEvent, false);
- host()->ForwardWheelEvent(webEvent);
+ GetMouseWheelPhaseHandler()->AddPhaseIfNeededAndScheduleEndEvent(webEvent, true);
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter())
+ host()->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(this, &webEvent, ui::LatencyInfo());
return;
}
if (!m_pendingWheelEvents.isEmpty()) {
@@ -796,7 +894,7 @@ void RenderWidgetHostViewQt::handleWheelEvent(QWheelEvent *event)
m_pendingWheelEvents.append(WebEventFactory::toWebWheelEvent(event));
}
-void RenderWidgetHostViewQt::WheelEventAck(const blink::WebMouseWheelEvent &event, content::InputEventAckState /*ack_result*/)
+void RenderWidgetHostViewQt::WheelEventAck(const blink::WebMouseWheelEvent &event, blink::mojom::InputEventResultState /*ack_result*/)
{
if (event.phase == blink::WebMouseWheelEvent::kPhaseEnded)
return;
@@ -805,19 +903,22 @@ void RenderWidgetHostViewQt::WheelEventAck(const blink::WebMouseWheelEvent &even
while (!m_pendingWheelEvents.isEmpty() && !m_wheelAckPending) {
blink::WebMouseWheelEvent webEvent = m_pendingWheelEvents.takeFirst();
m_wheelAckPending = (webEvent.phase != blink::WebMouseWheelEvent::kPhaseEnded);
- m_mouseWheelPhaseHandler.AddPhaseIfNeededAndScheduleEndEvent(webEvent, false);
- host()->ForwardWheelEvent(webEvent);
+ m_mouseWheelPhaseHandler.AddPhaseIfNeededAndScheduleEndEvent(webEvent, true);
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter())
+ host()->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(this, &webEvent, ui::LatencyInfo());
}
}
-void RenderWidgetHostViewQt::GestureEventAck(const blink::WebGestureEvent &event, content::InputEventAckState ack_result)
+void RenderWidgetHostViewQt::GestureEventAck(const blink::WebGestureEvent &event,
+ blink::mojom::InputEventResultState ack_result,
+ blink::mojom::ScrollResultDataPtr scroll_result_data)
{
// Forward unhandled scroll events back as wheel events
- if (event.GetType() != blink::WebInputEvent::kGestureScrollUpdate)
+ if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollUpdate)
return;
switch (ack_result) {
- case content::INPUT_EVENT_ACK_STATE_NOT_CONSUMED:
- case content::INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS:
+ case blink::mojom::InputEventResultState::kNotConsumed:
+ case blink::mojom::InputEventResultState::kNoConsumerExists:
WebEventFactory::sendUnhandledWheelEvent(event, delegate());
break;
default:
@@ -830,32 +931,13 @@ content::MouseWheelPhaseHandler *RenderWidgetHostViewQt::GetMouseWheelPhaseHandl
return &m_mouseWheelPhaseHandler;
}
-void RenderWidgetHostViewQt::SetNeedsBeginFrames(bool needs_begin_frames)
+blink::mojom::FrameWidgetInputHandler *RenderWidgetHostViewQt::getFrameWidgetInputHandler()
{
- // Not used with viz
- NOTREACHED();
-}
-
-content::RenderFrameHost *RenderWidgetHostViewQt::getFocusedFrameHost()
-{
- content::RenderViewHostImpl *viewHost = content::RenderViewHostImpl::From(host());
- if (!viewHost)
+ auto *focused_widget = GetFocusedWidget();
+ if (!focused_widget)
return nullptr;
- content::FrameTreeNode *focusedFrame = viewHost->GetDelegate()->GetFrameTree()->GetFocusedFrame();
- if (!focusedFrame)
- return nullptr;
-
- return focusedFrame->current_frame_host();
-}
-
-content::mojom::FrameInputHandler *RenderWidgetHostViewQt::getFrameInputHandler()
-{
- content::RenderFrameHostImpl *frameHost = static_cast<content::RenderFrameHostImpl *>(getFocusedFrameHost());
- if (!frameHost)
- return nullptr;
-
- return frameHost->GetFrameInputHandler();
+ return focused_widget->GetFrameWidgetInputHandler();
}
ui::TextInputType RenderWidgetHostViewQt::getTextInputType() const
@@ -866,11 +948,6 @@ ui::TextInputType RenderWidgetHostViewQt::getTextInputType() const
return ui::TEXT_INPUT_TYPE_NONE;
}
-void RenderWidgetHostViewQt::SetWantsAnimateOnlyBeginFrames()
-{
- m_delegatedFrameHost->SetWantsAnimateOnlyBeginFrames();
-}
-
viz::SurfaceId RenderWidgetHostViewQt::GetCurrentSurfaceId() const
{
return m_delegatedFrameHost->GetCurrentSurfaceId();
@@ -881,20 +958,32 @@ const viz::FrameSinkId &RenderWidgetHostViewQt::GetFrameSinkId() const
return m_delegatedFrameHost->frame_sink_id();
}
-const viz::LocalSurfaceIdAllocation &RenderWidgetHostViewQt::GetLocalSurfaceIdAllocation() const
+const viz::LocalSurfaceId &RenderWidgetHostViewQt::GetLocalSurfaceId() const
+{
+ return m_dfhLocalSurfaceIdAllocator.GetCurrentLocalSurfaceId();
+}
+
+void RenderWidgetHostViewQt::FocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_screen)
{
- return m_dfhLocalSurfaceIdAllocator.GetCurrentLocalSurfaceIdAllocation();
+ Q_UNUSED(node_bounds_in_screen);
+ if (!is_editable_node) {
+ m_delegate->inputMethodStateChanged(false /*editorVisible*/, false /*passwordInput*/);
+ m_delegate->setInputMethodHints(Qt::ImhNone);
+ }
+}
+
+base::flat_map<std::string, std::string> RenderWidgetHostViewQt::GetKeyboardLayoutMap()
+{
+ return ui::GenerateDomKeyboardLayoutMap();
}
void RenderWidgetHostViewQt::TakeFallbackContentFrom(content::RenderWidgetHostView *view)
{
DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewQt *viewQt = static_cast<RenderWidgetHostViewQt *>(view);
- base::Optional<SkColor> color = viewQt->GetBackgroundColor();
- if (color)
- SetBackgroundColor(*color);
+ CopyBackgroundColorIfPresentFrom(*viewQt);
+
m_delegatedFrameHost->TakeFallbackContentFrom(viewQt->m_delegatedFrameHost.get());
- host()->GetContentRenderingTimeoutFrom(viewQt->host());
}
void RenderWidgetHostViewQt::EnsureSurfaceSynchronizedForWebTest()
@@ -911,10 +1000,9 @@ void RenderWidgetHostViewQt::ResetFallbackToFirstNavigationSurface()
{
}
-void RenderWidgetHostViewQt::OnRenderFrameMetadataChangedAfterActivation()
+void RenderWidgetHostViewQt::OnRenderFrameMetadataChangedAfterActivation(base::TimeTicks activation_time)
{
- content::RenderWidgetHostViewBase::OnRenderFrameMetadataChangedAfterActivation();
-
+ Q_UNUSED(activation_time);
const cc::RenderFrameMetadata &metadata = host()->render_frame_metadata_provider()->LastRenderFrameMetadata();
if (metadata.selection.start != m_selectionStart || metadata.selection.end != m_selectionEnd) {
m_selectionStart = metadata.selection.start;
@@ -922,17 +1010,22 @@ void RenderWidgetHostViewQt::OnRenderFrameMetadataChangedAfterActivation()
m_touchSelectionControllerClient->UpdateClientSelectionBounds(m_selectionStart, m_selectionEnd);
}
- gfx::Vector2dF scrollOffset = metadata.root_scroll_offset.value_or(gfx::Vector2dF());
- gfx::SizeF contentsSize = metadata.root_layer_size;
+ gfx::PointF scrollOffset = gfx::PointF();
+ if (metadata.root_scroll_offset.has_value())
+ scrollOffset = gfx::ScalePoint(metadata.root_scroll_offset.value(),
+ 1 / metadata.device_scale_factor);
std::swap(m_lastScrollOffset, scrollOffset);
- std::swap(m_lastContentsSize, contentsSize);
if (m_adapterClient && scrollOffset != m_lastScrollOffset)
m_adapterClient->updateScrollPosition(toQt(m_lastScrollOffset));
+
+ gfx::SizeF contentsSize =
+ gfx::ScaleSize(metadata.root_layer_size, 1 / metadata.device_scale_factor);
+ std::swap(m_lastContentsSize, contentsSize);
if (m_adapterClient && contentsSize != m_lastContentsSize)
m_adapterClient->updateContentsSize(toQt(m_lastContentsSize));
}
-void RenderWidgetHostViewQt::synchronizeVisualProperties(const base::Optional<viz::LocalSurfaceIdAllocation> &childSurfaceId)
+void RenderWidgetHostViewQt::synchronizeVisualProperties(const absl::optional<viz::LocalSurfaceId> &childSurfaceId)
{
if (childSurfaceId)
m_dfhLocalSurfaceIdAllocator.UpdateFromChild(*childSurfaceId);
@@ -944,17 +1037,28 @@ void RenderWidgetHostViewQt::synchronizeVisualProperties(const base::Optional<vi
m_rootLayer->SetBounds(gfx::Rect(gfx::Point(), viewSizeInPixels));
m_uiCompositorLocalSurfaceIdAllocator.GenerateId();
m_uiCompositor->SetScaleAndSize(
- m_screenInfo.device_scale_factor,
+ GetScreenInfo().device_scale_factor,
viewSizeInPixels,
- m_uiCompositorLocalSurfaceIdAllocator.GetCurrentLocalSurfaceIdAllocation());
+ m_uiCompositorLocalSurfaceIdAllocator.GetCurrentLocalSurfaceId());
m_delegatedFrameHost->EmbedSurface(
- m_dfhLocalSurfaceIdAllocator.GetCurrentLocalSurfaceIdAllocation().local_surface_id(),
+ m_dfhLocalSurfaceIdAllocator.GetCurrentLocalSurfaceId(),
viewSizeInDips,
cc::DeadlinePolicy::UseDefaultDeadline());
host()->SynchronizeVisualProperties();
}
+void RenderWidgetHostViewQt::resetTouchSelectionController()
+{
+ Q_ASSERT(m_touchSelectionControllerClient);
+ m_touchSelectionControllerClient->resetControls();
+ ui::TouchSelectionController::Config config;
+ config.max_tap_duration = base::Milliseconds(ui::GestureConfiguration::GetInstance()->long_press_time_in_ms());
+ config.tap_slop = ui::GestureConfiguration::GetInstance()->max_touch_move_in_pixels_for_click();
+ config.enable_longpress_drag_selection = false;
+ m_touchSelectionController.reset(new ui::TouchSelectionController(m_touchSelectionControllerClient.get(), config));
+}
+
std::unique_ptr<content::SyntheticGestureTarget> RenderWidgetHostViewQt::CreateSyntheticGestureTarget()
{
return nullptr;
@@ -965,4 +1069,14 @@ ui::Compositor *RenderWidgetHostViewQt::GetCompositor()
return m_uiCompositor.get();
}
+absl::optional<content::DisplayFeature> RenderWidgetHostViewQt::GetDisplayFeature()
+{
+ return absl::nullopt;
+}
+
+void RenderWidgetHostViewQt::SetDisplayFeatureForTesting(const content::DisplayFeature *)
+{
+ NOTIMPLEMENTED();
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/render_widget_host_view_qt.h b/src/core/render_widget_host_view_qt.h
index 7ed01f424..a55e04dd8 100644
--- a/src/core/render_widget_host_view_qt.h
+++ b/src/core/render_widget_host_view_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef RENDER_WIDGET_HOST_VIEW_QT_H
#define RENDER_WIDGET_HOST_VIEW_QT_H
@@ -48,22 +12,16 @@
#include "components/viz/common/resources/transferable_resource.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "components/viz/host/host_frame_sink_client.h"
-#include "content/browser/accessibility/browser_accessibility_manager.h"
+#include "content/browser/accessibility/web_contents_accessibility.h"
#include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "ui/events/gesture_detection/filtered_gesture_provider.h"
-QT_BEGIN_NAMESPACE
-class QAccessibleInterface;
-QT_END_NAMESPACE
-
namespace content {
class RenderFrameHost;
class RenderWidgetHostImpl;
-namespace mojom {
-class FrameInputHandler;
-}
+class WebContents;
}
namespace ui {
@@ -73,7 +31,9 @@ class TouchSelectionController;
namespace QtWebEngineCore {
class RenderWidgetHostViewQtDelegateClient;
+class InputEventObserverQt;
class TouchSelectionControllerClientQt;
+class WebContentsAccessibilityQt;
class WebContentsAdapterClient;
class RenderWidgetHostViewQt
@@ -81,6 +41,8 @@ class RenderWidgetHostViewQt
, public ui::GestureProviderClient
, public base::SupportsWeakPtr<RenderWidgetHostViewQt>
, public content::TextInputManager::Observer
+ , public content::RenderFrameMetadataProvider::Observer
+ , public content::RenderWidgetHost::InputEventObserver
{
public:
RenderWidgetHostViewQt(content::RenderWidgetHost* widget);
@@ -92,52 +54,63 @@ public:
void setAdapterClient(WebContentsAdapterClient *adapterClient);
RenderWidgetHostViewQtDelegateClient *delegateClient() const { return m_delegateClient.get(); }
+ // Overridden from RenderWidgetHostView:
void InitAsChild(gfx::NativeView) override;
- void InitAsPopup(content::RenderWidgetHostView*, const gfx::Rect&) override;
- void InitAsFullscreen(content::RenderWidgetHostView*) override;
+ void InitAsPopup(content::RenderWidgetHostView*, const gfx::Rect&, const gfx::Rect&) override;
void SetSize(const gfx::Size& size) override;
void SetBounds(const gfx::Rect&) override;
gfx::NativeView GetNativeView() override;
- gfx::NativeViewAccessible GetNativeViewAccessible() override;
+ gfx::NativeViewAccessible GetNativeViewAccessible() override { return nullptr; }
void Focus() override;
bool HasFocus() override;
bool IsMouseLocked() override;
+ viz::FrameSinkId GetRootFrameSinkId() override;
bool IsSurfaceAvailableForCopy() override;
void CopyFromSurface(const gfx::Rect &src_rect,
const gfx::Size &output_size,
base::OnceCallback<void(const SkBitmap &)> callback) override;
- void Show() override;
+ void ShowWithVisibility(content::PageVisibilityState page_visibility) override;
void Hide() override;
bool IsShowing() override;
gfx::Rect GetViewBounds() override;
void UpdateBackgroundColor() override;
- bool LockMouse(bool) override;
+ blink::mojom::PointerLockResult LockMouse(bool) override;
+ blink::mojom::PointerLockResult ChangeMouseLock(bool) override;
void UnlockMouse() override;
- void UpdateCursor(const content::WebCursor&) override;
- void DisplayCursor(const content::WebCursor&) override;
+ void UpdateCursor(const ui::Cursor&) override;
+ void DisplayCursor(const ui::Cursor&) override;
+ content::CursorManager *GetCursorManager() override;
void SetIsLoading(bool) override;
void ImeCancelComposition() override;
- void ImeCompositionRangeChanged(const gfx::Range&, const std::vector<gfx::Rect>&) override;
+ void ImeCompositionRangeChanged(const gfx::Range &,
+ const absl::optional<std::vector<gfx::Rect>> &,
+ const absl::optional<std::vector<gfx::Rect>> &) override;
void RenderProcessGone() override;
+ bool TransformPointToCoordSpaceForView(const gfx::PointF &point,
+ content::RenderWidgetHostViewBase *target_view,
+ gfx::PointF *transformed_point) override;
void Destroy() override;
- void SetTooltipText(const base::string16 &tooltip_text) override;
- void DisplayTooltipText(const base::string16& tooltip_text) override;
- void DidCreateNewRendererCompositorFrameSink(viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink) override;
- void SubmitCompositorFrame(const viz::LocalSurfaceId&, viz::CompositorFrame, base::Optional<viz::HitTestRegionList>) override;
- void WheelEventAck(const blink::WebMouseWheelEvent &event, content::InputEventAckState ack_result) override;
- void GestureEventAck(const blink::WebGestureEvent &event, content::InputEventAckState ack_result) override;
+ void UpdateTooltipUnderCursor(const std::u16string &tooltip_text) override;
+ void UpdateTooltip(const std::u16string& tooltip_text) override;
+ void WheelEventAck(const blink::WebMouseWheelEvent &event,
+ blink::mojom::InputEventResultState ack_result) override;
+ void GestureEventAck(const blink::WebGestureEvent &event,
+ blink::mojom::InputEventResultState ack_result,
+ blink::mojom::ScrollResultDataPtr scroll_result_data) override;
content::MouseWheelPhaseHandler *GetMouseWheelPhaseHandler() override;
viz::ScopedSurfaceIdAllocator DidUpdateVisualProperties(const cc::RenderFrameMetadata &metadata) override;
void OnDidUpdateVisualPropertiesComplete(const cc::RenderFrameMetadata &metadata);
- void GetScreenInfo(content::ScreenInfo *results) override;
+ // Overridden from RenderWidgetHostViewBase:
gfx::Rect GetBoundsInRootWindow() override;
- void ProcessAckedTouchEvent(const content::TouchEventWithLatencyInfo &touch, content::InputEventAckState ack_result) override;
- void SetNeedsBeginFrames(bool needs_begin_frames) override;
- void SetWantsAnimateOnlyBeginFrames() override;
+ void ProcessAckedTouchEvent(const content::TouchEventWithLatencyInfo &touch,
+ blink::mojom::InputEventResultState ack_result) override;
viz::SurfaceId GetCurrentSurfaceId() const override;
const viz::FrameSinkId &GetFrameSinkId() const override;
- const viz::LocalSurfaceIdAllocation &GetLocalSurfaceIdAllocation() const override;
+ const viz::LocalSurfaceId &GetLocalSurfaceId() const override;
+ void FocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_screen) override;
+ base::flat_map<std::string, std::string> GetKeyboardLayoutMap() override;
+
void TakeFallbackContentFrom(content::RenderWidgetHostView *view) override;
void EnsureSurfaceSynchronizedForWebTest() override;
uint32_t GetCaptureSequenceNumber() const override;
@@ -145,11 +118,25 @@ public:
void DidStopFlinging() override;
std::unique_ptr<content::SyntheticGestureTarget> CreateSyntheticGestureTarget() override;
ui::Compositor *GetCompositor() override;
-#if defined(OS_MACOSX)
+ absl::optional<content::DisplayFeature> GetDisplayFeature() override;
+ void SetDisplayFeatureForTesting(const content::DisplayFeature*) override;
+ content::WebContentsAccessibility *GetWebContentsAccessibility() override;
+#if BUILDFLAG(IS_MAC)
+ void ShowSharePicker(
+ const std::string &title,
+ const std::string &text,
+ const std::string &url,
+ const std::vector<std::string> &file_paths,
+ blink::mojom::ShareService::ShareCallback callback) override { QT_NOT_YET_IMPLEMENTED }
void SetActive(bool active) override { QT_NOT_YET_IMPLEMENTED }
void SpeakSelection() override { QT_NOT_YET_IMPLEMENTED }
void ShowDefinitionForSelection() override { QT_NOT_YET_IMPLEMENTED }
-#endif // defined(OS_MACOSX)
+ void SetWindowFrameInScreen(const gfx::Rect&) override { QT_NOT_YET_IMPLEMENTED }
+#endif // BUILDFLAG(IS_MAC)
+ void NotifyHostAndDelegateOnWasShown(blink::mojom::RecordContentToVisibleTimeRequestPtr) override { QT_NOT_YET_IMPLEMENTED }
+ void RequestSuccessfulPresentationTimeFromHostOrDelegate(blink::mojom::RecordContentToVisibleTimeRequestPtr) override {}
+ void CancelSuccessfulPresentationTimeRequestForHostAndDelegate() override {}
+ void InvalidateLocalSurfaceIdAndAllocationGroup() override {}
// Overridden from ui::GestureProviderClient.
void OnGestureEvent(const ui::GestureEventData& gesture) override;
@@ -159,11 +146,19 @@ public:
void OnSelectionBoundsChanged(content::TextInputManager *text_input_manager, RenderWidgetHostViewBase *updated_view) override;
void OnTextSelectionChanged(content::TextInputManager *text_input_manager, RenderWidgetHostViewBase *updated_view) override;
- // Overridden from content::BrowserAccessibilityDelegate
- content::BrowserAccessibilityManager* CreateBrowserAccessibilityManager(content::BrowserAccessibilityDelegate* delegate, bool for_root_frame) override;
-
// Overridden from content::RenderFrameMetadataProvider::Observer
- void OnRenderFrameMetadataChangedAfterActivation() override;
+ void OnRenderFrameMetadataChangedAfterActivation(base::TimeTicks activation_time) override;
+ void OnRenderFrameMetadataChangedBeforeActivation(const cc::RenderFrameMetadata &) override {}
+ void OnRenderFrameSubmission() override {}
+ void OnLocalSurfaceIdChanged(const cc::RenderFrameMetadata &) override {}
+
+ // Overridden from content::RenderWidgetHost::InputEventObserver
+ void OnInputEvent(const blink::WebInputEvent &) override { }
+ void OnInputEventAck(blink::mojom::InputEventResultSource,
+ blink::mojom::InputEventResultState state,
+ const blink::WebInputEvent &event) override;
+
+ static void registerInputEventObserver(content::WebContents *, content::RenderFrameHost *);
// Called from RenderWidgetHostViewQtDelegateClient.
Compositor::Id compositorId();
@@ -174,45 +169,49 @@ public:
void processMotionEvent(const ui::MotionEvent &motionEvent);
void resetInputManagerState() { m_imState = 0; }
- // Called from WebContentsDelegateQt.
- void OnDidFirstVisuallyNonEmptyPaint();
-
// Called from WebContentsAdapter.
gfx::SizeF lastContentsSize() const { return m_lastContentsSize; }
- gfx::Vector2dF lastScrollOffset() const { return m_lastScrollOffset; }
-
- ui::TextInputType getTextInputType() const;
- content::mojom::FrameInputHandler *getFrameInputHandler();
+ gfx::PointF lastScrollOffset() const { return m_lastScrollOffset; }
ui::TouchSelectionController *getTouchSelectionController() const { return m_touchSelectionController.get(); }
TouchSelectionControllerClientQt *getTouchSelectionControllerClient() const { return m_touchSelectionControllerClient.get(); }
+ blink::mojom::FrameWidgetInputHandler *getFrameWidgetInputHandler();
+ ui::TextInputType getTextInputType() const;
void synchronizeVisualProperties(
- const base::Optional<viz::LocalSurfaceIdAllocation> &childSurfaceId);
+ const absl::optional<viz::LocalSurfaceId> &childSurfaceId);
+
+ void resetTouchSelectionController();
private:
friend class DelegatedFrameHostClientQt;
+ friend class WebContentsAccessibilityQt;
bool isPopup() const;
- content::RenderFrameHost *getFocusedFrameHost();
+
+ bool updateCursorFromResource(ui::mojom::CursorType type);
scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner;
+
+ std::unique_ptr<content::CursorManager> m_cursorManager;
+
ui::FilteredGestureProvider m_gestureProvider;
+
viz::FrameSinkId m_frameSinkId;
std::unique_ptr<RenderWidgetHostViewQtDelegateClient> m_delegateClient;
std::unique_ptr<RenderWidgetHostViewQtDelegate> m_delegate;
+ std::unique_ptr<WebContentsAccessibilityQt> m_webContentsAccessibility;
QMetaObject::Connection m_adapterClientDestroyedConnection;
WebContentsAdapterClient *m_adapterClient = nullptr;
bool m_isMouseLocked = false;
bool m_visible = false;
bool m_deferredShow = false;
- gfx::Vector2dF m_lastScrollOffset;
+ gfx::PointF m_lastScrollOffset;
gfx::SizeF m_lastContentsSize;
DelegatedFrameHostClientQt m_delegatedFrameHostClient { this };
// VIZ
- content::ScreenInfo m_screenInfo;
std::unique_ptr<content::DelegatedFrameHost> m_delegatedFrameHost;
std::unique_ptr<ui::Layer> m_rootLayer;
std::unique_ptr<ui::Compositor> m_uiCompositor;
@@ -236,6 +235,14 @@ private:
base::WeakPtrFactory<RenderWidgetHostViewQt> m_weakPtrFactory { this };
};
+class WebContentsAccessibilityQt : public content::WebContentsAccessibility
+{
+ RenderWidgetHostViewQt *m_rwhv;
+public:
+ WebContentsAccessibilityQt(RenderWidgetHostViewQt *rwhv) : m_rwhv(rwhv) {}
+ QObject *accessibilityParentObject() const;
+};
+
} // namespace QtWebEngineCore
#endif // RENDER_WIDGET_HOST_VIEW_QT_H
diff --git a/src/core/render_widget_host_view_qt_delegate.h b/src/core/render_widget_host_view_qt_delegate.h
index f5227bd52..b1f33db7a 100644
--- a/src/core/render_widget_host_view_qt_delegate.h
+++ b/src/core/render_widget_host_view_qt_delegate.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,8 +15,7 @@
#ifndef RENDER_WIDGET_HOST_VIEW_QT_DELEGATE_H
#define RENDER_WIDGET_HOST_VIEW_QT_DELEGATE_H
-#include "qtwebenginecoreglobal_p.h"
-
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QtCore/QRect>
#include <QtGui/QColor>
#include <QtGui/QCursor>
@@ -65,7 +28,8 @@ QT_END_NAMESPACE
namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT RenderWidgetHostViewQtDelegate {
+class WebContentsAdapterClient;
+class Q_WEBENGINECORE_EXPORT RenderWidgetHostViewQtDelegate {
public:
virtual ~RenderWidgetHostViewQtDelegate() { }
virtual void initAsPopup(const QRect&) = 0;
@@ -78,14 +42,15 @@ public:
virtual void show() = 0;
virtual void hide() = 0;
virtual bool isVisible() const = 0;
- virtual QWindow* window() const = 0;
+ virtual QWindow *Window() const = 0;
virtual void updateCursor(const QCursor &) = 0;
virtual void resize(int width, int height) = 0;
virtual void move(const QPoint &) = 0;
virtual void inputMethodStateChanged(bool editorVisible, bool passwordInput) = 0;
virtual void setInputMethodHints(Qt::InputMethodHints hints) = 0;
virtual void setClearColor(const QColor &color) = 0;
- virtual bool copySurface(const QRect &, const QSize &, QImage &) = 0;
+ virtual void adapterClientChanged(WebContentsAdapterClient *client) = 0;
+ virtual void updateAdapterClientIfNeeded(WebContentsAdapterClient *client) = 0;
virtual void unhandledWheelEvent(QWheelEvent *) {}
};
diff --git a/src/core/render_widget_host_view_qt_delegate_client.cpp b/src/core/render_widget_host_view_qt_delegate_client.cpp
index bee4bc4c2..3e8cad669 100644
--- a/src/core/render_widget_host_view_qt_delegate_client.cpp
+++ b/src/core/render_widget_host_view_qt_delegate_client.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "render_widget_host_view_qt_delegate_client.h"
@@ -47,18 +11,17 @@
#include "web_event_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
+#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "ui/touch_selection/touch_selection_controller.h"
#include <QEvent>
#include <QInputMethodEvent>
-#include <QSGNode>
+#include <QSet>
#include <QStyleHints>
#include <QTextFormat>
#include <QVariant>
-#include <private/qguiapplication_p.h>
-#include <qpa/qplatforminputcontext.h>
-#include <qpa/qplatformintegration.h>
+#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/private/qinputcontrol_p.h>
namespace QtWebEngineCore {
@@ -72,39 +35,38 @@ static inline int firstAvailableId(const QMap<int, int> &map)
return usedIds.first_unmarked_bit();
}
-static QList<QTouchEvent::TouchPoint>
-mapTouchPointIds(const QList<QTouchEvent::TouchPoint> &inputPoints)
+typedef QPair<int, QTouchEvent::TouchPoint> TouchPoint;
+QList<TouchPoint> RenderWidgetHostViewQtDelegateClient::mapTouchPointIds(const QList<QTouchEvent::TouchPoint> &input)
{
- static QMap<int, int> touchIdMapping;
- QList<QTouchEvent::TouchPoint> outputPoints = inputPoints;
- for (int i = 0; i < outputPoints.size(); ++i) {
- QTouchEvent::TouchPoint &point = outputPoints[i];
+ QList<TouchPoint> output;
+ for (int i = 0; i < input.size(); ++i) {
+ const QTouchEvent::TouchPoint &point = input[i];
int qtId = point.id();
- QMap<int, int>::const_iterator it = touchIdMapping.find(qtId);
- if (it == touchIdMapping.end())
- it = touchIdMapping.insert(qtId, firstAvailableId(touchIdMapping));
- point.setId(it.value());
+ QMap<int, int>::const_iterator it = m_touchIdMapping.find(qtId);
+ if (it == m_touchIdMapping.end()) {
+ Q_ASSERT_X(m_touchIdMapping.size() <= 16, "", "Number of mapped ids can't exceed 16 for velocity tracker");
+ it = m_touchIdMapping.insert(qtId, firstAvailableId(m_touchIdMapping));
+ }
- if (point.state() == Qt::TouchPointReleased)
- touchIdMapping.remove(qtId);
+ output.append(qMakePair(it.value(), point));
}
- return outputPoints;
-}
+ Q_ASSERT(output.size() == std::accumulate(output.cbegin(), output.cend(), QSet<int>(),
+ [] (QSet<int> s, const TouchPoint &p) { s.insert(p.second.id()); return s; }).size());
-static inline bool compareTouchPoints(const QTouchEvent::TouchPoint &lhs,
- const QTouchEvent::TouchPoint &rhs)
-{
- // TouchPointPressed < TouchPointMoved < TouchPointReleased
- return lhs.state() < rhs.state();
+ for (auto &&point : std::as_const(input))
+ if (point.state() == QEventPoint::Released)
+ m_touchIdMapping.remove(point.id());
+
+ return output;
}
static uint32_t s_eventId = 0;
class MotionEventQt : public ui::MotionEvent
{
public:
- MotionEventQt(const QList<QTouchEvent::TouchPoint> &touchPoints,
+ MotionEventQt(const QList<TouchPoint> &touchPoints,
const base::TimeTicks &eventTime, Action action,
const Qt::KeyboardModifiers modifiers, int index = -1)
: touchPoints(touchPoints)
@@ -114,8 +76,12 @@ public:
, flags(flagsFromModifiers(modifiers))
, index(index)
{
- // ACTION_DOWN and ACTION_UP must be accesssed through pointer_index 0
- Q_ASSERT((action != Action::DOWN && action != Action::UP) || index == 0);
+ // index is only valid for ACTION_DOWN and ACTION_UP and should correspond to the point causing it
+ // see blink_event_util.cc:ToWebTouchPointState for details
+ Q_ASSERT_X((action != Action::POINTER_DOWN && action != Action::POINTER_UP && index == -1)
+ || (action == Action::POINTER_DOWN && index >= 0 && touchPoint(index).state() == QEventPoint::Pressed)
+ || (action == Action::POINTER_UP && index >= 0 && touchPoint(index).state() == QEventPoint::Released),
+ "MotionEventQt", qPrintable(QString("action: %1, index: %2, state: %3").arg(int(action)).arg(index).arg(touchPoint(index).state())));
}
uint32_t GetUniqueEventId() const override { return eventId; }
@@ -124,39 +90,39 @@ public:
size_t GetPointerCount() const override { return touchPoints.size(); }
int GetPointerId(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).id();
+ return touchPoints[pointer_index].first;
}
float GetX(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).pos().x();
+ return touchPoint(pointer_index).position().x();
}
float GetY(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).pos().y();
+ return touchPoint(pointer_index).position().y();
}
float GetRawX(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).screenPos().x();
+ return touchPoint(pointer_index).globalPosition().x();
}
float GetRawY(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).screenPos().y();
+ return touchPoint(pointer_index).globalPosition().y();
}
float GetTouchMajor(size_t pointer_index) const override
{
- QSizeF diams = touchPoints.at(pointer_index).ellipseDiameters();
+ QSizeF diams = touchPoint(pointer_index).ellipseDiameters();
return std::max(diams.height(), diams.width());
}
float GetTouchMinor(size_t pointer_index) const override
{
- QSizeF diams = touchPoints.at(pointer_index).ellipseDiameters();
+ QSizeF diams = touchPoint(pointer_index).ellipseDiameters();
return std::min(diams.height(), diams.width());
}
float GetOrientation(size_t pointer_index) const override { return 0; }
int GetFlags() const override { return flags; }
float GetPressure(size_t pointer_index) const override
{
- return touchPoints.at(pointer_index).pressure();
+ return touchPoint(pointer_index).pressure();
}
float GetTiltX(size_t pointer_index) const override { return 0; }
float GetTiltY(size_t pointer_index) const override { return 0; }
@@ -177,19 +143,19 @@ public:
float GetHistoricalY(size_t pointer_index, size_t historical_index) const override { return 0; }
ToolType GetToolType(size_t pointer_index) const override
{
- return (touchPoints.at(pointer_index).flags() & QTouchEvent::TouchPoint::InfoFlag::Pen)
- ? ui::MotionEvent::ToolType::STYLUS
- : ui::MotionEvent::ToolType::FINGER;
+ return ui::MotionEvent::ToolType::FINGER;
}
+
int GetButtonState() const override { return 0; }
private:
- QList<QTouchEvent::TouchPoint> touchPoints;
+ QList<TouchPoint> touchPoints;
base::TimeTicks eventTime;
Action action;
const uint32_t eventId;
int flags;
int index;
+ const QTouchEvent::TouchPoint& touchPoint(size_t i) const { return touchPoints[i].second; }
};
RenderWidgetHostViewQtDelegateClient::RenderWidgetHostViewQtDelegateClient(
@@ -197,11 +163,6 @@ RenderWidgetHostViewQtDelegateClient::RenderWidgetHostViewQtDelegateClient(
: m_rwhv(rwhv)
{
Q_ASSERT(rwhv);
-
- const QPlatformInputContext *context =
- QGuiApplicationPrivate::platformIntegration()->inputContext();
- m_imeHasHiddenTextCapability =
- context && context->hasCapability(QPlatformInputContext::HiddenTextCapability);
}
Compositor::Id RenderWidgetHostViewQtDelegateClient::compositorId()
@@ -237,7 +198,7 @@ void RenderWidgetHostViewQtDelegateClient::visualPropertiesChanged()
m_rwhv->host()->SendScreenRects();
if (m_viewRectInDips.size() != oldViewRect.size() || screenInfoChanged)
- m_rwhv->synchronizeVisualProperties(base::nullopt);
+ m_rwhv->synchronizeVisualProperties(absl::nullopt);
}
bool RenderWidgetHostViewQtDelegateClient::forwardEvent(QEvent *event)
@@ -247,7 +208,7 @@ bool RenderWidgetHostViewQtDelegateClient::forwardEvent(QEvent *event)
switch (event->type()) {
case QEvent::ShortcutOverride: {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
-
+ event->ignore();
auto acceptKeyOutOfInputField = [](QKeyEvent *keyEvent) -> bool {
#ifdef Q_OS_MACOS
// Check if a shortcut is registered for this key sequence.
@@ -331,9 +292,13 @@ bool RenderWidgetHostViewQtDelegateClient::forwardEvent(QEvent *event)
handleHoverEvent(static_cast<QHoverEvent *>(event));
break;
case QEvent::FocusIn:
- case QEvent::FocusOut:
- handleFocusEvent(static_cast<QFocusEvent *>(event));
- break;
+ case QEvent::FocusOut: {
+ // Focus in/out events for popup event do not mean 'parent' focus change
+ // and should not be handled by Chromium
+ QFocusEvent *e = static_cast<QFocusEvent *>(event);
+ if (e->reason() != Qt::PopupFocusReason)
+ handleFocusEvent(e);
+ } break;
case QEvent::InputMethod:
handleInputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
@@ -346,7 +311,10 @@ bool RenderWidgetHostViewQtDelegateClient::forwardEvent(QEvent *event)
return false;
#endif
case QEvent::HoverLeave:
- m_rwhv->host()->ForwardMouseEvent(WebEventFactory::toWebMouseEvent(event));
+ if (m_rwhv->host()->delegate() && m_rwhv->host()->delegate()->GetInputEventRouter()) {
+ auto webEvent = WebEventFactory::toWebMouseEvent(event);
+ m_rwhv->host()->delegate()->GetInputEventRouter()->RouteMouseEvent(m_rwhv, &webEvent, ui::LatencyInfo());
+ }
break;
default:
return false;
@@ -357,17 +325,8 @@ bool RenderWidgetHostViewQtDelegateClient::forwardEvent(QEvent *event)
QVariant RenderWidgetHostViewQtDelegateClient::inputMethodQuery(Qt::InputMethodQuery query)
{
switch (query) {
- case Qt::ImEnabled: {
- ui::TextInputType type = m_rwhv->getTextInputType();
- bool editorVisible = type != ui::TEXT_INPUT_TYPE_NONE;
- // IME manager should disable composition on input fields with ImhHiddenText hint if
- // supported
- if (m_imeHasHiddenTextCapability)
- return QVariant(editorVisible);
-
- bool passwordInput = type == ui::TEXT_INPUT_TYPE_PASSWORD;
- return QVariant(editorVisible && !passwordInput);
- }
+ case Qt::ImEnabled:
+ return QVariant(m_rwhv->getTextInputType() != ui::TEXT_INPUT_TYPE_NONE);
case Qt::ImFont:
// TODO: Implement this
return QVariant();
@@ -385,6 +344,7 @@ QVariant RenderWidgetHostViewQtDelegateClient::inputMethodQuery(Qt::InputMethodQ
}
return QVariant();
}
+ case Qt::ImAbsolutePosition:
case Qt::ImCursorPosition:
return m_cursorPosition;
case Qt::ImAnchorPosition:
@@ -398,12 +358,8 @@ QVariant RenderWidgetHostViewQtDelegateClient::inputMethodQuery(Qt::InputMethodQ
// TODO: Implement this
return QVariant(); // No limit.
case Qt::ImHints:
-#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
return int(toQtInputMethodHints(m_rwhv->getTextInputType()) | Qt::ImhNoPredictiveText
| Qt::ImhNoTextHandles | Qt::ImhNoEditMenu);
-#else
- return int(toQtInputMethodHints(m_rwhv->getTextInputType()) | Qt::ImhNoPredictiveText);
-#endif
default:
return QVariant();
}
@@ -424,20 +380,20 @@ void RenderWidgetHostViewQtDelegateClient::handlePointerEvent(T *event)
// Currently WebMouseEvent is a subclass of WebPointerProperties, so basically
// tablet events are mouse events with extra properties.
blink::WebMouseEvent webEvent = WebEventFactory::toWebMouseEvent(event);
- if ((webEvent.GetType() == blink::WebInputEvent::kMouseDown
- || webEvent.GetType() == blink::WebInputEvent::kMouseUp)
+ if ((webEvent.GetType() == blink::WebInputEvent::Type::kMouseDown
+ || webEvent.GetType() == blink::WebInputEvent::Type::kMouseUp)
&& webEvent.button == blink::WebMouseEvent::Button::kNoButton) {
- // Blink can only handle the 3 main mouse-buttons and may assert when processing mouse-down
+ // Blink can only handle the 5 main mouse-buttons and may assert when processing mouse-down
// for no button.
LOG(INFO) << "Unhandled mouse button";
return;
}
- if (webEvent.GetType() == blink::WebInputEvent::kMouseDown) {
+ if (webEvent.GetType() == blink::WebInputEvent::Type::kMouseDown) {
if (event->button() != m_clickHelper.lastPressButton
|| (event->timestamp() - m_clickHelper.lastPressTimestamp
> static_cast<ulong>(qGuiApp->styleHints()->mouseDoubleClickInterval()))
- || (event->pos() - m_clickHelper.lastPressPosition).manhattanLength()
+ || (event->position() - m_clickHelper.lastPressPosition).manhattanLength()
> qGuiApp->styleHints()->startDragDistance()
|| m_clickHelper.clickCounter >= 3)
m_clickHelper.clickCounter = 0;
@@ -445,18 +401,22 @@ void RenderWidgetHostViewQtDelegateClient::handlePointerEvent(T *event)
m_clickHelper.lastPressTimestamp = event->timestamp();
webEvent.click_count = ++m_clickHelper.clickCounter;
m_clickHelper.lastPressButton = event->button();
- m_clickHelper.lastPressPosition = QPointF(event->pos()).toPoint();
+ m_clickHelper.lastPressPosition = event->position().toPoint();
}
- webEvent.movement_x = event->globalX() - m_previousMousePosition.x();
- webEvent.movement_y = event->globalY() - m_previousMousePosition.y();
+ if (webEvent.GetType() == blink::WebInputEvent::Type::kMouseUp)
+ webEvent.click_count = m_clickHelper.clickCounter;
+
+ webEvent.movement_x = event->globalPosition().x() - m_previousMousePosition.x();
+ webEvent.movement_y = event->globalPosition().y() - m_previousMousePosition.y();
+ webEvent.is_raw_movement_event = true;
if (m_rwhv->IsMouseLocked())
QCursor::setPos(m_previousMousePosition);
else
- m_previousMousePosition = event->globalPos();
+ m_previousMousePosition = event->globalPosition().toPoint();
- if (m_imeInProgress && webEvent.GetType() == blink::WebInputEvent::kMouseDown) {
+ if (m_imeInProgress && webEvent.GetType() == blink::WebInputEvent::Type::kMouseDown) {
m_imeInProgress = false;
// Tell input method to commit the pre-edit string entered so far, and finish the
// composition operation.
@@ -469,7 +429,8 @@ void RenderWidgetHostViewQtDelegateClient::handlePointerEvent(T *event)
#endif
}
- m_rwhv->host()->ForwardMouseEvent(webEvent);
+ if (m_rwhv->host()->delegate() && m_rwhv->host()->delegate()->GetInputEventRouter())
+ m_rwhv->host()->delegate()->GetInputEventRouter()->RouteMouseEvent(m_rwhv, &webEvent, ui::LatencyInfo());
}
void RenderWidgetHostViewQtDelegateClient::handleMouseEvent(QMouseEvent *event)
@@ -479,12 +440,6 @@ void RenderWidgetHostViewQtDelegateClient::handleMouseEvent(QMouseEvent *event)
if (event->type() == QEvent::MouseButtonRelease)
m_mouseButtonPressed--;
- // Don't forward mouse events synthesized by the system, which are caused by genuine touch
- // events. Chromium would then process for e.g. a mouse click handler twice, once due to the
- // system synthesized mouse event, and another time due to a touch-to-gesture-to-mouse
- // transformation done by Chromium.
- if (event->source() == Qt::MouseEventSynthesizedBySystem)
- return;
handlePointerEvent<QMouseEvent>(event);
}
@@ -521,29 +476,32 @@ void RenderWidgetHostViewQtDelegateClient::handleKeyEvent(QKeyEvent *event)
if (event->type() == QEvent::KeyRelease && event->isAutoRepeat())
return;
+ if (!m_rwhv->GetFocusedWidget())
+ return;
+
content::NativeWebKeyboardEvent webEvent = WebEventFactory::toWebKeyboardEvent(event);
- if (webEvent.GetType() == blink::WebInputEvent::kRawKeyDown && !m_editCommand.empty()) {
+ if (webEvent.GetType() == blink::WebInputEvent::Type::kRawKeyDown && !m_editCommand.empty()) {
ui::LatencyInfo latency;
latency.set_source_event_type(ui::SourceEventType::KEY_PRESS);
- content::EditCommands commands;
- commands.emplace_back(m_editCommand, "");
+ std::vector<blink::mojom::EditCommandPtr> commands;
+ commands.emplace_back(blink::mojom::EditCommand::New(m_editCommand, ""));
m_editCommand.clear();
- m_rwhv->host()->ForwardKeyboardEventWithCommands(webEvent, latency, &commands, nullptr);
+ m_rwhv->GetFocusedWidget()->ForwardKeyboardEventWithCommands(webEvent, latency, std::move(commands), nullptr);
return;
}
bool keyDownTextInsertion =
- webEvent.GetType() == blink::WebInputEvent::kRawKeyDown && webEvent.text[0];
- webEvent.skip_in_browser = keyDownTextInsertion;
- m_rwhv->host()->ForwardKeyboardEvent(webEvent);
+ webEvent.GetType() == blink::WebInputEvent::Type::kRawKeyDown && webEvent.text[0];
+ webEvent.skip_if_unhandled = keyDownTextInsertion;
+ m_rwhv->GetFocusedWidget()->ForwardKeyboardEvent(webEvent);
if (keyDownTextInsertion) {
// Blink won't consume the RawKeyDown, but rather the Char event in this case.
// The RawKeyDown is skipped on the way back (see above).
// The same os_event will be set on both NativeWebKeyboardEvents.
- webEvent.skip_in_browser = false;
- webEvent.SetType(blink::WebInputEvent::kChar);
- m_rwhv->host()->ForwardKeyboardEvent(webEvent);
+ webEvent.skip_if_unhandled = false;
+ webEvent.SetType(blink::WebInputEvent::Type::kChar);
+ m_rwhv->GetFocusedWidget()->ForwardKeyboardEvent(webEvent);
}
}
@@ -564,59 +522,70 @@ void RenderWidgetHostViewQtDelegateClient::handleTouchEvent(QTouchEvent *event)
// Calculate a delta between event timestamps and Now() on the first received event, and
// apply this delta to all successive events. This delta is most likely smaller than it
// should by calculating it here but this will hopefully cause less than one frame of delay.
- base::TimeTicks eventTimestamp =
- base::TimeTicks() + base::TimeDelta::FromMilliseconds(event->timestamp());
- static base::TimeDelta eventsToNowDelta = base::TimeTicks::Now() - eventTimestamp;
- eventTimestamp += eventsToNowDelta;
+ base::TimeTicks eventTimestamp = base::TimeTicks() + base::Milliseconds(event->timestamp());
+ if (m_eventsToNowDelta == 0)
+ m_eventsToNowDelta = (base::TimeTicks::Now() - eventTimestamp).InMicroseconds();
+ eventTimestamp += base::Microseconds(m_eventsToNowDelta);
+
+ auto touchPoints = mapTouchPointIds(event->points());
+ // Make sure that POINTER_DOWN action is delivered before MOVE, and MOVE before POINTER_UP
+ std::sort(touchPoints.begin(), touchPoints.end(), [] (const TouchPoint &l, const TouchPoint &r) {
+ return l.second.state() < r.second.state();
+ });
+
+ auto sc = qScopeGuard([&] () {
+ switch (event->type()) {
+ case QEvent::TouchCancel:
+ for (auto &&it : std::as_const(touchPoints))
+ m_touchIdMapping.remove(it.second.id());
+ Q_FALLTHROUGH();
+
+ case QEvent::TouchEnd:
+ m_previousTouchPoints.clear();
+ m_touchMotionStarted = false;
+ break;
- QList<QTouchEvent::TouchPoint> touchPoints = mapTouchPointIds(event->touchPoints());
- // Make sure that ACTION_POINTER_DOWN is delivered before ACTION_MOVE,
- // and ACTION_MOVE before ACTION_POINTER_UP.
- std::sort(touchPoints.begin(), touchPoints.end(), compareTouchPoints);
+ default:
+ m_previousTouchPoints = touchPoints;
+ break;
+ }
+ });
+ ui::MotionEvent::Action action;
// Check first if the touch event should be routed to the selectionController
if (!touchPoints.isEmpty()) {
- ui::MotionEvent::Action action;
- switch (touchPoints[0].state()) {
- case Qt::TouchPointPressed:
+ switch (touchPoints[0].second.state()) {
+ case QEventPoint::Pressed:
action = ui::MotionEvent::Action::DOWN;
break;
- case Qt::TouchPointMoved:
+ case QEventPoint::Updated:
action = ui::MotionEvent::Action::MOVE;
break;
- case Qt::TouchPointReleased:
+ case QEventPoint::Released:
action = ui::MotionEvent::Action::UP;
break;
default:
action = ui::MotionEvent::Action::NONE;
break;
}
-
- MotionEventQt motionEvent(touchPoints, eventTimestamp, action, event->modifiers(), 0);
- if (m_rwhv->getTouchSelectionController()->WillHandleTouchEvent(motionEvent)) {
- m_previousTouchPoints = touchPoints;
- event->accept();
- return;
- }
} else {
// An empty touchPoints always corresponds to a TouchCancel event.
// We can't forward touch cancellations without a previously processed touch event,
// as Chromium expects the previous touchPoints for Action::CANCEL.
// If both are empty that means the TouchCancel was sent without an ongoing touch,
// so there's nothing to cancel anyway.
+ Q_ASSERT(event->type() == QEvent::TouchCancel);
touchPoints = m_previousTouchPoints;
if (touchPoints.isEmpty())
return;
- MotionEventQt cancelEvent(touchPoints, eventTimestamp, ui::MotionEvent::Action::CANCEL,
- event->modifiers());
- if (m_rwhv->getTouchSelectionController()->WillHandleTouchEvent(cancelEvent)) {
- m_previousTouchPoints.clear();
- event->accept();
- return;
- }
+ action = ui::MotionEvent::Action::CANCEL;
}
+ MotionEventQt me(touchPoints, eventTimestamp, action, event->modifiers());
+ if (m_rwhv->getTouchSelectionController()->WillHandleTouchEvent(me))
+ return;
+
switch (event->type()) {
case QEvent::TouchBegin:
m_sendMotionActionDown = true;
@@ -626,19 +595,17 @@ void RenderWidgetHostViewQtDelegateClient::handleTouchEvent(QTouchEvent *event)
case QEvent::TouchUpdate:
m_touchMotionStarted = true;
break;
- case QEvent::TouchCancel: {
+ case QEvent::TouchCancel:
+ {
// Only process TouchCancel events received following a TouchBegin or TouchUpdate event
if (m_touchMotionStarted) {
- MotionEventQt cancelEvent(touchPoints, eventTimestamp, ui::MotionEvent::Action::CANCEL,
- event->modifiers());
+ MotionEventQt cancelEvent(touchPoints, eventTimestamp, ui::MotionEvent::Action::CANCEL, event->modifiers());
m_rwhv->processMotionEvent(cancelEvent);
}
- clearPreviousTouchMotionState();
return;
}
case QEvent::TouchEnd:
- clearPreviousTouchMotionState();
m_rwhv->getTouchSelectionControllerClient()->onTouchUp();
break;
default:
@@ -658,34 +625,50 @@ void RenderWidgetHostViewQtDelegateClient::handleTouchEvent(QTouchEvent *event)
#endif
}
- for (int i = 0; i < touchPoints.size(); ++i) {
- ui::MotionEvent::Action action;
- switch (touchPoints[i].state()) {
- case Qt::TouchPointPressed:
- if (m_sendMotionActionDown) {
- action = ui::MotionEvent::Action::DOWN;
- m_sendMotionActionDown = false;
- } else {
- action = ui::MotionEvent::Action::POINTER_DOWN;
+ // MEMO for the basis of this logic look into:
+ // * blink_event_util.cc:ToWebTouchPointState: which is used later to forward touch event
+ // composed from motion event after gesture recognition
+ // * gesture_detector.cc:GestureDetector::OnTouchEvent: contains logic for every motion
+ // event action and corresponding gesture recognition routines
+ // * input_router_imp.cc:InputRouterImp::SetMovementXYForTouchPoints: expectation about
+ // touch event content like number of points for different states
+
+ int lastPressIndex = -1;
+ while ((lastPressIndex + 1) < touchPoints.size() && touchPoints[lastPressIndex + 1].second.state() == QEventPoint::Pressed)
+ ++lastPressIndex;
+
+ switch (event->type()) {
+ case QEvent::TouchBegin:
+ m_rwhv->processMotionEvent(MotionEventQt(touchPoints.mid(lastPressIndex),
+ eventTimestamp, ui::MotionEvent::Action::DOWN, event->modifiers()));
+ --lastPressIndex;
+ Q_FALLTHROUGH();
+
+ case QEvent::TouchUpdate:
+ for (; lastPressIndex >= 0; --lastPressIndex) {
+ Q_ASSERT(touchPoints[lastPressIndex].second.state() == QEventPoint::Pressed);
+ MotionEventQt me(touchPoints.mid(lastPressIndex), eventTimestamp, ui::MotionEvent::Action::POINTER_DOWN, event->modifiers(), 0);
+ m_rwhv->processMotionEvent(me);
+ }
+
+ if (event->touchPointStates() & Qt::TouchPointMoved)
+ m_rwhv->processMotionEvent(MotionEventQt(touchPoints, eventTimestamp, ui::MotionEvent::Action::MOVE, event->modifiers()));
+
+ Q_FALLTHROUGH();
+
+ case QEvent::TouchEnd:
+ while (!touchPoints.isEmpty() && touchPoints.back().second.state() == QEventPoint::Released) {
+ auto action = touchPoints.size() > 1 ? ui::MotionEvent::Action::POINTER_UP : ui::MotionEvent::Action::UP;
+ int index = action == ui::MotionEvent::Action::POINTER_UP ? touchPoints.size() - 1 : -1;
+ m_rwhv->processMotionEvent(MotionEventQt(touchPoints, eventTimestamp, action, event->modifiers(), index));
+ touchPoints.pop_back();
}
break;
- case Qt::TouchPointMoved:
- action = ui::MotionEvent::Action::MOVE;
- break;
- case Qt::TouchPointReleased:
- action = touchPoints.size() > 1 ? ui::MotionEvent::Action::POINTER_UP
- : ui::MotionEvent::Action::UP;
- break;
- default:
- // Ignore Qt::TouchPointStationary
- continue;
- }
- MotionEventQt motionEvent(touchPoints, eventTimestamp, action, event->modifiers(), i);
- m_rwhv->processMotionEvent(motionEvent);
+ default:
+ Q_ASSERT_X(false, __FUNCTION__, "Other event types are expected to be already handled.");
+ break;
}
-
- m_previousTouchPoints = touchPoints;
}
#if QT_CONFIG(tabletevent)
@@ -700,15 +683,24 @@ void RenderWidgetHostViewQtDelegateClient::handleGestureEvent(QNativeGestureEven
{
const Qt::NativeGestureType type = event->gestureType();
// These are the only supported gestures by Chromium so far.
- if (type == Qt::ZoomNativeGesture || type == Qt::SmartZoomNativeGesture) {
- m_rwhv->host()->ForwardGestureEvent(WebEventFactory::toWebGestureEvent(event));
+ if (type == Qt::ZoomNativeGesture || type == Qt::SmartZoomNativeGesture
+ || type == Qt::BeginNativeGesture || type == Qt::EndNativeGesture) {
+ auto *hostDelegate = m_rwhv->host()->delegate();
+ if (hostDelegate && hostDelegate->GetInputEventRouter()) {
+ auto webEvent = WebEventFactory::toWebGestureEvent(event);
+ hostDelegate->GetInputEventRouter()->RouteGestureEvent(m_rwhv, &webEvent, ui::LatencyInfo());
+ }
}
}
#endif
void RenderWidgetHostViewQtDelegateClient::handleHoverEvent(QHoverEvent *event)
{
- m_rwhv->host()->ForwardMouseEvent(WebEventFactory::toWebMouseEvent(event));
+ auto *hostDelegate = m_rwhv->host()->delegate();
+ if (hostDelegate && hostDelegate->GetInputEventRouter()) {
+ auto webEvent = WebEventFactory::toWebMouseEvent(event);
+ hostDelegate->GetInputEventRouter()->RouteMouseEvent(m_rwhv, &webEvent, ui::LatencyInfo());
+ }
}
void RenderWidgetHostViewQtDelegateClient::handleFocusEvent(QFocusEvent *event)
@@ -767,6 +759,7 @@ void RenderWidgetHostViewQtDelegateClient::handleInputMethodEvent(QInputMethodEv
underlines.push_back(ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, start, end,
ui::ImeTextSpan::Thickness::kThin,
+ ui::ImeTextSpan::UnderlineStyle::kSolid,
SK_ColorTRANSPARENT));
QTextCharFormat format = qvariant_cast<QTextFormat>(attribute.value).toCharFormat();
@@ -810,10 +803,8 @@ void RenderWidgetHostViewQtDelegateClient::handleInputMethodEvent(QInputMethodEv
}
if (hasSelection) {
- content::mojom::FrameInputHandler *frameInputHandler = m_rwhv->getFrameInputHandler();
- if (frameInputHandler)
- frameInputHandler->SetEditableSelectionOffsets(selectionRange.start(),
- selectionRange.end());
+ if (auto *frameWidgetInputHandler = m_rwhv->getFrameWidgetInputHandler())
+ frameWidgetInputHandler->SetEditableSelectionOffsets(selectionRange.start(), selectionRange.end());
}
int replacementLength = event->replacementLength();
@@ -841,8 +832,7 @@ void RenderWidgetHostViewQtDelegateClient::handleInputMethodEvent(QInputMethodEv
if (commitString.isEmpty() && preeditString.isEmpty() && replacementLength == 0) {
if (!m_receivedEmptyImeEvent && m_imeInProgress && !hasSelection) {
m_receivedEmptyImeEvent = true;
- QInputMethodEvent *eventCopy = new QInputMethodEvent(*event);
- QGuiApplication::postEvent(qApp->focusObject(), eventCopy);
+ QGuiApplication::postEvent(qApp->focusObject(), event->clone());
} else {
m_receivedEmptyImeEvent = false;
if (m_imeInProgress) {
@@ -919,7 +909,7 @@ void RenderWidgetHostViewQtDelegateClient::selectionChanged()
// position if the selection is cleared because TextInputState changes before the
// TextSelection change.
Q_ASSERT(text_input_manager->GetTextInputState());
- m_cursorPosition = text_input_manager->GetTextInputState()->selection_start;
+ m_cursorPosition = text_input_manager->GetTextInputState()->selection.start();
m_rwhv->delegate()->inputMethodStateChanged(true /*editorVisible*/,
type == ui::TEXT_INPUT_TYPE_PASSWORD);
diff --git a/src/core/render_widget_host_view_qt_delegate_client.h b/src/core/render_widget_host_view_qt_delegate_client.h
index f67bed861..57354f549 100644
--- a/src/core/render_widget_host_view_qt_delegate_client.h
+++ b/src/core/render_widget_host_view_qt_delegate_client.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,13 +17,13 @@
#include "compositor/compositor.h"
+#include <QMap>
#include <QtGui/QCursor>
#include <QtGui/QTouchEvent>
QT_BEGIN_NAMESPACE
class QEvent;
class QVariant;
-
class QMouseEvent;
class QKeyEvent;
class QTabletEvent;
@@ -82,7 +46,7 @@ struct MultipleMouseClickHelper
ulong lastPressTimestamp = 0;
};
-class Q_WEBENGINECORE_PRIVATE_EXPORT RenderWidgetHostViewQtDelegateClient
+class Q_WEBENGINECORE_EXPORT RenderWidgetHostViewQtDelegateClient
{
public:
RenderWidgetHostViewQtDelegateClient(RenderWidgetHostViewQt *rwhv);
@@ -132,7 +96,6 @@ private:
RenderWidgetHostViewQt *m_rwhv;
// Mouse
- bool m_imeHasHiddenTextCapability;
uint m_mouseButtonPressed = 0;
QPoint m_previousMousePosition;
MultipleMouseClickHelper m_clickHelper;
@@ -141,9 +104,13 @@ private:
std::string m_editCommand;
// Touch
- QList<QTouchEvent::TouchPoint> m_previousTouchPoints;
+ typedef QPair<int, QTouchEvent::TouchPoint> TouchPoint;
+ QList<TouchPoint> mapTouchPointIds(const QList<QTouchEvent::TouchPoint> &input);
+ QMap<int, int> m_touchIdMapping;
+ QList<TouchPoint> m_previousTouchPoints;
bool m_touchMotionStarted = false;
bool m_sendMotionActionDown = false;
+ int64_t m_eventsToNowDelta = 0; // delta for first touch in microseconds
// IME
bool m_receivedEmptyImeEvent = false;
diff --git a/src/core/render_widget_host_view_qt_delegate_item.cpp b/src/core/render_widget_host_view_qt_delegate_item.cpp
new file mode 100644
index 000000000..23e5bc935
--- /dev/null
+++ b/src/core/render_widget_host_view_qt_delegate_item.cpp
@@ -0,0 +1,455 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "render_widget_host_view_qt_delegate_item.h"
+
+#include "render_widget_host_view_qt_delegate_client.h"
+
+#include <QtGui/qevent.h>
+#include <QtGui/qguiapplication.h>
+#include <QtGui/qwindow.h>
+#include <QtQuick/qsgimagenode.h>
+
+#if QT_CONFIG(accessibility)
+#include <QtGui/qaccessible.h>
+#endif
+
+namespace QtWebEngineCore {
+
+RenderWidgetHostViewQtDelegateItem::RenderWidgetHostViewQtDelegateItem(RenderWidgetHostViewQtDelegateClient *client, bool isPopup)
+ : m_client(client)
+ , m_isPopup(isPopup)
+{
+ setFlag(ItemHasContents);
+ setAcceptedMouseButtons(Qt::AllButtons);
+ setKeepMouseGrab(true);
+ setAcceptHoverEvents(true);
+ setAcceptTouchEvents(true);
+ setKeepTouchGrab(true);
+ if (!isPopup) {
+ setFocus(true);
+ setActiveFocusOnTab(true);
+ }
+ bind(client->compositorId());
+}
+
+RenderWidgetHostViewQtDelegateItem::~RenderWidgetHostViewQtDelegateItem()
+{
+ releaseTextureResources();
+ if (m_widgetDelegate) {
+ m_widgetDelegate->Unbind();
+ m_widgetDelegate->Destroy();
+ }
+}
+
+void RenderWidgetHostViewQtDelegateItem::initAsPopup(const QRect &screenRect)
+{
+ Q_ASSERT(m_isPopup);
+ setSize(screenRect.size());
+ if (m_widgetDelegate)
+ m_widgetDelegate->InitAsPopup(screenRect);
+}
+
+QRectF RenderWidgetHostViewQtDelegateItem::viewGeometry() const
+{
+ // Transform the entire rect to find the correct top left corner.
+ const QPointF p1 = mapToGlobal(mapFromScene(QPointF(0, 0)));
+ const QPointF p2 = mapToGlobal(mapFromScene(QPointF(width(), height())));
+ QRectF geometry = QRectF(p1, p2).normalized();
+ // But keep the size untransformed to behave like other QQuickItems.
+ geometry.setSize(size());
+ return geometry;
+}
+
+QRect RenderWidgetHostViewQtDelegateItem::windowGeometry() const
+{
+ if (!Window())
+ return QRect();
+ return Window()->frameGeometry();
+}
+
+void RenderWidgetHostViewQtDelegateItem::setKeyboardFocus()
+{
+ setFocus(true);
+}
+
+bool RenderWidgetHostViewQtDelegateItem::hasKeyboardFocus()
+{
+ return hasActiveFocus();
+}
+
+void RenderWidgetHostViewQtDelegateItem::lockMouse()
+{
+ grabMouse();
+}
+
+void RenderWidgetHostViewQtDelegateItem::unlockMouse()
+{
+ ungrabMouse();
+}
+
+void RenderWidgetHostViewQtDelegateItem::show()
+{
+ if (isVisible())
+ m_client->notifyShown();
+ else
+ setVisible(true);
+}
+
+void RenderWidgetHostViewQtDelegateItem::hide()
+{
+ if (isVisible())
+ setVisible(false);
+ else
+ m_client->notifyHidden();
+}
+
+bool RenderWidgetHostViewQtDelegateItem::isVisible() const
+{
+ return QQuickItem::isVisible();
+}
+
+QWindow *RenderWidgetHostViewQtDelegateItem::Window() const
+{
+ if (m_widgetDelegate) {
+ if (auto *window = m_widgetDelegate->Window())
+ return window;
+ }
+ return QQuickItem::window();
+}
+
+void RenderWidgetHostViewQtDelegateItem::readyToSwap()
+{
+ // Call update() on UI thread.
+ QMetaObject::invokeMethod(this, &QQuickItem::update, Qt::QueuedConnection);
+}
+
+void RenderWidgetHostViewQtDelegateItem::updateCursor(const QCursor &cursor)
+{
+ setCursor(cursor);
+}
+
+void RenderWidgetHostViewQtDelegateItem::resize(int width, int height)
+{
+ setSize(QSizeF(width, height));
+ if (m_widgetDelegate)
+ m_widgetDelegate->Resize(width, height);
+}
+
+void RenderWidgetHostViewQtDelegateItem::move(const QPoint &point)
+{
+ if (m_widgetDelegate && m_isPopup)
+ m_widgetDelegate->MoveWindow(point);
+}
+
+void RenderWidgetHostViewQtDelegateItem::inputMethodStateChanged(bool editorVisible, bool passwordInput)
+{
+ setFlag(QQuickItem::ItemAcceptsInputMethod, editorVisible && !passwordInput);
+
+ if (parentItem())
+ parentItem()->setFlag(QQuickItem::ItemAcceptsInputMethod, editorVisible && !passwordInput);
+
+ if (m_widgetDelegate)
+ m_widgetDelegate->SetInputMethodEnabled(editorVisible && !passwordInput);
+
+ qApp->inputMethod()->update(Qt::ImQueryInput | Qt::ImEnabled | Qt::ImHints);
+ if (qApp->inputMethod()->isVisible() != editorVisible)
+ qApp->inputMethod()->setVisible(editorVisible);
+}
+
+void RenderWidgetHostViewQtDelegateItem::setWidgetDelegate(WidgetDelegate *delegate)
+{
+ Q_ASSERT(!m_widgetDelegate || !delegate);
+ m_widgetDelegate = delegate;
+ if (m_widgetDelegate) {
+ if (m_inputMethodHints)
+ m_widgetDelegate->SetInputMethodHints(m_inputMethodHints);
+ if (m_clearColor.isValid())
+ m_widgetDelegate->SetClearColor(m_clearColor);
+ if (flags().testFlag(QQuickItem::ItemAcceptsInputMethod))
+ m_widgetDelegate->SetInputMethodEnabled(true);
+ if (m_adapterClient)
+ m_widgetDelegate->Bind(m_adapterClient);
+ }
+}
+
+void RenderWidgetHostViewQtDelegateItem::setInputMethodHints(Qt::InputMethodHints hints)
+{
+ m_inputMethodHints = hints;
+ if (m_widgetDelegate)
+ m_widgetDelegate->SetInputMethodHints(hints);
+}
+
+void RenderWidgetHostViewQtDelegateItem::setClearColor(const QColor &color)
+{
+ m_clearColor = color;
+ if (m_widgetDelegate)
+ m_widgetDelegate->SetClearColor(color);
+}
+
+bool RenderWidgetHostViewQtDelegateItem::event(QEvent *event)
+{
+ if (event->type() == QEvent::ShortcutOverride)
+ return m_client->forwardEvent(event);
+
+#if QT_CONFIG(gestures)
+ if (event->type() == QEvent::NativeGesture)
+ return m_client->forwardEvent(event);
+#endif
+
+ return QQuickItem::event(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::focusInEvent(QFocusEvent *event)
+{
+#if QT_CONFIG(accessibility)
+ if (QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(this)) {
+ if (auto *focusChild = iface->focusChild()) {
+ QAccessibleEvent focusEvent(focusChild, QAccessible::Focus);
+ if (focusEvent.object())
+ focusEvent.setChild(-1);
+ QAccessible::updateAccessibility(&focusEvent);
+ }
+ }
+#endif // QT_CONFIG(accessibility)
+
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::focusOutEvent(QFocusEvent *event)
+{
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::mousePressEvent(QMouseEvent *event)
+{
+ if (!m_isPopup && m_widgetDelegate) {
+ if (m_widgetDelegate->ActiveFocusOnPress()) {
+ forceActiveFocus();
+ } else {
+ event->ignore();
+ return;
+ }
+ }
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::mouseMoveEvent(QMouseEvent *event)
+{
+ if (!m_isPopup && m_widgetDelegate && !m_widgetDelegate->ActiveFocusOnPress()) {
+ event->ignore();
+ return;
+ }
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::mouseReleaseEvent(QMouseEvent *event)
+{
+ if (!m_isPopup && m_widgetDelegate && !m_widgetDelegate->ActiveFocusOnPress()) {
+ event->ignore();
+ return;
+ }
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::keyPressEvent(QKeyEvent *event)
+{
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::keyReleaseEvent(QKeyEvent *event)
+{
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::wheelEvent(QWheelEvent *event)
+{
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::touchEvent(QTouchEvent *event)
+{
+ if (!m_isPopup && m_widgetDelegate) {
+ if (event->type() == QEvent::TouchBegin && m_widgetDelegate->ActiveFocusOnPress())
+ forceActiveFocus();
+
+ if (!m_widgetDelegate->ActiveFocusOnPress()) {
+ event->ignore();
+ return;
+ }
+ }
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::hoverMoveEvent(QHoverEvent *event)
+{
+ event->ignore();
+ if ((!m_isPopup && m_widgetDelegate && !m_widgetDelegate->ActiveFocusOnPress())
+ || event->position() == event->oldPosF()) {
+ return;
+ }
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::hoverLeaveEvent(QHoverEvent *event)
+{
+ event->ignore();
+ m_client->forwardEvent(event);
+}
+
+QVariant RenderWidgetHostViewQtDelegateItem::inputMethodQuery(Qt::InputMethodQuery query) const
+{
+ return m_client->inputMethodQuery(query);
+}
+
+void RenderWidgetHostViewQtDelegateItem::inputMethodEvent(QInputMethodEvent *event)
+{
+ m_client->forwardEvent(event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
+{
+ QQuickItem::geometryChange(newGeometry, oldGeometry);
+ m_client->visualPropertiesChanged();
+}
+
+void RenderWidgetHostViewQtDelegateItem::itemChange(ItemChange change, const ItemChangeData &value)
+{
+ QQuickItem::itemChange(change, value);
+ if (change == QQuickItem::ItemSceneChange) {
+ for (const QMetaObject::Connection &c : std::as_const(m_windowConnections))
+ disconnect(c);
+ m_windowConnections.clear();
+ if (value.window) {
+ m_windowConnections.append(connect(value.window, &QQuickWindow::beforeRendering,
+ this, &RenderWidgetHostViewQtDelegateItem::onBeforeRendering, Qt::DirectConnection));
+ m_windowConnections.append(connect(value.window, &QQuickWindow::afterFrameEnd, this,
+ &RenderWidgetHostViewQtDelegateItem::onAfterFrameEnd,
+ Qt::DirectConnection));
+ m_windowConnections.append(connect(value.window, SIGNAL(xChanged(int)), SLOT(onWindowPosChanged())));
+ m_windowConnections.append(
+ connect(value.window, SIGNAL(yChanged(int)), SLOT(onWindowPosChanged())));
+ m_windowConnections.append(
+ connect(value.window, &QQuickWindow::sceneGraphAboutToStop, this,
+ &RenderWidgetHostViewQtDelegateItem::releaseTextureResources,
+ Qt::DirectConnection));
+ if (!m_isPopup)
+ m_windowConnections.append(connect(value.window, SIGNAL(closing(QQuickCloseEvent *)), SLOT(onHide())));
+ }
+ m_client->visualPropertiesChanged();
+ } else if (change == QQuickItem::ItemVisibleHasChanged) {
+ if (value.boolValue) {
+ m_client->notifyShown();
+ } else {
+ m_client->notifyHidden();
+ if (!m_isPopup)
+ onHide();
+ }
+ }
+}
+
+QSGNode *RenderWidgetHostViewQtDelegateItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
+{
+ auto comp = compositor();
+ if (!comp)
+ return oldNode;
+
+ QQuickWindow *win = QQuickItem::window();
+
+ QSGImageNode *node = nullptr;
+ // Delete old node before swapFrame to decrement refcount of
+ // QImage in software mode.
+ if (comp->type() == Compositor::Type::Software)
+ delete oldNode;
+ else
+ node = static_cast<QSGImageNode*>(oldNode);
+
+ if (!node) {
+ node = win->createImageNode();
+ node->setOwnsTexture(true);
+ }
+
+ comp->swapFrame();
+
+ QSize texSize = comp->size();
+ QSizeF texSizeInDips = QSizeF(texSize) / comp->devicePixelRatio();
+ node->setRect(QRectF(QPointF(0, 0), texSizeInDips));
+
+ QQuickWindow::CreateTextureOptions texOpts;
+ if (comp->requiresAlphaChannel() || m_clearColor.alpha() < 255)
+ texOpts.setFlag(QQuickWindow::TextureHasAlphaChannel);
+ else
+ texOpts.setFlag(QQuickWindow::TextureIsOpaque);
+ QSGTexture *texture = comp->texture(win, texOpts);
+ if (texture) {
+ node->setTexture(texture);
+ if (comp->textureIsFlipped())
+ node->setTextureCoordinatesTransform(QSGImageNode::MirrorVertically);
+ } else {
+ if (!oldNode || comp->type() == Compositor::Type::Software) {
+ qDebug("Compositor returned null texture");
+ delete node;
+ return nullptr;
+ }
+ }
+
+ return node;
+}
+
+void RenderWidgetHostViewQtDelegateItem::onBeforeRendering()
+{
+ auto comp = compositor();
+ if (!comp || comp->type() == Compositor::Type::Software)
+ return;
+ comp->waitForTexture();
+}
+
+void RenderWidgetHostViewQtDelegateItem::onAfterFrameEnd()
+{
+ auto comp = compositor();
+ if (!comp || comp->type() != Compositor::Type::Native)
+ return;
+ comp->releaseTexture();
+}
+
+void RenderWidgetHostViewQtDelegateItem::onWindowPosChanged()
+{
+ m_client->visualPropertiesChanged();
+}
+
+void RenderWidgetHostViewQtDelegateItem::onHide()
+{
+ QFocusEvent event(QEvent::FocusOut, Qt::OtherFocusReason);
+ m_client->forwardEvent(&event);
+}
+
+void RenderWidgetHostViewQtDelegateItem::releaseTextureResources()
+{
+ auto comp = compositor();
+ if (!comp || comp->type() != Compositor::Type::Native)
+ return;
+
+ comp->releaseResources();
+}
+
+void RenderWidgetHostViewQtDelegateItem::adapterClientChanged(WebContentsAdapterClient *client)
+{
+ m_adapterClient = client;
+ if (m_widgetDelegate)
+ m_widgetDelegate->Bind(client);
+}
+
+void RenderWidgetHostViewQtDelegateItem::updateAdapterClientIfNeeded(WebContentsAdapterClient *client)
+{
+ if (client == m_adapterClient)
+ return;
+ adapterClientChanged(client);
+}
+
+void RenderWidgetHostViewQtDelegateItem::unhandledWheelEvent(QWheelEvent *ev)
+{
+ if (m_widgetDelegate)
+ m_widgetDelegate->unhandledWheelEvent(ev);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/render_widget_host_view_qt_delegate_item.h b/src/core/render_widget_host_view_qt_delegate_item.h
new file mode 100644
index 000000000..0da6b4948
--- /dev/null
+++ b/src/core/render_widget_host_view_qt_delegate_item.h
@@ -0,0 +1,125 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef RENDER_WIDGET_HOST_VIEW_QT_DELEGATE_ITEM_H
+#define RENDER_WIDGET_HOST_VIEW_QT_DELEGATE_ITEM_H
+
+#include "compositor/compositor.h"
+#include "render_widget_host_view_qt_delegate.h"
+
+#include <QtQuick/QQuickItem>
+
+QT_BEGIN_NAMESPACE
+class QQuickWebEngineViewPrivate;
+class QWebEngineViewPrivate;
+QT_END_NAMESPACE
+
+namespace QtWebEngineCore {
+
+class RenderWidgetHostViewQtDelegateClient;
+class WebContentsAdapterClient;
+class WebEngineQuickWidget;
+
+class WidgetDelegate
+{
+public:
+ virtual ~WidgetDelegate() = default;
+ virtual void InitAsPopup(const QRect &screenRect) = 0;
+ virtual void SetInputMethodEnabled(bool) { }
+ virtual void SetInputMethodHints(Qt::InputMethodHints) { }
+ virtual void SetClearColor(const QColor &) { }
+ virtual bool ActiveFocusOnPress() = 0;
+ virtual void MoveWindow(const QPoint & ) { }
+ virtual void Bind(WebContentsAdapterClient *) = 0;
+ virtual void Unbind() = 0;
+ virtual void Destroy() = 0;
+ virtual void Resize(int, int) { }
+ virtual QWindow *Window() { return nullptr; }
+ virtual void unhandledWheelEvent(QWheelEvent *) { }
+};
+
+// Useful information keyboard and mouse QEvent propagation.
+// A RenderWidgetHostViewQtDelegateItem instance initialized as a popup will receive
+// no keyboard focus (so all keyboard QEvents will be sent to the parent RWHVQD instance),
+// but will still receive mouse input (all mouse QEvent moves and clicks will be given to the popup
+// RWHVQD instance, and the mouse interaction area covers the surface of the whole parent
+// QWebEngineView, and not only the smaller surface that an HTML select popup would occupy).
+class Q_WEBENGINECORE_EXPORT RenderWidgetHostViewQtDelegateItem
+ : public QQuickItem
+ , public RenderWidgetHostViewQtDelegate
+ , public Compositor::Observer
+{
+ Q_OBJECT
+public:
+ RenderWidgetHostViewQtDelegateItem(RenderWidgetHostViewQtDelegateClient *client, bool isPopup);
+ ~RenderWidgetHostViewQtDelegateItem();
+
+ void initAsPopup(const QRect&) override;
+ QRectF viewGeometry() const override;
+ QRect windowGeometry() const override;
+ void setKeyboardFocus() override;
+ bool hasKeyboardFocus() override;
+ void lockMouse() override;
+ void unlockMouse() override;
+ void show() override;
+ void hide() override;
+ bool isVisible() const override;
+ QWindow *Window() const override;
+ void updateCursor(const QCursor &) override;
+ void resize(int width, int height) override;
+ void move(const QPoint &screenPos) override;
+ void inputMethodStateChanged(bool editorVisible, bool passwordInput) override;
+ void setInputMethodHints(Qt::InputMethodHints) override;
+ void setClearColor(const QColor &color) override;
+ void unhandledWheelEvent(QWheelEvent *ev) override;
+
+ void readyToSwap() override;
+
+ void setWidgetDelegate(WidgetDelegate *delegate);
+
+protected:
+ bool event(QEvent *event) override;
+ void focusInEvent(QFocusEvent *event) override;
+ void focusOutEvent(QFocusEvent *event) override;
+ void mousePressEvent(QMouseEvent *event) override;
+ void mouseMoveEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent *event) override;
+ void keyPressEvent(QKeyEvent *event) override;
+ void keyReleaseEvent(QKeyEvent *event) override;
+ void wheelEvent(QWheelEvent *event) override;
+ void touchEvent(QTouchEvent *event) override;
+ void hoverMoveEvent(QHoverEvent *event) override;
+ void hoverLeaveEvent(QHoverEvent *event) override;
+ QVariant inputMethodQuery(Qt::InputMethodQuery query) const override;
+ void inputMethodEvent(QInputMethodEvent *event) override;
+ void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
+ void itemChange(ItemChange change, const ItemChangeData &value) override;
+ QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) override;
+
+ void adapterClientChanged(WebContentsAdapterClient *client) override;
+ void updateAdapterClientIfNeeded(WebContentsAdapterClient *client) override;
+
+private Q_SLOTS:
+ void onBeforeRendering();
+ void onAfterFrameEnd();
+ void onWindowPosChanged();
+ void releaseTextureResources();
+ void onHide();
+
+private:
+ friend QWebEngineViewPrivate;
+ friend QQuickWebEngineViewPrivate;
+ friend WebEngineQuickWidget;
+
+ RenderWidgetHostViewQtDelegateClient *m_client;
+ bool m_isPopup;
+ QColor m_clearColor;
+ Qt::InputMethodHints m_inputMethodHints = {};
+ QList<QMetaObject::Connection> m_windowConnections;
+ WebContentsAdapterClient *m_adapterClient = nullptr;
+ WidgetDelegate *m_widgetDelegate = nullptr;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // RENDER_WIDGET_HOST_VIEW_QT_DELEGATE_ITEM_H
diff --git a/src/core/renderer/content_renderer_client_qt.cpp b/src/core/renderer/content_renderer_client_qt.cpp
index 8c4d02ad7..cc127e55f 100644
--- a/src/core/renderer/content_renderer_client_qt.cpp
+++ b/src/core/renderer/content_renderer_client_qt.cpp
@@ -1,91 +1,56 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "renderer/content_renderer_client_qt.h"
-#include "extensions/buildflags/buildflags.h"
-#include "printing/buildflags/buildflags.h"
#include "renderer/content_settings_observer_qt.h"
-#include "base/strings/string_split.h"
-#if QT_CONFIG(webengine_spellchecker)
-#include "components/spellcheck/renderer/spellcheck.h"
-#include "components/spellcheck/renderer/spellcheck_provider.h"
-#endif
-#include "components/cdm/renderer/external_clear_key_key_system_properties.h"
-#include "components/cdm/renderer/widevine_key_system_properties.h"
+#include "renderer/render_configuration.h"
+#include "renderer/render_frame_observer_qt.h"
+#include "renderer/user_resource_controller.h"
+#include "renderer/web_engine_page_render_frame.h"
+#include "web_engine_library_info.h"
+
+#include "base/task/sequenced_task_runner.h"
+#include "components/autofill/content/renderer/autofill_agent.h"
+#include "components/autofill/content/renderer/password_autofill_agent.h"
+#include "components/autofill/content/renderer/password_generation_agent.h"
+#include "components/cdm/renderer/external_clear_key_key_system_info.h"
+#include "components/cdm/renderer/widevine_key_system_info.h"
#include "components/error_page/common/error.h"
-#include "components/error_page/common/error_page_params.h"
#include "components/error_page/common/localized_error.h"
+#include "components/grit/components_resources.h"
#include "components/network_hints/renderer/web_prescient_networking_impl.h"
-#if QT_CONFIG(webengine_printing_and_pdf)
-#include "components/printing/renderer/print_render_frame_helper.h"
-#endif
#include "components/visitedlink/renderer/visitedlink_reader.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "content/public/renderer/render_frame.h"
-#include "content/public/child/child_thread.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/render_thread.h"
-#include "content/public/renderer/render_view.h"
-#include "media/base/key_system_properties.h"
+#include "extensions/buildflags/buildflags.h"
+#include "media/base/key_system_info.h"
+#include "media/cdm/cdm_capability.h"
#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/binder_map.h"
#include "net/base/net_errors.h"
-#include "services/service_manager/public/cpp/connector.h"
-#include "services/service_manager/public/cpp/interface_provider.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "printing/buildflags/buildflags.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/platform/web_url_error.h"
-#include "third_party/blink/public/platform/web_url_request.h"
-#include "third_party/blink/public/web/web_security_policy.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
-#include "content/public/common/web_preferences.h"
+
+#if QT_CONFIG(webengine_spellchecker)
+#include "components/spellcheck/renderer/spellcheck.h"
+#include "components/spellcheck/renderer/spellcheck_provider.h"
+#endif
#if QT_CONFIG(webengine_printing_and_pdf)
#include "renderer/print_web_view_helper_delegate_qt.h"
+
+#include "components/pdf/renderer/internal_plugin_renderer_helpers.h"
+#include "components/pdf/renderer/pdf_internal_plugin_delegate.h"
+#include "components/printing/renderer/print_render_frame_helper.h"
#endif
-#include "common/qt_messages.h"
-#include "renderer/render_frame_observer_qt.h"
-#include "renderer/render_view_observer_qt.h"
-#include "renderer/render_thread_observer_qt.h"
-#include "renderer/user_resource_controller.h"
#if QT_CONFIG(webengine_webchannel)
#include "renderer/web_channel_ipc_transport.h"
#endif
@@ -93,32 +58,36 @@
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "common/extensions/extensions_client_qt.h"
#include "extensions/extensions_renderer_client_qt.h"
-#endif //ENABLE_EXTENSIONS
+
+#include "extensions/common/constants.h"
+#include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h"
+#include "mojo/public/cpp/bindings/associated_remote.h"
+#include "services/service_manager/public/cpp/binder_registry.h"
+#include "third_party/blink/public/web/web_security_policy.h"
+#endif // ENABLE_EXTENSIONS
#if BUILDFLAG(ENABLE_PLUGINS)
+#include "content/renderer/render_frame_impl.h"
#include "plugins/loadable_plugin_placeholder_qt.h"
-#include "plugins/plugin_placeholder_qt.h"
-#include "content/common/frame_messages.h"
#endif // ENABLE_PLUGINS
-#include "services/service_manager/public/cpp/binder_registry.h"
-#include "services/service_manager/public/cpp/connector.h"
-#include "services/service_manager/public/cpp/service_binding.h"
-
-#include "components/grit/components_resources.h"
-
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
#include "base/feature_list.h"
#include "content/public/renderer/key_system_support.h"
#include "media/base/media_switches.h"
#include "media/base/video_codecs.h"
+#include "media/cdm/clear_key_cdm_common.h"
#include "third_party/widevine/cdm/buildflags.h"
+#if BUILDFLAG(ENABLE_WIDEVINE)
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#endif
+#endif
-namespace QtWebEngineCore {
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+#include "chrome/renderer/media/webrtc_logging_agent_impl.h"
+#endif
-static const char kHttpErrorDomain[] = "http";
+namespace QtWebEngineCore {
ContentRendererClientQt::ContentRendererClientQt()
{
@@ -132,31 +101,24 @@ ContentRendererClientQt::~ContentRendererClientQt() {}
void ContentRendererClientQt::RenderThreadStarted()
{
+ base::i18n::SetICUDefaultLocale(WebEngineLibraryInfo::getApplicationLocale());
content::RenderThread *renderThread = content::RenderThread::Get();
- m_renderThreadObserver.reset(new RenderThreadObserverQt());
+ m_renderConfiguration.reset(new RenderConfiguration());
+ m_userResourceController.reset(new UserResourceController());
m_visitedLinkReader.reset(new visitedlink::VisitedLinkReader);
m_webCacheImpl.reset(new web_cache::WebCacheImpl());
- renderThread->AddObserver(m_renderThreadObserver.data());
- renderThread->AddObserver(UserResourceController::instance());
+ renderThread->AddObserver(m_renderConfiguration.data());
+ renderThread->AddObserver(m_userResourceController.data());
#if QT_CONFIG(webengine_spellchecker)
if (!m_spellCheck)
InitSpellCheck();
#endif
- // Allow XMLHttpRequests from qrc to file.
- // ### consider removing for Qt6
- blink::WebURL qrc(blink::KURL("qrc:"));
- blink::WebString file(blink::WebString::FromASCII("file"));
- blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(
- qrc, file, blink::WebString(), 0, network::mojom::CorsDomainMatchMode::kAllowSubdomains,
- network::mojom::CorsPortMatchMode::kAllowAnyPort,
- network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
-
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Allow the pdf viewer extension to access chrome resources
- blink::WebURL pdfViewerExtension(blink::KURL("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai"));
+ blink::WebURL pdfViewerExtension(GURL("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai"));
blink::WebString chromeResources(blink::WebString::FromASCII("chrome"));
blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(
pdfViewerExtension, chromeResources, blink::WebString(), 0,
@@ -169,41 +131,49 @@ void ContentRendererClientQt::RenderThreadStarted()
void ContentRendererClientQt::ExposeInterfacesToBrowser(mojo::BinderMap* binders)
{
- binders->Add(m_visitedLinkReader->GetBindCallback(), base::SequencedTaskRunnerHandle::Get());
+ binders->Add<visitedlink::mojom::VisitedLinkNotificationSink>(
+ m_visitedLinkReader->GetBindCallback(), base::SingleThreadTaskRunner::GetCurrentDefault());
- binders->Add(base::BindRepeating(&web_cache::WebCacheImpl::BindReceiver,
- base::Unretained(m_webCacheImpl.get())),
- base::SequencedTaskRunnerHandle::Get());
+ binders->Add<web_cache::mojom::WebCache>(
+ base::BindRepeating(&web_cache::WebCacheImpl::BindReceiver,
+ base::Unretained(m_webCacheImpl.get())),
+ base::SingleThreadTaskRunner::GetCurrentDefault());
#if QT_CONFIG(webengine_spellchecker)
- binders->Add(base::BindRepeating(
+ binders->Add<spellcheck::mojom::SpellChecker>(
+ base::BindRepeating(
[](ContentRendererClientQt *client,
mojo::PendingReceiver<spellcheck::mojom::SpellChecker> receiver) {
if (!client->m_spellCheck)
client->InitSpellCheck();
client->m_spellCheck->BindReceiver(std::move(receiver));
}, this),
- base::SequencedTaskRunnerHandle::Get());
+ base::SingleThreadTaskRunner::GetCurrentDefault());
#endif
-}
-void ContentRendererClientQt::RenderViewCreated(content::RenderView *render_view)
-{
- // RenderViewObservers destroy themselves with their RenderView.
- new RenderViewObserverQt(render_view);
- UserResourceController::instance()->renderViewCreated(render_view);
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ binders->Add<chrome::mojom::WebRtcLoggingAgent>(
+ base::BindRepeating(
+ [](ContentRendererClientQt *client,
+ mojo::PendingReceiver<chrome::mojom::WebRtcLoggingAgent> receiver) {
+ client->GetWebRtcLoggingAgent()->AddReceiver(std::move(receiver));
+ }, this),
+ base::SingleThreadTaskRunner::GetCurrentDefault());
+#endif
}
void ContentRendererClientQt::RenderFrameCreated(content::RenderFrame *render_frame)
{
QtWebEngineCore::RenderFrameObserverQt *render_frame_observer =
new QtWebEngineCore::RenderFrameObserverQt(render_frame, m_webCacheImpl.data());
+ if (render_frame->IsMainFrame()) {
#if QT_CONFIG(webengine_webchannel)
- if (render_frame->IsMainFrame())
new WebChannelIPCTransport(render_frame);
#endif
+ new WebEnginePageRenderFrame(render_frame);
+ }
- UserResourceController::instance()->renderFrameCreated(render_frame);
+ m_userResourceController->renderFrameCreated(render_frame);
new QtWebEngineCore::ContentSettingsObserverQt(render_frame);
@@ -213,10 +183,37 @@ void ContentRendererClientQt::RenderFrameCreated(content::RenderFrame *render_fr
#if QT_CONFIG(webengine_printing_and_pdf)
new printing::PrintRenderFrameHelper(render_frame, base::WrapUnique(new PrintWebViewHelperDelegateQt()));
#endif // QT_CONFIG(webengine_printing_and_pdf)
+
+ blink::AssociatedInterfaceRegistry *associated_interfaces = render_frame_observer->associatedInterfaces();
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
+ associated_interfaces->AddInterface<extensions::mojom::MimeHandlerViewContainerManager>(
+ base::BindRepeating(
+ &extensions::MimeHandlerViewContainerManager::BindReceiver,
+ render_frame->GetRoutingID()));
+
auto registry = std::make_unique<service_manager::BinderRegistry>();
ExtensionsRendererClientQt::GetInstance()->RenderFrameCreated(render_frame, render_frame_observer->registry());
#endif
+
+ autofill::PasswordAutofillAgent *password_autofill_agent =
+ new autofill::PasswordAutofillAgent(render_frame, associated_interfaces);
+ autofill::PasswordGenerationAgent *password_generation_agent =
+ new autofill::PasswordGenerationAgent(render_frame, password_autofill_agent,
+ associated_interfaces);
+
+ new autofill::AutofillAgent(render_frame, password_autofill_agent, password_generation_agent,
+ associated_interfaces);
+}
+
+void ContentRendererClientQt::WebViewCreated(blink::WebView *web_view,
+ bool was_created_by_renderer,
+ const url::Origin *outermost_origin)
+{
+ Q_UNUSED(was_created_by_renderer);
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ ExtensionsRendererClientQt::GetInstance()->WebViewCreated(web_view, outermost_origin);
+#endif
}
void ContentRendererClientQt::RunScriptsAtDocumentStart(content::RenderFrame *render_frame)
@@ -234,7 +231,7 @@ void ContentRendererClientQt::RunScriptsAtDocumentEnd(content::RenderFrame *rend
RenderFrameObserverQt *render_frame_observer = RenderFrameObserverQt::Get(render_frame);
if (render_frame_observer && !render_frame_observer->isFrameDetached())
- UserResourceController::instance()->RunScriptsAtDocumentEnd(render_frame);
+ m_userResourceController->RunScriptsAtDocumentEnd(render_frame);
#if BUILDFLAG(ENABLE_EXTENSIONS)
ExtensionsRendererClientQt::GetInstance()->RunScriptsAtDocumentEnd(render_frame);
@@ -250,40 +247,29 @@ void ContentRendererClientQt::RunScriptsAtDocumentIdle(content::RenderFrame *ren
#endif
}
-bool ContentRendererClientQt::HasErrorPage(int httpStatusCode)
-{
- // Use an internal error page, if we have one for the status code.
- if (!error_page::LocalizedError::HasStrings(error_page::Error::kHttpErrorDomain, httpStatusCode)) {
- return false;
- }
-
- return true;
-}
-
-bool ContentRendererClientQt::ShouldSuppressErrorPage(content::RenderFrame *frame, const GURL &)
-{
- return !(frame->GetWebkitPreferences().enable_error_page);
-}
-
// To tap into the chromium localized strings. Ripped from the chrome layer (highly simplified).
void ContentRendererClientQt::PrepareErrorPage(content::RenderFrame *renderFrame,
const blink::WebURLError &web_error,
const std::string &httpMethod,
+ content::mojom::AlternativeErrorPageOverrideInfoPtr alternative_error_page_info,
std::string *errorHtml)
{
GetNavigationErrorStringsInternal(
renderFrame, httpMethod,
- error_page::Error::NetError(web_error.url(), web_error.reason(), web_error.has_copy_in_cache()), errorHtml);
+ error_page::Error::NetError((GURL)web_error.url(), web_error.reason(), web_error.extended_reason(),
+ net::ResolveErrorInfo(), web_error.has_copy_in_cache()),
+ errorHtml);
}
void ContentRendererClientQt::PrepareErrorPageForHttpStatusError(content::RenderFrame *renderFrame,
- const GURL &unreachable_url,
+ const blink::WebURLError &error,
const std::string &httpMethod,
int http_status,
+ content::mojom::AlternativeErrorPageOverrideInfoPtr alternative_error_page_info,
std::string *errorHtml)
{
GetNavigationErrorStringsInternal(renderFrame, httpMethod,
- error_page::Error::HttpError(unreachable_url, http_status),
+ error_page::Error::HttpError(error.url(), http_status),
errorHtml);
}
@@ -303,11 +289,12 @@ void ContentRendererClientQt::GetNavigationErrorStringsInternal(content::RenderF
// TODO(elproxy): We could potentially get better diagnostics here by first calling
// NetErrorHelper::GetErrorStringsForDnsProbe, but that one is harder to untangle.
+ base::Value::Dict error_page_params;
error_page::LocalizedError::PageState errorPageState =
- error_page::LocalizedError::GetPageState(
- error.reason(), error.domain(), error.url(), isPost,
- error.stale_copy_in_cache(), false, RenderThreadObserverQt::is_incognito_process(), false,
- false, locale, std::unique_ptr<error_page::ErrorPageParams>());
+ error_page::LocalizedError::GetPageState(
+ error.reason(), error.domain(), error.url(), isPost, false,
+ error.stale_copy_in_cache(), false,
+ RenderConfiguration::is_incognito_process(), false, false, false, locale, false, &error_page_params);
resourceId = IDR_NET_ERROR_HTML;
@@ -316,7 +303,7 @@ void ContentRendererClientQt::GetNavigationErrorStringsInternal(content::RenderF
if (template_html.empty())
NOTREACHED() << "unable to load template. ID: " << resourceId;
else // "t" is the id of the templates root node.
- *errorHtml = webui::GetTemplatesHtml(template_html, &errorPageState.strings, "t");
+ *errorHtml = webui::GetTemplatesHtml(template_html, errorPageState.strings, "t");
}
}
@@ -335,6 +322,92 @@ std::unique_ptr<blink::WebPrescientNetworking> ContentRendererClientQt::CreatePr
return std::make_unique<network_hints::WebPrescientNetworkingImpl>(render_frame);
}
+namespace {
+bool IsPdfExtensionOrigin(const url::Origin &origin)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ return origin.scheme() == extensions::kExtensionScheme &&
+ origin.host() == extension_misc::kPdfExtensionId;
+#else
+ return false;
+#endif
+}
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+void AppendParams(const std::vector<content::WebPluginMimeType::Param> &additional_params,
+ blink::WebVector<blink::WebString> *existing_names,
+ blink::WebVector<blink::WebString> *existing_values)
+{
+ DCHECK(existing_names->size() == existing_values->size());
+ size_t existing_size = existing_names->size();
+ size_t total_size = existing_size + additional_params.size();
+
+ blink::WebVector<blink::WebString> names(total_size);
+ blink::WebVector<blink::WebString> values(total_size);
+
+ for (size_t i = 0; i < existing_size; ++i) {
+ names[i] = (*existing_names)[i];
+ values[i] = (*existing_values)[i];
+ }
+
+ for (size_t i = 0; i < additional_params.size(); ++i) {
+ names[existing_size + i] = blink::WebString::FromUTF16(additional_params[i].name);
+ values[existing_size + i] = blink::WebString::FromUTF16(additional_params[i].value);
+ }
+
+ existing_names->Swap(names);
+ existing_values->Swap(values);
+}
+#endif // BUILDFLAG(ENABLE_PLUGINS)
+
+#if QT_CONFIG(webengine_printing_and_pdf)
+// based on chrome/renderer/pdf/chrome_pdf_internal_plugin_delegate.cc:
+class PdfInternalPluginDelegateQt final
+ : public pdf::PdfInternalPluginDelegate
+{
+public:
+ PdfInternalPluginDelegateQt() = default;
+ PdfInternalPluginDelegateQt(const PdfInternalPluginDelegateQt &) = delete;
+ PdfInternalPluginDelegateQt& operator=(const PdfInternalPluginDelegateQt &) = delete;
+ ~PdfInternalPluginDelegateQt() override = default;
+
+ // `pdf::PdfInternalPluginDelegate`:
+ bool IsAllowedOrigin(const url::Origin &origin) const override;
+};
+
+bool PdfInternalPluginDelegateQt::IsAllowedOrigin(const url::Origin &origin) const
+{
+ return IsPdfExtensionOrigin(origin);
+}
+#endif
+} // namespace
+
+bool ContentRendererClientQt::IsPluginHandledExternally(content::RenderFrame *render_frame,
+ const blink::WebElement &plugin_element,
+ const GURL &original_url,
+ const std::string &original_mime_type)
+{
+#if BUILDFLAG(ENABLE_EXTENSIONS) && BUILDFLAG(ENABLE_PLUGINS)
+ bool found = false;
+ content::WebPluginInfo plugin_info;
+ std::string mime_type;
+
+ static_cast<content::RenderFrameImpl *>(render_frame)->GetPepperHost()->GetPluginInfo(
+ original_url, original_mime_type, &found, &plugin_info, &mime_type);
+ if (!found)
+ return false;
+ if (IsPdfExtensionOrigin(render_frame->GetWebFrame()->GetSecurityOrigin()))
+ return true;
+ return extensions::MimeHandlerViewContainerManager::Get(
+ content::RenderFrame::FromWebFrame(
+ plugin_element.GetDocument().GetFrame()),
+ true /* create_if_does_not_exist */)
+ ->CreateFrameContainer(plugin_element, original_url, mime_type, plugin_info);
+#else
+ return false;
+#endif
+}
+
bool ContentRendererClientQt::OverrideCreatePlugin(content::RenderFrame *render_frame,
const blink::WebPluginParams &params,
blink::WebPlugin **plugin)
@@ -342,56 +415,52 @@ bool ContentRendererClientQt::OverrideCreatePlugin(content::RenderFrame *render_
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (!ExtensionsRendererClientQt::GetInstance()->OverrideCreatePlugin(render_frame, params))
return false;
-#endif //ENABLE_EXTENSIONS
+#endif // ENABLE_EXTENSIONS
#if BUILDFLAG(ENABLE_PLUGINS)
- chrome::mojom::PluginInfoPtr plugin_info = chrome::mojom::PluginInfo::New();
content::WebPluginInfo info;
std::string mime_type;
bool found = false;
- render_frame->Send(new FrameHostMsg_GetPluginInfo(render_frame->GetRoutingID(), params.url,
- render_frame->GetWebFrame()->Top()->GetSecurityOrigin(),
- params.mime_type.Utf8(), &found, &info, &mime_type));
+ static_cast<content::RenderFrameImpl *>(render_frame)->GetPepperHost()->GetPluginInfo(
+ params.url, params.mime_type.Utf8(), &found, &info, &mime_type);
if (!found) {
- *plugin = CreatePlugin(render_frame, params, *plugin_info);
+ *plugin = LoadablePluginPlaceholderQt::CreateLoadableMissingPlugin(render_frame, params)->plugin();
return true;
}
-#endif // BUILDFLAG(ENABLE_PLUGINS)
- return content::ContentRendererClient::OverrideCreatePlugin(render_frame, params, plugin);
-}
+ if (info.name == u"Chromium PDF Viewer") {
+ blink::WebPluginParams new_params(params);
+ for (const auto& mime_type : info.mime_types) {
+ if (mime_type.mime_type == params.mime_type.Utf8()) {
+ AppendParams(mime_type.additional_params, &new_params.attribute_names,
+ &new_params.attribute_values);
+ break;
+ }
+ }
-#if BUILDFLAG(ENABLE_PLUGINS)
-// static
-blink::WebPlugin* ContentRendererClientQt::CreatePlugin(content::RenderFrame* render_frame,
- const blink::WebPluginParams& original_params,
- const chrome::mojom::PluginInfo& plugin_info)
-{
- // If the browser plugin is to be enabled, this should be handled by the
- // renderer, so the code won't reach here due to the early exit in OverrideCreatePlugin.
- return LoadablePluginPlaceholderQt::CreateLoadableMissingPlugin(render_frame, original_params)->plugin();
+ *plugin = pdf::CreateInternalPlugin(std::move(new_params), render_frame, std::make_unique<PdfInternalPluginDelegateQt>());
+ return true;
+ }
+ *plugin = render_frame->CreatePlugin(info, params);
+#endif // BUILDFLAG(ENABLE_PLUGINS)
+ return true;
}
-#endif //BUILDFLAG(ENABLE_PLUGINS)
-content::BrowserPluginDelegate *ContentRendererClientQt::CreateBrowserPluginDelegate(content::RenderFrame *render_frame,
- const content::WebPluginInfo &info,
- const std::string &mime_type,
- const GURL &original_url)
+bool ContentRendererClientQt::IsOriginIsolatedPepperPlugin(const base::FilePath& plugin_path)
{
-#if BUILDFLAG(ENABLE_EXTENSIONS)
- return ExtensionsRendererClientQt::GetInstance()->CreateBrowserPluginDelegate(render_frame, info, mime_type,
- original_url);
-#else
- return nullptr;
-#endif
+ return plugin_path.value() == FILE_PATH_LITERAL("internal-pdf-viewer");
}
-void ContentRendererClientQt::BindReceiverOnMainThread(mojo::GenericPendingReceiver receiver)
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+chrome::WebRtcLoggingAgentImpl *ContentRendererClientQt::GetWebRtcLoggingAgent()
{
- std::string interface_name = *receiver.interface_name();
- auto pipe = receiver.PassPipe();
- m_registry.TryBindInterface(interface_name, &pipe);
+ if (!m_webrtcLoggingAgentImpl) {
+ m_webrtcLoggingAgentImpl = std::make_unique<chrome::WebRtcLoggingAgentImpl>();
+ }
+
+ return m_webrtcLoggingAgentImpl.get();
}
+#endif // QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
void ContentRendererClientQt::GetInterface(const std::string &interface_name, mojo::ScopedMessagePipeHandle interface_pipe)
{
@@ -405,129 +474,125 @@ void ContentRendererClientQt::GetInterface(const std::string &interface_name, mo
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
// External Clear Key (used for testing).
-static void AddExternalClearKey(std::vector<std::unique_ptr<media::KeySystemProperties>> *concrete_key_systems)
-{
- // TODO(xhwang): Move these into an array so we can use a for loop to add
- // supported key systems below.
- static const char kExternalClearKeyKeySystem[] =
- "org.chromium.externalclearkey";
- static const char kExternalClearKeyDecryptOnlyKeySystem[] =
- "org.chromium.externalclearkey.decryptonly";
- static const char kExternalClearKeyMessageTypeTestKeySystem[] =
- "org.chromium.externalclearkey.messagetypetest";
- static const char kExternalClearKeyFileIOTestKeySystem[] =
- "org.chromium.externalclearkey.fileiotest";
- static const char kExternalClearKeyOutputProtectionTestKeySystem[] =
- "org.chromium.externalclearkey.outputprotectiontest";
- static const char kExternalClearKeyPlatformVerificationTestKeySystem[] =
- "org.chromium.externalclearkey.platformverificationtest";
- static const char kExternalClearKeyInitializeFailKeySystem[] =
- "org.chromium.externalclearkey.initializefail";
- static const char kExternalClearKeyCrashKeySystem[] =
- "org.chromium.externalclearkey.crash";
- static const char kExternalClearKeyVerifyCdmHostTestKeySystem[] =
- "org.chromium.externalclearkey.verifycdmhosttest";
- static const char kExternalClearKeyStorageIdTestKeySystem[] =
- "org.chromium.externalclearkey.storageidtest";
- static const char kExternalClearKeyDifferentGuidTestKeySystem[] =
- "org.chromium.externalclearkey.differentguid";
- static const char kExternalClearKeyCdmProxyTestKeySystem[] =
- "org.chromium.externalclearkey.cdmproxytest";
-
- media::mojom::KeySystemCapabilityPtr capability;
- if (!content::IsKeySystemSupported(kExternalClearKeyKeySystem, &capability)) {
- DVLOG(1) << "External Clear Key not supported";
+static void AddExternalClearKey(const media::mojom::KeySystemCapabilityPtr &capability,
+ media::KeySystemInfos* key_systems)
+{
+ Q_UNUSED(capability);
+ if (!base::FeatureList::IsEnabled(media::kExternalClearKeyForTesting)) {
+ DLOG(ERROR) << "ExternalClearKey supported despite not enabled.";
return;
}
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyKeySystem));
-
- // Add support of decrypt-only mode in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyDecryptOnlyKeySystem));
-
- // A key system that triggers various types of messages in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyMessageTypeTestKeySystem));
-
- // A key system that triggers the FileIO test in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyFileIOTestKeySystem));
-
- // A key system that triggers the output protection test in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyOutputProtectionTestKeySystem));
-
- // A key system that triggers the platform verification test in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyPlatformVerificationTestKeySystem));
+ // TODO(xhwang): Actually use `capability` to determine capabilities.
+ key_systems->push_back(std::make_unique<cdm::ExternalClearKeyKeySystemInfo>());
+}
- // A key system that Chrome thinks is supported by ClearKeyCdm, but actually
- // will be refused by ClearKeyCdm. This is to test the CDM initialization
- // failure case.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyInitializeFailKeySystem));
+#if BUILDFLAG(ENABLE_WIDEVINE)
+media::SupportedCodecs GetVP9Codecs(const base::flat_set<media::VideoCodecProfile> &profiles)
+{
+ if (profiles.empty()) {
+ // If no profiles are specified, then all are supported.
+ return media::EME_CODEC_VP9_PROFILE0 | media::EME_CODEC_VP9_PROFILE2;
+ }
- // A key system that triggers a crash in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyCrashKeySystem));
+ media::SupportedCodecs supported_vp9_codecs = media::EME_CODEC_NONE;
+ for (const auto& profile : profiles) {
+ switch (profile) {
+ case media::VP9PROFILE_PROFILE0:
+ supported_vp9_codecs |= media::EME_CODEC_VP9_PROFILE0;
+ break;
+ case media::VP9PROFILE_PROFILE2:
+ supported_vp9_codecs |= media::EME_CODEC_VP9_PROFILE2;
+ break;
+ default:
+ DVLOG(1) << "Unexpected " << media::GetCodecName(media::VideoCodec::kVP9)
+ << " profile: " << media::GetProfileName(profile);
+ break;
+ }
+ }
- // A key system that triggers the verify host files test in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyVerifyCdmHostTestKeySystem));
+ return supported_vp9_codecs;
+}
- // A key system that fetches the Storage ID in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyStorageIdTestKeySystem));
+#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
+media::SupportedCodecs GetHevcCodecs(const base::flat_set<media::VideoCodecProfile> &profiles)
+{
+ // If no profiles are specified, then all are supported.
+ if (profiles.empty()) {
+ return media::EME_CODEC_HEVC_PROFILE_MAIN |
+ media::EME_CODEC_HEVC_PROFILE_MAIN10;
+ }
- // A key system that is registered with a different CDM GUID.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyDifferentGuidTestKeySystem));
+ media::SupportedCodecs supported_hevc_codecs = media::EME_CODEC_NONE;
+ for (const auto& profile : profiles) {
+ switch (profile) {
+ case media::HEVCPROFILE_MAIN:
+ supported_hevc_codecs |= media::EME_CODEC_HEVC_PROFILE_MAIN;
+ break;
+ case media::HEVCPROFILE_MAIN10:
+ supported_hevc_codecs |= media::EME_CODEC_HEVC_PROFILE_MAIN10;
+ break;
+ default:
+ DVLOG(1) << "Unexpected " << media::GetCodecName(media::VideoCodec::kHEVC)
+ << " profile: " << media::GetProfileName(profile);
+ break;
+ }
+ }
- // A key system that triggers CDM Proxy test in ClearKeyCdm.
- concrete_key_systems->emplace_back(
- new cdm::ExternalClearKeyProperties(kExternalClearKeyCdmProxyTestKeySystem));
+ return supported_hevc_codecs;
}
+#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC)
-#if BUILDFLAG(ENABLE_WIDEVINE)
-static media::SupportedCodecs GetSupportedCodecs(const std::vector<media::VideoCodec> &supported_video_codecs,
+static media::SupportedCodecs GetSupportedCodecs(const media::CdmCapability& capability,
bool is_secure)
{
media::SupportedCodecs supported_codecs = media::EME_CODEC_NONE;
- // Audio codecs are always supported because the CDM only does decrypt-only
- // for audio. The only exception is when |is_secure| is true and there's no
- // secure video decoder available, which is a signal that secure hardware
- // decryption is not available either.
- // TODO(sandersd): Distinguish these from those that are directly supported,
- // as those may offer a higher level of protection.
- if (!supported_video_codecs.empty() || !is_secure) {
- supported_codecs |= media::EME_CODEC_OPUS;
- supported_codecs |= media::EME_CODEC_VORBIS;
- supported_codecs |= media::EME_CODEC_FLAC;
+ for (const auto& codec : capability.audio_codecs) {
+ switch (codec) {
+ case media::AudioCodec::kOpus:
+ supported_codecs |= media::EME_CODEC_OPUS;
+ break;
+ case media::AudioCodec::kVorbis:
+ supported_codecs |= media::EME_CODEC_VORBIS;
+ break;
+ case media::AudioCodec::kFLAC:
+ supported_codecs |= media::EME_CODEC_FLAC;
+ break;
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
- supported_codecs |= media::EME_CODEC_AAC;
-#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+ case media::AudioCodec::kAAC:
+ supported_codecs |= media::EME_CODEC_AAC;
+ break;
+#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+ default:
+ DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec);
+ break;
+ }
}
- // Video codecs are determined by what was registered for the CDM.
- for (const auto &codec : supported_video_codecs) {
- switch (codec) {
- case media::VideoCodec::kCodecVP8:
+ for (const auto &codec : capability.video_codecs) {
+ switch (codec.first) {
+ case media::VideoCodec::kVP8:
supported_codecs |= media::EME_CODEC_VP8;
break;
- case media::VideoCodec::kCodecVP9:
- supported_codecs |= media::EME_CODEC_VP9_PROFILE0;
- supported_codecs |= media::EME_CODEC_VP9_PROFILE2;
+ case media::VideoCodec::kVP9:
+ supported_codecs |= GetVP9Codecs(codec.second.supported_profiles);
+ break;
+ case media::VideoCodec::kAV1:
+ supported_codecs |= media::EME_CODEC_AV1;
break;
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
- case media::VideoCodec::kCodecH264:
+ case media::VideoCodec::kH264:
supported_codecs |= media::EME_CODEC_AVC1;
break;
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
+ case media::VideoCodec::kHEVC:
+ supported_codecs |= GetHevcCodecs(codec.second.supported_profiles);
+ break;
+#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC)
default:
- DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec);
+ DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec.first);
break;
}
}
@@ -535,23 +600,36 @@ static media::SupportedCodecs GetSupportedCodecs(const std::vector<media::VideoC
return supported_codecs;
}
-static void AddWidevine(std::vector<std::unique_ptr<media::KeySystemProperties>> *concrete_key_systems)
+static void AddWidevine(const media::mojom::KeySystemCapabilityPtr &capability,
+ media::KeySystemInfos *key_systems)
{
- media::mojom::KeySystemCapabilityPtr capability;
- if (!content::IsKeySystemSupported(kWidevineKeySystem, &capability)) {
- DVLOG(1) << "Widevine CDM is not currently available.";
- return;
+ // Codecs and encryption schemes.
+ media::SupportedCodecs codecs = media::EME_CODEC_NONE;
+ media::SupportedCodecs hw_secure_codecs = media::EME_CODEC_NONE;
+ base::flat_set<media::EncryptionScheme> encryption_schemes;
+ base::flat_set<media::EncryptionScheme> hw_secure_encryption_schemes;
+ base::flat_set<media::CdmSessionType> session_types;
+ base::flat_set<media::CdmSessionType> hw_secure_session_types;
+ if (capability->sw_secure_capability) {
+ codecs = GetSupportedCodecs(capability->sw_secure_capability.value(), /*is_secure=*/false);
+ encryption_schemes = capability->sw_secure_capability->encryption_schemes;
+ if (!base::Contains(capability->sw_secure_capability->session_types, media::CdmSessionType::kTemporary)) {
+ DVLOG(1) << "Temporary sessions must be supported.";
+ return;
+ }
}
- // Codecs and encryption schemes.
- auto codecs = GetSupportedCodecs(capability->video_codecs, /*is_secure=*/false);
- const auto &encryption_schemes = capability->encryption_schemes;
- auto hw_secure_codecs = GetSupportedCodecs(capability->hw_secure_video_codecs,
- /*is_secure=*/true);
- const auto &hw_secure_encryption_schemes = capability->hw_secure_encryption_schemes;
+ if (capability->hw_secure_capability) {
+ hw_secure_codecs = GetSupportedCodecs(capability->hw_secure_capability.value(), /*is_secure=*/true);
+ hw_secure_encryption_schemes = capability->hw_secure_capability->encryption_schemes;
+ if (!base::Contains(capability->hw_secure_capability->session_types, media::CdmSessionType::kTemporary)) {
+ DVLOG(1) << "Temporary sessions must be supported.";
+ return;
+ }
+ }
// Robustness.
- using Robustness = cdm::WidevineKeySystemProperties::Robustness;
+ using Robustness = cdm::WidevineKeySystemInfo::Robustness;
auto max_audio_robustness = Robustness::SW_SECURE_CRYPTO;
auto max_video_robustness = Robustness::SW_SECURE_DECODE;
@@ -560,40 +638,52 @@ static void AddWidevine(std::vector<std::unique_ptr<media::KeySystemProperties>>
max_video_robustness = Robustness::HW_SECURE_ALL;
}
- // Session types.
- bool cdm_supports_temporary_session = base::Contains(capability->session_types, media::CdmSessionType::kTemporary);
- if (!cdm_supports_temporary_session) {
- DVLOG(1) << "Temporary session must be supported.";
- return;
- }
-
- auto persistent_license_support = media::EmeSessionTypeSupport::NOT_SUPPORTED;
- auto persistent_usage_record_support = media::EmeSessionTypeSupport::NOT_SUPPORTED;
-
// Others.
auto persistent_state_support = media::EmeFeatureSupport::REQUESTABLE;
auto distinctive_identifier_support = media::EmeFeatureSupport::NOT_SUPPORTED;
- concrete_key_systems->emplace_back(new cdm::WidevineKeySystemProperties(
- codecs, encryption_schemes, hw_secure_codecs,
- hw_secure_encryption_schemes, max_audio_robustness, max_video_robustness,
- persistent_license_support, persistent_usage_record_support,
- persistent_state_support, distinctive_identifier_support));
+ key_systems->emplace_back(new cdm::WidevineKeySystemInfo(
+ codecs, std::move(encryption_schemes), std::move(session_types),
+ hw_secure_codecs, std::move(hw_secure_encryption_schemes),
+ std::move(hw_secure_session_types),
+ max_audio_robustness, max_video_robustness,
+ persistent_state_support,
+ distinctive_identifier_support));
}
#endif // BUILDFLAG(ENABLE_WIDEVINE)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-void ContentRendererClientQt::AddSupportedKeySystems(std::vector<std::unique_ptr<media::KeySystemProperties>> *key_systems)
+void OnKeySystemSupportUpdated(media::GetSupportedKeySystemsCB cb,
+ content::KeySystemCapabilityPtrMap key_system_capabilities)
{
+ media::KeySystemInfos key_systems;
+ for (const auto &entry : key_system_capabilities) {
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- if (base::FeatureList::IsEnabled(media::kExternalClearKeyForTesting))
- AddExternalClearKey(key_systems);
-
+ const auto &key_system = entry.first;
+ const auto &capability = entry.second;
#if BUILDFLAG(ENABLE_WIDEVINE)
- AddWidevine(key_systems);
+ if (key_system == kWidevineKeySystem) {
+ AddWidevine(capability, &key_systems);
+ continue;
+ }
#endif // BUILDFLAG(ENABLE_WIDEVINE)
+ if (key_system == media::kExternalClearKeyKeySystem) {
+ AddExternalClearKey(capability, &key_systems);
+ continue;
+ }
+
+ DLOG(ERROR) << "Unrecognized key system: " << key_system;
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
+ }
+
+ cb.Run(std::move(key_systems));
+}
+
+void ContentRendererClientQt::GetSupportedKeySystems(media::GetSupportedKeySystemsCB cb)
+{
+ content::ObserveKeySystemSupportUpdate(
+ base::BindRepeating(&OnKeySystemSupportUpdated, std::move(cb)));
}
#if QT_CONFIG(webengine_spellchecker)
@@ -606,25 +696,16 @@ void ContentRendererClientQt::InitSpellCheck()
void ContentRendererClientQt::WillSendRequest(blink::WebLocalFrame *frame,
ui::PageTransition transition_type,
const blink::WebURL &url,
- const blink::WebURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin *initiator_origin,
- GURL *new_url,
- bool *attach_same_site_cookies)
+ GURL *new_url)
{
#if BUILDFLAG(ENABLE_EXTENSIONS)
- ExtensionsRendererClientQt::GetInstance()->WillSendRequest(frame, transition_type, url, /*site_for_cookies,*/
- initiator_origin, new_url, attach_same_site_cookies);
+ ExtensionsRendererClientQt::GetInstance()->WillSendRequest(frame, transition_type, url, site_for_cookies,
+ initiator_origin, new_url);
if (!new_url->is_empty())
return;
#endif
}
-bool ContentRendererClientQt::RequiresWebComponentsV0(const GURL &url)
-{
- Q_UNUSED(url);
- // Google services still presents pages using these features
- // to Chromium 80 based browsers (YouTube in particular).
- return true;
-}
-
} // namespace QtWebEngineCore
diff --git a/src/core/renderer/content_renderer_client_qt.h b/src/core/renderer/content_renderer_client_qt.h
index f2e725453..b2231f00a 100644
--- a/src/core/renderer/content_renderer_client_qt.h
+++ b/src/core/renderer/content_renderer_client_qt.h
@@ -1,58 +1,24 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef CONTENT_RENDERER_CLIENT_QT_H
#define CONTENT_RENDERER_CLIENT_QT_H
#include "qtwebenginecoreglobal_p.h"
#include "content/public/renderer/content_renderer_client.h"
-#include "components/spellcheck/spellcheck_buildflags.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/local_interface_provider.h"
-#include "ppapi/buildflags/buildflags.h"
-
-#if BUILDFLAG(ENABLE_PLUGINS)
-#include "qtwebengine/browser/plugin.mojom.h"
-#include "third_party/blink/public/web/web_plugin_params.h"
-#endif
#include <QScopedPointer>
+namespace blink {
+class WebPlugin;
+struct WebPluginParams;
+}
+
+namespace chrome {
+class WebRtcLoggingAgentImpl;
+}
+
namespace error_page {
class Error;
}
@@ -69,14 +35,10 @@ class WebCacheImpl;
class SpellCheck;
#endif
-namespace content {
-struct WebPluginInfo;
-}
-
namespace QtWebEngineCore {
-class RenderThreadObserverQt;
-
+class UserResourceController;
+class RenderConfiguration;
class ContentRendererClientQt
: public content::ContentRendererClient
, public service_manager::LocalInterfaceProvider
@@ -88,56 +50,52 @@ public:
// content::ContentRendererClient:
void RenderThreadStarted() override;
void ExposeInterfacesToBrowser(mojo::BinderMap* binders) override;
- void RenderViewCreated(content::RenderView *render_view) override;
void RenderFrameCreated(content::RenderFrame *render_frame) override;
- bool ShouldSuppressErrorPage(content::RenderFrame *, const GURL &) override;
- bool HasErrorPage(int http_status_code) override;
+ void WebViewCreated(blink::WebView *web_view,
+ bool was_created_by_renderer,
+ const url::Origin *outermost_origin) override;
void PrepareErrorPage(content::RenderFrame *render_frame,
const blink::WebURLError &error,
const std::string &http_method,
+ content::mojom::AlternativeErrorPageOverrideInfoPtr alternative_error_page_info,
std::string *error_html) override;
void PrepareErrorPageForHttpStatusError(content::RenderFrame *render_frame,
- const GURL &unreachable_url,
+ const blink::WebURLError &error,
const std::string &http_method,
int http_status,
- std::string *error_html) override;
-
+ content::mojom::AlternativeErrorPageOverrideInfoPtr alternative_error_page_info,
+ std::string *error_html) override;
uint64_t VisitedLinkHash(const char *canonical_url, size_t length) override;
bool IsLinkVisited(uint64_t linkHash) override;
std::unique_ptr<blink::WebPrescientNetworking> CreatePrescientNetworking(content::RenderFrame *render_frame) override;
- void AddSupportedKeySystems(std::vector<std::unique_ptr<media::KeySystemProperties>> *key_systems) override;
-
+ void GetSupportedKeySystems(media::GetSupportedKeySystemsCB cb) override;
void RunScriptsAtDocumentStart(content::RenderFrame *render_frame) override;
void RunScriptsAtDocumentEnd(content::RenderFrame *render_frame) override;
void RunScriptsAtDocumentIdle(content::RenderFrame *render_frame) override;
+ bool IsPluginHandledExternally(content::RenderFrame *embedder_frame,
+ const blink::WebElement &plugin_element,
+ const GURL &original_url,
+ const std::string &original_mime_type) override;
bool OverrideCreatePlugin(content::RenderFrame *render_frame,
const blink::WebPluginParams &params,
blink::WebPlugin **plugin) override;
- content::BrowserPluginDelegate *CreateBrowserPluginDelegate(content::RenderFrame *render_frame,
- const content::WebPluginInfo &info,
- const std::string &mime_type,
- const GURL &original_url) override;
+ bool IsOriginIsolatedPepperPlugin(const base::FilePath& plugin_path) override;
void WillSendRequest(blink::WebLocalFrame *frame,
ui::PageTransition transition_type,
const blink::WebURL &url,
- const blink::WebURL &site_for_cookies,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin *initiator_origin,
- GURL *new_url,
- bool *attach_same_site_cookies) override;
+ GURL *new_url) override;
- void BindReceiverOnMainThread(mojo::GenericPendingReceiver receiver) override;
- bool RequiresWebComponentsV0(const GURL &url) override;
-
-#if BUILDFLAG(ENABLE_PLUGINS)
- static blink::WebPlugin* CreatePlugin(content::RenderFrame* render_frame,
- const blink::WebPluginParams& params,
- const chrome::mojom::PluginInfo& plugin_info);
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ chrome::WebRtcLoggingAgentImpl *GetWebRtcLoggingAgent();
#endif
+
private:
-#if BUILDFLAG(ENABLE_SPELLCHECK)
+#if QT_CONFIG(webengine_spellchecker)
void InitSpellCheck();
#endif
// service_manager::LocalInterfaceProvider:
@@ -146,16 +104,16 @@ private:
void GetNavigationErrorStringsInternal(content::RenderFrame *renderFrame, const std::string &httpMethod,
const error_page::Error &error, std::string *errorHtml);
- QScopedPointer<RenderThreadObserverQt> m_renderThreadObserver;
+ QScopedPointer<RenderConfiguration> m_renderConfiguration;
+ QScopedPointer<UserResourceController> m_userResourceController;
QScopedPointer<visitedlink::VisitedLinkReader> m_visitedLinkReader;
QScopedPointer<web_cache::WebCacheImpl> m_webCacheImpl;
#if QT_CONFIG(webengine_spellchecker)
QScopedPointer<SpellCheck> m_spellCheck;
#endif
-
- service_manager::BinderRegistry m_registry;
-
- DISALLOW_COPY_AND_ASSIGN(ContentRendererClientQt);
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ std::unique_ptr<chrome::WebRtcLoggingAgentImpl> m_webrtcLoggingAgentImpl;
+#endif
};
} // namespace
diff --git a/src/core/renderer/content_settings_observer_qt.cpp b/src/core/renderer/content_settings_observer_qt.cpp
index df9b77037..3e3c159f5 100644
--- a/src/core/renderer/content_settings_observer_qt.cpp
+++ b/src/core/renderer/content_settings_observer_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Based on chrome/renderer/content_settings_observer.cc:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -46,15 +10,12 @@
#include "content/public/renderer/render_frame.h"
#include "third_party/blink/public/platform/web_security_origin.h"
-#include "third_party/blink/public/web/web_plugin_document.h"
+#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "url/origin.h"
#include "common/qt_messages.h"
-using blink::WebSecurityOrigin;
-using blink::WebString;
-
namespace {
bool IsUniqueFrame(blink::WebFrame *frame)
@@ -82,21 +43,20 @@ bool ContentSettingsObserverQt::OnMessageReceived(const IPC::Message &message)
{
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ContentSettingsObserverQt, message)
- IPC_MESSAGE_HANDLER(QtWebEngineMsg_RequestFileSystemAccessAsyncResponse, OnRequestFileSystemAccessAsyncResponse)
+ IPC_MESSAGE_HANDLER(QtWebEngineMsg_RequestStorageAccessAsyncResponse, OnRequestStorageAccessAsyncResponse)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
-void ContentSettingsObserverQt::DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition /*transition*/)
+void ContentSettingsObserverQt::DidCommitProvisionalLoad(ui::PageTransition /*transition*/)
{
blink::WebLocalFrame *frame = render_frame()->GetWebFrame();
if (frame->Parent())
return; // Not a top-level navigation.
- if (!is_same_document_navigation)
- ClearBlockedContentSettings();
+ ClearBlockedContentSettings();
GURL url = frame->GetDocument().Url();
// If we start failing this DCHECK, please makes sure we don't regress
@@ -109,68 +69,51 @@ void ContentSettingsObserverQt::OnDestruct()
delete this;
}
-bool ContentSettingsObserverQt::AllowDatabase()
-{
- blink::WebFrame *frame = render_frame()->GetWebFrame();
- if (IsUniqueFrame(frame))
- return false;
-
- bool result = false;
- Send(new QtWebEngineHostMsg_AllowDatabase(routing_id(), url::Origin(frame->GetSecurityOrigin()).GetURL(),
- url::Origin(frame->Top()->GetSecurityOrigin()).GetURL(), &result));
- return result;
-}
-
-void ContentSettingsObserverQt::RequestFileSystemAccessAsync(base::OnceCallback<void(bool)> callback)
+void ContentSettingsObserverQt::AllowStorageAccess(StorageType storage_type,
+ base::OnceCallback<void(bool)> callback)
{
blink::WebFrame *frame = render_frame()->GetWebFrame();
if (IsUniqueFrame(frame)) {
std::move(callback).Run(false);
return;
}
+
++m_currentRequestId;
bool inserted = m_permissionRequests.insert(std::make_pair(m_currentRequestId, std::move(callback))).second;
// Verify there are no duplicate insertions.
DCHECK(inserted);
- Send(new QtWebEngineHostMsg_RequestFileSystemAccessAsync(routing_id(), m_currentRequestId,
- url::Origin(frame->GetSecurityOrigin()).GetURL(),
- url::Origin(frame->Top()->GetSecurityOrigin()).GetURL()));
+ Send(new QtWebEngineHostMsg_RequestStorageAccessAsync(routing_id(), m_currentRequestId,
+ url::Origin(frame->GetSecurityOrigin()).GetURL(),
+ url::Origin(frame->Top()->GetSecurityOrigin()).GetURL(),
+ int(storage_type)));
}
-bool ContentSettingsObserverQt::AllowIndexedDB()
-{
- blink::WebFrame *frame = render_frame()->GetWebFrame();
- if (IsUniqueFrame(frame))
- return false;
-
- bool result = false;
- Send(new QtWebEngineHostMsg_AllowIndexedDB(routing_id(),
- url::Origin(frame->GetSecurityOrigin()).GetURL(),
- url::Origin(frame->Top()->GetSecurityOrigin()).GetURL(), &result));
- return result;
-}
-
-bool ContentSettingsObserverQt::AllowStorage(bool local)
+bool ContentSettingsObserverQt::AllowStorageAccessSync(StorageType storage_type)
{
blink::WebLocalFrame *frame = render_frame()->GetWebFrame();
if (IsUniqueFrame(frame))
return false;
- StoragePermissionsKey key(url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL(), local);
- const auto permissions = m_cachedStoragePermissions.find(key);
- if (permissions != m_cachedStoragePermissions.end())
- return permissions->second;
+ bool sameOrigin = url::Origin(frame->Top()->GetSecurityOrigin()).IsSameOriginWith(url::Origin(frame->GetSecurityOrigin()));
+ StoragePermissionsKey key(url::Origin(frame->GetSecurityOrigin()).GetURL(), int(storage_type));
+ if (sameOrigin) {
+ const auto permissions = m_cachedStoragePermissions.find(key);
+ if (permissions != m_cachedStoragePermissions.end())
+ return permissions->second;
+ }
bool result = false;
- Send(new QtWebEngineHostMsg_AllowDOMStorage(routing_id(), url::Origin(frame->GetSecurityOrigin()).GetURL(),
- url::Origin(frame->Top()->GetSecurityOrigin()).GetURL(), local, &result));
- m_cachedStoragePermissions[key] = result;
+ Send(new QtWebEngineHostMsg_AllowStorageAccess(routing_id(), url::Origin(frame->GetSecurityOrigin()).GetURL(),
+ url::Origin(frame->Top()->GetSecurityOrigin()).GetURL(),
+ int(storage_type), &result));
+ if (sameOrigin)
+ m_cachedStoragePermissions[key] = result;
return result;
}
-void ContentSettingsObserverQt::OnRequestFileSystemAccessAsyncResponse(int request_id, bool allowed)
+void ContentSettingsObserverQt::OnRequestStorageAccessAsyncResponse(int request_id, bool allowed)
{
auto it = m_permissionRequests.find(request_id);
if (it == m_permissionRequests.end())
diff --git a/src/core/renderer/content_settings_observer_qt.h b/src/core/renderer/content_settings_observer_qt.h
index 0c69d289c..415d0b6b7 100644
--- a/src/core/renderer/content_settings_observer_qt.h
+++ b/src/core/renderer/content_settings_observer_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -50,10 +14,6 @@
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "url/gurl.h"
-namespace blink {
-class WebSecurityOrigin;
-}
-
namespace QtWebEngineCore {
// Handles blocking content per content settings for each RenderFrame.
@@ -67,33 +27,30 @@ public:
~ContentSettingsObserverQt() override;
// blink::WebContentSettingsClient:
- bool AllowDatabase() override;
- void RequestFileSystemAccessAsync(base::OnceCallback<void(bool)> callback) override;
- bool AllowIndexedDB() override;
- bool AllowStorage(bool local) override;
+ void AllowStorageAccess(StorageType storage_type,
+ base::OnceCallback<void(bool)> callback) override;
+ bool AllowStorageAccessSync(StorageType storage_type) override;
private:
// RenderFrameObserver implementation:
bool OnMessageReceived(const IPC::Message &message) override;
- void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override;
+ void DidCommitProvisionalLoad(ui::PageTransition transition) override;
void OnDestruct() override;
// Message handlers.
- void OnRequestFileSystemAccessAsyncResponse(int request_id, bool allowed);
+ void OnRequestStorageAccessAsyncResponse(int request_id, bool allowed);
// Clears m_cachedStoragePermissions
void ClearBlockedContentSettings();
// Caches the result of AllowStorage.
- using StoragePermissionsKey = std::pair<GURL, bool>;
+ using StoragePermissionsKey = std::pair<GURL, int>;
base::flat_map<StoragePermissionsKey, bool> m_cachedStoragePermissions;
int m_currentRequestId;
base::flat_map<int, base::OnceCallback<void(bool)>> m_permissionRequests;
-
- DISALLOW_COPY_AND_ASSIGN(ContentSettingsObserverQt);
};
} // namespace QtWebEngineCore
-#endif // RENDERER_CONTENT_SETTINGS_OBSERVER_QT_H
+#endif // CONTENT_SETTINGS_OBSERVER_QT_H
diff --git a/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.cpp b/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.cpp
index 418429330..191e36d04 100644
--- a/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.cpp
+++ b/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.cpp
@@ -1,44 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "extensions_dispatcher_delegate_qt.h"
+#include "chrome/grit/renderer_resources.h"
+#include "extensions/renderer/resource_bundle_source_map.h"
+
namespace QtWebEngineCore {
ExtensionsDispatcherDelegateQt::ExtensionsDispatcherDelegateQt()
@@ -49,4 +16,10 @@ ExtensionsDispatcherDelegateQt::~ExtensionsDispatcherDelegateQt()
{
}
+void ExtensionsDispatcherDelegateQt::PopulateSourceMap(extensions::ResourceBundleSourceMap *source_map)
+{
+ // Custom binding for hangout services extension.
+ source_map->RegisterSource("webrtcDesktopCapturePrivate", IDR_WEBRTC_DESKTOP_CAPTURE_PRIVATE_CUSTOM_BINDINGS_JS);
+}
+
} //namespace QtWebEngineCore
diff --git a/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.h b/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.h
index 25aa18e71..42ae165d1 100644
--- a/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.h
+++ b/src/core/renderer/extensions/extensions_dispatcher_delegate_qt.h
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef EXTENSIONSDISPATCHERDELEGATEQT_H
#define EXTENSIONSDISPATCHERDELEGATEQT_H
-#include "base/macros.h"
#include "extensions/renderer/dispatcher_delegate.h"
namespace QtWebEngineCore {
@@ -52,7 +15,8 @@ public:
~ExtensionsDispatcherDelegateQt() override;
private:
- DISALLOW_COPY_AND_ASSIGN(ExtensionsDispatcherDelegateQt);
+ // extensions::DispatcherDelegate implementation.
+ void PopulateSourceMap(extensions::ResourceBundleSourceMap *source_map) override;
};
} // namespace QtWebEngineCore
diff --git a/src/core/renderer/extensions/extensions_renderer_client_qt.cpp b/src/core/renderer/extensions/extensions_renderer_client_qt.cpp
index 7d4c9a83c..b36ed9e8b 100644
--- a/src/core/renderer/extensions/extensions_renderer_client_qt.cpp
+++ b/src/core/renderer/extensions/extensions_renderer_client_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on chrome/renderer/extensions/chrome_extensions_renderer_client.cc:
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
@@ -45,12 +9,14 @@
#include "extensions_renderer_client_qt.h"
#include "extensions_dispatcher_delegate_qt.h"
-#include "renderer/render_thread_observer_qt.h"
+#include "renderer/render_configuration.h"
#include "renderer_permissions_policy_delegate_qt.h"
#include "resource_request_policy_qt.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
+#include "base/stl_util.h"
+#include "base/types/optional_util.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
@@ -61,10 +27,8 @@
#include "extensions/common/switches.h"
#include "extensions/renderer/dispatcher.h"
#include "extensions/renderer/extension_frame_helper.h"
+#include "extensions/renderer/extension_web_view_helper.h"
#include "extensions/renderer/extensions_render_frame_observer.h"
-#include "extensions/renderer/guest_view/extensions_guest_view_container.h"
-#include "extensions/renderer/guest_view/extensions_guest_view_container_dispatcher.h"
-#include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.h"
#include "extensions/renderer/renderer_extension_registry.h"
#include "extensions/renderer/script_context.h"
#include "third_party/blink/public/platform/web_url.h"
@@ -72,7 +36,6 @@
namespace chrome {
const char kExtensionInvalidRequestURL[] = "chrome-extension://invalid/";
-const char kExtensionResourceInvalidRequestURL[] = "chrome-extension-resource://invalid/";
}
namespace QtWebEngineCore {
@@ -88,7 +51,7 @@ ExtensionsRendererClientQt::~ExtensionsRendererClientQt()
// Returns true if the current render process was launched incognito.
bool ExtensionsRendererClientQt::IsIncognitoProcess() const
{
- return RenderThreadObserverQt::is_incognito_process();
+ return RenderConfiguration::is_incognito_process();
}
// Returns the lowest isolated world ID available to extensions.
@@ -127,9 +90,6 @@ bool ExtensionsRendererClientQt::ExtensionAPIEnabledForServiceWorkerScript(const
if (!script_url.SchemeIs(extensions::kExtensionScheme))
return false;
- if (!extensions::ExtensionsClient::Get()->ExtensionAPIEnabledInExtensionServiceWorkers())
- return false;
-
const extensions::Extension* extension =
extensions::RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(script_url);
@@ -147,17 +107,18 @@ bool ExtensionsRendererClientQt::ExtensionAPIEnabledForServiceWorkerScript(const
void ExtensionsRendererClientQt::RenderThreadStarted()
{
content::RenderThread *thread = content::RenderThread::Get();
- // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
- // injects it using SetExtensionDispatcher(). Don't overwrite it.
if (!extension_dispatcher_)
extension_dispatcher_.reset(new extensions::Dispatcher(std::make_unique<ExtensionsDispatcherDelegateQt>()));
extension_dispatcher_->OnRenderThreadStarted(thread);
permissions_policy_delegate_.reset(new RendererPermissionsPolicyDelegateQt(extension_dispatcher_.get()));
resource_request_policy_.reset(new extensions::ResourceRequestPolicyQt(extension_dispatcher_.get()));
- guest_view_container_dispatcher_.reset(new extensions::ExtensionsGuestViewContainerDispatcher());
thread->AddObserver(extension_dispatcher_.get());
- thread->AddObserver(guest_view_container_dispatcher_.get());
+}
+
+void ExtensionsRendererClientQt::WebViewCreated(blink::WebView *web_view, const url::Origin *outermost_origin)
+{
+ new extensions::ExtensionWebViewHelper(web_view, outermost_origin);
}
void ExtensionsRendererClientQt::RenderFrameCreated(content::RenderFrame *render_frame,
@@ -181,12 +142,14 @@ bool ExtensionsRendererClientQt::OverrideCreatePlugin(content::RenderFrame *rend
void ExtensionsRendererClientQt::WillSendRequest(blink::WebLocalFrame *frame,
ui::PageTransition transition_type,
const blink::WebURL &url,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin *initiator_origin,
- GURL *new_url,
- bool *attach_same_site_cookies)
+ GURL *new_url)
{
if (url.ProtocolIs(extensions::kExtensionScheme) &&
- !resource_request_policy_->CanRequestResource(url, frame, transition_type)) {
+ !resource_request_policy_->CanRequestResource(url, frame,
+ transition_type,
+ base::OptionalFromPtr(initiator_origin))) {
*new_url = GURL(chrome::kExtensionInvalidRequestURL);
}
}
@@ -200,16 +163,6 @@ bool ExtensionsRendererClientQt::ShouldFork(blink::WebLocalFrame *frame,
return false; // TODO: Fix this to a sensible value
}
-content::BrowserPluginDelegate *ExtensionsRendererClientQt::CreateBrowserPluginDelegate(content::RenderFrame *render_frame,
- const content::WebPluginInfo &info,
- const std::string &mime_type,
- const GURL &original_url)
-{
- if (mime_type == content::kBrowserPluginMimeType)
- return new extensions::ExtensionsGuestViewContainer(render_frame);
- return new extensions::MimeHandlerViewContainer(render_frame, info, mime_type, original_url);
-}
-
void ExtensionsRendererClientQt::RunScriptsAtDocumentStart(content::RenderFrame *render_frame)
{
extension_dispatcher_->RunScriptsAtDocumentStart(render_frame);
diff --git a/src/core/renderer/extensions/extensions_renderer_client_qt.h b/src/core/renderer/extensions/extensions_renderer_client_qt.h
index 87e324213..163819cbc 100644
--- a/src/core/renderer/extensions/extensions_renderer_client_qt.h
+++ b/src/core/renderer/extensions/extensions_renderer_client_qt.h
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef EXTENSIONSRENDERERCLIENTQT_H
#define EXTENSIONSRENDERERCLIENTQT_H
#include <memory>
-#include <string>
-#include "base/macros.h"
#include "extensions/renderer/extensions_renderer_client.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "ui/base/page_transition_types.h"
@@ -54,13 +16,15 @@ namespace blink {
class WebLocalFrame;
struct WebPluginParams;
class WebURL;
+class WebView;
}
namespace content {
-class BrowserPluginDelegate;
class RenderFrame;
-class RenderView;
-struct WebPluginInfo;
+}
+
+namespace net {
+class SiteForCookies;
}
namespace url {
@@ -69,7 +33,6 @@ class Origin;
namespace extensions {
class Dispatcher;
-class ExtensionsGuestViewContainerDispatcher;
class ResourceRequestPolicyQt;
}
@@ -93,25 +56,23 @@ public:
// Match ContentRendererClientQt's method names...
void RenderThreadStarted();
+ void WebViewCreated(blink::WebView *web_view,
+ const url::Origin *outermost_origin);
void RenderFrameCreated(content::RenderFrame *, service_manager::BinderRegistry *);
bool OverrideCreatePlugin(content::RenderFrame *render_frame,
const blink::WebPluginParams &params);
void WillSendRequest(blink::WebLocalFrame *frame,
ui::PageTransition transition_type,
const blink::WebURL &url,
+ const net::SiteForCookies &site_for_cookies,
const url::Origin *initiator_origin,
- GURL *new_url,
- bool *attach_same_site_cookies);
+ GURL *new_url);
static bool ShouldFork(blink::WebLocalFrame *frame,
const GURL &url,
bool is_initial_navigation,
bool is_server_redirect,
bool *send_referrer);
- static content::BrowserPluginDelegate *CreateBrowserPluginDelegate(content::RenderFrame *render_frame,
- const content::WebPluginInfo &info,
- const std::string &mime_type,
- const GURL &original_url);
bool ExtensionAPIEnabledForServiceWorkerScript(const GURL &scope, const GURL &script_url) const override;
@@ -128,7 +89,6 @@ private:
std::unique_ptr<ExtensionsDispatcherDelegateQt> extension_dispatcher_delegate_;
std::unique_ptr<RendererPermissionsPolicyDelegateQt> permissions_policy_delegate_;
std::unique_ptr<extensions::Dispatcher> extension_dispatcher_;
- std::unique_ptr<extensions::ExtensionsGuestViewContainerDispatcher> guest_view_container_dispatcher_;
std::unique_ptr<extensions::ResourceRequestPolicyQt> resource_request_policy_;
};
diff --git a/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.cpp b/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.cpp
index aef4903b7..fdfbe463b 100644
--- a/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.cpp
+++ b/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "renderer_permissions_policy_delegate_qt.h"
diff --git a/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.h b/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.h
index 385b7a4b0..23bfa8c88 100644
--- a/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.h
+++ b/src/core/renderer/extensions/renderer_permissions_policy_delegate_qt.h
@@ -1,46 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef RENDERERPERMISSIONSPOLICYDELEGATEQT_H
#define RENDERERPERMISSIONSPOLICYDELEGATEQT_H
-#include "base/macros.h"
#include "extensions/common/permissions/permissions_data.h"
namespace extensions {
@@ -56,9 +19,6 @@ public:
~RendererPermissionsPolicyDelegateQt() override;
bool IsRestrictedUrl(const GURL &, std::string *) override;
-
-private:
- DISALLOW_COPY_AND_ASSIGN(RendererPermissionsPolicyDelegateQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/renderer/extensions/resource_request_policy_qt.cpp b/src/core/renderer/extensions/resource_request_policy_qt.cpp
index efe44521d..a61e53310 100644
--- a/src/core/renderer/extensions/resource_request_policy_qt.cpp
+++ b/src/core/renderer/extensions/resource_request_policy_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// based on chrome/renderer/extensions/resource_request_policy.cc:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -63,8 +27,9 @@ ResourceRequestPolicyQt::ResourceRequestPolicyQt(Dispatcher *dispatcher)
void ResourceRequestPolicyQt::OnExtensionLoaded(const Extension &extension)
{
- if (WebAccessibleResourcesInfo::HasWebAccessibleResources(&extension)
- || WebviewInfo::HasWebviewAccessibleResources(extension, m_dispatcher->webview_partition_id())
+ if (WebAccessibleResourcesInfo::HasWebAccessibleResources(&extension) ||
+ WebviewInfo::HasWebviewAccessibleResources(extension,
+ m_dispatcher->webview_partition_id().value_or(std::string()))
// // Hosted app icons are accessible.
// // TODO(devlin): Should we incorporate this into
// // WebAccessibleResourcesInfo?
@@ -85,7 +50,8 @@ void ResourceRequestPolicyQt::OnExtensionUnloaded(const ExtensionId &extension_i
// than those triggered through UI.
bool ResourceRequestPolicyQt::CanRequestResource(const GURL &resource_url,
blink::WebLocalFrame *frame,
- ui::PageTransition transition_type)
+ ui::PageTransition transition_type,
+ const absl::optional<url::Origin>& initiator_origin)
{
CHECK(resource_url.SchemeIs(kExtensionScheme));
@@ -96,7 +62,7 @@ bool ResourceRequestPolicyQt::CanRequestResource(const GURL &resource_url,
// current extension or has a devtools scheme.
GURL page_origin = url::Origin(frame->Top()->GetSecurityOrigin()).GetURL();
- GURL extension_origin = resource_url.GetOrigin();
+ GURL extension_origin = resource_url.DeprecatedGetOriginAsURL();
// We always allow loads in the following cases, regardless of web accessible
// resources:
@@ -112,7 +78,7 @@ bool ResourceRequestPolicyQt::CanRequestResource(const GURL &resource_url,
// of the frame, to account for about:blank subframes being scripted by an
// extension parent (though we'll still need the frame origin check for
// sandboxed frames).
- if (frame_url.GetOrigin() == extension_origin || page_origin == extension_origin)
+ if (frame_url.DeprecatedGetOriginAsURL() == extension_origin || page_origin == extension_origin)
return true;
if (!ui::PageTransitionIsWebTriggerable(transition_type))
@@ -165,8 +131,10 @@ bool ResourceRequestPolicyQt::CanRequestResource(const GURL &resource_url,
// Disallow loading of extension resources which are not explicitly listed
// as web or WebView accessible if the manifest version is 2 or greater.
- if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(extension, resource_url.path()) &&
- !WebviewInfo::IsResourceWebviewAccessible(extension, m_dispatcher->webview_partition_id(), resource_url.path()))
+ if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(extension, resource_url.path(), initiator_origin) &&
+ !WebviewInfo::IsResourceWebviewAccessible(extension,
+ m_dispatcher->webview_partition_id().value_or(std::string()),
+ resource_url.path()))
{
std::string message = base::StringPrintf(
"Denying load of %s. Resources must be listed in the "
diff --git a/src/core/renderer/extensions/resource_request_policy_qt.h b/src/core/renderer/extensions/resource_request_policy_qt.h
index e6d4e79bb..ec108519f 100644
--- a/src/core/renderer/extensions/resource_request_policy_qt.h
+++ b/src/core/renderer/extensions/resource_request_policy_qt.h
@@ -1,50 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef RESOURCEREQUESTPOLICYQT_H
#define RESOURCEREQUESTPOLICYQT_H
#include <set>
-#include "base/macros.h"
#include "extensions/common/extension_id.h"
+#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/page_transition_types.h"
+#include "url/origin.h"
class GURL;
@@ -73,7 +38,8 @@ public:
// than those triggered through UI.
bool CanRequestResource(const GURL &resource_url,
blink::WebLocalFrame *frame,
- ui::PageTransition transition_type);
+ ui::PageTransition transition_type,
+ const absl::optional<url::Origin> &initiator_origin);
private:
Dispatcher *m_dispatcher;
@@ -81,8 +47,6 @@ private:
// The set of extension IDs with any potentially web- or webview-accessible
// resources.
std::set<ExtensionId> m_web_accessible_ids;
-
- DISALLOW_COPY_AND_ASSIGN(ResourceRequestPolicyQt);
};
} // namespace extensions
diff --git a/src/core/renderer/pepper/pepper_flash_renderer_host_qt.cpp b/src/core/renderer/pepper/pepper_flash_renderer_host_qt.cpp
deleted file mode 100644
index 9af05fd08..000000000
--- a/src/core/renderer/pepper/pepper_flash_renderer_host_qt.cpp
+++ /dev/null
@@ -1,432 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// This is based on chrome/renderer/pepper/pepper_flash_renderer_host.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#include "pepper_flash_renderer_host_qt.h"
-
-#include <map>
-#include <vector>
-
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_util.h"
-#include "content/public/renderer/pepper_plugin_instance.h"
-#include "content/public/renderer/render_thread.h"
-#include "content/public/renderer/renderer_ppapi_host.h"
-#include "ipc/ipc_message_macros.h"
-#include "net/http/http_util.h"
-#include "ppapi/c/pp_errors.h"
-#include "ppapi/c/trusted/ppb_browser_font_trusted.h"
-#include "ppapi/host/dispatch_host_message.h"
-#include "ppapi/proxy/host_dispatcher.h"
-#include "ppapi/proxy/ppapi_messages.h"
-#include "ppapi/proxy/resource_message_params.h"
-#include "ppapi/proxy/serialized_structs.h"
-#include "ppapi/thunk/enter.h"
-#include "ppapi/thunk/ppb_image_data_api.h"
-#include "skia/ext/platform_canvas.h"
-#include "third_party/skia/include/core/SkCanvas.h"
-#include "third_party/skia/include/core/SkMatrix.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkPoint.h"
-#include "third_party/skia/include/core/SkTextBlob.h"
-#include "third_party/skia/include/core/SkTypeface.h"
-#include "third_party/skia/include/private/SkTemplates.h"
-#include "ui/gfx/geometry/rect.h"
-#include "url/gurl.h"
-
-using ppapi::thunk::EnterResourceNoLock;
-using ppapi::thunk::PPB_ImageData_API;
-
-namespace {
-
-// Some non-simple HTTP request headers that Flash may set.
-// (Please see http://www.w3.org/TR/cors/#simple-header for the definition of
-// simple headers.)
-//
-// The list and the enum defined below are used to collect data about request
-// headers used in PPB_Flash.Navigate() calls, in order to understand the impact
-// of rejecting PPB_Flash.Navigate() requests with non-simple headers.
-//
-// TODO(yzshen): We should be able to remove the histogram recording code once
-// we get the answer.
-const char* const kRejectedHttpRequestHeaders[] = {
- "authorization", //
- "cache-control", //
- "content-encoding", //
- "content-md5", //
- "content-type", // If the media type is not one of those covered by the
- // simple header definition.
- "expires", //
- "from", //
- "if-match", //
- "if-none-match", //
- "if-range", //
- "if-unmodified-since", //
- "pragma", //
- "referer" //
-};
-
-// Please note that new entries should be added right above
-// FLASH_NAVIGATE_USAGE_ENUM_COUNT, and existing entries shouldn't be re-ordered
-// or removed, since this ordering is used in a histogram.
-enum FlashNavigateUsage {
- // This section must be in the same order as kRejectedHttpRequestHeaders.
- REJECT_AUTHORIZATION = 0,
- REJECT_CACHE_CONTROL,
- REJECT_CONTENT_ENCODING,
- REJECT_CONTENT_MD5,
- REJECT_CONTENT_TYPE,
- REJECT_EXPIRES,
- REJECT_FROM,
- REJECT_IF_MATCH,
- REJECT_IF_NONE_MATCH,
- REJECT_IF_RANGE,
- REJECT_IF_UNMODIFIED_SINCE,
- REJECT_PRAGMA,
- REJECT_REFERER,
-
- // The navigate request is rejected because of headers not listed above
- // (e.g., custom headers).
- REJECT_OTHER_HEADERS,
-
- // Total number of rejected navigate requests.
- TOTAL_REJECTED_NAVIGATE_REQUESTS,
-
- // Total number of navigate requests.
- TOTAL_NAVIGATE_REQUESTS,
- FLASH_NAVIGATE_USAGE_ENUM_COUNT
-};
-
-static base::LazyInstance<std::map<std::string, FlashNavigateUsage>>::
- DestructorAtExit g_rejected_headers = LAZY_INSTANCE_INITIALIZER;
-
-bool IsSimpleHeader(const std::string& lower_case_header_name,
- const std::string& header_value)
-{
- if (lower_case_header_name == "accept" ||
- lower_case_header_name == "accept-language" ||
- lower_case_header_name == "content-language")
- return true;
-
- if (lower_case_header_name == "content-type") {
- std::string lower_case_mime_type;
- std::string lower_case_charset;
- bool had_charset = false;
- net::HttpUtil::ParseContentType(header_value,
- &lower_case_mime_type,
- &lower_case_charset,
- &had_charset,
- NULL);
- return lower_case_mime_type == "application/x-www-form-urlencoded" ||
- lower_case_mime_type == "multipart/form-data" ||
- lower_case_mime_type == "text/plain";
- }
-
- return false;
-}
-
-void RecordFlashNavigateUsage(FlashNavigateUsage usage)
-{
- DCHECK_NE(FLASH_NAVIGATE_USAGE_ENUM_COUNT, usage);
- UMA_HISTOGRAM_ENUMERATION(
- "Plugin.FlashNavigateUsage",
- usage,
- FLASH_NAVIGATE_USAGE_ENUM_COUNT);
-}
-
-} // namespace
-
-namespace QtWebEngineCore {
-
-PepperFlashRendererHostQt::PepperFlashRendererHostQt(
- content::RendererPpapiHost* host,
- PP_Instance instance,
- PP_Resource resource)
- : ResourceHost(host->GetPpapiHost(), instance, resource),
- host_(host),
- weak_factory_(this)
-{
-}
-
-PepperFlashRendererHostQt::~PepperFlashRendererHostQt() {
- // This object may be destroyed in the middle of a sync message. If that is
- // the case, make sure we respond to all the pending navigate calls.
- std::vector<ppapi::host::ReplyMessageContext>::reverse_iterator it;
- for (it = navigate_replies_.rbegin(); it != navigate_replies_.rend(); ++it)
- SendReply(*it, IPC::Message());
-}
-
-int32_t PepperFlashRendererHostQt::OnResourceMessageReceived(
- const IPC::Message& msg,
- ppapi::host::HostMessageContext* context)
-{
- PPAPI_BEGIN_MESSAGE_MAP(PepperFlashRendererHostQt, msg)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_GetProxyForURL,
- OnGetProxyForURL)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_SetInstanceAlwaysOnTop,
- OnSetInstanceAlwaysOnTop)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_DrawGlyphs,
- OnDrawGlyphs)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_Navigate, OnNavigate)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_IsRectTopmost,
- OnIsRectTopmost)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(PpapiHostMsg_Flash_InvokePrinting,
- OnInvokePrinting)
- PPAPI_END_MESSAGE_MAP()
- return PP_ERROR_FAILED;
-}
-
-int32_t PepperFlashRendererHostQt::OnGetProxyForURL(
- ppapi::host::HostMessageContext* host_context,
- const std::string& url)
-{
- GURL gurl(url);
- if (!gurl.is_valid())
- return PP_ERROR_FAILED;
- std::string proxy;
- bool result = content::RenderThread::Get()->ResolveProxy(gurl, &proxy);
- if (!result)
- return PP_ERROR_FAILED;
- host_context->reply_msg = PpapiPluginMsg_Flash_GetProxyForURLReply(proxy);
- return PP_OK;
-}
-
-int32_t PepperFlashRendererHostQt::OnSetInstanceAlwaysOnTop(
- ppapi::host::HostMessageContext* host_context,
- bool on_top)
-{
- content::PepperPluginInstance* plugin_instance =
- host_->GetPluginInstance(pp_instance());
- if (plugin_instance)
- plugin_instance->SetAlwaysOnTop(on_top);
- return PP_OK;
-}
-
-int32_t PepperFlashRendererHostQt::OnDrawGlyphs(
- ppapi::host::HostMessageContext* host_context,
- ppapi::proxy::PPBFlash_DrawGlyphs_Params params)
-{
- if (params.glyph_indices.size() != params.glyph_advances.size() ||
- params.glyph_indices.empty())
- return PP_ERROR_FAILED;
-
- int weight = (params.font_desc.weight + 1) * 100;
- SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
- if (params.font_desc.italic)
- slant = SkFontStyle::kItalic_Slant;
- SkFontStyle style(weight, SkFontStyle::kNormal_Width, slant);
- sk_sp<SkTypeface> typeface(
- SkTypeface::MakeFromName(params.font_desc.face.c_str(), style));
- if (!typeface)
- return PP_ERROR_FAILED;
-
- EnterResourceNoLock<PPB_ImageData_API> enter(params.image_data.host_resource(), true);
- if (enter.failed())
- return PP_ERROR_FAILED;
-
- PPB_ImageData_API* image = static_cast<PPB_ImageData_API*>(enter.object());
- SkCanvas* canvas = image->GetCanvas();
- bool needs_unmapping = false;
- if (!canvas) {
- needs_unmapping = true;
- image->Map();
- canvas = image->GetCanvas();
- if (!canvas)
- return PP_ERROR_FAILED; // Failure mapping.
- }
-
- SkAutoCanvasRestore acr(canvas, true);
-
- // Clip is applied in pixels before the transform.
- SkRect clip_rect = {
- SkIntToScalar(params.clip.point.x), SkIntToScalar(params.clip.point.y),
- SkIntToScalar(params.clip.point.x + params.clip.size.width),
- SkIntToScalar(params.clip.point.y + params.clip.size.height)};
- canvas->clipRect(clip_rect);
-
- SkMatrix matrix;
- matrix.set(SkMatrix::kMScaleX, SkFloatToScalar(params.transformation[0][0]));
- matrix.set(SkMatrix::kMSkewX, SkFloatToScalar(params.transformation[0][1]));
- matrix.set(SkMatrix::kMTransX, SkFloatToScalar(params.transformation[0][2]));
- matrix.set(SkMatrix::kMSkewY, SkFloatToScalar(params.transformation[1][0]));
- matrix.set(SkMatrix::kMScaleY, SkFloatToScalar(params.transformation[1][1]));
- matrix.set(SkMatrix::kMTransY, SkFloatToScalar(params.transformation[1][2]));
- matrix.set(SkMatrix::kMPersp0, SkFloatToScalar(params.transformation[2][0]));
- matrix.set(SkMatrix::kMPersp1, SkFloatToScalar(params.transformation[2][1]));
- matrix.set(SkMatrix::kMPersp2, SkFloatToScalar(params.transformation[2][2]));
- canvas->concat(matrix);
-
- SkPaint paint;
- paint.setColor(params.color);
-
- SkFont font(std::move(typeface), SkIntToScalar(params.font_desc.size));
- font.setHinting(SkFontHinting::kFull);
- if (params.allow_subpixel_aa) {
- font.setSubpixel(true);
- font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
- }
-
- SkScalar x = SkIntToScalar(params.position.x);
- SkScalar y = SkIntToScalar(params.position.y);
-
- // Build up the skia advances.
- size_t glyph_count = params.glyph_indices.size();
- if (glyph_count) {
- SkTextBlobBuilder builder;
- auto rec = builder.allocRunPos(font, glyph_count);
- memcpy(rec.glyphs, &params.glyph_indices[0], glyph_count * 2);
- SkPoint* pos = reinterpret_cast<SkPoint*>(rec.pos);
- for (uint32_t i = 0; i < glyph_count; i++) {
- pos[i].set(x, y);
- x += SkFloatToScalar(params.glyph_advances[i].x);
- y += SkFloatToScalar(params.glyph_advances[i].y);
- }
- canvas->drawTextBlob(builder.make(), 0, 0, paint);
- }
-
- if (needs_unmapping)
- image->Unmap();
-
- return PP_OK;
-}
-
-// CAUTION: This code is subtle because Navigate is a sync call which may
-// cause re-entrancy or cause the instance to be destroyed. If the instance
-// is destroyed we need to ensure that we respond to all outstanding sync
-// messages so that the plugin process does not remain blocked.
-int32_t PepperFlashRendererHostQt::OnNavigate(
- ppapi::host::HostMessageContext* host_context,
- const ppapi::URLRequestInfoData& data,
- const std::string& target,
- bool from_user_action)
-{
- // If our PepperPluginInstance is already destroyed, just return a failure.
- content::PepperPluginInstance* plugin_instance =
- host_->GetPluginInstance(pp_instance());
- if (!plugin_instance)
- return PP_ERROR_FAILED;
-
- std::map<std::string, FlashNavigateUsage>& rejected_headers =
- g_rejected_headers.Get();
- if (rejected_headers.empty()) {
- for (size_t i = 0; i < base::size(kRejectedHttpRequestHeaders); ++i)
- rejected_headers[kRejectedHttpRequestHeaders[i]] =
- static_cast<FlashNavigateUsage>(i);
- }
-
- net::HttpUtil::HeadersIterator header_iter(
- data.headers.begin(), data.headers.end(), "\n\r");
- bool rejected = false;
- while (header_iter.GetNext()) {
- std::string lower_case_header_name =
- base::ToLowerASCII(header_iter.name());
- if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) {
- rejected = true;
-
- std::map<std::string, FlashNavigateUsage>::const_iterator iter =
- rejected_headers.find(lower_case_header_name);
- FlashNavigateUsage usage =
- iter != rejected_headers.end() ? iter->second : REJECT_OTHER_HEADERS;
- RecordFlashNavigateUsage(usage);
- }
- }
-
- RecordFlashNavigateUsage(TOTAL_NAVIGATE_REQUESTS);
- if (rejected) {
- RecordFlashNavigateUsage(TOTAL_REJECTED_NAVIGATE_REQUESTS);
- return PP_ERROR_NOACCESS;
- }
-
- // Navigate may call into Javascript (e.g. with a "javascript:" URL),
- // or do things like navigate away from the page, either one of which will
- // need to re-enter into the plugin. It is safe, because it is essentially
- // equivalent to NPN_GetURL, where Flash would expect re-entrancy.
- ppapi::proxy::HostDispatcher* host_dispatcher =
- ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
- host_dispatcher->set_allow_plugin_reentrancy();
-
- // Grab a weak pointer to ourselves on the stack so we can check if we are
- // still alive.
- base::WeakPtr<PepperFlashRendererHostQt> weak_ptr = weak_factory_.GetWeakPtr();
- // Keep track of reply contexts in case we are destroyed during a Navigate
- // call. Even if we are destroyed, we still need to send these replies to
- // unblock the plugin process.
- navigate_replies_.push_back(host_context->MakeReplyMessageContext());
- plugin_instance->Navigate(data, target.c_str(), from_user_action);
- // This object might have been destroyed by this point. If it is destroyed
- // the reply will be sent in the destructor. Otherwise send the reply here.
- if (weak_ptr.get()) {
- SendReply(navigate_replies_.back(), IPC::Message());
- navigate_replies_.pop_back();
- }
-
- // Return PP_OK_COMPLETIONPENDING so that no reply is automatically sent.
- return PP_OK_COMPLETIONPENDING;
-}
-
-int32_t PepperFlashRendererHostQt::OnIsRectTopmost(
- ppapi::host::HostMessageContext* host_context,
- const PP_Rect& rect)
-{
- content::PepperPluginInstance* plugin_instance =
- host_->GetPluginInstance(pp_instance());
- if (plugin_instance &&
- plugin_instance->IsRectTopmost(
- gfx::Rect(
- rect.point.x,
- rect.point.y,
- rect.size.width,
- rect.size.height)))
- return PP_OK;
- return PP_ERROR_FAILED;
-}
-
-int32_t PepperFlashRendererHostQt::OnInvokePrinting(
- ppapi::host::HostMessageContext* host_context)
-{
- return PP_ERROR_FAILED;
-}
-
-} //QtWebEngineCore
diff --git a/src/core/renderer/pepper/pepper_flash_renderer_host_qt.h b/src/core/renderer/pepper/pepper_flash_renderer_host_qt.h
deleted file mode 100644
index ae6bc0876..000000000
--- a/src/core/renderer/pepper/pepper_flash_renderer_host_qt.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEPPER_FLASH_RENDERER_HOST_QT_H
-#define PEPPER_FLASH_RENDERER_HOST_QT_H
-
-#include <string>
-#include <vector>
-
-#include "base/memory/weak_ptr.h"
-#include "ppapi/host/host_message_context.h"
-#include "ppapi/host/resource_host.h"
-
-struct PP_Rect;
-
-namespace ppapi {
-struct URLRequestInfoData;
-}
-
-namespace ppapi {
-namespace proxy {
-struct PPBFlash_DrawGlyphs_Params;
-}
-}
-
-namespace content {
-class RendererPpapiHost;
-}
-
-namespace QtWebEngineCore {
-
-class PepperFlashRendererHostQt : public ppapi::host::ResourceHost {
-public:
- PepperFlashRendererHostQt(content::RendererPpapiHost* host,
- PP_Instance instance,
- PP_Resource resource);
- ~PepperFlashRendererHostQt() override;
-
- // ppapi::host::ResourceHost override.
- int32_t OnResourceMessageReceived(
- const IPC::Message& msg,
- ppapi::host::HostMessageContext* context) override;
-
-private:
- int32_t OnGetProxyForURL(ppapi::host::HostMessageContext* host_context,
- const std::string& url);
- int32_t OnSetInstanceAlwaysOnTop(
- ppapi::host::HostMessageContext* host_context,
- bool on_top);
- int32_t OnDrawGlyphs(ppapi::host::HostMessageContext* host_context,
- ppapi::proxy::PPBFlash_DrawGlyphs_Params params);
- int32_t OnNavigate(ppapi::host::HostMessageContext* host_context,
- const ppapi::URLRequestInfoData& data,
- const std::string& target,
- bool from_user_action);
- int32_t OnIsRectTopmost(ppapi::host::HostMessageContext* host_context,
- const PP_Rect& rect);
- int32_t OnInvokePrinting(ppapi::host::HostMessageContext* host_context);
-
- // A stack of ReplyMessageContexts to track Navigate() calls which have not
- // yet been replied to.
- std::vector<ppapi::host::ReplyMessageContext> navigate_replies_;
-
- content::RendererPpapiHost* host_;
- base::WeakPtrFactory<PepperFlashRendererHostQt> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(PepperFlashRendererHostQt);
-};
-
-} //QtWebEngineCore
-#endif // PEPPER_FLASH_RENDERER_HOST_QT_H
diff --git a/src/core/renderer/pepper/pepper_renderer_host_factory_qt.cpp b/src/core/renderer/pepper/pepper_renderer_host_factory_qt.cpp
index 33c744f13..d0daea8c2 100644
--- a/src/core/renderer/pepper/pepper_renderer_host_factory_qt.cpp
+++ b/src/core/renderer/pepper/pepper_renderer_host_factory_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// This is based on chrome/renderer/pepper/chrome_renderer_pepper_host_factory.cc:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -43,20 +7,12 @@
// found in the LICENSE.Chromium file.
#include "pepper_renderer_host_factory_qt.h"
-#include "pepper_flash_renderer_host_qt.h"
#include "qtwebenginecoreglobal_p.h"
-#include "base/memory/ptr_util.h"
-#include "chrome/renderer/pepper/pepper_flash_font_file_host.h"
-#if QT_CONFIG(webengine_printing_and_pdf)
-#include "components/pdf/renderer/pepper_pdf_host.h"
-#endif // QT_CONFIG(webengine_printing_and_pdf)
#include "content/public/renderer/renderer_ppapi_host.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/ppapi_messages.h"
-#include "ppapi/proxy/ppapi_message_utils.h"
-#include "ppapi/shared_impl/ppapi_permissions.h"
namespace QtWebEngineCore {
@@ -81,52 +37,13 @@ std::unique_ptr<ppapi::host::ResourceHost> PepperRendererHostFactoryQt::CreateRe
if (!host_->IsValidInstance(instance))
return nullptr;
- if (host_->GetPpapiHost()->permissions().HasPermission(ppapi::PERMISSION_FLASH)) {
- switch (message.type()) {
- case PpapiHostMsg_Flash_Create::ID:
- return base::WrapUnique(new PepperFlashRendererHostQt(host_, instance, resource));
- case PpapiHostMsg_FlashMenu_Create::ID: {
- ppapi::host::ReplyMessageContext reply_context(
- ppapi::proxy::ResourceMessageReplyParams(resource, 0),
- NULL,
- MSG_ROUTING_NONE);
- reply_context.params.set_result(PP_ERROR_USERCANCEL);
- host_->GetPpapiHost()->SendReply(reply_context, PpapiPluginMsg_FlashMenu_ShowReply(-1));
- break;
- }
- case PpapiHostMsg_FlashFullscreen_Create::ID:
- // Not implemented
- break;
- }
+ // Create a default ResourceHost for this message type to suppress
+ // "Failed to create PPAPI resource host" console error message.
+ switch (message.type()) {
+ case PpapiHostMsg_UMA_Create::ID:
+ return std::make_unique<ppapi::host::ResourceHost>(host_->GetPpapiHost(), instance, resource);
}
- // TODO(raymes): PDF also needs access to the FlashFontFileHost currently.
- // We should either rename PPB_FlashFont_File to PPB_FontFile_Private or get
- // rid of its use in PDF if possible.
- if (host_->GetPpapiHost()->permissions().HasPermission(ppapi::PERMISSION_FLASH)
- || host_->GetPpapiHost()->permissions().HasPermission(ppapi::PERMISSION_PDF)) {
- switch (message.type()) {
- case PpapiHostMsg_FlashFontFile_Create::ID: {
- ppapi::proxy::SerializedFontDescription description;
- PP_PrivateFontCharset charset;
- if (ppapi::UnpackMessage<PpapiHostMsg_FlashFontFile_Create>(message, &description, &charset))
- return base::WrapUnique(new PepperFlashFontFileHost(host_, instance, resource, description, charset));
- break;
- }
- case PpapiHostMsg_FlashDRM_Create::ID:
- // Not implemented
- break;
- }
- }
-
-#if QT_CONFIG(webengine_printing_and_pdf)
- if (host_->GetPpapiHost()->permissions().HasPermission(ppapi::PERMISSION_PDF)) {
- switch (message.type()) {
- case PpapiHostMsg_PDF_Create::ID:
- return std::make_unique<pdf::PepperPDFHost>(host_, instance, resource);
- }
- }
-#endif // QT_CONFIG(webengine_printing_and_pdf)
return nullptr;
}
diff --git a/src/core/renderer/pepper/pepper_renderer_host_factory_qt.h b/src/core/renderer/pepper/pepper_renderer_host_factory_qt.h
index ec3440a08..c31aa23d7 100644
--- a/src/core/renderer/pepper/pepper_renderer_host_factory_qt.h
+++ b/src/core/renderer/pepper/pepper_renderer_host_factory_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PEPPER_RENDERER_HOST_FACTORY_QT_H
#define PEPPER_RENDERER_HOST_FACTORY_QT_H
@@ -65,8 +29,6 @@ public:
private:
// Not owned by this object.
content::RendererPpapiHost* host_;
-
- DISALLOW_COPY_AND_ASSIGN(PepperRendererHostFactoryQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/renderer/plugins/loadable_plugin_placeholder_qt.cpp b/src/core/renderer/plugins/loadable_plugin_placeholder_qt.cpp
index b43d9a24b..06fd4f71f 100644
--- a/src/core/renderer/plugins/loadable_plugin_placeholder_qt.cpp
+++ b/src/core/renderer/plugins/loadable_plugin_placeholder_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -61,15 +25,12 @@ gin::WrapperInfo LoadablePluginPlaceholderQt::kWrapperInfo = {gin::kEmbedderNati
LoadablePluginPlaceholderQt::LoadablePluginPlaceholderQt(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
const std::string& html_data,
- const base::string16& title)
+ const std::u16string& title)
: plugins::LoadablePluginPlaceholder(render_frame, params, html_data)
- , context_menu_request_id_(0)
{}
LoadablePluginPlaceholderQt::~LoadablePluginPlaceholderQt()
{
- if (context_menu_request_id_ && render_frame())
- render_frame()->CancelContextMenu(context_menu_request_id_);
}
// TODO(bauerb): Move this method to NonLoadablePluginPlaceholder?
@@ -77,13 +38,13 @@ LoadablePluginPlaceholderQt::~LoadablePluginPlaceholderQt()
LoadablePluginPlaceholderQt* LoadablePluginPlaceholderQt::CreateLoadableMissingPlugin(content::RenderFrame* render_frame,
const blink::WebPluginParams& params)
{
- const base::StringPiece template_html(ui::ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_BLOCKED_PLUGIN_HTML));
+ std::string template_html(ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_BLOCKED_PLUGIN_HTML));
- base::DictionaryValue values;
- values.SetString("name", "");
- values.SetString("message", l10n_util::GetStringUTF8(IDS_PLUGIN_NOT_SUPPORTED));
+ base::Value::Dict values;
+ values.Set("name", "");
+ values.Set("message", l10n_util::GetStringUTF8(IDS_PLUGIN_NOT_SUPPORTED));
- const std::string html_data = webui::GetI18nTemplateHtml(template_html, &values);
+ const std::string html_data = webui::GetI18nTemplateHtml(template_html, std::move(values));
// Will destroy itself when its WebViewPlugin is going away.
return new LoadablePluginPlaceholderQt(render_frame, params, html_data, params.mime_type.Utf16());
diff --git a/src/core/renderer/plugins/loadable_plugin_placeholder_qt.h b/src/core/renderer/plugins/loadable_plugin_placeholder_qt.h
index 7bcad2d96..9b9d1bca8 100644
--- a/src/core/renderer/plugins/loadable_plugin_placeholder_qt.h
+++ b/src/core/renderer/plugins/loadable_plugin_placeholder_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -44,7 +8,6 @@
#ifndef LOADALBLE_PLUGIN_PLACEHOLDER_QT_H
#define LOADALBLE_PLUGIN_PLACEHOLDER_QT_H
-#include "base/macros.h"
#include "components/plugins/renderer/loadable_plugin_placeholder.h"
namespace QtWebEngineCore {
@@ -63,20 +26,14 @@ private:
LoadablePluginPlaceholderQt(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
const std::string& html_data,
- const base::string16& title);
+ const std::u16string& title);
~LoadablePluginPlaceholderQt() override;
// content::LoadablePluginPlaceholder overrides.
blink::WebPlugin* CreatePlugin() override;
- void OnBlockedContent(content::RenderFrame::PeripheralContentStatus status,
- bool is_same_origin) override {}
// WebViewPlugin::Delegate (via PluginPlaceholder) methods:
v8::Local<v8::Value> GetV8Handle(v8::Isolate* isolate) override;
-
- int context_menu_request_id_; // Nonzero when request pending.
-
- DISALLOW_COPY_AND_ASSIGN(LoadablePluginPlaceholderQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/renderer/plugins/plugin_placeholder_qt.cpp b/src/core/renderer/plugins/plugin_placeholder_qt.cpp
deleted file mode 100644
index a72c29873..000000000
--- a/src/core/renderer/plugins/plugin_placeholder_qt.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "plugin_placeholder_qt.h"
-
-#include "content/public/renderer/render_frame.h"
-#include "content/public/renderer/v8_value_converter.h"
-#include "gin/object_template_builder.h"
-
-namespace QtWebEngineCore {
-
-// static
-gin::WrapperInfo PluginPlaceholderQt::kWrapperInfo = {gin::kEmbedderNativeGin};
-
-PluginPlaceholderQt::PluginPlaceholderQt(content::RenderFrame* render_frame,
- const blink::WebPluginParams& params,
- const std::string& html_data)
- : PluginPlaceholderBase(render_frame, params, html_data)
-{}
-
-PluginPlaceholderQt::~PluginPlaceholderQt() {}
-
-v8::Local<v8::Value> PluginPlaceholderQt::GetV8Handle(v8::Isolate* isolate)
-{
- return gin::CreateHandle(isolate, this).ToV8();
-}
-
-gin::ObjectTemplateBuilder PluginPlaceholderQt::GetObjectTemplateBuilder(v8::Isolate* isolate)
-{
- return gin::Wrappable<PluginPlaceholderQt>::GetObjectTemplateBuilder(isolate)
- .SetMethod<void (QtWebEngineCore::PluginPlaceholderQt::*)()>(
- "hide", &PluginPlaceholderQt::HideCallback);
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/renderer/plugins/plugin_placeholder_qt.h b/src/core/renderer/plugins/plugin_placeholder_qt.h
deleted file mode 100644
index a99c0d045..000000000
--- a/src/core/renderer/plugins/plugin_placeholder_qt.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef PLUGIN_PLACEHOLDER_QT_H
-#define PLUGIN_PLACEHOLDER_QT_H
-
-#include "base/macros.h"
-#include "components/plugins/renderer/plugin_placeholder.h"
-#include "gin/handle.h"
-#include "gin/wrappable.h"
-#include "third_party/blink/public/web/web_plugin_params.h"
-
-namespace QtWebEngineCore {
-
-// A basic placeholder that supports only hiding.
-class PluginPlaceholderQt final : public plugins::PluginPlaceholderBase
- , public gin::Wrappable<PluginPlaceholderQt>
-{
-public:
- static gin::WrapperInfo kWrapperInfo;
-
- PluginPlaceholderQt(content::RenderFrame* render_frame,
- const blink::WebPluginParams& params,
- const std::string& html_data);
- ~PluginPlaceholderQt() override;
-
-private:
- // WebViewPlugin::Delegate methods:
- v8::Local<v8::Value> GetV8Handle(v8::Isolate* isolate) final;
-
- // gin::Wrappable method:
- gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
- v8::Isolate* isolate) override;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // PLUGIN_PLACEHOLDER_QT_H
diff --git a/src/core/renderer/print_web_view_helper_delegate_qt.cpp b/src/core/renderer/print_web_view_helper_delegate_qt.cpp
index b85ff7249..f01568e65 100644
--- a/src/core/renderer/print_web_view_helper_delegate_qt.cpp
+++ b/src/core/renderer/print_web_view_helper_delegate_qt.cpp
@@ -1,74 +1,40 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
-#include "content/public/renderer/render_frame.h"
-#include "content/public/renderer/render_view.h"
+#include "extensions/buildflags/buildflags.h"
#include "extensions/common/constants.h"
-#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
+#include "url/origin.h"
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+#include "chrome/common/webui_url_constants.h"
+#include "extensions/common/constants.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "extensions/renderer/guest_view/mime_handler_view/post_message_support.h"
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+#include "pdf_util_qt.h"
#include "print_web_view_helper_delegate_qt.h"
#include "web_engine_library_info.h"
namespace QtWebEngineCore {
-PrintWebViewHelperDelegateQt::~PrintWebViewHelperDelegateQt() {}
-bool PrintWebViewHelperDelegateQt::CancelPrerender(content::RenderFrame *)
-{
- return false;
-}
+PrintWebViewHelperDelegateQt::~PrintWebViewHelperDelegateQt() {}
blink::WebElement PrintWebViewHelperDelegateQt::GetPdfElement(blink::WebLocalFrame *frame)
{
- GURL url = frame->GetDocument().Url();
- if (url.SchemeIs(extensions::kExtensionScheme) && url.host() == extension_misc::kPdfExtensionId) {
- // <object> with id="plugin" is created in
- // chrome/browser/resources/pdf/pdf.js.
- auto plugin_element = frame->GetDocument().GetElementById("plugin");
- CHECK(!plugin_element.IsNull());
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ if (frame->Parent() && IsPdfInternalPluginAllowedOrigin(frame->Parent()->GetSecurityOrigin())) {
+ auto plugin_element = frame->GetDocument().QuerySelector("embed");
+ DCHECK(!plugin_element.IsNull());
return plugin_element;
}
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return blink::WebElement();
}
@@ -82,7 +48,7 @@ bool PrintWebViewHelperDelegateQt::OverridePrint(blink::WebLocalFrame *frame)
return false;
}
-}
+} // namespace QtWebEngineCore
namespace printing {
// std::string PrintingContextDelegate::GetAppLocale()
diff --git a/src/core/renderer/print_web_view_helper_delegate_qt.h b/src/core/renderer/print_web_view_helper_delegate_qt.h
index f02580b91..5c7dd2431 100644
--- a/src/core/renderer/print_web_view_helper_delegate_qt.h
+++ b/src/core/renderer/print_web_view_helper_delegate_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -46,8 +10,8 @@
#include "components/printing/renderer/print_render_frame_helper.h"
-namespace content {
-class RenderView;
+namespace blink {
+class WebLocalFrame;
}
namespace QtWebEngineCore {
@@ -57,14 +21,13 @@ class PrintWebViewHelperDelegateQt : public printing::PrintRenderFrameHelper::De
public:
~PrintWebViewHelperDelegateQt() override;
- bool CancelPrerender(content::RenderFrame *render_frame) override;
-
blink::WebElement GetPdfElement(blink::WebLocalFrame *frame) override;
bool IsPrintPreviewEnabled() override;
bool OverridePrint(blink::WebLocalFrame *frame) override;
-}; // class PrintWebViewHelperDelegateQt
-}
+};
+
+} // namespace QtWebEngineCore
#endif // PRINT_WEB_VIEW_HELPER_DELEGATE_QT_H
diff --git a/src/core/renderer/render_configuration.cpp b/src/core/renderer/render_configuration.cpp
new file mode 100644
index 000000000..7b35cdd48
--- /dev/null
+++ b/src/core/renderer/render_configuration.cpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/renderer/chrome_render_thread_observer.cc:
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "renderer/render_configuration.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
+
+namespace QtWebEngineCore {
+
+bool RenderConfiguration::m_isIncognitoProcess = false;
+
+void RenderConfiguration::RegisterMojoInterfaces(
+ blink::AssociatedInterfaceRegistry *associated_interfaces)
+{
+ associated_interfaces->AddInterface<qtwebengine::mojom::RendererConfiguration>(
+ base::BindRepeating(&RenderConfiguration::OnRendererConfigurationAssociatedRequest,
+ base::Unretained(this)));
+}
+
+void RenderConfiguration::UnregisterMojoInterfaces(
+ blink::AssociatedInterfaceRegistry *associated_interfaces)
+{
+ associated_interfaces->RemoveInterface(qtwebengine::mojom::RendererConfiguration::Name_);
+}
+
+void RenderConfiguration::SetInitialConfiguration(bool is_incognito_process)
+{
+ m_isIncognitoProcess = is_incognito_process;
+}
+
+void RenderConfiguration::OnRendererConfigurationAssociatedRequest(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::RendererConfiguration> receiver)
+{
+ m_rendererConfigurationReceivers.Add(this, std::move(receiver));
+}
+
+} // namespace
diff --git a/src/core/renderer/render_configuration.h b/src/core/renderer/render_configuration.h
new file mode 100644
index 000000000..d9c867e02
--- /dev/null
+++ b/src/core/renderer/render_configuration.h
@@ -0,0 +1,42 @@
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef RENDER_CONFIGURATION_H
+#define RENDER_CONFIGURATION_H
+
+#include "content/public/renderer/render_thread_observer.h"
+#include "mojo/public/cpp/bindings/associated_receiver_set.h"
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
+#include "qtwebengine/common/renderer_configuration.mojom.h"
+
+namespace QtWebEngineCore {
+
+class RenderConfiguration : public content::RenderThreadObserver,
+ public qtwebengine::mojom::RendererConfiguration
+{
+public:
+ RenderConfiguration() = default;
+ ~RenderConfiguration() override = default;
+
+ static bool is_incognito_process() { return m_isIncognitoProcess; }
+
+private:
+ // content::RenderThreadObserver:
+ void RegisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
+ void UnregisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
+
+ // qtwebengine::mojom::RendererConfiguration:
+ void SetInitialConfiguration(bool is_incognito_process) override;
+
+ void OnRendererConfigurationAssociatedRequest(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::RendererConfiguration> receiver);
+
+ static bool m_isIncognitoProcess;
+
+ mojo::AssociatedReceiverSet<qtwebengine::mojom::RendererConfiguration>
+ m_rendererConfigurationReceivers;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // RENDER_CONFIGURATION_H
diff --git a/src/core/renderer/render_frame_observer_qt.cpp b/src/core/renderer/render_frame_observer_qt.cpp
index cc01acec6..e6489eefb 100644
--- a/src/core/renderer/render_frame_observer_qt.cpp
+++ b/src/core/renderer/render_frame_observer_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// This is based on chrome/renderer/pepper/pepper_helper.cc:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -44,14 +8,18 @@
#include "render_frame_observer_qt.h"
-#include "base/memory/ptr_util.h"
-#include "chrome/renderer/pepper/pepper_shared_memory_message_filter.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "content/public/renderer/render_frame.h"
+#include "third_party/blink/public/web/web_document_loader.h"
+
+#if QT_CONFIG(webengine_pepper_plugins)
+#include "base/memory/ptr_util.h"
+#include "chrome/renderer/pepper/pepper_shared_memory_message_filter.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "ppapi/host/ppapi_host.h"
#include "renderer/pepper/pepper_renderer_host_factory_qt.h"
+#endif
namespace QtWebEngineCore {
@@ -77,7 +45,13 @@ void RenderFrameObserverQt::DidCreatePepperPlugin(content::RendererPpapiHost *ho
}
#endif
-void RenderFrameObserverQt::FrameDetached()
+bool RenderFrameObserverQt::OnAssociatedInterfaceRequestForFrame(const std::string &interface_name,
+ mojo::ScopedInterfaceEndpointHandle *handle)
+{
+ return m_associated_interfaces.TryBindInterface(interface_name, handle);
+}
+
+void RenderFrameObserverQt::WillDetach()
{
m_isFrameDetached = true;
}
diff --git a/src/core/renderer/render_frame_observer_qt.h b/src/core/renderer/render_frame_observer_qt.h
index 6bdf4ad23..8cab3bd9a 100644
--- a/src/core/renderer/render_frame_observer_qt.h
+++ b/src/core/renderer/render_frame_observer_qt.h
@@ -1,51 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef RENDER_FRAME_OBSERVER_QT_H
#define RENDER_FRAME_OBSERVER_QT_H
#include "qtwebenginecoreglobal_p.h"
-#include "base/compiler_specific.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_observer_tracker.h"
-#include "ppapi/buildflags/buildflags.h"
#include "services/service_manager/public/cpp/binder_registry.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
namespace content {
class RenderFrame;
@@ -67,20 +30,25 @@ public:
#if QT_CONFIG(webengine_pepper_plugins)
void DidCreatePepperPlugin(content::RendererPpapiHost *host) override;
#endif
+ bool OnAssociatedInterfaceRequestForFrame(
+ const std::string &interface_name,
+ mojo::ScopedInterfaceEndpointHandle *handle) override;
void OnDestruct() override;
- void FrameDetached() override;
+ void WillDetach() override;
bool isFrameDetached() const;
service_manager::BinderRegistry *registry() { return &registry_; }
+ blink::AssociatedInterfaceRegistry *associatedInterfaces() {
+ return &m_associated_interfaces;
+ }
private:
- DISALLOW_COPY_AND_ASSIGN(RenderFrameObserverQt);
-
void ReadyToCommitNavigation(blink::WebDocumentLoader *) override;
bool m_isFrameDetached;
service_manager::BinderRegistry registry_;
+ blink::AssociatedInterfaceRegistry m_associated_interfaces;
web_cache::WebCacheImpl *m_web_cache_impl;
};
diff --git a/src/core/renderer/render_thread_observer_qt.cpp b/src/core/renderer/render_thread_observer_qt.cpp
deleted file mode 100644
index 4912ebfc2..000000000
--- a/src/core/renderer/render_thread_observer_qt.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// based on chrome/renderer/chrome_render_thread_observer.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "renderer/render_thread_observer_qt.h"
-
-#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
-
-namespace QtWebEngineCore {
-
-bool RenderThreadObserverQt::m_isIncognitoProcess = false;
-
-void RenderThreadObserverQt::RegisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces)
-{
- associated_interfaces->AddInterface(
- base::Bind(&RenderThreadObserverQt::OnRendererConfigurationAssociatedRequest, base::Unretained(this)));
-}
-
-void RenderThreadObserverQt::UnregisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces)
-{
- associated_interfaces->RemoveInterface(qtwebengine::mojom::RendererConfiguration::Name_);
-}
-
-void RenderThreadObserverQt::SetInitialConfiguration(bool is_incognito_process)
-{
- m_isIncognitoProcess = is_incognito_process;
-}
-
-void RenderThreadObserverQt::OnRendererConfigurationAssociatedRequest(
- mojo::PendingAssociatedReceiver<qtwebengine::mojom::RendererConfiguration> receiver)
-{
- m_rendererConfigurationReceivers.Add(this, std::move(receiver));
-}
-
-} // namespace
diff --git a/src/core/renderer/render_thread_observer_qt.h b/src/core/renderer/render_thread_observer_qt.h
deleted file mode 100644
index 05372049b..000000000
--- a/src/core/renderer/render_thread_observer_qt.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RENDER_THREAD_OBSERVER_QT_H
-#define RENDER_THREAD_OBSERVER_QT_H
-
-#include "content/public/renderer/render_thread_observer.h"
-#include "mojo/public/cpp/bindings/associated_receiver_set.h"
-#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
-#include "qtwebengine/common/renderer_configuration.mojom.h"
-
-namespace QtWebEngineCore {
-
-class RenderThreadObserverQt
- : public content::RenderThreadObserver
- , public qtwebengine::mojom::RendererConfiguration
-{
-public:
- RenderThreadObserverQt() = default;
- ~RenderThreadObserverQt() override = default;
-
- static bool is_incognito_process() { return m_isIncognitoProcess; }
-
-private:
- // content::RenderThreadObserver:
- void RegisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
- void UnregisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
-
- // qtwebengine::mojom::RendererConfiguration:
- void SetInitialConfiguration(bool is_incognito_process) override;
-
- void OnRendererConfigurationAssociatedRequest(
- mojo::PendingAssociatedReceiver<qtwebengine::mojom::RendererConfiguration> receiver);
-
- static bool m_isIncognitoProcess;
-
- mojo::AssociatedReceiverSet<qtwebengine::mojom::RendererConfiguration> m_rendererConfigurationReceivers;
-
- DISALLOW_COPY_AND_ASSIGN(RenderThreadObserverQt);
-};
-
-} // namespace QtWebEngineCore
-
-#endif // RENDER_THREAD_OBSERVER_QT_H
diff --git a/src/core/renderer/render_view_observer_qt.cpp b/src/core/renderer/render_view_observer_qt.cpp
deleted file mode 100644
index 5b0b9a77d..000000000
--- a/src/core/renderer/render_view_observer_qt.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "renderer/render_view_observer_qt.h"
-
-#include "common/qt_messages.h"
-
-#include "content/public/renderer/render_view.h"
-#include "third_party/blink/public/web/web_document.h"
-#include "third_party/blink/public/web/web_element.h"
-#include "third_party/blink/public/web/web_frame.h"
-#include "third_party/blink/public/web/web_frame_content_dumper.h"
-#include "third_party/blink/public/web/web_frame_widget.h"
-#include "third_party/blink/public/web/web_local_frame.h"
-#include "third_party/blink/public/web/web_view.h"
-
-RenderViewObserverQt::RenderViewObserverQt(content::RenderView *render_view) : content::RenderViewObserver(render_view)
-{}
-
-void RenderViewObserverQt::onFetchDocumentMarkup(quint64 requestId)
-{
- blink::WebString markup;
- if (render_view()->GetWebView()->MainFrame()->IsWebLocalFrame())
- markup = blink::WebFrameContentDumper::DumpAsMarkup(
- static_cast<blink::WebLocalFrame *>(render_view()->GetWebView()->MainFrame()));
- Send(new RenderViewObserverHostQt_DidFetchDocumentMarkup(routing_id(), requestId, markup.Utf16()));
-}
-
-void RenderViewObserverQt::onFetchDocumentInnerText(quint64 requestId)
-{
- blink::WebString text;
- if (render_view()->GetWebView()->MainFrame()->IsWebLocalFrame())
- text = blink::WebFrameContentDumper::DumpWebViewAsText(render_view()->GetWebView(),
- std::numeric_limits<std::size_t>::max());
- Send(new RenderViewObserverHostQt_DidFetchDocumentInnerText(routing_id(), requestId, text.Utf16()));
-}
-
-void RenderViewObserverQt::onSetBackgroundColor(quint32 color)
-{
- render_view()->GetWebView()->SetBaseBackgroundColorOverride(color);
-}
-
-void RenderViewObserverQt::OnDestruct()
-{
- delete this;
-}
-
-bool RenderViewObserverQt::OnMessageReceived(const IPC::Message &message)
-{
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(RenderViewObserverQt, message)
- IPC_MESSAGE_HANDLER(RenderViewObserverQt_FetchDocumentMarkup, onFetchDocumentMarkup)
- IPC_MESSAGE_HANDLER(RenderViewObserverQt_FetchDocumentInnerText, onFetchDocumentInnerText)
- IPC_MESSAGE_HANDLER(RenderViewObserverQt_SetBackgroundColor, onSetBackgroundColor)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
diff --git a/src/core/renderer/render_view_observer_qt.h b/src/core/renderer/render_view_observer_qt.h
deleted file mode 100644
index 5c555b222..000000000
--- a/src/core/renderer/render_view_observer_qt.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef RENDER_VIEW_OBSERVER_QT_H
-#define RENDER_VIEW_OBSERVER_QT_H
-
-#include "content/public/renderer/render_view_observer.h"
-
-#include <QtGlobal>
-
-class RenderViewObserverQt : public content::RenderViewObserver
-{
-public:
- RenderViewObserverQt(content::RenderView *render_view);
-
-private:
- void onFetchDocumentMarkup(quint64 requestId);
- void onFetchDocumentInnerText(quint64 requestId);
- void onSetBackgroundColor(quint32 color);
-
- void OnDestruct() override;
-
- bool OnMessageReceived(const IPC::Message &message) override;
-
- DISALLOW_COPY_AND_ASSIGN(RenderViewObserverQt);
-};
-
-#endif // RENDER_VIEW_OBSERVER_QT_H
diff --git a/src/core/renderer/user_resource_controller.cpp b/src/core/renderer/user_resource_controller.cpp
index 3c1ad0477..eff304981 100644
--- a/src/core/renderer/user_resource_controller.cpp
+++ b/src/core/renderer/user_resource_controller.cpp
@@ -1,60 +1,20 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "user_resource_controller.h"
#include "base/memory/weak_ptr.h"
-#include "base/pending_task.h"
#include "base/strings/pattern.h"
+#include "base/task/single_thread_task_runner.h"
#include "content/public/renderer/render_frame.h"
-#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_frame_observer.h"
-#include "content/public/renderer/render_view_observer.h"
#include "extensions/common/url_pattern.h"
-#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
-#include "third_party/blink/public/web/web_view.h"
-#include "v8/include/v8.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
-#include "common/qt_messages.h"
-#include "common/user_script_data.h"
+#include "qtwebengine/userscript/user_script_data.h"
#include "type_conversion.h"
#include "user_script.h"
@@ -62,9 +22,9 @@
#include <bitset>
-Q_GLOBAL_STATIC(UserResourceController, qt_webengine_userResourceController)
+namespace QtWebEngineCore {
-static content::RenderView *const globalScriptsIndex = nullptr;
+static content::RenderFrame *const globalScriptsIndex = nullptr;
// Scripts meant to run after the load event will be run 500ms after DOMContentLoaded if the load event doesn't come within that delay.
static const int afterLoadTimeout = 500;
@@ -97,7 +57,7 @@ static bool includeRuleMatchesURL(const std::string &pat, const GURL &url)
return false;
}
-static bool scriptMatchesURL(const UserScriptData &scriptData, const GURL &url)
+static bool scriptMatchesURL(const QtWebEngineCore::UserScriptData &scriptData, const GURL &url)
{
// Logic taken from Chromium (extensions/common/user_script.cc)
bool matchFound;
@@ -132,26 +92,34 @@ static bool scriptMatchesURL(const UserScriptData &scriptData, const GURL &url)
return true;
}
-class UserResourceController::RenderFrameObserverHelper : public content::RenderFrameObserver
+// using UserScriptDataPtr = mojo::StructPtr<qtwebengine::mojom::UserScriptData>;
+
+class UserResourceController::RenderFrameObserverHelper
+ : public content::RenderFrameObserver,
+ public qtwebengine::mojom::UserResourceControllerRenderFrame
{
public:
- RenderFrameObserverHelper(content::RenderFrame *render_frame);
+ RenderFrameObserverHelper(content::RenderFrame *render_frame,
+ UserResourceController *controller);
+ void BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::UserResourceControllerRenderFrame>
+ receiver);
private:
// RenderFrameObserver implementation.
- void DidCommitProvisionalLoad(bool is_same_document_navigation, ui::PageTransition transition) override;
- void DidFinishDocumentLoad() override;
+ void DidCommitProvisionalLoad(ui::PageTransition transition) override;
+ void DidDispatchDOMContentLoadedEvent() override;
void DidFinishLoad() override;
- void FrameDetached() override;
+ void WillDetach() override;
void OnDestruct() override;
- bool OnMessageReceived(const IPC::Message &message) override;
-
- void onUserScriptAdded(const UserScriptData &);
- void onUserScriptRemoved(const UserScriptData &);
- void onScriptsCleared();
+ void AddScript(const QtWebEngineCore::UserScriptData &data) override;
+ void RemoveScript(const QtWebEngineCore::UserScriptData &data) override;
+ void ClearScripts() override;
class Runner;
QScopedPointer<Runner> m_runner;
+ mojo::AssociatedReceiver<qtwebengine::mojom::UserResourceControllerRenderFrame> m_binding;
+ UserResourceController *m_userResourceController;
};
// Helper class to create WeakPtrs so the AfterLoad tasks can be canceled and to
@@ -159,13 +127,16 @@ private:
class UserResourceController::RenderFrameObserverHelper::Runner : public base::SupportsWeakPtr<Runner>
{
public:
- explicit Runner(blink::WebLocalFrame *frame) : m_frame(frame) {}
+ explicit Runner(blink::WebLocalFrame *frame, UserResourceController *controller)
+ : m_frame(frame), m_userResourceController(controller)
+ {
+ }
- void run(UserScriptData::InjectionPoint p)
+ void run(QtWebEngineCore::UserScriptData::InjectionPoint p)
{
DCHECK_LT(p, m_ran.size());
if (!m_ran[p]) {
- UserResourceController::instance()->runScripts(p, m_frame);
+ m_userResourceController->runScripts(p, m_frame);
m_ran[p] = true;
}
}
@@ -173,42 +144,29 @@ public:
private:
blink::WebLocalFrame *m_frame;
std::bitset<3> m_ran;
+ UserResourceController *m_userResourceController;
};
-// Used only for script cleanup on RenderView destruction.
-class UserResourceController::RenderViewObserverHelper : public content::RenderViewObserver
-{
-public:
- RenderViewObserverHelper(content::RenderView *render_view);
-
-private:
- // RenderViewObserver implementation.
- void OnDestruct() override;
-};
-
-void UserResourceController::runScripts(UserScriptData::InjectionPoint p, blink::WebLocalFrame *frame)
+void UserResourceController::runScripts(QtWebEngineCore::UserScriptData::InjectionPoint p,
+ blink::WebLocalFrame *frame)
{
content::RenderFrame *renderFrame = content::RenderFrame::FromWebFrame(frame);
if (!renderFrame)
return;
const bool isMainFrame = renderFrame->IsMainFrame();
- content::RenderView *renderView = renderFrame->GetRenderView();
- if (!renderView)
- return;
-
- QList<uint64_t> scriptsToRun = m_viewUserScriptMap.value(0).values();
- scriptsToRun.append(m_viewUserScriptMap.value(renderView).values());
+ QList<uint64_t> scriptsToRun = m_frameUserScriptMap.value(globalScriptsIndex);
+ scriptsToRun.append(m_frameUserScriptMap.value(renderFrame));
- for (uint64_t id : qAsConst(scriptsToRun)) {
- const UserScriptData &script = m_scripts.value(id);
+ for (uint64_t id : std::as_const(scriptsToRun)) {
+ const QtWebEngineCore::UserScriptData &script = m_scripts.value(id);
if (script.injectionPoint != p || (!script.injectForSubframes && !isMainFrame))
continue;
if (!scriptMatchesURL(script, frame->GetDocument().Url()))
continue;
blink::WebScriptSource source(blink::WebString::FromUTF8(script.source), script.url);
if (script.worldId)
- frame->ExecuteScriptInIsolatedWorld(script.worldId, source);
+ frame->ExecuteScriptInIsolatedWorld(script.worldId, source, blink::BackForwardCacheAware::kAllow); // FIXME, check
else
frame->ExecuteScript(source);
}
@@ -216,119 +174,103 @@ void UserResourceController::runScripts(UserScriptData::InjectionPoint p, blink:
void UserResourceController::RunScriptsAtDocumentEnd(content::RenderFrame *render_frame)
{
- runScripts(UserScriptData::DocumentLoadFinished, render_frame->GetWebFrame());
+ runScripts(QtWebEngineCore::UserScriptData::DocumentLoadFinished, render_frame->GetWebFrame());
}
-UserResourceController::RenderFrameObserverHelper::RenderFrameObserverHelper(content::RenderFrame *render_frame)
+UserResourceController::RenderFrameObserverHelper::RenderFrameObserverHelper(
+ content::RenderFrame *render_frame, UserResourceController *controller)
: content::RenderFrameObserver(render_frame)
-{}
+ , m_binding(this)
+ , m_userResourceController(controller)
+{
+ render_frame->GetAssociatedInterfaceRegistry()->AddInterface<qtwebengine::mojom::UserResourceControllerRenderFrame>(
+ base::BindRepeating(&UserResourceController::RenderFrameObserverHelper::BindReceiver,
+ base::Unretained(this)));
+}
-UserResourceController::RenderViewObserverHelper::RenderViewObserverHelper(content::RenderView *render_view)
- : content::RenderViewObserver(render_view)
-{}
-void UserResourceController::RenderFrameObserverHelper::DidCommitProvisionalLoad(bool is_same_document_navigation,
- ui::PageTransition /*transitionbool*/)
+void UserResourceController::RenderFrameObserverHelper::BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::UserResourceControllerRenderFrame>
+ receiver)
{
- if (is_same_document_navigation)
- return;
+ m_binding.Bind(std::move(receiver));
+}
+void UserResourceController::RenderFrameObserverHelper::DidCommitProvisionalLoad(ui::PageTransition /*transition*/)
+{
// We are almost ready to run scripts. We still have to wait until the host
// process has been notified of the DidCommitProvisionalLoad event to ensure
// that the WebChannelTransportHost is ready to receive messages.
- m_runner.reset(new Runner(render_frame()->GetWebFrame()));
+ m_runner.reset(new Runner(render_frame()->GetWebFrame(), m_userResourceController));
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&Runner::run, m_runner->AsWeakPtr(), UserScriptData::DocumentElementCreation));
+ base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&Runner::run, m_runner->AsWeakPtr(),
+ QtWebEngineCore::UserScriptData::DocumentElementCreation));
}
-void UserResourceController::RenderFrameObserverHelper::DidFinishDocumentLoad()
+void UserResourceController::RenderFrameObserverHelper::DidDispatchDOMContentLoadedEvent()
{
// Don't run scripts if provisional load failed (DidFailProvisionalLoad
// called instead of DidCommitProvisionalLoad).
if (m_runner)
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, base::BindOnce(&Runner::run, m_runner->AsWeakPtr(), UserScriptData::AfterLoad),
- base::TimeDelta::FromMilliseconds(afterLoadTimeout));
+ base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
+ FROM_HERE,
+ base::BindOnce(&Runner::run, m_runner->AsWeakPtr(),
+ QtWebEngineCore::UserScriptData::AfterLoad),
+ base::Milliseconds(afterLoadTimeout));
}
void UserResourceController::RenderFrameObserverHelper::DidFinishLoad()
{
if (m_runner)
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&Runner::run, m_runner->AsWeakPtr(), UserScriptData::AfterLoad));
+ base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&Runner::run, m_runner->AsWeakPtr(),
+ QtWebEngineCore::UserScriptData::AfterLoad));
}
-void UserResourceController::RenderFrameObserverHelper::FrameDetached()
+void UserResourceController::RenderFrameObserverHelper::WillDetach()
{
m_runner.reset();
}
void UserResourceController::RenderFrameObserverHelper::OnDestruct()
{
+ if (content::RenderFrame *frame = render_frame()) {
+ m_userResourceController->renderFrameDestroyed(frame);
+ }
delete this;
}
-void UserResourceController::RenderViewObserverHelper::OnDestruct()
-{
- // Remove all scripts associated with the render view.
- if (content::RenderView *view = render_view())
- UserResourceController::instance()->renderViewDestroyed(view);
- delete this;
-}
-
-bool UserResourceController::RenderFrameObserverHelper::OnMessageReceived(const IPC::Message &message)
-{
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(UserResourceController::RenderFrameObserverHelper, message)
- IPC_MESSAGE_HANDLER(RenderFrameObserverHelper_AddScript, onUserScriptAdded)
- IPC_MESSAGE_HANDLER(RenderFrameObserverHelper_RemoveScript, onUserScriptRemoved)
- IPC_MESSAGE_HANDLER(RenderFrameObserverHelper_ClearScripts, onScriptsCleared)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
-void UserResourceController::RenderFrameObserverHelper::onUserScriptAdded(const UserScriptData &script)
+void UserResourceController::RenderFrameObserverHelper::AddScript(
+ const QtWebEngineCore::UserScriptData &script)
{
if (content::RenderFrame *frame = render_frame())
- if (content::RenderView *view = frame->GetRenderView())
- UserResourceController::instance()->addScriptForView(script, view);
+ m_userResourceController->addScriptForFrame(script, frame);
}
-void UserResourceController::RenderFrameObserverHelper::onUserScriptRemoved(const UserScriptData &script)
+void UserResourceController::RenderFrameObserverHelper::RemoveScript(
+ const QtWebEngineCore::UserScriptData &script)
{
if (content::RenderFrame *frame = render_frame())
- if (content::RenderView *view = frame->GetRenderView())
- UserResourceController::instance()->removeScriptForView(script, view);
+ m_userResourceController->removeScriptForFrame(script, frame);
}
-void UserResourceController::RenderFrameObserverHelper::onScriptsCleared()
+void UserResourceController::RenderFrameObserverHelper::ClearScripts()
{
if (content::RenderFrame *frame = render_frame())
- if (content::RenderView *view = frame->GetRenderView())
- UserResourceController::instance()->clearScriptsForView(view);
+ m_userResourceController->clearScriptsForFrame(frame);
}
-UserResourceController *UserResourceController::instance()
+void UserResourceController::BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::UserResourceController> receiver)
{
- return qt_webengine_userResourceController();
+ m_binding.Bind(std::move(receiver));
}
-bool UserResourceController::OnControlMessageReceived(const IPC::Message &message)
-{
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(UserResourceController, message)
- IPC_MESSAGE_HANDLER(UserResourceController_AddScript, onAddScript)
- IPC_MESSAGE_HANDLER(UserResourceController_RemoveScript, onRemoveScript)
- IPC_MESSAGE_HANDLER(UserResourceController_ClearScripts, onClearScripts)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
-UserResourceController::UserResourceController()
+UserResourceController::UserResourceController() : m_binding(this)
{
#if !defined(QT_NO_DEBUG) || defined(QT_FORCE_ASSERTS)
static bool onlyCalledOnce = true;
@@ -340,68 +282,85 @@ UserResourceController::UserResourceController()
void UserResourceController::renderFrameCreated(content::RenderFrame *renderFrame)
{
// Will destroy itself when the RenderFrame is destroyed.
- new RenderFrameObserverHelper(renderFrame);
+ new RenderFrameObserverHelper(renderFrame, this);
}
-void UserResourceController::renderViewCreated(content::RenderView *renderView)
+void UserResourceController::renderFrameDestroyed(content::RenderFrame *renderFrame)
{
- // Will destroy itself when the RenderView is destroyed.
- new RenderViewObserverHelper(renderView);
+ FrameUserScriptMap::iterator it = m_frameUserScriptMap.find(renderFrame);
+ if (it == m_frameUserScriptMap.end()) // ASSERT maybe?
+ return;
+ if (renderFrame->IsMainFrame()) {
+ for (uint64_t id : std::as_const(it.value()))
+ m_scripts.remove(id);
+ }
+ m_frameUserScriptMap.erase(it);
}
-void UserResourceController::renderViewDestroyed(content::RenderView *renderView)
+void UserResourceController::addScriptForFrame(const QtWebEngineCore::UserScriptData &script,
+ content::RenderFrame *frame)
{
- ViewUserScriptMap::iterator it = m_viewUserScriptMap.find(renderView);
- if (it == m_viewUserScriptMap.end()) // ASSERT maybe?
- return;
- for (uint64_t id : qAsConst(it.value())) {
- m_scripts.remove(id);
- }
- m_viewUserScriptMap.remove(renderView);
+ FrameUserScriptMap::iterator it = m_frameUserScriptMap.find(frame);
+ if (it == m_frameUserScriptMap.end())
+ it = m_frameUserScriptMap.insert(frame, UserScriptList());
+
+ if (!(*it).contains(script.scriptId))
+ (*it).append(script.scriptId);
+ if (!frame || frame->IsMainFrame())
+ m_scripts.insert(script.scriptId, script);
}
-void UserResourceController::addScriptForView(const UserScriptData &script, content::RenderView *view)
+void UserResourceController::removeScriptForFrame(const QtWebEngineCore::UserScriptData &script,
+ content::RenderFrame *frame)
{
- ViewUserScriptMap::iterator it = m_viewUserScriptMap.find(view);
- if (it == m_viewUserScriptMap.end())
- it = m_viewUserScriptMap.insert(view, UserScriptSet());
+ FrameUserScriptMap::iterator it = m_frameUserScriptMap.find(frame);
+ if (it == m_frameUserScriptMap.end())
+ return;
- (*it).insert(script.scriptId);
- m_scripts.insert(script.scriptId, script);
+ (*it).removeOne(script.scriptId);
+ if (!frame || frame->IsMainFrame())
+ m_scripts.remove(script.scriptId);
}
-void UserResourceController::removeScriptForView(const UserScriptData &script, content::RenderView *view)
+void UserResourceController::clearScriptsForFrame(content::RenderFrame *frame)
{
- ViewUserScriptMap::iterator it = m_viewUserScriptMap.find(view);
- if (it == m_viewUserScriptMap.end())
+ FrameUserScriptMap::iterator it = m_frameUserScriptMap.find(frame);
+ if (it == m_frameUserScriptMap.end())
return;
+ if (!frame || frame->IsMainFrame()) {
+ for (uint64_t id : std::as_const(it.value()))
+ m_scripts.remove(id);
+ }
- (*it).remove(script.scriptId);
- m_scripts.remove(script.scriptId);
+ m_frameUserScriptMap.remove(frame);
}
-void UserResourceController::clearScriptsForView(content::RenderView *view)
+void UserResourceController::AddScript(const QtWebEngineCore::UserScriptData &script)
{
- ViewUserScriptMap::iterator it = m_viewUserScriptMap.find(view);
- if (it == m_viewUserScriptMap.end())
- return;
- for (uint64_t id : qAsConst(it.value()))
- m_scripts.remove(id);
+ addScriptForFrame(script, globalScriptsIndex);
+}
- m_viewUserScriptMap.remove(view);
+void UserResourceController::RemoveScript(const QtWebEngineCore::UserScriptData &script)
+{
+ removeScriptForFrame(script, globalScriptsIndex);
}
-void UserResourceController::onAddScript(const UserScriptData &script)
+void UserResourceController::ClearScripts()
{
- addScriptForView(script, globalScriptsIndex);
+ clearScriptsForFrame(globalScriptsIndex);
}
-void UserResourceController::onRemoveScript(const UserScriptData &script)
+void UserResourceController::RegisterMojoInterfaces(
+ blink::AssociatedInterfaceRegistry *associated_interfaces)
{
- removeScriptForView(script, globalScriptsIndex);
+ associated_interfaces->AddInterface<qtwebengine::mojom::UserResourceController>(
+ base::BindRepeating(&UserResourceController::BindReceiver, base::Unretained(this)));
}
-void UserResourceController::onClearScripts()
+void UserResourceController::UnregisterMojoInterfaces(
+ blink::AssociatedInterfaceRegistry *associated_interfaces)
{
- clearScriptsForView(globalScriptsIndex);
+ associated_interfaces->RemoveInterface(qtwebengine::mojom::UserResourceController::Name_);
}
+
+} // namespace
diff --git a/src/core/renderer/user_resource_controller.h b/src/core/renderer/user_resource_controller.h
index 3a493b9b7..a5dab73f1 100644
--- a/src/core/renderer/user_resource_controller.h
+++ b/src/core/renderer/user_resource_controller.h
@@ -1,51 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef USER_RESOURCE_CONTROLLER_H
#define USER_RESOURCE_CONTROLLER_H
#include "content/public/renderer/render_thread_observer.h"
-
-#include "common/user_script_data.h"
+#include "qtwebengine/userscript/userscript.mojom.h"
+#include "qtwebengine/userscript/user_script_data.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
#include <QtCore/QHash>
-#include <QtCore/QSet>
+#include <QtCore/QList>
namespace blink {
class WebLocalFrame;
@@ -53,45 +18,48 @@ class WebLocalFrame;
namespace content {
class RenderFrame;
-class RenderView;
}
-class UserResourceController : public content::RenderThreadObserver
+namespace QtWebEngineCore {
+
+class UserResourceController : public content::RenderThreadObserver,
+ qtwebengine::mojom::UserResourceController
{
public:
- static UserResourceController *instance();
UserResourceController();
void renderFrameCreated(content::RenderFrame *);
- void renderViewCreated(content::RenderView *);
- void renderViewDestroyed(content::RenderView *renderView);
- void addScriptForView(const UserScriptData &, content::RenderView *);
- void removeScriptForView(const UserScriptData &, content::RenderView *);
- void clearScriptsForView(content::RenderView *);
+ void renderFrameDestroyed(content::RenderFrame *);
+ void addScriptForFrame(const QtWebEngineCore::UserScriptData &, content::RenderFrame *);
+ void removeScriptForFrame(const QtWebEngineCore::UserScriptData &, content::RenderFrame *);
+ void clearScriptsForFrame(content::RenderFrame *);
void RunScriptsAtDocumentEnd(content::RenderFrame *render_frame);
+ void BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebengine::mojom::UserResourceController> receiver);
private:
Q_DISABLE_COPY(UserResourceController)
- class RenderFrameObserverHelper;
- class RenderViewObserverHelper;
+ // content::RenderThreadObserver:
+ void RegisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
+ void UnregisterMojoInterfaces(blink::AssociatedInterfaceRegistry *associated_interfaces) override;
- // RenderProcessObserver implementation.
- bool OnControlMessageReceived(const IPC::Message &message) override;
-
- void onAddScript(const UserScriptData &);
- void onRemoveScript(const UserScriptData &);
- void onClearScripts();
+ class RenderFrameObserverHelper;
- void runScripts(UserScriptData::InjectionPoint, blink::WebLocalFrame *);
+ void AddScript(const QtWebEngineCore::UserScriptData &data) override;
+ void RemoveScript(const QtWebEngineCore::UserScriptData &data) override;
+ void ClearScripts() override;
- typedef QSet<uint64_t> UserScriptSet;
- typedef QHash<const content::RenderView *, UserScriptSet> ViewUserScriptMap;
- ViewUserScriptMap m_viewUserScriptMap;
- QHash<uint64_t, UserScriptData> m_scripts;
+ void runScripts(QtWebEngineCore::UserScriptData::InjectionPoint, blink::WebLocalFrame *);
+ typedef QList<uint64_t> UserScriptList;
+ typedef QHash<const content::RenderFrame *, UserScriptList> FrameUserScriptMap;
+ FrameUserScriptMap m_frameUserScriptMap;
+ QHash<uint64_t, QtWebEngineCore::UserScriptData> m_scripts;
+ mojo::AssociatedReceiver<qtwebengine::mojom::UserResourceController> m_binding;
friend class RenderFrameObserverHelper;
};
+} // namespace QtWebEngineCore
#endif // USER_RESOURCE_CONTROLLER_H
diff --git a/src/core/renderer/web_channel_ipc_transport.cpp b/src/core/renderer/web_channel_ipc_transport.cpp
index 1fb3bc678..89b20c7d1 100644
--- a/src/core/renderer/web_channel_ipc_transport.cpp
+++ b/src/core/renderer/web_channel_ipc_transport.cpp
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.Chromium file.
#include "renderer/web_channel_ipc_transport.h"
-#include "common/qt_messages.h"
-
#include "content/public/renderer/render_frame.h"
#include "gin/arguments.h"
#include "gin/handle.h"
@@ -54,11 +16,8 @@
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "v8/include/v8.h"
-#include "services/service_manager/public/cpp/interface_provider.h"
#include "qtwebengine/browser/qtwebchannel.mojom.h"
-#include <QJsonDocument>
-
namespace QtWebEngineCore {
class WebChannelTransport : public gin::Wrappable<WebChannelTransport>
@@ -74,8 +33,8 @@ private:
// gin::WrappableBase
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate *isolate) override;
-
- DISALLOW_COPY_AND_ASSIGN(WebChannelTransport);
+ mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportHost> m_remote;
+ content::RenderFrame *m_renderFrame = nullptr;
};
gin::WrapperInfo WebChannelTransport::kWrapperInfo = { gin::kEmbedderNativeGin };
@@ -89,23 +48,23 @@ void WebChannelTransport::Install(blink::WebLocalFrame *frame, uint worldId)
context = frame->MainWorldScriptContext();
else
context = frame->IsolatedWorldScriptContext(worldId);
+ if (context.IsEmpty())
+ return;
v8::Context::Scope contextScope(context);
gin::Handle<WebChannelTransport> transport = gin::CreateHandle(isolate, new WebChannelTransport);
+ if (transport.IsEmpty())
+ return;
v8::Local<v8::Object> global = context->Global();
- v8::MaybeLocal<v8::Value> qtObjectValue = global->Get(context, gin::StringToV8(isolate, "qt"));
v8::Local<v8::Object> qtObject;
- if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject()) {
- qtObject = v8::Object::New(isolate);
- auto whocares = global->Set(context, gin::StringToV8(isolate, "qt"), qtObject);
- // FIXME: Perhaps error out, but the return value is V8 internal...
- Q_UNUSED(whocares);
- } else {
- qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked());
- }
- auto whocares = qtObject->Set(context, gin::StringToV8(isolate, "webChannelTransport"), transport.ToV8());
- Q_UNUSED(whocares);
+ qtObject = v8::Object::New(isolate);
+ global->CreateDataProperty(context,
+ gin::StringToSymbol(isolate, "qt"),
+ qtObject).Check();
+ qtObject->CreateDataProperty(context,
+ gin::StringToSymbol(isolate, "webChannelTransport"),
+ transport.ToV8()).Check();
}
void WebChannelTransport::Uninstall(blink::WebLocalFrame *frame, uint worldId)
@@ -117,16 +76,16 @@ void WebChannelTransport::Uninstall(blink::WebLocalFrame *frame, uint worldId)
context = frame->MainWorldScriptContext();
else
context = frame->IsolatedWorldScriptContext(worldId);
+ if (context.IsEmpty())
+ return;
v8::Context::Scope contextScope(context);
v8::Local<v8::Object> global(context->Global());
- v8::MaybeLocal<v8::Value> qtObjectValue = global->Get(context, gin::StringToV8(isolate, "qt"));
- if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject())
+ v8::Local<v8::Value> qtObjectValue;
+ if (!global->Get(context, gin::StringToV8(isolate, "qt")).ToLocal(&qtObjectValue) || !qtObjectValue->IsObject())
return;
- v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked());
- // FIXME: We can't do anything about a failure, so why the .. is it nodiscard?
- auto whocares = qtObject->Delete(context, gin::StringToV8(isolate, "webChannelTransport"));
- Q_UNUSED(whocares);
+ v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue);
+ qtObject->Delete(context, gin::StringToV8(isolate, "webChannelTransport")).Check();
}
void WebChannelTransport::NativeQtSendMessage(gin::Arguments *args)
@@ -152,22 +111,17 @@ void WebChannelTransport::NativeQtSendMessage(gin::Arguments *args)
return;
}
v8::Local<v8::String> jsonString = v8::Local<v8::String>::Cast(jsonValue);
+ std::vector<uint8_t> json(jsonString->Utf8Length(isolate), 0);
+ jsonString->WriteUtf8(isolate, reinterpret_cast<char *>(json.data()), json.size(), nullptr,
+ v8::String::REPLACE_INVALID_UTF8);
- QByteArray json(jsonString->Utf8Length(isolate), 0);
- jsonString->WriteUtf8(isolate, json.data(), json.size(), nullptr, v8::String::REPLACE_INVALID_UTF8);
-
- QJsonParseError error;
- QJsonDocument doc = QJsonDocument::fromJson(json, &error);
- if (error.error != QJsonParseError::NoError) {
- args->ThrowTypeError("Invalid JSON");
- return;
+ if (!m_remote) {
+ renderFrame->GetRemoteAssociatedInterfaces()->GetInterface(&m_remote);
+ m_renderFrame = renderFrame;
}
+ DCHECK(renderFrame == m_renderFrame);
- int size = 0;
- const char *rawData = doc.rawData(&size);
- mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportHost> webChannelTransport;
- renderFrame->GetRemoteAssociatedInterfaces()->GetInterface(&webChannelTransport);
- webChannelTransport->DispatchWebChannelMessage(std::vector<uint8_t>(rawData, rawData + size));
+ m_remote->DispatchWebChannelMessage(json);
}
gin::ObjectTemplateBuilder WebChannelTransport::GetObjectTemplateBuilder(v8::Isolate *isolate)
@@ -177,16 +131,19 @@ gin::ObjectTemplateBuilder WebChannelTransport::GetObjectTemplateBuilder(v8::Iso
}
WebChannelIPCTransport::WebChannelIPCTransport(content::RenderFrame *renderFrame)
- : content::RenderFrameObserver(renderFrame), m_worldId(0), m_worldInitialized(false)
+ : content::RenderFrameObserver(renderFrame)
+ , m_worldId(0)
+ , m_worldInitialized(false)
+ , m_binding(this)
{
- renderFrame->GetAssociatedInterfaceRegistry()->AddInterface(
+ renderFrame->GetAssociatedInterfaceRegistry()->AddInterface<qtwebchannel::mojom::WebChannelTransportRender>(
base::BindRepeating(&WebChannelIPCTransport::BindReceiver, base::Unretained(this)));
}
void WebChannelIPCTransport::BindReceiver(
mojo::PendingAssociatedReceiver<qtwebchannel::mojom::WebChannelTransportRender> receiver)
{
- m_receivers.Add(this, std::move(receiver));
+ m_binding.Bind(std::move(receiver));
}
void WebChannelIPCTransport::SetWorldId(uint32_t worldId)
@@ -213,18 +170,14 @@ void WebChannelIPCTransport::ResetWorldId()
m_worldId = 0;
}
-void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t> &binaryJson, uint32_t worldId)
+void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t> &json,
+ uint32_t worldId)
{
DCHECK(m_worldId == worldId);
if (!m_canUseContext)
return;
- QJsonDocument doc = QJsonDocument::fromRawData(reinterpret_cast<const char *>(binaryJson.data()), binaryJson.size(),
- QJsonDocument::BypassValidation);
- DCHECK(doc.isObject());
- QByteArray json = doc.toJson(QJsonDocument::Compact);
-
blink::WebLocalFrame *frame = render_frame()->GetWebFrame();
v8::Isolate *isolate = blink::MainThreadIsolate();
v8::HandleScope handleScope(isolate);
@@ -236,17 +189,18 @@ void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t
v8::Context::Scope contextScope(context);
v8::Local<v8::Object> global(context->Global());
- v8::MaybeLocal<v8::Value> qtObjectValue(global->Get(context, gin::StringToV8(isolate, "qt")));
- if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject())
+ v8::Local<v8::Value> qtObjectValue;
+ if (!global->Get(context, gin::StringToV8(isolate, "qt")).ToLocal(&qtObjectValue) || !qtObjectValue->IsObject())
return;
- v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked());
- v8::MaybeLocal<v8::Value> webChannelObjectValue(
- qtObject->Get(context, gin::StringToV8(isolate, "webChannelTransport")));
- if (webChannelObjectValue.IsEmpty() || !webChannelObjectValue.ToLocalChecked()->IsObject())
+ v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue);
+ v8::Local<v8::Value> webChannelObjectValue;
+ if (!qtObject->Get(context, gin::StringToV8(isolate, "webChannelTransport")).ToLocal(&webChannelObjectValue)
+ || !webChannelObjectValue->IsObject())
return;
- v8::Local<v8::Object> webChannelObject = v8::Local<v8::Object>::Cast(webChannelObjectValue.ToLocalChecked());
- v8::MaybeLocal<v8::Value> callbackValue(webChannelObject->Get(context, gin::StringToV8(isolate, "onmessage")));
- if (callbackValue.IsEmpty() || !callbackValue.ToLocalChecked()->IsFunction()) {
+ v8::Local<v8::Object> webChannelObject = v8::Local<v8::Object>::Cast(webChannelObjectValue);
+ v8::Local<v8::Value> callbackValue;
+ if (!webChannelObject->Get(context, gin::StringToV8(isolate, "onmessage")).ToLocal(&callbackValue)
+ || !callbackValue->IsFunction()) {
LOG(WARNING) << "onmessage is not a callable property of qt.webChannelTransport. Some things might not work as "
"expected.";
return;
@@ -255,30 +209,32 @@ void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t
v8::Local<v8::Object> messageObject(v8::Object::New(isolate));
v8::Maybe<bool> wasSet = messageObject->DefineOwnProperty(
context, v8::String::NewFromUtf8(isolate, "data").ToLocalChecked(),
- v8::String::NewFromUtf8(isolate, json.constData(), v8::NewStringType::kNormal, json.size()).ToLocalChecked(),
+ v8::String::NewFromUtf8(isolate, reinterpret_cast<const char *>(json.data()),
+ v8::NewStringType::kNormal, json.size())
+ .ToLocalChecked(),
v8::PropertyAttribute(v8::ReadOnly | v8::DontDelete));
DCHECK(!wasSet.IsNothing() && wasSet.FromJust());
- v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(callbackValue.ToLocalChecked());
+ v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(callbackValue);
v8::Local<v8::Value> argv[] = { messageObject };
frame->CallFunctionEvenIfScriptDisabled(callback, webChannelObject, 1, argv);
}
-void WebChannelIPCTransport::WillReleaseScriptContext(v8::Local<v8::Context> context, int worldId)
-{
- if (static_cast<uint>(worldId) == m_worldId)
- m_canUseContext = false;
-}
-
-void WebChannelIPCTransport::DidClearWindowObject()
+void WebChannelIPCTransport::DidCreateScriptContext(v8::Local<v8::Context> context, int32_t worldId)
{
- if (!m_canUseContext) {
+ if (static_cast<uint>(worldId) == m_worldId && !m_canUseContext) {
m_canUseContext = true;
if (m_worldInitialized)
WebChannelTransport::Install(render_frame()->GetWebFrame(), m_worldId);
}
}
+void WebChannelIPCTransport::WillReleaseScriptContext(v8::Local<v8::Context> context, int worldId)
+{
+ if (static_cast<uint>(worldId) == m_worldId)
+ m_canUseContext = false;
+}
+
void WebChannelIPCTransport::OnDestruct()
{
delete this;
diff --git a/src/core/renderer/web_channel_ipc_transport.h b/src/core/renderer/web_channel_ipc_transport.h
index 15778a7bc..95aa39850 100644
--- a/src/core/renderer/web_channel_ipc_transport.h
+++ b/src/core/renderer/web_channel_ipc_transport.h
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_CHANNEL_IPC_TRANSPORT_H
#define WEB_CHANNEL_IPC_TRANSPORT_H
#include "content/public/renderer/render_frame_observer.h"
-#include "services/service_manager/public/cpp/binder_registry.h"
-#include "mojo/public/cpp/bindings/associated_receiver_set.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "qtwebengine/browser/qtwebchannel.mojom.h"
@@ -61,11 +25,11 @@ private:
// qtwebchannel::mojom::WebChannelTransportRender
void SetWorldId(uint32_t worldId) override;
void ResetWorldId() override;
- void DispatchWebChannelMessage(const std::vector<uint8_t> &binaryJson, uint32_t worldId) override;
+ void DispatchWebChannelMessage(const std::vector<uint8_t> &json, uint32_t worldId) override;
// RenderFrameObserver
+ void DidCreateScriptContext(v8::Local<v8::Context> context, int32_t worldId) override;
void WillReleaseScriptContext(v8::Local<v8::Context> context, int worldId) override;
- void DidClearWindowObject() override;
void OnDestruct() override;
void BindReceiver(mojo::PendingAssociatedReceiver<qtwebchannel::mojom::WebChannelTransportRender> receiver);
@@ -76,7 +40,7 @@ private:
bool m_worldInitialized;
// True means it's currently OK to manipulate the frame's script context.
bool m_canUseContext = false;
- mojo::AssociatedReceiverSet<qtwebchannel::mojom::WebChannelTransportRender> m_receivers;
+ mojo::AssociatedReceiver<qtwebchannel::mojom::WebChannelTransportRender> m_binding;
};
} // namespace
diff --git a/src/core/renderer/web_engine_page_render_frame.cpp b/src/core/renderer/web_engine_page_render_frame.cpp
new file mode 100644
index 000000000..1e7ac62fc
--- /dev/null
+++ b/src/core/renderer/web_engine_page_render_frame.cpp
@@ -0,0 +1,66 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "renderer/web_engine_page_render_frame.h"
+#include "content/public/renderer/render_frame.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
+
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_frame_content_dumper.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
+
+namespace QtWebEngineCore {
+
+WebEnginePageRenderFrame::WebEnginePageRenderFrame(content::RenderFrame *render_frame)
+ : content::RenderFrameObserver(render_frame), m_binding(this), m_ready(false)
+{
+ render_frame->GetAssociatedInterfaceRegistry()->AddInterface<qtwebenginepage::mojom::WebEnginePageRenderFrame>(
+ base::BindRepeating(&WebEnginePageRenderFrame::BindReceiver, base::Unretained(this)));
+}
+
+void WebEnginePageRenderFrame::BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebenginepage::mojom::WebEnginePageRenderFrame> receiver)
+{
+ m_binding.Bind(std::move(receiver));
+}
+
+void WebEnginePageRenderFrame::FetchDocumentMarkup(uint64_t requestId,
+ FetchDocumentMarkupCallback callback)
+{
+ blink::WebLocalFrame *frame = render_frame()->GetWebFrame();
+ blink::WebString markup;
+ if (m_ready)
+ markup = blink::WebFrameContentDumper::DumpAsMarkup(frame);
+ else
+ markup = blink::WebString::FromUTF8("<html><head></head><body></body></html>");
+ std::move(callback).Run(requestId, markup.Utf8());
+}
+
+void WebEnginePageRenderFrame::FetchDocumentInnerText(uint64_t requestId,
+ FetchDocumentInnerTextCallback callback)
+{
+ blink::WebLocalFrame *frame = render_frame()->GetWebFrame();
+ blink::WebString text;
+ if (m_ready) {
+ text = blink::WebFrameContentDumper::DumpFrameTreeAsText(
+ frame, std::numeric_limits<int32_t>::max());
+ }
+ std::move(callback).Run(requestId, text.Utf8());
+}
+
+void WebEnginePageRenderFrame::SetBackgroundColor(uint32_t color)
+{
+ render_frame()->GetWebFrame()->View()->SetBaseBackgroundColorOverrideForInspector(color);
+}
+
+void WebEnginePageRenderFrame::OnDestruct()
+{
+ delete this;
+}
+
+void WebEnginePageRenderFrame::DidFinishLoad()
+{
+ m_ready = true;
+}
+}
diff --git a/src/core/renderer/web_engine_page_render_frame.h b/src/core/renderer/web_engine_page_render_frame.h
new file mode 100644
index 000000000..7d0e25267
--- /dev/null
+++ b/src/core/renderer/web_engine_page_render_frame.h
@@ -0,0 +1,41 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#ifndef WEB_ENGINE_PAGE_RENDER_FRAME_H
+#define WEB_ENGINE_PAGE_RENDER_FRAME_H
+
+#include "content/public/renderer/render_frame_observer.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "qtwebengine/browser/qtwebenginepage.mojom.h"
+
+namespace content {
+class RenderFrame;
+}
+
+namespace QtWebEngineCore {
+
+class WebEnginePageRenderFrame : private content::RenderFrameObserver,
+ public qtwebenginepage::mojom::WebEnginePageRenderFrame
+{
+public:
+ WebEnginePageRenderFrame(content::RenderFrame *render_frame);
+ WebEnginePageRenderFrame(const WebEnginePageRenderFrame &) = delete;
+ WebEnginePageRenderFrame &operator=(const WebEnginePageRenderFrame &) = delete;
+
+private:
+ void FetchDocumentMarkup(uint64_t requestId, FetchDocumentMarkupCallback callback) override;
+ void FetchDocumentInnerText(uint64_t requestId,
+ FetchDocumentInnerTextCallback callback) override;
+ void SetBackgroundColor(uint32_t color) override;
+ void OnDestruct() override;
+ void DidFinishLoad() override;
+ void
+ BindReceiver(mojo::PendingAssociatedReceiver<qtwebenginepage::mojom::WebEnginePageRenderFrame>
+ receiver);
+
+private:
+ mojo::AssociatedReceiver<qtwebenginepage::mojom::WebEnginePageRenderFrame> m_binding;
+ bool m_ready;
+};
+} // namespace QtWebEngineCore
+
+#endif // WEB_ENGINE_PAGE_RENDER_FRAME_H
diff --git a/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.cpp b/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.cpp
deleted file mode 100644
index d54a9cdf2..000000000
--- a/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// This is based on chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#include "pepper_flash_browser_host_qt.h"
-
-#include "base/time/time.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_ppapi_host.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_process_host.h"
-#include "ipc/ipc_message_macros.h"
-#include "ppapi/c/pp_errors.h"
-#include "ppapi/c/private/ppb_flash.h"
-#include "ppapi/host/dispatch_host_message.h"
-#include "ppapi/proxy/ppapi_messages.h"
-#include "ppapi/proxy/resource_message_params.h"
-#include "ppapi/shared_impl/time_conversion.h"
-#include "qtwebenginecoreglobal_p.h"
-#include "url/gurl.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#elif defined(OS_MACOSX)
-#include <CoreServices/CoreServices.h>
-#endif
-
-using content::BrowserPpapiHost;
-using content::BrowserThread;
-using content::RenderProcessHost;
-
-namespace QtWebEngineCore {
-
-PepperFlashBrowserHostQt::PepperFlashBrowserHostQt(BrowserPpapiHost* host,
- PP_Instance instance,
- PP_Resource resource)
- : ResourceHost(host->GetPpapiHost(), instance, resource),
- host_(host),
- weak_factory_(this)
-{
- int unused;
- host->GetRenderFrameIDsForInstance(instance, &render_process_id_, &unused);
-}
-
-PepperFlashBrowserHostQt::~PepperFlashBrowserHostQt() {}
-
-int32_t PepperFlashBrowserHostQt::OnResourceMessageReceived(
- const IPC::Message& msg,
- ppapi::host::HostMessageContext* context)
-{
- PPAPI_BEGIN_MESSAGE_MAP(PepperFlashBrowserHostQt, msg)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(PpapiHostMsg_Flash_UpdateActivity,
- OnUpdateActivity)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Flash_GetLocalTimeZoneOffset,
- OnGetLocalTimeZoneOffset)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(PpapiHostMsg_Flash_GetLocalDataRestrictions,
- OnGetLocalDataRestrictions)
- PPAPI_END_MESSAGE_MAP()
- return PP_ERROR_FAILED;
-}
-
-int32_t PepperFlashBrowserHostQt::OnUpdateActivity(ppapi::host::HostMessageContext* host_context)
-{
-#if defined(OS_WIN)
- // Reading then writing back the same value to the screensaver timeout system
- // setting resets the countdown which prevents the screensaver from turning
- // on "for a while". As long as the plugin pings us with this message faster
- // than the screensaver timeout, it won't go on.
- int value = 0;
- if (SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &value, 0))
- SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, value, NULL, 0);
-#elif defined(OS_MACOSX)
- UpdateSystemActivity(OverallAct);
-#endif
- return PP_OK;
-}
-
-int32_t PepperFlashBrowserHostQt::OnGetLocalTimeZoneOffset(
- ppapi::host::HostMessageContext* host_context,
- const base::Time& t)
-{
- // The reason for this processing being in the browser process is that on
- // Linux, the localtime calls require filesystem access prohibited by the
- // sandbox.
- host_context->reply_msg = PpapiPluginMsg_Flash_GetLocalTimeZoneOffsetReply(
- ppapi::PPGetLocalTimeZoneOffset(t));
- return PP_OK;
-}
-
-int32_t PepperFlashBrowserHostQt::OnGetLocalDataRestrictions(
- ppapi::host::HostMessageContext* context)
-{
- QT_NOT_YET_IMPLEMENTED
- return PP_OK;
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.h b/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.h
deleted file mode 100644
index 5d1107dfb..000000000
--- a/src/core/renderer_host/pepper/pepper_flash_browser_host_qt.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEPPER_FLASH_BROWSER_HOST_QT_H
-#define PEPPER_FLASH_BROWSER_HOST_QT_H
-
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "ppapi/host/host_message_context.h"
-#include "ppapi/host/resource_host.h"
-
-namespace base {
-class Time;
-}
-
-namespace content {
-class BrowserPpapiHost;
-class ResourceContext;
-}
-
-class GURL;
-
-namespace QtWebEngineCore {
-
-class PepperFlashBrowserHostQt : public ppapi::host::ResourceHost {
-public:
- PepperFlashBrowserHostQt(content::BrowserPpapiHost* host,
- PP_Instance instance,
- PP_Resource resource);
- ~PepperFlashBrowserHostQt() override;
-
- // ppapi::host::ResourceHost override.
- int32_t OnResourceMessageReceived(
- const IPC::Message& msg,
- ppapi::host::HostMessageContext* context) override;
-
-private:
- int32_t OnUpdateActivity(ppapi::host::HostMessageContext* host_context);
- int32_t OnGetLocalTimeZoneOffset(
- ppapi::host::HostMessageContext* host_context,
- const base::Time& t);
- int32_t OnGetLocalDataRestrictions(ppapi::host::HostMessageContext* context);
-
- void GetLocalDataRestrictions(ppapi::host::ReplyMessageContext reply_context,
- const GURL& document_url,
- const GURL& plugin_url);
-
- content::BrowserPpapiHost* host_;
- int render_process_id_;
- base::WeakPtrFactory<PepperFlashBrowserHostQt> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(PepperFlashBrowserHostQt);
-};
-
-} // namespace QtWebEngineCore
-
-#endif // PEPPER_FLASH_BROWSER_HOST_QT_H
diff --git a/src/core/renderer_host/pepper/pepper_host_factory_qt.cpp b/src/core/renderer_host/pepper/pepper_host_factory_qt.cpp
deleted file mode 100644
index 00ab4963b..000000000
--- a/src/core/renderer_host/pepper/pepper_host_factory_qt.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// This is based on chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc:
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#include "pepper_host_factory_qt.h"
-
-#include "base/memory/ptr_util.h"
-#include "build/build_config.h"
-#include "chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h"
-#include "content/public/browser/browser_ppapi_host.h"
-#include "ppapi/host/message_filter_host.h"
-#include "ppapi/host/ppapi_host.h"
-#include "ppapi/host/resource_host.h"
-#include "ppapi/proxy/ppapi_messages.h"
-#include "ppapi/shared_impl/ppapi_permissions.h"
-
-#include "pepper_flash_browser_host_qt.h"
-#include "pepper_isolated_file_system_message_filter.h"
-
-using ppapi::host::MessageFilterHost;
-using ppapi::host::ResourceMessageFilter;
-
-namespace QtWebEngineCore {
-
-PepperHostFactoryQt::PepperHostFactoryQt(content::BrowserPpapiHost* host)
- : host_(host)
-{
-}
-
-PepperHostFactoryQt::~PepperHostFactoryQt() {}
-
-std::unique_ptr<ppapi::host::ResourceHost> PepperHostFactoryQt::CreateResourceHost(ppapi::host::PpapiHost* host,
- PP_Resource resource,
- PP_Instance instance,
- const IPC::Message& message)
-{
- DCHECK(host == host_->GetPpapiHost());
-
-
- if (!host_->IsValidInstance(instance))
- return nullptr;
-
- // Flash interfaces.
- if (host_->GetPpapiHost()->permissions().HasPermission(ppapi::PERMISSION_FLASH)) {
- switch (message.type()) {
- case PpapiHostMsg_Flash_Create::ID:
- return base::WrapUnique(new PepperFlashBrowserHostQt(host_, instance, resource));
- case PpapiHostMsg_FlashClipboard_Create::ID: {
- scoped_refptr<ResourceMessageFilter> clipboard_filter(new PepperFlashClipboardMessageFilter);
- return base::WrapUnique(new MessageFilterHost(
- host_->GetPpapiHost(), instance, resource, clipboard_filter));
- }
- }
- }
-
- // Permissions for the following interfaces will be checked at the
- // time of the corresponding instance's methods calls (because
- // permission check can be performed only on the UI
- // thread). Currently these interfaces are available only for
- // whitelisted apps which may not have access to the other private
- // interfaces.
- if (message.type() == PpapiHostMsg_IsolatedFileSystem_Create::ID) {
- PepperIsolatedFileSystemMessageFilter* isolated_fs_filter = PepperIsolatedFileSystemMessageFilter::Create(instance, host_);
- if (!isolated_fs_filter)
- return nullptr;
- return base::WrapUnique(
- new MessageFilterHost(host_->GetPpapiHost(), instance, resource, isolated_fs_filter));
- }
-
- return nullptr;
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/renderer_host/pepper/pepper_host_factory_qt.h b/src/core/renderer_host/pepper/pepper_host_factory_qt.h
deleted file mode 100644
index 0446cf9e3..000000000
--- a/src/core/renderer_host/pepper/pepper_host_factory_qt.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEPPER_HOST_FACTORY_QT_H
-#define PEPPER_HOST_FACTORY_QT_H
-
-#include "base/compiler_specific.h"
-#include "ppapi/host/host_factory.h"
-#include "ppapi/host/resource_host.h"
-#include "ppapi/host/ppapi_host.h"
-
-namespace content {
-class BrowserPpapiHost;
-} // namespace content
-
-namespace QtWebEngineCore {
-
-class PepperHostFactoryQt final : public ppapi::host::HostFactory {
-public:
- // Non-owning pointer to the filter must outlive this class.
- explicit PepperHostFactoryQt(content::BrowserPpapiHost* host);
- ~PepperHostFactoryQt() override;
-
- virtual std::unique_ptr<ppapi::host::ResourceHost> CreateResourceHost(
- ppapi::host::PpapiHost* host,
- PP_Resource resource,
- PP_Instance instance,
- const IPC::Message& message) override;
-private:
- // Non-owning pointer.
- content::BrowserPpapiHost* host_;
-
- DISALLOW_COPY_AND_ASSIGN(PepperHostFactoryQt);
-};
-} // namespace QtWebEngineCore
-
-#endif // PEPPER_HOST_FACTORY_QT_H
diff --git a/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.cpp b/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.cpp
deleted file mode 100644
index 6e9efb5ad..000000000
--- a/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// This is based on chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc:
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE.Chromium file.
-
-#include "pepper_isolated_file_system_message_filter.h"
-
-#include "base/macros.h"
-#include "base/task/post_task.h"
-#include "chrome/common/chrome_switches.h"
-#include "content/public/browser/browser_ppapi_host.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/child_process_security_policy.h"
-#include "content/public/browser/render_view_host.h"
-#include "ppapi/c/pp_errors.h"
-#include "ppapi/host/dispatch_host_message.h"
-#include "ppapi/host/host_message_context.h"
-#include "ppapi/host/ppapi_host.h"
-#include "ppapi/proxy/ppapi_messages.h"
-#include "ppapi/shared_impl/file_system_util.h"
-#include "storage/browser/file_system/isolated_context.h"
-
-namespace QtWebEngineCore {
-
-// static
-PepperIsolatedFileSystemMessageFilter* PepperIsolatedFileSystemMessageFilter::Create(PP_Instance instance, content::BrowserPpapiHost *host)
-{
- int render_process_id;
- int unused_render_frame_id;
- if (!host->GetRenderFrameIDsForInstance(instance, &render_process_id, &unused_render_frame_id))
- return nullptr;
- return new PepperIsolatedFileSystemMessageFilter(render_process_id, host->GetPpapiHost());
-}
-
-PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter(int render_process_id,
- ppapi::host::PpapiHost *ppapi_host)
- : m_render_process_id(render_process_id),
- m_ppapi_host(ppapi_host)
-{}
-
-PepperIsolatedFileSystemMessageFilter::~PepperIsolatedFileSystemMessageFilter()
-{}
-
-scoped_refptr<base::TaskRunner> PepperIsolatedFileSystemMessageFilter::OverrideTaskRunnerForMessage(const IPC::Message &)
-{
- // In order to reach ExtensionSystem, we need to get ProfileManager first.
- // ProfileManager lives in UI thread, so we need to do this in UI thread.
- return base::CreateSingleThreadTaskRunner({content::BrowserThread::UI});
-}
-
-int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived(const IPC::Message& msg, ppapi::host::HostMessageContext *context)
-{
- PPAPI_BEGIN_MESSAGE_MAP(PepperIsolatedFileSystemMessageFilter, msg)
- PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_IsolatedFileSystem_BrowserOpen, OnOpenFileSystem)
- PPAPI_END_MESSAGE_MAP()
- return PP_ERROR_FAILED;
-}
-
-int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem(ppapi::host::HostMessageContext *context,
- PP_IsolatedFileSystemType_Private type)
-{
- switch (type) {
- case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_INVALID:
- break;
- case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_CRX:
- return PP_ERROR_NOTSUPPORTED;
- case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_PLUGINPRIVATE:
- return OpenPluginPrivateFileSystem(context);
- }
- NOTREACHED();
- context->reply_msg = PpapiPluginMsg_IsolatedFileSystem_BrowserOpenReply(std::string());
- return PP_ERROR_FAILED;
-}
-
-int32_t PepperIsolatedFileSystemMessageFilter::OpenPluginPrivateFileSystem(ppapi::host::HostMessageContext *context)
-{
- DCHECK(m_ppapi_host);
- // Only plugins with private permission can open the filesystem.
- if (!m_ppapi_host->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
- return PP_ERROR_NOACCESS;
-
- const std::string& root_name = ppapi::IsolatedFileSystemTypeToRootName(PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_PLUGINPRIVATE);
- const std::string& fsid =
- storage::IsolatedContext::GetInstance()->RegisterFileSystemForVirtualPath(
- storage::kFileSystemTypePluginPrivate, root_name, base::FilePath());
-
- // Grant full access of isolated filesystem to renderer process.
- content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance();
- policy->GrantCreateReadWriteFileSystem(m_render_process_id, fsid);
-
- context->reply_msg = PpapiPluginMsg_IsolatedFileSystem_BrowserOpenReply(fsid);
- return PP_OK;
-}
-
-} // namespace chrome
diff --git a/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.h b/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.h
deleted file mode 100644
index 750f7cea0..000000000
--- a/src/core/renderer_host/pepper/pepper_isolated_file_system_message_filter.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H
-#define PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H
-
-#include "base/macros.h"
-#include "ppapi/c/pp_instance.h"
-#include "ppapi/c/pp_resource.h"
-#include "ppapi/c/private/ppb_isolated_file_system_private.h"
-#include "ppapi/host/resource_host.h"
-#include "ppapi/host/resource_message_filter.h"
-
-namespace content {
-class BrowserPpapiHost;
-}
-
-namespace ppapi {
-namespace host {
-struct HostMessageContext;
-} // namespace host
-} // namespace ppapi
-
-namespace QtWebEngineCore {
-
-class PepperIsolatedFileSystemMessageFilter : public ppapi::host::ResourceMessageFilter {
-public:
- static PepperIsolatedFileSystemMessageFilter *Create(PP_Instance instance, content::BrowserPpapiHost *host);
-
- // ppapi::host::ResourceMessageFilter implementation.
- scoped_refptr<base::TaskRunner> OverrideTaskRunnerForMessage(const IPC::Message &msg) override;
- int32_t OnResourceMessageReceived(const IPC::Message &msg, ppapi::host::HostMessageContext *context) override;
-
-private:
- PepperIsolatedFileSystemMessageFilter(int render_process_id, ppapi::host::PpapiHost *ppapi_host);
-
- ~PepperIsolatedFileSystemMessageFilter() override;
-
-
- int32_t OnOpenFileSystem(ppapi::host::HostMessageContext *context, PP_IsolatedFileSystemType_Private type);
- int32_t OpenPluginPrivateFileSystem(ppapi::host::HostMessageContext *context);
-
- const int m_render_process_id;
-
- // Not owned by this object.
- ppapi::host::PpapiHost* m_ppapi_host;
-
- DISALLOW_COPY_AND_ASSIGN(PepperIsolatedFileSystemMessageFilter);
-};
-
-} // namespace QtWebEngineCore
-
-#endif // PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H
diff --git a/src/core/renderer_host/render_view_observer_host_qt.cpp b/src/core/renderer_host/render_view_observer_host_qt.cpp
deleted file mode 100644
index 165a9d86a..000000000
--- a/src/core/renderer_host/render_view_observer_host_qt.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "render_view_observer_host_qt.h"
-
-#include "common/qt_messages.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/web_contents.h"
-
-#include "render_widget_host_view_qt.h"
-#include "type_conversion.h"
-#include "web_contents_adapter_client.h"
-
-namespace QtWebEngineCore {
-
-RenderViewObserverHostQt::RenderViewObserverHostQt(content::WebContents *webContents, WebContentsAdapterClient *adapterClient)
- : content::WebContentsObserver(webContents)
- , m_adapterClient(adapterClient)
-{
-}
-
-void RenderViewObserverHostQt::fetchDocumentMarkup(quint64 requestId)
-{
- web_contents()->GetRenderViewHost()->Send(
- new RenderViewObserverQt_FetchDocumentMarkup(
- web_contents()->GetRenderViewHost()->GetRoutingID(), requestId));
-}
-
-void RenderViewObserverHostQt::fetchDocumentInnerText(quint64 requestId)
-{
- web_contents()->GetRenderViewHost()->Send(
- new RenderViewObserverQt_FetchDocumentInnerText(
- web_contents()->GetRenderViewHost()->GetRoutingID(), requestId));
-}
-
-bool RenderViewObserverHostQt::OnMessageReceived(const IPC::Message &message)
-{
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(RenderViewObserverHostQt, message)
- IPC_MESSAGE_HANDLER(RenderViewObserverHostQt_DidFetchDocumentMarkup,
- onDidFetchDocumentMarkup)
- IPC_MESSAGE_HANDLER(RenderViewObserverHostQt_DidFetchDocumentInnerText,
- onDidFetchDocumentInnerText)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
-void RenderViewObserverHostQt::onDidFetchDocumentMarkup(quint64 requestId, const base::string16 &markup)
-{
- m_adapterClient->didFetchDocumentMarkup(requestId, toQt(markup));
-}
-
-void RenderViewObserverHostQt::onDidFetchDocumentInnerText(quint64 requestId, const base::string16 &innerText)
-{
- m_adapterClient->didFetchDocumentInnerText(requestId, toQt(innerText));
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/renderer_host/render_view_observer_host_qt.h b/src/core/renderer_host/render_view_observer_host_qt.h
deleted file mode 100644
index 8590ecbc5..000000000
--- a/src/core/renderer_host/render_view_observer_host_qt.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RENDER_VIEW_OBSERVER_HOST_QT_H
-#define RENDER_VIEW_OBSERVER_HOST_QT_H
-
-#include "content/public/browser/web_contents_observer.h"
-
-#include <QtGlobal>
-
-namespace content {
-class WebContents;
-}
-
-namespace QtWebEngineCore {
-
-class WebContentsAdapterClient;
-
-class RenderViewObserverHostQt : public content::WebContentsObserver
-{
-public:
- RenderViewObserverHostQt(content::WebContents *, WebContentsAdapterClient *adapterClient);
- void fetchDocumentMarkup(quint64 requestId);
- void fetchDocumentInnerText(quint64 requestId);
-
-private:
- bool OnMessageReceived(const IPC::Message &message) override;
- void onDidFetchDocumentMarkup(quint64 requestId, const base::string16 &markup);
- void onDidFetchDocumentInnerText(quint64 requestId, const base::string16 &innerText);
-
- WebContentsAdapterClient *m_adapterClient;
-};
-
-} // namespace QtWebEngineCore
-
-#endif // RENDER_VIEW_OBSERVER_HOST_QT_H
diff --git a/src/core/renderer_host/user_resource_controller_host.cpp b/src/core/renderer_host/user_resource_controller_host.cpp
index 6b9bb63fe..f2a00fc72 100644
--- a/src/core/renderer_host/user_resource_controller_host.cpp
+++ b/src/core/renderer_host/user_resource_controller_host.cpp
@@ -1,53 +1,20 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "user_resource_controller_host.h"
-#include "common/qt_messages.h"
#include "type_conversion.h"
#include "web_contents_adapter.h"
+
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_observer.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
+#include "ipc/ipc_channel_proxy.h"
+#include "qtwebengine/userscript/userscript.mojom.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
namespace QtWebEngineCore {
@@ -59,6 +26,7 @@ public:
// WebContentsObserver overrides:
void RenderFrameCreated(content::RenderFrameHost *renderFrameHost) override;
void RenderFrameHostChanged(content::RenderFrameHost *oldHost, content::RenderFrameHost *newHost) override;
+ void RenderFrameDeleted(content::RenderFrameHost *render_frame_host) override;
void WebContentsDestroyed() override;
private:
@@ -75,16 +43,25 @@ UserResourceControllerHost::WebContentsObserverHelper::WebContentsObserverHelper
void UserResourceControllerHost::WebContentsObserverHelper::RenderFrameCreated(content::RenderFrameHost *renderFrameHost)
{
content::WebContents *contents = web_contents();
+ auto &remote = m_controllerHost->GetUserResourceControllerRenderFrame(renderFrameHost);
const QList<UserScript> scripts = m_controllerHost->m_perContentsScripts.value(contents);
for (const UserScript &script : scripts)
- renderFrameHost->Send(new RenderFrameObserverHelper_AddScript(renderFrameHost->GetRoutingID(), script.data()));
+ remote->AddScript(script.data());
}
void UserResourceControllerHost::WebContentsObserverHelper::RenderFrameHostChanged(content::RenderFrameHost *oldHost,
content::RenderFrameHost *newHost)
{
- if (oldHost)
- oldHost->Send(new RenderFrameObserverHelper_ClearScripts(oldHost->GetRoutingID()));
+ if (oldHost) {
+ auto &remote = m_controllerHost->GetUserResourceControllerRenderFrame(oldHost);
+ remote->ClearScripts();
+ }
+}
+
+void UserResourceControllerHost::WebContentsObserverHelper::RenderFrameDeleted(
+ content::RenderFrameHost *render_frame_host)
+{
+ m_controllerHost->m_renderFrames.erase(render_frame_host);
}
void UserResourceControllerHost::WebContentsObserverHelper::WebContentsDestroyed()
@@ -111,20 +88,19 @@ UserResourceControllerHost::RenderProcessObserverHelper::RenderProcessObserverHe
void UserResourceControllerHost::RenderProcessObserverHelper::RenderProcessHostDestroyed(content::RenderProcessHost *renderer)
{
Q_ASSERT(m_controllerHost);
+ delete m_controllerHost->m_observedProcesses[renderer];
m_controllerHost->m_observedProcesses.remove(renderer);
}
void UserResourceControllerHost::addUserScript(const UserScript &script, WebContentsAdapter *adapter)
{
- if (script.isNull())
- return;
// Global scripts should be dispatched to all our render processes.
const bool isProfileWideScript = !adapter;
if (isProfileWideScript) {
if (!m_profileWideScripts.contains(script)) {
m_profileWideScripts.append(script);
- for (content::RenderProcessHost *renderer : qAsConst(m_observedProcesses))
- renderer->Send(new UserResourceController_AddScript(script.data()));
+ for (auto controller : m_observedProcesses.values())
+ (*controller)->AddScript(script.data());
}
} else {
content::WebContents *contents = adapter->webContents();
@@ -141,24 +117,20 @@ void UserResourceControllerHost::addUserScript(const UserScript &script, WebCont
m_perContentsScripts.insert(contents, currentScripts);
}
}
- contents->GetRenderViewHost()->Send(
- new RenderFrameObserverHelper_AddScript(
- contents->GetRenderViewHost()->GetMainFrame()->GetRoutingID(),
- script.data()));
+ GetUserResourceControllerRenderFrame(contents->GetPrimaryMainFrame())
+ ->AddScript(script.data());
}
}
bool UserResourceControllerHost::removeUserScript(const UserScript &script, WebContentsAdapter *adapter)
{
- if (script.isNull())
- return false;
const bool isProfileWideScript = !adapter;
if (isProfileWideScript) {
QList<UserScript>::iterator it = std::find(m_profileWideScripts.begin(), m_profileWideScripts.end(), script);
if (it == m_profileWideScripts.end())
return false;
- for (content::RenderProcessHost *renderer : qAsConst(m_observedProcesses))
- renderer->Send(new UserResourceController_RemoveScript((*it).data()));
+ for (auto controller : m_observedProcesses.values())
+ (*controller)->RemoveScript((*it).data());
m_profileWideScripts.erase(it);
} else {
content::WebContents *contents = adapter->webContents();
@@ -168,8 +140,8 @@ bool UserResourceControllerHost::removeUserScript(const UserScript &script, WebC
QList<UserScript>::iterator it = std::find(list.begin(), list.end(), script);
if (it == list.end())
return false;
- contents->GetRenderViewHost()->Send(
- new RenderFrameObserverHelper_RemoveScript(contents->GetMainFrame()->GetRoutingID(), (*it).data()));
+ GetUserResourceControllerRenderFrame(contents->GetPrimaryMainFrame())
+ ->RemoveScript((*it).data());
list.erase(it);
}
return true;
@@ -180,13 +152,15 @@ void UserResourceControllerHost::clearAllScripts(WebContentsAdapter *adapter)
const bool isProfileWideScript = !adapter;
if (isProfileWideScript) {
m_profileWideScripts.clear();
- for (content::RenderProcessHost *renderer : qAsConst(m_observedProcesses))
- renderer->Send(new UserResourceController_ClearScripts);
+ for (auto controller : m_observedProcesses.values())
+ (*controller)->ClearScripts();
} else {
content::WebContents *contents = adapter->webContents();
m_perContentsScripts.remove(contents);
- contents->GetRenderViewHost()->Send(
- new RenderFrameObserverHelper_ClearScripts(contents->GetMainFrame()->GetRoutingID()));
+ mojo::AssociatedRemote<qtwebengine::mojom::UserResourceControllerRenderFrame>
+ userResourceController;
+ GetUserResourceControllerRenderFrame(contents->GetPrimaryMainFrame())
+ ->ClearScripts();
}
}
@@ -201,15 +175,18 @@ void UserResourceControllerHost::reserve(WebContentsAdapter *adapter, int count)
void UserResourceControllerHost::renderProcessStartedWithHost(content::RenderProcessHost *renderer)
{
- if (m_observedProcesses.contains(renderer))
+ if (m_observedProcesses.keys().contains(renderer))
return;
if (m_renderProcessObserver.isNull())
m_renderProcessObserver.reset(new RenderProcessObserverHelper(this));
renderer->AddObserver(m_renderProcessObserver.data());
- m_observedProcesses.insert(renderer);
- for (const UserScript &script : qAsConst(m_profileWideScripts))
- renderer->Send(new UserResourceController_AddScript(script.data()));
+ auto userResourceController = new UserResourceControllerRemote;
+ renderer->GetChannel()->GetRemoteAssociatedInterface(userResourceController);
+ m_observedProcesses.insert(renderer, userResourceController);
+ for (const UserScript &script : std::as_const(m_profileWideScripts)) {
+ (*userResourceController)->AddScript(script.data());
+ }
}
void UserResourceControllerHost::webContentsDestroyed(content::WebContents *contents)
@@ -223,8 +200,26 @@ UserResourceControllerHost::UserResourceControllerHost()
UserResourceControllerHost::~UserResourceControllerHost()
{
- for (content::RenderProcessHost *renderer : qAsConst(m_observedProcesses))
+ for (content::RenderProcessHost *renderer : m_observedProcesses.keys()) {
renderer->RemoveObserver(m_renderProcessObserver.data());
+ delete m_observedProcesses[renderer];
+ }
+}
+
+const UserResourceControllerRenderFrameRemote &
+UserResourceControllerHost::GetUserResourceControllerRenderFrame(content::RenderFrameHost *rfh)
+{
+ auto it = m_renderFrames.find(rfh);
+ if (it == m_renderFrames.end()) {
+ UserResourceControllerRenderFrameRemote remote;
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(remote.BindNewEndpointAndPassReceiver());
+ it = m_renderFrames.insert(std::make_pair(rfh, std::move(remote))).first;
+ } else if (it->second.is_bound() && !it->second.is_connected()) {
+ it->second.reset();
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(&it->second);
+ }
+
+ return it->second;
}
} // namespace
diff --git a/src/core/renderer_host/user_resource_controller_host.h b/src/core/renderer_host/user_resource_controller_host.h
index 7b89cb893..eb4404879 100644
--- a/src/core/renderer_host/user_resource_controller_host.h
+++ b/src/core/renderer_host/user_resource_controller_host.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,20 +17,37 @@
#include "qtwebenginecoreglobal_p.h"
-#include <QtCore/QSet>
+#include <QtCore/QHash>
#include <QtCore/QScopedPointer>
+#include <map>
#include "user_script.h"
namespace content {
class RenderProcessHost;
class WebContents;
+class RenderFrameHost;
+}
+
+namespace mojo {
+template <typename Type>
+class AssociatedRemote;
+}
+
+namespace qtwebengine {
+namespace mojom {
+class UserResourceController;
+class UserResourceControllerRenderFrame;
+}
}
namespace QtWebEngineCore {
+class UserScript;
+using UserResourceControllerRemote = mojo::AssociatedRemote<qtwebengine::mojom::UserResourceController>;
+using UserResourceControllerRenderFrameRemote = mojo::AssociatedRemote<qtwebengine::mojom::UserResourceControllerRenderFrame>;
class WebContentsAdapter;
-class Q_WEBENGINECORE_PRIVATE_EXPORT UserResourceControllerHost
+class Q_WEBENGINECORE_EXPORT UserResourceControllerHost
{
public:
@@ -86,12 +67,15 @@ private:
class RenderProcessObserverHelper;
void webContentsDestroyed(content::WebContents *);
+ const UserResourceControllerRenderFrameRemote &
+ GetUserResourceControllerRenderFrame(content::RenderFrameHost *rfh);
QList<UserScript> m_profileWideScripts;
typedef QHash<content::WebContents *, QList<UserScript>> ContentsScriptsMap;
ContentsScriptsMap m_perContentsScripts;
- QSet<content::RenderProcessHost *> m_observedProcesses;
+ QHash<content::RenderProcessHost *, UserResourceControllerRemote *> m_observedProcesses;
QScopedPointer<RenderProcessObserverHelper> m_renderProcessObserver;
+ std::map<content::RenderFrameHost *, UserResourceControllerRenderFrameRemote> m_renderFrames;
};
} // namespace
diff --git a/src/core/renderer_host/web_channel_ipc_transport_host.cpp b/src/core/renderer_host/web_channel_ipc_transport_host.cpp
index 9ed3749ad..0824ed56d 100644
--- a/src/core/renderer_host/web_channel_ipc_transport_host.cpp
+++ b/src/core/renderer_host/web_channel_ipc_transport_host.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "web_channel_ipc_transport_host.h"
@@ -46,7 +10,6 @@
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "qtwebengine/browser/qtwebchannel.mojom.h"
-#include "common/qt_messages.h"
#include <QJsonDocument>
#include <QJsonObject>
@@ -61,23 +24,15 @@ inline QDebug operator<<(QDebug stream, content::RenderFrameHost *frame)
return stream << "frame " << frame->GetRoutingID() << " in process " << frame->GetProcess()->GetID();
}
-template<class T>
-inline QDebug operator<<(QDebug stream, const base::Optional<T> &opt)
-{
- if (opt)
- return stream << *opt;
- else
- return stream << "nullopt";
-}
-
WebChannelIPCTransportHost::WebChannelIPCTransportHost(content::WebContents *contents, uint worldId, QObject *parent)
: QWebChannelAbstractTransport(parent)
, content::WebContentsObserver(contents)
, m_worldId(worldId)
, m_receiver(contents, this)
{
- for (content::RenderFrameHost *frame : contents->GetAllFrames())
- setWorldId(frame, worldId);
+ contents->ForEachRenderFrameHost([this, worldId](content::RenderFrameHost *frame) {
+ setWorldId(frame, worldId);
+ });
}
WebChannelIPCTransportHost::~WebChannelIPCTransportHost()
@@ -93,21 +48,20 @@ uint WebChannelIPCTransportHost::worldId() const
void WebChannelIPCTransportHost::sendMessage(const QJsonObject &message)
{
QJsonDocument doc(message);
- int size = 0;
- const char *rawData = doc.rawData(&size);
- content::RenderFrameHost *frame = web_contents()->GetMainFrame();
- mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> webChannelTransport;
- frame->GetRemoteAssociatedInterfaces()->GetInterface(&webChannelTransport);
+ QByteArray json = doc.toJson(QJsonDocument::Compact);
+ content::RenderFrameHost *frame = web_contents()->GetPrimaryMainFrame();
qCDebug(log).nospace() << "sending webchannel message to " << frame << ": " << doc;
- webChannelTransport->DispatchWebChannelMessage(std::vector<uint8_t>(rawData, rawData + size), m_worldId);
+ GetWebChannelIPCTransportRemote(frame)->DispatchWebChannelMessage(
+ std::vector<uint8_t>(json.begin(), json.end()), m_worldId);
}
void WebChannelIPCTransportHost::setWorldId(uint32_t worldId)
{
if (m_worldId == worldId)
return;
- for (content::RenderFrameHost *frame : web_contents()->GetAllFrames())
- setWorldId(frame, worldId);
+ web_contents()->ForEachRenderFrameHost([this, worldId](content::RenderFrameHost *frame) {
+ setWorldId(frame, worldId);
+ });
m_worldId = worldId;
}
@@ -116,31 +70,28 @@ void WebChannelIPCTransportHost::setWorldId(content::RenderFrameHost *frame, uin
if (!frame->IsRenderFrameLive())
return;
qCDebug(log).nospace() << "sending setWorldId(" << worldId << ") message to " << frame;
- mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> webChannelTransport;
- frame->GetRemoteAssociatedInterfaces()->GetInterface(&webChannelTransport);
- webChannelTransport->SetWorldId(worldId);
+ GetWebChannelIPCTransportRemote(frame)->SetWorldId(worldId);
}
void WebChannelIPCTransportHost::resetWorldId()
{
- for (content::RenderFrameHost *frame : web_contents()->GetAllFrames()) {
+ web_contents()->ForEachRenderFrameHost([this] (content::RenderFrameHost *frame) {
if (!frame->IsRenderFrameLive())
return;
- mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> webChannelTransport;
- frame->GetRemoteAssociatedInterfaces()->GetInterface(&webChannelTransport);
- webChannelTransport->ResetWorldId();
- }
+ GetWebChannelIPCTransportRemote(frame)->ResetWorldId();
+ });
}
-void WebChannelIPCTransportHost::DispatchWebChannelMessage(const std::vector<uint8_t> &binaryJson)
+void WebChannelIPCTransportHost::DispatchWebChannelMessage(const std::vector<uint8_t> &json)
{
- content::RenderFrameHost *frame = web_contents()->GetMainFrame();
+ content::RenderFrameHost *frame = web_contents()->GetPrimaryMainFrame();
if (m_receiver.GetCurrentTargetFrame() != frame) {
return;
}
- QJsonDocument doc = QJsonDocument::fromRawData(reinterpret_cast<const char *>(binaryJson.data()), binaryJson.size());
+ QJsonDocument doc = QJsonDocument::fromJson(
+ QByteArray(reinterpret_cast<const char *>(json.data()), json.size()));
if (!doc.isObject()) {
qCCritical(log).nospace() << "received invalid webchannel message from " << frame;
@@ -156,4 +107,33 @@ void WebChannelIPCTransportHost::RenderFrameCreated(content::RenderFrameHost *fr
setWorldId(frame, m_worldId);
}
+void WebChannelIPCTransportHost::RenderFrameDeleted(content::RenderFrameHost *rfh)
+{
+ m_renderFrames.erase(rfh);
+}
+
+void WebChannelIPCTransportHost::BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebchannel::mojom::WebChannelTransportHost> receiver,
+ content::RenderFrameHost *rfh)
+{
+ m_receiver.Bind(rfh, std::move(receiver));
+}
+
+
+const mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> &
+WebChannelIPCTransportHost::GetWebChannelIPCTransportRemote(content::RenderFrameHost *rfh)
+{
+ auto it = m_renderFrames.find(rfh);
+ if (it == m_renderFrames.end()) {
+ mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> remote;
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(remote.BindNewEndpointAndPassReceiver());
+ it = m_renderFrames.insert(std::make_pair(rfh, std::move(remote))).first;
+ } else if (it->second.is_bound() && !it->second.is_connected()) {
+ it->second.reset();
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(&it->second);
+ }
+
+ return it->second;
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/renderer_host/web_channel_ipc_transport_host.h b/src/core/renderer_host/web_channel_ipc_transport_host.h
index a1575355a..9e003c222 100644
--- a/src/core/renderer_host/web_channel_ipc_transport_host.h
+++ b/src/core/renderer_host/web_channel_ipc_transport_host.h
@@ -1,52 +1,17 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_CHANNEL_IPC_TRANSPORT_H
#define WEB_CHANNEL_IPC_TRANSPORT_H
#include "qtwebenginecoreglobal.h"
+#include "content/public/browser/render_frame_host_receiver_set.h"
#include "content/public/browser/web_contents_observer.h"
-#include "content/public/browser/web_contents_receiver_set.h"
#include "qtwebengine/browser/qtwebchannel.mojom.h"
#include <QWebChannelAbstractTransport>
+#include <map>
QT_FORWARD_DECLARE_CLASS(QString)
@@ -67,21 +32,31 @@ public:
// QWebChannelAbstractTransport
void sendMessage(const QJsonObject &message) override;
+ void BindReceiver(
+ mojo::PendingAssociatedReceiver<qtwebchannel::mojom::WebChannelTransportHost> receiver,
+ content::RenderFrameHost *rfh);
+
private:
void setWorldId(content::RenderFrameHost *frame, uint32_t worldId);
void resetWorldId();
- void onWebChannelMessage(const std::vector<char> &message);
+
+ const mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender> &
+ GetWebChannelIPCTransportRemote(content::RenderFrameHost *rfh);
// WebContentsObserver
void RenderFrameCreated(content::RenderFrameHost *frame) override;
+ void RenderFrameDeleted(content::RenderFrameHost *render_frame_host) override;
// qtwebchannel::mojom::WebChannelTransportHost
- void DispatchWebChannelMessage(const std::vector<uint8_t> &binaryJson) override;
+ void DispatchWebChannelMessage(const std::vector<uint8_t> &json) override;
// Empty only during construction/destruction. Synchronized to all the
// WebChannelIPCTransports/RenderFrames in the observed WebContents.
uint32_t m_worldId;
- content::WebContentsFrameReceiverSet<qtwebchannel::mojom::WebChannelTransportHost> m_receiver;
+ content::RenderFrameHostReceiverSet<qtwebchannel::mojom::WebChannelTransportHost> m_receiver;
+ std::map<content::RenderFrameHost *,
+ mojo::AssociatedRemote<qtwebchannel::mojom::WebChannelTransportRender>>
+ m_renderFrames;
};
} // namespace
diff --git a/src/core/renderer_host/web_engine_page_host.cpp b/src/core/renderer_host/web_engine_page_host.cpp
new file mode 100644
index 000000000..ea9b363ea
--- /dev/null
+++ b/src/core/renderer_host/web_engine_page_host.cpp
@@ -0,0 +1,76 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "web_engine_page_host.h"
+
+#include "qtwebengine/browser/qtwebenginepage.mojom.h"
+#include "content/public/browser/web_contents.h"
+
+#include "render_widget_host_view_qt.h"
+#include "type_conversion.h"
+#include "web_contents_adapter_client.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+
+namespace QtWebEngineCore {
+
+WebEnginePageHost::WebEnginePageHost(content::WebContents *webContents,
+ WebContentsAdapterClient *adapterClient)
+ : content::WebContentsObserver(webContents), m_adapterClient(adapterClient)
+{
+}
+
+void WebEnginePageHost::FetchDocumentMarkup(uint64_t requestId)
+{
+ auto &remote = GetWebEnginePageRenderFrame(web_contents()->GetPrimaryMainFrame());
+ remote->FetchDocumentMarkup(
+ requestId,
+ base::BindOnce(&WebEnginePageHost::OnDidFetchDocumentMarkup, base::Unretained(this)));
+}
+
+void WebEnginePageHost::FetchDocumentInnerText(uint64_t requestId)
+{
+ auto &remote = GetWebEnginePageRenderFrame(web_contents()->GetPrimaryMainFrame());
+ remote->FetchDocumentInnerText(requestId,
+ base::BindOnce(&WebEnginePageHost::OnDidFetchDocumentInnerText,
+ base::Unretained(this)));
+}
+
+void WebEnginePageHost::OnDidFetchDocumentMarkup(uint64_t requestId, const std::string &markup)
+{
+ m_adapterClient->didFetchDocumentMarkup(requestId, toQt(markup));
+}
+
+void WebEnginePageHost::OnDidFetchDocumentInnerText(uint64_t requestId,
+ const std::string &innerText)
+{
+ m_adapterClient->didFetchDocumentInnerText(requestId, toQt(innerText));
+}
+
+void WebEnginePageHost::RenderFrameDeleted(content::RenderFrameHost *render_frame)
+{
+ m_renderFrames.erase(render_frame);
+}
+
+void WebEnginePageHost::SetBackgroundColor(uint32_t color)
+{
+ auto &remote = GetWebEnginePageRenderFrame(web_contents()->GetPrimaryMainFrame());
+ remote->SetBackgroundColor(color);
+}
+
+const WebEnginePageRenderFrameRemote &
+WebEnginePageHost::GetWebEnginePageRenderFrame(content::RenderFrameHost *rfh)
+{
+ auto it = m_renderFrames.find(rfh);
+ if (it == m_renderFrames.end()) {
+ WebEnginePageRenderFrameRemote remote;
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(remote.BindNewEndpointAndPassReceiver());
+ it = m_renderFrames.insert(std::make_pair(rfh, std::move(remote))).first;
+ } else if (it->second.is_bound() && !it->second.is_connected()) {
+ it->second.reset();
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(&it->second);
+ }
+
+ return it->second;
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/renderer_host/web_engine_page_host.h b/src/core/renderer_host/web_engine_page_host.h
new file mode 100644
index 000000000..20b9145b2
--- /dev/null
+++ b/src/core/renderer_host/web_engine_page_host.h
@@ -0,0 +1,54 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef WEB_ENGINE_PAGE_HOST_H
+#define WEB_ENGINE_PAGE_HOST_H
+
+#include "content/public/browser/web_contents_observer.h"
+
+#include <QtGlobal>
+
+namespace content {
+class WebContents;
+}
+
+namespace mojo {
+template<typename Type>
+class AssociatedRemote;
+}
+
+namespace qtwebenginepage {
+namespace mojom {
+class WebEnginePageRenderFrame;
+}
+}
+
+namespace QtWebEngineCore {
+
+using WebEnginePageRenderFrameRemote = mojo::AssociatedRemote<qtwebenginepage::mojom::WebEnginePageRenderFrame>;
+
+class WebContentsAdapterClient;
+
+class WebEnginePageHost : public content::WebContentsObserver
+{
+public:
+ WebEnginePageHost(content::WebContents *, WebContentsAdapterClient *adapterClient);
+ void FetchDocumentMarkup(uint64_t requestId);
+ void FetchDocumentInnerText(uint64_t requestId);
+ void RenderFrameDeleted(content::RenderFrameHost *render_frame) override;
+ void SetBackgroundColor(uint32_t color);
+
+private:
+ void OnDidFetchDocumentMarkup(uint64_t requestId, const std::string &markup);
+ void OnDidFetchDocumentInnerText(uint64_t requestId, const std::string &innerText);
+ const WebEnginePageRenderFrameRemote &
+ GetWebEnginePageRenderFrame(content::RenderFrameHost *rfh);
+
+private:
+ WebContentsAdapterClient *m_adapterClient;
+ std::map<content::RenderFrameHost *, WebEnginePageRenderFrameRemote> m_renderFrames;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // WEB_ENGINE_PAGE_HOST_H
diff --git a/src/core/request_controller.h b/src/core/request_controller.h
index ffcf9edac..8008b2edb 100644
--- a/src/core/request_controller.h
+++ b/src/core/request_controller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef REQUEST_CONTROLLER_H
#define REQUEST_CONTROLLER_H
diff --git a/src/core/resource_bundle_qt.cpp b/src/core/resource_bundle_qt.cpp
index 61b0f3021..693d1291f 100644
--- a/src/core/resource_bundle_qt.cpp
+++ b/src/core/resource_bundle_qt.cpp
@@ -1,46 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "base/command_line.h"
+#include "base/files/file_util.h"
+#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
+#include "base/notreached.h"
#include "content/public/common/content_switches.h"
-#include "services/service_manager/sandbox/switches.h"
+#include "sandbox/policy/switches.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/data_pack.h"
#include "ui/base/resource/resource_bundle.h"
@@ -48,7 +15,7 @@
#include "web_engine_library_info.h"
-#if defined(OS_LINUX)
+#if BUILDFLAG(IS_LINUX)
#include "base/posix/global_descriptors.h"
#include "global_descriptors_qt.h"
#endif
@@ -58,10 +25,10 @@ namespace ui {
void ResourceBundle::LoadCommonResources()
{
// We repacked the resources we need and installed them. now let chromium mmap that file.
- AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_PAK), SCALE_FACTOR_NONE);
- AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_100P_PAK), SCALE_FACTOR_100P);
- AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_200P_PAK), SCALE_FACTOR_200P);
- AddOptionalDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_DEVTOOLS_PAK), SCALE_FACTOR_NONE);
+ AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_100P_PAK), ui::k100Percent);
+ AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_200P_PAK), ui::k200Percent);
+ AddDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_PAK), ui::kScaleFactorNone);
+ AddOptionalDataPackFromPath(WebEngineLibraryInfo::getPath(QT_RESOURCES_DEVTOOLS_PAK), ui::kScaleFactorNone);
}
gfx::Image& ResourceBundle::GetNativeImageNamed(int resource_id)
@@ -72,10 +39,10 @@ gfx::Image& ResourceBundle::GetNativeImageNamed(int resource_id)
// static
bool ResourceBundle::LocaleDataPakExists(const std::string& locale)
{
-#if defined(OS_LINUX)
+#if BUILDFLAG(IS_LINUX)
base::CommandLine *parsed_command_line = base::CommandLine::ForCurrentProcess();
std::string process_type = parsed_command_line->GetSwitchValueASCII(switches::kProcessType);
- bool no_sandbox = parsed_command_line->HasSwitch(service_manager::switches::kNoSandbox);
+ bool no_sandbox = parsed_command_line->HasSwitch(sandbox::policy::switches::kNoSandbox);
if (process_type == switches::kRendererProcess && !no_sandbox) {
// The Renderer Process is sandboxed thus only one locale is available in it.
// The particular one is passed by the --lang command line option.
@@ -87,21 +54,22 @@ bool ResourceBundle::LocaleDataPakExists(const std::string& locale)
}
#endif
- return !GetLocaleFilePath(locale).empty();
+ const auto path = GetLocaleFilePath(locale);
+ return !path.empty() && base::PathExists(path);
}
-std::string ResourceBundle::LoadLocaleResources(const std::string& pref_locale)
+std::string ResourceBundle::LoadLocaleResources(const std::string &pref_locale, bool /*crash_on_failure*/)
{
DCHECK(!locale_resources_data_.get()) << "locale.pak already loaded";
- std::string app_locale = l10n_util::GetApplicationLocale(pref_locale);
+ std::string app_locale = l10n_util::GetApplicationLocale(pref_locale, false /* set_icu_locale */);
-#if defined(OS_LINUX)
+#if BUILDFLAG(IS_LINUX)
int locale_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(kWebEngineLocale);
if (locale_fd > -1) {
- std::unique_ptr<DataPack> data_pack(new DataPack(SCALE_FACTOR_100P));
+ std::unique_ptr<DataPack> data_pack(new DataPack(ui::k100Percent));
data_pack->LoadFromFile(base::File(locale_fd));
- locale_resources_data_.reset(data_pack.release());
+ locale_resources_data_ = std::move(data_pack);
return app_locale;
}
#endif
@@ -116,7 +84,7 @@ std::string ResourceBundle::LoadLocaleResources(const std::string& pref_locale)
return std::string();
}
- std::unique_ptr<DataPack> data_pack(new DataPack(SCALE_FACTOR_100P));
+ std::unique_ptr<DataPack> data_pack(new DataPack(ui::k100Percent));
if (!data_pack->LoadFromPath(locale_file_path)) {
UMA_HISTOGRAM_ENUMERATION("ResourceBundle.LoadLocaleResourcesError",
logging::GetLastSystemErrorCode(), 16000);
@@ -125,7 +93,7 @@ std::string ResourceBundle::LoadLocaleResources(const std::string& pref_locale)
return std::string();
}
- locale_resources_data_.reset(data_pack.release());
+ locale_resources_data_ = std::move(data_pack);
return app_locale;
}
diff --git a/src/core/resource_context_qt.cpp b/src/core/resource_context_qt.cpp
deleted file mode 100644
index 79c105956..000000000
--- a/src/core/resource_context_qt.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "resource_context_qt.h"
-
-namespace QtWebEngineCore {
-
-ResourceContextQt::ResourceContextQt(ProfileIODataQt *io_data)
- : m_io_data(io_data)
-{
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/resource_context_qt.h b/src/core/resource_context_qt.h
deleted file mode 100644
index 4107e7c24..000000000
--- a/src/core/resource_context_qt.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RESOURCE_CONTEXT_QT_H
-#define RESOURCE_CONTEXT_QT_H
-
-#include "content/public/browser/resource_context.h"
-
-#include "extensions/buildflags/buildflags.h"
-
-namespace net {
-class URLRequestContext;
-class URLRequestContextGetter;
-}
-
-#if BUILDFLAG(ENABLE_EXTENSIONS)
-namespace extensions {
-class ExtensionSystemQt;
-}
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
-class GURL;
-
-namespace QtWebEngineCore {
-
-class ProfileIODataQt;
-
-class ResourceContextQt : public content::ResourceContext
-{
-public:
- ResourceContextQt(ProfileIODataQt *io_data);
-private:
- friend class ProfileIODataQt;
- ProfileIODataQt* m_io_data;
- DISALLOW_COPY_AND_ASSIGN(ResourceContextQt);
-};
-
-} // namespace QtWebEngineCore
-
-#endif // RESOURCE_CONTEXT_QT_H
diff --git a/src/core/sandbox_win.cpp b/src/core/sandbox_win.cpp
new file mode 100644
index 000000000..bc70bced7
--- /dev/null
+++ b/src/core/sandbox_win.cpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qtwebenginecoreglobal_p.h"
+#include "sandbox/win/src/process_mitigations.h"
+#include "sandbox/win/src/sandbox_factory.h"
+
+#ifndef NDEBUG
+#include "base/command_line.h"
+#include "base/logging.h"
+#endif
+
+namespace QtWebEngineSandbox {
+// A duplicate of the function by same name in sandbox_helper_win.cc
+static void InitializeSandboxInfo(sandbox::SandboxInterfaceInfo *info)
+{
+ info->broker_services = sandbox::SandboxFactory::GetBrokerServices();
+ if (!info->broker_services) {
+ info->target_services = sandbox::SandboxFactory::GetTargetServices();
+ } else {
+ // Ensure the proper mitigations are enforced for the browser process.
+ info->broker_services->RatchetDownSecurityMitigations(
+ sandbox::MITIGATION_DEP | sandbox::MITIGATION_DEP_NO_ATL_THUNK |
+ sandbox::MITIGATION_HARDEN_TOKEN_IL_POLICY);
+ // Note: these mitigations are "post-startup". Some mitigations that need
+ // to be enabled sooner (e.g. MITIGATION_EXTENSION_POINT_DISABLE) are done
+ // so in Chrome_ELF.
+ }
+}
+
+// Initializes the staticlib copy of //base and //sandbox used for Windows sandboxing
+void initializeStaticCopy(int argc, const char **argv)
+{
+#ifndef NDEBUG
+ // Initialize //base for debugging
+ base::CommandLine::Init(argc, argv);
+ logging::LoggingSettings settings;
+ settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
+ logging::InitLogging(settings);
+#endif
+ sandbox::SandboxInterfaceInfo *info = new sandbox::SandboxInterfaceInfo();
+ memset(info, 0, sizeof(sandbox::SandboxInterfaceInfo));
+ InitializeSandboxInfo(info);
+ QtWebEngineSandbox::staticSandboxInterfaceInfo(info);
+}
+} // namespace QtWebEngineSandbox
diff --git a/src/core/select_file_dialog_factory_qt.cpp b/src/core/select_file_dialog_factory_qt.cpp
new file mode 100644
index 000000000..1f897a805
--- /dev/null
+++ b/src/core/select_file_dialog_factory_qt.cpp
@@ -0,0 +1,149 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "select_file_dialog_factory_qt.h"
+
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "file_picker_controller.h"
+#include "type_conversion.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
+#include "web_contents_adapter_client.h"
+#include "web_contents_view_qt.h"
+
+#include <QSharedPointer>
+#include <QTimer>
+
+namespace QtWebEngineCore {
+
+SelectFilePolicyQt::SelectFilePolicyQt(content::WebContents *source_contents)
+ : m_webContents(source_contents)
+{
+}
+
+SelectFilePolicyQt::~SelectFilePolicyQt() { }
+
+bool SelectFilePolicyQt::CanOpenSelectFileDialog()
+{
+ return true;
+}
+
+void SelectFilePolicyQt::SelectFileDenied() { }
+
+content::WebContents *SelectFilePolicyQt::webContents()
+{
+ return m_webContents;
+}
+
+static FilePickerController::FileChooserMode toFileChooserMode(ui::SelectFileDialog::Type type)
+{
+ switch (type) {
+ case ui::SelectFileDialog::Type::SELECT_FOLDER:
+ case ui::SelectFileDialog::Type::SELECT_UPLOAD_FOLDER:
+ case ui::SelectFileDialog::Type::SELECT_EXISTING_FOLDER:
+ return FilePickerController::FileChooserMode::UploadFolder;
+ case ui::SelectFileDialog::Type::SELECT_SAVEAS_FILE:
+ return FilePickerController::FileChooserMode::Save;
+ case ui::SelectFileDialog::Type::SELECT_OPEN_FILE:
+ return FilePickerController::FileChooserMode::Open;
+ case ui::SelectFileDialog::Type::SELECT_OPEN_MULTI_FILE:
+ case ui::SelectFileDialog::Type::SELECT_NONE:
+ default:
+ return FilePickerController::FileChooserMode::OpenMultiple;
+ break;
+ }
+}
+
+class SelectFileDialogQt : public ui::SelectFileDialog
+{
+public:
+ SelectFileDialogQt(Listener *, std::unique_ptr<ui::SelectFilePolicy>,
+ WebContentsAdapterClient *);
+
+ // ui::SelectFileDialog implementation:
+ bool IsRunning(gfx::NativeWindow) const override;
+ void ListenerDestroyed() override;
+ void SelectFileImpl(Type type, const std::u16string &title, const base::FilePath &default_path,
+ const FileTypeInfo *file_types, int file_type_index,
+ const base::FilePath::StringType &default_extension,
+ gfx::NativeWindow owning_window, void *params, const GURL *) override;
+
+ bool HasMultipleFileTypeChoicesImpl() override;
+
+private:
+ WebContentsAdapterClient *m_client;
+ QSharedPointer<FilePickerController> m_filePickerController;
+};
+
+SelectFileDialogQt::SelectFileDialogQt(Listener *listener,
+ std::unique_ptr<ui::SelectFilePolicy> policy,
+ WebContentsAdapterClient *client)
+ : SelectFileDialog(listener, std::move(policy)), m_client(client)
+{
+}
+
+bool SelectFileDialogQt::IsRunning(gfx::NativeWindow) const
+{
+ return listener_;
+}
+
+void SelectFileDialogQt::ListenerDestroyed()
+{
+ listener_ = nullptr;
+}
+
+bool SelectFileDialogQt::HasMultipleFileTypeChoicesImpl()
+{
+ return false;
+}
+
+extern FilePickerController *createFilePickerController(FilePickerController::FileChooserMode mode,
+ ui::SelectFileDialog::Listener *listener,
+ const QString &defaultFileName,
+ const QStringList &acceptedMimeTypes,
+ QObject *parent = nullptr);
+
+void SelectFileDialogQt::SelectFileImpl(Type type, const std::u16string &title,
+ const base::FilePath &default_path,
+ const FileTypeInfo *file_types, int file_type_index,
+ const base::FilePath::StringType &default_extension,
+ gfx::NativeWindow owning_window, void *params, const GURL *caller)
+{
+ Q_UNUSED(title);
+ Q_UNUSED(file_type_index);
+ Q_UNUSED(default_extension);
+ Q_UNUSED(owning_window);
+ Q_UNUSED(params);
+ Q_UNUSED(caller);
+
+ QStringList acceptedSuffixes;
+ if (file_types) {
+ for (const auto &type : file_types->extensions) {
+ for (const auto &extension : type)
+ acceptedSuffixes.append("." + toQt(extension));
+ }
+ }
+
+ m_filePickerController.reset(createFilePickerController(
+ toFileChooserMode(type), listener_, toQt(default_path.value()), acceptedSuffixes));
+ QTimer::singleShot(0, [this]() { m_client->runFileChooser(m_filePickerController); });
+}
+
+SelectFileDialogFactoryQt::SelectFileDialogFactoryQt() = default;
+
+SelectFileDialogFactoryQt::~SelectFileDialogFactoryQt() = default;
+
+ui::SelectFileDialog *
+SelectFileDialogFactoryQt::Create(ui::SelectFileDialog::Listener *listener,
+ std::unique_ptr<ui::SelectFilePolicy> policy)
+{
+ content::WebContents *webContents =
+ static_cast<SelectFilePolicyQt *>(policy.get())->webContents()->GetOutermostWebContents();
+ WebContentsAdapterClient *client =
+ WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(webContents)->GetView())
+ ->client();
+ if (!client)
+ return nullptr;
+ return new SelectFileDialogQt(listener, std::move(policy), client);
+}
+
+} // namespace QtWebEngineCore
diff --git a/src/core/select_file_dialog_factory_qt.h b/src/core/select_file_dialog_factory_qt.h
new file mode 100644
index 000000000..8036995f1
--- /dev/null
+++ b/src/core/select_file_dialog_factory_qt.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef SELECT_FILE_DIALOG_FACTORY_QT_H_
+#define SELECT_FILE_DIALOG_FACTORY_QT_H_
+
+#include "ui/shell_dialogs/select_file_dialog_factory.h"
+#include "ui/shell_dialogs/select_file_policy.h"
+
+namespace content {
+class WebContents;
+}
+
+namespace QtWebEngineCore {
+
+class SelectFilePolicyQt : public ui::SelectFilePolicy
+{
+public:
+ explicit SelectFilePolicyQt(content::WebContents *source_contents);
+ ~SelectFilePolicyQt() override;
+
+ // Overridden from ui::SelectFilePolicy:
+ bool CanOpenSelectFileDialog() override;
+ void SelectFileDenied() override;
+
+ content::WebContents *webContents();
+
+private:
+ content::WebContents *m_webContents;
+};
+
+// Implements a file Open / Save dialog for File System Access API.
+class SelectFileDialogFactoryQt : public ui::SelectFileDialogFactory
+{
+public:
+ SelectFileDialogFactoryQt();
+ ~SelectFileDialogFactoryQt() override;
+
+ // Overridden from ui::SelectFileDialogFactory:
+ ui::SelectFileDialog *Create(ui::SelectFileDialog::Listener *listener,
+ std::unique_ptr<ui::SelectFilePolicy> policy) override;
+};
+
+} // namespace QtWebEngineCore
+
+#endif // SELECT_FILE_DIALOG_FACTORY_QT_H_
diff --git a/src/core/tools/qwebengine_convert_dict/CMakeLists.txt b/src/core/tools/qwebengine_convert_dict/CMakeLists.txt
new file mode 100644
index 000000000..5e8a1de14
--- /dev/null
+++ b/src/core/tools/qwebengine_convert_dict/CMakeLists.txt
@@ -0,0 +1,37 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(QT_FEATURE_webengine_spellchecker AND NOT CMAKE_CROSSCOMPILING)
+ qt_get_tool_target_name(dict_target_name qwebengine_convert_dict)
+ qt_internal_add_tool(${dict_target_name}
+ TARGET_DESCRIPTION "QtWebEngine Dictionary Conversion Tool"
+ INSTALL_DIR ${INSTALL_LIBEXECDIR}
+ TOOLS_TARGET WebEngineCore
+ SOURCES main.cpp
+ INCLUDE_DIRECTORIES
+ ../../../3rdparty/chromium/third_party/abseil-cpp
+ )
+ if(COMMAND qt_internal_return_unless_building_tools)
+ qt_internal_return_unless_building_tools()
+ endif()
+ qt_skip_warnings_are_errors(${dict_target_name})
+ add_dependencies(${dict_target_name} WebEngineCore)
+ qt_internal_extend_target(${dict_target_name} CONDITION WIN32
+ DEFINES WIN32_LEAN_AND_MEAN
+ )
+ qt_internal_extend_target(${dict_target_name} CONDITION GCC OR CLANG
+ COMPILE_OPTIONS -Wno-unused-parameter
+ )
+ set_target_properties(${dict_target_name} PROPERTIES CXX_STANDARD 20)
+ if(NOT QT_FEATURE_webengine_system_icu AND QT_WILL_INSTALL)
+ # tool can be called durig build so copy icu file
+ get_target_property(icuFile WebEngineCore ICUDTL_FILE)
+ addCopyCommand(${dict_target_name} "${icuFile}"
+ "${QT_BUILD_DIR}/${INSTALL_LIBEXECDIR}")
+ endif()
+ qt_internal_extend_target(${dict_target_name}
+ CONDITION NOT QT_FEATURE_webengine_system_icu
+ DEFINES USE_ICU_FILE
+ )
+endif()
+
diff --git a/src/core/tools/qwebengine_convert_dict/main.cpp b/src/core/tools/qwebengine_convert_dict/main.cpp
new file mode 100644
index 000000000..a82947ddc
--- /dev/null
+++ b/src/core/tools/qwebengine_convert_dict/main.cpp
@@ -0,0 +1,254 @@
+/******************************************************************************
+** This is just slightly modified version of convert_dict.cc
+** chromium/chrome/tools/convert_dict/convert_dict.cc
+**
+** Original work:
+** Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
+** Modified work:
+** Copyright (C) 2016 The Qt Company Ltd.
+**
+** SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+**
+** This tool converts Hunspell .aff/.dic pairs to a combined binary dictionary
+** format (.bdic). This format is more compact, and can be more efficiently
+** read by the client application.
+**
+******************************************************************************/
+
+#include <base/at_exit.h>
+#include <base/containers/span.h>
+#include <base/files/file_path.h>
+#include <base/files/file_util.h>
+#include <base/i18n/icu_util.h>
+#include <build/build_config.h>
+#include <chrome/tools/convert_dict/aff_reader.h>
+#include <chrome/tools/convert_dict/dic_reader.h>
+#include <third_party/hunspell/google/bdict_reader.h>
+#include <third_party/hunspell/google/bdict_writer.h>
+#include <base/path_service.h>
+
+#include <QTextStream>
+#include <QLibraryInfo>
+#include <QDir>
+#include <QCoreApplication>
+
+// see also src/core/type_conversion.h
+inline base::FilePath::StringType toFilePathString(const QString &str)
+{
+#if defined(Q_OS_WIN)
+ return QDir::toNativeSeparators(str).toStdWString();
+#else
+ return str.toStdString();
+#endif
+}
+
+inline base::FilePath toFilePath(const QString &str)
+{
+ return base::FilePath(toFilePathString(str));
+}
+
+#if defined(Q_OS_WIN)
+inline QString toQt(const std::wstring &string)
+{
+ return QString::fromStdWString(string);
+}
+#endif
+
+inline QString toQt(const std::u16string &string)
+{
+ return QString::fromStdU16String(string);
+}
+
+inline QString toQt(const std::string &string)
+{
+ return QString::fromStdString(string);
+}
+
+template<class T>
+QTextStream &operator<<(QTextStream &out, base::span<T> span)
+{
+ out << '[';
+ QString prefix;
+ for (const auto &element : span) {
+ out << prefix;
+ out << element;
+ prefix = QStringLiteral(",");
+ }
+ out << ']';
+ return out;
+}
+
+// Compares the given word list with the serialized trie to make sure they
+// are the same.
+inline bool VerifyWords(const convert_dict::DicReader::WordList& org_words,
+ const std::string& serialized, QTextStream& out)
+{
+ hunspell::BDictReader reader;
+ if (!reader.Init(reinterpret_cast<const unsigned char*>(serialized.data()),
+ serialized.size())) {
+ out << "BDict is invalid\n";
+ return false;
+ }
+ hunspell::WordIterator iter = reader.GetAllWordIterator();
+
+ int affix_ids[hunspell::BDict::MAX_AFFIXES_PER_WORD];
+
+ static const int buf_size = 128;
+ char buf[buf_size];
+ for (size_t i = 0; i < org_words.size(); i++) {
+ int affix_matches = iter.Advance(buf, buf_size, affix_ids);
+ if (affix_matches == 0) {
+ out << "Found the end before we expected\n";
+ return false;
+ }
+
+ if (org_words[i].first != buf) {
+ out << "Word does not match!\n"
+ << " Index: " << i << "\n"
+ << " Expected: " << QString::fromStdString(org_words[i].first) << "\n"
+ << " Actual: " << QString::fromUtf8(buf) << "\n";
+ return false;
+ }
+
+ base::span<const int> expectedAffixes(org_words[i].second);
+ base::span<const int> actualAffixes(affix_ids, (size_t)affix_matches);
+
+ if (!std::equal(expectedAffixes.begin(), expectedAffixes.end(),
+ actualAffixes.begin(), actualAffixes.end(),
+ [](int a, int b) { return a == b; })) {
+ out << "Affixes do not match!\n"
+ << " Index: " << i << "\n"
+ << " Word: " << QString::fromUtf8(buf) << "\n"
+ << " Expected: " << expectedAffixes << "\n"
+ << " Actual: " << actualAffixes << "\n";
+ return false;
+ }
+ }
+
+ return true;
+}
+
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+QString frameworkIcuDataPath()
+{
+ return QLibraryInfo::location(QLibraryInfo::LibrariesPath) +
+ QStringLiteral("/QtWebEngineCore.framework/Resources/");
+}
+#endif
+
+int main(int argc, char *argv[])
+{
+ // Required only for making QLibraryInfo::location() return a valid path, when the application
+ // picks up a qt.conf file (which is the case for official Qt packages).
+ QCoreApplication app(argc, argv);
+ Q_UNUSED(app);
+
+ QTextStream out(stdout);
+
+ if (argc != 3) {
+ QTextStream out(stdout);
+ out << "Usage: qwebengine_convert_dict <dic file> <bdic file>\n\nExample:\n"
+ "qwebengine_convert_dict ./en-US.dic ./en-US.bdic\nwill read en-US.dic, "
+ "en-US.dic_delta, and en-US.aff from the current directory and generate "
+ "en-US.bdic\n\n";
+ return 1;
+ }
+#if defined(USE_ICU_FILE)
+ bool icuDataDirFound = false;
+ QString icuDataDir = QLibraryInfo::path(QLibraryInfo::DataPath)
+ % QLatin1String("/resources");
+
+ // Try to look up the path to the ICU data directory via an environment variable
+ // (e.g. for the case when the tool is ran during build phase, and regular installed
+ // ICU data file is not available).
+ const QString icuPossibleEnvDataDir = qEnvironmentVariable("QT_WEBENGINE_ICU_DATA_DIR");
+ const QString appPath = QCoreApplication::applicationDirPath();
+ QLatin1String icuDataFilePath("/icudtl.dat");
+ if (!icuPossibleEnvDataDir.isEmpty() && QFileInfo::exists(icuPossibleEnvDataDir)) {
+ icuDataDir = icuPossibleEnvDataDir;
+ icuDataDirFound = true;
+ }
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+ // In a macOS Qt framework build, the resources are inside the QtWebEngineCore framework
+ // Resources directory, rather than in the Qt install location.
+ else if (QFileInfo::exists(frameworkIcuDataPath())) {
+ icuDataDir = frameworkIcuDataPath();
+ icuDataDirFound = true;
+ }
+#endif
+ // Try to find the ICU data directory in the installed Qt location.
+ else if (QFileInfo::exists(icuDataDir + icuDataFilePath)) {
+ icuDataDirFound = true;
+ } else if (QFileInfo::exists(appPath + icuDataFilePath)) {
+ // during build icudtl file can be simply in application directory
+ icuDataDir = appPath;
+ icuDataDirFound = true;
+ }
+ if (icuDataDirFound) {
+ base::PathService::Override(base::DIR_QT_LIBRARY_DATA, toFilePath(icuDataDir));
+ } else {
+ QTextStream out(stdout);
+ out << "Couldn't find ICU data directory. Please check that the following path exists: "
+ << icuDataDir
+ << "\nAlternatively provide the directory path via the QT_WEBENGINE_ICU_DATA_DIR "
+ "environment variable.\n\n";
+ return 1;
+ }
+#endif // USE_ICU_FILE
+
+ base::i18n::InitializeICU();
+
+ base::FilePath file_in_path = toFilePath(argv[1]);
+ base::FilePath file_out_path = toFilePath(argv[2]);
+ base::FilePath aff_path = file_in_path.ReplaceExtension(FILE_PATH_LITERAL(".aff"));
+
+ out << "Reading " << toQt(aff_path.value()) << "\n";
+ convert_dict::AffReader aff_reader(aff_path);
+
+ if (!aff_reader.Read()) {
+ out << "Unable to read the aff file.\n";
+ return 1;
+ }
+
+ base::FilePath dic_path = file_in_path.ReplaceExtension(FILE_PATH_LITERAL(".dic"));
+ out << "Reading " << toQt(dic_path.value()) << "\n";
+
+ // DicReader will also read the .dic_delta file.
+ convert_dict::DicReader dic_reader(dic_path);
+ if (!dic_reader.Read(&aff_reader)) {
+ out << "Unable to read the dic file.\n";
+ return 1;
+ }
+
+ hunspell::BDictWriter writer;
+ writer.SetComment(aff_reader.comments());
+ writer.SetAffixRules(aff_reader.affix_rules());
+ writer.SetAffixGroups(aff_reader.GetAffixGroups());
+ writer.SetReplacements(aff_reader.replacements());
+ writer.SetOtherCommands(aff_reader.other_commands());
+ writer.SetWords(dic_reader.words());
+
+ out << "Serializing...\n";
+
+ std::string serialized = writer.GetBDict();
+
+ out << "Verifying...\n";
+
+ if (!VerifyWords(dic_reader.words(), serialized, out)) {
+ out << "ERROR converting, the dictionary does not check out OK.\n";
+ return 1;
+ }
+
+ out << "Writing " << toQt(file_out_path.value()) << "\n";
+ FILE *out_file = base::OpenFile(file_out_path, "wb");
+ if (!out_file) {
+ out << "ERROR writing file\n";
+ return 1;
+ }
+ size_t written = fwrite(&serialized[0], 1, serialized.size(), out_file);
+ Q_ASSERT(written == serialized.size());
+ base::CloseFile(out_file);
+ out << "Success. Dictionary converted.\n";
+ return 0;
+}
+
diff --git a/src/core/tools/webenginedriver/CMakeLists.txt b/src/core/tools/webenginedriver/CMakeLists.txt
new file mode 100644
index 000000000..b20311980
--- /dev/null
+++ b/src/core/tools/webenginedriver/CMakeLists.txt
@@ -0,0 +1,57 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(WIN32)
+ set(WEBENGINEDRIVER_EXECUTABLE webenginedriver.exe)
+else()
+ set(WEBENGINEDRIVER_EXECUTABLE webenginedriver)
+endif()
+set(WEBENGINEDRIVER_EXECUTABLE ${WEBENGINEDRIVER_EXECUTABLE} PARENT_SCOPE)
+
+if(QT_FEATURE_webenginedriver)
+ get_install_config(config)
+ get_architectures(archs)
+ list(GET archs 0 arch)
+
+ ##
+ # DOCS
+ ##
+ add_code_attributions_target(
+ TARGET generate_webenginedriver_attributions
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/webenginedriver_attributions.qdoc
+ GN_TARGET //chrome/test/chromedriver:chromedriver_server
+ EXTRA_THIRD_PARTY_DIRS
+ third_party/selenium-atoms/sizzle
+ third_party/selenium-atoms/wgxpath
+ third_party/selenium-atoms/closure-lib
+ FILE_TEMPLATE ../../doc/about_credits.tmpl
+ ENTRY_TEMPLATE ../../doc/about_credits_entry.tmpl
+ BUILDDIR ${buildDir}/${config}/${arch}
+ )
+ add_dependencies(generate_webenginedriver_attributions run_core_GnDone)
+ add_dependencies(prepare_docs_WebEngineCore generate_webenginedriver_attributions)
+
+ ##
+ # INSTALL
+ ##
+ install(
+ PROGRAMS ${buildDir}/${config}/${arch}/${WEBENGINEDRIVER_EXECUTABLE}
+ CONFIGURATIONS ${config}
+ RUNTIME DESTINATION "${INSTALL_LIBEXECDIR}"
+ )
+ if(NOT QT_WILL_INSTALL)
+ add_custom_target(copy-webenginedriver
+ ALL
+ DEPENDS ${QT_BUILD_DIR}/${INSTALL_LIBEXECDIR}/${WEBENGINEDRIVER_EXECUTABLE}
+ )
+ add_custom_command(
+ OUTPUT ${QT_BUILD_DIR}/${INSTALL_LIBEXECDIR}/${WEBENGINEDRIVER_EXECUTABLE}
+ COMMAND ${CMAKE_COMMAND} -E copy ${buildDir}/${config}/${arch}/${WEBENGINEDRIVER_EXECUTABLE}
+ ${QT_BUILD_DIR}/${INSTALL_LIBEXECDIR}
+ DEPENDS
+ WebEngineCore
+ ${buildDir}/${config}/${arch}/${WEBENGINEDRIVER_EXECUTABLE}
+ USES_TERMINAL
+ )
+ endif()
+endif()
diff --git a/src/core/touch_handle_drawable_client.h b/src/core/touch_handle_drawable_client.h
index a2c87948a..ddfaa9f57 100644
--- a/src/core/touch_handle_drawable_client.h
+++ b/src/core/touch_handle_drawable_client.h
@@ -1,53 +1,17 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef TOUCH_HANDLE_DRAWABLE_CLIENT_H
#define TOUCH_HANDLE_DRAWABLE_CLIENT_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QRect>
namespace QtWebEngineCore {
-class Q_WEBENGINECORE_PRIVATE_EXPORT TouchHandleDrawableClient {
+class Q_WEBENGINECORE_EXPORT TouchHandleDrawableDelegate {
public:
- virtual ~TouchHandleDrawableClient() { }
+ virtual ~TouchHandleDrawableDelegate() { }
virtual void setImage(int orientation) = 0;
virtual void setBounds(const QRect &bounds) = 0;
diff --git a/src/core/touch_handle_drawable_qt.cpp b/src/core/touch_handle_drawable_qt.cpp
index 66b1cf40e..1e979fa03 100644
--- a/src/core/touch_handle_drawable_qt.cpp
+++ b/src/core/touch_handle_drawable_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -49,7 +13,6 @@
#include "type_conversion.h"
#include "web_contents_adapter_client.h"
-#include "ui/gfx/image/image.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/resources/grit/ui_resources.h"
@@ -68,27 +31,6 @@ const int kSelectionHandlePadding = 0;
// Epsilon value used to compare float values to zero.
const float kEpsilon = 1e-8f;
-// Returns the appropriate handle image based on the handle orientation.
-gfx::Image* GetHandleImage(ui::TouchHandleOrientation orientation)
-{
- int resource_id = 0;
- switch (orientation) {
- case ui::TouchHandleOrientation::LEFT:
- resource_id = IDR_TEXT_SELECTION_HANDLE_LEFT;
- break;
- case ui::TouchHandleOrientation::CENTER:
- resource_id = IDR_TEXT_SELECTION_HANDLE_CENTER;
- break;
- case ui::TouchHandleOrientation::RIGHT:
- resource_id = IDR_TEXT_SELECTION_HANDLE_RIGHT;
- break;
- case ui::TouchHandleOrientation::UNDEFINED:
- NOTREACHED() << "Invalid touch handle bound type.";
- return nullptr;
- };
- return &ui::ResourceBundle::GetSharedInstance().GetImageNamed(resource_id);
-}
-
bool IsNearlyZero(float value)
{
return std::abs(value) < kEpsilon;
@@ -96,21 +38,12 @@ bool IsNearlyZero(float value)
} // namespace
-TouchHandleDrawableQt::TouchHandleDrawableQt(RenderWidgetHostViewQt *rwhv)
- : m_rwhv(rwhv)
+TouchHandleDrawableQt::TouchHandleDrawableQt(TouchHandleDrawableDelegate *delegate)
+ : m_delegate(delegate)
, m_enabled(false)
, m_alpha(0)
, m_orientation(ui::TouchHandleOrientation::UNDEFINED)
{
- QMap<int, QImage> images;
- for (int orientation = 0; orientation < static_cast<int>(ui::TouchHandleOrientation::UNDEFINED); ++orientation) {
- gfx::Image* image = GetHandleImage(static_cast<ui::TouchHandleOrientation>(orientation));
- images.insert(orientation, toQImage(image->AsBitmap()));
- }
-
- Q_ASSERT(m_rwhv);
- Q_ASSERT(m_rwhv->adapterClient());
- m_client.reset(m_rwhv->adapterClient()->createTouchHandle(images));
}
TouchHandleDrawableQt::~TouchHandleDrawableQt()
@@ -119,12 +52,12 @@ TouchHandleDrawableQt::~TouchHandleDrawableQt()
void TouchHandleDrawableQt::UpdateBounds()
{
- if (!m_client)
+ if (!m_delegate)
return;
gfx::RectF newBounds = m_relativeBounds;
newBounds.Offset(m_originPosition.x(), m_originPosition.y());
- m_client->setBounds(toQt(gfx::ToEnclosingRect(newBounds)));
+ m_delegate->setBounds(toQt(gfx::ToEnclosingRect(newBounds)));
}
bool TouchHandleDrawableQt::IsVisible() const
@@ -134,19 +67,19 @@ bool TouchHandleDrawableQt::IsVisible() const
void TouchHandleDrawableQt::SetEnabled(bool enabled)
{
- if (!m_client)
+ if (!m_delegate)
return;
if (enabled == m_enabled)
return;
m_enabled = enabled;
- m_client->setVisible(enabled);
+ m_delegate->setVisible(enabled);
}
void TouchHandleDrawableQt::SetOrientation(ui::TouchHandleOrientation orientation, bool mirror_vertical, bool mirror_horizontal)
{
- if (!m_client)
+ if (!m_delegate)
return;
// TODO: Implement adaptive handle orientation logic
@@ -157,7 +90,7 @@ void TouchHandleDrawableQt::SetOrientation(ui::TouchHandleOrientation orientatio
return;
m_orientation = orientation;
gfx::Image* image = GetHandleImage(orientation);
- m_client->setImage(static_cast<int>(orientation));
+ m_delegate->setImage(static_cast<int>(orientation));
// Calculate the relative bounds.
gfx::Size image_size = image->Size();
@@ -178,15 +111,15 @@ void TouchHandleDrawableQt::SetOrigin(const gfx::PointF& position)
void TouchHandleDrawableQt::SetAlpha(float alpha)
{
- if (!m_client)
+ if (!m_delegate)
return;
if (alpha == m_alpha)
return;
m_alpha = alpha;
- m_client->setOpacity(m_alpha);
- m_client->setVisible(IsVisible());
+ m_delegate->setOpacity(m_alpha);
+ m_delegate->setVisible(IsVisible());
}
gfx::RectF TouchHandleDrawableQt::GetVisibleBounds() const
@@ -195,10 +128,11 @@ gfx::RectF TouchHandleDrawableQt::GetVisibleBounds() const
bounds.Offset(m_originPosition.x(), m_originPosition.y());
gfx::RectF visibleBounds(bounds);
- visibleBounds.Inset(kSelectionHandlePadding,
- kSelectionHandlePadding + kSelectionHandleVerticalVisualOffset,
- kSelectionHandlePadding,
- kSelectionHandlePadding);
+ visibleBounds.Inset(gfx::InsetsF::TLBR(
+ kSelectionHandlePadding,
+ kSelectionHandlePadding + kSelectionHandleVerticalVisualOffset,
+ kSelectionHandlePadding,
+ kSelectionHandlePadding));
return visibleBounds;
}
@@ -208,4 +142,25 @@ float TouchHandleDrawableQt::GetDrawableHorizontalPaddingRatio() const
return 0.0;
}
+// Returns the appropriate handle image based on the handle orientation.
+gfx::Image *TouchHandleDrawableQt::GetHandleImage(ui::TouchHandleOrientation orientation)
+{
+ int resource_id = 0;
+ switch (orientation) {
+ case ui::TouchHandleOrientation::LEFT:
+ resource_id = IDR_TEXT_SELECTION_HANDLE_LEFT;
+ break;
+ case ui::TouchHandleOrientation::CENTER:
+ resource_id = IDR_TEXT_SELECTION_HANDLE_CENTER;
+ break;
+ case ui::TouchHandleOrientation::RIGHT:
+ resource_id = IDR_TEXT_SELECTION_HANDLE_RIGHT;
+ break;
+ case ui::TouchHandleOrientation::UNDEFINED:
+ NOTREACHED() << "Invalid touch handle bound type.";
+ return nullptr;
+ };
+ return &ui::ResourceBundle::GetSharedInstance().GetImageNamed(resource_id);
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/touch_handle_drawable_qt.h b/src/core/touch_handle_drawable_qt.h
index 46fa217b7..1738e68e9 100644
--- a/src/core/touch_handle_drawable_qt.h
+++ b/src/core/touch_handle_drawable_qt.h
@@ -1,60 +1,25 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef TOUCH_HANDLE_DRAWABLE_QT_H
#define TOUCH_HANDLE_DRAWABLE_QT_H
#include "ui/touch_selection/touch_handle.h"
#include "ui/touch_selection/touch_handle_orientation.h"
+#include "ui/gfx/image/image.h"
#include <QtCore/QScopedPointer>
namespace QtWebEngineCore {
-class RenderWidgetHostViewQt;
-class TouchHandleDrawableClient;
+class TouchHandleDrawableDelegate;
class TouchHandleDrawableQt : public ui::TouchHandleDrawable
{
public:
- explicit TouchHandleDrawableQt(RenderWidgetHostViewQt *rwhv);
+ explicit TouchHandleDrawableQt(TouchHandleDrawableDelegate *delegate);
~TouchHandleDrawableQt() override;
+ static gfx::Image *GetHandleImage(ui::TouchHandleOrientation orientation);
private:
void UpdateBounds();
@@ -71,15 +36,13 @@ private:
float GetDrawableHorizontalPaddingRatio() const override;
RenderWidgetHostViewQt *m_rwhv;
- QScopedPointer<TouchHandleDrawableClient> m_client;
+ QScopedPointer<TouchHandleDrawableDelegate> m_delegate;
bool m_enabled;
float m_alpha;
ui::TouchHandleOrientation m_orientation;
gfx::RectF m_relativeBounds;
gfx::PointF m_originPosition;
-
- DISALLOW_COPY_AND_ASSIGN(TouchHandleDrawableQt);
};
} // namespace QtWebEngineCore
diff --git a/src/core/touch_selection_controller_client_qt.cpp b/src/core/touch_selection_controller_client_qt.cpp
index 0f44210d1..befee6aaf 100644
--- a/src/core/touch_selection_controller_client_qt.cpp
+++ b/src/core/touch_selection_controller_client_qt.cpp
@@ -1,51 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "render_widget_host_view_qt.h"
#include "touch_handle_drawable_qt.h"
+#include "touch_handle_drawable_client.h"
#include "touch_selection_controller_client_qt.h"
#include "touch_selection_menu_controller.h"
#include "type_conversion.h"
#include "web_contents_adapter.h"
#include "web_contents_adapter_client.h"
-#include "content/browser/frame_host/render_frame_host_impl.h"
+#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "ui/gfx/geometry/size_conversions.h"
@@ -229,29 +194,29 @@ void TouchSelectionControllerClientQt::SetNeedsAnimate()
void TouchSelectionControllerClientQt::MoveCaret(const gfx::PointF& position)
{
- content::mojom::FrameInputHandler *frameInputHandler = m_rwhv->getFrameInputHandler();
- if (!frameInputHandler)
+ auto *frameWidgetInputHandler = m_rwhv->getFrameWidgetInputHandler();
+ if (!frameWidgetInputHandler)
return;
- frameInputHandler->MoveCaret(gfx::ToRoundedPoint(position));
+ frameWidgetInputHandler->MoveCaret(gfx::ToRoundedPoint(position));
}
void TouchSelectionControllerClientQt::MoveRangeSelectionExtent(const gfx::PointF& extent)
{
- content::mojom::FrameInputHandler *frameInputHandler = m_rwhv->getFrameInputHandler();
- if (!frameInputHandler)
+ auto *frameWidgetInputHandler = m_rwhv->getFrameWidgetInputHandler();
+ if (!frameWidgetInputHandler)
return;
- frameInputHandler->MoveRangeSelectionExtent(gfx::ToRoundedPoint(extent));
+ frameWidgetInputHandler->MoveRangeSelectionExtent(gfx::ToRoundedPoint(extent));
}
void TouchSelectionControllerClientQt::SelectBetweenCoordinates(const gfx::PointF& base, const gfx::PointF& extent)
{
- content::mojom::FrameInputHandler *frameInputHandler = m_rwhv->getFrameInputHandler();
- if (!frameInputHandler)
+ auto *frameWidgetInputHandler = m_rwhv->getFrameWidgetInputHandler();
+ if (!frameWidgetInputHandler)
return;
- frameInputHandler->SelectRange(gfx::ToRoundedPoint(base), gfx::ToRoundedPoint(extent));
+ frameWidgetInputHandler->SelectRange(gfx::ToRoundedPoint(base), gfx::ToRoundedPoint(extent));
}
void TouchSelectionControllerClientQt::OnSelectionEvent(ui::SelectionEventType event)
@@ -285,20 +250,39 @@ void TouchSelectionControllerClientQt::OnSelectionEvent(ui::SelectionEventType e
updateMenu();
}
-void TouchSelectionControllerClientQt::OnDragUpdate(const gfx::PointF& position)
+void TouchSelectionControllerClientQt::OnDragUpdate(const ui::TouchSelectionDraggable::Type type, const gfx::PointF& position)
{
+ Q_UNUSED(type);
Q_UNUSED(position);
}
std::unique_ptr<ui::TouchHandleDrawable> TouchSelectionControllerClientQt::CreateDrawable()
{
- return std::unique_ptr<ui::TouchHandleDrawable>(new TouchHandleDrawableQt(m_rwhv));
+ Q_ASSERT(m_rwhv);
+ Q_ASSERT(m_rwhv->adapterClient());
+ QMap<int, QImage> images;
+ for (int orientation = 0; orientation < static_cast<int>(ui::TouchHandleOrientation::UNDEFINED);
+ ++orientation) {
+ gfx::Image *image = TouchHandleDrawableQt::GetHandleImage(
+ static_cast<ui::TouchHandleOrientation>(orientation));
+ images.insert(orientation, toQImage(image->AsBitmap()));
+ }
+ auto delegate = m_rwhv->adapterClient()->createTouchHandleDelegate(images);
+ return std::unique_ptr<ui::TouchHandleDrawable>(new TouchHandleDrawableQt(delegate));
}
void TouchSelectionControllerClientQt::DidScroll()
{
}
+void TouchSelectionControllerClientQt::resetControls()
+{
+ if (m_menuShowing) {
+ hideMenu();
+ GetTouchSelectionController()->HideAndDisallowShowingAutomatically();
+ }
+}
+
void TouchSelectionControllerClientQt::showMenu()
{
gfx::RectF rect = GetTouchSelectionController()->GetRectBetweenBounds();
diff --git a/src/core/touch_selection_controller_client_qt.h b/src/core/touch_selection_controller_client_qt.h
index 0d8dcf696..3fdca7922 100644
--- a/src/core/touch_selection_controller_client_qt.h
+++ b/src/core/touch_selection_controller_client_qt.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef TOUCH_SELECTION_CONTROLLER_CLIENT_QT_H
#define TOUCH_SELECTION_CONTROLLER_CLIENT_QT_H
+#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/touch_selection_controller_client_manager.h"
-#include "content/public/common/context_menu_params.h"
#include "ui/touch_selection/touch_selection_controller.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
@@ -51,6 +15,7 @@ namespace QtWebEngineCore {
class RenderWidgetHostViewQt;
class TouchSelectionMenuController;
+class TouchHandleDrawableDelegate;
class TouchSelectionControllerClientQt
: public ui::TouchSelectionControllerClient
@@ -74,7 +39,7 @@ public:
void ExecuteCommand(int command_id, int event_flags) override;
void RunContextMenu() override;
bool ShouldShowQuickMenu() override { return false; }
- base::string16 GetSelectedText() override { return base::string16(); }
+ std::u16string GetSelectedText() override { return std::u16string(); }
// content::TouchSelectionControllerClientManager overrides
void DidStopFlinging() override;
@@ -86,6 +51,9 @@ public:
ui::TouchSelectionController* GetTouchSelectionController() override;
void AddObserver(Observer* observer) override;
void RemoveObserver(Observer* observer) override;
+ void OnSwipeToMoveCursorBegin() override {}
+ void OnSwipeToMoveCursorEnd() override {}
+ void OnClientHitTestRegionUpdated(ui::TouchSelectionControllerClient *) override {}
// ui::TouchSelectionControllerClient overrides
bool SupportsAnimation() const override;
@@ -94,10 +62,12 @@ public:
void MoveRangeSelectionExtent(const gfx::PointF& extent) override;
void SelectBetweenCoordinates(const gfx::PointF& base, const gfx::PointF& extent) override;
void OnSelectionEvent(ui::SelectionEventType event) override;
- void OnDragUpdate(const gfx::PointF& position) override;
+ void OnDragUpdate(const ui::TouchSelectionDraggable::Type type, const gfx::PointF& position) override;
std::unique_ptr<ui::TouchHandleDrawable> CreateDrawable() override;
void DidScroll() override;
+ void resetControls();
+
private:
void showMenu();
void hideMenu();
diff --git a/src/core/touch_selection_menu_controller.cpp b/src/core/touch_selection_menu_controller.cpp
index cdec9a064..98481baf0 100644
--- a/src/core/touch_selection_menu_controller.cpp
+++ b/src/core/touch_selection_menu_controller.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "touch_selection_controller_client_qt.h"
#include "touch_selection_menu_controller.h"
@@ -53,17 +17,11 @@ TouchSelectionMenuController::~TouchSelectionMenuController()
int TouchSelectionMenuController::buttonCount()
{
- int buttonCount = 1;
-
- for (int commandId = 0; commandId <= static_cast<int>(Paste); ++commandId) {
- if (m_touchSelectionControllerClient->IsCommandIdEnabled(commandId))
- buttonCount++;
- }
-
- return buttonCount;
+ // Context menu should be always available
+ return qPopulationCount(static_cast<quint8>(availableActions())) + 1;
}
-bool TouchSelectionMenuController::isCommandEnabled(TouchSelectionCommand command)
+bool TouchSelectionMenuController::isCommandEnabled(TouchSelectionMenuController::TouchSelectionCommandFlag command)
{
return m_touchSelectionControllerClient->IsCommandIdEnabled(static_cast<int>(command));
}
@@ -88,4 +46,21 @@ void TouchSelectionMenuController::runContextMenu()
return m_touchSelectionControllerClient->RunContextMenu();
}
+TouchSelectionMenuController::TouchSelectionCommandFlags TouchSelectionMenuController::availableActions()
+{
+ TouchSelectionCommandFlags availableActions;
+
+ if (m_touchSelectionControllerClient->IsCommandIdEnabled(Cut)) {
+ availableActions |= TouchSelectionMenuController::Cut;
+ }
+ if (m_touchSelectionControllerClient->IsCommandIdEnabled(Copy)) {
+ availableActions |= TouchSelectionMenuController::Copy;
+ }
+ if (m_touchSelectionControllerClient->IsCommandIdEnabled(Paste)) {
+ availableActions |= TouchSelectionMenuController::Paste;
+ }
+
+ return availableActions;
+}
+
} // namespace QtWebEngineCore
diff --git a/src/core/touch_selection_menu_controller.h b/src/core/touch_selection_menu_controller.h
index 34137b05b..6a1fc1960 100644
--- a/src/core/touch_selection_menu_controller.h
+++ b/src/core/touch_selection_menu_controller.h
@@ -1,65 +1,32 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef TOUCH_SELECTION_MENU_CONTROLLER_H
#define TOUCH_SELECTION_MENU_CONTROLLER_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include <QtCore/QObject>
namespace QtWebEngineCore {
class TouchSelectionControllerClientQt;
-class Q_WEBENGINECORE_PRIVATE_EXPORT TouchSelectionMenuController : public QObject {
+class Q_WEBENGINECORE_EXPORT TouchSelectionMenuController : public QObject {
Q_OBJECT
public:
- enum TouchSelectionCommand {
- Cut,
- Copy,
- Paste
+ enum TouchSelectionCommandFlag {
+ Cut = 0x1,
+ Copy = 0x2,
+ Paste = 0x4
};
+ Q_DECLARE_FLAGS(TouchSelectionCommandFlags, TouchSelectionCommandFlag)
+ Q_FLAG(TouchSelectionCommandFlag)
TouchSelectionMenuController(TouchSelectionControllerClientQt *touchSelectionControllerClient);
~TouchSelectionMenuController();
int buttonCount();
- bool isCommandEnabled(TouchSelectionCommand);
+ bool isCommandEnabled(TouchSelectionCommandFlag);
+ TouchSelectionCommandFlags availableActions();
public Q_SLOTS:
void cut();
diff --git a/src/core/type_conversion.cpp b/src/core/type_conversion.cpp
index de507f836..2d4fb323d 100644
--- a/src/core/type_conversion.cpp
+++ b/src/core/type_conversion.cpp
@@ -1,52 +1,19 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "type_conversion.h"
-#include <content/public/common/favicon_url.h>
+#include "base/containers/contains.h"
+#include <components/favicon_base/favicon_util.h>
#include <net/cert/x509_certificate.h>
#include <net/cert/x509_util.h>
#include <ui/events/event_constants.h>
-#include <ui/gfx/image/image_skia.h>
+#include "ui/gfx/image/image.h"
+#include "ui/gfx/image/image_skia.h"
+#include "ui/gfx/image/image_skia_rep.h"
+#include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h"
#include <QtCore/qcoreapplication.h>
-#include <QtGui/qmatrix4x4.h>
#include <QtNetwork/qsslcertificate.h>
namespace QtWebEngineCore {
@@ -64,6 +31,7 @@ QImage toQImage(const SkBitmap &bitmap)
case kA16_unorm_SkColorType:
case kR16G16_float_SkColorType:
case kR16G16_unorm_SkColorType:
+ case kR8_unorm_SkColorType:
qWarning("Unknown or unsupported skia image format");
break;
case kAlpha_8_SkColorType:
@@ -86,6 +54,7 @@ QImage toQImage(const SkBitmap &bitmap)
break;
}
break;
+ case kSRGBA_8888_SkColorType:
case kRGB_888x_SkColorType:
case kRGBA_8888_SkColorType:
switch (bitmap.alphaType()) {
@@ -133,6 +102,22 @@ QImage toQImage(const SkBitmap &bitmap)
break;
}
break;
+ case kBGR_101010x_SkColorType:
+ case kBGR_101010x_XR_SkColorType:
+ case kBGRA_1010102_SkColorType:
+ switch (bitmap.alphaType()) {
+ case kUnknown_SkAlphaType:
+ break;
+ case kUnpremul_SkAlphaType:
+ // not supported - treat as opaque
+ case kOpaque_SkAlphaType:
+ image = toQImage(bitmap, QImage::Format_BGR30);
+ break;
+ case kPremul_SkAlphaType:
+ image = toQImage(bitmap, QImage::Format_A2BGR30_Premultiplied);
+ break;
+ }
+ break;
case kGray_8_SkColorType:
image = toQImage(bitmap, QImage::Format_Grayscale8);
break;
@@ -201,6 +186,23 @@ SkBitmap toSkBitmap(const QImage &image)
return bitmapCopy;
}
+QIcon toQIcon(const gfx::Image &image)
+{
+ // Based on ExtractSkBitmapsToStore in chromium/components/favicon/core/favicon_service_impl.cc
+ gfx::ImageSkia image_skia = image.AsImageSkia();
+ image_skia.EnsureRepsForSupportedScales();
+ const std::vector<gfx::ImageSkiaRep> &image_reps = image_skia.image_reps();
+ std::vector<SkBitmap> bitmaps;
+ const std::vector<float> favicon_scales = favicon_base::GetFaviconScales();
+ for (size_t i = 0; i < image_reps.size(); ++i) {
+ // Don't save if the scale isn't one of supported favicon scales.
+ if (!base::Contains(favicon_scales, image_reps[i].scale()))
+ continue;
+ bitmaps.push_back(image_reps[i].GetBitmap());
+ }
+ return toQIcon(bitmaps);
+}
+
QIcon toQIcon(const std::vector<SkBitmap> &bitmaps)
{
if (!bitmaps.size())
@@ -242,44 +244,6 @@ int flagsFromModifiers(Qt::KeyboardModifiers modifiers)
return modifierFlags;
}
-FaviconInfo::FaviconTypeFlags toQt(content::FaviconURL::IconType type)
-{
- switch (type) {
- case content::FaviconURL::IconType::kFavicon:
- return FaviconInfo::Favicon;
- case content::FaviconURL::IconType::kTouchIcon:
- return FaviconInfo::TouchIcon;
- case content::FaviconURL::IconType::kTouchPrecomposedIcon:
- return FaviconInfo::TouchPrecomposedIcon;
- case content::FaviconURL::IconType::kInvalid:
- return FaviconInfo::InvalidIcon;
- }
- Q_UNREACHABLE();
- return FaviconInfo::InvalidIcon;
-}
-
-FaviconInfo toFaviconInfo(const content::FaviconURL &favicon_url)
-{
- FaviconInfo info;
- info.url = toQt(favicon_url.icon_url);
- info.type = toQt(favicon_url.icon_type);
- // TODO: Add support for rel sizes attribute (favicon_url.icon_sizes):
- // http://www.w3schools.com/tags/att_link_sizes.asp
- info.size = QSize(0, 0);
- return info;
-}
-
-void convertToQt(const SkMatrix44 &m, QMatrix4x4 &c)
-{
- QMatrix4x4 qtMatrix(
- m.get(0, 0), m.get(0, 1), m.get(0, 2), m.get(0, 3),
- m.get(1, 0), m.get(1, 1), m.get(1, 2), m.get(1, 3),
- m.get(2, 0), m.get(2, 1), m.get(2, 2), m.get(2, 3),
- m.get(3, 0), m.get(3, 1), m.get(3, 2), m.get(3, 3));
- qtMatrix.optimize();
- c = qtMatrix;
-}
-
static QSslCertificate toCertificate(CRYPTO_BUFFER *buffer)
{
auto derCert = net::x509_util::CryptoBufferAsStringPiece(buffer);
diff --git a/src/core/type_conversion.h b/src/core/type_conversion.h
index 9c193e69e..0da8a6931 100644
--- a/src/core/type_conversion.h
+++ b/src/core/type_conversion.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef TYPE_CONVERSION_H
#define TYPE_CONVERSION_H
@@ -49,29 +13,23 @@
#include <QRect>
#include <QString>
#include <QUrl>
-#include <base/strings/nullable_string16.h>
#include "base/files/file_path.h"
#include "base/time/time.h"
-#include "content/public/common/file_chooser_file_info.h"
-#include "favicon_manager.h"
#include "net/cookies/canonical_cookie.h"
+#include "third_party/blink/public/mojom/favicon/favicon_url.mojom-forward.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkPixelRef.h"
-#include "third_party/skia/include/core/SkMatrix44.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "url/gurl.h"
+#include "url/origin.h"
-QT_FORWARD_DECLARE_CLASS(QMatrix4x4)
QT_FORWARD_DECLARE_CLASS(QSslCertificate)
-namespace content {
-struct FaviconURL;
-}
-
namespace gfx {
+class Image;
class ImageSkiaRep;
}
@@ -81,13 +39,28 @@ class X509Certificate;
namespace QtWebEngineCore {
-inline QString toQt(const base::string16 &string)
+#if defined(Q_OS_WIN)
+inline QString toQt(const std::wstring &string)
{
-#if defined(OS_WIN)
- return QString::fromStdWString(string.data());
-#else
- return QString::fromUtf16(string.data());
+ return QString::fromStdWString(string);
+}
#endif
+
+inline QString toQt(const std::u16string &string)
+{
+ return QString::fromStdU16String(string);
+}
+
+inline QString toQt(const absl::optional<std::u16string> &string)
+{
+ if (!string.has_value())
+ return QString();
+ return QString::fromStdU16String(*string);
+}
+
+inline QString toQString(const base::StringPiece &string)
+{
+ return QString::fromUtf8(string.data(), string.size());
}
inline QString toQString(const std::string &string)
@@ -95,6 +68,11 @@ inline QString toQString(const std::string &string)
return QString::fromStdString(string);
}
+inline QByteArray toQByteArray(const base::StringPiece &string)
+{
+ return QByteArray(string.data(), string.size());
+}
+
inline QByteArray toQByteArray(const std::string &string)
{
return QByteArray::fromStdString(string);
@@ -106,18 +84,16 @@ inline QString toQt(const std::string &string)
return toQString(string);
}
-inline base::string16 toString16(const QString &qString)
+inline std::u16string toString16(const QString &qString)
{
-#if defined(OS_WIN)
- return base::string16(qString.toStdWString());
-#else
- return base::string16(qString.utf16());
-#endif
+ return qString.toStdU16String();
}
-inline base::NullableString16 toNullableString16(const QString &qString)
+inline absl::optional<std::u16string> toOptionalString16(const QString &qString)
{
- return base::NullableString16(toString16(qString), qString.isNull());
+ if (qString.isNull())
+ return absl::nullopt;
+ return absl::make_optional(qString.toStdU16String());
}
inline QUrl toQt(const GURL &url)
@@ -133,11 +109,26 @@ inline GURL toGurl(const QUrl& url)
return GURL(url.toEncoded().toStdString());
}
+inline QUrl toQt(const url::Origin &origin)
+{
+ return QUrl::fromEncoded(toQByteArray(origin.Serialize()));
+}
+
+inline url::Origin toOrigin(const QUrl &url)
+{
+ return url::Origin::Create(toGurl(url));
+}
+
inline QPoint toQt(const gfx::Point &point)
{
return QPoint(point.x(), point.y());
}
+inline QPointF toQt(const gfx::PointF &point)
+{
+ return QPointF(point.x(), point.y());
+}
+
inline QPointF toQt(const gfx::Vector2dF &point)
{
return QPointF(point.x(), point.y());
@@ -188,6 +179,11 @@ inline QSizeF toQt(const gfx::SizeF &size)
return QSizeF(size.width(), size.height());
}
+inline QSize toQt(const SkISize &size)
+{
+ return QSize(size.width(), size.height());
+}
+
inline QColor toQt(const SkColor &c)
{
return QColor(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c), SkColorGetA(c));
@@ -208,10 +204,9 @@ QImage toQImage(const SkBitmap &bitmap);
QImage toQImage(const gfx::ImageSkiaRep &imageSkiaRep);
SkBitmap toSkBitmap(const QImage &image);
+QIcon toQIcon(const gfx::Image &image);
QIcon toQIcon(const std::vector<SkBitmap> &bitmaps);
-void convertToQt(const SkMatrix44 &m, QMatrix4x4 &c);
-
inline QDateTime toQt(base::Time time)
{
return QDateTime::fromMSecsSinceEpoch(time.ToJavaTime());
@@ -235,7 +230,7 @@ inline QNetworkCookie toQt(const net::CanonicalCookie & cookie)
inline base::FilePath::StringType toFilePathString(const QString &str)
{
-#if defined(OS_WIN)
+#if defined(Q_OS_WIN)
return QDir::toNativeSeparators(str).toStdWString();
#else
return str.toStdString();
@@ -247,46 +242,9 @@ inline base::FilePath toFilePath(const QString &str)
return base::FilePath(toFilePathString(str));
}
-template <typename T>
-inline T fileListingHelper(const QString &)
-// Clang is still picky about this though it should be supported eventually.
-// See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#941
-#ifndef Q_CC_CLANG
-= delete;
-#else
-{ return T(); }
-#endif
-
-template <>
-inline content::FileChooserFileInfo fileListingHelper<content::FileChooserFileInfo>(const QString &file)
-{
- content::FileChooserFileInfo choose_file;
- base::FilePath fp(toFilePath(file));
- choose_file.file_path = fp;
- choose_file.display_name = fp.BaseName().value();
- return choose_file;
-}
-
-template <>
-inline base::FilePath fileListingHelper<base::FilePath>(const QString &file)
-{
- return base::FilePath(toFilePathString(file));
-}
-
-
-template <typename T>
-inline std::vector<T> toVector(const QStringList &fileList)
-{
- std::vector<T> selectedFiles;
- selectedFiles.reserve(fileList.size());
- for (const QString &file : fileList)
- selectedFiles.push_back(fileListingHelper<T>(file));
- return selectedFiles;
-}
-
int flagsFromModifiers(Qt::KeyboardModifiers modifiers);
-inline QStringList fromVector(const std::vector<base::string16> &vector)
+inline QStringList fromVector(const std::vector<std::u16string> &vector)
{
QStringList result;
for (auto s: vector) {
@@ -295,8 +253,6 @@ inline QStringList fromVector(const std::vector<base::string16> &vector)
return result;
}
-FaviconInfo toFaviconInfo(const content::FaviconURL &);
-
QList<QSslCertificate> toCertificateChain(net::X509Certificate *certificate);
Qt::InputMethodHints toQtInputMethodHints(ui::TextInputType inputType);
diff --git a/src/core/user_notification_controller.cpp b/src/core/user_notification_controller.cpp
index f94605a55..9c1122cca 100644
--- a/src/core/user_notification_controller.cpp
+++ b/src/core/user_notification_controller.cpp
@@ -1,48 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "user_notification_controller.h"
#include "type_conversion.h"
-#include "base/callback.h"
-#include "content/public/browser/notification_event_dispatcher.h"
#include "third_party/blink/public/mojom/notifications/notification.mojom-shared.h"
#include "third_party/blink/public/common/notifications/notification_resources.h"
#include "third_party/blink/public/common/notifications/platform_notification_data.h"
diff --git a/src/core/user_notification_controller.h b/src/core/user_notification_controller.h
index bab85c7ec..21d9fc653 100644
--- a/src/core/user_notification_controller.h
+++ b/src/core/user_notification_controller.h
@@ -1,50 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef DESKTOP_NOTIFICATION_CONTROLLER_H
#define DESKTOP_NOTIFICATION_CONTROLLER_H
-#include "qtwebenginecoreglobal.h"
+#include <QtWebEngineCore/qtwebenginecoreglobal.h>
-#include <QtCore/QSharedPointer>
-#include <QtCore/QUrl>
-#include <QtGui/QIcon>
+#include <QtCore/qsharedpointer.h>
+#include <QtCore/qurl.h>
+#include <QtGui/qimage.h>
class GURL;
diff --git a/src/core/user_script.cpp b/src/core/user_script.cpp
index 7ccb6e10a..c33fb9081 100644
--- a/src/core/user_script.cpp
+++ b/src/core/user_script.cpp
@@ -1,43 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "common/user_script_data.h"
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "base/strings/string_util.h"
+
+#include "qtwebengine/userscript/user_script_data.h"
#include "user_script.h"
#include "type_conversion.h"
@@ -54,7 +20,7 @@ bool GetDeclarationValue(const base::StringPiece& line,
std::string temp(line.data() + index + prefix.length(),
line.length() - index - prefix.length());
- if (temp.empty() || !base::IsUnicodeWhitespace(temp[0]))
+ if (temp.empty() || !base::IsWhitespace(temp[0]))
return false;
base::TrimWhitespaceASCII(temp, base::TRIM_ALL, value);
@@ -72,30 +38,19 @@ ASSERT_ENUMS_MATCH(UserScript::DocumentElementCreation, UserScriptData::Document
UserScript::UserScript()
: QSharedData()
{
+ static uint64_t idCount = 0;
+ m_scriptData.scriptId = idCount++;
}
-UserScript::UserScript(const UserScript &other)
- : QSharedData(other)
-{
- if (other.isNull())
- return;
- scriptData.reset(new UserScriptData(*other.scriptData));
- m_name = other.m_name;
-}
+UserScript::UserScript(const UserScript &other) = default;
-UserScript::~UserScript()
-{
-}
+UserScript::~UserScript() = default;
UserScript &UserScript::operator=(const UserScript &other)
{
- if (other.isNull()) {
- scriptData.reset();
- m_name = QString();
- return *this;
- }
- scriptData.reset(new UserScriptData(*other.scriptData));
+ m_scriptData = other.m_scriptData;
m_name = other.m_name;
+ m_url = other.m_url;
return *this;
}
@@ -107,101 +62,82 @@ QString UserScript::name() const
void UserScript::setName(const QString &name)
{
m_name = name;
- initData();
- scriptData->url = GURL(QStringLiteral("userScript:%1").arg(name).toStdString());
+ m_scriptData.url = GURL(QStringLiteral("userScript:%1").arg(name).toStdString());
}
QString UserScript::sourceCode() const
{
- if (isNull())
- return QString();
- return toQt(scriptData->source);
+ return toQt(m_scriptData.source);
}
void UserScript::setSourceCode(const QString &source)
{
- initData();
- scriptData->source = source.toStdString();
+ m_scriptData.source = source.toStdString();
parseMetadataHeader();
}
-UserScript::InjectionPoint UserScript::injectionPoint() const
+QUrl UserScript::sourceUrl() const
{
- if (isNull())
- return UserScript::AfterLoad;
- return static_cast<UserScript::InjectionPoint>(scriptData->injectionPoint);
+ return m_url;
}
-void UserScript::setInjectionPoint(UserScript::InjectionPoint p)
+void UserScript::setSourceUrl(const QUrl &url)
{
- initData();
- scriptData->injectionPoint = p;
+ m_url = url;
}
-uint UserScript::worldId() const
+UserScript::InjectionPoint UserScript::injectionPoint() const
{
- if (isNull())
- return 1;
- return scriptData->worldId;
+ return static_cast<UserScript::InjectionPoint>(m_scriptData.injectionPoint);
}
-void UserScript::setWorldId(uint id)
+void UserScript::setInjectionPoint(UserScript::InjectionPoint p)
{
- initData();
- scriptData->worldId = id;
+ m_scriptData.injectionPoint = p;
}
-bool UserScript::runsOnSubFrames() const
+quint32 UserScript::worldId() const
{
- if (isNull())
- return false;
- return scriptData->injectForSubframes;
+ return m_scriptData.worldId;
}
-void UserScript::setRunsOnSubFrames(bool on)
+void UserScript::setWorldId(quint32 id)
{
- initData();
- scriptData->injectForSubframes = on;
+ m_scriptData.worldId = id;
}
-bool UserScript::operator==(const UserScript &other) const
+bool UserScript::runsOnSubFrames() const
{
- if (isNull() != other.isNull())
- return false;
- if (isNull()) // neither is valid
- return true;
- return worldId() == other.worldId()
- && runsOnSubFrames() == other.runsOnSubFrames()
- && injectionPoint() == other.injectionPoint()
- && name() == other.name() && sourceCode() == other.sourceCode();
+ return m_scriptData.injectForSubframes;
}
-void UserScript::initData()
+void UserScript::setRunsOnSubFrames(bool on)
{
- if (scriptData.isNull())
- scriptData.reset(new UserScriptData);
+ m_scriptData.injectForSubframes = on;
}
-bool UserScript::isNull() const
+const UserScriptData &UserScript::data() const
{
- return scriptData.isNull();
+ return m_scriptData;
}
-UserScriptData &UserScript::data() const
+bool UserScript::operator==(const UserScript &other) const
{
- return *(scriptData.data());
+ return worldId() == other.worldId() && runsOnSubFrames() == other.runsOnSubFrames()
+ && injectionPoint() == other.injectionPoint() && name() == other.name()
+ && sourceCode() == other.sourceCode() && sourceUrl() == other.sourceUrl();
}
void UserScript::parseMetadataHeader()
{
// Clear previous values
- scriptData->globs.clear();
- scriptData->excludeGlobs.clear();
- scriptData->urlPatterns.clear();
+ m_scriptData.globs.clear();
+ m_scriptData.excludeGlobs.clear();
+ m_scriptData.urlPatterns.clear();
// Logic taken from Chromium (extensions/browser/user_script_loader.cc)
// http://wiki.greasespot.net/Metadata_block
- const std::string &script_text = scriptData->source;
+ const std::string &script_text = m_scriptData.source;
base::StringPiece line;
size_t line_start = 0;
size_t line_end = line_start;
@@ -228,13 +164,13 @@ void UserScript::parseMetadataHeader()
if (line_end == std::string::npos)
line_end = script_text.length() - 1;
- line.set(script_text.data() + line_start, line_end - line_start);
+ line = base::StringPiece(script_text.data() + line_start, line_end - line_start);
if (!in_metadata) {
- if (line.starts_with(kUserScriptBegin))
+ if (base::StartsWith(line, kUserScriptBegin))
in_metadata = true;
} else {
- if (line.starts_with(kUserScriptEnd))
+ if (base::StartsWith(line, kUserScriptEnd))
break;
std::string value;
@@ -247,7 +183,7 @@ void UserScript::parseMetadataHeader()
base::ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\");
base::ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?");
}
- scriptData->globs.push_back(value);
+ m_scriptData.globs.push_back(value);
} else if (GetDeclarationValue(line, kExcludeDeclaration, &value)) {
if (value.front() != '/' || value.back() != '/') {
// The greasemonkey spec only allows for wildcards (*), so
@@ -255,16 +191,16 @@ void UserScript::parseMetadataHeader()
base::ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\");
base::ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?");
}
- scriptData->excludeGlobs.push_back(value);
+ m_scriptData.excludeGlobs.push_back(value);
} else if (GetDeclarationValue(line, kMatchDeclaration, &value)) {
- scriptData->urlPatterns.push_back(value);
+ m_scriptData.urlPatterns.push_back(value);
} else if (GetDeclarationValue(line, kRunAtDeclaration, &value)) {
if (value == kRunAtDocumentStartValue)
- scriptData->injectionPoint = DocumentElementCreation;
+ m_scriptData.injectionPoint = DocumentElementCreation;
else if (value == kRunAtDocumentEndValue)
- scriptData->injectionPoint = DocumentLoadFinished;
+ m_scriptData.injectionPoint = DocumentLoadFinished;
else if (value == kRunAtDocumentIdleValue)
- scriptData->injectionPoint = AfterLoad;
+ m_scriptData.injectionPoint = AfterLoad;
}
}
@@ -273,8 +209,8 @@ void UserScript::parseMetadataHeader()
// If no patterns were specified, default to @include *. This is what
// Greasemonkey does.
- if (scriptData->globs.empty() && scriptData->urlPatterns.empty())
- scriptData->globs.push_back("*");
+ if (m_scriptData.globs.empty() && m_scriptData.urlPatterns.empty())
+ m_scriptData.globs.push_back("*");
}
} // namespace QtWebEngineCore
diff --git a/src/core/user_script.h b/src/core/user_script.h
index 8f65f4b74..fdc7782b8 100644
--- a/src/core/user_script.h
+++ b/src/core/user_script.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -53,17 +17,19 @@
#include "qtwebenginecoreglobal_p.h"
+#include "qtwebengine/userscript/user_script_data.h"
+
#include <QtCore/QScopedPointer>
#include <QtCore/QSharedData>
#include <QtCore/QString>
+#include <QtCore/QUrl>
-struct UserScriptData;
namespace QtWebEngineCore {
-
class UserResourceControllerHost;
-class Q_WEBENGINECORE_PRIVATE_EXPORT UserScript : public QSharedData {
+class UserScript : public QSharedData
+{
public:
enum InjectionPoint {
AfterLoad,
@@ -76,19 +42,20 @@ public:
~UserScript();
UserScript &operator=(const UserScript &other);
- bool isNull() const;
-
QString name() const;
void setName(const QString &);
QString sourceCode() const;
void setSourceCode(const QString &);
+ QUrl sourceUrl() const;
+ void setSourceUrl(const QUrl &);
+
InjectionPoint injectionPoint() const;
void setInjectionPoint(InjectionPoint);
- uint worldId() const;
- void setWorldId(uint id);
+ quint32 worldId() const;
+ void setWorldId(quint32 id);
bool runsOnSubFrames() const;
void setRunsOnSubFrames(bool on);
@@ -96,13 +63,13 @@ public:
bool operator==(const UserScript &) const;
private:
- void initData();
- UserScriptData &data() const;
+ const UserScriptData &data() const;
void parseMetadataHeader();
friend class UserResourceControllerHost;
- QScopedPointer<UserScriptData> scriptData;
+ UserScriptData m_scriptData;
QString m_name;
+ QUrl m_url;
};
} // namespace QtWebEngineCore
diff --git a/src/core/visited_links_manager_qt.cpp b/src/core/visited_links_manager_qt.cpp
index 37343cc39..9e1bd7a32 100644
--- a/src/core/visited_links_manager_qt.cpp
+++ b/src/core/visited_links_manager_qt.cpp
@@ -1,45 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "visited_links_manager_qt.h"
#include "content_browser_client_qt.h"
+#include "profile_adapter.h"
#include "profile_qt.h"
#include "type_conversion.h"
@@ -53,8 +18,8 @@ namespace {
class BasicUrlIterator : public visitedlink::VisitedLinkWriter::URLIterator {
public:
BasicUrlIterator(const QList<QUrl> &urls) : m_urls(urls) {}
- virtual const GURL& NextURL() { m_currentUrl = toGurl(m_urls.takeFirst()); return m_currentUrl; }
- virtual bool HasNextURL() const { return !m_urls.isEmpty(); }
+ const GURL &NextURL() override { m_currentUrl = toGurl(m_urls.takeFirst()); return m_currentUrl; }
+ bool HasNextURL() const override { return !m_urls.isEmpty(); }
private:
QList<QUrl> m_urls;
GURL m_currentUrl;
@@ -71,7 +36,7 @@ class VisitedLinkDelegateQt : public visitedlink::VisitedLinkDelegate
{
public:
~VisitedLinkDelegateQt() {}
- void RebuildTable(const scoped_refptr<URLEnumerator>& enumerator) { enumerator->OnComplete(true); }
+ void RebuildTable(const scoped_refptr<URLEnumerator> &enumerator) override { enumerator->OnComplete(true); }
};
void VisitedLinksManagerQt::deleteAllVisitedLinkData()
@@ -90,27 +55,12 @@ bool VisitedLinksManagerQt::containsUrl(const QUrl &url) const
return m_visitedLinkWriter->IsVisited(toGurl(url));
}
-static void ensureDirectoryExists(const base::FilePath &path)
-{
- if (base::PathExists(path))
- return;
-
- base::File::Error error;
- if (base::CreateDirectoryAndGetError(path, &error))
- return;
-
- std::string errorstr = base::File::ErrorToString(error);
- qWarning("Cannot create directory %s. Error: %s.",
- path.AsUTF8Unsafe().c_str(),
- errorstr.c_str());
-}
-
VisitedLinksManagerQt::VisitedLinksManagerQt(ProfileQt *profile, bool persistVisitedLinks)
: m_delegate(new VisitedLinkDelegateQt)
{
Q_ASSERT(profile);
if (persistVisitedLinks)
- ensureDirectoryExists(profile->GetPath());
+ profile->profileAdapter()->ensureDataPathExists();
m_visitedLinkWriter.reset(new visitedlink::VisitedLinkWriter(profile, m_delegate.data(), persistVisitedLinks));
m_visitedLinkWriter->Init();
}
diff --git a/src/core/visited_links_manager_qt.h b/src/core/visited_links_manager_qt.h
index c4e24ce1f..7bcf32d52 100644
--- a/src/core/visited_links_manager_qt.h
+++ b/src/core/visited_links_manager_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -55,9 +19,7 @@
#include <QList>
#include <QScopedPointer>
-QT_BEGIN_NAMESPACE
-class QUrl;
-QT_END_NAMESPACE
+QT_FORWARD_DECLARE_CLASS(QUrl)
namespace visitedlink {
class VisitedLinkWriter;
@@ -70,7 +32,7 @@ namespace QtWebEngineCore {
class ProfileQt;
class VisitedLinkDelegateQt;
-class Q_WEBENGINECORE_PRIVATE_EXPORT VisitedLinksManagerQt {
+class Q_WEBENGINECORE_EXPORT VisitedLinksManagerQt {
public:
virtual~VisitedLinksManagerQt();
diff --git a/src/core/web_contents_adapter.cpp b/src/core/web_contents_adapter.cpp
index e88c80bc8..6decf8780 100644
--- a/src/core/web_contents_adapter.cpp
+++ b/src/core/web_contents_adapter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,17 +7,19 @@
#include "web_contents_adapter.h"
+#include "autofill_client_qt.h"
+#include "content_browser_client_qt.h"
#include "devtools_frontend_qt.h"
#include "download_manager_delegate_qt.h"
+#include "favicon_driver_qt.h"
+#include "favicon_service_factory_qt.h"
+#include "find_text_helper.h"
#include "media_capture_devices_dispatcher.h"
-#if QT_CONFIG(webengine_printing_and_pdf)
-#include "printing/print_view_manager_qt.h"
-#endif
-#include "profile_adapter_client.h"
+#include "pdf_util_qt.h"
#include "profile_adapter.h"
#include "profile_qt.h"
-#include "qwebenginecallback_p.h"
-#include "renderer_host/render_view_observer_host_qt.h"
+#include "qwebengineloadinginfo.h"
+#include "renderer_host/web_engine_page_host.h"
#include "render_widget_host_view_qt.h"
#include "type_conversion.h"
#include "web_contents_view_qt.h"
@@ -61,39 +27,62 @@
#include "web_engine_settings.h"
#include "base/command_line.h"
-#include "base/run_loop.h"
-#include "base/task/post_task.h"
+#include "base/metrics/user_metrics.h"
+#include "base/task/current_thread.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/thread_controller_with_message_pump_impl.h"
#include "base/values.h"
+#include "chrome/browser/tab_contents/form_interaction_tab_helper.h"
+#include "components/autofill/core/browser/autofill_manager.h"
+#include "components/autofill/content/browser/content_autofill_driver_factory.h"
+#include "components/embedder_support/user_agent_utils.h"
+#include "components/favicon/core/favicon_service.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "content/browser/web_contents/web_contents_impl.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/navigation_entry.h"
+#include "content/public/browser/navigation_entry_restore_context.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/favicon_status.h"
-#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/drop_data.h"
-#include "content/public/common/page_state.h"
-#include "content/public/common/page_zoom.h"
#include "content/public/common/url_constants.h"
-#include "content/public/common/web_preferences.h"
#include "extensions/buildflags/buildflags.h"
-#include "third_party/blink/public/common/media/media_player_action.h"
#include "third_party/blink/public/common/page/page_zoom.h"
+#include "third_party/blink/public/common/page_state/page_state.h"
#include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
-#include "printing/buildflags/buildflags.h"
-#include "ui/base/clipboard/clipboard.h"
+#include "third_party/blink/public/common/web_preferences/web_preferences.h"
+#include "third_party/blink/public/mojom/frame/media_player_action.mojom.h"
#include "ui/base/clipboard/clipboard_constants.h"
#include "ui/base/clipboard/custom_data_helper.h"
#include "ui/gfx/font_render_params.h"
+#include "ui/native_theme/native_theme.h"
+#include "qtwebengine/browser/qtwebenginepage.mojom.h"
+
+#include <QtCore/QVariant>
+#include <QtCore/QElapsedTimer>
+#include <QtCore/QMimeData>
+#include <QtCore/QTemporaryDir>
+#include <QtGui/QDrag>
+#include <QtGui/QDragEnterEvent>
+#include <QtGui/QGuiApplication>
+#include <QtGui/QPageLayout>
+#include <QtGui/QPixmap>
+#include <QtGui/QStyleHints>
+
+#if QT_CONFIG(accessibility)
+#include "browser_accessibility_qt.h"
+#include "content/browser/accessibility/browser_accessibility_manager.h"
+#include <QtGui/qaccessible.h>
+#endif
+
+#if QT_CONFIG(webengine_printing_and_pdf)
+#include "printing/print_view_manager_qt.h"
+#endif
#if QT_CONFIG(webengine_webchannel)
#include "renderer_host/web_channel_ipc_transport_host.h"
@@ -104,39 +93,18 @@
#include "extensions/extension_web_contents_observer_qt.h"
#endif
-#include <QDir>
-#include <QGuiApplication>
-#include <QPageLayout>
-#include <QStringList>
-#include <QStyleHints>
-#include <QTimer>
-#include <QVariant>
-#include <QtCore/qelapsedtimer.h>
-#include <QtCore/qmimedata.h>
-#include <QtCore/qtemporarydir.h>
-#include <QtGui/qdrag.h>
-#include <QtGui/QDragEnterEvent>
-#include <QtGui/qpixmap.h>
-
-// Can't include headers as qaccessible.h conflicts with Chromium headers.
-namespace content {
-extern QAccessibleInterface *toQAccessibleInterface(BrowserAccessibility *acc);
-}
-
namespace QtWebEngineCore {
#define CHECK_INITIALIZED(return_value) \
if (!isInitialized()) \
return return_value
-#define CHECK_VALID_RENDER_WIDGET_HOST_VIEW(render_view_host) \
- if (!render_view_host->IsRenderViewLive() && render_view_host->GetWidget()->GetView()) { \
+#define CHECK_VALID_RENDER_WIDGET_HOST_VIEW(render_frame_host) \
+ if (!render_frame_host->IsRenderFrameLive() && render_frame_host->GetView()) { \
LOG(WARNING) << "Ignore navigation due to terminated render process with invalid RenderWidgetHostView."; \
return; \
}
-static const int kTestWindowWidth = 800;
-static const int kTestWindowHeight = 600;
static const int kHistoryStreamVersion = 4;
static QVariant fromJSValue(const base::Value *result)
@@ -147,57 +115,48 @@ static QVariant fromJSValue(const base::Value *result)
break;
case base::Value::Type::BOOLEAN:
{
- bool out;
- if (result->GetAsBoolean(&out))
- ret.setValue(out);
+ if (auto out = result->GetIfBool())
+ ret.setValue(*out);
break;
}
case base::Value::Type::INTEGER:
{
- int out;
- if (result->GetAsInteger(&out))
- ret.setValue(out);
+ if (auto out = result->GetIfInt())
+ ret.setValue(*out);
break;
}
case base::Value::Type::DOUBLE:
{
- double out;
- if (result->GetAsDouble(&out))
- ret.setValue(out);
+ if (auto out = result->GetIfDouble())
+ ret.setValue(*out);
break;
}
case base::Value::Type::STRING:
{
- base::string16 out;
- if (result->GetAsString(&out))
- ret.setValue(toQt(out));
+ if (auto out = result->GetIfString())
+ ret.setValue(toQt(*out));
break;
}
case base::Value::Type::LIST:
{
- const base::ListValue *out;
- if (result->GetAsList(&out)) {
+ if (const auto out = result->GetIfList()) {
+ size_t size = out->size();
QVariantList list;
- list.reserve(out->GetSize());
- for (size_t i = 0; i < out->GetSize(); ++i) {
- const base::Value *outVal = 0;
- if (out->Get(i, &outVal) && outVal)
- list.insert(i, fromJSValue(outVal));
+ list.reserve(size);
+ for (size_t i = 0; i < size; ++i) {
+ auto &outVal = (*out)[i];
+ list.insert(i, fromJSValue(&outVal));
}
ret.setValue(list);
}
break;
}
- case base::Value::Type::DICTIONARY:
+ case base::Value::Type::DICT:
{
- const base::DictionaryValue *out;
- if (result->GetAsDictionary(&out)) {
+ if (const auto dict = result->GetIfDict()) {
QVariantMap map;
- base::DictionaryValue::Iterator it(*out);
- while (!it.IsAtEnd()) {
- map.insert(toQt(it.key()), fromJSValue(&it.value()));
- it.Advance();
- }
+ for (const auto pair : *dict)
+ map.insert(toQt(pair.first), fromJSValue(&pair.second));
ret.setValue(map);
}
break;
@@ -241,7 +200,6 @@ static void callbackOnPdfSavingFinished(WebContentsAdapterClient *adapterClient,
static std::unique_ptr<content::WebContents> createBlankWebContents(WebContentsAdapterClient *adapterClient, content::BrowserContext *browserContext)
{
content::WebContents::CreateParams create_params(browserContext, nullptr);
- create_params.routing_id = MSG_ROUTING_NONE;
create_params.initially_hidden = true;
std::unique_ptr<content::WebContents> webContents = content::WebContents::Create(create_params);
@@ -251,10 +209,28 @@ static std::unique_ptr<content::WebContents> createBlankWebContents(WebContentsA
return webContents;
}
+static int navigationListSize(content::NavigationController &controller) {
+ // If we're currently on the initial NavigationEntry, no navigation has
+ // committed, so the initial NavigationEntry should not be part of the
+ // "Navigation List", and we should return 0 as the navigation list size.
+ if (controller.GetLastCommittedEntry()->IsInitialEntry())
+ return 0;
+ return controller.GetEntryCount();
+}
+
+static int navigationListCurrentIndex(content::NavigationController &controller) {
+ // If we're currently on the initial NavigationEntry, no navigation has
+ // committed, so the initial NavigationEntry should not be part of the
+ // "Navigation List", and we should return -1 as the current index.
+ if (controller.GetLastCommittedEntry()->IsInitialEntry())
+ return -1;
+ return controller.GetCurrentEntryIndex();
+}
+
static void serializeNavigationHistory(content::NavigationController &controller, QDataStream &output)
{
- const int currentIndex = controller.GetCurrentEntryIndex();
- const int count = controller.GetEntryCount();
+ const int currentIndex = navigationListCurrentIndex(controller);
+ const int count = navigationListSize(controller);
const int pendingIndex = controller.GetPendingEntryIndex();
output << kHistoryStreamVersion;
@@ -303,6 +279,8 @@ static void deserializeNavigationHistory(QDataStream &input, int *currentIndex,
int count;
input >> count >> *currentIndex;
+ std::unique_ptr<content::NavigationEntryRestoreContext> context = content::NavigationEntryRestoreContext::Create();
+
entries->reserve(count);
// Logic taken from SerializedNavigationEntry::ReadFromPickle and ToNavigationEntries.
for (int i = 0; i < count; ++i) {
@@ -342,7 +320,8 @@ static void deserializeNavigationHistory(QDataStream &input, int *currentIndex,
std::unique_ptr<content::NavigationEntry> entry = content::NavigationController::CreateNavigationEntry(
toGurl(virtualUrl),
content::Referrer(toGurl(referrerUrl), static_cast<network::mojom::ReferrerPolicy>(referrerPolicy)),
- base::nullopt, // optional initiator_origin
+ absl::nullopt, // optional initiator_origin
+ absl::nullopt, // optional initiator_base_url
// Use a transition type of reload so that we don't incorrectly
// increase the typed count.
ui::PAGE_TRANSITION_RELOAD,
@@ -353,7 +332,7 @@ static void deserializeNavigationHistory(QDataStream &input, int *currentIndex,
nullptr);
entry->SetTitle(toString16(title));
- entry->SetPageState(content::PageState::CreateFromEncodedData(std::string(pageState.data(), pageState.size())));
+ entry->SetPageState(blink::PageState::CreateFromEncodedData(std::string(pageState.data(), pageState.size())), context.get());
entry->SetHasPostData(hasPostData);
entry->SetOriginalRequestURL(toGurl(originalRequestUrl));
entry->SetIsOverridingUserAgent(isOverridingUserAgent);
@@ -371,15 +350,18 @@ static void deserializeNavigationHistory(QDataStream &input, int *currentIndex,
}
}
-static void Navigate(WebContentsAdapter *adapter, const content::NavigationController::LoadURLParams &params)
+namespace {
+
+void Navigate(WebContentsAdapter *adapter, const content::NavigationController::LoadURLParams &params)
{
Q_ASSERT(adapter);
adapter->webContents()->GetController().LoadURLWithParams(params);
adapter->focusIfNecessary();
adapter->resetSelection();
+ adapter->findTextHelper()->stopFinding();
}
-static void NavigateTask(QWeakPointer<WebContentsAdapter> weakAdapter, const content::NavigationController::LoadURLParams &params)
+void NavigateTask(QWeakPointer<WebContentsAdapter> weakAdapter, const content::NavigationController::LoadURLParams &params)
{
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const auto adapter = weakAdapter.toStrongRef();
@@ -388,7 +370,6 @@ static void NavigateTask(QWeakPointer<WebContentsAdapter> weakAdapter, const con
Navigate(adapter.get(), params);
}
-namespace {
static QList<WebContentsAdapter *> recursive_guard_loading_adapters;
class LoadRecursionGuard {
@@ -424,52 +405,30 @@ QSharedPointer<WebContentsAdapter> WebContentsAdapter::createFromSerializedNavig
// Unlike WebCore, Chromium only supports Restoring to a new WebContents instance.
std::unique_ptr<content::WebContents> newWebContents = createBlankWebContents(adapterClient, adapterClient->profileAdapter()->profile());
content::NavigationController &controller = newWebContents->GetController();
- controller.Restore(currentIndex, content::RestoreType::LAST_SESSION_EXITED_CLEANLY, &entries);
-
- if (controller.GetActiveEntry()) {
- // Set up the file access rights for the selected navigation entry.
- // TODO(joth): This is duplicated from chrome/.../session_restore.cc and
- // should be shared e.g. in NavigationController. http://crbug.com/68222
- const int id = newWebContents->GetMainFrame()->GetProcess()->GetID();
- const content::PageState& pageState = controller.GetActiveEntry()->GetPageState();
- const std::vector<base::FilePath>& filePaths = pageState.GetReferencedFiles();
- for (std::vector<base::FilePath>::const_iterator file = filePaths.begin(); file != filePaths.end(); ++file)
- content::ChildProcessSecurityPolicy::GetInstance()->GrantReadFile(id, *file);
- }
+ controller.Restore(currentIndex, content::RestoreType::kRestored, &entries);
return QSharedPointer<WebContentsAdapter>::create(std::move(newWebContents));
}
-WebContentsAdapter::WebContentsAdapter()
+WebContentsAdapter::WebContentsAdapter(std::unique_ptr<content::WebContents> webContents)
: m_profileAdapter(nullptr)
- , m_webContents(nullptr)
+ , m_webContents(std::move(webContents))
#if QT_CONFIG(webengine_webchannel)
, m_webChannel(nullptr)
, m_webChannelWorld(0)
#endif
, m_adapterClient(nullptr)
- , m_nextRequestId(CallbackDirectory::ReservedCallbackIdsEnd)
- , m_currentDropAction(blink::kWebDragOperationNone)
+ , m_nextRequestId(1)
+ , m_currentDropAction(blink::kDragOperationNone)
, m_devToolsFrontend(nullptr)
{
// This has to be the first thing we create, and the last we destroy.
WebEngineContext::current();
}
-WebContentsAdapter::WebContentsAdapter(std::unique_ptr<content::WebContents> webContents)
- : m_profileAdapter(nullptr)
- , m_webContents(std::move(webContents))
-#if QT_CONFIG(webengine_webchannel)
- , m_webChannel(nullptr)
- , m_webChannelWorld(0)
-#endif
- , m_adapterClient(nullptr)
- , m_nextRequestId(CallbackDirectory::ReservedCallbackIdsEnd)
- , m_currentDropAction(blink::kWebDragOperationNone)
- , m_devToolsFrontend(nullptr)
+WebContentsAdapter::WebContentsAdapter()
+ : WebContentsAdapter(nullptr)
{
- // This has to be the first thing we create, and the last we destroy.
- WebEngineContext::current();
}
WebContentsAdapter::~WebContentsAdapter()
@@ -487,7 +446,7 @@ void WebContentsAdapter::setClient(WebContentsAdapterClient *adapterClient)
Q_ASSERT(m_profileAdapter);
// This might replace any adapter that has been initialized with this WebEngineSettings.
- adapterClient->webEngineSettings()->setWebContentsAdapter(this);
+ WebEngineSettings::get(adapterClient->webEngineSettings())->setWebContentsAdapter(this);
}
bool WebContentsAdapter::isInitialized() const
@@ -495,6 +454,10 @@ bool WebContentsAdapter::isInitialized() const
return (bool)m_webContentsDelegate;
}
+ui::NativeTheme::PreferredColorScheme toWeb(Qt::ColorScheme colorScheme) {
+ return colorScheme == Qt::ColorScheme::Dark ? ui::NativeTheme::PreferredColorScheme::kDark : ui::NativeTheme::PreferredColorScheme::kLight;
+}
+
void WebContentsAdapter::initialize(content::SiteInstance *site)
{
Q_ASSERT(m_adapterClient);
@@ -511,7 +474,7 @@ void WebContentsAdapter::initialize(content::SiteInstance *site)
// Create and attach observers to the WebContents.
m_webContentsDelegate.reset(new WebContentsDelegateQt(m_webContents.get(), m_adapterClient));
- m_renderViewObserverHost.reset(new RenderViewObserverHostQt(m_webContents.get(), m_adapterClient));
+ m_pageHost.reset(new WebEnginePageHost(m_webContents.get(), m_adapterClient));
// Let the WebContent's view know about the WebContentsAdapterClient.
WebContentsViewQt* contentsView = static_cast<WebContentsViewQt*>(static_cast<content::WebContentsImpl*>(m_webContents.get())->GetView());
@@ -527,6 +490,12 @@ void WebContentsAdapter::initialize(content::SiteInstance *site)
extensions::ExtensionWebContentsObserverQt::CreateForWebContents(webContents());
#endif
+ content::BrowserContext *context = webContents()->GetBrowserContext();
+ FaviconDriverQt::CreateForWebContents(
+ webContents(), FaviconServiceFactoryQt::GetForBrowserContext(context), m_adapterClient);
+
+ AutofillClientQt::CreateForWebContents(webContents());
+
// Create an instance of WebEngineVisitedLinksManager to catch the first
// content::NOTIFICATION_RENDERER_PROCESS_CREATED event. This event will
// force to initialize visited links in VisitedLinkSlave.
@@ -536,24 +505,32 @@ void WebContentsAdapter::initialize(content::SiteInstance *site)
// Create a RenderView with the initial empty document
content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
Q_ASSERT(rvh);
- if (!rvh->IsRenderViewLive())
- static_cast<content::WebContentsImpl*>(m_webContents.get())->CreateRenderViewForRenderManager(rvh, MSG_ROUTING_NONE, MSG_ROUTING_NONE, base::UnguessableToken::Create(), content::FrameReplicationState());
+ if (!m_webContents->GetPrimaryMainFrame()->IsRenderFrameLive())
+ static_cast<content::WebContentsImpl*>(m_webContents.get())->CreateRenderViewForRenderManager(
+ rvh, absl::nullopt, nullptr);
m_webContentsDelegate->RenderViewHostChanged(nullptr, rvh);
+ // Make sure the system theme's light/dark mode is propagated to webpages
+ QObject::connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, [](Qt::ColorScheme colorScheme){
+ ui::NativeTheme::GetInstanceForWeb()->set_preferred_color_scheme(toWeb(colorScheme));
+ });
+ ui::NativeTheme::GetInstanceForWeb()->set_preferred_color_scheme(toWeb(QGuiApplication::styleHints()->colorScheme()));
+
m_adapterClient->initializationFinished();
}
void WebContentsAdapter::initializeRenderPrefs()
{
- blink::mojom::RendererPreferences *rendererPrefs = m_webContents->GetMutableRendererPrefs();
+ blink::RendererPreferences *rendererPrefs = m_webContents->GetMutableRendererPrefs();
rendererPrefs->use_custom_colors = true;
// Qt returns a flash time (the whole cycle) in ms, chromium expects just the interval in
// seconds
const int qtCursorFlashTime = QGuiApplication::styleHints()->cursorFlashTime();
rendererPrefs->caret_blink_interval =
- base::TimeDelta::FromMillisecondsD(0.5 * static_cast<double>(qtCursorFlashTime));
- rendererPrefs->user_agent_override = m_profileAdapter->httpUserAgent().toStdString();
+ base::Milliseconds(0.5 * static_cast<double>(qtCursorFlashTime));
+ rendererPrefs->user_agent_override = blink::UserAgentOverride::UserAgentOnly(m_profileAdapter->httpUserAgent().toStdString());
+ rendererPrefs->user_agent_override.ua_metadata_override = profile()->userAgentMetadata();
rendererPrefs->accept_languages = m_profileAdapter->httpAcceptLanguageWithoutQualities().toStdString();
#if QT_CONFIG(webengine_webrtc)
base::CommandLine* commandLine = base::CommandLine::ForCurrentProcess();
@@ -562,10 +539,13 @@ void WebContentsAdapter::initializeRenderPrefs()
commandLine->GetSwitchValueASCII(switches::kForceWebRtcIPHandlingPolicy);
else
rendererPrefs->webrtc_ip_handling_policy =
- m_adapterClient->webEngineSettings()->testAttribute(WebEngineSettings::WebRTCPublicInterfacesOnly)
+ m_adapterClient->webEngineSettings()->testAttribute(
+ QWebEngineSettings::WebRTCPublicInterfacesOnly)
? blink::kWebRTCIPHandlingDefaultPublicInterfaceOnly
: blink::kWebRTCIPHandlingDefault;
#endif
+ rendererPrefs->can_accept_load_drops = m_adapterClient->webEngineSettings()->testAttribute(QWebEngineSettings::NavigateOnDropEnabled);
+
// Set web-contents font settings to the default font settings as Chromium constantly overrides
// the global font defaults with the font settings of the latest web-contents created.
static const gfx::FontRenderParams params = gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr);
@@ -599,8 +579,9 @@ bool WebContentsAdapter::canGoToOffset(int offset) const
void WebContentsAdapter::stop()
{
CHECK_INITIALIZED();
- content::NavigationController& controller = m_webContents->GetController();
+ base::RecordAction(base::UserMetricsAction("Stop"));
+ content::NavigationController& controller = m_webContents->GetController();
int index = controller.GetPendingEntryIndex();
if (index != -1)
controller.RemoveEntryAtIndex(index);
@@ -612,10 +593,12 @@ void WebContentsAdapter::stop()
void WebContentsAdapter::reload()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Reload"));
+
bool wasDiscarded = (m_lifecycleState == LifecycleState::Discarded);
setLifecycleState(LifecycleState::Active);
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
- WebEngineSettings *settings = m_adapterClient->webEngineSettings();
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
+ WebEngineSettings *settings = WebEngineSettings::get(m_adapterClient->webEngineSettings());
settings->doApply();
if (!wasDiscarded) // undiscard() already triggers a reload
m_webContents->GetController().Reload(content::ReloadType::NORMAL, /*checkRepost = */false);
@@ -625,10 +608,12 @@ void WebContentsAdapter::reload()
void WebContentsAdapter::reloadAndBypassCache()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("ReloadBypassingCache"));
+
bool wasDiscarded = (m_lifecycleState == LifecycleState::Discarded);
setLifecycleState(LifecycleState::Active);
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
- WebEngineSettings *settings = m_adapterClient->webEngineSettings();
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
+ WebEngineSettings *settings = WebEngineSettings::get(m_adapterClient->webEngineSettings());
settings->doApply();
if (!wasDiscarded) // undiscard() already triggers a reload
m_webContents->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /*checkRepost = */false);
@@ -649,6 +634,7 @@ void WebContentsAdapter::load(const QUrl &url)
void WebContentsAdapter::load(const QWebEngineHttpRequest &request)
{
+ base::RecordAction(base::UserMetricsAction("LoadURL"));
GURL gurl = toGurl(request.url());
if (!isInitialized()) {
scoped_refptr<content::SiteInstance> site =
@@ -658,10 +644,9 @@ void WebContentsAdapter::load(const QWebEngineHttpRequest &request)
setLifecycleState(LifecycleState::Active);
}
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
- WebEngineSettings *settings = m_adapterClient->webEngineSettings();
- settings->doApply();
+ WebEngineSettings::get(m_adapterClient->webEngineSettings())->doApply();
// The situation can occur when relying on the editingFinished signal in QML to set the url
// of the WebView.
@@ -702,10 +687,11 @@ void WebContentsAdapter::load(const QWebEngineHttpRequest &request)
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
// chromium accepts LOAD_TYPE_HTTP_POST only for the HTTP and HTTPS protocols
if (!params.url.SchemeIsHTTPOrHTTPS()) {
- m_adapterClient->loadFinished(false, request.url(), false,
- net::ERR_DISALLOWED_URL_SCHEME,
- QCoreApplication::translate("WebContentsAdapter",
- "HTTP-POST data can only be sent over HTTP(S) protocol"));
+ m_adapterClient->loadFinished(QWebEngineLoadingInfo(
+ request.url(), QWebEngineLoadingInfo::LoadFailedStatus, false,
+ QCoreApplication::translate("WebContentsAdapter",
+ "HTTP-POST data can only be sent over HTTP(S) protocol"),
+ net::ERR_DISALLOWED_URL_SCHEME));
return;
}
params.post_data = network::ResourceRequestBody::CreateFromBytes(
@@ -715,8 +701,8 @@ void WebContentsAdapter::load(const QWebEngineHttpRequest &request)
}
// convert the custom headers into the format that chromium expects
- QVector<QByteArray> headers = request.headers();
- for (QVector<QByteArray>::const_iterator it = headers.cbegin(); it != headers.cend(); ++it) {
+ QList<QByteArray> headers = request.headers();
+ for (QList<QByteArray>::const_iterator it = headers.cbegin(); it != headers.cend(); ++it) {
if (params.extra_headers.length() > 0)
params.extra_headers += '\n';
params.extra_headers += (*it).toStdString() + ": " + request.header(*it).toStdString();
@@ -732,7 +718,7 @@ void WebContentsAdapter::load(const QWebEngineHttpRequest &request)
if (resizeNeeded) {
// Schedule navigation on the event loop.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
base::BindOnce(&NavigateTask, sharedFromThis().toWeakRef(), std::move(params)));
} else {
Navigate(this, params);
@@ -746,10 +732,9 @@ void WebContentsAdapter::setContent(const QByteArray &data, const QString &mimeT
else
setLifecycleState(LifecycleState::Active);
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
- WebEngineSettings *settings = m_adapterClient->webEngineSettings();
- settings->doApply();
+ WebEngineSettings::get(m_adapterClient->webEngineSettings())->doApply();
QByteArray encodedData = data.toPercentEncoding();
std::string urlString;
@@ -761,7 +746,8 @@ void WebContentsAdapter::setContent(const QByteArray &data, const QString &mimeT
GURL dataUrlToLoad(urlString);
if (dataUrlToLoad.spec().size() > url::kMaxURLChars) {
- m_adapterClient->loadFinished(false, baseUrl, false, net::ERR_ABORTED);
+ m_adapterClient->loadFinished(QWebEngineLoadingInfo(baseUrl, QWebEngineLoadingInfo::LoadFailedStatus,
+ false, QString(), net::ERR_ABORTED));
return;
}
content::NavigationController::LoadURLParams params((dataUrlToLoad));
@@ -777,7 +763,8 @@ void WebContentsAdapter::setContent(const QByteArray &data, const QString &mimeT
void WebContentsAdapter::save(const QString &filePath, int savePageFormat)
{
CHECK_INITIALIZED();
- m_webContentsDelegate->setSavePageInfo(SavePageInfo(filePath, savePageFormat));
+ base::RecordAction(base::UserMetricsAction("SavePage"));
+ m_webContentsDelegate->setSavePageInfo(new SavePageInfo(filePath, savePageFormat));
m_webContents->OnSavePage();
}
@@ -806,12 +793,15 @@ QUrl WebContentsAdapter::requestedUrl() const
QUrl WebContentsAdapter::iconUrl() const
{
CHECK_INITIALIZED(QUrl());
- if (content::NavigationEntry* entry = m_webContents->GetController().GetVisibleEntry()) {
- content::FaviconStatus &favicon = entry->GetFavicon();
- if (favicon.valid)
- return toQt(favicon.url);
- }
- return QUrl();
+ FaviconDriverQt *driver = FaviconDriverQt::FromWebContents(webContents());
+ return toQt(driver->GetFaviconURL());
+}
+
+QIcon WebContentsAdapter::icon() const
+{
+ CHECK_INITIALIZED(QIcon());
+ FaviconDriverQt *driver = FaviconDriverQt::FromWebContents(webContents());
+ return toQIcon(driver->GetFavicon());
}
QString WebContentsAdapter::pageTitle() const
@@ -831,42 +821,49 @@ QString WebContentsAdapter::selectedText() const
void WebContentsAdapter::undo()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Undo"));
m_webContents->Undo();
}
void WebContentsAdapter::redo()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Redo"));
m_webContents->Redo();
}
void WebContentsAdapter::cut()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Cut"));
m_webContents->Cut();
}
void WebContentsAdapter::copy()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Copy"));
m_webContents->Copy();
}
void WebContentsAdapter::paste()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("Paste"));
m_webContents->Paste();
}
void WebContentsAdapter::pasteAndMatchStyle()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
m_webContents->PasteAndMatchStyle();
}
void WebContentsAdapter::selectAll()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("SelectAll"));
m_webContents->SelectAll();
}
@@ -885,7 +882,8 @@ void WebContentsAdapter::unselect()
void WebContentsAdapter::navigateBack()
{
CHECK_INITIALIZED();
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ base::RecordAction(base::UserMetricsAction("Back"));
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
if (!m_webContents->GetController().CanGoBack())
return;
m_webContents->GetController().GoBack();
@@ -895,7 +893,8 @@ void WebContentsAdapter::navigateBack()
void WebContentsAdapter::navigateForward()
{
CHECK_INITIALIZED();
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ base::RecordAction(base::UserMetricsAction("Forward"));
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
if (!m_webContents->GetController().CanGoForward())
return;
m_webContents->GetController().GoForward();
@@ -905,7 +904,7 @@ void WebContentsAdapter::navigateForward()
void WebContentsAdapter::navigateToIndex(int offset)
{
CHECK_INITIALIZED();
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
m_webContents->GetController().GoToIndex(offset);
focusIfNecessary();
}
@@ -913,7 +912,7 @@ void WebContentsAdapter::navigateToIndex(int offset)
void WebContentsAdapter::navigateToOffset(int offset)
{
CHECK_INITIALIZED();
- CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetRenderViewHost());
+ CHECK_VALID_RENDER_WIDGET_HOST_VIEW(m_webContents->GetPrimaryMainFrame());
m_webContents->GetController().GoToOffset(offset);
focusIfNecessary();
}
@@ -921,13 +920,13 @@ void WebContentsAdapter::navigateToOffset(int offset)
int WebContentsAdapter::navigationEntryCount()
{
CHECK_INITIALIZED(0);
- return m_webContents->GetController().GetEntryCount();
+ return navigationListSize(m_webContents->GetController());
}
int WebContentsAdapter::currentNavigationEntryIndex()
{
CHECK_INITIALIZED(0);
- return m_webContents->GetController().GetCurrentEntryIndex();
+ return navigationListCurrentIndex(m_webContents->GetController());
}
QUrl WebContentsAdapter::getNavigationEntryOriginalUrl(int index)
@@ -991,9 +990,8 @@ void WebContentsAdapter::setZoomFactor(qreal factor)
content::HostZoomMap *zoomMap = content::HostZoomMap::GetForWebContents(m_webContents.get());
if (zoomMap) {
- int render_process_id = m_webContents->GetMainFrame()->GetProcess()->GetID();
- int render_view_id = m_webContents->GetRenderViewHost()->GetRoutingID();
- zoomMap->SetTemporaryZoomLevel(render_process_id, render_view_id, zoomLevel);
+ const content::GlobalRenderFrameHostId global_id = m_webContents->GetPrimaryMainFrame()->GetGlobalId();
+ zoomMap->SetTemporaryZoomLevel(global_id, zoomLevel);
}
}
@@ -1029,15 +1027,13 @@ QWebEngineUrlRequestInterceptor* WebContentsAdapter::requestInterceptor() const
QAccessibleInterface *WebContentsAdapter::browserAccessible()
{
CHECK_INITIALIZED(nullptr);
- content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
- Q_ASSERT(rvh);
- content::RenderFrameHostImpl *rfh = static_cast<content::RenderFrameHostImpl *>(rvh->GetMainFrame());
+ content::RenderFrameHostImpl *rfh = static_cast<content::RenderFrameHostImpl *>(m_webContents->GetPrimaryMainFrame());
if (!rfh)
return nullptr;
content::BrowserAccessibilityManager *manager = rfh->GetOrCreateBrowserAccessibilityManager();
if (!manager) // FIXME!
return nullptr;
- content::BrowserAccessibility *acc = manager->GetRoot();
+ content::BrowserAccessibility *acc = manager->GetFromAXNode(manager->GetRoot());
return content::toQAccessibleInterface(acc);
}
@@ -1046,58 +1042,63 @@ QAccessibleInterface *WebContentsAdapter::browserAccessible()
void WebContentsAdapter::runJavaScript(const QString &javaScript, quint32 worldId)
{
CHECK_INITIALIZED();
- content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
- Q_ASSERT(rvh);
-// static_cast<content::RenderFrameHostImpl *>(rvh->GetMainFrame())->NotifyUserActivation();
- if (worldId == 0) {
- rvh->GetMainFrame()->ExecuteJavaScript(toString16(javaScript), base::NullCallback());
+ content::RenderFrameHost *rfh = m_webContents->GetPrimaryMainFrame();
+ Q_ASSERT(rfh);
+ if (!static_cast<content::RenderFrameHostImpl*>(rfh)->GetAssociatedLocalFrame()) {
+ qWarning() << "Local frame is gone, not running script";
return;
}
-
- content::RenderFrameHost::JavaScriptResultCallback callback = base::BindOnce(&callbackOnEvaluateJS, m_adapterClient, CallbackDirectory::NoCallbackId);
- rvh->GetMainFrame()->ExecuteJavaScriptInIsolatedWorld(toString16(javaScript), std::move(callback), worldId);
+ if (worldId == 0)
+ rfh->ExecuteJavaScript(toString16(javaScript), base::NullCallback());
+ else
+ rfh->ExecuteJavaScriptInIsolatedWorld(toString16(javaScript), base::NullCallback(), worldId);
}
quint64 WebContentsAdapter::runJavaScriptCallbackResult(const QString &javaScript, quint32 worldId)
{
CHECK_INITIALIZED(0);
- content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
- Q_ASSERT(rvh);
-// static_cast<content::RenderFrameHostImpl *>(rvh->GetMainFrame())->NotifyUserActivation();
+ content::RenderFrameHost *rfh = m_webContents->GetPrimaryMainFrame();
+ Q_ASSERT(rfh);
+ if (!static_cast<content::RenderFrameHostImpl*>(rfh)->GetAssociatedLocalFrame()) {
+ qWarning() << "Local frame is gone, not running script";
+ return 0;
+ }
content::RenderFrameHost::JavaScriptResultCallback callback = base::BindOnce(&callbackOnEvaluateJS, m_adapterClient, m_nextRequestId);
if (worldId == 0)
- rvh->GetMainFrame()->ExecuteJavaScript(toString16(javaScript), std::move(callback));
+ rfh->ExecuteJavaScript(toString16(javaScript), std::move(callback));
else
- rvh->GetMainFrame()->ExecuteJavaScriptInIsolatedWorld(toString16(javaScript), std::move(callback), worldId);
+ rfh->ExecuteJavaScriptInIsolatedWorld(toString16(javaScript), std::move(callback), worldId);
return m_nextRequestId++;
}
quint64 WebContentsAdapter::fetchDocumentMarkup()
{
CHECK_INITIALIZED(0);
- m_renderViewObserverHost->fetchDocumentMarkup(m_nextRequestId);
+ m_pageHost->FetchDocumentMarkup(m_nextRequestId);
return m_nextRequestId++;
}
quint64 WebContentsAdapter::fetchDocumentInnerText()
{
CHECK_INITIALIZED(0);
- m_renderViewObserverHost->fetchDocumentInnerText(m_nextRequestId);
+ m_pageHost->FetchDocumentInnerText(m_nextRequestId);
return m_nextRequestId++;
}
-void WebContentsAdapter::updateWebPreferences(const content::WebPreferences & webPreferences)
+void WebContentsAdapter::updateWebPreferences(const blink::web_pref::WebPreferences &webPreferences)
{
CHECK_INITIALIZED();
- m_webContents->GetRenderViewHost()->UpdateWebkitPreferences(webPreferences);
+ m_webContents->SetWebPreferences(webPreferences);
// In case of updating preferences during navigation, there might be a pending RVH what will
// be active on successful navigation.
- content::RenderFrameHost *pendingRFH = (static_cast<content::WebContentsImpl*>(m_webContents.get()))->GetPendingMainFrame();
+ content::RenderFrameHost *pendingRFH =
+ (static_cast<content::WebContentsImpl*>(m_webContents.get()))
+ ->GetPrimaryFrameTree().root()->render_manager()->speculative_frame_host();
if (pendingRFH) {
content::RenderViewHost *pendingRVH = pendingRFH->GetRenderViewHost();
Q_ASSERT(pendingRVH);
- pendingRVH->UpdateWebkitPreferences(webPreferences);
+ static_cast<content::RenderViewHostImpl*>(pendingRVH)->SendWebPreferencesToRenderer();
}
}
@@ -1107,13 +1108,12 @@ void WebContentsAdapter::download(const QUrl &url, const QString &suggestedFileN
{
CHECK_INITIALIZED();
content::BrowserContext *bctx = m_webContents->GetBrowserContext();
- content::DownloadManager *dlm = content::BrowserContext::GetDownloadManager(bctx);
+ content::DownloadManager *dlm = bctx->GetDownloadManager();
DownloadManagerDelegateQt *dlmd = m_profileAdapter->downloadManagerDelegate();
if (!dlm)
return;
- dlmd->markNextDownloadAsUserRequested();
dlm->SetDelegate(dlmd);
net::NetworkTrafficAnnotationTag traffic_annotation =
@@ -1173,7 +1173,7 @@ qint64 WebContentsAdapter::renderProcessPid() const
{
CHECK_INITIALIZED(0);
- content::RenderProcessHost *renderProcessHost = m_webContents->GetMainFrame()->GetProcess();
+ content::RenderProcessHost *renderProcessHost = m_webContents->GetPrimaryMainFrame()->GetProcess();
const base::Process &process = renderProcessHost->GetProcess();
if (!process.IsValid())
return 0;
@@ -1183,25 +1183,25 @@ qint64 WebContentsAdapter::renderProcessPid() const
void WebContentsAdapter::copyImageAt(const QPoint &location)
{
CHECK_INITIALIZED();
- m_webContents->GetRenderViewHost()->GetMainFrame()->CopyImageAt(location.x(), location.y());
+ m_webContents->GetPrimaryMainFrame()->CopyImageAt(location.x(), location.y());
}
-static blink::MediaPlayerAction::Type toBlinkMediaPlayerActionType(WebContentsAdapter::MediaPlayerAction action)
+static blink::mojom::MediaPlayerActionType toBlinkMediaPlayerActionType(WebContentsAdapter::MediaPlayerAction action)
{
switch (action) {
case WebContentsAdapter::MediaPlayerPlay:
- return blink::MediaPlayerAction::Type::kPlay;
+ return blink::mojom::MediaPlayerActionType::kPlay;
case WebContentsAdapter::MediaPlayerMute:
- return blink::MediaPlayerAction::Type::kMute;
+ return blink::mojom::MediaPlayerActionType::kMute;
case WebContentsAdapter::MediaPlayerLoop:
- return blink::MediaPlayerAction::Type::kLoop;
+ return blink::mojom::MediaPlayerActionType::kLoop;
case WebContentsAdapter::MediaPlayerControls:
- return blink::MediaPlayerAction::Type::kControls;
+ return blink::mojom::MediaPlayerActionType::kControls;
case WebContentsAdapter::MediaPlayerNoAction:
break;
}
NOTREACHED();
- return (blink::MediaPlayerAction::Type)-1;
+ return (blink::mojom::MediaPlayerActionType)-1;
}
void WebContentsAdapter::executeMediaPlayerActionAt(const QPoint &location, MediaPlayerAction action, bool enable)
@@ -1209,8 +1209,8 @@ void WebContentsAdapter::executeMediaPlayerActionAt(const QPoint &location, Medi
CHECK_INITIALIZED();
if (action == MediaPlayerNoAction)
return;
- blink::MediaPlayerAction blinkAction(toBlinkMediaPlayerActionType(action), enable);
- m_webContents->GetRenderViewHost()->GetMainFrame()->ExecuteMediaPlayerActionAtLocation(toGfx(location), blinkAction);
+ blink::mojom::MediaPlayerAction blinkAction(toBlinkMediaPlayerActionType(action), enable);
+ m_webContents->GetPrimaryMainFrame()->ExecuteMediaPlayerActionAtLocation(toGfx(location), blinkAction);
}
void WebContentsAdapter::inspectElementAt(const QPoint &location)
@@ -1261,7 +1261,10 @@ void WebContentsAdapter::openDevToolsFrontend(QSharedPointer<WebContentsAdapter>
setLifecycleState(LifecycleState::Active);
- m_devToolsFrontend = DevToolsFrontendQt::Show(frontendAdapter, m_webContents.get());
+ content::WebContents *webContents = m_webContents.get();
+ if (content::WebContents *guest = guestWebContents())
+ webContents = guest;
+ m_devToolsFrontend = DevToolsFrontendQt::Show(frontendAdapter, webContents);
updateRecommendedState();
}
@@ -1281,15 +1284,22 @@ void WebContentsAdapter::devToolsFrontendDestroyed(DevToolsFrontendQt *frontend)
updateRecommendedState();
}
+QString WebContentsAdapter::devToolsId()
+{
+ return QString::fromStdString(DevToolsFrontendQt::GetId(m_webContents.get()));
+}
+
void WebContentsAdapter::exitFullScreen()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("ToggleFullscreen"));
m_webContents->ExitFullscreen(false);
}
void WebContentsAdapter::changedFullScreen()
{
CHECK_INITIALIZED();
+ base::RecordAction(base::UserMetricsAction("ToggleFullscreen"));
m_webContents->NotifyFullscreenChanged(false);
}
@@ -1305,33 +1315,42 @@ void WebContentsAdapter::wasHidden()
m_webContents->WasHidden();
}
-void WebContentsAdapter::printToPDF(const QPageLayout &pageLayout, const QString &filePath)
+void WebContentsAdapter::printToPDF(const QPageLayout &pageLayout, const QPageRanges &pageRanges, const QString &filePath)
{
#if QT_CONFIG(webengine_printing_and_pdf)
CHECK_INITIALIZED();
- PrintViewManagerQt::PrintToPDFFileCallback callback = base::Bind(&callbackOnPdfSavingFinished,
- m_adapterClient,
- filePath);
- PrintViewManagerQt::FromWebContents(m_webContents.get())->PrintToPDFFileWithCallback(pageLayout,
- true,
- filePath,
- callback);
+ PrintViewManagerQt::PrintToPDFFileCallback callback = base::BindOnce(&callbackOnPdfSavingFinished,
+ m_adapterClient,
+ filePath);
+ content::WebContents *webContents = m_webContents.get();
+ if (content::WebContents *guest = guestWebContents())
+ webContents = guest;
+ PrintViewManagerQt::FromWebContents(webContents)->PrintToPDFFileWithCallback(pageLayout,
+ pageRanges,
+ true,
+ filePath,
+ std::move(callback));
#endif // QT_CONFIG(webengine_printing_and_pdf)
}
quint64 WebContentsAdapter::printToPDFCallbackResult(const QPageLayout &pageLayout,
+ const QPageRanges &pageRanges,
bool colorMode,
bool useCustomMargins)
{
#if QT_CONFIG(webengine_printing_and_pdf)
CHECK_INITIALIZED(0);
- PrintViewManagerQt::PrintToPDFCallback callback = base::Bind(&callbackOnPrintingFinished,
- m_adapterClient,
- m_nextRequestId);
- PrintViewManagerQt::FromWebContents(m_webContents.get())->PrintToPDFWithCallback(pageLayout,
- colorMode,
- useCustomMargins,
- callback);
+ PrintViewManagerQt::PrintToPDFCallback callback = base::BindOnce(&callbackOnPrintingFinished,
+ m_adapterClient,
+ m_nextRequestId);
+ content::WebContents *webContents = m_webContents.get();
+ if (content::WebContents *guest = guestWebContents())
+ webContents = guest;
+ PrintViewManagerQt::FromWebContents(webContents)->PrintToPDFWithCallback(pageLayout,
+ pageRanges,
+ colorMode,
+ useCustomMargins,
+ std::move(callback));
return m_nextRequestId++;
#else
Q_UNUSED(pageLayout);
@@ -1376,7 +1395,7 @@ void WebContentsAdapter::grantFeaturePermission(const QUrl &securityOrigin, Prof
void WebContentsAdapter::grantMouseLockPermission(const QUrl &securityOrigin, bool granted)
{
CHECK_INITIALIZED();
- if (securityOrigin != toQt(m_webContents->GetLastCommittedURL().GetOrigin()))
+ if (securityOrigin != toQt(m_webContents->GetLastCommittedURL().DeprecatedGetOriginAsURL()))
return;
if (granted) {
@@ -1394,15 +1413,17 @@ void WebContentsAdapter::grantMouseLockPermission(const QUrl &securityOrigin, bo
granted = false;
}
- m_webContents->GotResponseToLockMouseRequest(granted);
+ m_webContents->GotResponseToLockMouseRequest(granted ? blink::mojom::PointerLockResult::kSuccess
+ : blink::mojom::PointerLockResult::kPermissionDenied);
}
void WebContentsAdapter::handlePendingMouseLockPermission()
{
CHECK_INITIALIZED();
- auto it = m_pendingMouseLockPermissions.find(toQt(m_webContents->GetLastCommittedURL().GetOrigin()));
+ auto it = m_pendingMouseLockPermissions.find(toQt(m_webContents->GetLastCommittedURL().DeprecatedGetOriginAsURL()));
if (it != m_pendingMouseLockPermissions.end()) {
- m_webContents->GotResponseToLockMouseRequest(it.value());
+ m_webContents->GotResponseToLockMouseRequest(it.value() ? blink::mojom::PointerLockResult::kSuccess
+ : blink::mojom::PointerLockResult::kPermissionDenied);
m_pendingMouseLockPermissions.erase(it);
}
}
@@ -1410,8 +1431,13 @@ void WebContentsAdapter::handlePendingMouseLockPermission()
void WebContentsAdapter::setBackgroundColor(const QColor &color)
{
CHECK_INITIALIZED();
- if (content::RenderWidgetHostView *rwhv = m_webContents->GetRenderWidgetHostView())
- rwhv->SetBackgroundColor(toSk(color));
+ SkColor c = toSk(color);
+ if (content::RenderWidgetHostView *rwhv = m_webContents->GetRenderWidgetHostView()) {
+ rwhv->SetBackgroundColor(c);
+ ((content::RenderWidgetHostViewBase *)rwhv)->SetContentBackgroundColor(c);
+ }
+ if (color != Qt::transparent)
+ m_pageHost->SetBackgroundColor(c);
}
content::WebContents *WebContentsAdapter::webContents() const
@@ -1419,6 +1445,12 @@ content::WebContents *WebContentsAdapter::webContents() const
return m_webContents.get();
}
+content::WebContents *WebContentsAdapter::guestWebContents() const
+{
+ std::vector<content::WebContents *> innerWebContents = m_webContents->GetInnerWebContents();
+ return !innerWebContents.empty() ? innerWebContents[0] : nullptr;
+}
+
#if QT_CONFIG(webengine_webchannel)
QWebChannel *WebContentsAdapter::webChannel() const
{
@@ -1455,12 +1487,14 @@ void WebContentsAdapter::setWebChannel(QWebChannel *channel, uint worldId)
static QMimeData *mimeDataFromDropData(const content::DropData &dropData)
{
QMimeData *mimeData = new QMimeData();
- if (!dropData.text.is_null())
- mimeData->setText(toQt(dropData.text.string()));
- if (!dropData.html.is_null())
- mimeData->setHtml(toQt(dropData.html.string()));
- if (dropData.url.is_valid())
+ if (dropData.text.has_value())
+ mimeData->setText(toQt(*dropData.text));
+ if (dropData.html.has_value())
+ mimeData->setHtml(toQt(*dropData.html));
+ if (dropData.url.is_valid()) {
mimeData->setUrls(QList<QUrl>() << toQt(dropData.url));
+ mimeData->setText(toQt(dropData.url_title));
+ }
if (!dropData.custom_data.empty()) {
base::Pickle pickle;
ui::WriteCustomDataToPickle(dropData.custom_data, &pickle);
@@ -1469,16 +1503,16 @@ static QMimeData *mimeDataFromDropData(const content::DropData &dropData)
return mimeData;
}
-static blink::WebDragOperationsMask toWeb(const Qt::DropActions action)
+static blink::DragOperationsMask toWeb(const Qt::DropActions action)
{
- int result = blink::kWebDragOperationNone;
+ int result = blink::kDragOperationNone;
if (action & Qt::CopyAction)
- result |= blink::kWebDragOperationCopy;
+ result |= blink::kDragOperationCopy;
if (action & Qt::LinkAction)
- result |= blink::kWebDragOperationLink;
+ result |= blink::kDragOperationLink;
if (action & Qt::MoveAction)
- result |= blink::kWebDragOperationMove;
- return static_cast<blink::WebDragOperationsMask>(result);
+ result |= blink::kDragOperationMove;
+ return static_cast<blink::DragOperationsMask>(result);
}
void WebContentsAdapter::startDragging(QObject *dragSource, const content::DropData &dropData,
@@ -1497,7 +1531,7 @@ void WebContentsAdapter::startDragging(QObject *dragSource, const content::DropD
m_currentDropData->file_contents.clear();
m_currentDropData->file_contents_content_disposition.clear();
- m_currentDropAction = blink::kWebDragOperationNone;
+ m_currentDropAction = blink::kDragOperationNone;
QDrag *drag = new QDrag(dragSource); // will be deleted by Qt's DnD implementation
bool dValid = true;
QMetaObject::Connection onDestroyed = QObject::connect(dragSource, &QObject::destroyed, [&dValid](){
@@ -1515,18 +1549,26 @@ void WebContentsAdapter::startDragging(QObject *dragSource, const content::DropD
}
{
- base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
+ base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
drag->exec(allowedActions);
}
QObject::disconnect(onDestroyed);
if (dValid) {
if (m_webContents) {
- content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
+ // This is the quickest and (at the moment) the most safe solution to not break guest views when
+ // dropping data into them. We don't even try to support dropping into PDF input fields,
+ // since it's not working in Chrome right now.
+ content::WebContents *targetWebContents = m_webContents.get();
+ if (content::WebContents *guest = guestWebContents())
+ targetWebContents = guest;
+
+ content::RenderViewHost *rvh = targetWebContents->GetRenderViewHost();
if (rvh) {
rvh->GetWidget()->DragSourceEndedAt(gfx::PointF(m_lastDragClientPos.x(), m_lastDragClientPos.y()),
gfx::PointF(m_lastDragScreenPos.x(), m_lastDragScreenPos.y()),
- blink::WebDragOperation(m_currentDropAction));
+ ui::mojom::DragOperation(m_currentDropAction),
+ base::DoNothing());
rvh->GetWidget()->DragSourceSystemDragEnded();
}
}
@@ -1577,23 +1619,28 @@ static void fillDropDataFromMimeData(content::DropData *dropData, const QMimeDat
}
if (!dropData->filenames.empty())
return;
+ if (!urls.empty()) {
+ dropData->url = toGurl(urls.first());
+ if (mimeData->hasText())
+ dropData->url_title = toString16(mimeData->text());
+ }
if (mimeData->hasHtml())
- dropData->html = toNullableString16(mimeData->html());
+ dropData->html = toOptionalString16(mimeData->html());
if (mimeData->hasText())
- dropData->text = toNullableString16(mimeData->text());
+ dropData->text = toOptionalString16(mimeData->text());
if (mimeData->hasFormat(QLatin1String(ui::kMimeTypeWebCustomData))) {
QByteArray customData = mimeData->data(QLatin1String(ui::kMimeTypeWebCustomData));
ui::ReadCustomDataIntoMap(customData.constData(), customData.length(), &dropData->custom_data);
}
}
-Qt::DropAction toQt(blink::WebDragOperation op)
+Qt::DropAction toQt(ui::mojom::DragOperation op)
{
- if (op & blink::kWebDragOperationCopy)
+ if (int(op) & int(ui::mojom::DragOperation::kCopy))
return Qt::CopyAction;
- if (op & blink::kWebDragOperationLink)
+ if (int(op) & int(ui::mojom::DragOperation::kLink))
return Qt::LinkAction;
- if (op & blink::kWebDragOperationMove || op & blink::kWebDragOperationDelete)
+ if (int(op) & int(ui::mojom::DragOperation::kMove))
return Qt::MoveAction;
return Qt::IgnoreAction;
}
@@ -1636,21 +1683,22 @@ void WebContentsAdapter::enterDrag(QDragEnterEvent *e, const QPointF &screenPos)
content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
rvh->GetWidget()->FilterDropData(m_currentDropData.get());
- rvh->GetWidget()->DragTargetDragEnter(*m_currentDropData, toGfx(e->posF()), toGfx(screenPos),
+ rvh->GetWidget()->DragTargetDragEnter(*m_currentDropData, toGfx(e->position()), toGfx(screenPos),
toWeb(e->possibleActions()),
- toWeb(e->mouseButtons()) | toWeb(e->keyboardModifiers()));
+ toWeb(e->buttons()) | toWeb(e->modifiers()),
+ base::DoNothing());
}
Qt::DropAction WebContentsAdapter::updateDragPosition(QDragMoveEvent *e, const QPointF &screenPos)
{
CHECK_INITIALIZED(Qt::DropAction());
content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
- m_lastDragClientPos = e->posF();
+ m_lastDragClientPos = e->position();
m_lastDragScreenPos = screenPos;
rvh->GetWidget()->DragTargetDragOver(toGfx(m_lastDragClientPos), toGfx(m_lastDragScreenPos), toWeb(e->possibleActions()),
- toWeb(e->mouseButtons()) | toWeb(e->keyboardModifiers()));
+ toWeb(e->buttons()) | toWeb(e->modifiers()), base::DoNothing());
waitForUpdateDragActionCalled();
- return toQt(blink::WebDragOperation(m_currentDropAction));
+ return toQt(ui::mojom::DragOperation(m_currentDropAction));
}
void WebContentsAdapter::waitForUpdateDragActionCalled()
@@ -1659,7 +1707,7 @@ void WebContentsAdapter::waitForUpdateDragActionCalled()
const qint64 timeout = 3000;
QElapsedTimer t;
t.start();
- auto seqMan = base::MessageLoopCurrent::GetCurrentSequenceManagerImpl();
+ auto seqMan = base::CurrentThread::GetCurrentSequenceManagerImpl();
base::MessagePump::Delegate *delegate =
static_cast<base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl *>(
seqMan->controller_.get());
@@ -1667,7 +1715,7 @@ void WebContentsAdapter::waitForUpdateDragActionCalled()
DCHECK(delegate);
m_updateDragActionCalled = false;
for (;;) {
- while (delegate->DoWork() && !m_updateDragActionCalled) {}
+ while (delegate->DoWork().is_immediate() && !m_updateDragActionCalled) {}
if (m_updateDragActionCalled)
break;
if (t.hasExpired(timeout)) {
@@ -1675,7 +1723,7 @@ void WebContentsAdapter::waitForUpdateDragActionCalled()
static_cast<int>(timeout));
return;
}
- base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1));
+ base::PlatformThread::Sleep(base::Milliseconds(1));
}
}
@@ -1683,7 +1731,7 @@ void WebContentsAdapter::updateDragAction(int action)
{
CHECK_INITIALIZED();
m_updateDragActionCalled = true;
- m_currentDropAction = static_cast<blink::WebDragOperation>(action);
+ m_currentDropAction = action;
}
void WebContentsAdapter::endDragging(QDropEvent *e, const QPointF &screenPos)
@@ -1691,10 +1739,10 @@ void WebContentsAdapter::endDragging(QDropEvent *e, const QPointF &screenPos)
CHECK_INITIALIZED();
content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
rvh->GetWidget()->FilterDropData(m_currentDropData.get());
- m_lastDragClientPos = e->posF();
+ m_lastDragClientPos = e->position();
m_lastDragScreenPos = screenPos;
rvh->GetWidget()->DragTargetDrop(*m_currentDropData, toGfx(m_lastDragClientPos), toGfx(m_lastDragScreenPos),
- toWeb(e->mouseButtons()) | toWeb(e->keyboardModifiers()));
+ toWeb(e->buttons()) | toWeb(e->modifiers()), base::DoNothing());
m_currentDropData.reset();
}
@@ -1719,8 +1767,8 @@ void WebContentsAdapter::replaceMisspelling(const QString &word)
void WebContentsAdapter::focusIfNecessary()
{
CHECK_INITIALIZED();
- const WebEngineSettings *settings = m_adapterClient->webEngineSettings();
- bool focusOnNavigation = settings->testAttribute(WebEngineSettings::FocusOnNavigationEnabled);
+ const QWebEngineSettings *settings = m_adapterClient->webEngineSettings();
+ bool focusOnNavigation = settings->testAttribute(QWebEngineSettings::FocusOnNavigationEnabled);
if (focusOnNavigation)
m_webContents->Focus();
}
@@ -1738,8 +1786,104 @@ void WebContentsAdapter::resetSelection()
if (auto rwhv = static_cast<RenderWidgetHostViewQt *>(m_webContents->GetRenderWidgetHostView())) {
if (auto mgr = rwhv->GetTextInputManager())
if (auto selection = const_cast<content::TextInputManager::TextSelection *>(mgr->GetTextSelection(rwhv)))
- selection->SetSelection(base::string16(), 0, gfx::Range(), false);
+ selection->SetSelection(std::u16string(), 0, gfx::Range(), false);
+ }
+}
+
+void WebContentsAdapter::resetTouchSelectionController()
+{
+ CHECK_INITIALIZED();
+ unselect();
+ if (auto rwhv = static_cast<RenderWidgetHostViewQt *>(m_webContents->GetRenderWidgetHostView()))
+ rwhv->resetTouchSelectionController();
+}
+
+void WebContentsAdapter::changeTextDirection(bool leftToRight)
+{
+ CHECK_INITIALIZED();
+ if (auto rwhv = static_cast<RenderWidgetHostViewQt *>(m_webContents->GetRenderWidgetHostView())) {
+ auto textInputManager = rwhv->GetTextInputManager();
+ if (!textInputManager)
+ return;
+ if (auto activeWidget = textInputManager->GetActiveWidget()) {
+ activeWidget->UpdateTextDirection(leftToRight ? base::i18n::TextDirection::LEFT_TO_RIGHT : base::i18n::TextDirection::RIGHT_TO_LEFT);
+ activeWidget->NotifyTextDirection();
+ }
+ }
+}
+
+quint64 WebContentsAdapter::mainFrameId() const
+{
+ CHECK_INITIALIZED(content::RenderFrameHost::kNoFrameTreeNodeId);
+ return static_cast<quint64>(m_webContents->GetPrimaryMainFrame()->GetFrameTreeNodeId());
+}
+
+#define CHECK_INITIALIZED_AND_VALID_FRAME(webengine_frame_id_variable, frame_tree_node_variable, \
+ return_value) \
+ CHECK_INITIALIZED(return_value); \
+ if (webengine_frame_id_variable == kInvalidFrameId) \
+ return return_value; \
+ auto *frame_tree_node_variable = content::FrameTreeNode::GloballyFindByID( \
+ static_cast<int>(webengine_frame_id_variable)); \
+ if (!frame_tree_node_variable) \
+ return return_value
+
+QString WebContentsAdapter::frameName(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, QString());
+ return QString::fromStdString(ftn->frame_name());
+}
+
+QString WebContentsAdapter::frameHtmlName(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, QString());
+ auto &maybeName = ftn->html_name();
+ return maybeName ? QString::fromStdString(*maybeName) : QString("");
+}
+
+QList<quint64> WebContentsAdapter::frameChildren(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, {});
+ QList<quint64> result;
+ size_t numChildren = ftn->child_count();
+ result.reserve(numChildren);
+ for (size_t i = 0; i < numChildren; ++i) {
+ result.push_back(ftn->child_at(i)->frame_tree_node_id());
}
+ return result;
+}
+
+QUrl WebContentsAdapter::frameUrl(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, QUrl());
+ return toQt(ftn->current_url());
+}
+
+QSizeF WebContentsAdapter::frameSize(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, QSizeF());
+ auto *rfh = ftn->current_frame_host();
+ Q_ASSERT(rfh);
+ auto maybeSize = rfh->GetFrameSize();
+ return maybeSize ? toQt(*maybeSize) : QSizeF();
+}
+
+std::optional<quint64> WebContentsAdapter::findFrameIdByName(const QString &name) const
+{
+ CHECK_INITIALIZED({});
+ auto *ftn = content::FrameTreeNode::From(m_webContents->GetPrimaryMainFrame());
+ Q_ASSERT(ftn);
+ if (auto *foundFtn = ftn->frame_tree().FindByName(name.toStdString()))
+ return foundFtn->frame_tree_node_id();
+ return {};
+}
+
+bool WebContentsAdapter::hasFrame(quint64 id) const
+{
+ CHECK_INITIALIZED_AND_VALID_FRAME(id, ftn, false);
+ auto *rfh = ftn->current_frame_host();
+ Q_ASSERT(rfh);
+ return content::WebContents::FromRenderFrameHost(rfh) == m_webContents.get();
}
WebContentsAdapterClient::RenderProcessTerminationStatus
@@ -1750,18 +1894,20 @@ WebContentsAdapterClient::renderProcessExitStatus(int terminationStatus) {
status = WebContentsAdapterClient::NormalTerminationStatus;
break;
case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
+ case base::TERMINATION_STATUS_LAUNCH_FAILED:
status = WebContentsAdapterClient::AbnormalTerminationStatus;
break;
case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
-#if defined(OS_CHROMEOS)
- case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
-#endif
+ case base::TERMINATION_STATUS_OOM:
status = WebContentsAdapterClient::KilledTerminationStatus;
break;
case base::TERMINATION_STATUS_PROCESS_CRASHED:
-#if defined(OS_ANDROID)
+#if BUILDFLAG(IS_ANDROID)
case base::TERMINATION_STATUS_OOM_PROTECTED:
#endif
+#if BUILDFLAG(IS_WIN)
+ case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
+#endif
status = WebContentsAdapterClient::CrashedTerminationStatus;
break;
case base::TERMINATION_STATUS_STILL_RUNNING:
@@ -1773,12 +1919,6 @@ WebContentsAdapterClient::renderProcessExitStatus(int terminationStatus) {
return status;
}
-FaviconManager *WebContentsAdapter::faviconManager()
-{
- CHECK_INITIALIZED(nullptr);
- return m_webContentsDelegate->faviconManager();
-}
-
FindTextHelper *WebContentsAdapter::findTextHelper()
{
CHECK_INITIALIZED(nullptr);
@@ -1788,7 +1928,8 @@ FindTextHelper *WebContentsAdapter::findTextHelper()
void WebContentsAdapter::viewSource()
{
CHECK_INITIALIZED();
- m_webContents->GetMainFrame()->ViewSource();
+ base::RecordAction(base::UserMetricsAction("ViewSource"));
+ m_webContents->GetPrimaryMainFrame()->ViewSource();
}
bool WebContentsAdapter::canViewSource()
@@ -1894,13 +2035,13 @@ WebContentsAdapter::LifecycleState WebContentsAdapter::determineRecommendedState
return LifecycleState::Frozen;
// Form input is not saved.
- if (m_webContents->GetPageImportanceSignals().had_form_interaction)
+ if (FormInteractionTabHelper::FromWebContents(m_webContents.get())->had_form_interaction())
return LifecycleState::Frozen;
// Do not discard PDFs as they might contain entry that is not saved and they
// don't remember their scrolling positions. See crbug.com/547286 and
// crbug.com/65244.
- if (m_webContents->GetContentsMimeType() == "application/pdf")
+ if (m_webContents->GetContentsMimeType() == kPDFMimeType)
return LifecycleState::Frozen;
return LifecycleState::Discarded;
@@ -1960,6 +2101,7 @@ void WebContentsAdapter::discard()
if (m_webContents->IsLoading()) {
m_webContentsDelegate->didFailLoad(m_webContentsDelegate->url(webContents()), net::Error::ERR_ABORTED,
QStringLiteral("Discarded"));
+ m_webContentsDelegate->DidStopLoading();
}
content::WebContents::CreateParams createParams(m_profileAdapter->profile());
@@ -1974,7 +2116,7 @@ void WebContentsAdapter::discard()
nullContents->SetWasDiscarded(true);
// Kill render process if this is the only page it's got.
- content::RenderProcessHost *renderProcessHost = m_webContents->GetMainFrame()->GetProcess();
+ content::RenderProcessHost *renderProcessHost = m_webContents->GetPrimaryMainFrame()->GetProcess();
renderProcessHost->FastShutdownIfPossible(/* page_count */ 1u,
/* skip_unload_handlers */ false);
@@ -1985,14 +2127,14 @@ void WebContentsAdapter::discard()
m_webChannel = nullptr;
m_webChannelWorld = 0;
#endif
- m_renderViewObserverHost.reset();
+ m_pageHost.reset();
m_webContentsDelegate.reset();
m_webContents.reset();
m_webContents = std::move(nullContents);
initializeRenderPrefs();
m_webContentsDelegate = std::move(nullDelegate);
- m_renderViewObserverHost.reset(new RenderViewObserverHostQt(m_webContents.get(), m_adapterClient));
+ m_pageHost.reset(new WebEnginePageHost(m_webContents.get(), m_adapterClient));
WebContentsViewQt *contentsView =
static_cast<WebContentsViewQt *>(static_cast<content::WebContentsImpl *>(m_webContents.get())->GetView());
contentsView->setClient(m_adapterClient);
@@ -2011,11 +2153,9 @@ void WebContentsAdapter::undiscard()
// Create a RenderView with the initial empty document
content::RenderViewHost *rvh = m_webContents->GetRenderViewHost();
Q_ASSERT(rvh);
- if (!rvh->IsRenderViewLive())
+ if (!m_webContents->GetPrimaryMainFrame()->IsRenderFrameLive())
static_cast<content::WebContentsImpl *>(m_webContents.get())
- ->CreateRenderViewForRenderManager(rvh, MSG_ROUTING_NONE, MSG_ROUTING_NONE,
- base::UnguessableToken::Create(),
- content::FrameReplicationState());
+ ->CreateRenderViewForRenderManager(rvh, absl::nullopt, nullptr);
m_webContentsDelegate->RenderViewHostChanged(nullptr, rvh);
m_adapterClient->initializationFinished();
m_adapterClient->selectionChanged();
@@ -2038,9 +2178,9 @@ ASSERT_ENUMS_MATCH(ReferrerPolicy::NoReferrerWhenDowngrade, network::mojom::Refe
ASSERT_ENUMS_MATCH(ReferrerPolicy::Never, network::mojom::ReferrerPolicy::kNever)
ASSERT_ENUMS_MATCH(ReferrerPolicy::Origin, network::mojom::ReferrerPolicy::kOrigin)
ASSERT_ENUMS_MATCH(ReferrerPolicy::OriginWhenCrossOrigin, network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin)
-ASSERT_ENUMS_MATCH(ReferrerPolicy::NoReferrerWhenDowngradeOriginWhenCrossOrigin, network::mojom::ReferrerPolicy::kNoReferrerWhenDowngradeOriginWhenCrossOrigin)
+//ASSERT_ENUMS_MATCH(ReferrerPolicy::NoReferrerWhenDowngradeOriginWhenCrossOrigin, network::mojom::ReferrerPolicy::kNoReferrerWhenDowngradeOriginWhenCrossOrigin)
ASSERT_ENUMS_MATCH(ReferrerPolicy::SameOrigin, network::mojom::ReferrerPolicy::kSameOrigin)
ASSERT_ENUMS_MATCH(ReferrerPolicy::StrictOrigin, network::mojom::ReferrerPolicy::kStrictOrigin)
-ASSERT_ENUMS_MATCH(ReferrerPolicy::Last, network::mojom::ReferrerPolicy::kLast)
+ASSERT_ENUMS_MATCH(ReferrerPolicy::Last, network::mojom::ReferrerPolicy::kMaxValue)
} // namespace QtWebEngineCore
diff --git a/src/core/web_contents_adapter.h b/src/core/web_contents_adapter.h
index d833314f2..a5cad8664 100644
--- a/src/core/web_contents_adapter.h
+++ b/src/core/web_contents_adapter.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,22 +15,29 @@
#ifndef WEB_CONTENTS_ADAPTER_H
#define WEB_CONTENTS_ADAPTER_H
-#include "qtwebenginecoreglobal_p.h"
-#include "web_contents_adapter_client.h"
-#include <memory>
+#include <QtCore/QSharedPointer>
+#include <QtCore/QString>
+#include <QtCore/QUrl>
+#include <QtCore/QPointer>
#include <QtGui/qtgui-config.h>
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+#include <QtWebEngineCore/qwebenginecontextmenurequest.h>
#include <QtWebEngineCore/qwebenginehttprequest.h>
+#include <QtWebEngineCore/qwebengineframe.h>
+
+#include "web_contents_adapter_client.h"
-#include <QScopedPointer>
-#include <QSharedPointer>
-#include <QString>
-#include <QUrl>
-#include <QPointer>
+#include <memory>
+#include <optional>
+
+namespace blink {
+namespace web_pref {
+struct WebPreferences;
+}
+}
namespace content {
class WebContents;
-struct WebPreferences;
-struct OpenURLParams;
class SiteInstance;
}
@@ -77,7 +48,7 @@ class QDragMoveEvent;
class QDropEvent;
class QMimeData;
class QPageLayout;
-class QString;
+class QPageRanges;
class QTemporaryDir;
class QWebChannel;
class QWebEngineUrlRequestInterceptor;
@@ -86,16 +57,16 @@ QT_END_NAMESPACE
namespace QtWebEngineCore {
class DevToolsFrontendQt;
-class FaviconManager;
class FindTextHelper;
-class MessagePassingInterface;
class ProfileQt;
-class RenderViewObserverHostQt;
+class WebEnginePageHost;
class WebChannelIPCTransportHost;
-class WebEngineContext;
-class Q_WEBENGINECORE_PRIVATE_EXPORT WebContentsAdapter : public QEnableSharedFromThis<WebContentsAdapter> {
+class Q_WEBENGINECORE_EXPORT WebContentsAdapter : public QEnableSharedFromThis<WebContentsAdapter> {
public:
+ // Sentinel to indicate a frame doesn't exist, for example with `findFrameByName`
+ static constexpr quint64 kInvalidFrameId = -3;
+
static QSharedPointer<WebContentsAdapter> createFromSerializedNavigationHistory(QDataStream &input, WebContentsAdapterClient *adapterClient);
WebContentsAdapter();
WebContentsAdapter(std::unique_ptr<content::WebContents> webContents);
@@ -132,6 +103,7 @@ public:
QString pageTitle() const;
QString selectedText() const;
QUrl iconUrl() const;
+ QIcon icon() const;
void undo();
void redo();
@@ -161,7 +133,7 @@ public:
quint64 runJavaScriptCallbackResult(const QString &javaScript, quint32 worldId);
quint64 fetchDocumentMarkup();
quint64 fetchDocumentInnerText();
- void updateWebPreferences(const content::WebPreferences &webPreferences);
+ void updateWebPreferences(const blink::web_pref::WebPreferences &webPreferences);
void download(const QUrl &url, const QString &suggestedFileName,
const QUrl &referrerUrl = QUrl(),
ReferrerPolicy referrerPolicy = ReferrerPolicy::Default);
@@ -192,6 +164,7 @@ public:
void openDevToolsFrontend(QSharedPointer<WebContentsAdapter> devtoolsFrontend);
void closeDevToolsFrontend();
void devToolsFrontendDestroyed(DevToolsFrontendQt *frontend);
+ QString devToolsId();
void grantMediaAccessPermission(const QUrl &securityOrigin, WebContentsAdapterClient::MediaRequestFlags flags);
void grantMouseLockPermission(const QUrl &securityOrigin, bool granted);
@@ -205,8 +178,8 @@ public:
#if QT_CONFIG(webengine_webchannel)
QWebChannel *webChannel() const;
void setWebChannel(QWebChannel *, uint worldId);
+ WebChannelIPCTransportHost *webChannelTransport() { return m_webChannelTransport.get(); }
#endif
- FaviconManager *faviconManager();
FindTextHelper *findTextHelper();
QPointF lastScrollOffset() const;
@@ -221,8 +194,8 @@ public:
void endDragging(QDropEvent *e, const QPointF &screenPos);
void leaveDrag();
#endif // QT_CONFIG(draganddrop)
- void printToPDF(const QPageLayout&, const QString&);
- quint64 printToPDFCallbackResult(const QPageLayout &,
+ void printToPDF(const QPageLayout&, const QPageRanges &, const QString&);
+ quint64 printToPDFCallbackResult(const QPageLayout &, const QPageRanges &,
bool colorMode = true,
bool useCustomMargins = true);
@@ -233,10 +206,22 @@ public:
bool isFindTextInProgress() const;
bool hasFocusedFrame() const;
void resetSelection();
+ void resetTouchSelectionController();
+ void changeTextDirection(bool leftToRight);
+
+ quint64 mainFrameId() const;
+ QString frameName(quint64 id) const;
+ QString frameHtmlName(quint64 id) const;
+ QList<quint64> frameChildren(quint64 id) const;
+ QUrl frameUrl(quint64 id) const;
+ QSizeF frameSize(quint64 id) const;
+ std::optional<quint64> findFrameIdByName(const QString &name) const;
+ bool hasFrame(quint64 id) const;
// meant to be used within WebEngineCore only
void initialize(content::SiteInstance *site);
content::WebContents *webContents() const;
+ content::WebContents *guestWebContents() const;
void updateRecommendedState();
void setRequestInterceptor(QWebEngineUrlRequestInterceptor *interceptor);
QWebEngineUrlRequestInterceptor* requestInterceptor() const;
@@ -261,7 +246,7 @@ private:
ProfileAdapter *m_profileAdapter;
std::unique_ptr<content::WebContents> m_webContents;
std::unique_ptr<WebContentsDelegateQt> m_webContentsDelegate;
- std::unique_ptr<RenderViewObserverHostQt> m_renderViewObserverHost;
+ std::unique_ptr<WebEnginePageHost> m_pageHost;
#if QT_CONFIG(webengine_webchannel)
std::unique_ptr<WebChannelIPCTransportHost> m_webChannelTransport;
QWebChannel *m_webChannel;
diff --git a/src/core/web_contents_adapter_client.h b/src/core/web_contents_adapter_client.h
index 78040cc8d..a1ad301ed 100644
--- a/src/core/web_contents_adapter_client.h
+++ b/src/core/web_contents_adapter_client.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,26 +15,28 @@
#ifndef WEB_CONTENTS_ADAPTER_CLIENT_H
#define WEB_CONTENTS_ADAPTER_CLIENT_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
#include "profile_adapter.h"
#include <QFlags>
#include <QRect>
-#include <QSharedPointer>
#include <QString>
#include <QStringList>
#include <QUrl>
-QT_FORWARD_DECLARE_CLASS(CertificateErrorController)
-QT_FORWARD_DECLARE_CLASS(ClientCertSelectController)
QT_FORWARD_DECLARE_CLASS(QKeyEvent)
QT_FORWARD_DECLARE_CLASS(QVariant)
+QT_FORWARD_DECLARE_CLASS(QWebEngineFileSystemAccessRequest)
QT_FORWARD_DECLARE_CLASS(QWebEngineFindTextResult)
-QT_FORWARD_DECLARE_CLASS(QWebEngineQuotaRequest)
+QT_FORWARD_DECLARE_CLASS(QWebEngineLoadingInfo)
QT_FORWARD_DECLARE_CLASS(QWebEngineRegisterProtocolHandlerRequest)
QT_FORWARD_DECLARE_CLASS(QWebEngineUrlRequestInfo)
QT_FORWARD_DECLARE_CLASS(QWebEngineUrlRequestInterceptor)
+QT_FORWARD_DECLARE_CLASS(QWebEngineContextMenuRequest)
+QT_FORWARD_DECLARE_CLASS(QWebEngineCertificateError)
+QT_FORWARD_DECLARE_CLASS(QWebEngineSettings)
+QT_FORWARD_DECLARE_CLASS(QWebEngineWebAuthUxRequest)
namespace content {
struct DropData;
@@ -78,293 +44,24 @@ struct DropData;
namespace QtWebEngineCore {
+class AutofillPopupController;
+class CertificateErrorController;
+class ClientCertSelectController;
class AuthenticationDialogController;
class ColorChooserController;
+class DesktopMediaController;
class FilePickerController;
class JavaScriptDialogController;
class RenderWidgetHostViewQt;
class RenderWidgetHostViewQtDelegate;
class RenderWidgetHostViewQtDelegateClient;
-class TouchHandleDrawableClient;
+class TouchHandleDrawableDelegate;
class TouchSelectionMenuController;
class WebContentsAdapter;
class WebContentsDelegateQt;
class WebEngineSettings;
-// Must match blink::WebReferrerPolicy
-enum class ReferrerPolicy {
- Always,
- Default,
- NoReferrerWhenDowngrade,
- Never,
- Origin,
- OriginWhenCrossOrigin,
- NoReferrerWhenDowngradeOriginWhenCrossOrigin,
- SameOrigin,
- StrictOrigin,
- Last = StrictOrigin,
-};
-
-class WebEngineContextMenuSharedData : public QSharedData {
-
-public:
- WebEngineContextMenuSharedData()
- : hasImageContent(false)
- , isEditable(false)
- , isSpellCheckerEnabled(false)
- , mediaType(0)
- , mediaFlags(0)
- , editFlags(0)
- {
- }
- bool hasImageContent;
- bool isEditable;
- bool isSpellCheckerEnabled;
- uint mediaType;
- uint mediaFlags;
- uint editFlags;
- QPoint pos;
- QUrl linkUrl;
- QUrl unfilteredLinkUrl;
- QUrl mediaUrl;
- QString altText;
- QString linkText;
- QString titleText;
- QString selectedText;
- QString suggestedFileName;
- QString misspelledWord;
- QStringList spellCheckerSuggestions;
- QUrl pageUrl;
- QUrl frameUrl;
- ReferrerPolicy referrerPolicy = ReferrerPolicy::Default;
- // Some likely candidates for future additions as we add support for the related actions:
- // bool isImageBlocked;
- // <enum tbd> mediaType;
- // ...
-};
-
-class WebEngineContextMenuData {
-public:
- // Must match blink::WebContextMenuData::MediaType:
- enum MediaType {
- // No special node is in context.
- MediaTypeNone = 0x0,
- // An image node is selected.
- MediaTypeImage,
- // A video node is selected.
- MediaTypeVideo,
- // An audio node is selected.
- MediaTypeAudio,
- // A canvas node is selected.
- MediaTypeCanvas,
- // A file node is selected.
- MediaTypeFile,
- // A plugin node is selected.
- MediaTypePlugin,
- MediaTypeLast = MediaTypePlugin
- };
- // Must match blink::WebContextMenuData::MediaFlags:
- enum MediaFlags {
- MediaNone = 0x0,
- MediaInError = 0x1,
- MediaPaused = 0x2,
- MediaMuted = 0x4,
- MediaLoop = 0x8,
- MediaCanSave = 0x10,
- MediaHasAudio = 0x20,
- MediaCanToggleControls = 0x40,
- MediaControls = 0x80,
- MediaCanPrint = 0x100,
- MediaCanRotate = 0x200,
- };
-
- // Must match blink::WebContextMenuData::EditFlags:
- enum EditFlags {
- CanDoNone = 0x0,
- CanUndo = 0x1,
- CanRedo = 0x2,
- CanCut = 0x4,
- CanCopy = 0x8,
- CanPaste = 0x10,
- CanDelete = 0x20,
- CanSelectAll = 0x40,
- CanTranslate = 0x80,
- CanEditRichly = 0x100,
- };
-
- WebEngineContextMenuData():d(new WebEngineContextMenuSharedData) {
- }
-
- void setPosition(const QPoint &pos) {
- d->pos = pos;
- }
-
- QPoint position() const {
- return d->pos;
- }
-
- void setLinkUrl(const QUrl &url) {
- d->linkUrl = url;
- }
-
- QUrl linkUrl() const {
- return d->linkUrl;
- }
-
- void setUnfilteredLinkUrl(const QUrl &url) {
- d->unfilteredLinkUrl = url;
- }
-
- QUrl unfilteredLinkUrl() const {
- return d->unfilteredLinkUrl;
- }
-
- void setAltText(const QString &text) {
- d->altText = text;
- }
-
- QString altText() const {
- return d->altText;
- }
-
- void setLinkText(const QString &text) {
- d->linkText = text;
- }
-
- QString linkText() const {
- return d->linkText;
- }
-
- void setTitleText(const QString &text) {
- d->titleText = text;
- }
-
- QString titleText() const {
- return d->titleText;
- }
-
- void setSelectedText(const QString &text) {
- d->selectedText = text;
- }
-
- QString selectedText() const {
- return d->selectedText;
- }
-
- void setMediaUrl(const QUrl &url) {
- d->mediaUrl = url;
- }
-
- QUrl mediaUrl() const {
- return d->mediaUrl;
- }
-
- void setMediaType(MediaType type) {
- d->mediaType = type;
- }
-
- MediaType mediaType() const {
- return MediaType(d->mediaType);
- }
-
- void setHasImageContent(bool imageContent) {
- d->hasImageContent = imageContent;
- }
-
- bool hasImageContent() const {
- return d->hasImageContent;
- }
-
- void setMediaFlags(MediaFlags flags) {
- d->mediaFlags = flags;
- }
-
- MediaFlags mediaFlags() const {
- return MediaFlags(d->mediaFlags);
- }
-
- void setEditFlags(EditFlags flags) {
- d->editFlags = flags;
- }
-
- EditFlags editFlags() const {
- return EditFlags(d->editFlags);
- }
-
- void setSuggestedFileName(const QString &filename) {
- d->suggestedFileName = filename;
- }
-
- QString suggestedFileName() const {
- return d->suggestedFileName;
- }
-
- void setIsEditable(bool editable) {
- d->isEditable = editable;
- }
-
- bool isEditable() const {
- return d->isEditable;
- }
-
- void setIsSpellCheckerEnabled(bool spellCheckerEnabled) {
- d->isSpellCheckerEnabled = spellCheckerEnabled;
- }
-
- bool isSpellCheckerEnabled() const {
- return d->isSpellCheckerEnabled;
- }
-
- void setMisspelledWord(const QString &word) {
- d->misspelledWord = word;
- }
-
- QString misspelledWord() const {
- return d->misspelledWord;
- }
-
- void setSpellCheckerSuggestions(const QStringList &suggestions) {
- d->spellCheckerSuggestions = suggestions;
- }
-
- QStringList spellCheckerSuggestions() const {
- return d->spellCheckerSuggestions;
- }
-
- void setFrameUrl(const QUrl &url) {
- d->frameUrl = url;
- }
-
- QUrl frameUrl() const {
- return d->frameUrl;
- }
-
- void setPageUrl(const QUrl &url) {
- d->pageUrl = url;
- }
-
- QUrl pageUrl() const {
- return d->pageUrl;
- }
-
- QUrl referrerUrl() const {
- return !d->frameUrl.isEmpty() ? d->frameUrl : d->pageUrl;
- }
-
- void setReferrerPolicy(ReferrerPolicy referrerPolicy) {
- d->referrerPolicy = referrerPolicy;
- }
-
- ReferrerPolicy referrerPolicy() const {
- return d->referrerPolicy;
- }
-
-private:
- QSharedDataPointer<WebEngineContextMenuSharedData> d;
-};
-
-
-class Q_WEBENGINECORE_PRIVATE_EXPORT WebContentsAdapterClient {
+class Q_WEBENGINECORE_EXPORT WebContentsAdapterClient {
public:
// This must match window_open_disposition_list.h.
enum WindowOpenDisposition {
@@ -390,12 +87,6 @@ public:
InternalAuthorizationDialog = 0x10,
};
- enum NavigationRequestAction {
- AcceptRequest,
- // Make room in the valid range of the enum for extra actions exposed in Experimental.
- IgnoreRequest = 0xFF
- };
-
enum NavigationType {
LinkNavigation,
TypedNavigation,
@@ -459,14 +150,14 @@ public:
virtual void loadProgressChanged(int progress) = 0;
virtual void didUpdateTargetURL(const QUrl&) = 0;
virtual void selectionChanged() = 0;
+ virtual void zoomUpdateIsNeeded() = 0;
virtual void recentlyAudibleChanged(bool recentlyAudible) = 0;
virtual void renderProcessPidChanged(qint64 pid) = 0;
virtual QRectF viewportRect() const = 0;
virtual QColor backgroundColor() const = 0;
- virtual void loadStarted(const QUrl &provisionalUrl, bool isErrorPage = false) = 0;
+ virtual void loadStarted(QWebEngineLoadingInfo info) = 0;
virtual void loadCommitted() = 0;
- virtual void didFirstVisuallyNonEmptyPaint() = 0;
- virtual void loadFinished(bool success, const QUrl &url, bool isErrorPage = false, int errorCode = 0, const QString &errorDescription = QString()) = 0;
+ virtual void loadFinished(QWebEngineLoadingInfo info) = 0;
virtual void focusContainer() = 0;
virtual void unhandledKeyEvent(QKeyEvent *event) = 0;
virtual QSharedPointer<WebContentsAdapter>
@@ -476,8 +167,9 @@ public:
virtual bool isBeingAdopted() = 0;
virtual void close() = 0;
virtual void windowCloseRejected() = 0;
- virtual void contextMenuRequested(const WebEngineContextMenuData &) = 0;
- virtual void navigationRequested(int navigationType, const QUrl &url, int &navigationRequestAction, bool isMainFrame) = 0;
+ virtual void contextMenuRequested(QWebEngineContextMenuRequest *request) = 0;
+ virtual void desktopMediaRequested(DesktopMediaController *) = 0;
+ virtual void navigationRequested(int navigationType, const QUrl &url, bool &accepted, bool isMainFrame, bool hasFormData) = 0;
virtual void requestFullScreenMode(const QUrl &origin, bool fullscreen) = 0;
virtual bool isFullScreenMode() const = 0;
virtual void javascriptDialog(QSharedPointer<JavaScriptDialogController>) = 0;
@@ -497,35 +189,36 @@ public:
virtual void runFeaturePermissionRequest(ProfileAdapter::PermissionType, const QUrl &securityOrigin) = 0;
virtual void runMediaAccessPermissionRequest(const QUrl &securityOrigin, MediaRequestFlags requestFlags) = 0;
virtual void runMouseLockPermissionRequest(const QUrl &securityOrigin) = 0;
- virtual void runQuotaRequest(QWebEngineQuotaRequest) = 0;
virtual void runRegisterProtocolHandlerRequest(QWebEngineRegisterProtocolHandlerRequest) = 0;
- virtual WebEngineSettings *webEngineSettings() const = 0;
+ virtual void runFileSystemAccessRequest(QWebEngineFileSystemAccessRequest) = 0;
+ virtual QWebEngineSettings *webEngineSettings() const = 0;
RenderProcessTerminationStatus renderProcessExitStatus(int);
virtual void renderProcessTerminated(RenderProcessTerminationStatus terminationStatus, int exitCode) = 0;
virtual void requestGeometryChange(const QRect &geometry, const QRect &frameGeometry) = 0;
- virtual void allowCertificateError(const QSharedPointer<CertificateErrorController> &errorController) = 0;
+ virtual void allowCertificateError(const QWebEngineCertificateError &error) = 0;
virtual void selectClientCert(const QSharedPointer<ClientCertSelectController> &selectController) = 0;
virtual void updateScrollPosition(const QPointF &position) = 0;
virtual void updateContentsSize(const QSizeF &size) = 0;
virtual void updateNavigationActions() = 0;
virtual void updateEditActions() = 0;
- virtual void startDragging(const content::DropData &dropData, Qt::DropActions allowedActions,
- const QPixmap &pixmap, const QPoint &offset) = 0;
- virtual bool supportsDragging() const = 0;
+ virtual QObject *dragSource() const = 0;
virtual bool isEnabled() const = 0;
virtual const QObject *holdingQObject() const = 0;
virtual void setToolTip(const QString& toolTipText) = 0;
virtual ClientType clientType() = 0;
virtual void printRequested() = 0;
- virtual void widgetChanged(RenderWidgetHostViewQtDelegate *newWidget) = 0;
- virtual TouchHandleDrawableClient *createTouchHandle(const QMap<int, QImage> &images) = 0;
+ virtual TouchHandleDrawableDelegate * createTouchHandleDelegate(const QMap<int, QImage> &images) = 0;
virtual void showTouchSelectionMenu(TouchSelectionMenuController *menuController, const QRect &bounds, const QSize &handleSize) = 0;
virtual void hideTouchSelectionMenu() = 0;
virtual void findTextFinished(const QWebEngineFindTextResult &result) = 0;
+ virtual void showAutofillPopup(AutofillPopupController *controller, const QRect &bounds,
+ bool autoselectFirstSuggestion) = 0;
+ virtual void hideAutofillPopup() = 0;
virtual ProfileAdapter *profileAdapter() = 0;
virtual WebContentsAdapter* webContentsAdapter() = 0;
virtual void releaseProfile() = 0;
+ virtual void showWebAuthDialog(QWebEngineWebAuthUxRequest *request) = 0;
};
} // namespace QtWebEngineCore
diff --git a/src/core/web_contents_delegate_qt.cpp b/src/core/web_contents_delegate_qt.cpp
index 77dd4593f..4df73fb69 100644
--- a/src/core/web_contents_delegate_qt.cpp
+++ b/src/core/web_contents_delegate_qt.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@@ -43,15 +7,22 @@
#include "web_contents_delegate_qt.h"
-#include "profile_adapter.h"
+#include "certificate_error_controller.h"
#include "color_chooser_controller.h"
#include "color_chooser_qt.h"
-#include "favicon_manager.h"
+#include "custom_handlers/protocol_handler_registry_factory.h"
+#include "custom_handlers/register_protocol_handler_request_controller_impl.h"
+#include "desktop_media_controller.h"
+#include "desktop_media_controller_p.h"
#include "file_picker_controller.h"
+#include "find_text_helper.h"
+#include "javascript_dialog_manager_qt.h"
#include "media_capture_devices_dispatcher.h"
+#include "native_web_keyboard_event_qt.h"
+#include "profile_adapter.h"
#include "profile_qt.h"
+#include "qwebengineloadinginfo.h"
#include "qwebengineregisterprotocolhandlerrequest.h"
-#include "register_protocol_handler_request_controller_impl.h"
#include "render_widget_host_view_qt.h"
#include "type_conversion.h"
#include "visited_links_manager_qt.h"
@@ -59,28 +30,28 @@
#include "web_contents_adapter.h"
#include "web_contents_view_qt.h"
#include "web_engine_context.h"
+#include "web_engine_error.h"
#include "web_engine_settings.h"
+#include "certificate_error_controller.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
+#include "components/custom_handlers/protocol_handler_registry.h"
#include "components/web_cache/browser/web_cache_manager.h"
-#include "content/browser/frame_host/render_frame_host_impl.h"
-#include "content/browser/renderer_host/render_widget_host_impl.h"
+#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/invalidate_type.h"
+#include "content/public/browser/media_stream_request.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/favicon_url.h"
-#include "content/public/common/frame_navigate_params.h"
#include "content/public/common/url_constants.h"
-#include "content/public/common/web_preferences.h"
#include "net/base/data_url.h"
#include "net/base/url_util.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include <QDesktopServices>
#include <QTimer>
@@ -103,11 +74,8 @@ static WebContentsAdapterClient::JavaScriptConsoleMessageLevel mapToJavascriptCo
WebContentsDelegateQt::WebContentsDelegateQt(content::WebContents *webContents, WebContentsAdapterClient *adapterClient)
: m_viewClient(adapterClient)
- , m_faviconManager(new FaviconManager(webContents, adapterClient))
, m_findTextHelper(new FindTextHelper(webContents, adapterClient))
- , m_lastLoadProgress(-1)
, m_loadingState(determineLoadingState(webContents))
- , m_didStartLoadingSeen(m_loadingState == LoadingState::Loading)
, m_frameFocusedObserver(adapterClient)
{
webContents->SetDelegate(this);
@@ -127,7 +95,7 @@ content::WebContents *WebContentsDelegateQt::OpenURLFromTab(content::WebContents
content::SiteInstance *target_site_instance = params.source_site_instance.get();
content::Referrer referrer = params.referrer;
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
- QSharedPointer<WebContentsAdapter> targetAdapter = createWindow(0, params.disposition, gfx::Rect(), params.user_gesture);
+ QSharedPointer<WebContentsAdapter> targetAdapter = createWindow(nullptr, params.disposition, gfx::Rect(), toQt(params.url), params.user_gesture);
if (targetAdapter) {
if (targetAdapter->profile() != source->GetBrowserContext()) {
target_site_instance = nullptr;
@@ -136,11 +104,15 @@ content::WebContents *WebContentsDelegateQt::OpenURLFromTab(content::WebContents
if (!targetAdapter->isInitialized())
targetAdapter->initialize(target_site_instance);
target = targetAdapter->webContents();
+ } else {
+ return target;
}
}
Q_ASSERT(target);
content::NavigationController::LoadURLParams load_url_params(params.url);
+ load_url_params.initiator_frame_token = params.initiator_frame_token;
+ load_url_params.initiator_process_id = params.initiator_process_id;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = target_site_instance;
load_url_params.referrer = referrer;
@@ -156,6 +128,7 @@ content::WebContents *WebContentsDelegateQt::OpenURLFromTab(content::WebContents
load_url_params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
+ load_url_params.impression = params.impression;
if (params.post_data) {
load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
@@ -177,6 +150,10 @@ static bool shouldUseActualURL(content::NavigationEntry *entry)
if (entry->GetPageType() != content::PAGE_TYPE_NORMAL)
return false;
+ // Show the virtual URL based on custom base, if present
+ if (!entry->GetBaseURLForDataURL().is_empty())
+ return false;
+
// Show invalid data URL
std::string mime_type, charset, data;
if (!net::DataURL::Parse(entry->GetURL(), &mime_type, &charset, &data))
@@ -212,8 +189,8 @@ void WebContentsDelegateQt::NavigationStateChanged(content::WebContents* source,
}
}
-QUrl WebContentsDelegateQt::url(content::WebContents* source) const {
-
+QUrl WebContentsDelegateQt::url(content::WebContents *source) const
+{
content::NavigationEntry *entry = source->GetController().GetVisibleEntry();
QUrl newUrl;
if (entry) {
@@ -224,22 +201,25 @@ QUrl WebContentsDelegateQt::url(content::WebContents* source) const {
GURL strippedUrl = net::SimplifyUrlForRequest(url);
newUrl = QUrl(QString("%1:%2").arg(content::kViewSourceScheme, QString::fromStdString(strippedUrl.spec())));
}
- // If there is a visible entry there are special cases when we dont wan't to use the actual URL
+ // If there is a visible entry there are special cases where we dont wan't to use the actual URL
if (newUrl.isEmpty())
newUrl = shouldUseActualURL(entry) ? toQt(url) : toQt(entry->GetVirtualURL());
}
m_pendingUrlUpdate = false;
return newUrl;
}
-void WebContentsDelegateQt::AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked)
+void WebContentsDelegateQt::AddNewContents(content::WebContents *source, std::unique_ptr<content::WebContents> new_contents, const GURL &target_url,
+ WindowOpenDisposition disposition, const blink::mojom::WindowFeatures &window_features, bool user_gesture, bool *was_blocked)
{
- Q_UNUSED(source);
- QSharedPointer<WebContentsAdapter> newAdapter = createWindow(std::move(new_contents), disposition, initial_pos, user_gesture);
+ Q_UNUSED(source)
+ QSharedPointer<WebContentsAdapter> newAdapter = createWindow(std::move(new_contents), disposition, window_features.bounds, toQt(target_url), user_gesture);
// Chromium can forget to pass user-agent override settings to new windows (see QTBUG-61774 and QTBUG-76249),
// so set it here. Note the actual value doesn't really matter here. Only the second value does, but we try
// to give the correct user-agent anyway.
if (newAdapter)
- newAdapter->webContents()->SetUserAgentOverride(newAdapter->profileAdapter()->httpUserAgent().toStdString(), true);
+ newAdapter->webContents()->SetUserAgentOverride(
+ blink::UserAgentOverride::UserAgentOnly(newAdapter->profileAdapter()->httpUserAgent().toStdString()),
+ true);
if (newAdapter && !newAdapter->isInitialized())
newAdapter->loadDefault();
if (was_blocked)
@@ -255,20 +235,21 @@ void WebContentsDelegateQt::CloseContents(content::WebContents *source)
void WebContentsDelegateQt::LoadProgressChanged(double progress)
{
- if (!m_loadingErrorFrameList.isEmpty())
- return;
- if (m_lastLoadProgress < 0) // suppress signals that aren't between loadStarted and loadFinished
+ if (!m_loadingInfo.isLoading()) // suppress signals that aren't between loadStarted and loadFinished
return;
- m_lastLoadProgress = qMax(m_lastLoadProgress, qRound(progress * 100)); // ensure monotonicity
- m_lastLoadProgress = qMin(m_lastLoadProgress, 100);
- m_viewClient->loadProgressChanged(m_lastLoadProgress);
+
+ int p = qMin(qRound(progress * 100), 100);
+ if (p > m_loadingInfo.progress) { // ensure strict monotonic increase
+ m_loadingInfo.progress = p;
+ m_viewClient->loadProgressChanged(p);
+ }
}
bool WebContentsDelegateQt::HandleKeyboardEvent(content::WebContents *, const content::NativeWebKeyboardEvent &event)
{
- Q_ASSERT(!event.skip_in_browser);
+ Q_ASSERT(!event.skip_if_unhandled);
if (event.os_event)
- m_viewClient->unhandledKeyEvent(reinterpret_cast<QKeyEvent *>(event.os_event));
+ m_viewClient->unhandledKeyEvent(ToKeyEvent(event.os_event));
// FIXME: ?
return true;
}
@@ -277,14 +258,13 @@ void WebContentsDelegateQt::RenderFrameCreated(content::RenderFrameHost *render_
{
content::FrameTreeNode *node = static_cast<content::RenderFrameHostImpl *>(render_frame_host)->frame_tree_node();
m_frameFocusedObserver.addNode(node);
-}
-void WebContentsDelegateQt::RenderFrameDeleted(content::RenderFrameHost *render_frame_host)
-{
- m_loadingErrorFrameList.removeOne(render_frame_host->GetRoutingID());
+ // If it's a child frame (render_widget_host_view_child_frame) install an InputEventObserver on
+ // it. Note that it is only needed for WheelEventAck.
+ RenderWidgetHostViewQt::registerInputEventObserver(web_contents(), render_frame_host);
}
-void WebContentsDelegateQt::RenderProcessGone(base::TerminationStatus status)
+void WebContentsDelegateQt::PrimaryMainFrameRenderProcessGone(base::TerminationStatus status)
{
// RenderProcessHost::FastShutdownIfPossible results in TERMINATION_STATUS_STILL_RUNNING
if (status != base::TERMINATION_STATUS_STILL_RUNNING) {
@@ -299,6 +279,7 @@ void WebContentsDelegateQt::RenderProcessGone(base::TerminationStatus status)
|| status == base::TERMINATION_STATUS_STILL_RUNNING) {
return;
}
+ LOG(INFO) << "ProcessGone: " << int(status) << " (" << web_contents()->GetCrashedErrorCode() << ")";
setLoadingState(LoadingState::Unloaded);
}
@@ -318,8 +299,10 @@ void WebContentsDelegateQt::RenderFrameHostChanged(content::RenderFrameHost *old
if (new_host->GetFrameOwnerElementType() == blink::FrameOwnerElementType::kNone) {
content::RenderProcessHost *renderProcessHost = new_host->GetProcess();
const base::Process &process = renderProcessHost->GetProcess();
- if (process.IsValid())
+ if (process.IsValid()) {
m_viewClient->renderProcessPidChanged(process.Pid());
+ m_viewClient->zoomUpdateIsNeeded();
+ }
}
}
}
@@ -328,44 +311,91 @@ void WebContentsDelegateQt::RenderViewHostChanged(content::RenderViewHost *, con
{
if (newHost && newHost->GetWidget() && newHost->GetWidget()->GetView()) {
auto rwhv = static_cast<RenderWidgetHostViewQt *>(newHost->GetWidget()->GetView());
- m_viewClient->widgetChanged(rwhv->delegate());
+ Q_ASSERT(rwhv->delegate());
+ rwhv->delegate()->adapterClientChanged(m_viewClient);
+ m_viewClient->zoomUpdateIsNeeded();
+ auto backgroundColor = m_viewClient->backgroundColor();
+ if (backgroundColor != Qt::white)
+ m_viewClient->webContentsAdapter()->setBackgroundColor(backgroundColor);
+ }
+}
+
+void WebContentsDelegateQt::RenderViewReady()
+{
+ // The render view might have returned after a crash without us getting a RenderViewHostChanged call
+ content::RenderWidgetHostView *newHostView = web_contents()->GetRenderWidgetHostView();
+ if (newHostView) {
+ auto *rwhv = static_cast<RenderWidgetHostViewQt *>(newHostView);
+ Q_ASSERT(rwhv->delegate());
+ rwhv->delegate()->updateAdapterClientIfNeeded(m_viewClient);
}
}
-void WebContentsDelegateQt::EmitLoadStarted(const QUrl &url, bool isErrorPage)
+void WebContentsDelegateQt::emitLoadStarted(bool isErrorPage)
{
- if (m_lastLoadProgress >= 0 && m_lastLoadProgress < 100) // already running
+ for (auto &&wc : m_certificateErrorControllers)
+ if (auto controller = wc.lock())
+ controller->deactivate();
+ m_certificateErrorControllers.clear();
+
+ // only report first ever load start or separate one for error page only
+ if (!isErrorPage && m_loadingInfo.isLoading()) // already running
return;
- m_viewClient->loadStarted(url, isErrorPage);
- m_viewClient->updateNavigationActions();
- m_viewClient->loadProgressChanged(0);
- m_lastLoadProgress = 0;
+
+ m_isDocumentEmpty = true; // reset to default which may only be overridden on actual resource load complete
+ if (!isErrorPage) {
+ m_loadingInfo.progress = 0;
+ m_viewClient->loadStarted(QWebEngineLoadingInfo(m_loadingInfo.url, QWebEngineLoadingInfo::LoadStartedStatus));
+ m_viewClient->updateNavigationActions();
+ m_viewClient->loadProgressChanged(0);
+ }
}
void WebContentsDelegateQt::DidStartNavigation(content::NavigationHandle *navigation_handle)
{
- if (!navigation_handle->IsInMainFrame())
- return;
+ if (!webEngineSettings()->testAttribute(QWebEngineSettings::ErrorPageEnabled))
+ navigation_handle->SetSilentlyIgnoreErrors();
- // Error-pages are not reported as separate started navigations.
- Q_ASSERT(!navigation_handle->IsErrorPage());
+ if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument())
+ return;
- m_loadingErrorFrameList.clear();
- m_faviconManager->resetCandidates();
- EmitLoadStarted(toQt(navigation_handle->GetURL()));
+ m_loadingInfo.url = toQt(navigation_handle->GetURL());
+ // IsErrorPage is only set after navigation commit, so check it otherwise: error page shouldn't have navigation entry
+ bool isErrorPage = m_loadingInfo.triggersErrorPage && !navigation_handle->GetNavigationEntry();
+ emitLoadStarted(isErrorPage);
}
-void WebContentsDelegateQt::EmitLoadFinished(bool success, const QUrl &url, bool isErrorPage, int errorCode, const QString &errorDescription)
+void WebContentsDelegateQt::emitLoadFinished(bool isErrorPage)
{
- if (m_lastLoadProgress < 0) // not currently running
+ if (!m_loadingInfo.isLoading()) // not currently running
+ return;
+
+ Q_ASSERT(!isErrorPage || webEngineSettings()->testAttribute(QWebEngineSettings::ErrorPageEnabled));
+ Q_ASSERT((m_loadingInfo.triggersErrorPage && webEngineSettings()->testAttribute(QWebEngineSettings::ErrorPageEnabled)) || !m_loadingInfo.triggersErrorPage);
+
+ if (isErrorPage) {
+ m_loadingInfo.isErrorPage = isErrorPage;
return;
- m_lastLoadProgress = -1;
- m_viewClient->loadProgressChanged(100);
- m_viewClient->loadFinished(success, url, isErrorPage, errorCode, errorDescription);
+ }
+
+ if (m_loadingInfo.progress < 100) {
+ m_loadingInfo.progress = 100;
+ m_viewClient->loadProgressChanged(100);
+ }
+
+ auto loadStatus = m_loadingInfo.success
+ ? QWebEngineLoadingInfo::LoadSucceededStatus
+ : (m_loadingInfo.errorCode == WebEngineError::UserAbortedError
+ ? QWebEngineLoadingInfo::LoadStoppedStatus : QWebEngineLoadingInfo::LoadFailedStatus);
+ QWebEngineLoadingInfo info(m_loadingInfo.url, loadStatus, m_loadingInfo.isErrorPage,
+ m_loadingInfo.errorDescription, m_loadingInfo.errorCode,
+ QWebEngineLoadingInfo::ErrorDomain(m_loadingInfo.errorDomain),
+ m_loadingInfo.responseHeaders);
+ m_viewClient->loadFinished(std::move(info));
m_viewClient->updateNavigationActions();
}
-void WebContentsDelegateQt::EmitLoadCommitted()
+void WebContentsDelegateQt::emitLoadCommitted()
{
m_findTextHelper->handleLoadCommitted();
m_viewClient->loadCommitted();
@@ -385,58 +415,56 @@ void WebContentsDelegateQt::DidFinishNavigation(content::NavigationHandle *navig
profileAdapter->visitedLinksManager()->addUrl(url);
}
- EmitLoadCommitted();
+ emitLoadCommitted();
+ }
+
+ const net::HttpResponseHeaders * const responseHeaders = navigation_handle->GetResponseHeaders();
+ if (responseHeaders != nullptr) {
+ m_loadingInfo.responseHeaders.clear();
+ std::size_t iter = 0;
+ std::string headerName;
+ std::string headerValue;
+ while (responseHeaders->EnumerateHeaderLines(&iter, &headerName, &headerValue)) {
+ m_loadingInfo.responseHeaders.insert(
+ QByteArray::fromStdString(headerName),
+ QByteArray::fromStdString(headerValue)
+ );
+ }
}
+
// Success is reported by DidFinishLoad, but DidFailLoad is now dead code and needs to be handled below
if (navigation_handle->GetNetErrorCode() == net::OK)
return;
// WebContentsObserver::DidFailLoad is not called any longer so we have to report the failure here.
- const net::Error error_code = navigation_handle->GetNetErrorCode();
- const std::string error_description = net::ErrorToString(error_code);
- didFailLoad(toQt(navigation_handle->GetURL()), error_code, toQt(error_description));
+ int error_code = navigation_handle->GetNetErrorCode();
+ if (error_code == net::ERR_HTTP_RESPONSE_CODE_FAILURE)
+ if (auto entry = web_contents()->GetController().GetActiveEntry())
+ error_code = entry->GetHttpStatusCode();
+ didFailLoad(toQt(navigation_handle->GetURL()), error_code, WebEngineError::toQtErrorDescription(error_code));
// The load will succede as an error-page load later, and we reported the original error above
if (navigation_handle->IsErrorPage()) {
// Now report we are starting to load an error-page.
- m_loadingErrorFrameList.append(navigation_handle->GetRenderFrameHost()->GetRoutingID());
- m_faviconManager->resetCandidates();
- EmitLoadStarted(toQt(GURL(content::kUnreachableWebDataURL)), true);
// If it is already committed we will not see another DidFinishNavigation call or a DidFinishLoad call.
if (navigation_handle->HasCommitted())
- EmitLoadCommitted();
+ emitLoadCommitted();
}
}
-void WebContentsDelegateQt::DidStartLoading()
+void WebContentsDelegateQt::PrimaryPageChanged(content::Page &)
{
- // Based on TabLoadTracker::DidStartLoading
+ // Based on TabLoadTracker::PrimaryPageChanged
- if (!web_contents()->IsLoadingToDifferentDocument())
+ if (!web_contents()->ShouldShowLoadingUI())
return;
- if (m_loadingState == LoadingState::Loading) {
- DCHECK(m_didStartLoadingSeen);
- return;
- }
- m_didStartLoadingSeen = true;
-}
-
-void WebContentsDelegateQt::DidReceiveResponse()
-{
- // Based on TabLoadTracker::DidReceiveResponse
-
- if (m_loadingState == LoadingState::Loading) {
- DCHECK(m_didStartLoadingSeen);
- return;
- }
// A transition to loading requires both DidStartLoading (navigation
// committed) and DidReceiveResponse (data has been transmitted over the
// network) events to occur. This is because NavigationThrottles can block
// actual network requests, but not the rest of the state machinery.
- if (m_didStartLoadingSeen)
- setLoadingState(LoadingState::Loading);
+ setLoadingState(LoadingState::Loading);
}
void WebContentsDelegateQt::DidStopLoading()
@@ -445,47 +473,52 @@ void WebContentsDelegateQt::DidStopLoading()
// NOTE: PageAlmostIdle feature not implemented
- if (m_loadingState == LoadingState::Loading)
- setLoadingState(LoadingState::Loaded);
+ setLoadingState(LoadingState::Loaded);
+
+ emitLoadFinished();
+ m_loadingInfo.clear();
}
void WebContentsDelegateQt::didFailLoad(const QUrl &url, int errorCode, const QString &errorDescription)
{
m_viewClient->iconChanged(QUrl());
- EmitLoadFinished(false /* success */ , url, false /* isErrorPage */, errorCode, errorDescription);
+ bool errorPageEnabled = webEngineSettings()->testAttribute(QWebEngineSettings::ErrorPageEnabled);
+ // Delay notifying failure until the error-page is done loading.
+ // Error-pages are not loaded on failures due to abort.
+ bool aborted = (errorCode == -3 /* ERR_ABORTED*/ );
+ m_loadingInfo.success = false;
+ m_loadingInfo.url = url;
+ m_loadingInfo.errorCode = errorCode;
+ m_loadingInfo.errorDomain = WebEngineError::toQtErrorDomain(errorCode);
+ m_loadingInfo.errorDescription = errorDescription;
+ m_loadingInfo.triggersErrorPage = errorPageEnabled && !aborted;
}
-void WebContentsDelegateQt::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code, const base::string16& error_description)
+void WebContentsDelegateQt::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code)
{
- if (m_loadingState == LoadingState::Loading)
- setLoadingState(LoadingState::Loaded);
+ setLoadingState(LoadingState::Loaded);
- if (render_frame_host != web_contents()->GetMainFrame())
+ if (render_frame_host != web_contents()->GetPrimaryMainFrame())
return;
if (validated_url.spec() == content::kUnreachableWebDataURL) {
// error-pages should only ever fail due to abort:
Q_ASSERT(error_code == -3 /* ERR_ABORTED */);
- m_loadingErrorFrameList.removeOne(render_frame_host->GetRoutingID());
m_viewClient->iconChanged(QUrl());
-
- EmitLoadFinished(false /* success */, toQt(validated_url), true /* isErrorPage */);
+ emitLoadFinished(/* isErrorPage = */true);
return;
}
-
- didFailLoad(toQt(validated_url), error_code, toQt(error_description));
+ didFailLoad(toQt(validated_url), error_code, WebEngineError::toQtErrorDescription(error_code));
}
void WebContentsDelegateQt::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url)
{
Q_ASSERT(validated_url.is_valid());
if (validated_url.spec() == content::kUnreachableWebDataURL) {
- m_loadingErrorFrameList.removeOne(render_frame_host->GetRoutingID());
-
// Trigger LoadFinished signal for main frame's error page only.
if (!render_frame_host->GetParent()) {
m_viewClient->iconChanged(QUrl());
- EmitLoadFinished(true /* success */, toQt(validated_url), true /* isErrorPage */);
+ emitLoadFinished(/* isErrorPage = */true);
}
return;
@@ -496,45 +529,32 @@ void WebContentsDelegateQt::DidFinishLoad(content::RenderFrameHost* render_frame
return;
}
- if (!m_faviconManager->hasCandidate())
- m_viewClient->iconChanged(QUrl());
-
content::NavigationEntry *entry = web_contents()->GetController().GetActiveEntry();
- int http_statuscode = 0;
- if (entry)
- http_statuscode = entry->GetHttpStatusCode();
- EmitLoadFinished(true /* success */ , toQt(validated_url), false /* isErrorPage */, http_statuscode);
-}
+ int http_statuscode = entry ? entry->GetHttpStatusCode() : 0;
+ bool errorPageEnabled = webEngineSettings()->testAttribute(QWebEngineSettings::ErrorPageEnabled);
+ bool triggersErrorPage = errorPageEnabled && (http_statuscode >= 400) && m_isDocumentEmpty;
-void WebContentsDelegateQt::DidUpdateFaviconURL(const std::vector<content::FaviconURL> &candidates)
-{
- QList<FaviconInfo> faviconCandidates;
- faviconCandidates.reserve(static_cast<int>(candidates.size()));
- for (const content::FaviconURL &candidate : candidates) {
- // Store invalid candidates too for later debugging via API
- faviconCandidates.append(toFaviconInfo(candidate));
- }
-
- // Favicon URL can be changed from JavaScript too. Thus we need to reset
- // the current candidate icon list to not handle previous icon as a candidate.
- m_faviconManager->resetCandidates();
- m_faviconManager->update(faviconCandidates);
+ m_loadingInfo.success = http_statuscode < 400;
+ m_loadingInfo.url = toQt(validated_url);
+ m_loadingInfo.errorCode = http_statuscode;
+ m_loadingInfo.errorDomain = WebEngineError::toQtErrorDomain(http_statuscode);
+ m_loadingInfo.errorDescription = WebEngineError::toQtErrorDescription(http_statuscode);
+ m_loadingInfo.triggersErrorPage = triggersErrorPage;
}
void WebContentsDelegateQt::WebContentsCreated(content::WebContents * /*source_contents*/,
int /*opener_render_process_id*/, int /*opener_render_frame_id*/,
const std::string &/*frame_name*/,
- const GURL &target_url, content::WebContents *newContents)
+ const GURL &/*target_url*/, content::WebContents *newContents)
{
- m_initialTargetUrl = toQt(target_url);
if (auto *view = static_cast<content::WebContentsImpl *>(newContents)->GetView())
static_cast<WebContentsViewQt *>(view)->setFactoryClient(m_viewClient);
}
-content::ColorChooser *WebContentsDelegateQt::OpenColorChooser(content::WebContents *source, SkColor color, const std::vector<blink::mojom::ColorSuggestionPtr> &suggestion)
+std::unique_ptr<content::ColorChooser> WebContentsDelegateQt::OpenColorChooser(content::WebContents *source, SkColor color, const std::vector<blink::mojom::ColorSuggestionPtr> &suggestion)
{
Q_UNUSED(suggestion);
- ColorChooserQt *colorChooser = new ColorChooserQt(source, toQt(color));
+ auto colorChooser = std::make_unique<ColorChooserQt>(source, toQt(color));
m_viewClient->showColorDialog(colorChooser->controller());
return colorChooser;
@@ -544,17 +564,17 @@ content::JavaScriptDialogManager *WebContentsDelegateQt::GetJavaScriptDialogMana
return JavaScriptDialogManagerQt::GetInstance();
}
-void WebContentsDelegateQt::EnterFullscreenModeForTab(content::WebContents *web_contents, const GURL& origin, const blink::mojom::FullscreenOptions &)
+void WebContentsDelegateQt::EnterFullscreenModeForTab(content::RenderFrameHost *requesting_frame, const blink::mojom::FullscreenOptions &options)
{
- Q_UNUSED(web_contents);
+ Q_UNUSED(options);
if (!m_viewClient->isFullScreenMode())
- m_viewClient->requestFullScreenMode(toQt(origin), true);
+ m_viewClient->requestFullScreenMode(toQt(requesting_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL()), true);
}
void WebContentsDelegateQt::ExitFullscreenModeForTab(content::WebContents *web_contents)
{
if (m_viewClient->isFullScreenMode())
- m_viewClient->requestFullScreenMode(toQt(web_contents->GetLastCommittedURL().GetOrigin()), false);
+ m_viewClient->requestFullScreenMode(toQt(web_contents->GetLastCommittedURL().DeprecatedGetOriginAsURL()), false);
}
bool WebContentsDelegateQt::IsFullscreenForTabOrPending(const content::WebContents* web_contents)
@@ -568,17 +588,19 @@ ASSERT_ENUMS_MATCH(FilePickerController::OpenMultiple, blink::mojom::FileChooser
ASSERT_ENUMS_MATCH(FilePickerController::UploadFolder, blink::mojom::FileChooserParams::Mode::kUploadFolder)
ASSERT_ENUMS_MATCH(FilePickerController::Save, blink::mojom::FileChooserParams::Mode::kSave)
+extern FilePickerController *createFilePickerController(FilePickerController::FileChooserMode mode, scoped_refptr<content::FileSelectListener> listener, const QString &defaultFileName, const QStringList &acceptedMimeTypes, QObject *parent = nullptr);
+
void WebContentsDelegateQt::RunFileChooser(content::RenderFrameHost * /*frameHost*/,
- std::unique_ptr<content::FileSelectListener> listener,
+ scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params)
{
QStringList acceptedMimeTypes;
acceptedMimeTypes.reserve(params.accept_types.size());
- for (std::vector<base::string16>::const_iterator it = params.accept_types.begin(); it < params.accept_types.end(); ++it)
+ for (std::vector<std::u16string>::const_iterator it = params.accept_types.begin(); it < params.accept_types.end(); ++it)
acceptedMimeTypes.append(toQt(*it));
- m_filePickerController.reset(new FilePickerController(static_cast<FilePickerController::FileChooserMode>(params.mode),
- std::move(listener), toQt(params.default_file_name.value()), acceptedMimeTypes));
+ m_filePickerController.reset(createFilePickerController(static_cast<FilePickerController::FileChooserMode>(params.mode),
+ listener, toQt(params.default_file_name.value()), acceptedMimeTypes));
// Defer the call to not block base::MessageLoop::RunTask with modal dialogs.
QTimer::singleShot(0, [this] () {
@@ -587,7 +609,7 @@ void WebContentsDelegateQt::RunFileChooser(content::RenderFrameHost * /*frameHos
}
bool WebContentsDelegateQt::DidAddMessageToConsole(content::WebContents *source, blink::mojom::ConsoleMessageLevel log_level,
- const base::string16 &message, int32_t line_no, const base::string16 &source_id)
+ const std::u16string &message, int32_t line_no, const std::u16string &source_id)
{
Q_UNUSED(source);
m_viewClient->javaScriptConsoleMessage(mapToJavascriptConsoleMessageLevel(log_level), toQt(message), static_cast<int>(line_no), toQt(source_id));
@@ -599,9 +621,45 @@ void WebContentsDelegateQt::FindReply(content::WebContents *source, int request_
m_findTextHelper->handleFindReply(source, request_id, number_of_matches, selection_rect, active_match_ordinal, final_update);
}
+static void processMediaAccessRequest(content::WebContents *webContents,
+ const content::MediaStreamRequest &request,
+ content::MediaResponseCallback callback,
+ content::DesktopMediaID id)
+{
+ MediaCaptureDevicesDispatcher::GetInstance()->processMediaAccessRequest(
+ webContents, request, std::move(callback), id);
+}
+
+static inline bool needsPickerDialog(const content::MediaStreamRequest &request)
+{
+ return (request.requested_video_device_id.empty() && // device already selected in chooseDesktopMedia
+ (request.video_type == blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE
+ || request.video_type == blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE));
+}
+
void WebContentsDelegateQt::RequestMediaAccessPermission(content::WebContents *web_contents, const content::MediaStreamRequest &request, content::MediaResponseCallback callback)
{
- MediaCaptureDevicesDispatcher::GetInstance()->processMediaAccessRequest(m_viewClient, web_contents, request, std::move(callback));
+ if (needsPickerDialog(request)) {
+#if QT_CONFIG(webengine_webrtc)
+ base::OnceCallback<void(content::DesktopMediaID)> cb = base::BindOnce(
+ &processMediaAccessRequest, web_contents, std::move(request), std::move(callback));
+ // ownership is taken by the request
+ auto *controller = new DesktopMediaController(
+ new DesktopMediaControllerPrivate(std::move(cb)));
+ QObject::connect(controller, &DesktopMediaController::mediaListsInitialized, [controller, delegate = AsWeakPtr()]() {
+ if (delegate)
+ delegate->adapterClient()->desktopMediaRequested(controller);
+ else
+ controller->deleteLater();
+ });
+#else
+ // To keep the old behavior return the default screen even if webrtc is disabled
+ processMediaAccessRequest(web_contents, std::move(request), std::move(callback),
+ content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0));
+#endif // QT_CONFIG(webengine_webrtc)
+ } else {
+ processMediaAccessRequest(web_contents, std::move(request), std::move(callback), {});
+ }
}
void WebContentsDelegateQt::SetContentsBounds(content::WebContents *source, const gfx::Rect &bounds)
@@ -612,8 +670,8 @@ void WebContentsDelegateQt::SetContentsBounds(content::WebContents *source, cons
QRect frameGeometry(toQt(bounds));
QRect geometry;
if (RenderWidgetHostViewQt *rwhv = static_cast<RenderWidgetHostViewQt*>(web_contents()->GetRenderWidgetHostView())) {
- if (rwhv->delegate() && rwhv->delegate()->window())
- geometry = frameGeometry.marginsRemoved(rwhv->delegate()->window()->frameMargins());
+ if (rwhv->delegate() && rwhv->delegate()->Window())
+ geometry = frameGeometry.marginsRemoved(rwhv->delegate()->Window()->frameMargins());
}
m_viewClient->requestGeometryChange(geometry, frameGeometry);
}
@@ -624,25 +682,10 @@ void WebContentsDelegateQt::UpdateTargetURL(content::WebContents* source, const
m_viewClient->didUpdateTargetURL(toQt(url));
}
-void WebContentsDelegateQt::OnVisibilityChanged(content::Visibility visibility)
-{
- if (visibility != content::Visibility::HIDDEN)
- web_cache::WebCacheManager::GetInstance()->ObserveActivity(web_contents()->GetMainFrame()->GetProcess()->GetID());
-}
-
-void WebContentsDelegateQt::DidFirstVisuallyNonEmptyPaint()
-{
- RenderWidgetHostViewQt *rwhv = static_cast<RenderWidgetHostViewQt*>(web_contents()->GetRenderWidgetHostView());
- if (!rwhv)
- return;
-
- rwhv->OnDidFirstVisuallyNonEmptyPaint();
-}
-
void WebContentsDelegateQt::ActivateContents(content::WebContents* contents)
{
- WebEngineSettings *settings = m_viewClient->webEngineSettings();
- if (settings->testAttribute(settings->Attribute::AllowWindowActivationFromJavaScript))
+ QWebEngineSettings *settings = m_viewClient->webEngineSettings();
+ if (settings->testAttribute(QWebEngineSettings::AllowWindowActivationFromJavaScript))
contents->Focus();
}
@@ -651,19 +694,19 @@ void WebContentsDelegateQt::RequestToLockMouse(content::WebContents *web_content
Q_UNUSED(user_gesture);
if (last_unlocked_by_target)
- web_contents->GotResponseToLockMouseRequest(true);
+ web_contents->GotResponseToLockMouseRequest(blink::mojom::PointerLockResult::kSuccess);
else
- m_viewClient->runMouseLockPermissionRequest(toQt(web_contents->GetLastCommittedURL().GetOrigin()));
+ m_viewClient->runMouseLockPermissionRequest(toQt(web_contents->GetLastCommittedURL().DeprecatedGetOriginAsURL()));
}
-void WebContentsDelegateQt::overrideWebPreferences(content::WebContents *webContents, content::WebPreferences *webPreferences)
+void WebContentsDelegateQt::overrideWebPreferences(content::WebContents *webContents, blink::web_pref::WebPreferences *webPreferences)
{
- m_viewClient->webEngineSettings()->overrideWebPreferences(webContents, webPreferences);
+ WebEngineSettings::get(m_viewClient->webEngineSettings())->overrideWebPreferences(webContents, webPreferences);
}
QSharedPointer<WebContentsAdapter>
WebContentsDelegateQt::createWindow(std::unique_ptr<content::WebContents> new_contents,
- WindowOpenDisposition disposition, const gfx::Rect &initial_pos,
+ WindowOpenDisposition disposition, const gfx::Rect &initial_pos, const QUrl &url,
bool user_gesture)
{
QSharedPointer<WebContentsAdapter> newAdapter = QSharedPointer<WebContentsAdapter>::create(std::move(new_contents));
@@ -671,12 +714,18 @@ WebContentsDelegateQt::createWindow(std::unique_ptr<content::WebContents> new_co
return m_viewClient->adoptNewWindow(
std::move(newAdapter),
static_cast<WebContentsAdapterClient::WindowOpenDisposition>(disposition), user_gesture,
- toQt(initial_pos), m_initialTargetUrl);
+ toQt(initial_pos), url);
}
-void WebContentsDelegateQt::allowCertificateError(const QSharedPointer<CertificateErrorController> &errorController)
+void WebContentsDelegateQt::allowCertificateError(
+ const QSharedPointer<CertificateErrorController> &controller)
{
- m_viewClient->allowCertificateError(errorController);
+ QWebEngineCertificateError error(controller);
+ m_viewClient->allowCertificateError(error);
+ if (!error.isOverridable() || (!controller->deferred() && !controller->answered()))
+ error.rejectCertificate();
+ else
+ m_certificateErrorControllers.append(controller);
}
void WebContentsDelegateQt::selectClientCert(const QSharedPointer<ClientCertSelectController> &selectController)
@@ -693,17 +742,17 @@ extern WebContentsAdapterClient::NavigationType pageTransitionToNavigationType(u
void WebContentsDelegateQt::launchExternalURL(const QUrl &url, ui::PageTransition page_transition, bool is_main_frame, bool has_user_gesture)
{
- WebEngineSettings *settings = m_viewClient->webEngineSettings();
+ QWebEngineSettings *settings = m_viewClient->webEngineSettings();
bool navigationAllowedByPolicy = false;
bool navigationRequestAccepted = true;
switch (settings->unknownUrlSchemePolicy()) {
- case WebEngineSettings::DisallowUnknownUrlSchemes:
+ case QWebEngineSettings::DisallowUnknownUrlSchemes:
break;
- case WebEngineSettings::AllowUnknownUrlSchemesFromUserInteraction:
+ case QWebEngineSettings::AllowUnknownUrlSchemesFromUserInteraction:
navigationAllowedByPolicy = has_user_gesture;
break;
- case WebEngineSettings::AllowAllUnknownUrlSchemes:
+ case QWebEngineSettings::AllowAllUnknownUrlSchemes:
navigationAllowedByPolicy = true;
break;
default:
@@ -711,10 +760,8 @@ void WebContentsDelegateQt::launchExternalURL(const QUrl &url, ui::PageTransitio
}
if (navigationAllowedByPolicy) {
- int navigationRequestAction = WebContentsAdapterClient::AcceptRequest;
- m_viewClient->navigationRequested(pageTransitionToNavigationType(page_transition), url, navigationRequestAction, is_main_frame);
- navigationRequestAccepted = navigationRequestAction == WebContentsAdapterClient::AcceptRequest;
-#ifndef QT_NO_DESKTOPSERVICES
+ m_viewClient->navigationRequested(pageTransitionToNavigationType(page_transition), url, navigationRequestAccepted, is_main_frame, false);
+#if QT_CONFIG(desktopservices)
if (navigationRequestAccepted)
QDesktopServices::openUrl(url);
#endif
@@ -725,7 +772,7 @@ void WebContentsDelegateQt::launchExternalURL(const QUrl &url, ui::PageTransitio
if (!navigationAllowedByPolicy)
errorDescription = QStringLiteral("Launching external protocol forbidden by WebEngineSettings::UnknownUrlSchemePolicy");
else
- errorDescription = QStringLiteral("Launching external protocol suppressed by WebContentsAdapterClient::navigationRequested");
+ errorDescription = QStringLiteral("Launching external protocol suppressed by 'navigationRequested' API");
didFailLoad(url, net::Error::ERR_ABORTED, errorDescription);
}
}
@@ -739,12 +786,6 @@ void WebContentsDelegateQt::BeforeUnloadFired(content::WebContents *tab, bool pr
m_viewClient->windowCloseRejected();
}
-void WebContentsDelegateQt::BeforeUnloadFired(bool proceed, const base::TimeTicks &proceed_time)
-{
- Q_UNUSED(proceed);
- Q_UNUSED(proceed_time);
-}
-
bool WebContentsDelegateQt::CheckMediaAccessPermission(content::RenderFrameHost *, const GURL& security_origin, blink::mojom::MediaStreamType type)
{
switch (type) {
@@ -754,40 +795,36 @@ bool WebContentsDelegateQt::CheckMediaAccessPermission(content::RenderFrameHost
return m_viewClient->profileAdapter()->checkPermission(toQt(security_origin), ProfileAdapter::VideoCapturePermission);
default:
LOG(INFO) << "WebContentsDelegateQt::CheckMediaAccessPermission: "
- << "Unsupported media stream type checked" << type;
+ << "Unsupported media stream type checked " << type;
return false;
}
}
-void WebContentsDelegateQt::RegisterProtocolHandler(content::WebContents *webContents, const std::string &protocol, const GURL &url, bool)
+void WebContentsDelegateQt::RegisterProtocolHandler(content::RenderFrameHost *frameHost, const std::string &protocol, const GURL &url, bool)
{
- content::BrowserContext *context = webContents->GetBrowserContext();
- if (context->IsOffTheRecord())
- return;
+ content::BrowserContext *context = frameHost->GetBrowserContext();
- ProtocolHandler handler =
- ProtocolHandler::CreateProtocolHandler(protocol, url);
+ custom_handlers::ProtocolHandler handler =
+ custom_handlers::ProtocolHandler::CreateProtocolHandler(protocol, url);
- ProtocolHandlerRegistry *registry =
+ custom_handlers::ProtocolHandlerRegistry *registry =
ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
if (registry->SilentlyHandleRegisterHandlerRequest(handler))
return;
QWebEngineRegisterProtocolHandlerRequest request(
- QSharedPointer<RegisterProtocolHandlerRequestControllerImpl>::create(webContents, handler));
+ QSharedPointer<RegisterProtocolHandlerRequestControllerImpl>::create(content::WebContents::FromRenderFrameHost(frameHost), handler));
m_viewClient->runRegisterProtocolHandlerRequest(std::move(request));
}
-void WebContentsDelegateQt::UnregisterProtocolHandler(content::WebContents *webContents, const std::string &protocol, const GURL &url, bool)
+void WebContentsDelegateQt::UnregisterProtocolHandler(content::RenderFrameHost *frameHost, const std::string &protocol, const GURL &url, bool)
{
- content::BrowserContext* context = webContents->GetBrowserContext();
- if (context->IsOffTheRecord())
- return;
+ content::BrowserContext* context = frameHost->GetBrowserContext();
- ProtocolHandler handler =
- ProtocolHandler::CreateProtocolHandler(protocol, url);
+ custom_handlers::ProtocolHandler handler =
+ custom_handlers::ProtocolHandler::CreateProtocolHandler(protocol, url);
- ProtocolHandlerRegistry* registry =
+ custom_handlers::ProtocolHandlerRegistry* registry =
ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
registry->RemoveHandler(handler);
}
@@ -807,9 +844,25 @@ void WebContentsDelegateQt::ContentsZoomChange(bool zoom_in)
adapter->setZoomFactor(adapter->currentZoomFactor() - 0.1f);
}
-FaviconManager *WebContentsDelegateQt::faviconManager()
+void WebContentsDelegateQt::ResourceLoadComplete(content::RenderFrameHost* render_frame_host,
+ const content::GlobalRequestID& request_id,
+ const blink::mojom::ResourceLoadInfo& resource_load_info)
{
- return m_faviconManager.data();
+ Q_UNUSED(render_frame_host);
+ Q_UNUSED(request_id);
+
+ if (resource_load_info.request_destination == network::mojom::RequestDestination::kDocument) {
+ m_isDocumentEmpty = (resource_load_info.raw_body_bytes == 0);
+ }
+}
+
+void WebContentsDelegateQt::InnerWebContentsAttached(content::WebContents *inner_web_contents,
+ content::RenderFrameHost *render_frame_host,
+ bool is_full_page)
+{
+ blink::web_pref::WebPreferences guestPrefs = inner_web_contents->GetOrCreateWebPreferences();
+ webEngineSettings()->overrideWebPreferences(inner_web_contents, &guestPrefs);
+ inner_web_contents->SetWebPreferences(guestPrefs);
}
FindTextHelper *WebContentsDelegateQt::findTextHelper()
@@ -818,7 +871,7 @@ FindTextHelper *WebContentsDelegateQt::findTextHelper()
}
WebEngineSettings *WebContentsDelegateQt::webEngineSettings() const {
- return m_viewClient->webEngineSettings();
+ return WebEngineSettings::get(m_viewClient->webEngineSettings());
}
WebContentsAdapter *WebContentsDelegateQt::webContentsAdapter() const
@@ -830,14 +883,13 @@ void WebContentsDelegateQt::copyStateFrom(WebContentsDelegateQt *source)
{
m_title = source->m_title;
NavigationStateChanged(web_contents(), content::INVALIDATE_TYPE_URL);
- m_faviconManager->copyStateFrom(source->m_faviconManager.data());
}
WebContentsDelegateQt::LoadingState WebContentsDelegateQt::determineLoadingState(content::WebContents *contents)
{
// Based on TabLoadTracker::DetermineLoadingState
- if (contents->IsLoadingToDifferentDocument() && !contents->IsWaitingForResponse())
+ if (contents->ShouldShowLoadingUI() && !contents->IsWaitingForResponse())
return LoadingState::Loading;
content::NavigationController &controller = contents->GetController();
@@ -875,6 +927,8 @@ int &WebContentsDelegateQt::streamCount(blink::mojom::MediaStreamType type)
case blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE:
case blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE:
case blink::mojom::MediaStreamType::DISPLAY_AUDIO_CAPTURE:
+ case blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE_THIS_TAB:
+ case blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE_SET:
return m_desktopStreamCount;
case blink::mojom::MediaStreamType::NO_SERVICE:
@@ -886,22 +940,36 @@ int &WebContentsDelegateQt::streamCount(blink::mojom::MediaStreamType type)
return m_videoStreamCount;
}
-void WebContentsDelegateQt::addDevices(const blink::MediaStreamDevices &devices)
+void WebContentsDelegateQt::addDevices(const blink::mojom::StreamDevices &devices)
{
- for (const auto &device : devices)
- ++streamCount(device.type);
+ if (devices.audio_device.has_value())
+ addDevice(devices.audio_device.value());
+ if (devices.video_device.has_value())
+ addDevice(devices.video_device.value());
webContentsAdapter()->updateRecommendedState();
}
-void WebContentsDelegateQt::removeDevices(const blink::MediaStreamDevices &devices)
+void WebContentsDelegateQt::removeDevices(const blink::mojom::StreamDevices &devices)
{
- for (const auto &device : devices)
- ++streamCount(device.type);
+ if (devices.audio_device.has_value())
+ removeDevice(devices.audio_device.value());
+ if (devices.video_device.has_value())
+ removeDevice(devices.video_device.value());
webContentsAdapter()->updateRecommendedState();
}
+void WebContentsDelegateQt::addDevice(const blink::MediaStreamDevice &device)
+{
+ ++streamCount(device.type);
+}
+
+void WebContentsDelegateQt::removeDevice(const blink::MediaStreamDevice &device)
+{
+ --streamCount(device.type);
+}
+
FrameFocusedObserver::FrameFocusedObserver(WebContentsAdapterClient *adapterClient)
: m_viewClient(adapterClient)
{}
diff --git a/src/core/web_contents_delegate_qt.h b/src/core/web_contents_delegate_qt.h
index bfef9a1df..51004878d 100644
--- a/src/core/web_contents_delegate_qt.h
+++ b/src/core/web_contents_delegate_qt.h
@@ -1,74 +1,35 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_CONTENTS_DELEGATE_QT_H
#define WEB_CONTENTS_DELEGATE_QT_H
-#include "content/browser/frame_host/frame_tree_node.h"
-#include "content/public/browser/media_capture_devices.h"
+#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "third_party/skia/include/core/SkColor.h"
-#include "base/callback.h"
+#include "web_contents_adapter_client.h"
-#include "color_chooser_controller.h"
-#include "favicon_manager.h"
-#include "find_text_helper.h"
-#include "javascript_dialog_manager_qt.h"
+#include <QtCore/qlist.h>
+#include <QtCore/qmap.h>
-#include <QtCore/qvector.h>
-
-QT_FORWARD_DECLARE_CLASS(CertificateErrorController)
-QT_FORWARD_DECLARE_CLASS(ClientCertSelectController)
+namespace blink {
+ namespace web_pref {
+ struct WebPreferences;
+ }
+}
namespace content {
- class ColorChooser;
- class SiteInstance;
- class JavaScriptDialogManager;
- class WebContents;
- struct WebPreferences;
- struct ColorSuggestion;
+class ColorChooser;
+class JavaScriptDialogManager;
+class WebContents;
+struct MediaStreamRequest;
}
namespace QtWebEngineCore {
+class FindTextHelper;
class WebContentsAdapter;
class WebContentsAdapterClient;
class WebEngineSettings;
@@ -87,7 +48,7 @@ protected:
private:
WebContentsAdapterClient *m_viewClient;
- QVector<content::FrameTreeNode *> m_observedNodes;
+ QList<content::FrameTreeNode *> m_observedNodes;
};
class SavePageInfo
@@ -120,22 +81,23 @@ public:
// WebContentsDelegate overrides
content::WebContents *OpenURLFromTab(content::WebContents *source, const content::OpenURLParams &params) override;
void NavigationStateChanged(content::WebContents* source, content::InvalidateTypes changed_flags) override;
- void AddNewContents(content::WebContents *source, std::unique_ptr<content::WebContents> new_contents, WindowOpenDisposition disposition, const gfx::Rect &initial_pos, bool user_gesture, bool *was_blocked) override;
+ void AddNewContents(content::WebContents *source, std::unique_ptr<content::WebContents> new_contents, const GURL &target_url,
+ WindowOpenDisposition disposition, const blink::mojom::WindowFeatures &window_features, bool user_gesture, bool *was_blocked) override;
void CloseContents(content::WebContents *source) override;
void LoadProgressChanged(double progress) override;
bool HandleKeyboardEvent(content::WebContents *source, const content::NativeWebKeyboardEvent &event) override;
- content::ColorChooser* OpenColorChooser(content::WebContents *source, SkColor color, const std::vector<blink::mojom::ColorSuggestionPtr> &suggestions) override;
+ std::unique_ptr<content::ColorChooser> OpenColorChooser(content::WebContents *source, SkColor color, const std::vector<blink::mojom::ColorSuggestionPtr> &suggestions) override;
void WebContentsCreated(content::WebContents *source_contents, int opener_render_process_id, int opener_render_frame_id,
const std::string &frame_name, const GURL &target_url, content::WebContents *new_contents) override;
content::JavaScriptDialogManager *GetJavaScriptDialogManager(content::WebContents *source) override;
- void EnterFullscreenModeForTab(content::WebContents *web_contents, const GURL &origin, const blink::mojom::FullscreenOptions &options) override;
+ void EnterFullscreenModeForTab(content::RenderFrameHost *requesting_frame, const blink::mojom::FullscreenOptions &options) override;
void ExitFullscreenModeForTab(content::WebContents*) override;
bool IsFullscreenForTabOrPending(const content::WebContents* web_contents) override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
- std::unique_ptr<content::FileSelectListener> listener,
+ scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
bool DidAddMessageToConsole(content::WebContents *source, blink::mojom::ConsoleMessageLevel log_level,
- const base::string16 &message, int32_t line_no, const base::string16 &source_id) override;
+ const std::u16string &message, int32_t line_no, const std::u16string &source_id) override;
void FindReply(content::WebContents *source, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override;
void RequestMediaAccessPermission(content::WebContents *web_contents,
const content::MediaStreamRequest &request,
@@ -145,41 +107,41 @@ public:
void RequestToLockMouse(content::WebContents *web_contents, bool user_gesture, bool last_unlocked_by_target) override;
void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override;
- void RegisterProtocolHandler(content::WebContents* web_contents, const std::string& protocol, const GURL& url, bool user_gesture) override;
- void UnregisterProtocolHandler(content::WebContents* web_contents, const std::string& protocol, const GURL& url, bool user_gesture) override;
+ void RegisterProtocolHandler(content::RenderFrameHost* frame_host, const std::string& protocol, const GURL& url, bool user_gesture) override;
+ void UnregisterProtocolHandler(content::RenderFrameHost* frame_host, const std::string& protocol, const GURL& url, bool user_gesture) override;
bool TakeFocus(content::WebContents *source, bool reverse) override;
void ContentsZoomChange(bool zoom_in) override;
// WebContentsObserver overrides
void RenderFrameCreated(content::RenderFrameHost *render_frame_host) override;
- void RenderFrameDeleted(content::RenderFrameHost *render_frame_host) override;
- void RenderProcessGone(base::TerminationStatus status) override;
+ void PrimaryMainFrameRenderProcessGone(base::TerminationStatus status) override;
void RenderFrameHostChanged(content::RenderFrameHost *old_host, content::RenderFrameHost *new_host) override;
void RenderViewHostChanged(content::RenderViewHost *old_host, content::RenderViewHost *new_host) override;
+ void RenderViewReady() override;
void DidStartNavigation(content::NavigationHandle *navigation_handle) override;
void DidFinishNavigation(content::NavigationHandle *navigation_handle) override;
- void DidStartLoading() override;
- void DidReceiveResponse() override;
+ void PrimaryPageChanged(content::Page &page) override;
void DidStopLoading() override;
- void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code, const base::string16& error_description) override;
+ void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override;
void DidFinishLoad(content::RenderFrameHost *render_frame_host, const GURL &validated_url) override;
- void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override;
- void DidUpdateFaviconURL(const std::vector<content::FaviconURL> &candidates) override;
- void OnVisibilityChanged(content::Visibility visibility) override;
- void DidFirstVisuallyNonEmptyPaint() override;
void ActivateContents(content::WebContents* contents) override;
+ void ResourceLoadComplete(content::RenderFrameHost* render_frame_host,
+ const content::GlobalRequestID& request_id,
+ const blink::mojom::ResourceLoadInfo& resource_load_info) override;
+ void InnerWebContentsAttached(content::WebContents *inner_web_contents,
+ content::RenderFrameHost *render_frame_host,
+ bool is_full_page) override;
void didFailLoad(const QUrl &url, int errorCode, const QString &errorDescription);
- void overrideWebPreferences(content::WebContents *, content::WebPreferences*);
+ void overrideWebPreferences(content::WebContents *, blink::web_pref::WebPreferences*);
void allowCertificateError(const QSharedPointer<CertificateErrorController> &);
void selectClientCert(const QSharedPointer<ClientCertSelectController> &);
void requestFeaturePermission(ProfileAdapter::PermissionType feature, const QUrl &requestingOrigin);
void launchExternalURL(const QUrl &url, ui::PageTransition page_transition, bool is_main_frame, bool has_user_gesture);
- FaviconManager *faviconManager();
FindTextHelper *findTextHelper();
- void setSavePageInfo(const SavePageInfo &spi) { m_savePageInfo = spi; }
- const SavePageInfo &savePageInfo() { return m_savePageInfo; }
+ void setSavePageInfo(SavePageInfo *spi) { m_savePageInfo.reset(spi); }
+ SavePageInfo *savePageInfo() { return m_savePageInfo.get(); }
WebEngineSettings *webEngineSettings() const;
WebContentsAdapter *webContentsAdapter() const;
@@ -190,8 +152,10 @@ public:
using LoadingState = WebContentsAdapterClient::LoadingState;
LoadingState loadingState() const { return m_loadingState; }
- void addDevices(const blink::MediaStreamDevices &devices);
- void removeDevices(const blink::MediaStreamDevices &devices);
+ void addDevices(const blink::mojom::StreamDevices &devices);
+ void removeDevices(const blink::mojom::StreamDevices &devices);
+ void addDevice(const blink::MediaStreamDevice &device);
+ void removeDevice(const blink::MediaStreamDevice &device);
bool isCapturingAudio() const { return m_audioStreamCount > 0; }
bool isCapturingVideo() const { return m_videoStreamCount > 0; }
@@ -204,10 +168,11 @@ private:
QSharedPointer<WebContentsAdapter>
createWindow(std::unique_ptr<content::WebContents> new_contents,
WindowOpenDisposition disposition, const gfx::Rect &initial_pos,
+ const QUrl &url,
bool user_gesture);
- void EmitLoadStarted(const QUrl &url, bool isErrorPage = false);
- void EmitLoadFinished(bool success, const QUrl &url, bool isErrorPage = false, int errorCode = 0, const QString &errorDescription = QString());
- void EmitLoadCommitted();
+ void emitLoadStarted(bool isErrorPage = false);
+ void emitLoadFinished(bool isErrorPage = false);
+ void emitLoadCommitted();
LoadingState determineLoadingState(content::WebContents *contents);
void setLoadingState(LoadingState state);
@@ -215,15 +180,10 @@ private:
int &streamCount(blink::mojom::MediaStreamType type);
WebContentsAdapterClient *m_viewClient;
- QVector<int64_t> m_loadingErrorFrameList;
- QScopedPointer<FaviconManager> m_faviconManager;
QScopedPointer<FindTextHelper> m_findTextHelper;
- SavePageInfo m_savePageInfo;
+ std::unique_ptr<SavePageInfo> m_savePageInfo;
QSharedPointer<FilePickerController> m_filePickerController;
- QUrl m_initialTargetUrl;
- int m_lastLoadProgress;
LoadingState m_loadingState;
- bool m_didStartLoadingSeen;
FrameFocusedObserver m_frameFocusedObserver;
QString m_title;
@@ -233,7 +193,22 @@ private:
int m_desktopStreamCount = 0;
mutable bool m_pendingUrlUpdate = false;
+ struct LoadingInfo {
+ bool success = false;
+ int progress = -1;
+ bool isLoading() const { return progress >= 0; }
+ QUrl url;
+ bool isErrorPage = false;
+ int errorCode = 0, errorDomain = 0;
+ QString errorDescription;
+ bool triggersErrorPage = false;
+ QMultiMap<QByteArray, QByteArray> responseHeaders;
+ void clear() { *this = LoadingInfo(); }
+ } m_loadingInfo;
+
+ bool m_isDocumentEmpty = true;
base::WeakPtrFactory<WebContentsDelegateQt> m_weakPtrFactory { this };
+ QList<QWeakPointer<CertificateErrorController>> m_certificateErrorControllers;
};
} // namespace QtWebEngineCore
diff --git a/src/core/web_contents_view_qt.cpp b/src/core/web_contents_view_qt.cpp
index d1c5012eb..023f9e99f 100644
--- a/src/core/web_contents_view_qt.cpp
+++ b/src/core/web_contents_view_qt.cpp
@@ -1,70 +1,38 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "web_contents_view_qt.h"
-#include "profile_adapter.h"
-#include "content_browser_client_qt.h"
#include "render_widget_host_view_qt.h"
#include "render_widget_host_view_qt_delegate.h"
-#include "render_widget_host_view_qt.h"
#include "touch_selection_controller_client_qt.h"
#include "type_conversion.h"
-#include "web_contents_adapter_client.h"
#include "web_contents_adapter.h"
-#include "web_engine_context.h"
-#include "web_contents_delegate_qt.h"
+#include "web_contents_adapter_client.h"
-#include "components/spellcheck/spellcheck_buildflags.h"
-#include "content/browser/renderer_host/render_view_host_impl.h"
-#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/web_contents_delegate.h"
-#include "content/public/common/context_menu_params.h"
+#include "third_party/blink/public/common/context_menu_data/context_menu_data.h"
#include "third_party/blink/public/common/context_menu_data/edit_flags.h"
-#include "third_party/blink/public/common/context_menu_data/media_type.h"
+#include "third_party/blink/public/mojom/context_menu/context_menu.mojom.h"
+
#include "ui/gfx/image/image_skia.h"
-#include <QtGui/qpixmap.h>
+#include <QtGui/QPixmap>
+#include <QtWebEngineCore/private/qwebenginecontextmenurequest_p.h>
namespace QtWebEngineCore {
+WebContentsViewQt::WebContentsViewQt(content::WebContents *webContents)
+ : m_webContents(webContents)
+ , m_client(nullptr)
+ , m_factoryClient(nullptr)
+ , m_contextMenuRequest(
+ new QWebEngineContextMenuRequest(new QWebEngineContextMenuRequestPrivate()))
+{
+}
+
void WebContentsViewQt::setFactoryClient(WebContentsAdapterClient* client)
{
if (m_factoryClient)
@@ -122,12 +90,13 @@ gfx::NativeView WebContentsViewQt::GetNativeView() const
return nullptr;
}
-void WebContentsViewQt::GetContainerBounds(gfx::Rect* out) const
+gfx::Rect WebContentsViewQt::GetContainerBounds() const
{
if (m_client) {
const QRectF r(m_client->viewportRect());
- *out = gfx::Rect(r.x(), r.y(), r.width(), r.height());
+ return gfx::Rect(r.x(), r.y(), r.width(), r.height());
}
+ return gfx::Rect();
}
void WebContentsViewQt::Focus()
@@ -147,85 +116,79 @@ void WebContentsViewQt::SetInitialFocus()
void WebContentsViewQt::FocusThroughTabTraversal(bool reverse)
{
content::WebContentsImpl *web_contents = static_cast<content::WebContentsImpl*>(m_webContents);
- if (web_contents->ShowingInterstitialPage()) {
- web_contents->GetInterstitialPage()->FocusThroughTabTraversal(reverse);
- return;
- }
- content::RenderWidgetHostView *fullscreen_view = web_contents->GetFullscreenRenderWidgetHostView();
- if (fullscreen_view) {
- fullscreen_view->Focus();
- return;
- }
web_contents->GetRenderViewHost()->SetInitialFocus(reverse);
}
-
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeNone, blink::ContextMenuDataMediaType::kNone)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeImage, blink::ContextMenuDataMediaType::kImage)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeVideo, blink::ContextMenuDataMediaType::kVideo)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeAudio, blink::ContextMenuDataMediaType::kAudio)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeCanvas, blink::ContextMenuDataMediaType::kCanvas)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypeFile, blink::ContextMenuDataMediaType::kFile)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaTypePlugin, blink::ContextMenuDataMediaType::kPlugin)
-
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaNone, blink::WebContextMenuData::kMediaNone)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaInError, blink::WebContextMenuData::kMediaInError)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaPaused, blink::WebContextMenuData::kMediaPaused)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaMuted, blink::WebContextMenuData::kMediaMuted)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaLoop, blink::WebContextMenuData::kMediaLoop)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaCanSave, blink::WebContextMenuData::kMediaCanSave)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaHasAudio, blink::WebContextMenuData::kMediaHasAudio)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaCanToggleControls, blink::WebContextMenuData::kMediaCanToggleControls)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaControls, blink::WebContextMenuData::kMediaControls)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaCanPrint, blink::WebContextMenuData::kMediaCanPrint)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::MediaCanRotate, blink::WebContextMenuData::kMediaCanRotate)
-
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanDoNone, blink::kCanDoNone)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanUndo, blink::kCanUndo)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanRedo, blink::kCanRedo)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanCut, blink::kCanCut)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanCopy, blink::kCanCopy)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanPaste, blink::kCanPaste)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanDelete, blink::kCanDelete)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanSelectAll, blink::kCanSelectAll)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanTranslate, blink::kCanTranslate)
-ASSERT_ENUMS_MATCH(WebEngineContextMenuData::CanEditRichly, blink::kCanEditRichly)
-
-static inline WebEngineContextMenuData fromParams(const content::ContextMenuParams &params)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeNone,
+ blink::mojom::ContextMenuDataMediaType::kNone)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeImage,
+ blink::mojom::ContextMenuDataMediaType::kImage)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeVideo,
+ blink::mojom::ContextMenuDataMediaType::kVideo)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeAudio,
+ blink::mojom::ContextMenuDataMediaType::kAudio)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeCanvas,
+ blink::mojom::ContextMenuDataMediaType::kCanvas)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypeFile,
+ blink::mojom::ContextMenuDataMediaType::kFile)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaTypePlugin,
+ blink::mojom::ContextMenuDataMediaType::kPlugin)
+
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaInError,
+ blink::ContextMenuData::kMediaInError)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaPaused,
+ blink::ContextMenuData::kMediaPaused)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaMuted, blink::ContextMenuData::kMediaMuted)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaLoop, blink::ContextMenuData::kMediaLoop)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaCanSave,
+ blink::ContextMenuData::kMediaCanSave)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaHasAudio,
+ blink::ContextMenuData::kMediaHasAudio)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaCanToggleControls,
+ blink::ContextMenuData::kMediaCanToggleControls)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaControls,
+ blink::ContextMenuData::kMediaControls)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaCanPrint,
+ blink::ContextMenuData::kMediaCanPrint)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::MediaCanRotate,
+ blink::ContextMenuData::kMediaCanRotate)
+
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanUndo, blink::kCanUndo)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanRedo, blink::kCanRedo)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanCut, blink::kCanCut)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanCopy, blink::kCanCopy)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanPaste, blink::kCanPaste)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanDelete, blink::kCanDelete)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanSelectAll, blink::kCanSelectAll)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanTranslate, blink::kCanTranslate)
+ASSERT_ENUMS_MATCH(QWebEngineContextMenuRequest::CanEditRichly, blink::kCanEditRichly)
+
+// static
+void WebContentsViewQt::update(QWebEngineContextMenuRequest *request,
+ const content::ContextMenuParams &params, bool spellcheckEnabled)
{
- WebEngineContextMenuData ret;
- ret.setPosition(QPoint(params.x, params.y));
- ret.setLinkUrl(toQt(params.link_url));
- ret.setLinkText(toQt(params.link_text.data()));
- ret.setAltText(toQt(params.alt_text.data()));
- ret.setTitleText(toQt(params.title_text.data()));
- ret.setUnfilteredLinkUrl(toQt(params.unfiltered_link_url));
- ret.setSelectedText(toQt(params.selection_text.data()));
- ret.setMediaUrl(toQt(params.src_url));
- ret.setMediaType((WebEngineContextMenuData::MediaType)params.media_type);
- ret.setHasImageContent(params.has_image_contents);
- ret.setMediaFlags((WebEngineContextMenuData::MediaFlags)params.media_flags);
- ret.setEditFlags((WebEngineContextMenuData::EditFlags)params.edit_flags);
- ret.setSuggestedFileName(toQt(params.suggested_filename.data()));
- ret.setIsEditable(params.is_editable);
+ auto *re = request->d.data();
+ re->m_position = QPoint(params.x, params.y);
+ re->m_filteredLinkUrl = toQt(params.link_url);
+ re->m_linkText = toQt(params.link_text);
+ re->m_altText = toQt(params.alt_text);
+ re->m_titleText = toQt(params.title_text);
+ re->m_unfilteredLinkUrl = toQt(params.unfiltered_link_url);
+ re->m_selectedText = toQt(params.selection_text);
+ re->m_mediaUrl = toQt(params.src_url);
+ re->m_mediaType = (QWebEngineContextMenuRequest::MediaType)params.media_type;
+ re->m_hasImageContent = params.has_image_contents;
+ re->m_mediaFlags = (QWebEngineContextMenuRequest::MediaFlags)params.media_flags;
+ re->m_editFlags = (QWebEngineContextMenuRequest::EditFlags)params.edit_flags;
+ re->m_suggestedFileName = toQt(params.suggested_filename);
+ re->m_isEditable = params.is_editable;
#if QT_CONFIG(webengine_spellchecker)
- ret.setMisspelledWord(toQt(params.misspelled_word));
- ret.setSpellCheckerSuggestions(fromVector(params.dictionary_suggestions));
+ re->m_misspelledWord = toQt(params.misspelled_word);
+ re->m_spellCheckerSuggestions = fromVector(params.dictionary_suggestions);
#endif
- ret.setFrameUrl(toQt(params.frame_url));
- ret.setPageUrl(toQt(params.page_url));
- ret.setReferrerPolicy((ReferrerPolicy)params.referrer_policy);
- return ret;
-}
-
-void WebContentsViewQt::ShowContextMenu(content::RenderFrameHost *, const content::ContextMenuParams &params)
-{
- if (auto rwhv = static_cast<RenderWidgetHostViewQt *>(m_webContents->GetRenderWidgetHostView())) {
- if (rwhv && rwhv->getTouchSelectionControllerClient()->handleContextMenu(params))
- return;
- }
-
- WebEngineContextMenuData contextMenuData(fromParams(params));
+ re->m_frameUrl = toQt(params.frame_url);
+ re->m_pageUrl = toQt(params.page_url);
+ re->m_referrerPolicy = (ReferrerPolicy)params.referrer_policy;
#if QT_CONFIG(webengine_spellchecker)
// Do not use params.spellcheck_enabled, since it is never
// correctly initialized for chrome asynchronous spellchecking.
@@ -234,34 +197,48 @@ void WebContentsViewQt::ShowContextMenu(content::RenderFrameHost *, const conten
// must be initialized to true due to the way how the initialization sequence
// in SpellCheck works ie. typing the first word triggers the creation
// of the SpellcheckService. Use user preference store instead.
- contextMenuData.setIsSpellCheckerEnabled(m_client->profileAdapter()->isSpellCheckEnabled());
+ re->m_isSpellCheckerEnabled = spellcheckEnabled;
#endif
- m_client->contextMenuRequested(contextMenuData);
}
-Qt::DropActions toQtDropActions(blink::WebDragOperationsMask ops)
+void WebContentsViewQt::ShowContextMenu(content::RenderFrameHost &,
+ const content::ContextMenuParams &params)
+{
+ if (auto rwhv =
+ static_cast<RenderWidgetHostViewQt *>(m_webContents->GetRenderWidgetHostView())) {
+ if (rwhv && rwhv->getTouchSelectionControllerClient()->handleContextMenu(params))
+ return;
+ }
+ const bool spellcheckEnabled = m_client->profileAdapter()->isSpellCheckEnabled();
+ update(m_contextMenuRequest.get(), params, spellcheckEnabled);
+ m_client->contextMenuRequested(m_contextMenuRequest.get());
+}
+
+static Qt::DropActions toQtDropActions(blink::DragOperationsMask ops)
{
Qt::DropActions result;
- if (ops & blink::kWebDragOperationCopy)
+ if (ops & blink::kDragOperationCopy)
result |= Qt::CopyAction;
- if (ops & blink::kWebDragOperationLink)
+ if (ops & blink::kDragOperationLink)
result |= Qt::LinkAction;
- if (ops & blink::kWebDragOperationMove || ops & blink::kWebDragOperationDelete)
+ if (ops & blink::kDragOperationMove)
result |= Qt::MoveAction;
return result;
}
void WebContentsViewQt::StartDragging(const content::DropData &drop_data,
- blink::WebDragOperationsMask allowed_ops,
+ blink::DragOperationsMask allowed_ops,
const gfx::ImageSkia &image,
const gfx::Vector2d &image_offset,
- const content::DragEventSourceInfo &event_info,
- content::RenderWidgetHostImpl* source_rwh)
+ const gfx::Rect &drag_obj_rect,
+ const blink::mojom::DragEventSourceInfo &event_info,
+ content::RenderWidgetHostImpl *source_rwh)
{
#if QT_CONFIG(draganddrop)
Q_UNUSED(event_info);
- if (!m_client->supportsDragging()) {
+ QObject *dragSource = m_client->dragSource();
+ if (!dragSource) {
if (source_rwh)
source_rwh->DragSourceSystemDragEnded();
return;
@@ -275,14 +252,14 @@ void WebContentsViewQt::StartDragging(const content::DropData &drop_data,
hotspot.setY(image_offset.y());
}
- m_client->startDragging(drop_data, toQtDropActions(allowed_ops), pixmap, hotspot);
+ m_client->webContentsAdapter()->startDragging(dragSource, drop_data, toQtDropActions(allowed_ops), pixmap, hotspot);
#endif // QT_CONFIG(draganddrop)
}
-void WebContentsViewQt::UpdateDragCursor(blink::WebDragOperation dragOperation)
+void WebContentsViewQt::UpdateDragCursor(ui::mojom::DragOperation dragOperation)
{
#if QT_CONFIG(draganddrop)
- m_client->webContentsAdapter()->updateDragAction(dragOperation);
+ m_client->webContentsAdapter()->updateDragAction(int(dragOperation));
#endif // QT_CONFIG(draganddrop)
}
diff --git a/src/core/web_contents_view_qt.h b/src/core/web_contents_view_qt.h
index 3dcb648bf..8754250e6 100644
--- a/src/core/web_contents_view_qt.h
+++ b/src/core/web_contents_view_qt.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_CONTENTS_VIEW_QT_H
#define WEB_CONTENTS_VIEW_QT_H
@@ -43,7 +7,13 @@
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/web_contents/web_contents_view.h"
-#include "api/qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+
+QT_FORWARD_DECLARE_CLASS(QWebEngineContextMenuRequest)
+
+namespace extensions {
+class MimeHandlerViewGuestDelegateQt;
+}
namespace content {
class WebContents;
@@ -59,11 +29,7 @@ class WebContentsViewQt
public:
static inline WebContentsViewQt *from(WebContentsView *view) { return static_cast<WebContentsViewQt*>(view); }
- WebContentsViewQt(content::WebContents* webContents)
- : m_webContents(webContents)
- , m_client(nullptr)
- , m_factoryClient(nullptr)
- { }
+ WebContentsViewQt(content::WebContents* webContents);
void setFactoryClient(WebContentsAdapterClient* client);
void setClient(WebContentsAdapterClient* client);
@@ -76,9 +42,7 @@ public:
content::RenderWidgetHostViewBase *CreateViewForChildWidget(content::RenderWidgetHost* render_widget_host) override;
- void SetPageTitle(const base::string16& title) override { }
-
- void RenderViewCreated(content::RenderViewHost* host) override { }
+ void SetPageTitle(const std::u16string& title) override { }
void RenderViewReady() override { }
@@ -92,9 +56,7 @@ public:
gfx::NativeWindow GetTopLevelNativeWindow() const override { return nullptr; }
- void GetContainerBounds(gfx::Rect* out) const override;
-
- void SizeContents(const gfx::Size& size) override { }
+ gfx::Rect GetContainerBounds() const override;
void Focus() override;
@@ -109,29 +71,40 @@ public:
gfx::Rect GetViewBounds() const override { return gfx::Rect(); }
void FocusThroughTabTraversal(bool reverse) override;
+ void OnCapturerCountChanged() override { QT_NOT_YET_IMPLEMENTED }
+ void FullscreenStateChanged(bool) override { }
+ void UpdateWindowControlsOverlay(const gfx::Rect &) override { QT_NOT_YET_IMPLEMENTED }
-#if defined(OS_MACOSX)
+#if BUILDFLAG(IS_MAC)
bool CloseTabAfterEventTrackingIfNeeded() override { QT_NOT_YET_IMPLEMENTED return false; }
-#endif // defined(OS_MACOSX)
+#endif
// content::RenderViewHostDelegateView overrides:
- void StartDragging(const content::DropData& drop_data, blink::WebDragOperationsMask allowed_ops,
+ void StartDragging(const content::DropData& drop_data, blink::DragOperationsMask allowed_ops,
const gfx::ImageSkia& image, const gfx::Vector2d& image_offset,
- const content::DragEventSourceInfo& event_info,
- content::RenderWidgetHostImpl* source_rwh) override;
+ const gfx::Rect& drag_obj_rect,
+ const blink::mojom::DragEventSourceInfo &event_info,
+ content::RenderWidgetHostImpl *source_rwh) override;
- void UpdateDragCursor(blink::WebDragOperation dragOperation) override;
+ void UpdateDragCursor(ui::mojom::DragOperation dragOperation) override;
- void ShowContextMenu(content::RenderFrameHost *, const content::ContextMenuParams &params) override;
+ void ShowContextMenu(content::RenderFrameHost &, const content::ContextMenuParams &params) override;
void GotFocus(content::RenderWidgetHostImpl *render_widget_host) override;
void LostFocus(content::RenderWidgetHostImpl *render_widget_host) override;
void TakeFocus(bool reverse) override;
private:
+ static void update(QWebEngineContextMenuRequest *request,
+ const content::ContextMenuParams &params, bool spellcheckEnabled);
+
+private:
content::WebContents *m_webContents;
WebContentsAdapterClient *m_client;
WebContentsAdapterClient *m_factoryClient;
+ std::unique_ptr<QWebEngineContextMenuRequest> m_contextMenuRequest;
+
+ friend class extensions::MimeHandlerViewGuestDelegateQt;
};
} // namespace QtWebEngineCore
diff --git a/src/core/web_engine_context.cpp b/src/core/web_engine_context.cpp
index bda57aab2..94110d51c 100644
--- a/src/core/web_engine_context.cpp
+++ b/src/core/web_engine_context.cpp
@@ -1,109 +1,89 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "web_engine_context.h"
#include <math.h>
+#include <QtGui/private/qrhi_p.h>
#include "base/base_switches.h"
+#include "base/functional/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
+#include "base/power_monitor/power_monitor.h"
+#include "base/power_monitor/power_monitor_device_source.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
+#include "base/strings/string_split.h"
#include "base/task/sequence_manager/thread_controller_with_message_pump_impl.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/thread_restrictions.h"
#include "cc/base/switches.h"
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+#include "chrome/browser/media/webrtc/webrtc_log_uploader.h"
+#endif
#include "chrome/common/chrome_switches.h"
+#include "content/common/process_visibility_tracker.h"
#include "content/gpu/gpu_child_thread.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/compositor/viz_process_transport_factory.h"
#include "components/viz/host/host_frame_sink_manager.h"
#if QT_CONFIG(webengine_printing_and_pdf)
#include "chrome/browser/printing/print_job_manager.h"
-#include "components/printing/browser/features.h"
#endif
#include "components/discardable_memory/service/discardable_shared_memory_manager.h"
+#include "components/download/public/common/download_task_runner.h"
#include "components/viz/common/features.h"
#include "components/web_cache/browser/web_cache_manager.h"
-#include "content/app/service_manager_environment.h"
+#include "content/app/mojo_ipc_support.h"
#include "content/browser/devtools/devtools_http_handler.h"
+#include "content/browser/gpu/gpu_main_thread_factory.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/scheduler/browser_task_executor.h"
#include "content/browser/startup_data_impl.h"
#include "content/browser/startup_helper.h"
+#include "content/browser/utility_process_host.h"
+#include "content/gpu/in_process_gpu_thread.h"
#include "content/public/app/content_main.h"
#include "content/public/app/content_main_runner.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
+#if QT_CONFIG(webengine_pepper_plugins)
#include "content/public/browser/plugin_service.h"
+#endif
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
-#include "content/public/common/network_service_util.h"
+#include "content/renderer/in_process_renderer_thread.h"
+#include "content/utility/in_process_utility_thread.h"
#include "gpu/command_buffer/service/gpu_switches.h"
-#include "gpu/command_buffer/service/sync_point_manager.h"
+#include "gpu/config/gpu_finch_features.h"
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
#include "mojo/core/embedder/embedder.h"
#include "net/base/port_util.h"
-#include "ppapi/buildflags/buildflags.h"
+#include "sandbox/policy/switches.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/mojom/network_context.mojom.h"
-#include "services/service_manager/sandbox/switches.h"
#include "services/tracing/public/cpp/trace_startup.h"
#include "services/tracing/public/cpp/tracing_features.h"
#include "third_party/blink/public/common/features.h"
+#include "ui/base/ui_base_features.h"
#include "ui/events/event_switches.h"
#include "ui/native_theme/native_theme_features.h"
+#include "ui/gl/gl_utils.h"
#include "ui/gl/gl_switches.h"
-#if defined(OS_WIN)
+#if defined(Q_OS_WIN)
#include "sandbox/win/src/sandbox_types.h"
#include "content/public/app/sandbox_helper_win.h"
-#endif // OS_WIN
+#endif // Q_OS_WIN
#if defined(Q_OS_MACOS)
-#include "base/mac/foundation_util.h"
+#include "base/apple/foundation_util.h"
#endif
#if QT_CONFIG(accessibility)
@@ -126,17 +106,18 @@
#include <QMutex>
#include <QOffscreenSurface>
#if QT_CONFIG(opengl)
-# include <QOpenGLContext>
+#include <QOpenGLContext>
+#include <qopenglcontext_platform.h>
#endif
#include <QQuickWindow>
+#include <QRegularExpression>
#include <QStringList>
#include <QSurfaceFormat>
-#include <QVector>
#include <QNetworkProxy>
#include <QtGui/qpa/qplatformintegration.h>
#include <QtGui/private/qguiapplication_p.h>
-
-using namespace QtWebEngineCore;
+#include <QtQuick/private/qsgrhisupport_p.h>
+#include <QLoggingCategory>
#if QT_CONFIG(opengl)
QT_BEGIN_NAMESPACE
@@ -144,25 +125,24 @@ Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
QT_END_NAMESPACE
#endif
-namespace {
+#define STRINGIFY_LITERAL(x) #x
+#define STRINGIFY_EXPANDED(x) STRINGIFY_LITERAL(x)
-#if QT_CONFIG(opengl)
-bool usingANGLE()
-{
-#if defined(Q_OS_WIN)
- if (qt_gl_global_share_context())
- return qt_gl_global_share_context()->isOpenGLES();
- return QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES;
-#else
- return false;
-#endif
-}
+namespace QtWebEngineCore {
+
+Q_LOGGING_CATEGORY(webEngineContextLog, "qt.webenginecontext")
-bool usingDefaultSGBackend()
+static bool usingSupportedSGBackend()
{
+ if (QQuickWindow::graphicsApi() != QSGRendererInterface::OpenGL
+ && QQuickWindow::graphicsApi() != QSGRendererInterface::Vulkan
+ && QQuickWindow::graphicsApi() != QSGRendererInterface::Metal
+ && QQuickWindow::graphicsApi() != QSGRendererInterface::Direct3D11)
+ return false;
+
const QStringList args = QGuiApplication::arguments();
- //folow logic from contextFactory in src/quick/scenegraph/qsgcontextplugin.cpp
+ // follow the logic from contextFactory in src/quick/scenegraph/qsgcontextplugin.cpp
QString device = QQuickWindow::sceneGraphBackend();
for (int index = 0; index < args.count(); ++index) {
@@ -173,92 +153,292 @@ bool usingDefaultSGBackend()
}
if (device.isEmpty())
- device = QString::fromLocal8Bit(qgetenv("QT_QUICK_BACKEND"));
+ device = qEnvironmentVariable("QT_QUICK_BACKEND");
if (device.isEmpty())
- device = QString::fromLocal8Bit(qgetenv("QMLSCENE_DEVICE"));
+ device = qEnvironmentVariable("QMLSCENE_DEVICE");
- return device.isEmpty();
+ return device.isEmpty() || device == QLatin1String("rhi");
}
-#endif // QT_CONFIG(opengl)
-#if QT_CONFIG(webengine_pepper_plugins)
-void dummyGetPluginCallback(const std::vector<content::WebPluginInfo>&)
+
+#if QT_CONFIG(opengl)
+bool usingSoftwareDynamicGL()
{
-}
+ const char openGlVar[] = "QT_OPENGL";
+ if (QCoreApplication::testAttribute(Qt::AA_UseSoftwareOpenGL))
+ return true;
+
+ if (qEnvironmentVariableIsSet(openGlVar)) {
+ const QByteArray requested = qgetenv(openGlVar);
+ if (requested == "software")
+ return true;
+ }
+#if defined(Q_OS_WIN)
+ HMODULE handle = QNativeInterface::QWGLContext::openGLModuleHandle();
+ wchar_t path[MAX_PATH];
+ DWORD size = GetModuleFileName(handle, path, MAX_PATH);
+ QFileInfo openGLModule(QString::fromWCharArray(path, size));
+ return openGLModule.fileName().contains(QLatin1String("opengl32sw"),Qt::CaseInsensitive);
+#else
+ return false;
#endif
+}
-} // namespace
+static bool openGLPlatformSupport()
+{
+ return QGuiApplicationPrivate::platformIntegration()->hasCapability(
+ QPlatformIntegration::OpenGL);
+}
-namespace QtWebEngineCore {
+static std::string getGLType(bool enableGLSoftwareRendering, bool disableGpu)
+{
+ const bool tryGL =
+ usingSupportedSGBackend() && !usingSoftwareDynamicGL() && openGLPlatformSupport();
+ if (disableGpu || (!tryGL && !enableGLSoftwareRendering))
+ return gl::kGLImplementationDisabledName;
+#if defined(Q_OS_MACOS)
+ return gl::kGLImplementationANGLEName;
+#else
#if defined(Q_OS_WIN)
-sandbox::SandboxInterfaceInfo *staticSandboxInterfaceInfo(sandbox::SandboxInterfaceInfo *info)
+ if (QQuickWindow::graphicsApi() == QSGRendererInterface::Direct3D11
+ || QQuickWindow::graphicsApi() == QSGRendererInterface::Vulkan) {
+ return gl::kGLImplementationANGLEName;
+ }
+#endif
+
+ if (!qt_gl_global_share_context() || !qt_gl_global_share_context()->isValid()) {
+ qWarning("WebEngineContext is used before QtWebEngineQuick::initialize() or OpenGL context "
+ "creation failed.");
+ return gl::kGLImplementationDisabledName;
+ }
+
+ const QSurfaceFormat sharedFormat = qt_gl_global_share_context()->format();
+
+ switch (sharedFormat.renderableType()) {
+ case QSurfaceFormat::OpenGL:
+ if (sharedFormat.profile() == QSurfaceFormat::CoreProfile) {
+ qWarning("An OpenGL Core Profile was requested, but it is not supported "
+ "on the current platform. Falling back to a non-Core profile. "
+ "Note that this might cause rendering issues.");
+ }
+ return gl::kGLImplementationDesktopName;
+ case QSurfaceFormat::OpenGLES:
+ return gl::kGLImplementationEGLName;
+ case QSurfaceFormat::OpenVG:
+ case QSurfaceFormat::DefaultRenderableType:
+ default:
+ // Shared contex created but no rederable type set.
+ qWarning("Unsupported rendering surface format. Please open bug report at "
+ "https://bugreports.qt.io");
+ }
+
+ return gl::kGLImplementationDisabledName;
+#endif // defined(Q_OS_MACOS)
+}
+#else
+static std::string getGLType(bool /*enableGLSoftwareRendering*/, bool disableGpu)
{
- static sandbox::SandboxInterfaceInfo *g_info = nullptr;
- if (info) {
- Q_ASSERT(g_info == nullptr);
- g_info = info;
+ if (disableGpu)
+ return gl::kGLImplementationDisabledName;
+#if defined(Q_OS_MACOS)
+ return gl::kGLImplementationANGLEName;
+#elif defined(Q_OS_WIN)
+ if (QQuickWindow::graphicsApi() == QSGRendererInterface::Direct3D11
+ || QQuickWindow::graphicsApi() == QSGRendererInterface::Vulkan) {
+ return gl::kGLImplementationANGLEName;
}
- return g_info;
+#endif
+ return gl::kGLImplementationDisabledName;
}
+#endif // QT_CONFIG(opengl)
+
+static std::string getVulkanType(base::CommandLine *cmd)
+{
+#if QT_CONFIG(webengine_vulkan)
+ if (cmd->HasSwitch(switches::kUseVulkan))
+ return cmd->GetSwitchValueASCII(switches::kUseVulkan);
#endif
-extern std::unique_ptr<base::MessagePump> messagePumpFactory();
+ return "disabled";
+}
-bool usingSoftwareDynamicGL()
+static std::string getAngleType(const std::string &glType, base::CommandLine *cmd)
{
- if (QCoreApplication::testAttribute(Qt::AA_UseSoftwareOpenGL))
- return true;
-#if defined(Q_OS_WIN) && QT_CONFIG(opengl)
- HMODULE handle = static_cast<HMODULE>(QOpenGLContext::openGLModuleHandle());
- wchar_t path[MAX_PATH];
- DWORD size = GetModuleFileName(handle, path, MAX_PATH);
- QFileInfo openGLModule(QString::fromWCharArray(path, size));
- return openGLModule.fileName() == QLatin1String("opengl32sw.dll");
+ if (glType == gl::kGLImplementationANGLEName) {
+ if (cmd->HasSwitch(switches::kUseANGLE))
+ return cmd->GetSwitchValueASCII(switches::kUseANGLE);
+
+#if defined(Q_OS_WIN)
+ return gl::kANGLEImplementationD3D11Name;
+#elif defined(Q_OS_MACOS)
+ return gl::kANGLEImplementationMetalName;
#else
- return false;
+ return gl::kANGLEImplementationDefaultName;
+#endif
+ }
+
+ return "disabled";
+}
+
+static quint64 getGPUVendorId()
+{
+#if QT_CONFIG(webengine_vulkan)
+ QVulkanInstance vulkanInstance;
+ vulkanInstance.setApiVersion(QVersionNumber(1, 1));
+ if (vulkanInstance.create()) {
+ QRhiVulkanInitParams params;
+ params.inst = &vulkanInstance;
+ QScopedPointer<QRhi> rhi(QRhi::create(QRhi::Vulkan, &params, QRhi::Flags(), nullptr));
+ return rhi->driverInfo().vendorId;
+ }
+#endif
+
+ return 0;
+}
+
+#if defined(Q_OS_WIN)
+static QString getAdapterLuid() {
+ static const bool preferSoftwareDevice = qEnvironmentVariableIntValue("QSG_RHI_PREFER_SOFTWARE_RENDERER");
+ QRhiD3D11InitParams rhiParams;
+ QRhi::Flags flags;
+ if (preferSoftwareDevice) {
+ flags |= QRhi::PreferSoftwareRenderer;
+ }
+ QScopedPointer<QRhi> rhi(QRhi::create(QRhi::D3D11,&rhiParams,flags,nullptr));
+ // mimic what QSGRhiSupport and QBackingStoreRhi does
+ if (!rhi && !preferSoftwareDevice) {
+ flags |= QRhi::PreferSoftwareRenderer;
+ rhi.reset(QRhi::create(QRhi::D3D11, &rhiParams, flags));
+ }
+ if (rhi) {
+ const QRhiD3D11NativeHandles *handles =
+ static_cast<const QRhiD3D11NativeHandles *>(rhi->nativeHandles());
+ Q_ASSERT(handles);
+ return QString("%1,%2").arg(handles->adapterLuidHigh).arg(handles->adapterLuidLow);
+ } else {
+ return QString();
+ }
+}
+#endif
+
+#if QT_CONFIG(webengine_pepper_plugins)
+void dummyGetPluginCallback(const std::vector<content::WebPluginInfo>&)
+{
+}
#endif
+
+static void logContext(const std::string &glType, base::CommandLine *cmd)
+{
+ if (Q_UNLIKELY(webEngineContextLog().isDebugEnabled())) {
+ QStringList log;
+ log << "\n";
+
+ log << "Chromium GL Backend:" << glType.c_str() << "\n";
+ log << "Chromium ANGLE Backend:" << getAngleType(glType, cmd).c_str() << "\n";
+ log << "Chromium Vulkan Backend:" << getVulkanType(cmd).c_str() << "\n";
+ log << "\n";
+
+ log << "QSG RHI Backend:" << QSGRhiSupport::instance()->rhiBackendName() << "\n";
+ log << "QSG RHI Backend Supported:" << (usingSupportedSGBackend() ? "yes" : "no") << "\n";
+ log << "GPU Vendor:";
+ if (quint64 vendorId = getGPUVendorId()) {
+ switch (vendorId) {
+ case 0x1002:
+ log << "AMD";
+ break;
+ case 0x10DE:
+ log << "NVIDIA";
+ break;
+ case 0x8086:
+ log << "Intel";
+ break;
+ case 0x1010:
+ log << "ImgTec";
+ break;
+ case 0x13B5:
+ log << "ARM";
+ break;
+ case 0x5143:
+ log << "Qualcomm";
+ break;
+ default:
+ break;
+ }
+ log << QString("(0x%1)\n").arg(vendorId, 0, 16);
+ } else {
+ log << "Unable to detect\n";
+ }
+ log << "\n";
+
+#if QT_CONFIG(opengl)
+#if defined(USE_OZONE)
+ log << "Using GLX:" << (GLContextHelper::getGlxPlatformInterface() ? "yes" : "no") << "\n";
+ log << "Using EGL:" << (GLContextHelper::getEglPlatformInterface() ? "yes" : "no") << "\n";
+#endif
+ log << "Using Shared GL:" << (qt_gl_global_share_context() ? "yes" : "no") << "\n";
+ if (qt_gl_global_share_context()) {
+ log << "Using Software Dynamic GL:" << (usingSoftwareDynamicGL() ? "yes" : "no")
+ << "\n";
+
+ const QSurfaceFormat sharedFormat = qt_gl_global_share_context()
+ ? qt_gl_global_share_context()->format()
+ : QSurfaceFormat::defaultFormat();
+ const auto profile =
+ QMetaEnum::fromType<QSurfaceFormat::OpenGLContextProfile>().valueToKey(
+ sharedFormat.profile());
+ const auto type = QMetaEnum::fromType<QSurfaceFormat::RenderableType>().valueToKey(
+ sharedFormat.renderableType());
+ log << "Surface Type:" << type << "\n";
+ log << "Surface Profile:" << profile << "\n";
+ log << "Surface Version:"
+ << QString("%1.%2")
+ .arg(sharedFormat.majorVersion())
+ .arg(sharedFormat.minorVersion())
+ << "\n";
+ }
+ log << "\n";
+#endif // QT_CONFIG(opengl)
+
+ log << "Init Parameters:\n";
+ const base::CommandLine::SwitchMap switchMap = cmd->GetSwitches();
+ for (const auto &pair : switchMap)
+ log << " * " << toQt(pair.first) << toQt(pair.second) << "\n";
+
+ qCDebug(webEngineContextLog) << qPrintable(log.join(" "));
+ }
}
-void setupProxyPac(base::CommandLine *commandLine){
+extern std::unique_ptr<base::MessagePump> messagePumpFactory();
+
+static void setupProxyPac(base::CommandLine *commandLine)
+{
if (commandLine->HasSwitch(switches::kProxyPacUrl)) {
QUrl pac_url(toQt(commandLine->GetSwitchValueASCII(switches::kProxyPacUrl)));
if (pac_url.isValid() && (pac_url.isLocalFile() ||
- !pac_url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive))) {
+ !pac_url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive))) {
QFile file;
if (pac_url.isLocalFile())
- file.setFileName(pac_url.toLocalFile());
+ file.setFileName(pac_url.toLocalFile());
else
- file.setFileName(pac_url.path().prepend(QChar(':')));
+ file.setFileName(pac_url.path().prepend(QChar(':')));
if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- QByteArray ba = file.readAll();
- commandLine->RemoveSwitch(switches::kProxyPacUrl);
- commandLine->AppendSwitchASCII(switches::kProxyPacUrl,
- ba.toBase64().prepend("data:application/x-javascript-config;base64,").toStdString());
+ QByteArray ba = file.readAll();
+ commandLine->RemoveSwitch(switches::kProxyPacUrl);
+ commandLine->AppendSwitchASCII(switches::kProxyPacUrl,
+ ba.toBase64().prepend("data:application/x-javascript-config;base64,").toStdString());
}
}
}
}
-static bool waitForViz = false;
-static void completeVizCleanup()
-{
- waitForViz = false;
-}
-
static void cleanupVizProcess()
{
auto gpuChildThread = content::GpuChildThread::instance();
if (!gpuChildThread)
return;
- auto vizMain = gpuChildThread->viz_main();
- auto vizCompositorThreadRunner = vizMain->viz_compositor_thread_runner();
- if (!vizCompositorThreadRunner)
- return;
- waitForViz = true;
content::GetHostFrameSinkManager()->SetConnectionLostCallback(base::DoNothing());
auto factory = static_cast<content::VizProcessTransportFactory*>(content::ImageTransportFactory::GetInstance());
factory->PrepareForShutDown();
- vizCompositorThreadRunner->CleanupForShutdown(base::BindOnce(&completeVizCleanup));
}
static QStringList parseEnvCommandLine(const QString &cmdLine)
@@ -309,7 +489,7 @@ static QStringList parseEnvCommandLine(const QString &cmdLine)
scoped_refptr<QtWebEngineCore::WebEngineContext> WebEngineContext::m_handle;
bool WebEngineContext::m_destroyed = false;
-
+bool WebEngineContext::m_closingDown = false;
void WebEngineContext::destroyProfileAdapter()
{
if (content::RenderProcessHost::run_renderer_in_process()) {
@@ -324,7 +504,7 @@ void WebEngineContext::addProfileAdapter(ProfileAdapter *profileAdapter)
{
Q_ASSERT(!m_profileAdapters.contains(profileAdapter));
const QString path = profileAdapter->dataPath();
- if (!path.isEmpty()) {
+ if (!profileAdapter->isOffTheRecord() && !profileAdapter->storageName().isEmpty()) {
for (auto profileAdapter : m_profileAdapters) {
if (profileAdapter->dataPath() == path) {
// QTBUG-66068
@@ -348,26 +528,31 @@ void WebEngineContext::removeProfileAdapter(ProfileAdapter *profileAdapter)
m_profileAdapters.removeAll(profileAdapter);
}
+void WebEngineContext::flushMessages()
+{
+ if (!m_destroyed) {
+ base::MessagePump::Delegate *delegate = static_cast<
+ base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl *>(
+ WebEngineContext::current()->m_runLoop->delegate_);
+ while (delegate->DoWork().is_immediate()) { }
+ }
+}
void WebEngineContext::destroy()
{
if (m_devtoolsServer)
m_devtoolsServer->stop();
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ if (m_webrtcLogUploader)
+ m_webrtcLogUploader->Shutdown();
+#endif
- base::MessagePump::Delegate *delegate =
- static_cast<base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl *>(
- m_runLoop->delegate_);
// Normally the GPU thread is shut down when the GpuProcessHost is destroyed
// on IO thread (triggered by ~BrowserMainRunner). But by that time the UI
// task runner is not working anymore so we need to do this earlier.
cleanupVizProcess();
- while (waitForViz) {
- while (delegate->DoWork()){}
- QThread::msleep(50);
- }
- destroyGpuProcess();
// Flush the UI message loop before quitting.
- while (delegate->DoWork()) { }
+ flushMessages();
#if QT_CONFIG(webengine_printing_and_pdf)
// Kill print job manager early as it has a content::NotificationRegistrar
@@ -389,7 +574,7 @@ void WebEngineContext::destroy()
// Handle any events posted by browser-context shutdown.
// This should deliver all nessesery calls of DeleteSoon from PostTask
- while (delegate->DoWork()) { }
+ flushMessages();
m_devtoolsServer.reset();
m_runLoop->AfterRun();
@@ -400,8 +585,7 @@ void WebEngineContext::destroy()
GLContextHelper::destroy();
// These would normally be in the content-runner, but we allocated them separately:
- m_startupData.reset();
- m_serviceManagerEnvironment.reset();
+ m_mojoIpcSupport.reset();
m_discardableSharedMemoryManager.reset();
// Destroying content-runner will force Chromium at_exit calls to run, and
@@ -410,6 +594,10 @@ void WebEngineContext::destroy()
// Drop the false reference.
m_handle->Release();
+
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ m_webrtcLogUploader.reset();
+#endif
}
WebEngineContext::~WebEngineContext()
@@ -419,7 +607,6 @@ WebEngineContext::~WebEngineContext()
Q_ASSERT(!m_devtoolsServer);
Q_ASSERT(!m_browserRunner);
Q_ASSERT(m_profileAdapters.isEmpty());
- delete s_syncPointManager.fetchAndStoreRelaxed(nullptr);
}
WebEngineContext *WebEngineContext::current()
@@ -440,7 +627,7 @@ ProfileAdapter *WebEngineContext::createDefaultProfileAdapter()
{
Q_ASSERT(!m_destroyed);
if (!m_defaultProfileAdapter) {
- ProfileAdapter *profile = new ProfileAdapter(QStringLiteral("Default"));
+ ProfileAdapter *profile = new ProfileAdapter();
// profile when added to m_profileAdapters might be set default
// profile in case of single-process
if (!m_defaultProfileAdapter)
@@ -464,6 +651,7 @@ void WebEngineContext::destroyContextPostRoutine()
// Destroy WebEngineContext before its static pointer is zeroed and destructor called.
// Before destroying MessageLoop via destroying BrowserMainRunner destructor
// WebEngineContext's pointer is used.
+ m_closingDown = true;
m_handle->destroy();
#if !defined(NDEBUG)
if (!m_handle->HasOneRef())
@@ -492,25 +680,48 @@ ProxyAuthentication WebEngineContext::qProxyNetworkAuthentication(QString host,
const static char kChromiumFlagsEnv[] = "QTWEBENGINE_CHROMIUM_FLAGS";
const static char kDisableSandboxEnv[] = "QTWEBENGINE_DISABLE_SANDBOX";
-const static char kDisableInProcGpuThread[] = "QTWEBENGINE_DISABLE_GPU_THREAD";
-static void appendToFeatureList(std::string &featureList, const char *feature)
+static void initializeFeatureList(base::CommandLine *commandLine, std::vector<std::string> enableFeatures, std::vector<std::string> disableFeatures)
{
- if (featureList.empty())
- featureList = feature;
- else
- featureList = featureList + "," + feature;
-}
+ std::string enableFeaturesString = base::JoinString(enableFeatures, ",");
+ if (commandLine->HasSwitch(switches::kEnableFeatures)) {
+ std::string commandLineEnableFeatures = commandLine->GetSwitchValueASCII(switches::kEnableFeatures);
-static void appendToFeatureSwitch(base::CommandLine *commandLine, const char *featureSwitch, std::string feature)
-{
- if (!commandLine->HasSwitch(featureSwitch)) {
- commandLine->AppendSwitchASCII(featureSwitch, feature);
- } else {
- std::string featureList = commandLine->GetSwitchValueASCII(featureSwitch);
- featureList = featureList + "," + feature;
- commandLine->AppendSwitchASCII(featureSwitch, featureList);
+ for (const std::string &enableFeature : base::SplitString(commandLineEnableFeatures, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
+ auto it = std::find(disableFeatures.begin(), disableFeatures.end(), enableFeature);
+ if (it == disableFeatures.end())
+ continue;
+
+ qWarning("An unsupported feature has been enabled from command line: %s\n"
+ "The feature is enabled but there is no guarantee that it will work or not break QtWebEngine.", enableFeature.c_str());
+
+ // If a feature is disabled and enabled at the same time, then it will be disabled.
+ // Remove feature from the disable list to make it possible to override from command line.
+ disableFeatures.erase(it);
+ }
+
+ enableFeaturesString = enableFeaturesString + "," + commandLineEnableFeatures;
+ }
+
+ std::string disableFeaturesString = base::JoinString(disableFeatures, ",");
+ if (commandLine->HasSwitch(switches::kDisableFeatures)) {
+ std::string commandLineDisableFeatures = commandLine->GetSwitchValueASCII(switches::kDisableFeatures);
+
+ for (const std::string &disableFeature : base::SplitString(commandLineDisableFeatures, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
+ auto it = std::find(enableFeatures.begin(), enableFeatures.end(), disableFeature);
+ if (it == enableFeatures.end())
+ continue;
+
+ qWarning("An essential feature has been disabled from command line: %s\n"
+ "The feature is disabled but there is no guarantee that it will not break QtWebEngine.", disableFeature.c_str());
+ }
+
+ disableFeaturesString = disableFeaturesString + "," + commandLineDisableFeatures;
}
+
+ commandLine->AppendSwitchASCII(switches::kEnableFeatures, enableFeaturesString);
+ commandLine->AppendSwitchASCII(switches::kDisableFeatures, disableFeaturesString);
+ base::FeatureList::InitializeInstance(enableFeaturesString, disableFeaturesString);
}
WebEngineContext::WebEngineContext()
@@ -520,11 +731,11 @@ WebEngineContext::WebEngineContext()
#if defined(Q_OS_MACOS)
// The bundled handling is currently both completely broken in Chromium,
// and unnecessary for us.
- base::mac::SetOverrideAmIBundled(false);
+ base::apple::SetOverrideAmIBundled(false);
#endif
base::ThreadPoolInstance::Create("Browser");
- m_contentRunner.reset(content::ContentMainRunner::Create());
+ m_contentRunner = content::ContentMainRunner::Create();
m_browserRunner = content::BrowserMainRunner::Create();
#ifdef Q_OS_LINUX
@@ -537,7 +748,6 @@ WebEngineContext::WebEngineContext()
// User might have registered "qrc" already with different options.
QWebEngineUrlScheme qrcScheme(QByteArrayLiteral("qrc"));
qrcScheme.setFlags(QWebEngineUrlScheme::SecureScheme
- | QWebEngineUrlScheme::LocalAccessAllowed
| QWebEngineUrlScheme::ViewSourceAllowed);
QWebEngineUrlScheme::registerScheme(qrcScheme);
}
@@ -547,241 +757,191 @@ WebEngineContext::WebEngineContext()
// Allow us to inject javascript like any webview toolkit.
content::RenderFrameHost::AllowInjectingJavaScript();
- QStringList appArgs = QCoreApplication::arguments();
-
- // If user requested GL support instead of using Skia rendering to
- // bitmaps, use software rendering via software OpenGL. This might be less
- // performant, but at least provides WebGL support.
- // TODO(miklocek), check if this still works with latest chromium
- bool enableGLSoftwareRendering = appArgs.contains(QStringLiteral("--enable-webgl-software-rendering"));
-
bool useEmbeddedSwitches = false;
-#if defined(QTWEBENGINE_EMBEDDED_SWITCHES)
- useEmbeddedSwitches = !appArgs.contains(QStringLiteral("--disable-embedded-switches"));
-#else
- useEmbeddedSwitches = appArgs.contains(QStringLiteral("--enable-embedded-switches"));
-#endif
+ bool enableGLSoftwareRendering = false;
+ base::CommandLine *parsedCommandLine =
+ initCommandLine(useEmbeddedSwitches, enableGLSoftwareRendering);
- base::CommandLine* parsedCommandLine = commandLine();
setupProxyPac(parsedCommandLine);
parsedCommandLine->AppendSwitchPath(switches::kBrowserSubprocessPath, WebEngineLibraryInfo::getPath(content::CHILD_PROCESS_EXE));
+ parsedCommandLine->AppendSwitchASCII(switches::kApplicationName, QCoreApplication::applicationName().toUtf8().toPercentEncoding().toStdString());
+
// Enable sandboxing on OS X and Linux (Desktop / Embedded) by default.
bool disable_sandbox = qEnvironmentVariableIsSet(kDisableSandboxEnv);
if (!disable_sandbox) {
#if defined(Q_OS_LINUX)
- parsedCommandLine->AppendSwitch(service_manager::switches::kDisableSetuidSandbox);
+ parsedCommandLine->AppendSwitch(sandbox::policy::switches::kDisableSetuidSandbox);
#endif
} else {
- parsedCommandLine->AppendSwitch(service_manager::switches::kNoSandbox);
+ parsedCommandLine->AppendSwitch(sandbox::policy::switches::kNoSandbox);
qInfo() << "Sandboxing disabled by user.";
}
- parsedCommandLine->AppendSwitch(switches::kEnableThreadedCompositing);
-
-#if defined(Q_OS_WIN)
- // This switch is used in Chromium's gl_context_wgl.cc file to determine whether to create
- // an OpenGL Core Profile context. If the switch is not set, it would always try to create a
- // Core Profile context, even if Qt uses a legacy profile, which causes
- // "Could not share GL contexts" warnings, because it's not possible to share between Core and
- // legacy profiles. See GLContextWGL::Initialize().
- // Given that Desktop GL Core profile is not currently supported on Windows anyway, pass this
- // switch to get rid of the warnings.
- //
- // The switch is also used to determine which version of OpenGL ES to use (2 or 3) when using
- // ANGLE.
- // If the switch is not set, Chromium will always try to create an ES3 context, even if Qt uses
- // an ES2 context, which causes resource sharing issues (black screen),
- // see gpu::gles2::GenerateGLContextAttribs().
- // Make sure to disable ES3 context creation when using ES2.
- const bool isGLES2Context = qt_gl_global_share_context()
- && qt_gl_global_share_context()->isOpenGLES()
- && qt_gl_global_share_context()->format().majorVersion() == 2;
- const bool isDesktopGLOrSoftware = !usingANGLE();
-
- if (isDesktopGLOrSoftware || isGLES2Context)
- parsedCommandLine->AppendSwitch(switches::kDisableES3GLContext);
-#endif
- bool threadedGpu = false;
-#if QT_CONFIG(opengl)
- threadedGpu = QOpenGLContext::supportsThreadedOpenGL();
-#if defined(Q_OS_MACOS)
- // QtBase disabled it when building on 10.14+, unfortunately we still need it
- // until we have fixed single-threaded viz-display-compositor.
- threadedGpu = true;
-#endif
-#endif
- threadedGpu = threadedGpu && !qEnvironmentVariableIsSet(kDisableInProcGpuThread);
-
- std::string disableFeatures;
- std::string enableFeatures;
- // Needed to allow navigations within pages that were set using setHtml(). One example is
- // tst_QWebEnginePage::acceptNavigationRequest.
- // This is deprecated behavior, and will be removed in a future Chromium version, as per
- // upstream Chromium commit ba52f56207a4b9d70b34880fbff2352e71a06422.
- appendToFeatureList(enableFeatures, features::kAllowContentInitiatedDataUrlNavigations.name);
+ // Do not advertise a feature we have removed at compile time
+ parsedCommandLine->AppendSwitch(switches::kDisableSpeechAPI);
- appendToFeatureList(enableFeatures, features::kTracingServiceInProcess.name);
+ std::vector<std::string> disableFeatures;
+ std::vector<std::string> enableFeatures;
- // The video-capture service is not functioning at this moment (since 69)
- appendToFeatureList(disableFeatures, features::kMojoVideoCapture.name);
+ enableFeatures.push_back(features::kNetworkServiceInProcess.name);
+ enableFeatures.push_back(features::kTracingServiceInProcess.name);
-#if defined(Q_OS_LINUX)
- // broken and crashy (even upstream):
- appendToFeatureList(disableFeatures, features::kFontSrcLocalMatching.name);
-#endif
+ // When enabled, event.movement is calculated in blink instead of in browser.
+ disableFeatures.push_back(features::kConsolidatedMovementXY.name);
- // We don't support the skia renderer (enabled by default on Linux since 80)
- appendToFeatureList(disableFeatures, features::kUseSkiaRenderer.name);
+ // Avoid crashing when websites tries using this feature (since 83)
+ disableFeatures.push_back(features::kInstalledApp.name);
- appendToFeatureList(disableFeatures, network::features::kDnsOverHttpsUpgrade.name);
-
- // When enabled, event.movement is calculated in blink instead of in browser.
- appendToFeatureList(disableFeatures, features::kConsolidatedMovementXY.name);
+ // Not implemented but it overrides the devtools eyedropper
+ // Should be sync with kEyeDropper base::Feature
+ parsedCommandLine->AppendSwitchASCII(switches::kDisableBlinkFeatures, "EyeDropperAPI");
+ disableFeatures.push_back(features::kEyeDropper.name);
// Explicitly tell Chromium about default-on features we do not support
- appendToFeatureList(disableFeatures, features::kBackgroundFetch.name);
- appendToFeatureList(disableFeatures, features::kSmsReceiver.name);
- appendToFeatureList(disableFeatures, features::kWebAuth.name);
- appendToFeatureList(disableFeatures, features::kWebAuthCable.name);
- appendToFeatureList(disableFeatures, features::kWebPayments.name);
- appendToFeatureList(disableFeatures, features::kWebUsb.name);
- appendToFeatureList(disableFeatures, media::kPictureInPicture.name);
+ disableFeatures.push_back(features::kBackgroundFetch.name);
+ disableFeatures.push_back(features::kWebOTP.name);
+ disableFeatures.push_back(features::kWebPayments.name);
+ disableFeatures.push_back(features::kWebUsb.name);
if (useEmbeddedSwitches) {
// embedded switches are based on the switches for Android, see content/browser/android/content_startup_flags.cc
- appendToFeatureList(enableFeatures, features::kOverlayScrollbar.name);
+ enableFeatures.push_back(features::kOverlayScrollbar.name);
parsedCommandLine->AppendSwitch(switches::kEnableViewport);
- parsedCommandLine->AppendSwitch(switches::kMainFrameResizesAreOrientationChanges);
parsedCommandLine->AppendSwitch(cc::switches::kDisableCompositedAntialiasing);
}
- appendToFeatureSwitch(parsedCommandLine, switches::kDisableFeatures, disableFeatures);
- appendToFeatureSwitch(parsedCommandLine, switches::kEnableFeatures, enableFeatures);
- base::FeatureList::InitializeInstance(
- parsedCommandLine->GetSwitchValueASCII(switches::kEnableFeatures),
- parsedCommandLine->GetSwitchValueASCII(switches::kDisableFeatures));
-
- GLContextHelper::initialize();
-
- const char *glType = 0;
-#if QT_CONFIG(opengl)
-
- const bool tryGL = (usingDefaultSGBackend() && !usingSoftwareDynamicGL() &&
- QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL))
- || enableGLSoftwareRendering;
- if (tryGL) {
- if (qt_gl_global_share_context() && qt_gl_global_share_context()->isValid()) {
- // If the native handle is QEGLNativeContext try to use GL ES/2.
- // If there is no native handle, assume we are using wayland and try GL ES/2.
- // If we are using ANGLE on Windows, use OpenGL ES (2 or 3).
- if (qt_gl_global_share_context()->nativeHandle().isNull()
- || !strcmp(qt_gl_global_share_context()->nativeHandle().typeName(),
- "QEGLNativeContext")
- || usingANGLE())
- {
- if (qt_gl_global_share_context()->isOpenGLES()) {
- glType = usingANGLE() ? gl::kGLImplementationANGLEName : gl::kGLImplementationEGLName;
- } else {
- QOpenGLContext context;
- QSurfaceFormat format;
-
- format.setRenderableType(QSurfaceFormat::OpenGL);
- format.setVersion(2, 0);
-
- context.setFormat(format);
- context.setShareContext(qt_gl_global_share_context());
- if (context.create()) {
- QOffscreenSurface surface;
-
- surface.setFormat(format);
- surface.create();
-
- if (context.makeCurrent(&surface)) {
- if (context.hasExtension("GL_ARB_ES2_compatibility"))
- glType = gl::kGLImplementationEGLName;
-
- context.doneCurrent();
- }
-
- surface.destroy();
- }
- }
- } else {
- if (!qt_gl_global_share_context()->isOpenGLES()) {
- // Default to Desktop non-Core profile OpenGL.
- glType = gl::kGLImplementationDesktopName;
-
- // Check if Core profile was requested and is supported.
- QSurfaceFormat globalSharedFormat = qt_gl_global_share_context()->format();
- if (globalSharedFormat.profile() == QSurfaceFormat::CoreProfile) {
-#ifdef Q_OS_MACOS
- glType = gl::kGLImplementationCoreProfileName;
-#else
- qWarning("An OpenGL Core Profile was requested, but it is not supported "
- "on the current platform. Falling back to a non-Core profile. "
- "Note that this might cause rendering issues.");
-#endif
- }
- }
+#if QT_CONFIG(webengine_vulkan) && defined(USE_OZONE)
+ if (QQuickWindow::graphicsApi() == QSGRendererInterface::Vulkan) {
+ enableFeatures.push_back(features::kVulkan.name);
+ parsedCommandLine->AppendSwitchASCII(switches::kUseVulkan,
+ switches::kVulkanImplementationNameNative);
+ const char deviceExtensionsVar[] = "QT_VULKAN_DEVICE_EXTENSIONS";
+ QByteArrayList requiredDeviceExtensions = { "VK_KHR_external_memory_fd",
+ "VK_EXT_external_memory_dma_buf",
+ "VK_EXT_image_drm_format_modifier" };
+ if (qEnvironmentVariableIsSet(deviceExtensionsVar)) {
+ QByteArrayList envExtList = qgetenv(deviceExtensionsVar).split(';');
+ int found = 0;
+ for (const QByteArray &ext : requiredDeviceExtensions) {
+ if (envExtList.contains(ext))
+ found++;
+ }
+ if (found != requiredDeviceExtensions.size()) {
+ qWarning().nospace()
+ << "Vulkan rendering may fail because " << deviceExtensionsVar
+ << " environment variable is already set but it doesn't contain"
+ << " some of the required Vulkan device extensions:\n"
+ << qPrintable(requiredDeviceExtensions.join('\n'));
}
- if (qt_gl_global_share_context()->format().profile() == QSurfaceFormat::CompatibilityProfile)
- parsedCommandLine->AppendSwitch(switches::kCreateDefaultGLContext);
} else {
- qWarning("WebEngineContext used before QtWebEngine::initialize() or OpenGL context creation failed.");
+ qputenv(deviceExtensionsVar, requiredDeviceExtensions.join(';'));
}
}
-#endif // QT_CONFIG(opengl)
+#endif // QT_CONFIG(webengine_vulkan) && defined(USE_OZONE)
+
+#if defined(Q_OS_WIN)
+ if (QQuickWindow::graphicsApi() == QSGRendererInterface::Direct3D11
+ || QQuickWindow::graphicsApi() == QSGRendererInterface::Vulkan) {
+ const QString luid = getAdapterLuid();
+ if (!luid.isEmpty())
+ parsedCommandLine->AppendSwitchASCII(switches::kUseAdapterLuid, luid.toStdString());
+ }
+#endif
+
+ initializeFeatureList(parsedCommandLine, enableFeatures, disableFeatures);
+
+ GLContextHelper::initialize();
- if (glType) {
+ // If user requested GL support instead of using Skia rendering to
+ // bitmaps, use software rendering via software OpenGL. This might be less
+ // performant, but at least provides WebGL support.
+ // TODO(miklocek), check if this still works with latest chromium
+ const bool disableGpu = parsedCommandLine->HasSwitch(switches::kDisableGpu);
+ std::string glType;
+ if (parsedCommandLine->HasSwitch(switches::kUseGL))
+ glType = parsedCommandLine->GetSwitchValueASCII(switches::kUseGL);
+ else {
+ glType = getGLType(enableGLSoftwareRendering, disableGpu);
parsedCommandLine->AppendSwitchASCII(switches::kUseGL, glType);
- parsedCommandLine->AppendSwitch(switches::kInProcessGPU);
+ }
+
+ parsedCommandLine->AppendSwitch(switches::kInProcessGPU);
+
+ if (glType != gl::kGLImplementationDisabledName) {
if (enableGLSoftwareRendering) {
parsedCommandLine->AppendSwitch(switches::kDisableGpuRasterization);
- parsedCommandLine->AppendSwitch(switches::kIgnoreGpuBlacklist);
+ parsedCommandLine->AppendSwitch(switches::kIgnoreGpuBlocklist);
}
- } else {
+#if QT_CONFIG(opengl)
+ if (glType != gl::kGLImplementationANGLEName) {
+ QOpenGLContext *shareContext = QOpenGLContext::globalShareContext();
+ Q_ASSERT(shareContext);
+ const QSurfaceFormat sharedFormat = shareContext->format();
+ if (sharedFormat.profile() == QSurfaceFormat::CompatibilityProfile)
+ parsedCommandLine->AppendSwitch(switches::kCreateDefaultGLContext);
+#if defined(Q_OS_WIN)
+ // This switch is used in Chromium's gl_context_wgl.cc file to determine whether to create
+ // an OpenGL Core Profile context. If the switch is not set, it would always try to create a
+ // Core Profile context, even if Qt uses a legacy profile, which causes
+ // "Could not share GL contexts" warnings, because it's not possible to share between Core and
+ // legacy profiles. See GLContextWGL::Initialize().
+ if (sharedFormat.renderableType() == QSurfaceFormat::OpenGL
+ && sharedFormat.profile() != QSurfaceFormat::CoreProfile) {
+ gl::GlWorkarounds workarounds = gl::GetGlWorkarounds();
+ workarounds.disable_es3gl_context = true;
+ gl::SetGlWorkarounds(workarounds);
+ }
+#endif
+ }
+#endif //QT_CONFIG(opengl)
+ } else if (!disableGpu) {
parsedCommandLine->AppendSwitch(switches::kDisableGpu);
}
- registerMainThreadFactories(threadedGpu);
+ logContext(glType, parsedCommandLine);
- SetContentClient(new ContentClientQt);
+ registerMainThreadFactories();
content::ContentMainParams contentMainParams(m_mainDelegate.get());
-#if defined(OS_WIN)
- contentMainParams.sandbox_info = staticSandboxInterfaceInfo();
- sandbox::SandboxInterfaceInfo sandbox_info = {0};
+ contentMainParams.setup_signal_handlers = false;
+#if defined(Q_OS_WIN)
+ contentMainParams.sandbox_info = QtWebEngineSandbox::staticSandboxInterfaceInfo();
+ sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
if (!contentMainParams.sandbox_info) {
content::InitializeSandboxInfo(&sandbox_info);
contentMainParams.sandbox_info = &sandbox_info;
}
#endif
- m_contentRunner->Initialize(contentMainParams);
+ m_contentRunner->Initialize(std::move(contentMainParams));
mojo::core::Configuration mojoConfiguration;
mojoConfiguration.is_broker_process = true;
mojo::core::Init(mojoConfiguration);
- // This block mirrors ContentMainRunnerImpl::RunServiceManager():
- m_mainDelegate->PreCreateMainMessageLoop();
+ // This block mirrors ContentMainRunnerImpl::RunBrowser():
+ m_mainDelegate->PreBrowserMain();
base::MessagePump::OverrideMessagePumpForUIFactory(messagePumpFactory);
content::BrowserTaskExecutor::Create();
- m_mainDelegate->PostEarlyInitialization(false);
+ m_mainDelegate->PostEarlyInitialization({});
content::StartBrowserThreadPool();
content::BrowserTaskExecutor::PostFeatureListSetup();
- tracing::InitTracingPostThreadPoolStartAndFeatureList();
+ tracing::InitTracingPostThreadPoolStartAndFeatureList(false);
+ base::PowerMonitor::Initialize(std::make_unique<base::PowerMonitorDeviceSource>());
+ content::ProcessVisibilityTracker::GetInstance();
m_discardableSharedMemoryManager = std::make_unique<discardable_memory::DiscardableSharedMemoryManager>();
- m_serviceManagerEnvironment = std::make_unique<content::ServiceManagerEnvironment>(content::BrowserTaskExecutor::CreateIOThread());
- m_startupData = m_serviceManagerEnvironment->CreateBrowserStartupData();
+
+ m_mojoIpcSupport = std::make_unique<content::MojoIpcSupport>(content::BrowserTaskExecutor::CreateIOThread());
+ download::SetIOTaskRunner(m_mojoIpcSupport->io_thread()->task_runner());
+ std::unique_ptr<content::StartupData> startupData = m_mojoIpcSupport->CreateBrowserStartupData();
// Once the MessageLoop has been created, attach a top-level RunLoop.
m_runLoop.reset(new base::RunLoop);
m_runLoop->BeforeRun();
- content::MainFunctionParams mainParams(*base::CommandLine::ForCurrentProcess());
- mainParams.startup_data = m_startupData.get();
- m_browserRunner->Initialize(mainParams);
+ content::MainFunctionParams mainParams(base::CommandLine::ForCurrentProcess());
+ mainParams.startup_data = std::move(startupData);
+ m_browserRunner->Initialize(std::move(mainParams));
m_devtoolsServer.reset(new DevToolsServerQt());
m_devtoolsServer->start();
@@ -793,14 +953,7 @@ WebEngineContext::WebEngineContext()
// Initialize WebCacheManager here to ensure its subscription to render process creation events.
web_cache::WebCacheManager::GetInstance();
- base::ThreadRestrictions::SetIOAllowed(true);
-
- if (parsedCommandLine->HasSwitch(network::switches::kExplicitlyAllowedPorts)) {
- std::string allowedPorts = parsedCommandLine->GetSwitchValueASCII(network::switches::kExplicitlyAllowedPorts);
- net::SetExplicitlyAllowedPorts(allowedPorts);
- }
-
-#if defined(OS_LINUX)
+#if defined(Q_OS_LINUX)
media::AudioManager::SetGlobalAppName(QCoreApplication::applicationName().toStdString());
#endif
@@ -811,7 +964,7 @@ WebEngineContext::WebEngineContext()
// be created from the FILE thread, and that GetPluginInfoArray is synchronous, it
// can't loads plugins synchronously from the IO thread to serve the render process' request
// and we need to make sure that it happened beforehand.
- content::PluginService::GetInstance()->GetPlugins(base::Bind(&dummyGetPluginCallback));
+ content::PluginService::GetInstance()->GetPlugins(base::BindOnce(&dummyGetPluginCallback));
#endif
#if QT_CONFIG(webengine_printing_and_pdf)
@@ -832,47 +985,116 @@ printing::PrintJobManager* WebEngineContext::getPrintJobManager()
}
#endif
-static QMutex s_spmMutex;
-QAtomicPointer<gpu::SyncPointManager> WebEngineContext::s_syncPointManager;
-
-gpu::SyncPointManager *WebEngineContext::syncPointManager()
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+WebRtcLogUploader *WebEngineContext::webRtcLogUploader()
{
- if (gpu::SyncPointManager *spm = s_syncPointManager.loadAcquire())
- return spm;
- QMutexLocker lock(&s_spmMutex);
- if (!s_syncPointManager)
- s_syncPointManager.store(new gpu::SyncPointManager());
- return s_syncPointManager.load();
+ if (!m_webrtcLogUploader)
+ m_webrtcLogUploader = std::make_unique<WebRtcLogUploader>();
+ return m_webrtcLogUploader.get();
}
+#endif
-base::CommandLine* WebEngineContext::commandLine() {
- if (base::CommandLine::CreateEmpty()) {
- base::CommandLine* parsedCommandLine = base::CommandLine::ForCurrentProcess();
- QStringList appArgs = QCoreApplication::arguments();
- if (qEnvironmentVariableIsSet(kChromiumFlagsEnv)) {
- appArgs = appArgs.mid(0, 1); // Take application name and drop the rest
- appArgs.append(parseEnvCommandLine(QString::fromLocal8Bit(qgetenv(kChromiumFlagsEnv))));
+
+base::CommandLine *WebEngineContext::initCommandLine(bool &useEmbeddedSwitches,
+ bool &enableGLSoftwareRendering)
+{
+ if (!base::CommandLine::CreateEmpty())
+ qFatal("base::CommandLine has been initialized unexpectedly.");
+
+ QStringList appArgs = QCoreApplication::arguments();
+ if (appArgs.empty()) {
+ qFatal("Argument list is empty, the program name is not passed to QCoreApplication. "
+ "base::CommandLine cannot be properly initialized.");
+ }
+
+ base::CommandLine *parsedCommandLine = base::CommandLine::ForCurrentProcess();
+ int index = appArgs.indexOf(QRegularExpression(QLatin1String("--webEngineArgs"),
+ QRegularExpression::CaseInsensitiveOption));
+ if (qEnvironmentVariableIsSet(kChromiumFlagsEnv)) {
+ appArgs = appArgs.mid(0, 1); // Take application name and drop the rest
+ appArgs.append(parseEnvCommandLine(qEnvironmentVariable(kChromiumFlagsEnv)));
+ if (index > -1)
+ qWarning("Note 'webEngineArgs' are overridden by QTWEBENGINE_CHROMIUM_FLAGS");
+ } else {
+ if (index > -1) {
+ appArgs.erase(appArgs.begin() + 1, appArgs.begin() + index + 1);
+ } else {
+ appArgs = appArgs.mid(0, 1);
}
-#ifdef Q_OS_WIN
- appArgs.removeAll(QStringLiteral("--enable-webgl-software-rendering"));
+ }
+#if defined(QTWEBENGINE_EMBEDDED_SWITCHES)
+ useEmbeddedSwitches = !appArgs.contains(QStringLiteral("--disable-embedded-switches"));
+#else
+ useEmbeddedSwitches = appArgs.contains(QStringLiteral("--enable-embedded-switches"));
#endif
- appArgs.removeAll(QStringLiteral("--disable-embedded-switches"));
- appArgs.removeAll(QStringLiteral("--enable-embedded-switches"));
+ enableGLSoftwareRendering =
+ appArgs.removeAll(QStringLiteral("--enable-webgl-software-rendering"));
+ appArgs.removeAll(QStringLiteral("--disable-embedded-switches"));
+ appArgs.removeAll(QStringLiteral("--enable-embedded-switches"));
+
+ bool isRemoteDebugPort =
+ (-1
+ != appArgs.indexOf(QRegularExpression(QStringLiteral("--remote-debugging-port=.*"),
+ QRegularExpression::CaseInsensitiveOption)))
+ || !qEnvironmentVariable("QTWEBENGINE_REMOTE_DEBUGGING").isEmpty();
+ bool isRemoteAllowOrigins =
+ (-1
+ != appArgs.indexOf(QRegularExpression(QStringLiteral("--remote-allow-origins=.*"),
+ QRegularExpression::CaseInsensitiveOption)));
+
+ if (isRemoteDebugPort && !isRemoteAllowOrigins) {
+ appArgs.append(QStringLiteral("--remote-allow-origins=*"));
+ qWarning("Added {--remote-allow-origins=*} to command-line arguments "
+ "to avoid web socket connection errors during remote debugging.");
+ }
- base::CommandLine::StringVector argv;
- argv.resize(appArgs.size());
+ base::CommandLine::StringVector argv;
+ argv.resize(appArgs.size());
#if defined(Q_OS_WIN)
- for (int i = 0; i < appArgs.size(); ++i)
- argv[i] = toString16(appArgs[i]);
+ for (int i = 0; i < appArgs.size(); ++i)
+ argv[i] = appArgs[i].toStdWString();
#else
- for (int i = 0; i < appArgs.size(); ++i)
- argv[i] = appArgs[i].toStdString();
+ for (int i = 0; i < appArgs.size(); ++i)
+ argv[i] = appArgs[i].toStdString();
#endif
- parsedCommandLine->InitFromArgv(argv);
- return parsedCommandLine;
- } else {
- return base::CommandLine::ForCurrentProcess();
- }
+ parsedCommandLine->InitFromArgv(argv);
+
+ return parsedCommandLine;
+}
+
+bool WebEngineContext::closingDown()
+{
+ return m_closingDown;
+}
+
+void WebEngineContext::registerMainThreadFactories()
+{
+ content::UtilityProcessHost::RegisterUtilityMainThreadFactory(content::CreateInProcessUtilityThread);
+ content::RenderProcessHostImpl::RegisterRendererMainThreadFactory(content::CreateInProcessRendererThread);
+ content::RegisterGpuMainThreadFactory(content::CreateInProcessGpuThread);
}
} // namespace
+
+QT_BEGIN_NAMESPACE
+const char *qWebEngineVersion() noexcept
+{
+ return STRINGIFY_EXPANDED(QTWEBENGINECORE_VERSION_STR);
+}
+
+const char *qWebEngineProcessName() noexcept
+{
+ return STRINGIFY_EXPANDED(QTWEBENGINEPROCESS_NAME);
+}
+
+const char *qWebEngineChromiumVersion() noexcept
+{
+ return STRINGIFY_EXPANDED(CHROMIUM_VERSION);
+}
+
+const char *qWebEngineChromiumSecurityPatchVersion() noexcept
+{
+ return "122.0.6261.128"; // FIXME: Remember to update
+}
+
+QT_END_NAMESPACE
diff --git a/src/core/web_engine_context.h b/src/core/web_engine_context.h
index 6cbd5c8e5..50b080db1 100644
--- a/src/core/web_engine_context.h
+++ b/src/core/web_engine_context.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_ENGINE_CONTEXT_H
#define WEB_ENGINE_CONTEXT_H
@@ -47,7 +11,7 @@
#include "base/values.h"
#include <QtGui/qtgui-config.h>
-#include <QVector>
+#include <QList>
namespace base {
class RunLoop;
@@ -57,11 +21,9 @@ class CommandLine;
namespace content {
class BrowserMainRunner;
class ContentMainRunner;
-class GpuProcess;
class GpuThreadController;
class InProcessChildThreadParams;
-class ServiceManagerEnvironment;
-struct StartupData;
+class MojoIpcSupport;
}
namespace discardable_memory {
@@ -70,7 +32,6 @@ class DiscardableSharedMemoryManager;
namespace gpu {
struct GpuPreferences;
-class SyncPointManager;
}
#if QT_CONFIG(webengine_printing_and_pdf)
@@ -86,6 +47,7 @@ struct SandboxInterfaceInfo;
#endif
QT_FORWARD_DECLARE_CLASS(QObject)
+class WebRtcLogUploader;
namespace QtWebEngineCore {
@@ -96,10 +58,6 @@ class ProfileAdapter;
bool usingSoftwareDynamicGL();
-#ifdef Q_OS_WIN
-Q_WEBENGINECORE_PRIVATE_EXPORT sandbox::SandboxInterfaceInfo *staticSandboxInterfaceInfo(sandbox::SandboxInterfaceInfo *info = nullptr);
-#endif
-
typedef std::tuple<bool, QString, QString> ProxyAuthentication;
class WebEngineContext : public base::RefCounted<WebEngineContext> {
@@ -107,7 +65,8 @@ public:
static WebEngineContext *current();
static void destroyContextPostRoutine();
static ProxyAuthentication qProxyNetworkAuthentication(QString host, int port);
-
+ static void flushMessages();
+ static bool closingDown();
ProfileAdapter *createDefaultProfileAdapter();
ProfileAdapter *defaultProfileAdapter();
@@ -115,13 +74,15 @@ public:
#if QT_CONFIG(webengine_printing_and_pdf)
printing::PrintJobManager* getPrintJobManager();
#endif
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ WebRtcLogUploader *webRtcLogUploader();
+#endif
void destroyProfileAdapter();
void addProfileAdapter(ProfileAdapter *profileAdapter);
void removeProfileAdapter(ProfileAdapter *profileAdapter);
void destroy();
- static base::CommandLine* commandLine();
-
- static gpu::SyncPointManager *syncPointManager();
+ static base::CommandLine *initCommandLine(bool &useEmbeddedSwitches,
+ bool &enableGLSoftwareRendering);
private:
friend class base::RefCounted<WebEngineContext>;
@@ -129,20 +90,18 @@ private:
WebEngineContext();
~WebEngineContext();
- static void registerMainThreadFactories(bool threaded);
- static void destroyGpuProcess();
+ static void registerMainThreadFactories();
std::unique_ptr<base::RunLoop> m_runLoop;
std::unique_ptr<ContentMainDelegateQt> m_mainDelegate;
std::unique_ptr<content::ContentMainRunner> m_contentRunner;
std::unique_ptr<content::BrowserMainRunner> m_browserRunner;
std::unique_ptr<discardable_memory::DiscardableSharedMemoryManager> m_discardableSharedMemoryManager;
- std::unique_ptr<content::StartupData> m_startupData;
- std::unique_ptr<content::ServiceManagerEnvironment> m_serviceManagerEnvironment;
+ std::unique_ptr<content::MojoIpcSupport> m_mojoIpcSupport;
std::unique_ptr<QObject> m_globalQObject;
std::unique_ptr<ProfileAdapter> m_defaultProfileAdapter;
std::unique_ptr<DevToolsServerQt> m_devtoolsServer;
- QVector<ProfileAdapter*> m_profileAdapters;
+ QList<ProfileAdapter*> m_profileAdapters;
#if QT_CONFIG(accessibility)
std::unique_ptr<AccessibilityActivationObserver> m_accessibilityActivationObserver;
#endif
@@ -150,9 +109,12 @@ private:
#if QT_CONFIG(webengine_printing_and_pdf)
std::unique_ptr<printing::PrintJobManager> m_printJobManager;
#endif
+#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions)
+ std::unique_ptr<WebRtcLogUploader> m_webrtcLogUploader;
+#endif
static scoped_refptr<QtWebEngineCore::WebEngineContext> m_handle;
static bool m_destroyed;
- static QAtomicPointer<gpu::SyncPointManager> s_syncPointManager;
+ static bool m_closingDown;
};
} // namespace
diff --git a/src/core/web_engine_context_threads.cpp b/src/core/web_engine_context_threads.cpp
deleted file mode 100644
index ba3e18499..000000000
--- a/src/core/web_engine_context_threads.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "web_engine_context.h"
-
-#include "base/bind.h"
-#include "base/task/post_task.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/thread_restrictions.h"
-#include "content/browser/gpu/gpu_main_thread_factory.h"
-#include "content/browser/renderer_host/render_process_host_impl.h"
-#include "content/browser/utility_process_host.h"
-#include "content/gpu/gpu_child_thread.h"
-#include "content/gpu/gpu_process.h"
-#include "content/gpu/in_process_gpu_thread.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/renderer/in_process_renderer_thread.h"
-#include "content/utility/in_process_utility_thread.h"
-#include "gpu/ipc/service/gpu_init.h"
-
-#include <memory>
-
-#include <QEventLoop>
-
-namespace QtWebEngineCore {
-
-struct GpuThreadControllerQt : content::GpuThreadController
-{
- GpuThreadControllerQt(const content::InProcessChildThreadParams &params, const gpu::GpuPreferences &gpuPreferences)
- {
- base::PostTask(
- FROM_HERE, { content::BrowserThread::UI },
- base::BindOnce(&GpuThreadControllerQt::createGpuProcess, params, gpuPreferences));
- }
- ~GpuThreadControllerQt() override
- {
- base::PostTask(
- FROM_HERE, { content::BrowserThread::UI },
- base::BindOnce(&GpuThreadControllerQt::destroyGpuProcess));
- }
-
- static void createGpuProcess(
- const content::InProcessChildThreadParams &params,
- const gpu::GpuPreferences &gpuPreferences)
- {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (s_gpuProcessDestroyed)
- return;
-
- s_gpuProcess = std::make_unique<content::GpuProcess>(base::ThreadPriority::DISPLAY);
- auto gpuInit = std::make_unique<gpu::GpuInit>();
- gpuInit->InitializeInProcess(base::CommandLine::ForCurrentProcess(), gpuPreferences);
- auto childThread = new content::GpuChildThread(params, std::move(gpuInit));
- childThread->Init(base::Time::Now());
- s_gpuProcess->set_main_thread(childThread);
- }
-
- static void destroyGpuProcess()
- {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (s_gpuProcessDestroyed)
- return;
-
- // viz::GpuServiceImpl::~GpuServiceImpl waits for io task.
- base::ScopedAllowBaseSyncPrimitivesForTesting allow;
- s_gpuProcess.reset();
- s_gpuProcessDestroyed = true;
- }
-
- static std::unique_ptr<content::GpuProcess> s_gpuProcess;
- static bool s_gpuProcessDestroyed;
-};
-
-std::unique_ptr<content::GpuProcess> GpuThreadControllerQt::s_gpuProcess;
-bool GpuThreadControllerQt::s_gpuProcessDestroyed = false;
-
-static std::unique_ptr<content::GpuThreadController> createGpuThreadController(
- const content::InProcessChildThreadParams &params,
- const gpu::GpuPreferences &gpuPreferences)
-{
- return std::make_unique<GpuThreadControllerQt>(params, gpuPreferences);
-}
-
-// static
-void WebEngineContext::destroyGpuProcess()
-{
- GpuThreadControllerQt::destroyGpuProcess();
-}
-
-// static
-void WebEngineContext::registerMainThreadFactories(bool threaded)
-{
- content::UtilityProcessHost::RegisterUtilityMainThreadFactory(content::CreateInProcessUtilityThread);
- content::RenderProcessHostImpl::RegisterRendererMainThreadFactory(content::CreateInProcessRendererThread);
- if (threaded)
- content::RegisterGpuMainThreadFactory(content::CreateInProcessGpuThread);
- else
- content::RegisterGpuMainThreadFactory(createGpuThreadController);
-}
-
-} // namespace QtWebEngineCore
diff --git a/src/core/web_engine_error.cpp b/src/core/web_engine_error.cpp
index 0d326473b..c18dfef8c 100644
--- a/src/core/web_engine_error.cpp
+++ b/src/core/web_engine_error.cpp
@@ -1,55 +1,26 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "web_engine_error.h"
+
+#include "components/error_page/common/error.h"
+#include "components/error_page/common/localized_error.h"
#include "net/base/net_errors.h"
+#include "type_conversion.h"
+
+#include <QString>
+
+using namespace QtWebEngineCore;
+
const int WebEngineError::UserAbortedError = net::ERR_ABORTED;
namespace {
const int noError = 0;
-const int systemRelatedErrors = -1;
const int connectionRelatedErrors = -100;
const int certificateErrors = -200;
const int httpErrors = -300;
const int cacheErrors = -400;
-const int internalErrors = -500;
const int ftpErrors = -600;
const int certificateManagerErrors = -700;
const int dnsResolverErrors = -800;
@@ -58,6 +29,10 @@ const int endErrors = -900;
WebEngineError::ErrorDomain WebEngineError::toQtErrorDomain(int error_code)
{
+ // net errors are always negative values, and https response codes are positive
+ if (error_code > 0)
+ return HttpStatusCodeDomain;
+
// Chromium's ranges from net/base/net_error_list.h:
// 0 No error
// 1- 99 System related errors
@@ -86,3 +61,13 @@ WebEngineError::ErrorDomain WebEngineError::toQtErrorDomain(int error_code)
else
return WebEngineError::InternalErrorDomain;
}
+
+QString WebEngineError::toQtErrorDescription(int errorCode)
+{
+ if (errorCode < 0)
+ return toQt(net::ErrorToString(errorCode));
+ else if (errorCode > 0)
+ return toQt(error_page::LocalizedError::GetErrorDetails(
+ error_page::Error::kHttpErrorDomain, errorCode, false, false));
+ return QString();
+}
diff --git a/src/core/web_engine_error.h b/src/core/web_engine_error.h
index cda9e4625..b43678ad2 100644
--- a/src/core/web_engine_error.h
+++ b/src/core/web_engine_error.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,9 +15,9 @@
#ifndef WEB_ENGINE_ERROR_H
#define WEB_ENGINE_ERROR_H
-#include "qtwebenginecoreglobal_p.h"
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
-class Q_WEBENGINECORE_PRIVATE_EXPORT WebEngineError
+class Q_WEBENGINECORE_EXPORT WebEngineError
{
public:
@@ -64,13 +28,14 @@ public:
CertificateErrorDomain,
HttpErrorDomain,
FtpErrorDomain,
- DnsErrorDomain
+ DnsErrorDomain,
+ HttpStatusCodeDomain
};
static const int UserAbortedError;
static ErrorDomain toQtErrorDomain(int error_code);
-
+ static QString toQtErrorDescription(int errorCode);
};
#endif // WEB_ENGINE_ERROR_H
diff --git a/src/core/web_engine_library_info.cpp b/src/core/web_engine_library_info.cpp
index 1c8316430..e71153899 100644
--- a/src/core/web_engine_library_info.cpp
+++ b/src/core/web_engine_library_info.cpp
@@ -1,43 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+#include "qtwebenginecoreglobal_p.h"
#include "web_engine_library_info.h"
#include "base/base_paths.h"
@@ -45,8 +10,11 @@
#include "base/files/file_util.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "content/public/common/content_paths.h"
+#include "sandbox/policy/switches.h"
+#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
+
#include "type_conversion.h"
#include <QByteArray>
@@ -55,8 +23,12 @@
#include <QFileInfo>
#include <QLibraryInfo>
#include <QLocale>
+#include <QLoggingCategory>
#include <QStandardPaths>
-#include <QString>
+
+#if defined(Q_OS_WIN)
+#include <windows.h>
+#endif
#ifndef QTWEBENGINEPROCESS_NAME
#error "No name defined for QtWebEngine's process"
@@ -64,6 +36,8 @@
using namespace QtWebEngineCore;
+Q_LOGGING_CATEGORY(webEngineLibraryInfoLog, "qt.webengine.libraryinfo")
+
namespace {
QString fallbackDir() {
@@ -71,19 +45,19 @@ QString fallbackDir() {
return directory;
}
-#if defined(OS_MACOSX) && defined(QT_MAC_FRAMEWORK_BUILD)
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
static inline CFBundleRef frameworkBundle()
{
- return CFBundleGetBundleWithIdentifier(CFSTR("org.qt-project.Qt.QtWebEngineCore"));
+ return CFBundleGetBundleWithIdentifier(CFSTR("org.qt-project.QtWebEngineCore"));
}
-static QString getPath(CFBundleRef frameworkBundle)
+static QString getBundlePath(CFBundleRef frameworkBundle)
{
QString path;
// The following is a fix for QtWebEngineProcess crashes on OS X 10.7 and before.
// We use it for the other OS X versions as well to make sure it works and because
// the directory structure should be the same.
- if (qApp->applicationName() == QLatin1String(QTWEBENGINEPROCESS_NAME)) {
+ if (qApp->applicationName() == QLatin1String(qWebEngineProcessName())) {
path = QDir::cleanPath(qApp->applicationDirPath() % QLatin1String("/../../../.."));
} else if (frameworkBundle) {
CFURLRef bundleUrl = CFBundleCopyBundleURL(frameworkBundle);
@@ -101,12 +75,12 @@ static QString getResourcesPath(CFBundleRef frameworkBundle)
// The following is a fix for QtWebEngineProcess crashes on OS X 10.7 and before.
// We use it for the other OS X versions as well to make sure it works and because
// the directory structure should be the same.
- if (qApp->applicationName() == QLatin1String(QTWEBENGINEPROCESS_NAME)) {
- path = getPath(frameworkBundle) % QLatin1String("/Resources");
+ if (qApp->applicationName() == QLatin1String(qWebEngineProcessName())) {
+ path = getBundlePath(frameworkBundle) % QLatin1String("/Resources");
} else if (frameworkBundle) {
CFURLRef resourcesRelativeUrl = CFBundleCopyResourcesDirectoryURL(frameworkBundle);
CFStringRef resourcesRelativePath = CFURLCopyFileSystemPath(resourcesRelativeUrl, kCFURLPOSIXPathStyle);
- path = getPath(frameworkBundle) % QLatin1Char('/') % QString::fromCFString(resourcesRelativePath);
+ path = getBundlePath(frameworkBundle) % QLatin1Char('/') % QString::fromCFString(resourcesRelativePath);
CFRelease(resourcesRelativePath);
CFRelease(resourcesRelativeUrl);
}
@@ -114,7 +88,7 @@ static QString getResourcesPath(CFBundleRef frameworkBundle)
}
#endif
-#if defined(OS_MACOSX)
+#if defined(Q_OS_DARWIN)
static QString getMainApplicationResourcesPath()
{
QString resourcesPath;
@@ -146,37 +120,62 @@ QString subProcessPath()
{
static QString processPath;
if (processPath.isEmpty()) {
-#if defined(OS_WIN)
- const QString processBinary = QLatin1String(QTWEBENGINEPROCESS_NAME) % QLatin1String(".exe");
+#if defined(Q_OS_WIN)
+ const QString processBinary = QLatin1String(qWebEngineProcessName()) % QLatin1String(".exe");
#else
- const QString processBinary = QLatin1String(QTWEBENGINEPROCESS_NAME);
+ const QString processBinary = QLatin1String(qWebEngineProcessName());
#endif
QStringList candidatePaths;
- const QByteArray fromEnv = qgetenv("QTWEBENGINEPROCESS_PATH");
+ const QString fromEnv = qEnvironmentVariable("QTWEBENGINEPROCESS_PATH");
if (!fromEnv.isEmpty()) {
// Only search in QTWEBENGINEPROCESS_PATH if set
- candidatePaths << QString::fromLocal8Bit(fromEnv);
+ candidatePaths << fromEnv;
} else {
-#if defined(OS_MACOSX) && defined(QT_MAC_FRAMEWORK_BUILD)
- candidatePaths << getPath(frameworkBundle())
- % QStringLiteral("/Helpers/" QTWEBENGINEPROCESS_NAME ".app/Contents/MacOS/" QTWEBENGINEPROCESS_NAME);
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+ candidatePaths << getBundlePath(frameworkBundle()) % QStringLiteral("/Helpers/")
+ % qWebEngineProcessName() % QStringLiteral(".app/Contents/MacOS/")
+ % qWebEngineProcessName();
#else
- candidatePaths << QLibraryInfo::location(QLibraryInfo::LibraryExecutablesPath)
+ candidatePaths << QLibraryInfo::path(QLibraryInfo::LibraryExecutablesPath)
+ % QLatin1Char('/') % processBinary;
+ candidatePaths << QLibraryInfo::path(QLibraryInfo::BinariesPath)
% QLatin1Char('/') % processBinary;
#endif
candidatePaths << QCoreApplication::applicationDirPath()
% QLatin1Char('/') % processBinary;
}
- for (const QString &candidate : qAsConst(candidatePaths)) {
+ for (const QString &candidate : std::as_const(candidatePaths)) {
if (QFileInfo::exists(candidate)) {
processPath = candidate;
+ qCDebug(webEngineLibraryInfoLog, "Qt WebEngine process path: %s",
+ qPrintable(candidate));
break;
}
}
- if (processPath.isEmpty())
- qFatal("Could not find %s", processBinary.toUtf8().constData());
+ if (processPath.isEmpty()) {
+ QStringList errorMessage;
+ errorMessage.append(
+ QStringLiteral("The following paths were searched for Qt WebEngine Process:"));
+ for (const QString &candidate : std::as_const(candidatePaths))
+ errorMessage.append(QStringLiteral(" ") % candidate);
+ errorMessage.append(QStringLiteral("but could not find it."));
+ if (fromEnv.isEmpty()) {
+ errorMessage.append(
+ QStringLiteral("You may override the default search path by using "
+ "QTWEBENGINEPROCESS_PATH environment variable."));
+ }
+ qFatal("%s", qPrintable(errorMessage.join('\n')));
+ }
+
+#if defined(Q_OS_WIN)
+ base::CommandLine *parsedCommandLine = base::CommandLine::ForCurrentProcess();
+ if (!parsedCommandLine->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
+ if (WebEngineLibraryInfo::isUNCPath(processPath) || WebEngineLibraryInfo::isRemoteDrivePath(processPath))
+ qCritical("Can not launch QtWebEngineProcess from network path if sandbox is enabled: %s.", processPath.toUtf8().constData());
+ }
+#endif
}
@@ -186,23 +185,55 @@ QString subProcessPath()
QString localesPath()
{
- static bool initialized = false;
- static QString potentialLocalesPath =
-#if defined(OS_MACOSX) && defined(QT_MAC_FRAMEWORK_BUILD)
- getResourcesPath(frameworkBundle()) % QLatin1String("/qtwebengine_locales");
+ static QString potentialLocalesPath;
+ if (potentialLocalesPath.isEmpty()) {
+ QStringList candidatePaths;
+ const QString translationPakFilename =
+#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0)
+ QLatin1String(WebEngineLibraryInfo::getResolvedLocale() + ".pak");
#else
- QLibraryInfo::location(QLibraryInfo::TranslationsPath) % QDir::separator() % QLatin1String("qtwebengine_locales");
+ QLatin1String((WebEngineLibraryInfo::getResolvedLocale() + ".pak").c_str());
+#endif
+ const QString fromEnv = qEnvironmentVariable("QTWEBENGINE_LOCALES_PATH");
+ if (!fromEnv.isEmpty()) {
+ // Only search in QTWEBENGINE_LOCALES_PATH if set
+ candidatePaths << fromEnv;
+ } else {
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+ candidatePaths << getResourcesPath(frameworkBundle()) % QDir::separator()
+ % QLatin1String("qtwebengine_locales");
#endif
+ candidatePaths << QLibraryInfo::path(QLibraryInfo::TranslationsPath) % QDir::separator()
+ % QLatin1String("qtwebengine_locales");
+ candidatePaths << fallbackDir();
+ }
- if (!initialized) {
- initialized = true;
- if (!QFileInfo::exists(potentialLocalesPath)) {
- qWarning("Installed Qt WebEngine locales directory not found at location %s. Trying application directory...", qPrintable(potentialLocalesPath));
- potentialLocalesPath = QCoreApplication::applicationDirPath() % QDir::separator() % QLatin1String("qtwebengine_locales");
+ for (const QString &candidate : std::as_const(candidatePaths)) {
+ if (QFileInfo::exists(candidate % QDir::separator() % translationPakFilename)) {
+ potentialLocalesPath = candidate;
+ qCDebug(webEngineLibraryInfoLog, "Qt WebEngine locales path: %s",
+ qPrintable(candidate));
+ break;
+ }
}
- if (!QFileInfo::exists(potentialLocalesPath)) {
- qWarning("Qt WebEngine locales directory not found at location %s. Trying fallback directory... Translations MAY NOT not be correct.", qPrintable(potentialLocalesPath));
- potentialLocalesPath = fallbackDir();
+
+ if (potentialLocalesPath.isEmpty()) {
+ QStringList warningMessage;
+ warningMessage.append(
+ QStringLiteral("The following paths were searched for Qt WebEngine locales:"));
+ for (const QString &candidate : std::as_const(candidatePaths))
+ warningMessage.append(QStringLiteral(" ") % candidate);
+ warningMessage.append(
+ QStringLiteral(
+ "but could not find the translation file for the current locale: ")
+ % translationPakFilename);
+ if (fromEnv.isEmpty()) {
+ warningMessage.append(
+ QStringLiteral("You may override the default search paths by using "
+ "QTWEBENGINE_LOCALES_PATH environment variable."));
+ }
+ warningMessage.append(QStringLiteral("Translations WILL NOT be correct."));
+ qWarning("%s", qPrintable(warningMessage.join('\n')));
}
}
@@ -218,13 +249,13 @@ QString dictionariesPath()
if (!initialized) {
initialized = true;
- const QByteArray fromEnv = qgetenv("QTWEBENGINE_DICTIONARIES_PATH");
+ const QString fromEnv = qEnvironmentVariable("QTWEBENGINE_DICTIONARIES_PATH");
if (!fromEnv.isEmpty()) {
// Only search in QTWEBENGINE_DICTIONARIES_PATH if set
- candidatePaths << QString::fromLocal8Bit(fromEnv);
+ candidatePaths << fromEnv;
} else {
// First try to find dictionaries near the application.
-#ifdef OS_MACOSX
+#ifdef Q_OS_DARWIN
QString resourcesDictionariesPath = getMainApplicationResourcesPath()
% QDir::separator() % QLatin1String("qtwebengine_dictionaries");
candidatePaths << resourcesDictionariesPath;
@@ -234,51 +265,80 @@ QString dictionariesPath()
candidatePaths << applicationDictionariesPath;
// Then try to find dictionaries near the installed library.
-#if defined(OS_MACOSX) && defined(QT_MAC_FRAMEWORK_BUILD)
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
QString frameworkDictionariesPath = getResourcesPath(frameworkBundle())
% QLatin1String("/qtwebengine_dictionaries");
candidatePaths << frameworkDictionariesPath;
#endif
- QString libraryDictionariesPath = QLibraryInfo::location(QLibraryInfo::DataPath)
+ QString libraryDictionariesPath = QLibraryInfo::path(QLibraryInfo::DataPath)
% QDir::separator() % QLatin1String("qtwebengine_dictionaries");
candidatePaths << libraryDictionariesPath;
}
- for (const QString &candidate : qAsConst(candidatePaths)) {
+ for (const QString &candidate : std::as_const(candidatePaths)) {
if (QFileInfo::exists(candidate)) {
potentialDictionariesPath = candidate;
+ qCDebug(webEngineLibraryInfoLog, "Qt WebEngine dictionaries path: %s",
+ qPrintable(candidate));
break;
}
}
+
+ if (potentialDictionariesPath.isEmpty()) {
+ // return path for error message
+ potentialDictionariesPath = QCoreApplication::applicationDirPath() % QDir::separator()
+ % QLatin1String("qtwebengine_dictionaries");
+ }
}
return potentialDictionariesPath;
}
#endif // QT_CONFIG(webengine_spellchecker)
-QString resourcesDataPath()
+QString resourcesPath()
{
- static bool initialized = false;
- static QString potentialResourcesPath =
-#if defined(OS_MACOSX) && defined(QT_MAC_FRAMEWORK_BUILD)
- getResourcesPath(frameworkBundle());
-#else
- QLibraryInfo::location(QLibraryInfo::DataPath) % QLatin1String("/resources");
+ static QString potentialResourcesPath;
+ if (potentialResourcesPath.isEmpty()) {
+ QStringList candidatePaths;
+ const QString resourcesPakFilename = QLatin1String("qtwebengine_resources.pak");
+ const QString fromEnv = qEnvironmentVariable("QTWEBENGINE_RESOURCES_PATH");
+ if (!fromEnv.isEmpty()) {
+ // Only search in QTWEBENGINE_RESOURCES_PATH if set
+ candidatePaths << fromEnv;
+ } else {
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+ candidatePaths << getResourcesPath(frameworkBundle());
#endif
- if (!initialized) {
- initialized = true;
- if (!QFileInfo::exists(potentialResourcesPath % QLatin1String("/qtwebengine_resources.pak"))) {
- qWarning("Qt WebEngine resources not found at %s. Trying parent directory...", qPrintable(potentialResourcesPath));
- potentialResourcesPath = QLibraryInfo::location(QLibraryInfo::DataPath);
+ candidatePaths << QLibraryInfo::path(QLibraryInfo::DataPath) % QDir::separator()
+ % QLatin1String("resources");
+ candidatePaths << QLibraryInfo::path(QLibraryInfo::DataPath);
+ candidatePaths << QCoreApplication::applicationDirPath();
+ candidatePaths << fallbackDir();
}
- if (!QFileInfo::exists(potentialResourcesPath % QLatin1String("/qtwebengine_resources.pak"))) {
- qWarning("Qt WebEngine resources not found at %s. Trying application directory...", qPrintable(potentialResourcesPath));
- potentialResourcesPath = QCoreApplication::applicationDirPath();
+
+ for (const QString &candidate : std::as_const(candidatePaths)) {
+ if (QFileInfo::exists(candidate % QDir::separator() % resourcesPakFilename)) {
+ potentialResourcesPath = candidate;
+ qCDebug(webEngineLibraryInfoLog, "Qt WebEngine resources path: %s",
+ qPrintable(candidate));
+ break;
+ }
}
- if (!QFileInfo::exists(potentialResourcesPath % QLatin1String("/qtwebengine_resources.pak"))) {
- qWarning("Qt WebEngine resources not found at %s. Trying fallback directory... The application MAY NOT work.", qPrintable(potentialResourcesPath));
- potentialResourcesPath = fallbackDir();
+
+ if (potentialResourcesPath.isEmpty()) {
+ QStringList errorMessage;
+ errorMessage.append(QStringLiteral(
+ "The following paths were searched for Qt WebEngine resources:"));
+ for (const QString &candidate : std::as_const(candidatePaths))
+ errorMessage.append(QStringLiteral(" ") % candidate);
+ errorMessage.append(QStringLiteral("but could not find any."));
+ if (fromEnv.isEmpty()) {
+ errorMessage.append(
+ QStringLiteral("You may override the default search paths by using "
+ "QTWEBENGINE_RESOURCES_PATH environment variable."));
+ }
+ qFatal("%s", qPrintable(errorMessage.join('\n')));
}
}
@@ -291,17 +351,21 @@ base::FilePath WebEngineLibraryInfo::getPath(int key)
QString directory;
switch (key) {
case QT_RESOURCES_PAK:
- return toFilePath(resourcesDataPath() % QLatin1String("/qtwebengine_resources.pak"));
+ return toFilePath(resourcesPath() % QLatin1String("/qtwebengine_resources.pak"));
case QT_RESOURCES_100P_PAK:
- return toFilePath(resourcesDataPath() % QLatin1String("/qtwebengine_resources_100p.pak"));
+ return toFilePath(resourcesPath() % QLatin1String("/qtwebengine_resources_100p.pak"));
case QT_RESOURCES_200P_PAK:
- return toFilePath(resourcesDataPath() % QLatin1String("/qtwebengine_resources_200p.pak"));
+ return toFilePath(resourcesPath() % QLatin1String("/qtwebengine_resources_200p.pak"));
case QT_RESOURCES_DEVTOOLS_PAK:
- return toFilePath(resourcesDataPath() % QLatin1String("/qtwebengine_devtools_resources.pak"));
+ return toFilePath(resourcesPath() % QLatin1String("/qtwebengine_devtools_resources.pak"));
+#if defined(Q_OS_DARWIN) && defined(QT_MAC_FRAMEWORK_BUILD)
+ case QT_FRAMEWORK_BUNDLE:
+ return toFilePath(getBundlePath(frameworkBundle()));
+#endif
case base::FILE_EXE:
case content::CHILD_PROCESS_EXE:
return toFilePath(subProcessPath());
-#if defined(OS_POSIX)
+#if BUILDFLAG(IS_POSIX)
case base::DIR_CACHE:
directory = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
break;
@@ -313,13 +377,15 @@ base::FilePath WebEngineLibraryInfo::getPath(int key)
directory = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
break;
case base::DIR_QT_LIBRARY_DATA:
- return toFilePath(resourcesDataPath());
+ return toFilePath(resourcesPath());
case ui::DIR_LOCALES:
return toFilePath(localesPath());
#if QT_CONFIG(webengine_spellchecker)
case base::DIR_APP_DICTIONARIES:
return toFilePath(dictionariesPath());
#endif
+ case base::DIR_ASSETS:
+ return toFilePath(resourcesPath());
default:
// Note: the path system expects this function to override the default
// behavior. So no need to log an error if we don't support a given
@@ -330,24 +396,49 @@ base::FilePath WebEngineLibraryInfo::getPath(int key)
return toFilePath(directory.isEmpty() ? fallbackDir() : directory);
}
-base::string16 WebEngineLibraryInfo::getApplicationName()
+std::u16string WebEngineLibraryInfo::getApplicationName()
{
return toString16(qApp->applicationName());
}
-std::string WebEngineLibraryInfo::getApplicationLocale()
+std::string WebEngineLibraryInfo::getResolvedLocale()
{
base::CommandLine *parsedCommandLine = base::CommandLine::ForCurrentProcess();
- if (!parsedCommandLine->HasSwitch(switches::kLang)) {
- const QString &locale = QLocale().bcp47Name();
+ std::string locale;
+ if (parsedCommandLine->HasSwitch(switches::kLang))
+ locale = parsedCommandLine->GetSwitchValueASCII(switches::kLang);
+ else
+ locale = QLocale().bcp47Name().toStdString();
- // QLocale::bcp47Name returns "en" for American English locale. Chromium requires the "US" suffix
- // to clarify the dialect and ignores the shorter version.
- if (locale == "en")
- return "en-US";
+ std::string resolvedLocale;
+ if (l10n_util::CheckAndResolveLocale(locale, &resolvedLocale))
+ return resolvedLocale;
- return locale.toStdString();
- }
+ return "en-US";
+}
+
+std::string WebEngineLibraryInfo::getApplicationLocale()
+{
+ base::CommandLine *parsedCommandLine = base::CommandLine::ForCurrentProcess();
+ return parsedCommandLine->HasSwitch(switches::kLang)
+ ? parsedCommandLine->GetSwitchValueASCII(switches::kLang)
+ : QLocale().bcp47Name().toStdString();
+}
- return parsedCommandLine->GetSwitchValueASCII(switches::kLang);
+#if defined(Q_OS_WIN)
+bool WebEngineLibraryInfo::isRemoteDrivePath(const QString &path)
+{
+ WCHAR wDriveLetter[4] = { 0 };
+ swprintf(wDriveLetter, L"%S", path.mid(0, 3).toStdString().c_str());
+ return GetDriveType(wDriveLetter) == DRIVE_REMOTE;
+}
+
+bool WebEngineLibraryInfo::isUNCPath(const QString &path)
+{
+ return (base::FilePath::IsSeparator(path.at(0).toLatin1())
+ && base::FilePath::IsSeparator(path.at(1).toLatin1())
+ && path.at(2) != QLatin1Char('.') && path.at(2) != QLatin1Char('?')
+ && path.at(2).isLetter() && path.at(3) != QLatin1Char(':'));
}
+
+#endif
diff --git a/src/core/web_engine_library_info.h b/src/core/web_engine_library_info.h
index a5cd914d3..b7503f2df 100644
--- a/src/core/web_engine_library_info.h
+++ b/src/core/web_engine_library_info.h
@@ -1,61 +1,32 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_ENGINE_LIBRARY_INFO_H
#define WEB_ENGINE_LIBRARY_INFO_H
#include "base/files/file_path.h"
-#include "base/strings/string16.h"
+#include <QString>
+
enum {
QT_RESOURCES_PAK = 5000,
QT_RESOURCES_100P_PAK = 5001,
QT_RESOURCES_200P_PAK = 5002,
- QT_RESOURCES_DEVTOOLS_PAK = 5003
+ QT_RESOURCES_DEVTOOLS_PAK = 5003,
+ QT_FRAMEWORK_BUNDLE = 5004
};
class WebEngineLibraryInfo {
public:
static base::FilePath getPath(int key);
// Called by localized_error in our custom chrome layer
- static base::string16 getApplicationName();
+ static std::u16string getApplicationName();
+ static std::string getResolvedLocale();
static std::string getApplicationLocale();
+#if defined(Q_OS_WIN)
+ static bool isRemoteDrivePath(const QString &path);
+ static bool isUNCPath(const QString &path);
+#endif
};
diff --git a/src/core/web_engine_settings.cpp b/src/core/web_engine_settings.cpp
index 837f05bf1..e302998f0 100644
--- a/src/core/web_engine_settings.cpp
+++ b/src/core/web_engine_settings.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "web_engine_settings.h"
@@ -45,15 +9,16 @@
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
-#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
-#include "content/public/common/web_preferences.h"
#include "media/base/media_switches.h"
+#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
-#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
+#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
+#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "ui/base/ui_base_switches.h"
+#include "ui/base/pointer/pointer_device.h"
#include "ui/events/event_switches.h"
#include "ui/native_theme/native_theme.h"
@@ -62,9 +27,9 @@
namespace QtWebEngineCore {
-QHash<WebEngineSettings::Attribute, bool> WebEngineSettings::s_defaultAttributes;
-QHash<WebEngineSettings::FontFamily, QString> WebEngineSettings::s_defaultFontFamilies;
-QHash<WebEngineSettings::FontSize, int> WebEngineSettings::s_defaultFontSizes;
+QHash<QWebEngineSettings::WebAttribute, bool> WebEngineSettings::s_defaultAttributes;
+QHash<QWebEngineSettings::FontFamily, QString> WebEngineSettings::s_defaultFontFamilies;
+QHash<QWebEngineSettings::FontSize, int> WebEngineSettings::s_defaultFontSizes;
static const int batchTimerTimeout = 0;
@@ -91,14 +56,30 @@ static inline bool isTouchEventsAPIEnabled() {
return touchEventsAPIEnabled;
}
+blink::mojom::ImageAnimationPolicy
+toBlinkImageAnimationPolicy(QWebEngineSettings::ImageAnimationPolicy policy)
+{
+ switch (policy) {
+ case QWebEngineSettings::AllowImageAnimation:
+ return blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
+ case QWebEngineSettings::AnimateImageOnce:
+ return blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAnimateOnce;
+ case QWebEngineSettings::DisallowImageAnimation:
+ return blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyNoAnimation;
+ }
+ return blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
+}
+
WebEngineSettings::WebEngineSettings(WebEngineSettings *_parentSettings)
- : m_adapter(0)
+ : m_adapter(nullptr)
, parentSettings(_parentSettings)
- , m_unknownUrlSchemePolicy(WebEngineSettings::InheritedUnknownUrlSchemePolicy)
+ , m_unknownUrlSchemePolicy(QWebEngineSettings::InheritedUnknownUrlSchemePolicy)
+ , m_imageAnimationPolicy(QWebEngineSettings::InheritedImageAnimationPolicy)
{
if (parentSettings)
parentSettings->childSettings.insert(this);
-
+ else
+ initDefaults();
m_batchTimer.setSingleShot(true);
m_batchTimer.setInterval(batchTimerTimeout);
QObject::connect(&m_batchTimer, &QTimer::timeout, [this]() {
@@ -111,12 +92,11 @@ WebEngineSettings::~WebEngineSettings()
if (parentSettings)
parentSettings->childSettings.remove(this);
// In QML the profile and its settings may be garbage collected before the page and its settings.
- for (WebEngineSettings *settings : qAsConst(childSettings)) {
- settings->parentSettings = 0;
- }
+ for (WebEngineSettings *settings : std::as_const(childSettings))
+ settings->parentSettings = nullptr;
}
-void WebEngineSettings::overrideWebPreferences(content::WebContents *webContents, content::WebPreferences *prefs)
+void WebEngineSettings::overrideWebPreferences(content::WebContents *webContents, blink::web_pref::WebPreferences *prefs)
{
// Apply our settings on top of those.
applySettingsToWebPreferences(prefs);
@@ -124,7 +104,7 @@ void WebEngineSettings::overrideWebPreferences(content::WebContents *webContents
// as the host process already overides some of the default WebPreferences values
// before we get here (e.g. number_of_cpu_cores).
if (webPreferences.isNull())
- webPreferences.reset(new content::WebPreferences(*prefs));
+ webPreferences.reset(new blink::web_pref::WebPreferences(*prefs));
if (webContents
&& applySettingsToRendererPreferences(webContents->GetMutableRendererPrefs())) {
@@ -132,22 +112,26 @@ void WebEngineSettings::overrideWebPreferences(content::WebContents *webContents
}
}
-void WebEngineSettings::setAttribute(WebEngineSettings::Attribute attr, bool on)
+void WebEngineSettings::setAttribute(QWebEngineSettings::WebAttribute attr, bool on)
{
m_attributes.insert(attr, on);
scheduleApplyRecursively();
}
-bool WebEngineSettings::testAttribute(WebEngineSettings::Attribute attr) const
+bool WebEngineSettings::testAttribute(QWebEngineSettings::WebAttribute attr) const
{
- if (!parentSettings) {
- Q_ASSERT(s_defaultAttributes.contains(attr));
- return m_attributes.value(attr, s_defaultAttributes.value(attr));
- }
- return m_attributes.value(attr, parentSettings->testAttribute(attr));
+ auto it = m_attributes.constFind(attr);
+ if (it != m_attributes.constEnd())
+ return *it;
+
+ if (parentSettings)
+ return parentSettings->testAttribute(attr);
+
+ Q_ASSERT(s_defaultAttributes.contains(attr));
+ return s_defaultAttributes.value(attr);
}
-bool WebEngineSettings::isAttributeExplicitlySet(Attribute attr) const
+bool WebEngineSettings::isAttributeExplicitlySet(QWebEngineSettings::WebAttribute attr) const
{
if (m_attributes.contains(attr))
return true;
@@ -158,19 +142,19 @@ bool WebEngineSettings::isAttributeExplicitlySet(Attribute attr) const
return false;
}
-void WebEngineSettings::resetAttribute(WebEngineSettings::Attribute attr)
+void WebEngineSettings::resetAttribute(QWebEngineSettings::WebAttribute attr)
{
m_attributes.remove(attr);
scheduleApplyRecursively();
}
-void WebEngineSettings::setFontFamily(WebEngineSettings::FontFamily which, const QString &family)
+void WebEngineSettings::setFontFamily(QWebEngineSettings::FontFamily which, const QString &family)
{
m_fontFamilies.insert(which, family);
scheduleApplyRecursively();
}
-QString WebEngineSettings::fontFamily(WebEngineSettings::FontFamily which)
+QString WebEngineSettings::fontFamily(QWebEngineSettings::FontFamily which)
{
if (!parentSettings) {
Q_ASSERT(s_defaultFontFamilies.contains(which));
@@ -179,19 +163,19 @@ QString WebEngineSettings::fontFamily(WebEngineSettings::FontFamily which)
return m_fontFamilies.value(which, parentSettings->fontFamily(which));
}
-void WebEngineSettings::resetFontFamily(WebEngineSettings::FontFamily which)
+void WebEngineSettings::resetFontFamily(QWebEngineSettings::FontFamily which)
{
m_fontFamilies.remove(which);
scheduleApplyRecursively();
}
-void WebEngineSettings::setFontSize(WebEngineSettings::FontSize type, int size)
+void WebEngineSettings::setFontSize(QWebEngineSettings::FontSize type, int size)
{
m_fontSizes.insert(type, size);
scheduleApplyRecursively();
}
-int WebEngineSettings::fontSize(WebEngineSettings::FontSize type) const
+int WebEngineSettings::fontSize(QWebEngineSettings::FontSize type) const
{
if (!parentSettings) {
Q_ASSERT(s_defaultFontSizes.contains(type));
@@ -200,7 +184,7 @@ int WebEngineSettings::fontSize(WebEngineSettings::FontSize type) const
return m_fontSizes.value(type, parentSettings->fontSize(type));
}
-void WebEngineSettings::resetFontSize(WebEngineSettings::FontSize type)
+void WebEngineSettings::resetFontSize(QWebEngineSettings::FontSize type)
{
m_fontSizes.remove(type);
scheduleApplyRecursively();
@@ -219,42 +203,60 @@ QString WebEngineSettings::defaultTextEncoding() const
return m_defaultEncoding.isEmpty()? parentSettings->defaultTextEncoding() : m_defaultEncoding;
}
-void WebEngineSettings::setUnknownUrlSchemePolicy(WebEngineSettings::UnknownUrlSchemePolicy policy)
+void WebEngineSettings::setUnknownUrlSchemePolicy(QWebEngineSettings::UnknownUrlSchemePolicy policy)
{
m_unknownUrlSchemePolicy = policy;
+ scheduleApplyRecursively();
}
-WebEngineSettings::UnknownUrlSchemePolicy WebEngineSettings::unknownUrlSchemePolicy() const
+void WebEngineSettings::setImageAnimationPolicy(QWebEngineSettings::ImageAnimationPolicy policy)
+{
+ m_imageAnimationPolicy = policy;
+ scheduleApplyRecursively();
+}
+
+QWebEngineSettings::ImageAnimationPolicy WebEngineSettings::imageAnimationPolicy() const
+{
+ if (m_imageAnimationPolicy != QWebEngineSettings::InheritedImageAnimationPolicy)
+ return m_imageAnimationPolicy;
+
+ if (parentSettings)
+ return parentSettings->imageAnimationPolicy();
+
+ return QWebEngineSettings::AllowImageAnimation;
+}
+
+QWebEngineSettings::UnknownUrlSchemePolicy WebEngineSettings::unknownUrlSchemePolicy() const
{
// value InheritedUnknownUrlSchemePolicy means it is taken from parent, if possible. If there
// is no parent, then AllowUnknownUrlSchemesFromUserInteraction (the default behavior) is used.
- if (m_unknownUrlSchemePolicy != InheritedUnknownUrlSchemePolicy)
+ if (m_unknownUrlSchemePolicy != QWebEngineSettings::InheritedUnknownUrlSchemePolicy)
return m_unknownUrlSchemePolicy;
if (parentSettings)
return parentSettings->unknownUrlSchemePolicy();
- return AllowUnknownUrlSchemesFromUserInteraction;
+ return QWebEngineSettings::AllowUnknownUrlSchemesFromUserInteraction;
}
void WebEngineSettings::initDefaults()
{
if (s_defaultAttributes.isEmpty()) {
// Initialize the default settings.
- s_defaultAttributes.insert(AutoLoadImages, true);
- s_defaultAttributes.insert(JavascriptEnabled, true);
- s_defaultAttributes.insert(JavascriptCanOpenWindows, true);
- s_defaultAttributes.insert(JavascriptCanAccessClipboard, false);
- s_defaultAttributes.insert(LinksIncludedInFocusChain, true);
- s_defaultAttributes.insert(LocalStorageEnabled, true);
- s_defaultAttributes.insert(LocalContentCanAccessRemoteUrls, false);
- s_defaultAttributes.insert(XSSAuditingEnabled, false);
- s_defaultAttributes.insert(SpatialNavigationEnabled, false);
- s_defaultAttributes.insert(LocalContentCanAccessFileUrls, true);
- s_defaultAttributes.insert(HyperlinkAuditingEnabled, false);
- s_defaultAttributes.insert(ErrorPageEnabled, true);
- s_defaultAttributes.insert(PluginsEnabled, false);
- s_defaultAttributes.insert(FullScreenSupportEnabled, false);
- s_defaultAttributes.insert(ScreenCaptureEnabled, false);
- s_defaultAttributes.insert(ShowScrollBars, true);
+ s_defaultAttributes.insert(QWebEngineSettings::AutoLoadImages, true);
+ s_defaultAttributes.insert(QWebEngineSettings::JavascriptEnabled, true);
+ s_defaultAttributes.insert(QWebEngineSettings::JavascriptCanOpenWindows, true);
+ s_defaultAttributes.insert(QWebEngineSettings::JavascriptCanAccessClipboard, false);
+ s_defaultAttributes.insert(QWebEngineSettings::LinksIncludedInFocusChain, true);
+ s_defaultAttributes.insert(QWebEngineSettings::LocalStorageEnabled, true);
+ s_defaultAttributes.insert(QWebEngineSettings::LocalContentCanAccessRemoteUrls, false);
+ s_defaultAttributes.insert(QWebEngineSettings::XSSAuditingEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::SpatialNavigationEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
+ s_defaultAttributes.insert(QWebEngineSettings::HyperlinkAuditingEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::ErrorPageEnabled, true);
+ s_defaultAttributes.insert(QWebEngineSettings::PluginsEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::FullScreenSupportEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::ScreenCaptureEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::ShowScrollBars, true);
// The following defaults matches logic in render_view_host_impl.cc
// But first we must ensure the WebContext has been initialized
QtWebEngineCore::WebEngineContext::current();
@@ -266,60 +268,72 @@ void WebEngineSettings::initDefaults()
bool accelerated2dCanvas =
!commandLine->HasSwitch(switches::kDisableAccelerated2dCanvas);
bool allowRunningInsecureContent = commandLine->HasSwitch(switches::kAllowRunningInsecureContent);
- s_defaultAttributes.insert(ScrollAnimatorEnabled, smoothScrolling);
- s_defaultAttributes.insert(WebGLEnabled, webGL);
- s_defaultAttributes.insert(Accelerated2dCanvasEnabled, accelerated2dCanvas);
- s_defaultAttributes.insert(AutoLoadIconsForPage, true);
- s_defaultAttributes.insert(TouchIconsEnabled, false);
- s_defaultAttributes.insert(FocusOnNavigationEnabled, false);
- s_defaultAttributes.insert(PrintElementBackgrounds, true);
- s_defaultAttributes.insert(AllowRunningInsecureContent, allowRunningInsecureContent);
- s_defaultAttributes.insert(AllowGeolocationOnInsecureOrigins, false);
- s_defaultAttributes.insert(AllowWindowActivationFromJavaScript, false);
+ s_defaultAttributes.insert(QWebEngineSettings::ScrollAnimatorEnabled, smoothScrolling);
+ s_defaultAttributes.insert(QWebEngineSettings::WebGLEnabled, webGL);
+ s_defaultAttributes.insert(QWebEngineSettings::Accelerated2dCanvasEnabled,
+ accelerated2dCanvas);
+ s_defaultAttributes.insert(QWebEngineSettings::AutoLoadIconsForPage, true);
+ s_defaultAttributes.insert(QWebEngineSettings::TouchIconsEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::FocusOnNavigationEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::PrintElementBackgrounds, true);
+ s_defaultAttributes.insert(QWebEngineSettings::AllowRunningInsecureContent,
+ allowRunningInsecureContent);
+ s_defaultAttributes.insert(QWebEngineSettings::AllowGeolocationOnInsecureOrigins, false);
+ s_defaultAttributes.insert(QWebEngineSettings::AllowWindowActivationFromJavaScript, false);
bool playbackRequiresUserGesture = false;
if (commandLine->HasSwitch(switches::kAutoplayPolicy))
playbackRequiresUserGesture = (commandLine->GetSwitchValueASCII(switches::kAutoplayPolicy) != switches::autoplay::kNoUserGestureRequiredPolicy);
- s_defaultAttributes.insert(PlaybackRequiresUserGesture, playbackRequiresUserGesture);
- s_defaultAttributes.insert(WebRTCPublicInterfacesOnly, false);
- s_defaultAttributes.insert(JavascriptCanPaste, false);
- s_defaultAttributes.insert(DnsPrefetchEnabled, false);
-#if QT_CONFIG(webengine_extensions)
- s_defaultAttributes.insert(PdfViewerEnabled, true);
+ s_defaultAttributes.insert(QWebEngineSettings::PlaybackRequiresUserGesture,
+ playbackRequiresUserGesture);
+ s_defaultAttributes.insert(QWebEngineSettings::WebRTCPublicInterfacesOnly, false);
+ s_defaultAttributes.insert(QWebEngineSettings::JavascriptCanPaste, false);
+ s_defaultAttributes.insert(QWebEngineSettings::DnsPrefetchEnabled, false);
+#if QT_CONFIG(webengine_extensions) && QT_CONFIG(webengine_printing_and_pdf)
+ s_defaultAttributes.insert(QWebEngineSettings::PdfViewerEnabled, true);
#else
- s_defaultAttributes.insert(PdfViewerEnabled, false);
+ s_defaultAttributes.insert(QWebEngineSettings::PdfViewerEnabled, false);
#endif
+ s_defaultAttributes.insert(QWebEngineSettings::NavigateOnDropEnabled, true);
+ bool noReadingFromCanvas =
+ commandLine->HasSwitch(switches::kDisableReadingFromCanvas);
+ s_defaultAttributes.insert(QWebEngineSettings::ReadingFromCanvasEnabled, !noReadingFromCanvas);
+ bool forceDarkMode = commandLine->HasSwitch(switches::kForceDarkMode);
+ s_defaultAttributes.insert(QWebEngineSettings::ForceDarkMode, forceDarkMode);
}
if (s_defaultFontFamilies.isEmpty()) {
// Default fonts
QFont defaultFont;
defaultFont.setStyleHint(QFont::Serif);
- s_defaultFontFamilies.insert(StandardFont, defaultFont.defaultFamily());
- s_defaultFontFamilies.insert(SerifFont, defaultFont.defaultFamily());
- s_defaultFontFamilies.insert(PictographFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::StandardFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::SerifFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::PictographFont,
+ defaultFont.defaultFamily());
defaultFont.setStyleHint(QFont::Fantasy);
- s_defaultFontFamilies.insert(FantasyFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::FantasyFont, defaultFont.defaultFamily());
defaultFont.setStyleHint(QFont::Cursive);
- s_defaultFontFamilies.insert(CursiveFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::CursiveFont, defaultFont.defaultFamily());
defaultFont.setStyleHint(QFont::SansSerif);
- s_defaultFontFamilies.insert(SansSerifFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::SansSerifFont,
+ defaultFont.defaultFamily());
defaultFont.setStyleHint(QFont::Monospace);
- s_defaultFontFamilies.insert(FixedFont, defaultFont.defaultFamily());
+ s_defaultFontFamilies.insert(QWebEngineSettings::FixedFont, defaultFont.defaultFamily());
}
if (s_defaultFontSizes.isEmpty()) {
- s_defaultFontSizes.insert(MinimumFontSize, 0);
- s_defaultFontSizes.insert(MinimumLogicalFontSize, 6);
- s_defaultFontSizes.insert(DefaultFixedFontSize, 13);
- s_defaultFontSizes.insert(DefaultFontSize, 16);
+ s_defaultFontSizes.insert(QWebEngineSettings::MinimumFontSize, 0);
+ s_defaultFontSizes.insert(QWebEngineSettings::MinimumLogicalFontSize, 6);
+ s_defaultFontSizes.insert(QWebEngineSettings::DefaultFixedFontSize, 13);
+ s_defaultFontSizes.insert(QWebEngineSettings::DefaultFontSize, 16);
}
m_defaultEncoding = QStringLiteral("ISO-8859-1");
- m_unknownUrlSchemePolicy = InheritedUnknownUrlSchemePolicy;
+ m_unknownUrlSchemePolicy = QWebEngineSettings::InheritedUnknownUrlSchemePolicy;
+ m_imageAnimationPolicy = QWebEngineSettings::InheritedImageAnimationPolicy;
}
void WebEngineSettings::scheduleApply()
@@ -343,86 +357,97 @@ void WebEngineSettings::doApply()
m_adapter->webContents()->SyncRendererPrefs();
}
-void WebEngineSettings::applySettingsToWebPreferences(content::WebPreferences *prefs)
+void WebEngineSettings::applySettingsToWebPreferences(blink::web_pref::WebPreferences *prefs)
{
+ // Not supported
+ prefs->picture_in_picture_enabled = false;
+
// Override for now
prefs->touch_event_feature_detection_enabled = isTouchEventsAPIEnabled();
#if !QT_CONFIG(webengine_embedded_build)
- prefs->available_hover_types = ui::HOVER_TYPE_HOVER;
- prefs->primary_hover_type = ui::HOVER_TYPE_HOVER;
+ prefs->available_hover_types = (int)blink::mojom::HoverType::kHoverHoverType;
+ prefs->primary_hover_type = blink::mojom::HoverType::kHoverHoverType;
#endif
if (prefs->viewport_enabled) {
// We need to enable the viewport options together as it doesn't really work
// to enable them separately. With viewport-enabled we match Android defaults.
prefs->viewport_meta_enabled = true;
prefs->shrinks_viewport_contents_to_fit = true;
+ prefs->main_frame_resizes_are_orientation_changes = true;
}
// Attributes mapping.
- prefs->loads_images_automatically = testAttribute(AutoLoadImages);
- prefs->javascript_enabled = testAttribute(JavascriptEnabled);
- prefs->javascript_can_access_clipboard = testAttribute(JavascriptCanAccessClipboard);
- prefs->tabs_to_links = testAttribute(LinksIncludedInFocusChain);
- prefs->local_storage_enabled = testAttribute(LocalStorageEnabled);
- prefs->databases_enabled = testAttribute(LocalStorageEnabled);
- prefs->allow_universal_access_from_file_urls = testAttribute(LocalContentCanAccessRemoteUrls);
- prefs->spatial_navigation_enabled = testAttribute(SpatialNavigationEnabled);
- prefs->allow_file_access_from_file_urls = testAttribute(LocalContentCanAccessFileUrls);
- prefs->hyperlink_auditing_enabled = testAttribute(HyperlinkAuditingEnabled);
- prefs->enable_scroll_animator = testAttribute(ScrollAnimatorEnabled);
- prefs->enable_error_page = testAttribute(ErrorPageEnabled);
- prefs->plugins_enabled = testAttribute(PluginsEnabled);
- prefs->fullscreen_supported = testAttribute(FullScreenSupportEnabled);
- prefs->accelerated_2d_canvas_enabled = testAttribute(Accelerated2dCanvasEnabled);
- prefs->webgl1_enabled = prefs->webgl2_enabled = testAttribute(WebGLEnabled);
- prefs->should_print_backgrounds = testAttribute(PrintElementBackgrounds);
- prefs->allow_running_insecure_content = testAttribute(AllowRunningInsecureContent);
- prefs->allow_geolocation_on_insecure_origins = testAttribute(AllowGeolocationOnInsecureOrigins);
- prefs->hide_scrollbars = !testAttribute(ShowScrollBars);
- if (isAttributeExplicitlySet(PlaybackRequiresUserGesture)) {
- prefs->autoplay_policy = testAttribute(PlaybackRequiresUserGesture)
- ? content::AutoplayPolicy::kUserGestureRequired
- : content::AutoplayPolicy::kNoUserGestureRequired;
+ prefs->loads_images_automatically = testAttribute(QWebEngineSettings::AutoLoadImages);
+ prefs->javascript_enabled = testAttribute(QWebEngineSettings::JavascriptEnabled);
+ prefs->javascript_can_access_clipboard =
+ testAttribute(QWebEngineSettings::JavascriptCanAccessClipboard);
+ prefs->tabs_to_links = testAttribute(QWebEngineSettings::LinksIncludedInFocusChain);
+ prefs->local_storage_enabled = testAttribute(QWebEngineSettings::LocalStorageEnabled);
+ prefs->databases_enabled = testAttribute(QWebEngineSettings::LocalStorageEnabled);
+ prefs->allow_remote_access_from_local_urls =
+ testAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls);
+ prefs->spatial_navigation_enabled = testAttribute(QWebEngineSettings::SpatialNavigationEnabled);
+ prefs->allow_file_access_from_file_urls =
+ testAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls);
+ prefs->hyperlink_auditing_enabled = testAttribute(QWebEngineSettings::HyperlinkAuditingEnabled);
+ prefs->enable_scroll_animator = testAttribute(QWebEngineSettings::ScrollAnimatorEnabled);
+ prefs->enable_error_page = testAttribute(QWebEngineSettings::ErrorPageEnabled);
+ prefs->plugins_enabled = testAttribute(QWebEngineSettings::PluginsEnabled);
+ prefs->fullscreen_supported = testAttribute(QWebEngineSettings::FullScreenSupportEnabled);
+ prefs->accelerated_2d_canvas_enabled =
+ testAttribute(QWebEngineSettings::Accelerated2dCanvasEnabled);
+ prefs->force_dark_mode_enabled = testAttribute(QWebEngineSettings::ForceDarkMode);
+ prefs->webgl1_enabled = prefs->webgl2_enabled = testAttribute(QWebEngineSettings::WebGLEnabled);
+ prefs->should_print_backgrounds = testAttribute(QWebEngineSettings::PrintElementBackgrounds);
+ prefs->allow_running_insecure_content =
+ testAttribute(QWebEngineSettings::AllowRunningInsecureContent);
+ prefs->allow_geolocation_on_insecure_origins =
+ testAttribute(QWebEngineSettings::AllowGeolocationOnInsecureOrigins);
+ prefs->hide_scrollbars = !testAttribute(QWebEngineSettings::ShowScrollBars);
+ if (isAttributeExplicitlySet(QWebEngineSettings::PlaybackRequiresUserGesture)) {
+ prefs->autoplay_policy = testAttribute(QWebEngineSettings::PlaybackRequiresUserGesture)
+ ? blink::mojom::AutoplayPolicy::kUserGestureRequired
+ : blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
}
- prefs->dom_paste_enabled = testAttribute(JavascriptCanPaste);
- prefs->dns_prefetching_enabled = testAttribute(DnsPrefetchEnabled);
+ prefs->dom_paste_enabled = testAttribute(QWebEngineSettings::JavascriptCanPaste);
+ prefs->dns_prefetching_enabled = testAttribute(QWebEngineSettings::DnsPrefetchEnabled);
+ prefs->disable_reading_from_canvas = !testAttribute(QWebEngineSettings::ReadingFromCanvasEnabled);
+ prefs->animation_policy = toBlinkImageAnimationPolicy(imageAnimationPolicy());
// Fonts settings.
- prefs->standard_font_family_map[content::kCommonScript] = toString16(fontFamily(StandardFont));
- prefs->fixed_font_family_map[content::kCommonScript] = toString16(fontFamily(FixedFont));
- prefs->serif_font_family_map[content::kCommonScript] = toString16(fontFamily(SerifFont));
- prefs->sans_serif_font_family_map[content::kCommonScript] = toString16(fontFamily(SansSerifFont));
- prefs->cursive_font_family_map[content::kCommonScript] = toString16(fontFamily(CursiveFont));
- prefs->fantasy_font_family_map[content::kCommonScript] = toString16(fontFamily(FantasyFont));
- prefs->pictograph_font_family_map[content::kCommonScript] = toString16(fontFamily(PictographFont));
- prefs->default_font_size = fontSize(DefaultFontSize);
- prefs->default_fixed_font_size = fontSize(DefaultFixedFontSize);
- prefs->minimum_font_size = fontSize(MinimumFontSize);
- prefs->minimum_logical_font_size = fontSize(MinimumLogicalFontSize);
+ prefs->standard_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::StandardFont));
+ prefs->fixed_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::FixedFont));
+ prefs->serif_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::SerifFont));
+ prefs->sans_serif_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::SansSerifFont));
+ prefs->cursive_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::CursiveFont));
+ prefs->fantasy_font_family_map[blink::web_pref::kCommonScript] =
+ toString16(fontFamily(QWebEngineSettings::FantasyFont));
+ prefs->default_font_size = fontSize(QWebEngineSettings::DefaultFontSize);
+ prefs->default_fixed_font_size = fontSize(QWebEngineSettings::DefaultFixedFontSize);
+ prefs->minimum_font_size = fontSize(QWebEngineSettings::MinimumFontSize);
+ prefs->minimum_logical_font_size = fontSize(QWebEngineSettings::MinimumLogicalFontSize);
prefs->default_encoding = defaultTextEncoding().toStdString();
// Set the theme colors. Based on chrome_content_browser_client.cc:
const ui::NativeTheme *webTheme = ui::NativeTheme::GetInstanceForWeb();
- // WebPreferences::preferred_color_scheme was deleted in Chromium 80, but it
- // will make a comeback in Chromium 82...
- //
- // See also: https://chromium-review.googlesource.com/c/chromium/src/+/2079192
- //
- // if (webTheme) {
- // switch (webTheme->GetPreferredColorScheme()) {
- // case ui::NativeTheme::PreferredColorScheme::kDark:
- // prefs->preferred_color_scheme = blink::PreferredColorScheme::kDark;
- // break;
- // case ui::NativeTheme::PreferredColorScheme::kLight:
- // prefs->preferred_color_scheme = blink::PreferredColorScheme::kLight;
- // break;
- // case ui::NativeTheme::PreferredColorScheme::kNoPreference:
- // prefs->preferred_color_scheme = blink::PreferredColorScheme::kNoPreference;
- // }
- // }
+ if (webTheme) {
+ switch (webTheme->GetPreferredColorScheme()) {
+ case ui::NativeTheme::PreferredColorScheme::kDark:
+ prefs->preferred_color_scheme = blink::mojom::PreferredColorScheme::kDark;
+ break;
+ case ui::NativeTheme::PreferredColorScheme::kLight:
+ prefs->preferred_color_scheme = blink::mojom::PreferredColorScheme::kLight;
+ break;
+ }
+ }
// Apply native CaptionStyle parameters.
- base::Optional<ui::CaptionStyle> style;
+ absl::optional<ui::CaptionStyle> style;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceCaptionStyle)) {
style = ui::CaptionStyle::FromSpec(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kForceCaptionStyle));
@@ -440,39 +465,44 @@ void WebEngineSettings::applySettingsToWebPreferences(content::WebPreferences *p
prefs->text_track_font_family = style->font_family;
prefs->text_track_font_variant = style->font_variant;
prefs->text_track_window_color = style->window_color;
- prefs->text_track_window_padding = style->window_padding;
prefs->text_track_window_radius = style->window_radius;
}
}
-bool WebEngineSettings::applySettingsToRendererPreferences(blink::mojom::RendererPreferences *prefs)
+bool WebEngineSettings::applySettingsToRendererPreferences(blink::RendererPreferences *prefs)
{
bool changed = false;
#if QT_CONFIG(webengine_webrtc)
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceWebRtcIPHandlingPolicy)) {
- std::string webrtc_ip_handling_policy = testAttribute(WebEngineSettings::WebRTCPublicInterfacesOnly)
- ? blink::kWebRTCIPHandlingDefaultPublicInterfaceOnly
- : blink::kWebRTCIPHandlingDefault;
+ std::string webrtc_ip_handling_policy =
+ testAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly)
+ ? blink::kWebRTCIPHandlingDefaultPublicInterfaceOnly
+ : blink::kWebRTCIPHandlingDefault;
if (prefs->webrtc_ip_handling_policy != webrtc_ip_handling_policy) {
prefs->webrtc_ip_handling_policy = webrtc_ip_handling_policy;
changed = true;
}
}
#endif
+ bool canNavigateOnDrop = testAttribute(QWebEngineSettings::NavigateOnDropEnabled);
+ if (canNavigateOnDrop != prefs->can_accept_load_drops) {
+ prefs->can_accept_load_drops = canNavigateOnDrop;
+ changed = true;
+ }
return changed;
}
void WebEngineSettings::scheduleApplyRecursively()
{
scheduleApply();
- for (WebEngineSettings *settings : qAsConst(childSettings)) {
+ for (WebEngineSettings *settings : std::as_const(childSettings)) {
settings->scheduleApply();
}
}
bool WebEngineSettings::getJavaScriptCanOpenWindowsAutomatically()
{
- return testAttribute(JavascriptCanOpenWindows);
+ return testAttribute(QWebEngineSettings::JavascriptCanOpenWindows);
}
void WebEngineSettings::setParentSettings(WebEngineSettings *_parentSettings)
@@ -482,6 +512,7 @@ void WebEngineSettings::setParentSettings(WebEngineSettings *_parentSettings)
parentSettings = _parentSettings;
if (parentSettings)
parentSettings->childSettings.insert(this);
+ scheduleApplyRecursively();
}
} // namespace QtWebEngineCore
diff --git a/src/core/web_engine_settings.h b/src/core/web_engine_settings.h
index 95eea669f..2bfc5949d 100644
--- a/src/core/web_engine_settings.h
+++ b/src/core/web_engine_settings.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//
// W A R N I N G
@@ -51,8 +15,8 @@
#ifndef WEB_ENGINE_SETTINGS_H
#define WEB_ENGINE_SETTINGS_H
-#include "qtwebenginecoreglobal_p.h"
-
+#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h>
+#include <QtWebEngineCore/qwebenginesettings.h>
#include <QScopedPointer>
#include <QHash>
#include <QUrl>
@@ -61,109 +25,51 @@
namespace content {
class WebContents;
-struct WebPreferences;
}
+
namespace blink {
-namespace mojom {
-class RendererPreferences;
+struct RendererPreferences;
+namespace web_pref {
+struct WebPreferences;
}
}
namespace QtWebEngineCore {
class WebContentsAdapter;
-class Q_WEBENGINECORE_PRIVATE_EXPORT WebEngineSettings {
+class WebEngineSettings {
public:
- // Attributes. Names match the ones from the public widgets API.
- enum Attribute {
- UnsupportedInCoreSettings = -1,
- AutoLoadImages,
- JavascriptEnabled,
- JavascriptCanOpenWindows,
- JavascriptCanAccessClipboard,
- LinksIncludedInFocusChain,
- LocalStorageEnabled,
- LocalContentCanAccessRemoteUrls,
- XSSAuditingEnabled,
- SpatialNavigationEnabled,
- LocalContentCanAccessFileUrls,
- HyperlinkAuditingEnabled,
- ScrollAnimatorEnabled,
- ErrorPageEnabled,
- PluginsEnabled,
- FullScreenSupportEnabled,
- ScreenCaptureEnabled,
- WebGLEnabled,
- Accelerated2dCanvasEnabled,
- AutoLoadIconsForPage,
- TouchIconsEnabled,
- FocusOnNavigationEnabled,
- PrintElementBackgrounds,
- AllowRunningInsecureContent,
- AllowGeolocationOnInsecureOrigins,
- AllowWindowActivationFromJavaScript,
- ShowScrollBars,
- PlaybackRequiresUserGesture,
- WebRTCPublicInterfacesOnly,
- JavascriptCanPaste,
- DnsPrefetchEnabled,
- PdfViewerEnabled,
- };
-
- // Must match the values from the public API in qwebenginesettings.h.
- enum FontFamily {
- StandardFont,
- FixedFont,
- SerifFont,
- SansSerifFont,
- CursiveFont,
- FantasyFont,
- PictographFont
- };
-
- // Must match the values from the public API in qwebenginesettings.h.
- enum FontSize {
- MinimumFontSize,
- MinimumLogicalFontSize,
- DefaultFontSize,
- DefaultFixedFontSize
- };
-
- // Must match the values from the public API in qwebenginesettings.h.
- enum UnknownUrlSchemePolicy {
- InheritedUnknownUrlSchemePolicy = 0,
- DisallowUnknownUrlSchemes = 1,
- AllowUnknownUrlSchemesFromUserInteraction,
- AllowAllUnknownUrlSchemes
- };
-
- explicit WebEngineSettings(WebEngineSettings *parentSettings = 0);
+ static WebEngineSettings* get(QWebEngineSettings *settings) { return settings->d_ptr.data(); }
+
+ explicit WebEngineSettings(WebEngineSettings *parentSettings = nullptr);
~WebEngineSettings();
void setParentSettings(WebEngineSettings *parentSettings);
- void overrideWebPreferences(content::WebContents *webContents, content::WebPreferences *prefs);
+ void overrideWebPreferences(content::WebContents *webContents, blink::web_pref::WebPreferences *prefs);
- void setAttribute(Attribute, bool on);
- bool testAttribute(Attribute) const;
- void resetAttribute(Attribute);
- bool isAttributeExplicitlySet(Attribute) const;
+ void setAttribute(QWebEngineSettings::WebAttribute, bool on);
+ bool testAttribute(QWebEngineSettings::WebAttribute) const;
+ void resetAttribute(QWebEngineSettings::WebAttribute);
+ bool isAttributeExplicitlySet(QWebEngineSettings::WebAttribute) const;
- void setFontFamily(FontFamily, const QString &);
- QString fontFamily(FontFamily);
- void resetFontFamily(FontFamily);
+ void setFontFamily(QWebEngineSettings::FontFamily, const QString &);
+ QString fontFamily(QWebEngineSettings::FontFamily);
+ void resetFontFamily(QWebEngineSettings::FontFamily);
- void setFontSize(FontSize type, int size);
- int fontSize(FontSize type) const;
- void resetFontSize(FontSize type);
+ void setFontSize(QWebEngineSettings::FontSize type, int size);
+ int fontSize(QWebEngineSettings::FontSize type) const;
+ void resetFontSize(QWebEngineSettings::FontSize type);
void setDefaultTextEncoding(const QString &encoding);
QString defaultTextEncoding() const;
- void setUnknownUrlSchemePolicy(UnknownUrlSchemePolicy policy);
- UnknownUrlSchemePolicy unknownUrlSchemePolicy() const;
+ void setUnknownUrlSchemePolicy(QWebEngineSettings::UnknownUrlSchemePolicy policy);
+ QWebEngineSettings::UnknownUrlSchemePolicy unknownUrlSchemePolicy() const;
+
+ void setImageAnimationPolicy(QWebEngineSettings::ImageAnimationPolicy policy);
+ QWebEngineSettings::ImageAnimationPolicy imageAnimationPolicy() const;
- void initDefaults();
void scheduleApply();
void scheduleApplyRecursively();
@@ -171,26 +77,28 @@ public:
bool getJavaScriptCanOpenWindowsAutomatically();
private:
+ void initDefaults();
void doApply();
- void applySettingsToWebPreferences(content::WebPreferences *);
- bool applySettingsToRendererPreferences(blink::mojom::RendererPreferences *);
+ void applySettingsToWebPreferences(blink::web_pref::WebPreferences *);
+ bool applySettingsToRendererPreferences(blink::RendererPreferences *);
void setWebContentsAdapter(WebContentsAdapter *adapter) { m_adapter = adapter; }
WebContentsAdapter* m_adapter;
- QHash<Attribute, bool> m_attributes;
- QHash<FontFamily, QString> m_fontFamilies;
- QHash<FontSize, int> m_fontSizes;
+ QHash<QWebEngineSettings::WebAttribute, bool> m_attributes;
+ QHash<QWebEngineSettings::FontFamily, QString> m_fontFamilies;
+ QHash<QWebEngineSettings::FontSize, int> m_fontSizes;
QString m_defaultEncoding;
- QScopedPointer<content::WebPreferences> webPreferences;
+ QScopedPointer<blink::web_pref::WebPreferences> webPreferences;
QTimer m_batchTimer;
WebEngineSettings *parentSettings;
QSet<WebEngineSettings *> childSettings;
- static QHash<Attribute, bool> s_defaultAttributes;
- static QHash<FontFamily, QString> s_defaultFontFamilies;
- static QHash<FontSize, int> s_defaultFontSizes;
- UnknownUrlSchemePolicy m_unknownUrlSchemePolicy;
+ static QHash<QWebEngineSettings::WebAttribute, bool> s_defaultAttributes;
+ static QHash<QWebEngineSettings::FontFamily, QString> s_defaultFontFamilies;
+ static QHash<QWebEngineSettings::FontSize, int> s_defaultFontSizes;
+ QWebEngineSettings::UnknownUrlSchemePolicy m_unknownUrlSchemePolicy;
+ QWebEngineSettings::ImageAnimationPolicy m_imageAnimationPolicy;
friend class WebContentsAdapter;
};
diff --git a/src/core/web_event_factory.cpp b/src/core/web_event_factory.cpp
index 428ef6068..617eea2d0 100644
--- a/src/core/web_event_factory.cpp
+++ b/src/core/web_event_factory.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
/*
* Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
@@ -71,6 +35,7 @@
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/events/keycodes/keyboard_code_conversion.h"
+#include "native_web_keyboard_event_qt.h"
#include "render_widget_host_view_qt_delegate.h"
#include <QtGui/private/qtgui-config_p.h>
@@ -205,10 +170,20 @@ static quint32 nativeKeyCodeForKeyEvent(const QKeyEvent *ev)
// Cygwin/X, etc). Also evdev key codes are *not* supported for the same
// reason.
#if defined(Q_OS_WINDOWS)
- return keyboardDriver() == KeyboardDriver::Windows ? ev->nativeScanCode() : 0;
+ if (keyboardDriver() == KeyboardDriver::Windows) {
+ // see GetScanCodeFromLParam in events_win_utils.cc:
+ quint32 scancode = ev->nativeScanCode() & 0xff;
+ if (ev->nativeScanCode() & 0x100)
+ scancode |= 0xe000;
+ return scancode;
+ }
+ return 0;
#elif defined(Q_OS_MACOS)
return keyboardDriver() == KeyboardDriver::Cocoa ? ev->nativeVirtualKey() : 0;
#elif defined(Q_OS_LINUX)
+ // Do not set native code to menu key if it was mapped to something else.
+ if (ev->nativeScanCode() == 135 && ev->key() != Qt::Key_Menu)
+ return 0;
return keyboardDriver() == KeyboardDriver::Xkb ? ev->nativeScanCode() : 0;
#else
return 0; // 0 means unknown, KeyboardEvent.code will be empty string.
@@ -584,6 +559,8 @@ static int windowsKeyCodeForQtKey(int qtKey, bool isKeypad)
case Qt::Key_QuoteDbl:
return VK_OEM_7; // case '\'': case '"': return 0xDE;
// VK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
+ case Qt::Key_AltGr:
+ return 0xE1; // (E1) VK_OEM_AX = ui::VKEY_ALTGR see ui/events/keycodes/keyboard_codes_win.h
// VK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
case Qt::Key_AudioRewind:
@@ -940,7 +917,6 @@ static ui::DomKey domKeyForQtKey(int qtKey)
return ui::DomKey::ZENKAKU;
case Qt::Key_Zenkaku_Hankaku:
return ui::DomKey::ZENKAKU_HANKAKU;
-#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
// Dead keys (ui/events/keycodes/keyboard_code_conversion_xkb.cc)
case Qt::Key_Dead_Grave:
return ui::DomKey::DeadKeyFromCombiningCharacter(0x0300);
@@ -1008,7 +984,6 @@ static ui::DomKey domKeyForQtKey(int qtKey)
return ui::DomKey::DeadKeyFromCombiningCharacter(0x00A4);
case Qt::Key_Dead_Greek:
return ui::DomKey::DeadKeyFromCombiningCharacter(0x037E);
-#endif
// General-Purpose Function Keys
case Qt::Key_F1:
return ui::DomKey::F1;
@@ -1227,8 +1202,12 @@ static WebMouseEvent::Button mouseButtonForEvent(T *event)
return WebMouseEvent::Button::kLeft;
else if (event->button() == Qt::RightButton)
return WebMouseEvent::Button::kRight;
- else if (event->button() == Qt::MidButton)
+ else if (event->button() == Qt::MiddleButton)
return WebMouseEvent::Button::kMiddle;
+ else if (event->button() == Qt::BackButton)
+ return WebMouseEvent::Button::kBack;
+ else if (event->button() == Qt::ForwardButton)
+ return WebMouseEvent::Button::kForward;
if (event->type() != QEvent::MouseMove && event->type() != QEvent::TabletMove)
return WebMouseEvent::Button::kNoButton;
@@ -1239,8 +1218,12 @@ static WebMouseEvent::Button mouseButtonForEvent(T *event)
return WebMouseEvent::Button::kLeft;
else if (event->buttons() & Qt::RightButton)
return WebMouseEvent::Button::kRight;
- else if (event->buttons() & Qt::MidButton)
+ else if (event->buttons() & Qt::MiddleButton)
return WebMouseEvent::Button::kMiddle;
+ else if (event->buttons() & Qt::BackButton)
+ return WebMouseEvent::Button::kBack;
+ else if (event->buttons() & Qt::ForwardButton)
+ return WebMouseEvent::Button::kForward;
return WebMouseEvent::Button::kNoButton;
}
@@ -1253,11 +1236,38 @@ static unsigned mouseButtonsModifiersForEvent(const T* event)
ret |= WebInputEvent::kLeftButtonDown;
if (event->buttons() & Qt::RightButton)
ret |= WebInputEvent::kRightButtonDown;
- if (event->buttons() & Qt::MidButton)
+ if (event->buttons() & Qt::MiddleButton)
ret |= WebInputEvent::kMiddleButtonDown;
+ if (event->buttons() & Qt::BackButton)
+ ret |= WebInputEvent::kBackButtonDown;
+ if (event->buttons() & Qt::ForwardButton)
+ ret |= WebInputEvent::kForwardButtonDown;
return ret;
}
+static WebInputEvent::Modifiers lockKeyModifiers(const quint32 nativeModifiers)
+{
+ unsigned result = 0;
+ if (keyboardDriver() == KeyboardDriver::Xkb) {
+ if (nativeModifiers & 0x42) /* Caps_Lock */
+ result |= WebInputEvent::kCapsLockOn;
+ if (nativeModifiers & 0x4d) /* Num_Lock */
+ result |= WebInputEvent::kNumLockOn;
+ } else if (keyboardDriver() == KeyboardDriver::Windows) {
+ if (nativeModifiers & 0x100) /* CapsLock */
+ result |= WebInputEvent::kCapsLockOn;
+ if (nativeModifiers & 0x200) /* NumLock */
+ result |= WebInputEvent::kNumLockOn;
+ if (nativeModifiers & 0x400) /* ScrollLock */
+ result |= WebInputEvent::kScrollLockOn;
+ } else if (keyboardDriver() == KeyboardDriver::Cocoa) {
+ if (nativeModifiers & 0x10000) /* NSEventModifierFlagCapsLock */
+ result |= WebInputEvent::kCapsLockOn;
+ }
+
+ return static_cast<WebInputEvent::Modifiers>(result);
+}
+
// If only a modifier key is pressed, Qt only reports the key code.
// But Chromium also expects the modifier being set.
static inline WebInputEvent::Modifiers modifierForKeyCode(int key)
@@ -1306,13 +1316,14 @@ static inline WebInputEvent::Modifiers modifiersForEvent(const QInputEvent* even
if (keyEvent->isAutoRepeat())
result |= WebInputEvent::kIsAutoRepeat;
result |= modifierForKeyCode(qtKeyForKeyEvent(keyEvent));
+ result |= lockKeyModifiers(keyEvent->nativeModifiers());
break;
}
default:
break;
}
- return (WebInputEvent::Modifiers)result;
+ return static_cast<WebInputEvent::Modifiers>(result);
}
static inline Qt::KeyboardModifiers keyboardModifiersForModifier(unsigned int modifier)
@@ -1348,6 +1359,10 @@ static inline Qt::MouseButtons mouseButtonsForModifier(unsigned int modifier)
buttons |= Qt::RightButton;
if (modifier & WebInputEvent::kMiddleButtonDown)
buttons |= Qt::MiddleButton;
+ if (modifier & WebInputEvent::kBackButtonDown)
+ buttons |= Qt::BackButton;
+ if (modifier & WebInputEvent::kForwardButtonDown)
+ buttons |= Qt::ForwardButton;
return buttons;
}
@@ -1356,36 +1371,36 @@ static WebInputEvent::Type webEventTypeForEvent(const QEvent* event)
switch (event->type()) {
case QEvent::MouseButtonPress:
case QEvent::TabletPress:
- return WebInputEvent::kMouseDown;
+ return WebInputEvent::Type::kMouseDown;
case QEvent::MouseButtonRelease:
case QEvent::TabletRelease:
- return WebInputEvent::kMouseUp;
+ return WebInputEvent::Type::kMouseUp;
case QEvent::Enter:
- return WebInputEvent::kMouseEnter;
+ return WebInputEvent::Type::kMouseEnter;
case QEvent::Leave:
- return WebInputEvent::kMouseLeave;
+ return WebInputEvent::Type::kMouseLeave;
case QEvent::MouseMove:
case QEvent::TabletMove:
- return WebInputEvent::kMouseMove;
+ return WebInputEvent::Type::kMouseMove;
case QEvent::Wheel:
- return WebInputEvent::kMouseWheel;
+ return WebInputEvent::Type::kMouseWheel;
case QEvent::KeyPress:
- return WebInputEvent::kRawKeyDown;
+ return WebInputEvent::Type::kRawKeyDown;
case QEvent::KeyRelease:
- return WebInputEvent::kKeyUp;
+ return WebInputEvent::Type::kKeyUp;
case QEvent::HoverMove:
- return WebInputEvent::kMouseMove;
+ return WebInputEvent::Type::kMouseMove;
case QEvent::TouchBegin:
- return WebInputEvent::kTouchStart;
+ return WebInputEvent::Type::kTouchStart;
case QEvent::TouchUpdate:
- return WebInputEvent::kTouchMove;
+ return WebInputEvent::Type::kTouchMove;
case QEvent::TouchEnd:
- return WebInputEvent::kTouchEnd;
+ return WebInputEvent::Type::kTouchEnd;
case QEvent::TouchCancel:
- return WebInputEvent::kTouchCancel;
+ return WebInputEvent::Type::kTouchCancel;
default:
Q_ASSERT(false);
- return WebInputEvent::kMouseMove;
+ return WebInputEvent::Type::kMouseMove;
}
}
@@ -1410,8 +1425,8 @@ static WebPointerProperties::PointerType pointerTypeForTabletEvent(const QTablet
WebMouseEvent WebEventFactory::toWebMouseEvent(QMouseEvent *ev)
{
WebMouseEvent webKitEvent(webEventTypeForEvent(ev),
- WebFloatPoint(ev->x(), ev->y()),
- WebFloatPoint(ev->globalX(), ev->globalY()),
+ gfx::PointF(ev->position().x(), ev->position().y()),
+ gfx::PointF(ev->globalPosition().x(), ev->globalPosition().y()),
mouseButtonForEvent<QMouseEvent>(ev),
0,
modifiersForEvent(ev),
@@ -1429,9 +1444,11 @@ WebMouseEvent WebEventFactory::toWebMouseEvent(QHoverEvent *ev)
webKitEvent.SetModifiers(modifiersForEvent(ev));
webKitEvent.SetType(webEventTypeForEvent(ev));
- webKitEvent.SetPositionInWidget(ev->pos().x(), ev->pos().y());
- webKitEvent.movement_x = ev->pos().x() - ev->oldPos().x();
- webKitEvent.movement_y = ev->pos().y() - ev->oldPos().y();
+ webKitEvent.SetPositionInWidget(ev->position().x(), ev->position().y());
+ webKitEvent.SetPositionInScreen(ev->globalPosition().x(), ev->globalPosition().y());
+ webKitEvent.movement_x = ev->position().x() - ev->oldPos().x();
+ webKitEvent.movement_y = ev->position().y() - ev->oldPos().y();
+ webKitEvent.is_raw_movement_event = true;
webKitEvent.pointer_type = WebPointerProperties::PointerType::kMouse;
return webKitEvent;
@@ -1441,8 +1458,8 @@ WebMouseEvent WebEventFactory::toWebMouseEvent(QHoverEvent *ev)
WebMouseEvent WebEventFactory::toWebMouseEvent(QTabletEvent *ev)
{
WebMouseEvent webKitEvent(webEventTypeForEvent(ev),
- WebFloatPoint(ev->x(), ev->y()),
- WebFloatPoint(ev->globalX(), ev->globalY()),
+ gfx::PointF(ev->position().x(), ev->position().y()),
+ gfx::PointF(ev->globalPosition().x(), ev->globalPosition().y()),
mouseButtonForEvent<QTabletEvent>(ev),
0,
modifiersForEvent(ev),
@@ -1464,42 +1481,48 @@ WebMouseEvent WebEventFactory::toWebMouseEvent(QEvent *ev)
WebMouseEvent webKitEvent;
webKitEvent.SetTimeStamp(base::TimeTicks::Now());
- webKitEvent.SetType(WebInputEvent::kMouseLeave);
+ webKitEvent.SetType(WebInputEvent::Type::kMouseLeave);
return webKitEvent;
}
-#ifndef QT_NO_GESTURES
+#if QT_CONFIG(gestures)
WebGestureEvent WebEventFactory::toWebGestureEvent(QNativeGestureEvent *ev)
{
WebGestureEvent webKitEvent;
webKitEvent.SetTimeStamp(base::TimeTicks::Now());
webKitEvent.SetModifiers(modifiersForEvent(ev));
- webKitEvent.SetPositionInWidget(WebFloatPoint(ev->localPos().x(),
- ev->localPos().y()));
+ webKitEvent.SetPositionInWidget(gfx::PointF(ev->position().x(),
+ ev->position().y()));
- webKitEvent.SetPositionInScreen(WebFloatPoint(ev->screenPos().x(),
- ev->screenPos().y()));
+ webKitEvent.SetPositionInScreen(gfx::PointF(ev->globalPosition().x(),
+ ev->globalPosition().y()));
webKitEvent.SetSourceDevice(blink::WebGestureDevice::kTouchpad);
Qt::NativeGestureType gestureType = ev->gestureType();
switch (gestureType) {
case Qt::ZoomNativeGesture:
- webKitEvent.SetType(WebInputEvent::kGesturePinchUpdate);
+ webKitEvent.SetType(WebInputEvent::Type::kGesturePinchUpdate);
webKitEvent.data.pinch_update.scale = static_cast<float>(ev->value() + 1.0);
break;
case Qt::SmartZoomNativeGesture:
- webKitEvent.SetType(WebInputEvent::kGestureDoubleTap);
+ webKitEvent.SetType(WebInputEvent::Type::kGestureDoubleTap);
webKitEvent.data.tap.tap_count = 1;
break;
case Qt::BeginNativeGesture:
+ webKitEvent.SetType(WebInputEvent::Type::kGesturePinchBegin);
+ webKitEvent.SetNeedsWheelEvent(true);
+ break;
case Qt::EndNativeGesture:
+ webKitEvent.SetType(WebInputEvent::Type::kGesturePinchEnd);
+ webKitEvent.SetNeedsWheelEvent(true);
+ break;
case Qt::RotateNativeGesture:
case Qt::PanNativeGesture:
case Qt::SwipeNativeGesture:
// Not implemented by Chromium for now.
- webKitEvent.SetType(blink::WebInputEvent::kUndefined);
+ webKitEvent.SetType(blink::WebInputEvent::Type::kUndefined);
break;
}
@@ -1522,20 +1545,19 @@ static QPoint getWheelEventDelta(const blink::WebGestureEvent &webEvent)
{
static const float cDefaultQtScrollStep = 20.f;
static const int wheelScrollLines = QGuiApplication::styleHints()->wheelScrollLines();
- return QPoint(webEvent.data.scroll_update.delta_x * QWheelEvent::DefaultDeltasPerStep / (wheelScrollLines * cDefaultQtScrollStep),
- webEvent.data.scroll_update.delta_y * QWheelEvent::DefaultDeltasPerStep / (wheelScrollLines * cDefaultQtScrollStep));
+ static const float deltasPerStep = static_cast<float>(QWheelEvent::DefaultDeltasPerStep);
+ return QPoint(webEvent.data.scroll_update.delta_x * deltasPerStep / (wheelScrollLines * cDefaultQtScrollStep),
+ webEvent.data.scroll_update.delta_y * deltasPerStep / (wheelScrollLines * cDefaultQtScrollStep));
}
blink::WebMouseWheelEvent::Phase toBlinkPhase(QWheelEvent *ev)
{
switch (ev->phase()) {
case Qt::NoScrollPhase:
-#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
case Qt::ScrollMomentum:
-#endif
return blink::WebMouseWheelEvent::kPhaseNone;
case Qt::ScrollBegin:
- return ev->angleDelta().isNull() ? blink::WebMouseWheelEvent::kPhaseMayBegin : blink::WebMouseWheelEvent::kPhaseBegan;
+ return blink::WebMouseWheelEvent::kPhaseBegan;
case Qt::ScrollUpdate:
return blink::WebMouseWheelEvent::kPhaseChanged;
case Qt::ScrollEnd:
@@ -1545,29 +1567,41 @@ blink::WebMouseWheelEvent::Phase toBlinkPhase(QWheelEvent *ev)
return blink::WebMouseWheelEvent::kPhaseNone;
}
+blink::WebMouseWheelEvent::Phase getMomentumPhase(QWheelEvent *ev)
+{
+ switch (ev->phase()) {
+ case Qt::ScrollMomentum:
+ return blink::WebMouseWheelEvent::kPhaseBegan;
+ case Qt::ScrollEnd:
+ return blink::WebMouseWheelEvent::kPhaseEnded;
+ case Qt::NoScrollPhase:
+ case Qt::ScrollBegin:
+ case Qt::ScrollUpdate:
+ return blink::WebMouseWheelEvent::kPhaseNone;
+ }
+ Q_UNREACHABLE();
+ return blink::WebMouseWheelEvent::kPhaseNone;
+}
+
blink::WebMouseWheelEvent WebEventFactory::toWebWheelEvent(QWheelEvent *ev)
{
WebMouseWheelEvent webEvent;
webEvent.SetType(webEventTypeForEvent(ev));
webEvent.SetModifiers(modifiersForEvent(ev));
webEvent.SetTimeStamp(base::TimeTicks::Now());
-#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
- webEvent.SetPositionInWidget(ev->x(), ev->y());
- webEvent.SetPositionInScreen(ev->globalX(), ev->globalY());
-#else
webEvent.SetPositionInWidget(static_cast<float>(ev->position().x()),
static_cast<float>(ev->position().y()));
webEvent.SetPositionInScreen(static_cast<float>(ev->globalPosition().x()),
static_cast<float>(ev->globalPosition().y()));
-#endif
- webEvent.wheel_ticks_x = static_cast<float>(ev->angleDelta().x()) / QWheelEvent::DefaultDeltasPerStep;
- webEvent.wheel_ticks_y = static_cast<float>(ev->angleDelta().y()) / QWheelEvent::DefaultDeltasPerStep;
+ webEvent.wheel_ticks_x = ev->angleDelta().x() / static_cast<float>(QWheelEvent::DefaultDeltasPerStep);
+ webEvent.wheel_ticks_y = ev->angleDelta().y() / static_cast<float>(QWheelEvent::DefaultDeltasPerStep);
webEvent.phase = toBlinkPhase(ev);
#if defined(Q_OS_DARWIN)
// PrecisePixel is a macOS term meaning it is a system scroll gesture, see qnsview_mouse.mm
+ webEvent.momentum_phase = getMomentumPhase(ev);
if (ev->source() == Qt::MouseEventSynthesizedBySystem)
- webEvent.delta_units = ui::input_types::ScrollGranularity::kScrollByPrecisePixel;
+ webEvent.delta_units = ui::ScrollGranularity::kScrollByPrecisePixel;
#endif
setBlinkWheelEventDelta(webEvent);
@@ -1584,38 +1618,36 @@ bool WebEventFactory::coalesceWebWheelEvent(blink::WebMouseWheelEvent &webEvent,
if (toBlinkPhase(ev) != webEvent.phase)
return false;
#if defined(Q_OS_DARWIN)
- if ((webEvent.delta_units == ui::input_types::ScrollGranularity::kScrollByPrecisePixel)
+ if (getMomentumPhase(ev) != webEvent.momentum_phase)
+ return false;
+
+ if ((webEvent.delta_units == ui::ScrollGranularity::kScrollByPrecisePixel)
!= (ev->source() == Qt::MouseEventSynthesizedBySystem))
return false;
#endif
webEvent.SetTimeStamp(base::TimeTicks::Now());
-#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
- webEvent.SetPositionInWidget(ev->x(), ev->y());
- webEvent.SetPositionInScreen(ev->globalX(), ev->globalY());
-#else
webEvent.SetPositionInWidget(static_cast<float>(ev->position().x()),
static_cast<float>(ev->position().y()));
webEvent.SetPositionInScreen(static_cast<float>(ev->globalPosition().x()),
static_cast<float>(ev->globalPosition().y()));
-#endif
- webEvent.wheel_ticks_x += static_cast<float>(ev->angleDelta().x()) / QWheelEvent::DefaultDeltasPerStep;
- webEvent.wheel_ticks_y += static_cast<float>(ev->angleDelta().y()) / QWheelEvent::DefaultDeltasPerStep;
+ webEvent.wheel_ticks_x = ev->angleDelta().x() / static_cast<float>(QWheelEvent::DefaultDeltasPerStep);
+ webEvent.wheel_ticks_y = ev->angleDelta().y() / static_cast<float>(QWheelEvent::DefaultDeltasPerStep);
setBlinkWheelEventDelta(webEvent);
return true;
}
-static QPointF toQt(blink::WebFloatPoint p)
+static QPointF toQt(gfx::PointF p)
{
- return QPointF(p.x, p.y);
+ return QPointF(p.x(), p.y());
}
void WebEventFactory::sendUnhandledWheelEvent(const blink::WebGestureEvent &event,
RenderWidgetHostViewQtDelegate *delegate)
{
- Q_ASSERT(event.GetType() == blink::WebInputEvent::kGestureScrollUpdate);
+ Q_ASSERT(event.GetType() == blink::WebInputEvent::Type::kGestureScrollUpdate);
QWheelEvent ev(toQt(event.PositionInWidget()),
toQt(event.PositionInScreen()),
@@ -1629,13 +1661,17 @@ void WebEventFactory::sendUnhandledWheelEvent(const blink::WebGestureEvent &even
content::NativeWebKeyboardEvent WebEventFactory::toWebKeyboardEvent(QKeyEvent *ev)
{
- content::NativeWebKeyboardEvent webKitEvent(reinterpret_cast<gfx::NativeEvent>(ev));
+ content::NativeWebKeyboardEvent webKitEvent(ToNativeEvent(ev));
webKitEvent.SetTimeStamp(base::TimeTicks::Now());
- webKitEvent.SetModifiers(modifiersForEvent(ev));
+ bool isBackTabWithoutModifier =
+ ev->key() == Qt::Key_Backtab && ev->modifiers() == Qt::NoModifier;
+ webKitEvent.SetModifiers(isBackTabWithoutModifier ? WebInputEvent::kShiftKey
+ : modifiersForEvent(ev));
webKitEvent.SetType(webEventTypeForEvent(ev));
int qtKey = qtKeyForKeyEvent(ev);
- Qt::KeyboardModifiers qtModifiers = qtModifiersForEvent(ev);
+ Qt::KeyboardModifiers qtModifiers =
+ isBackTabWithoutModifier ? Qt::ShiftModifier : qtModifiersForEvent(ev);
QString qtText = qtTextForKeyEvent(ev, qtKey, qtModifiers);
webKitEvent.native_key_code = nativeKeyCodeForKeyEvent(ev);
@@ -1670,10 +1706,12 @@ content::NativeWebKeyboardEvent WebEventFactory::toWebKeyboardEvent(QKeyEvent *e
ui::DomCodeToUsLayoutKeyboardCode(static_cast<ui::DomCode>(webKitEvent.dom_code));
const ushort* text = qtText.utf16();
- size_t textSize = std::min(sizeof(webKitEvent.text), size_t(qtText.length() * 2));
- memcpy(&webKitEvent.text, text, textSize);
- memcpy(&webKitEvent.unmodified_text, text, textSize);
-
+ size_t size = std::char_traits<char16_t>::length((char16_t *)text);
+ if (size <= blink::WebKeyboardEvent::kTextLengthCap - 1) { // should be null terminated
+ size_t textSize = std::min(sizeof(webKitEvent.text), size * sizeof(char16_t));
+ memcpy(&webKitEvent.text, text, textSize);
+ memcpy(&webKitEvent.unmodified_text, text, textSize);
+ }
if (webKitEvent.windows_key_code == VK_RETURN) {
// This is the same behavior as GTK:
// We need to treat the enter key as a key press of character \r. This
diff --git a/src/core/web_event_factory.h b/src/core/web_event_factory.h
index 390502a9d..53ebfb509 100644
--- a/src/core/web_event_factory.h
+++ b/src/core/web_event_factory.h
@@ -1,64 +1,28 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWebEngine module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef WEB_EVENT_FACTORY_H
#define WEB_EVENT_FACTORY_H
-#include "content/public/browser/native_web_keyboard_event.h"
-#ifndef QT_NO_GESTURES
-#include "third_party/blink/public/platform/web_gesture_event.h"
-#endif
-#include "third_party/blink/public/platform/web_mouse_event.h"
-#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "QtGui/qtguiglobal.h"
-#include <QtGlobal>
+#include "content/public/common/input/native_web_keyboard_event.h"
+#if QT_CONFIG(gestures)
+#include "third_party/blink/public/common/input/web_gesture_event.h"
+#endif
+#include "third_party/blink/public/common/input/web_mouse_event.h"
+#include "third_party/blink/public/common/input/web_mouse_wheel_event.h"
QT_BEGIN_NAMESPACE
class QEvent;
class QHoverEvent;
class QKeyEvent;
class QMouseEvent;
-#ifndef QT_NO_TABLETEVENT
+#if QT_CONFIG(tabletevent)
class QTabletEvent;
#endif
class QWheelEvent;
-#ifndef QT_NO_GESTURES
+#if QT_CONFIG(gestures)
class QNativeGestureEvent;
#endif
QT_END_NAMESPACE
@@ -72,11 +36,11 @@ class WebEventFactory {
public:
static blink::WebMouseEvent toWebMouseEvent(QMouseEvent *);
static blink::WebMouseEvent toWebMouseEvent(QHoverEvent *);
-#ifndef QT_NO_TABLETEVENT
+#if QT_CONFIG(tabletevent)
static blink::WebMouseEvent toWebMouseEvent(QTabletEvent *);
#endif
static blink::WebMouseEvent toWebMouseEvent(QEvent *);
-#ifndef QT_NO_GESTURES
+#if QT_CONFIG(gestures)
static blink::WebGestureEvent toWebGestureEvent(QNativeGestureEvent *);
#endif
static blink::WebMouseWheelEvent toWebWheelEvent(QWheelEvent *);
diff --git a/src/core/web_usb_detector_qt.cpp b/src/core/web_usb_detector_qt.cpp
new file mode 100644
index 000000000..511ac6801
--- /dev/null
+++ b/src/core/web_usb_detector_qt.cpp
@@ -0,0 +1,45 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+// based on chrome/browser/usb/web_usb_detector.cc
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "web_usb_detector_qt.h"
+
+#include "qtwebenginecoreglobal_p.h"
+
+#include "content/public/browser/device_service.h"
+#include "device/base/features.h"
+#include "services/device/public/mojom/usb_device.mojom.h"
+
+WebUsbDetectorQt::WebUsbDetectorQt() = default;
+
+WebUsbDetectorQt::~WebUsbDetectorQt() = default;
+
+void WebUsbDetectorQt::Initialize()
+{
+ if (!m_deviceManager) {
+ // Receive mojo::Remote<UsbDeviceManager> from DeviceService.
+ content::GetDeviceService().BindUsbDeviceManager(
+ m_deviceManager.BindNewPipeAndPassReceiver());
+ }
+ DCHECK(m_deviceManager);
+
+ // Listen for added/removed device events.
+ DCHECK(!m_clientReceiver.is_bound());
+ m_deviceManager->SetClient(m_clientReceiver.BindNewEndpointAndPassRemote());
+}
+
+void WebUsbDetectorQt::OnDeviceAdded(device::mojom::UsbDeviceInfoPtr device_info)
+{
+ Q_UNUSED(device_info);
+ QT_NOT_YET_IMPLEMENTED
+}
+
+void WebUsbDetectorQt::OnDeviceRemoved(device::mojom::UsbDeviceInfoPtr device_info)
+{
+ Q_UNUSED(device_info);
+ QT_NOT_YET_IMPLEMENTED
+}
diff --git a/src/core/web_usb_detector_qt.h b/src/core/web_usb_detector_qt.h
new file mode 100644
index 000000000..b9ab5e4bb
--- /dev/null
+++ b/src/core/web_usb_detector_qt.h
@@ -0,0 +1,34 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef WEB_USB_DETECTOR_QT_H
+#define WEB_USB_DETECTOR_QT_H
+
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/remote.h"
+#include "services/device/public/mojom/usb_manager.mojom.h"
+#include "services/device/public/mojom/usb_manager_client.mojom.h"
+#include "url/gurl.h"
+
+class WebUsbDetectorQt : public device::mojom::UsbDeviceManagerClient
+{
+public:
+ WebUsbDetectorQt();
+ ~WebUsbDetectorQt() override;
+
+ void Initialize();
+
+private:
+ // device::mojom::UsbDeviceManagerClient implementation.
+ void OnDeviceAdded(device::mojom::UsbDeviceInfoPtr device_info) override;
+ void OnDeviceRemoved(device::mojom::UsbDeviceInfoPtr device_info) override;
+
+ // Connection to |device_manager_instance_|.
+ mojo::Remote<device::mojom::UsbDeviceManager> m_deviceManager;
+ mojo::AssociatedReceiver<device::mojom::UsbDeviceManagerClient> m_clientReceiver { this };
+
+ base::WeakPtrFactory<WebUsbDetectorQt> m_weakFactory { this };
+};
+
+#endif // WEB_USB_DETECTOR_QT_H