summaryrefslogtreecommitdiffstats
path: root/src/core/api
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/api')
-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.pro86
-rw-r--r--src/core/api/qt_cmdline.cmake34
-rw-r--r--src/core/api/qtbug-60565.cpp138
-rw-r--r--src/core/api/qtbug-61521.cpp120
-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.cpp175
-rw-r--r--src/core/api/qwebenginecertificateerror.h80
-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.cpp192
-rw-r--r--src/core/api/qwebengineframe.h72
-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.cpp2531
-rw-r--r--src/core/api/qwebenginepage.h406
-rw-r--r--src/core/api/qwebenginepage_p.h226
-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
91 files changed, 11596 insertions, 2111 deletions
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 d53fb6942..000000000
--- a/src/core/api/core_api.pro
+++ /dev/null
@@ -1,86 +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
-
-### Qt6 Remove this workaround
-unix:!isEmpty(QMAKE_LFLAGS_VERSION_SCRIPT):!static {
- SOURCES += qtbug-60565.cpp \
- qtbug-61521.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/qtbug-60565.cpp b/src/core/api/qtbug-60565.cpp
deleted file mode 100644
index f48a2a701..000000000
--- a/src/core/api/qtbug-60565.cpp
+++ /dev/null
@@ -1,138 +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 <new>
-#include <unistd.h>
-
-#if defined(__LP64__)
-# define SIZE_T_MANGLING "m"
-#else
-# define SIZE_T_MANGLING "j"
-#endif
-
-#define SHIM_ALIAS_SYMBOL(fn) __attribute__((weak, alias(#fn)))
-#define SHIM_HIDDEN __attribute__ ((visibility ("hidden")))
-
-extern "C" {
-
-__asm__(".symver __ShimCppNew, _Znw" SIZE_T_MANGLING "@Qt_5");
-void* __ShimCppNew(size_t size)
- SHIM_ALIAS_SYMBOL(ShimCppNew);
-
-__asm__(".symver __ShimCppDelete, _ZdlPv@Qt_5");
-void __ShimCppDelete(void* address)
- SHIM_ALIAS_SYMBOL(ShimCppDelete);
-
-__asm__(".symver __ShimCppNewArray, _Zna" SIZE_T_MANGLING "@Qt_5");
-void* __ShimCppNewArray(size_t size)
- SHIM_ALIAS_SYMBOL(ShimCppNewArray);
-
-__asm__(".symver __ShimCppDeleteArray, _ZdaPv@Qt_5");
-void __ShimCppDeleteArray(void* address)
- SHIM_ALIAS_SYMBOL(ShimCppDeleteArray);
-
-__asm__(".symver __ShimCppNewNoThrow, _Znw" SIZE_T_MANGLING "RKSt9nothrow_t@Qt_5");
-void *__ShimCppNewNoThrow(size_t size, const std::nothrow_t&) noexcept
- SHIM_ALIAS_SYMBOL(ShimCppNewNoThrow);
-
-__asm__(".symver __ShimCppNewArrayNoThrow, _Zna" SIZE_T_MANGLING "RKSt9nothrow_t@Qt_5");
-void *__ShimCppNewArrayNoThrow(size_t size, const std::nothrow_t&) noexcept
- SHIM_ALIAS_SYMBOL(ShimCppNewArrayNoThrow);
-
-__asm__(".symver __ShimCppDeleteNoThrow, _ZdlPvRKSt9nothrow_t@Qt_5");
-void __ShimCppDeleteNoThrow(void* address, const std::nothrow_t&) noexcept
- SHIM_ALIAS_SYMBOL(ShimCppDeleteNoThrow);
-
-__asm__(".symver __ShimCppDeleteArrayNoThrow, _ZdaPvRKSt9nothrow_t@Qt_5");
-void __ShimCppDeleteArrayNoThrow(void* address, const std::nothrow_t&) noexcept
- SHIM_ALIAS_SYMBOL(ShimCppDeleteArrayNoThrow);
-
-static void* __shimCppNew(size_t size);
-static void* __shimCppNewArray(size_t size);
-static void __shimCppDelete(void *address);
-static void __shimCppDeleteArray(void *address);
-
-SHIM_HIDDEN void* ShimCppNew(size_t size) {
- return __shimCppNew(size);
-}
-
-SHIM_HIDDEN void* ShimCppNewNoThrow(size_t size, const std::nothrow_t&) noexcept {
- return __shimCppNew(size);
-}
-
-SHIM_HIDDEN void* ShimCppNewArray(size_t size) {
- return __shimCppNewArray(size);
-}
-
-SHIM_HIDDEN void* ShimCppNewArrayNoThrow(size_t size, const std::nothrow_t&) noexcept {
- return __shimCppNewArray(size);
-}
-
-SHIM_HIDDEN void ShimCppDelete(void* address) {
- __shimCppDelete(address);
-}
-
-SHIM_HIDDEN void ShimCppDeleteNoThrow(void* address, const std::nothrow_t&) noexcept {
- __shimCppDelete(address);
-}
-
-SHIM_HIDDEN void ShimCppDeleteArray(void* address) {
- __shimCppDeleteArray(address);
-}
-
-SHIM_HIDDEN void ShimCppDeleteArrayNoThrow(void* address, const std::nothrow_t&) noexcept {
- __shimCppDeleteArray(address);
-}
-} // extern "C"
-
-static void* __shimCppNew(size_t size) {
- return operator new(size);
-}
-
-static void* __shimCppNewArray(size_t size) {
- return operator new[](size);
-}
-
-static void __shimCppDelete(void* address) {
- operator delete(address);
-}
-
-static void __shimCppDeleteArray(void* address) {
- operator delete[](address);
-}
diff --git a/src/core/api/qtbug-61521.cpp b/src/core/api/qtbug-61521.cpp
deleted file mode 100644
index 002a1af22..000000000
--- a/src/core/api/qtbug-61521.cpp
+++ /dev/null
@@ -1,120 +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 <stdlib.h>
-#include <malloc.h>
-
-#define SHIM_ALIAS_SYMBOL(fn) __attribute__((weak, alias(#fn)))
-#define SHIM_SYMBOL_VERSION(fn) __asm__(".symver __" #fn "," #fn "@Qt_5")
-#define SHIM_HIDDEN __attribute__ ((visibility ("hidden")))
-
-extern "C" {
-
-SHIM_SYMBOL_VERSION(malloc);
-void* __malloc(size_t size)
- SHIM_ALIAS_SYMBOL(ShimMalloc);
-
-SHIM_SYMBOL_VERSION(free);
-void __free(void* ptr)
- SHIM_ALIAS_SYMBOL(ShimFree);
-
-SHIM_SYMBOL_VERSION(realloc);
-void* __realloc(void* ptr, size_t size)
- SHIM_ALIAS_SYMBOL(ShimRealloc);
-
-SHIM_SYMBOL_VERSION(calloc);
-void* __calloc(size_t n, size_t size)
- SHIM_ALIAS_SYMBOL(ShimCalloc);
-
-SHIM_SYMBOL_VERSION(cfree);
-void __cfree(void* ptr)
- SHIM_ALIAS_SYMBOL(ShimCFree);
-
-SHIM_SYMBOL_VERSION(memalign);
-void* __memalign(size_t align, size_t s)
- SHIM_ALIAS_SYMBOL(ShimMemalign);
-
-SHIM_SYMBOL_VERSION(valloc);
-void* __valloc(size_t size)
- SHIM_ALIAS_SYMBOL(ShimValloc);
-
-SHIM_SYMBOL_VERSION(pvalloc);
-void* __pvalloc(size_t size)
- SHIM_ALIAS_SYMBOL(ShimPvalloc);
-
-SHIM_SYMBOL_VERSION(posix_memalign);
-int __posix_memalign(void** r, size_t a, size_t s)
- SHIM_ALIAS_SYMBOL(ShimPosixMemalign);
-
-SHIM_HIDDEN void* ShimMalloc(size_t size) {
- return malloc(size);
-}
-
-SHIM_HIDDEN void ShimFree(void* ptr) {
- free(ptr);
-}
-
-SHIM_HIDDEN void* ShimRealloc(void* ptr, size_t size) {
- return realloc(ptr,size);
-}
-
-SHIM_HIDDEN void* ShimCalloc(size_t n, size_t size) {
- return calloc(n,size);
-}
-
-SHIM_HIDDEN void ShimCFree(void* ptr) {
- free(ptr);
-}
-
-SHIM_HIDDEN void* ShimMemalign(size_t align, size_t s) {
- return memalign(align,s);
-}
-
-SHIM_HIDDEN void* ShimValloc(size_t size) {
- return valloc(size);
-}
-
-SHIM_HIDDEN void* ShimPvalloc(size_t size) {
- return pvalloc(size);
-}
-
-SHIM_HIDDEN int ShimPosixMemalign(void** r, size_t a, size_t s) {
- return posix_memalign(r,a,s);
-}
-} // extern "C"
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..85c5d5127
--- /dev/null
+++ b/src/core/api/qwebenginecertificateerror.cpp
@@ -0,0 +1,175 @@
+// 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();
+}
+
+/*!
+ \property QWebEngineCertificateError::isMainFrame
+ \since 6.8
+
+ Returns whether the certificate error comes from the main frame. If false,
+ the error comes from a sub-resource and most likely needs to be rejected without
+ user input.
+*/
+bool QWebEngineCertificateError::isMainFrame() const
+{
+ return d->isMainFrame();
+}
+
+/*!
+ 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..3eef3dcca
--- /dev/null
+++ b/src/core/api/qwebenginecertificateerror.h
@@ -0,0 +1,80 @@
+// 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)
+ Q_PROPERTY(bool isMainFrame READ isMainFrame CONSTANT FINAL REVISION(6, 8))
+
+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;
+ bool isMainFrame() 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..1eedc4b92
--- /dev/null
+++ b/src/core/api/qwebengineframe.cpp
@@ -0,0 +1,192 @@
+// 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 "qwebenginescript.h"
+#include <QtQml/qqmlengine.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 void QWebEngineFrame::runJavaScript(const QString &script, const std::function<void(const QVariant &)> &callback)
+ \fn void QWebEngineFrame::runJavaScript(const QString &script, quint32 worldId)
+ \fn void QWebEngineFrame::runJavaScript(const QString &script, quint32 worldId, const
+ std::function<void(const QVariant &)> &callback)
+
+ Runs the JavaScript code contained in \a script on this frame, without checking
+ whether the DOM of the page has been constructed.
+ 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 callback is called with the result of the last
+ executed statement. \c callback 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 \a callback 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 QWebEngineScript::ScriptWorldId, QWebEnginePage::runJavaScript, {Script Injection}
+ */
+void QWebEngineFrame::runJavaScript(const QString &script,
+ const std::function<void(const QVariant &)> &callback)
+{
+ runJavaScript(script, QWebEngineScript::MainWorld, callback);
+}
+
+void QWebEngineFrame::runJavaScript(const QString &script, quint32 worldId,
+ const std::function<void(const QVariant &)> &callback)
+{
+ m_adapterClient->runJavaScript(script, worldId, m_id, callback);
+}
+
+void QWebEngineFrame::runJavaScript(const QString &script, quint32 worldId)
+{
+ runJavaScript(script, worldId, std::function<void(const QVariant &)>{});
+}
+
+void QWebEngineFrame::runJavaScript(const QString &script, const QJSValue &callback)
+{
+ runJavaScript(script, QWebEngineScript::MainWorld, callback);
+}
+
+void QWebEngineFrame::runJavaScript(const QString &script, quint32 worldId,
+ const QJSValue &callback)
+{
+ std::function<void(const QVariant &)> wrappedCallback;
+ if (!callback.isUndefined()) {
+ const QObject *holdingObject = m_adapterClient->holdingQObject();
+ wrappedCallback = [holdingObject, callback](const QVariant &result) {
+ if (auto engine = qmlEngine(holdingObject)) {
+ QJSValueList args;
+ args.append(engine->toScriptValue(result));
+ callback.call(args);
+ } else {
+ qWarning("No QML engine found to execute runJavaScript() callback");
+ }
+ };
+ }
+ runJavaScript(script, worldId, wrappedCallback);
+}
+
+/*! \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..988d50d8e
--- /dev/null
+++ b/src/core/api/qwebengineframe.h
@@ -0,0 +1,72 @@
+// 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 <QtQml/qqmlregistration.h>
+#include <QtQml/qjsvalue.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
+{
+ Q_GADGET
+
+ Q_PROPERTY(bool isValid READ isValid FINAL)
+ Q_PROPERTY(QString name READ name FINAL)
+ Q_PROPERTY(QString htmlName READ htmlName FINAL)
+ Q_PROPERTY(QUrl url READ url FINAL)
+ Q_PROPERTY(QSizeF size READ size FINAL)
+
+public:
+ QML_VALUE_TYPE(webEngineFrame)
+ QML_ADDED_IN_VERSION(6, 8)
+
+ bool isValid() const;
+ QString name() const;
+ QString htmlName() const;
+ QList<QWebEngineFrame> children() const;
+ QUrl url() const;
+ QSizeF size() const;
+
+ void runJavaScript(const QString &script,
+ const std::function<void(const QVariant &)> &callback);
+ void runJavaScript(const QString &script, quint32 worldId,
+ const std::function<void(const QVariant &)> &callback);
+ Q_INVOKABLE void runJavaScript(const QString &script, quint32 worldId = 0);
+ Q_INVOKABLE void runJavaScript(const QString &script, const QJSValue &callback);
+ Q_INVOKABLE void runJavaScript(const QString &script, quint32 worldId,
+ const QJSValue &callback);
+
+ 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;
+ friend class QQuickWebEngineView;
+
+ 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..439214235
--- /dev/null
+++ b/src/core/api/qwebenginepage.cpp
@@ -0,0 +1,2531 @@
+// 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::zoomFactorChanged(qreal factor)
+{
+ Q_Q(QWebEnginePage);
+ Q_EMIT q->zoomFactorChanged(factor);
+}
+
+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::runJavaScript(const QString &script, quint32 worldId, quint64 frameId,
+ const std::function<void(const QVariant &)> &callback)
+{
+ ensureInitialized();
+ if (adapter->lifecycleState() == WebContentsAdapter::LifecycleState::Discarded) {
+ qWarning("runJavaScript: disabled in Discarded state");
+ if (callback)
+ callback(QVariant());
+ } else
+ adapter->runJavaScript(script, worldId, frameId, callback);
+}
+
+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();
+
+ d_ptr->adapter->clearJavaScriptCallbacks();
+ for (auto strFun : std::as_const(d_ptr->m_stringCallbacks))
+ strFun(QString());
+ 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() && !qFuzzyCompare(factor, zoomFactor())) {
+ 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)
+{
+ runJavaScript(scriptSource, QWebEngineScript::MainWorld, resultCallback);
+}
+
+void QWebEnginePage::runJavaScript(const QString& scriptSource, quint32 worldId, const std::function<void(const QVariant &)> &resultCallback)
+{
+ Q_D(QWebEnginePage);
+ d->runJavaScript(scriptSource, worldId, WebContentsAdapter::kUseMainFrameId, resultCallback);
+}
+
+/*!
+ 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..13c582931
--- /dev/null
+++ b/src/core/api/qwebenginepage.h
@@ -0,0 +1,406 @@
+// 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 NOTIFY zoomFactorChanged)
+ 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 zoomFactorChanged(qreal factor);
+ 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..f0e179ea8
--- /dev/null
+++ b/src/core/api/qwebenginepage_p.h
@@ -0,0 +1,226 @@
+// 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 zoomFactorChanged(qreal factor) 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 runJavaScript(const QString &script, quint32 worldId, quint64 frameId,
+ const std::function<void(const QVariant &)> &callback) 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 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