diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2019-10-28 14:40:59 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2019-10-28 16:48:32 +0100 |
commit | b97f0eb87b6e6a6726b805c9de2159c6ad983f7d (patch) | |
tree | ef5984369eb0fac54704725aa8c976e8c1b059ac | |
parent | d82ff4e1d1a93bf0a31745a5454346ac54959cf8 (diff) | |
parent | de428e1a79708967f97aa8ffcbb2403d3b7d1e7f (diff) |
Merge "Merge remote-tracking branch 'origin/5.15' into dev"
153 files changed, 2456 insertions, 1249 deletions
diff --git a/configure.pri b/configure.pri index eff7d8f61..13ceb8cdc 100644 --- a/configure.pri +++ b/configure.pri @@ -1,3 +1,4 @@ +include(src/buildtools/config/support.pri) include(src/buildtools/config/functions.pri) # this must be done outside any function @@ -25,7 +26,10 @@ defineTest(isPythonVersionSupported) { defineTest(qtConfTest_detectJumboBuild) { mergeLimit = $$eval(config.input.merge_limit) mergeLimit = $$find(mergeLimit, "\\d") - isEmpty(mergeLimit): mergeLimit = 0 + isEmpty(mergeLimit) { + win32: mergeLimit = 0 + else: mergeLimit = 8 + } qtLog("Setting jumbo build merge batch limit to $${mergeLimit}.") $${1}.merge_limit = $$mergeLimit export($${1}.merge_limit) @@ -35,10 +39,16 @@ defineTest(qtConfTest_detectJumboBuild) { return(true) } +defineTest(qtConfReport_skipBuildWarning) { + $${1}() + !isEmpty(skipBuildReason):qtConfAddWarning($${skipBuildReason}) +} + defineTest(qtConfReport_jumboBuild) { - mergeLimit = $$eval(config.input.merge_limit) - mergeLimit = $$find(mergeLimit, "\d") - isEmpty(mergeLimit): mergeLimit = "no" + mergeLimit = $$eval(cache.webengine-jumbo-build.merge_limit) + isEmpty(mergeLimit)|!greaterThan(mergeLimit,0) { + mergeLimit = "no" + } qtConfReportPadded($${1}, $$mergeLimit) } @@ -96,6 +106,48 @@ defineTest(qtConfTest_detectBison) { return(true) } +defineTest(qtwebengine_platformError) { + platformError = $$1 + export(platformError) +} + +defineTest(qtConfTest_detectPlatform) { + QT_FOR_CONFIG += gui-private + + !linux:!win32:!macos { + qtwebengine_platformError("Unknown platform. Qt WebEngine only supports Linux, Windows, and macOS.") + } else { + linux:qtwebengine_isLinuxPlatformSupported() { + $${1}.platform = "linux" + } + win32:qtwebengine_isWindowsPlatformSupported() { + $${1}.platform = "windows" + } + macos:qtwebengine_isMacOsPlatformSupported() { + $${1}.platform = "macos" + } + } + + !isEmpty(platformError) { + qtLog("Platform not supported.") + $${1}.platformSupport = $$platformError + export($${1}.platformSupport) + $${1}.cache += platformSupport + export($${1}.cache) + return(false) + } + export($${1}.platformSupport) + return(true) +} + +defineTest(qtConfTest_detectArch) { + contains(QT_ARCH, "i386")|contains(QT_ARCH, "x86_64"): return(true) + contains(QT_ARCH, "arm")|contains(QT_ARCH, "arm64"): return(true) + contains(QT_ARCH, "mips"): return(true) + qtLog("Architecture not supported.") + return(false) +} + defineTest(qtConfTest_detectFlex) { flex = $$qtConfFindGnuTool("flex$$EXE_SUFFIX") isEmpty(flex) { @@ -319,3 +371,160 @@ defineTest(qtConfTest_hasGcc6OrNewer) { greaterThan(QMAKE_GCC_MAJOR_VERSION, 5):return(true) return(false) } + +defineTest(qtConfTest_detectSubmodule) { + isEmpty(QTWEBENGINE_ROOT) { + # topLevel build , add poor man's workaround + QTWEBENGINE_ROOT=$$PWD/../../../qtwebengine + } + !exists($$QTWEBENGINE_ROOT/src/3rdparty/chromium):return(false) + return(true) +} + +defineTest(qtConfTest_detectNoWhitespace) { + WSPC = $$find(OUT_PWD, \\s) + !isEmpty(WSPC):return(false) + return(true) +} + +defineTest(qtwebengine_confCheckError) { + QT_FOR_CONFIG += buildtools-private gui-private + return($$qtwebengine_checkError()) +} + +defineTest(qtwebengine_isLinuxPlatformSupported) { + !gcc|intel_icc { + qtwebengine_platformError("Qt WebEngine on Linux requires clang or GCC.") + return(false) + } + gcc:!clang:!qtwebengine_isGCCVersionSupported(): return(false) + gcc:!qtConfig(c++14) { + qtwebengine_platformError("C++14 support is required in order to build chromium.") + return(false) + } + return(true) +} + +defineTest(qtwebengine_isWindowsPlatformSupported) { + winrt { + qtwebengine_platformError("WinRT is not supported.") + return(false) + } + qtwebengine_isBuildingOnWin32() { + qtwebengine_platformError("Qt WebEngine on Windows must be built on a 64-bit machine.") + return(false) + } + !msvc|intel_icl { + qtwebengine_platformError("Qt WebEngine on Windows requires MSVC or Clang (MSVC mode).") + return(false) + } + !qtwebengine_isMinWinSDKVersion(10, 18362): { + qtwebengine_platformError("Qt WebEngine on Windows requires a Windows SDK version 10.0.18362 or newer.") + return(false) + } + return(true) +} + +defineTest(qtwebengine_isMacOsPlatformSupported) { + # FIXME: Try to get it back down to 8.2 for building on OS X 10.11 + !qtwebengine_isMinXcodeVersion(8, 3, 3) { + qtwebengine_platformError("Using Xcode version $$QMAKE_XCODE_VERSION, but at least version 8.3.3 is required to build Qt WebEngine.") + return(false) + } + !clang|intel_icc { + qtwebengine_platformError("Qt WebEngine on macOS requires Clang.") + return(false) + } + # We require macOS 10.12 (darwin version 16.0.0) or newer. + darwin_major_version = $$section(QMAKE_HOST.version, ., 0, 0) + lessThan(darwin_major_version, 16) { + qtwebengine_platformError("Building Qt WebEngine requires macOS version 10.12 or newer.") + return(false) + } + !qtwebengine_isMinOSXSDKVersion(10, 12): { + qtwebengine_platformError("Building Qt WebEngine requires a macOS SDK version of 10.12 or newer. Current version is $${WEBENGINE_OSX_SDK_PRODUCT_VERSION}.") + return(false) + } + return(true) +} + +defineTest(qtwebengine_isGCCVersionSupported) { + # Keep in sync with src/webengine/doc/src/qtwebengine-platform-notes.qdoc + greaterThan(QMAKE_GCC_MAJOR_VERSION, 4):return(true) + + qtwebengine_platformError("Using gcc version "$$QMAKE_GCC_MAJOR_VERSION"."$$QMAKE_GCC_MINOR_VERSION", but at least gcc version 5 is required to build Qt WebEngine.") + return(false) +} + +defineTest(qtwebengine_isBuildingOnWin32) { + # The check below is ugly, but necessary, as it seems to be the only reliable way to detect if the host + # architecture is 32 bit. QMAKE_HOST.arch does not work as it returns the architecture that the toolchain + # is building for, not the system's actual architecture. + PROGRAM_FILES_X86 = $$(ProgramW6432) + isEmpty(PROGRAM_FILES_X86): return(true) + return(false) +} + +defineTest(qtwebengine_isMinOSXSDKVersion) { + requested_major = $$1 + requested_minor = $$2 + requested_patch = $$3 + isEmpty(requested_patch): requested_patch = 0 + WEBENGINE_OSX_SDK_PRODUCT_VERSION = $$system("/usr/bin/xcodebuild -sdk $$QMAKE_MAC_SDK -version ProductVersion 2>/dev/null") + export(WEBENGINE_OSX_SDK_PRODUCT_VERSION) + isEmpty(WEBENGINE_OSX_SDK_PRODUCT_VERSION) { + qtwebengine_platformError("Could not resolve SDK product version for \'$$QMAKE_MAC_SDK\'.") + return(false) + } + major_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 0, 0) + minor_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 1, 1) + patch_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 2, 2) + isEmpty(patch_version): patch_version = 0 + + greaterThan(major_version, $$requested_major):return(true) + equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) + equals(major_version, $$requested_major):equals(minor_version, $$requested_minor):!lessThan(patch_version, $$requested_patch):return(true) + + return(false) +} + +defineTest(qtwebengine_isMinXcodeVersion) { + requested_major = $$1 + requested_minor = $$2 + requested_patch = $$3 + isEmpty(requested_minor): requested_minor = 0 + isEmpty(requested_patch): requested_patch = 0 + target_var = QMAKE_XCODE_VERSION + major_version = $$section($$target_var, ., 0, 0) + minor_version = $$section($$target_var, ., 1, 1) + patch_version = $$section($$target_var, ., 2, 2) + isEmpty(minor_version): minor_version = 0 + isEmpty(patch_version): patch_version = 0 + + greaterThan(major_version, $$requested_major):return(true) + equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) + equals(major_version, $$requested_major):equals(minor_version, $$requested_minor):!lessThan(patch_version, $$requested_patch):return(true) + + return(false) +} + +defineTest(qtwebengine_isMinWinSDKVersion) { + requested_major = $$1 + requested_minor = $$2 + WIN_SDK_VERSION = $$(WindowsSDKVersion) + + isEmpty(WIN_SDK_VERSION)|equals(WIN_SDK_VERSION, "\\") { + qtwebengine_platformError("Could not detect Windows SDK version (\'WindowsSDKVersion\' environment variable is not set).") + return(false) + } + + # major.0.minor + major_version = $$section(WIN_SDK_VERSION, ., 0, 0) + minor_version = $$section(WIN_SDK_VERSION, ., 2, 2) + + greaterThan(major_version, $$requested_major):return(true) + equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) + equals(major_version, $$requested_major):equals(minor_version, $$requested_minor)::return(true) + + return(false) +} diff --git a/dist/changes-5.12.5 b/dist/changes-5.12.5 new file mode 100644 index 000000000..15f0bcde6 --- /dev/null +++ b/dist/changes-5.12.5 @@ -0,0 +1,80 @@ +Qt 5.12.5 is a bug-fix release. It maintains both forward and backward +compatibility (source and binary) with Qt 5.12.0 through 5.12.4. + +For more details, refer to the online documentation included in this +distribution. The documentation is also available online: + +https://doc.qt.io/qt-5/index.html + +The Qt version 5.12 series is binary compatible with the 5.11.x series. +Applications compiled for 5.11 will continue to run with 5.12. + +Some of the changes listed in this file include issue tracking numbers +corresponding to tasks in the Qt Bug Tracker: + +https://bugreports.qt.io/ + +Each of these identifiers can be entered in the bug tracker to obtain more +information about a particular change. + +**************************************************************************** +* Qt 5.12.5 Changes * +**************************************************************************** + +General +------- + + - [QTBUG-62106] Fixed possible crash after rapid tapping. + - [QTBUG-75884] Fixed crash on setHttpUserAgent. + - [QTBUG-76249] Fixed user-agent on some new windows. + - [QTBUG-76268] Fixed tab key send on minimize. + - [QTBUG-76347] Fixed duplicate events being send from tablets. + - [QTBUG-76828] Clear shared context on exit. + - [QTBUG-76958] Fixed possible crash when loading in background. + +Chromium +-------- + + - Security fixes from Chromium up to version 76.0.3809.87, including: + + - CVE-2019-5829 + - CVE-2019-5831 + - CVE-2019-5832 + - CVE-2019-5837 + - CVE-2019-5839 + - CVE-2019-5842 + - CVE-2019-5851 + - CVE-2019-5852 + - CVE-2019-5854 + - CVE-2019-5855 + - CVE-2019-5856 + - CVE-2019-5857 + - CVE-2019-5860 + - CVE-2019-5861 + - CVE-2019-5862 + - CVE-2019-5865 + - Critical security issue 977057 + - Security bug 934161 + - Security bug 939644 + - Security bug 948172 + - Security bug 948228 + - Security bug 948944 + - Security bug 950005 + - Security bug 952849 + - Security bug 956625 + - Security bug 958457 + - Security bug 958689 + - Security bug 959193 + - Security bug 959518 + - Security bug 958717 + - Security bug 960785 + - Security bug 961674 + - Security bug 961597 + - Security bug 962083 + - Security bug 964002 + - Security bug 973893 + - Security bug 974627 + - Security bug 976050 + - Security bug 981602 + - Security bug 983850 + - Security bug 983938 diff --git a/dist/changes-5.13.1 b/dist/changes-5.13.1 new file mode 100644 index 000000000..9e3a49558 --- /dev/null +++ b/dist/changes-5.13.1 @@ -0,0 +1,91 @@ +Qt 5.13.1 is a bug-fix release. It maintains both forward and backward +compatibility (source and binary) with Qt 5.13.0. + +For more details, refer to the online documentation included in this +distribution. The documentation is also available online: + +https://doc.qt.io/qt-5/index.html + +The Qt version 5.13 series is binary compatible with the 5.12.x series. +Applications compiled for 5.12 will continue to run with 5.13. + +Some of the changes listed in this file include issue tracking numbers +corresponding to tasks in the Qt Bug Tracker: + +https://bugreports.qt.io/ + +Each of these identifiers can be entered in the bug tracker to obtain more +information about a particular change. + +**************************************************************************** +* Qt 5.13.1 Changes * +**************************************************************************** + +General +------- + + - [QTBUG-62106] Fixed possible crash after rapid tapping. + - [QTBUG-76226] Fixed PDF viewer on URLs with percent-encoded characters. + - [QTBUG-76249] Fixed user-agent on some new windows. + - [QTBUG-76958] Fixed possible crash when loading in background. + + +Chromium +-------- + + - Security fixes from Chromium up to version 76.0.3809.87, including: + + - CVE-2019-5829 + - CVE-2019-5831 + - CVE-2019-5832 + - CVE-2019-5836 + - CVE-2019-5837 + - CVE-2019-5839 + - CVE-2019-5842 + - CVE-2019-5851 + - CVE-2019-5852 + - CVE-2019-5854 + - CVE-2019-5855 + - CVE-2019-5856 + - CVE-2019-5857 + - CVE-2019-5860 + - CVE-2019-5861 + - CVE-2019-5862 + - CVE-2019-5865 + - Critical security issue 977057 + - Security issue 934161 + - Security issue 939644 + - Security issue 948172 + - Security issue 948228 + - Security issue 948944 + - Security issue 950005 + - Security issue 952849 + - Security issue 954762 + - Security issue 956625 + - Security issue 958717 + - Security issue 958457 + - Security issue 958689 + - Security issue 959192 + - Security issue 959193 + - Security issue 959518 + - Security issue 960785 + - Security issue 961597 + - Security issue 961674 + - Security issue 962083 + - Security issue 962572 + - Security issue 964002 + - Security issue 964795 + - Security issue 964928 + - Security issue 973893 + - Security issue 974627 + - Security issue 976050 + - Security issue 981602 + - Security issue 983850 + - Security issue 983938 + + +Qt WebEngine Core +----------------- + + - [QTBUG-60203] QWebEngineUrlRequestInterceptor can now set referer header. + diff --git a/examples/webengine/customdialogs/WebView.qml b/examples/webengine/customdialogs/WebView.qml index 0715bc709..d754ea7dc 100644 --- a/examples/webengine/customdialogs/WebView.qml +++ b/examples/webengine/customdialogs/WebView.qml @@ -49,7 +49,7 @@ ****************************************************************************/ import QtQuick 2.0 -import QtWebEngine 1.4 +import QtWebEngine 1.10 WebEngineView { @@ -57,6 +57,32 @@ WebEngineView { property bool useDefaultDialogs: true signal openForm(var form) + Rectangle { + id: tooltip + width: 200 + height: 30 + z: 50 + visible: false + color: "gray" + border.color: "black" + border.width: 2 + radius: 3 + + property string text: "" + + Text { + x: 0 + y: 0 + color: "#ffffff" + text: parent.text + font.pointSize: 12 + anchors.horizontalCenter: parent.horizontalCenter + anchors.verticalCenter: parent.verticalCenter + font.bold: false + } + + } + onContextMenuRequested: function(request) { // we only show menu for links with #openMenu if (!request.linkUrl.toString().endsWith("#openMenu")) { @@ -72,6 +98,22 @@ WebEngineView { properties: {"request": request}}); } + onTooltipRequested: function(request) { + if (useDefaultDialogs) + return; + + if (request.type == TooltipRequest.Show) { + tooltip.visible = true; + tooltip.x = request.x; + tooltip.y = request.y; + tooltip.text = request.text; + } else { + tooltip.visible = false; + } + + request.accepted = true; + } + onAuthenticationDialogRequested: function(request) { if (useDefaultDialogs) return; diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-auth1.png b/examples/webengine/customdialogs/doc/images/customdialogs-auth1.png Binary files differindex 2bde8bd8e..5e8f8d6bd 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-auth1.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-auth1.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-auth2.png b/examples/webengine/customdialogs/doc/images/customdialogs-auth2.png Binary files differindex ce358fca0..41828d36d 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-auth2.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-auth2.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-color1.png b/examples/webengine/customdialogs/doc/images/customdialogs-color1.png Binary files differindex a51d1bdd3..9208045b2 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-color1.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-color1.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-color2.png b/examples/webengine/customdialogs/doc/images/customdialogs-color2.png Binary files differindex 3b0b2e986..9087fdf14 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-color2.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-color2.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-file1.png b/examples/webengine/customdialogs/doc/images/customdialogs-file1.png Binary files differindex 0ff39bf38..ba8bdf78c 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-file1.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-file1.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-file2.png b/examples/webengine/customdialogs/doc/images/customdialogs-file2.png Binary files differindex e56078c44..aa25579d7 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-file2.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-file2.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-prompt1.png b/examples/webengine/customdialogs/doc/images/customdialogs-prompt1.png Binary files differindex 988b4deea..e36ba4a13 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-prompt1.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-prompt1.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-prompt2.png b/examples/webengine/customdialogs/doc/images/customdialogs-prompt2.png Binary files differindex 085339378..2c8d92649 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs-prompt2.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs-prompt2.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs-tooltip.png b/examples/webengine/customdialogs/doc/images/customdialogs-tooltip.png Binary files differnew file mode 100644 index 000000000..498de9595 --- /dev/null +++ b/examples/webengine/customdialogs/doc/images/customdialogs-tooltip.png diff --git a/examples/webengine/customdialogs/doc/images/customdialogs.png b/examples/webengine/customdialogs/doc/images/customdialogs.png Binary files differindex 13322d2f6..c42114a16 100644 --- a/examples/webengine/customdialogs/doc/images/customdialogs.png +++ b/examples/webengine/customdialogs/doc/images/customdialogs.png diff --git a/examples/webengine/customdialogs/doc/src/customdialogs.qdoc b/examples/webengine/customdialogs/doc/src/customdialogs.qdoc index 5c550ed5e..6319ce53b 100644 --- a/examples/webengine/customdialogs/doc/src/customdialogs.qdoc +++ b/examples/webengine/customdialogs/doc/src/customdialogs.qdoc @@ -140,6 +140,38 @@ To keep things simple, we do not provide any logic on component completion, and we simply close the form on any action. + \section2 Tooltip Requests + + \l [QML]{TooltipRequest} is a request object that is passed as a + parameter of the WebEngineView::tooltipRequested signal. We use the + \c onTooltipRequested signal handler to handle requests for + custom tooltip menus at specific positions: + + \quotefromfile webengine/customdialogs/WebView.qml + \skipto WebEngineView + \printuntil { + \dots 4 + \skipto onTooltipRequested + \printuntil } + \printuntil } + \printuntil } + \dots 4 + \skipuntil onFileDialogRequested + \skipuntil }}); + \skipuntil } + \skipto } + \printline } + + The second text field from the top on our page triggers the request. Next, + we check whether we should use the default menu. If not, we accept the + request and show a custom QML element as tooltip: + + \image customdialogs-tooltip.png + + \quotefromfile webengine/customdialogs/WebView.qml + \skipto Rectangle + \printuntil } + \section2 Authentication Dialog Requests \image customdialogs-auth1.png diff --git a/examples/webengine/customdialogs/index.html b/examples/webengine/customdialogs/index.html index 490dd79fd..69c0e6b21 100644 --- a/examples/webengine/customdialogs/index.html +++ b/examples/webengine/customdialogs/index.html @@ -11,6 +11,9 @@ <td><div class="div"><a href="#openMenu" class="link">Right click on text to see link context menu</a></div></td> </tr> <tr> + <td><div class="div"><p title="I am a tooltip.">Hover this text to display a tooltip</a></div></td> + </tr> + <tr> <td><button class="button" onclick="window.location = 'http://localhost.:5555/OPEN_AUTH'"> Open Authentication Dialog</button></td> </tr> diff --git a/examples/webengine/lifecycle/doc/src/lifecycle.qdoc b/examples/webengine/lifecycle/doc/src/lifecycle.qdoc index 4151d0597..d10e617e3 100644 --- a/examples/webengine/lifecycle/doc/src/lifecycle.qdoc +++ b/examples/webengine/lifecycle/doc/src/lifecycle.qdoc @@ -38,6 +38,8 @@ properties of the \l {WebEngineView} can be used to reduce the CPU and memory usage of background tabs in a tabbed browser. + For an overview of the lifecycle feature, see \l {Page Lifecycle API}. + \include examples-run.qdocinc \section1 UI Elements of the Example @@ -53,71 +55,6 @@ window also has a \l {Drawer} for changing settings. The drawer can be opened by clicking the "⋮" button on the tool bar. - \section1 Overview of Lifecycle States - - Each \l {WebEngineView} item can be in one of three \e {lifecycle states}: - active, frozen, or discarded. These states, like the sleep states of a CPU, - control the resource usage of web views. - - The \e {active} state is the normal, unrestricted state of a web view. All - visible web views are always in the active state, as are all web views that - have not yet finished loading. Only invisible, idle web views can be - transitioned to other lifecycle states. - - The \e {frozen} state is a low CPU usage state. In this state, most HTML - task sources are suspended (frozen) and, as a result, most DOM event - processing and JavaScript execution will also be suspended. The web view - must be invisible in order to be frozen as rendering is not possible in this - state. - - The \e {discarded} state is an extreme resource-saving state. In this state, - the browsing context of the web view will be discarded and the corresponding - renderer subprocess shut down. CPU and memory usage in this state is reduced - virtually to zero. On exiting this state the web page will be automatically - reloaded. The process of entering and exiting the discarded state is similar - to serializing the browsing history of the web view and destroying the view, - then creating a new view and restoring its history. - - See also \l {WebEngineView::LifecycleState}. The equivalent in the Widgets - API is \l {QWebEnginePage::LifecycleState}. - - \section2 The \c {lifecycleState} and \c {recommendedState} Properties - - The \l {WebEngineView::}{lifecycleState} property of the \l {WebEngineView} - type is a read-write property that controls the current lifecycle state of - the web view. This property is designed to place as few restrictions as - possible on what states can be transitioned to. For example, it is allowed - to freeze a web view that is currently playing music in the background, - stopping the music. In order to implement a less aggressive resource-saving - strategy that avoids interrupting user-visible background activity, the \l - {WebEngineView::} {recommendedState} property must be used. - - The \l {WebEngineView::}{recommendedState} property of the \l - {WebEngineView} type is a read-only property that calculates a safe limit on - the \l {WebEngineView::}{lifecycleState} property, taking into account the - current activity of the web view. So, in the example of a web view playing - music in the background, the recommended state will be \c {Active} since a - more aggressive state would stop the music. If the application wants to - avoid interrupting background activity, then it should avoid putting the web - view into a more aggressively resource-saving lifecycle state than what's - given by \l {WebEngineView::}{recommendedState}. - - See also \l {WebEngineView::lifecycleState} and \l - {WebEngineView::recommendedState}. The equivalents in the Widgets API are \l - {QWebEnginePage::lifecycleState} and \l {QWebEnginePage::recommendedState}. - - \section2 The Page Lifecycle API - - The \l {WebEngineView::}{lifecycleState} property is connected to the \l - {https://wicg.github.io/page-lifecycle/spec.html}{Page Lifecycle API}, a - work-in-progress extension to the HTML standard that specifies two new DOM - events, \c {freeze} and \c {resume}, and adds a new \c - {Document.wasDiscarded} boolean property. The \c {freeze} and \c {resume} - events are fired when transitioning from the \c {Active} to the \c {Frozen - state}, and vice-versa. The \c {Document.wasDiscarded} property is set to \c - {true} when transition from the \c {Discarded} state to the \c {Active} - state. - \section1 Lifecycle States in the Example The example implements two ways of changing the lifecycle state: manual and diff --git a/examples/webenginewidgets/notifications/doc/src/notifications.qdoc b/examples/webenginewidgets/notifications/doc/src/notifications.qdoc index 2c999e7e1..ec932f90c 100644 --- a/examples/webenginewidgets/notifications/doc/src/notifications.qdoc +++ b/examples/webenginewidgets/notifications/doc/src/notifications.qdoc @@ -44,22 +44,22 @@ In this example, we create an internal HTML page that is added through a resource collection file (.qrc). The page displays buttons for requesting - permissions and creating a notification. In addition, it contains JavaScript - logic for triggering these actions. + permissions and contains necessary JavaScript code to trigger this request: \quotefromfile webenginewidgets/notifications/data/index.html \skipto Notification.requestPermission \printline requestPermission - \dots - \skipto if - \printuntil createNotification() - \printline /^})$/ + \skipuntil resetPermission + \printuntil /\}\)$/ + + Also page contains a button for creating a notification. The following + JavaScript constructions are executed on the press event: \quotefromfile webenginewidgets/notifications/data/index.html \skipto createNotification() - \printuntil Notification - \dots - \printline /^})$/ + \printuntil new Notification + \skipuntil Notification was created + \printline } \section1 Main Function @@ -127,7 +127,8 @@ \skipto QWebEngineNotification::closed \printuntil QTimer - \printline /^\}/ + \skipto /\}/ + \printline /\}/ \section2 Closing Active Notification @@ -138,9 +139,7 @@ destroy the notification object through the \c std::unique_ptr::reset() method. \skipto onClosed - \dots - \skipto hide() - \printuntil reset + \printuntil } \section2 Implementing User Interaction @@ -152,5 +151,6 @@ \skipto mouseReleaseEvent \printuntil onClosed - \printuntil /^\}/ + \printline /\}$/ + \printline /\}$/ */ diff --git a/examples/webenginewidgets/notifications/main.cpp b/examples/webenginewidgets/notifications/main.cpp index 661b82ff5..c3039b9e0 100644 --- a/examples/webenginewidgets/notifications/main.cpp +++ b/examples/webenginewidgets/notifications/main.cpp @@ -56,11 +56,13 @@ #include <QWebEngineProfile> #include <QWebEngineView> -class WebEnginePage : public QWebEnginePage { +class WebEnginePage : public QWebEnginePage +{ public: WebEnginePage(QWidget *parent) : QWebEnginePage(parent) { } - bool acceptNavigationRequest(const QUrl &url, NavigationType, bool) override { + bool acceptNavigationRequest(const QUrl &url, NavigationType, bool) override + { if (url.scheme() != "https") return true; QDesktopServices::openUrl(url); @@ -81,16 +83,15 @@ int main(int argc, char *argv[]) QObject::connect(view.page(), &QWebEnginePage::featurePermissionRequested, [&] (const QUrl &origin, QWebEnginePage::Feature feature) { - if (feature != QWebEnginePage::Notifications) - return; - view.page()->setFeaturePermission(origin, feature, QWebEnginePage::PermissionGrantedByUser); - }); + if (feature != QWebEnginePage::Notifications) + return; + view.page()->setFeaturePermission(origin, feature, QWebEnginePage::PermissionGrantedByUser); + }); auto profile = view.page()->profile(); auto popup = new NotificationPopup(&view); - profile->setNotificationPresenter([&] (std::unique_ptr<QWebEngineNotification> notification) { - popup->present(notification); - }); + profile->setNotificationPresenter([&] (std::unique_ptr<QWebEngineNotification> notification) + { popup->present(notification); }); view.resize(640, 480); view.show(); diff --git a/examples/webenginewidgets/notifications/notificationpopup.h b/examples/webenginewidgets/notifications/notificationpopup.h index fcbb003b9..d211c7996 100644 --- a/examples/webenginewidgets/notifications/notificationpopup.h +++ b/examples/webenginewidgets/notifications/notificationpopup.h @@ -61,14 +61,16 @@ #include <memory> -class NotificationPopup : public QWidget { +class NotificationPopup : public QWidget +{ Q_OBJECT QLabel m_icon, m_title, m_message; std::unique_ptr<QWebEngineNotification> notification; public: - NotificationPopup(QWidget *parent) : QWidget(parent) { + NotificationPopup(QWidget *parent) : QWidget(parent) + { setWindowFlags(Qt::ToolTip); auto rootLayout = new QHBoxLayout(this); @@ -91,7 +93,8 @@ public: adjustSize(); } - void present(std::unique_ptr<QWebEngineNotification> &newNotification) { + void present(std::unique_ptr<QWebEngineNotification> &newNotification) + { if (notification) { notification->close(); notification.reset(); @@ -114,14 +117,16 @@ public: } protected slots: - void onClosed() { + void onClosed() + { hide(); notification->close(); notification.reset(); } protected: - void mouseReleaseEvent(QMouseEvent *event) override { + void mouseReleaseEvent(QMouseEvent *event) override + { QWidget::mouseReleaseEvent(event); if (notification && event->button() == Qt::LeftButton) { notification->click(); diff --git a/mkspecs/features/functions.prf b/mkspecs/features/functions.prf index a301929dc..512e2523b 100644 --- a/mkspecs/features/functions.prf +++ b/mkspecs/features/functions.prf @@ -1,3 +1,5 @@ +include($$QTWEBENGINE_ROOT/src/buildtools/config/support.pri) + defineReplace(getConfigDir) { CONFIG(release, debug|release):return("release") return("debug") @@ -96,103 +98,6 @@ defineReplace(gnOS) { return(unknown) } -defineTest(skipBuild) { - isEmpty(skipBuildReason): skipBuildReason = $$1 - else: skipBuildReason = "$$skipBuildReason $${EOL}$$1" - export(skipBuildReason) -} - -defineTest(isWebEngineCoreBuild) { - !qtHaveModule(gui) { - skipBuild("QtWebEngine requires QtGui.") - return(false) - } - - !exists($$QTWEBENGINE_ROOT/src/3rdparty/chromium) { - skipBuild("Submodule qtwebengine-chromium does not exist. Run 'git submodule update --init'.") - return(false) - } - - WSPC = $$find(OUT_PWD, \\s) - !isEmpty(WSPC) { - skipBuild("QtWebEngine cannot be built in a path that contains whitespace characters.") - return(false) - } - - !isPlatformSupported() { - # make sure we have skipBuildReason - isEmpty(skipBuildReason): skipBuild("Unknow error. Platform unspported") - return(false) - } - - linux:contains(QT_CONFIG,no-pkg-config) { - skipBuild("pkg-config is required") - return(false) - } - - include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri) - QT_FOR_CONFIG += buildtools-private - - win32:!qtConfig(webengine-win-compiler64) { - skipBuild("Required 64-bit cross-building or native toolchain could not be found.") - return(false) - } - - !qtConfig(webengine-gperf) { - skipBuild("Required gperf could not be found.") - return(false) - } - !qtConfig(webengine-bison) { - skipBuild("Required bison could not be found.") - return(false) - } - !qtConfig(webengine-flex) { - skipBuild("Required flex could not be found.") - return(false) - } - !qtConfig(webengine-python2) { - skipBuild("A suitable version of python2 could not be found.") - return(false) - } - - sanitizer: !qtConfig(webengine-sanitizer) { - skipBuild("Chosen sanitizer configuration is not supported. Check config.log for details or use -feature-webengine-sanitizer to force build with the chosen sanitizer configuration.") - return(false); - } - - linux { - - !qtConfig(webengine-host-pkg-config) { - skipBuild("Host pkg-config is required") - return(false) - } - - !qtConfig(webengine-system-glibc) { - skipBuild("A suitable version >= 2.27 of libc could not be found.") - return(false) - } - - QT_FOR_CONFIG += gui-private - - !qtConfig(webengine-system-khr) { - skipBuild("khronos development headers appear to be missing (mesa/libegl1-mesa-dev)") - return(false) - } - - for(package, $$list("nss dbus fontconfig")) { - !qtConfig(webengine-system-$$package) { - skipBuild("A suitable version of $$package could not be found.") - return(false) - } - } - - qtConfig(xcb) : !qtConfig(webengine-ozone-x11) { - skipBuild("Could not find all necessary libraries for qpa-xcb support") - return(false) - } - } -} - defineReplace(pkgConfigHostExecutable) { wrapper_name = $$OUT_PWD/pkg-config-host_wrapper.sh wrapper_cmd = $$QMAKE_PKG_CONFIG_HOST diff --git a/mkspecs/features/platform.prf b/mkspecs/features/platform.prf deleted file mode 100644 index 97cf96a78..000000000 --- a/mkspecs/features/platform.prf +++ /dev/null @@ -1,168 +0,0 @@ -include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri) -QT_FOR_CONFIG += buildtools-private - -defineTest(isQtMinimum) { - !equals(QT_MAJOR_VERSION, $$1): return(false) - count(ARGS, 1, greaterThan) { - lessThan(QT_MINOR_VERSION, $$2): return(false) - } - return(true) -} - -defineTest(isPlatformSupported) { - QT_FOR_CONFIG += gui-private - linux { - if(!gcc:!clang)|intel_icc { - skipBuild("Qt WebEngine on Linux requires clang or GCC.") - return(false) - } - gcc:!clang:!isGCCVersionSupported(): return(false) - } else:win32 { - winrt { - skipBuild("WinRT is not supported.") - return(false) - } - isBuildingOnWin32() { - skipBuild("Qt WebEngine on Windows must be built on a 64-bit machine.") - return(false) - } - !msvc|intel_icl { - skipBuild("Qt WebEngine on Windows requires MSVC or Clang (MSVC mode).") - return(false) - } - !isMinWinSDKVersion(10, 17763): { - skipBuild("Qt WebEngine on Windows requires a Windows SDK version 10.0.17763 or newer.") - return(false) - } - !qtConfig(webengine-winversion) { - skipBuild("Needs Visual Studio 2017 or higher") - return(false) - } - } else:osx { - # FIXME: Try to get it back down to 8.2 for building on OS X 10.11 - !isMinXcodeVersion(8, 3, 3) { - skipBuild("Using Xcode version $$QMAKE_XCODE_VERSION, but at least version 8.3.3 is required to build Qt WebEngine.") - return(false) - } - !clang|intel_icc { - skipBuild("Qt WebEngine on macOS requires Clang.") - return(false) - } - # We require macOS 10.12 (darwin version 16.0.0) or newer. - darwin_major_version = $$section(QMAKE_HOST.version, ., 0, 0) - lessThan(darwin_major_version, 16) { - skipBuild("Building Qt WebEngine requires macOS version 10.12 or newer.") - return(false) - } - !isMinOSXSDKVersion(10, 12): { - skipBuild("Building Qt WebEngine requires a macOS SDK version of 10.12 or newer. Current version is $${WEBENGINE_OSX_SDK_PRODUCT_VERSION}.") - return(false) - } - } else { - skipBuild("Unknown platform. Qt WebEngine only supports Linux, Windows, and macOS.") - return(false) - } - - # QMAKE doesn't set c++14 for MSVC2017, so only test for gcc and clang (which pretends to be gcc) - gcc:!contains(QT_CONFIG, c++14) { - skipBuild("C++14 support is required in order to build chromium.") - return(false) - } - static { - skipBuild("Static builds of QtWebEngine aren't supported.") - return(false) - } - !isArchSupported(): return(false) - return(true) -} - -defineTest(isArchSupported) { - contains(QT_ARCH, "i386")|contains(QT_ARCH, "x86_64"): return(true) - contains(QT_ARCH, "arm")|contains(QT_ARCH, "arm64"): return(true) - contains(QT_ARCH, "mips"): return(true) -# contains(QT_ARCH, "mips64"): return(true) - - skipBuild("QtWebEngine can only be built for x86, x86-64, ARM, Aarch64, and MIPSel architectures.") - return(false) -} - -defineTest(isGCCVersionSupported) { - # Keep in sync with src/webengine/doc/src/qtwebengine-platform-notes.qdoc - greaterThan(QT_GCC_MAJOR_VERSION, 4):return(true) - - skipBuild("Using gcc version "$$QT_GCC_MAJOR_VERSION"."$$QT_GCC_MINOR_VERSION", but at least gcc version 5 is required to build Qt WebEngine.") - return(false) -} - -defineTest(isBuildingOnWin32) { - # The check below is ugly, but necessary, as it seems to be the only reliable way to detect if the host - # architecture is 32 bit. QMAKE_HOST.arch does not work as it returns the architecture that the toolchain - # is building for, not the system's actual architecture. - PROGRAM_FILES_X86 = $$(ProgramW6432) - isEmpty(PROGRAM_FILES_X86): return(true) - return(false) -} - -defineTest(isMinOSXSDKVersion) { - requested_major = $$1 - requested_minor = $$2 - requested_patch = $$3 - isEmpty(requested_patch): requested_patch = 0 - WEBENGINE_OSX_SDK_PRODUCT_VERSION = $$system("/usr/bin/xcodebuild -sdk $$QMAKE_MAC_SDK -version ProductVersion 2>/dev/null") - export(WEBENGINE_OSX_SDK_PRODUCT_VERSION) - isEmpty(WEBENGINE_OSX_SDK_PRODUCT_VERSION) { - skipBuild("Could not resolve SDK product version for \'$$QMAKE_MAC_SDK\'.") - return(false) - } - major_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 0, 0) - minor_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 1, 1) - patch_version = $$section(WEBENGINE_OSX_SDK_PRODUCT_VERSION, ., 2, 2) - isEmpty(patch_version): patch_version = 0 - - greaterThan(major_version, $$requested_major):return(true) - equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) - equals(major_version, $$requested_major):equals(minor_version, $$requested_minor):!lessThan(patch_version, $$requested_patch):return(true) - - return(false) -} - -defineTest(isMinXcodeVersion) { - requested_major = $$1 - requested_minor = $$2 - requested_patch = $$3 - isEmpty(requested_minor): requested_minor = 0 - isEmpty(requested_patch): requested_patch = 0 - target_var = QMAKE_XCODE_VERSION - major_version = $$section($$target_var, ., 0, 0) - minor_version = $$section($$target_var, ., 1, 1) - patch_version = $$section($$target_var, ., 2, 2) - isEmpty(minor_version): minor_version = 0 - isEmpty(patch_version): patch_version = 0 - - greaterThan(major_version, $$requested_major):return(true) - equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) - equals(major_version, $$requested_major):equals(minor_version, $$requested_minor):!lessThan(patch_version, $$requested_patch):return(true) - - return(false) -} - -defineTest(isMinWinSDKVersion) { - requested_major = $$1 - requested_minor = $$2 - WIN_SDK_VERSION = $$(WindowsSDKVersion) - - isEmpty(WIN_SDK_VERSION)|equals(WIN_SDK_VERSION, "\\") { - skipBuild("Could not detect Windows SDK version (\'WindowsSDKVersion\' environment variable is not set).") - return(false) - } - - # major.0.minor - major_version = $$section(WIN_SDK_VERSION, ., 0, 0) - minor_version = $$section(WIN_SDK_VERSION, ., 2, 2) - - greaterThan(major_version, $$requested_major):return(true) - equals(major_version, $$requested_major):greaterThan(minor_version, $$requested_minor):return(true) - equals(major_version, $$requested_major):equals(minor_version, $$requested_minor)::return(true) - - return(false) -} diff --git a/qtwebengine.pro b/qtwebengine.pro index 6d4089b26..fc303a453 100644 --- a/qtwebengine.pro +++ b/qtwebengine.pro @@ -1,6 +1,5 @@ load(qt_parts) load(functions) -load(platform) QMAKE_DISTCLEAN += .qmake.cache @@ -13,7 +12,3 @@ OTHER_FILES = \ config.tests/snappy/* \ config.tests/re2/* \ mkspecs/features/* - -!isWebEngineCoreBuild():!isEmpty(skipBuildReason):!build_pass { - log(QtWebEngine will not be built. $${skipBuildReason} $${EOL}) -} diff --git a/src/3rdparty b/src/3rdparty -Subproject feccbb4ea7fa685dcd013f5a3f6c14ea768636c +Subproject dc5221146d665f5634fab11fb4c9b5515c1ab07 diff --git a/src/buildtools/config/common.pri b/src/buildtools/config/common.pri index 1a54f1559..23a134774 100644 --- a/src/buildtools/config/common.pri +++ b/src/buildtools/config/common.pri @@ -9,7 +9,6 @@ gn_args += \ is_component_build=false \ is_shared=true \ enable_message_center=false \ - enable_mus=false \ enable_nacl=false \ enable_remoting=false \ enable_reporting=false \ @@ -27,7 +26,8 @@ gn_args += \ toolkit_views=false \ treat_warnings_as_errors=false \ safe_browsing_mode=0 \ - optimize_webui=false + optimize_webui=false \ + forbid_non_component_debug_builds=false greaterThan(QMAKE_JUMBO_MERGE_LIMIT,0) { gn_args += \ diff --git a/src/buildtools/config/linux.pri b/src/buildtools/config/linux.pri index 998aedc40..493ea9766 100644 --- a/src/buildtools/config/linux.pri +++ b/src/buildtools/config/linux.pri @@ -164,9 +164,21 @@ host_build { gn_args += use_system_libpng=true qtConfig(webengine-printing-and-pdf): gn_args += pdfium_use_system_libpng=true } - qtConfig(webengine-system-jpeg): gn_args += use_system_libjpeg=true - qtConfig(webengine-system-freetype): gn_args += use_system_freetype=true - qtConfig(webengine-system-harfbuzz): gn_args += use_system_harfbuzz=true + qtConfig(webengine-system-jpeg) { + gn_args += use_system_libjpeg=true + } else { + gn_args += use_system_libjpeg=false + } + qtConfig(webengine-system-freetype) { + gn_args += use_system_freetype=true + } else { + gn_args += use_system_freetype=false + } + qtConfig(webengine-system-harfbuzz) { + gn_args += use_system_harfbuzz=true + } else { + gn_args += use_system_harfbuzz=false + } !qtConfig(webengine-system-glib): gn_args += use_glib=false qtConfig(webengine-pulseaudio) { gn_args += use_pulseaudio=true diff --git a/src/buildtools/config/support.pri b/src/buildtools/config/support.pri new file mode 100644 index 000000000..5bdd808d4 --- /dev/null +++ b/src/buildtools/config/support.pri @@ -0,0 +1,133 @@ +defineTest(qtwebengine_skipBuild) { + isEmpty(skipBuildReason): skipBuildReason = $$1 + else: skipBuildReason = "$$skipBuildReason $${EOL}$$1" + export(skipBuildReason) +} + +defineReplace(qtwebengine_checkError) { + + static { + qtwebengine_skipBuild("Static builds of QtWebEngine are not supported.") + return(false) + } + + !qtHaveModule(gui) { + qtwebengine_skipBuild("QtWebEngine requires QtGui.") + return(false) + } + + !qtConfig(webengine-submodule) { + qtwebengine_skipBuild("QtWebEngine required submodule qtwebengine-chromium does not exist. Run 'git submodule update --init'.") + return(false) + } + + !qtConfig(webengine-nowhitespace) { + qtwebengine_skipBuild("QtWebEngine cannot be built in a path that contains whitespace characters.") + return(false) + } + + qtConfig(webengine-no-platform-support) { + !isEmpty(platformError) { + qtwebengine_skipBuild($$platformError) + return(false) + } + !isEmpty(QTWEBENGINE_OUT_ROOT) { + include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri) + QT_FOR_CONFIG += buildtools-private + qtwebengine_skipBuild($$PLATFORM_ERROR) + return(false) + } + qtwebengine_skipBuild("QtWebEngine will not be built. Platform unsupported.") # re-run of configure when topLevel build + return(false): + } + + !qtConfig(webengine-arch-support) { + qtwebengine_skipBuild("QtWebEngine can only be built for x86, x86-64, ARM, Aarch64, and MIPSel architectures.") + return(false) + } + + !qtConfig(webengine-gperf) { + qtwebengine_skipBuild("Tool gperf is required to build QtWebEngine.") + return(false) + } + + !qtConfig(webengine-bison) { + qtwebengine_skipBuild("Tool bison is required to build QtWebEngine.") + return(false) + } + + !qtConfig(webengine-flex) { + qtwebengine_skipBuild("Tool flex is required to build QtWebEngine.") + return(false) + } + + !qtConfig(webengine-python2) { + qtwebengine_skipBuild("Python version 2 (2.7.5 or later) is required to build QtWebEngine.") + return(false) + } + + linux:!qtwebengine_checkErrorForLinux():return(false) + win:!qtwebengine_checkErrorForWindows():return(false) + + sanitizer: !qtConfig(webengine-sanitizer) { + qtwebengine_skipBuild("Chosen sanitizer configuration is not supported for QtWebEngine. Check config.log for details or use -feature-webengine-sanitizer to force build with the chosen sanitizer configuration.") + return(false); + } + + return(true) +} + +defineTest(qtwebengine_checkErrorForLinux) { + + !qtConfig(pkg-config) { + qtwebengine_skipBuild("A pkg-config support is required to build QtWebEngine.") + return(false) + } + + !qtConfig(webengine-host-pkg-config) { + qtwebengine_skipBuild("Host pkg-config is required to build QtWebEngine.") + return(false) + } + + !qtConfig(webengine-system-glibc) { + qtwebengine_skipBuild("A suitable version >= 2.27 of libc required to build QtWebEngine could not be found.") + return(false) + } + + !qtConfig(webengine-system-khr) { + qtwebengine_skipBuild("Khronos development headers required to build QtWebEngine are missing (see mesa/libegl1-mesa-dev)") + return(false) + } + + for(package, $$list("nss dbus fontconfig")) { + !qtConfig(webengine-system-$$package) { + qtwebengine_skipBuild("A suitable version of $$package required to build QtWebEngine could not be found.") + return(false) + } + } + + qtConfig(pkg-config):qtConfig(xcb):!qtConfig(webengine-ozone-x11) { + qtwebengine_skipBuild("Could not find all necessary libraries for qpa-xcb support in QtWebEngine.") + return(false) + } + return(true) +} + +defineTest(qtwebengine_checkErrorForWindows) { + !qtConfig(webengine-win-compiler64) { + qtwebengine_skipBuild("64-bit cross-building or native toolchain required to build QtWebEngine could not be found.") + return(false) + } + + !qtConfig(webengine-winversion) { + qtwebengine_skipBuild("QtWebEngine needs Visual Studio 2017 or higher.") + return(false) + } + return(true) +} + +defineTest(qtwebengine_makeCheckError) { + include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri) + QT_FOR_CONFIG += buildtools-private gui-private + return($$qtwebengine_checkError()) +} diff --git a/src/buildtools/config/windows.pri b/src/buildtools/config/windows.pri index dfa40e9dc..1a3d3d580 100644 --- a/src/buildtools/config/windows.pri +++ b/src/buildtools/config/windows.pri @@ -87,3 +87,10 @@ msvc { } else { error("Qt WebEngine for Windows can only be built with a Microsoft Visual Studio C++ compatible compiler") } + +qtConfig(webengine-spellchecker) { + qtConfig(webengine-native-spellchecker): gn_args += use_browser_spellchecker=true + else: gn_args += use_browser_spellchecker=false +} else { + gn_args += use_browser_spellchecker=false +} diff --git a/src/buildtools/configure.json b/src/buildtools/configure.json index 3fc342992..535d8358b 100644 --- a/src/buildtools/configure.json +++ b/src/buildtools/configure.json @@ -7,7 +7,7 @@ ], "commandline": { "options": { - "webengine-core": "boolean", + "build-qtwebengine-core": "boolean", "webengine-jumbo-build": { "type": "optionalString", "name": "merge_limit"} } }, @@ -351,18 +351,57 @@ "webengine-win-compiler64": { "label": "64bit compiler", "type": "isWindowsHostCompiler64" + }, + "webengine-platform-support": { + "label": "platform supported", + "type": "detectPlatform", + "log": "platformSupport" + }, + "webengine-arch-support": { + "label": "architecture supported", + "type": "detectArch" + }, + "webengine-submodule" : { + "label": "submodule initialized", + "type": "detectSubmodule" + }, + "webengine-nowhitespace" : { + "label": "build path without whitespace", + "type": "detectNoWhitespace" } }, "features": { - "webengine-core": { + "webengine-core-support": { "label": "Support Qt WebEngine Core", - "purpose": "Provides WebEngine Core support.", "condition": "module.gui && features.webengine-python2 && features.webengine-gperf && features.webengine-bison && features.webengine-flex - && (!features.xcb || features.webengine-ozone-x11)", + && features.webengine-submodule + && features.webengine-nowhitespace + && features.webengine-arch-support + && !features.webengine-no-platform-support + && !config.static + && (!config.linux || features.pkg-config) + && (!features.xcb || features.webengine-ozone-x11) + && (!config.win32 || features.webengine-winversion)", + "output": [ "privateFeature" ] + }, + "build-qtwebengine-core": { + "label": "Build Qt WebEngine Core", + "purpose": "Provides WebEngine Core support.", + "output": [ "privateFeature" ] + }, + "build-qtpdf": { + "label": "Support Qt PDF rendering module", + "purpose": "Enables building the Qt PDF rendering module.", + "output": [ "privateFeature" ] + }, + "webengine-developer-build": { + "label": "Developer build", + "purpose": "Enables the developer build configuration.", + "autoDetect": "features.private_tests", "output": [ "privateFeature" ] }, "webengine-python2": { @@ -393,7 +432,7 @@ "condition": "tests.webengine-ninja", "output": [ "privateFeature" ] }, - "webengine-system-fontconfig": { + "webengine-system-fontconfig": { "label": "fontconfig", "condition": "libs.webengine-fontconfig", "output": [ "privateFeature" ] @@ -613,43 +652,56 @@ "label": "64bit compiler", "condition": "config.win32 && tests.webengine-win-compiler64", "output": [ "privateFeature" ] + }, + "webengine-submodule": { + "label": "submodule", + "condition": "tests.webengine-submodule", + "output": [ "privateFeature" ] + }, + "webengine-nowhitespace": { + "label": "nowhitespace", + "condition" : "tests.webengine-nowhitespace", + "output": [ "privateFeature" ] + }, + "webengine-arch-support": { + "label": "architecture", + "condition" : "tests.webengine-arch-support", + "output": [ "privateFeature" ] + }, + "webengine-no-platform-support": { + "label": "platform", + "condition" : "!tests.webengine-platform-support", + "output": [ + "privateFeature", + { "type": "varAssign", "name": "PLATFORM_ERROR", "value": "tests.webengine-platform-support.platformSupport" } + ] } }, "report": [ { - "type": "warning", - "condition": "!module.gui", - "message": "QtWebEngine requires QtGui." - }, - { - "type": "warning", - "condition": "!features.webengine-python2", - "message": "Python version 2 (2.7.5 or later) is required to build QtWebEngine." + "type": "skipBuildWarning", + "condition": "!features.webengine-core-support && (features.build-qtwebengine-core || features.build-qtpdf)", + "message": "qtwebengine_confCheckError" }, { - "type": "warning", - "condition": "!features.webengine-gperf", - "message": "gperf is required to build QtWebEngine." + "type": "note", + "condition": "features.webengine-core-support && !features.build-qtwebengine-core", + "message": "QtWebEngine build is disabled by user." }, { - "type": "warning", - "condition": "!features.webengine-bison", - "message": "bison is required to build QtWebEngine." - }, - { - "type": "warning", - "condition": "!features.webengine-flex", - "message": "flex is required to build QtWebEngine." + "type": "note", + "condition": "features.webengine-core-support && !features.build-qtpdf", + "message": "QtPdf build is disabled by user." }, { "type": "warning", - "condition": "config.linux && !features.webengine-ozone-x11 && features.xcb", - "message": "Could not find all necessary libraries for qpa-xcb support." + "condition": "!features.webengine-core-support && features.build-qtwebengine-core", + "message": "QtWebEngine will not be built." }, { "type": "warning", - "condition": "config.win32 && !features.webengine-win-compiler64", - "message": "64-bit cross-building or native toolchain is required to build QtWebEngine." + "condition": "!features.webengine-core-support && features.build-qtpdf", + "message": "QtPdf will not be built." } ], "summary": [ @@ -662,9 +714,10 @@ "message": "Jumbo Build Merge Limit", "type": "jumboBuild" }, + "webengine-developer-build", { - "section": "Required system libraries", - "condition": "config.unix && !config.macos && features.webengine-core", + "section": "QtWebEngine required system libraries", + "condition": "config.unix && !config.macos", "entries": [ "webengine-system-fontconfig", "webengine-system-dbus", @@ -674,8 +727,8 @@ ] }, { - "section": "Required system libraries for qpa-xcb", - "condition": "config.unix && !config.macos && features.webengine-core", + "section": "QtWebEngine required system libraries for qpa-xcb", + "condition": "config.unix && !config.macos && features.xcb", "entries": [ "webengine-system-x11", "webengine-system-libdrm", diff --git a/src/core/api/qwebenginecookiestore.h b/src/core/api/qwebenginecookiestore.h index 3d313ac23..ff8865406 100644 --- a/src/core/api/qwebenginecookiestore.h +++ b/src/core/api/qwebenginecookiestore.h @@ -50,8 +50,10 @@ #include <functional> namespace QtWebEngineCore { -class ProfileAdapter; +class ContentBrowserClientQt; class CookieMonsterDelegateQt; +class ProfileAdapter; +class RestrictedCookieManagerQt; } // namespace QtWebEngineCore QT_BEGIN_NAMESPACE @@ -84,8 +86,10 @@ Q_SIGNALS: private: explicit QWebEngineCookieStore(QObject *parent = Q_NULLPTR); - friend class QtWebEngineCore::ProfileAdapter; + 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/qwebenginenotification.cpp b/src/core/api/qwebenginenotification.cpp index f91eabd25..abc63fed2 100644 --- a/src/core/api/qwebenginenotification.cpp +++ b/src/core/api/qwebenginenotification.cpp @@ -48,6 +48,22 @@ QT_BEGIN_NAMESPACE using QtWebEngineCore::UserNotificationController; /*! + \qmltype WebEngineNotification + \instantiates QWebEngineNotification + \inqmlmodule QtWebEngine + \since QtWebEngine 1.9 + \brief Encapsulates the data of an HTML5 web notification. + + This type contains the information and API for HTML5 desktop and push notifications. + + Web engine notifications are passed to the user in the + \l WebEngineProfile::presentNotification() signal. + + For more information about how to handle web notification, see the + \l{WebEngine Notifications Example}{Notification Example}. +*/ + +/*! \class QWebEngineNotification \brief The QWebEngineNotification class encapsulates the data of an HTML5 web notification. \since 5.13 @@ -56,10 +72,11 @@ using QtWebEngineCore::UserNotificationController; This class contains the information and API for HTML5 desktop and push notifications. - Web engine notifications are passed to the user in the - \l QWebEngineProfile::setNotificationPresenter() and - \l QQuickWebEngineProfile::presentNotification() calls and the - \l WebEngineProfile::presentNotification() signal. + Web engine notifications are passed to the user through the custom handler + provided with the \l QWebEngineProfile::setNotificationPresenter() call. + + For more information about how to handle web notification, see the + \l{WebEngine Notifications Example}{Notification Example}. */ class QWebEngineNotificationPrivate : public UserNotificationController::Client { @@ -115,6 +132,10 @@ bool QWebEngineNotification::matches(const QWebEngineNotification *other) const } /*! + \qmlproperty bool WebEngineNotification::title + \brief The title of the notification. +*/ +/*! \property QWebEngineNotification::title \brief The title of the notification. \sa message() @@ -126,6 +147,10 @@ QString QWebEngineNotification::title() const } /*! + \qmlproperty string WebEngineNotification::message + \brief The body of the notification message. +*/ +/*! \property QWebEngineNotification::message \brief The body of the notification message. \sa title() @@ -138,6 +163,13 @@ QString QWebEngineNotification::message() const } /*! + \qmlproperty string WebEngineNotification::tag + \brief The tag of the notification message. + + New notifications that have the same tag and origin URL as an existing + one should replace or update the old notification with the same tag. +*/ +/*! \property QWebEngineNotification::tag \brief The tag of the notification message. @@ -153,6 +185,10 @@ QString QWebEngineNotification::tag() const } /*! + \qmlproperty url WebEngineNotification::origin + \brief The URL of the page sending the notification. +*/ +/*! \property QWebEngineNotification::origin \brief The URL of the page sending the notification. */ @@ -175,6 +211,12 @@ QImage QWebEngineNotification::icon() const } /*! + \qmlproperty string WebEngineNotification::language + \brief The primary language for the notification's title and body. + + Its value is a valid BCP 47 language tag, or the empty string. +*/ +/*! \property QWebEngineNotification::language \brief The primary language for the notification's title and body. @@ -189,6 +231,14 @@ QString QWebEngineNotification::language() const } /*! + \qmlproperty enumeration WebEngineNotification::direction + \brief The text direction for the notification's title and body. + + \value Qt.LeftToRight Items are laid out from left to right. + \value Qt.RightToLeft Items are laid out from right to left. + \value Qt.LayoutDirectionAuto The direction to lay out items is determined automatically. +*/ +/*! \property QWebEngineNotification::direction \brief The text direction for the notification's title and body. \sa title(), message() @@ -200,6 +250,12 @@ Qt::LayoutDirection QWebEngineNotification::direction() const } /*! + \qmlmethod void WebEngineNotification::show() + Creates and dispatches a JavaScript \e {show event} on notification. + + Should be called by the notification platform when the notification has been shown to user. +*/ +/*! Creates and dispatches a JavaScript \e {show event} on notification. Should be called by the notification platform when the notification has been shown to user. @@ -212,6 +268,12 @@ void QWebEngineNotification::show() const } /*! + \qmlmethod void WebEngineNotification::click() + Creates and dispatches a JavaScript \e {click event} on notification. + + Should be called by the notification platform when the notification is activated by the user. +*/ +/*! Creates and dispatches a JavaScript \e {click event} on notification. Should be called by the notification platform when the notification is activated by the user. @@ -224,6 +286,13 @@ void QWebEngineNotification::click() const } /*! + \qmlmethod void WebEngineNotification::close() + Creates and dispatches a JavaScript \e {close event} on notification. + + Should be called by the notification platform when the notification is closed, + either by the underlying platform or by the user. +*/ +/*! Creates and dispatches a JavaScript \e {close event} on notification. Should be called by the notification platform when the notification is closed, @@ -237,6 +306,12 @@ void QWebEngineNotification::close() const } /*! + \qmlsignal WebEngineNotification::closed() + + This signal is emitted when the web page calls close steps for the notification, + and it no longer needs to be shown. +*/ +/*! \fn void QWebEngineNotification::closed() This signal is emitted when the web page calls close steps for the notification, diff --git a/src/core/api/qwebengineurlrequestinfo.cpp b/src/core/api/qwebengineurlrequestinfo.cpp index 2aa43a318..5492b21d4 100644 --- a/src/core/api/qwebengineurlrequestinfo.cpp +++ b/src/core/api/qwebengineurlrequestinfo.cpp @@ -64,7 +64,8 @@ ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypePing, content::Resource 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::ResourceTypeNavigationPreload, content::ResourceType::kNavigationPreload) +ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadMainFrame, content::ResourceType::kNavigationPreloadMainFrame) +ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeNavigationPreloadSubFrame, content::ResourceType::kNavigationPreloadSubFrame) ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeLast, content::ResourceType::kMaxValue) ASSERT_ENUMS_MATCH(QtWebEngineCore::WebContentsAdapterClient::LinkNavigation, QWebEngineUrlRequestInfo::NavigationTypeLink) @@ -186,8 +187,8 @@ QWebEngineUrlRequestInfo::QWebEngineUrlRequestInfo(QWebEngineUrlRequestInfoPriva violations. CSP reports are in JSON format and they are delivered by HTTP POST requests to specified servers. (Added in Qt 5.7) \value ResourceTypePluginResource A resource requested by a plugin. (Added in Qt 5.7) - \value ResourceTypeNavigationPreload A service worker navigation preload - request. (Added in Qt 5.14) + \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 ResourceTypeUnknown Unknown request type. \note For forward compatibility all values not matched should be treated as unknown, diff --git a/src/core/api/qwebengineurlrequestinfo.h b/src/core/api/qwebengineurlrequestinfo.h index c2c924b05..75b6e3a81 100644 --- a/src/core/api/qwebengineurlrequestinfo.h +++ b/src/core/api/qwebengineurlrequestinfo.h @@ -76,9 +76,10 @@ public: ResourceTypeServiceWorker, // the main resource of a service worker. ResourceTypeCspReport, // Content Security Policy (CSP) violation report ResourceTypePluginResource, // A resource requested by a plugin - ResourceTypeNavigationPreload, // A service worker navigation preload request. + ResourceTypeNavigationPreloadMainFrame = 19, // A main-frame service worker navigation preload request + ResourceTypeNavigationPreloadSubFrame, // A sub-frame service worker navigation preload request #ifndef Q_QDOC - ResourceTypeLast = ResourceTypeNavigationPreload, + ResourceTypeLast = ResourceTypeNavigationPreloadSubFrame, #endif ResourceTypeUnknown = 255 }; diff --git a/src/core/browser_accessibility_qt.cpp b/src/core/browser_accessibility_qt.cpp index f7e9c1c4f..c760dcd45 100644 --- a/src/core/browser_accessibility_qt.cpp +++ b/src/core/browser_accessibility_qt.cpp @@ -157,7 +157,7 @@ int BrowserAccessibilityQt::indexOfChild(const QAccessibleInterface *iface) cons { const BrowserAccessibilityQt *child = static_cast<const BrowserAccessibilityQt*>(iface); - return child->GetIndexInParent(); + return const_cast<BrowserAccessibilityQt *>(child)->GetIndexInParent(); } QString BrowserAccessibilityQt::text(QAccessible::Text t) const @@ -730,7 +730,7 @@ void BrowserAccessibilityQt::scrollToSubstring(int startIndex, int endIndex) int count = characterCount(); if (startIndex < endIndex && endIndex < count) manager()->ScrollToMakeVisible(*this, - GetRootFrameRangeBoundsRect( + GetRootFrameHypertextRangeBoundsRect( startIndex, endIndex - startIndex, ui::AXClippingBehavior::kUnclipped)); @@ -796,24 +796,24 @@ QAccessibleInterface *BrowserAccessibilityQt::cellAt(int row, int column) const if (row < 0 || row >= rows || column < 0 || column >= columns) return 0; - int cell_id = GetCellId(row, column); - BrowserAccessibility* cell = manager()->GetFromID(cell_id); + base::Optional<int> cell_id = GetCellId(row, column); + BrowserAccessibility* cell = cell_id ? manager()->GetFromID(*cell_id) : nullptr; if (cell) { QAccessibleInterface *iface = static_cast<BrowserAccessibilityQt*>(cell); return iface; } - return 0; + return nullptr; } QAccessibleInterface *BrowserAccessibilityQt::caption() const { - return 0; + return nullptr; } QAccessibleInterface *BrowserAccessibilityQt::summary() const { - return 0; + return nullptr; } QString BrowserAccessibilityQt::columnDescription(int column) const diff --git a/src/core/browser_main_parts_qt.cpp b/src/core/browser_main_parts_qt.cpp index d42a931d0..3e9af8167 100644 --- a/src/core/browser_main_parts_qt.cpp +++ b/src/core/browser_main_parts_qt.cpp @@ -51,6 +51,7 @@ #include "content/public/browser/browser_main_parts.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" +#include "content/public/browser/system_connector.h" #include "content/public/common/service_manager_connection.h" #include "extensions/buildflags/buildflags.h" #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -278,10 +279,10 @@ int BrowserMainPartsQt::PreCreateThreads() return 0; } -void BrowserMainPartsQt::ServiceManagerConnectionStarted(content::ServiceManagerConnection *connection) +void BrowserMainPartsQt::PostCreateThreads() { ServiceQt::GetInstance()->InitConnector(); - connection->GetConnector()->WarmService(service_manager::ServiceFilter::ByName("qtwebengine")); + content::GetSystemConnector()->WarmService(service_manager::ServiceFilter::ByName("qtwebengine")); } } // namespace QtWebEngineCore diff --git a/src/core/browser_main_parts_qt.h b/src/core/browser_main_parts_qt.h index 8c6d8340e..f287c2e44 100644 --- a/src/core/browser_main_parts_qt.h +++ b/src/core/browser_main_parts_qt.h @@ -65,7 +65,7 @@ public: void PreMainMessageLoopRun() override; void PostMainMessageLoopRun() override; int PreCreateThreads() override; - void ServiceManagerConnectionStarted(content::ServiceManagerConnection *connection) override; + void PostCreateThreads() override; private: DISALLOW_COPY_AND_ASSIGN(BrowserMainPartsQt); diff --git a/src/core/browsing_data_remover_delegate_qt.cpp b/src/core/browsing_data_remover_delegate_qt.cpp index 005a9820d..344ba817f 100644 --- a/src/core/browsing_data_remover_delegate_qt.cpp +++ b/src/core/browsing_data_remover_delegate_qt.cpp @@ -50,28 +50,31 @@ namespace QtWebEngineCore { bool DoesOriginMatchEmbedderMask(int origin_type_mask, const url::Origin &origin, - storage::SpecialStoragePolicy *policy) { + storage::SpecialStoragePolicy *policy) +{ Q_UNUSED(origin_type_mask); Q_UNUSED(origin); Q_UNUSED(policy); return true; } -content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher BrowsingDataRemoverDelegateQt::GetOriginTypeMatcher() const { +content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher BrowsingDataRemoverDelegateQt::GetOriginTypeMatcher() +{ return base::BindRepeating(&DoesOriginMatchEmbedderMask); } -bool BrowsingDataRemoverDelegateQt::MayRemoveDownloadHistory() const { +bool BrowsingDataRemoverDelegateQt::MayRemoveDownloadHistory() +{ return true; } -void BrowsingDataRemoverDelegateQt::RemoveEmbedderData( - const base::Time &delete_begin, +void BrowsingDataRemoverDelegateQt::RemoveEmbedderData(const base::Time &delete_begin, const base::Time &delete_end, int remove_mask, - const content::BrowsingDataFilterBuilder& filter_builder, + content::BrowsingDataFilterBuilder *filter_builder, int origin_type_mask, - base::OnceClosure callback) { + base::OnceClosure callback) +{ Q_UNUSED(delete_begin); Q_UNUSED(delete_end); Q_UNUSED(filter_builder); diff --git a/src/core/browsing_data_remover_delegate_qt.h b/src/core/browsing_data_remover_delegate_qt.h index fa99cdf90..dc2761ffc 100644 --- a/src/core/browsing_data_remover_delegate_qt.h +++ b/src/core/browsing_data_remover_delegate_qt.h @@ -50,13 +50,13 @@ public: BrowsingDataRemoverDelegateQt() {} ~BrowsingDataRemoverDelegateQt() override {} - content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher GetOriginTypeMatcher() const override; - bool MayRemoveDownloadHistory() const override; + content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher GetOriginTypeMatcher() override; + bool MayRemoveDownloadHistory() override; void RemoveEmbedderData( const base::Time &delete_begin, const base::Time &delete_end, int remove_mask, - const content::BrowsingDataFilterBuilder &filter_builder, + content::BrowsingDataFilterBuilder *filter_builder, int origin_type_mask, base::OnceClosure callback) override; }; diff --git a/src/core/certificate_error_controller.cpp b/src/core/certificate_error_controller.cpp index 71465a1af..bc83ed802 100644 --- a/src/core/certificate_error_controller.cpp +++ b/src/core/certificate_error_controller.cpp @@ -78,15 +78,15 @@ void CertificateErrorControllerPrivate::accept(bool accepted) CertificateErrorControllerPrivate::CertificateErrorControllerPrivate(int cert_error, const net::SSLInfo& ssl_info, const GURL &request_url, - content::ResourceType resource_type, - bool _overridable, + bool main_frame, + bool fatal_error, bool strict_enforcement, const base::Callback<void(content::CertificateRequestResultType)>& cb ) : certError(CertificateErrorController::CertificateError(cert_error)) , requestUrl(toQt(request_url)) - , resourceType(CertificateErrorController::ResourceType(resource_type)) - , overridable(_overridable) + , resourceType(main_frame ? CertificateErrorController::ResourceTypeMainFrame : CertificateErrorController::ResourceTypeOther) + , fatalError(fatal_error) , strictEnforcement(strict_enforcement) , callback(cb) { @@ -119,7 +119,7 @@ QUrl CertificateErrorController::url() const bool CertificateErrorController::overridable() const { - return d->overridable; + return !d->fatalError && !d->strictEnforcement; } bool CertificateErrorController::strictEnforcement() const diff --git a/src/core/certificate_error_controller_p.h b/src/core/certificate_error_controller_p.h index f3b0c23fa..a11f2b6f0 100644 --- a/src/core/certificate_error_controller_p.h +++ b/src/core/certificate_error_controller_p.h @@ -59,7 +59,7 @@ QT_BEGIN_NAMESPACE class CertificateErrorControllerPrivate { public: - CertificateErrorControllerPrivate(int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, content::ResourceType resource_type, bool overridable, bool strict_enforcement, const base::Callback<void(content::CertificateRequestResultType)>& callback); + CertificateErrorControllerPrivate(int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool main_frame, bool fatal_error, bool strict_enforcement, const base::Callback<void(content::CertificateRequestResultType)>& callback); void accept(bool accepted); @@ -68,7 +68,7 @@ public: QDateTime validStart; QDateTime validExpiry; CertificateErrorController::ResourceType resourceType; - bool overridable; + bool fatalError; bool strictEnforcement; const base::Callback<void(content::CertificateRequestResultType)> callback; QList<QSslCertificate> chain; diff --git a/src/core/chromium_overrides.cpp b/src/core/chromium_overrides.cpp index b226c34ea..4920540a0 100644 --- a/src/core/chromium_overrides.cpp +++ b/src/core/chromium_overrides.cpp @@ -42,6 +42,8 @@ #include "web_contents_view_qt.h" #include "base/values.h" +#include "content/browser/accessibility/accessibility_tree_formatter_blink.h" +#include "content/browser/accessibility/accessibility_tree_formatter_browser.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/font_list.h" @@ -136,6 +138,16 @@ ActivationClient *GetActivationClient(aura::Window *) } // namespace wm #endif // defined(USE_AURA) || defined(USE_OZONE) +namespace content { +std::vector<AccessibilityTreeFormatter::TestPass> AccessibilityTreeFormatter::GetTestPasses() +{ + return { + {"blink", &AccessibilityTreeFormatterBlink::CreateBlink}, + {"native", &AccessibilityTreeFormatter::Create}, + }; +} +} // namespace content + #if defined(USE_AURA) namespace ui { diff --git a/src/core/clipboard_qt.cpp b/src/core/clipboard_qt.cpp index f4a14570a..70e0a2376 100644 --- a/src/core/clipboard_qt.cpp +++ b/src/core/clipboard_qt.cpp @@ -116,15 +116,15 @@ void ClipboardQt::WriteObjects(ui::ClipboardType type, const ObjectMap &objects) // Commit the accumulated data. if (uncommittedData) QGuiApplication::clipboard()->setMimeData(uncommittedData.take(), - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); - if (type == ui::CLIPBOARD_TYPE_COPY_PASTE && IsSupportedClipboardType(ui::CLIPBOARD_TYPE_SELECTION)) { + if (type == ui::ClipboardType::kCopyPaste && IsSupportedClipboardType(ui::ClipboardType::kSelection)) { ObjectMap::const_iterator text_iter = objects.find(CBF_TEXT); if (text_iter != objects.end()) { // Copy text and SourceTag to the selection clipboard. ObjectMap::const_iterator next_iter = text_iter; - WriteObjects(ui::CLIPBOARD_TYPE_SELECTION, ObjectMap(text_iter, ++next_iter, base::KEEP_FIRST_OF_DUPES)); + WriteObjects(ui::ClipboardType::kSelection, ObjectMap(text_iter, ++next_iter, base::KEEP_FIRST_OF_DUPES)); } } } @@ -176,13 +176,13 @@ void ClipboardQt::WriteData(const ui::ClipboardFormatType &format, const char *d bool ClipboardQt::IsFormatAvailable(const ui::ClipboardFormatType &format, ui::ClipboardType type) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); return mimeData && mimeData->hasFormat(QString::fromStdString(format.ToString())); } void ClipboardQt::Clear(ui::ClipboardType type) { - QGuiApplication::clipboard()->clear(type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard + QGuiApplication::clipboard()->clear(type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); } @@ -196,7 +196,7 @@ void ClipboardQt::ReadAvailableTypes(ui::ClipboardType type, std::vector<base::s types->clear(); const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (!mimeData) return; if (mimeData->hasImage() && !mimeData->formats().contains(QStringLiteral("image/png"))) @@ -213,7 +213,7 @@ void ClipboardQt::ReadAvailableTypes(ui::ClipboardType type, std::vector<base::s void ClipboardQt::ReadText(ui::ClipboardType type, base::string16 *result) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (mimeData) *result = toString16(mimeData->text()); } @@ -221,7 +221,7 @@ void ClipboardQt::ReadText(ui::ClipboardType type, base::string16 *result) const void ClipboardQt::ReadAsciiText(ui::ClipboardType type, std::string *result) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (mimeData) *result = mimeData->text().toStdString(); } @@ -236,7 +236,7 @@ void ClipboardQt::ReadHTML(ui::ClipboardType type, base::string16 *markup, std:: *fragment_end = 0; const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (!mimeData) return; *markup = toString16(mimeData->html()); @@ -246,7 +246,7 @@ void ClipboardQt::ReadHTML(ui::ClipboardType type, base::string16 *markup, std:: void ClipboardQt::ReadRTF(ui::ClipboardType type, std::string *result) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (!mimeData) return; const QByteArray byteArray = mimeData->data(QString::fromLatin1(ui::kMimeTypeRTF)); @@ -256,7 +256,7 @@ void ClipboardQt::ReadRTF(ui::ClipboardType type, std::string *result) const SkBitmap ClipboardQt::ReadImage(ui::ClipboardType type) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (!mimeData) return SkBitmap(); QImage image = qvariant_cast<QImage>(mimeData->imageData()); @@ -282,7 +282,7 @@ SkBitmap ClipboardQt::ReadImage(ui::ClipboardType type) const void ClipboardQt::ReadCustomData(ui::ClipboardType clipboard_type, const base::string16 &type, base::string16 *result) const { const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData( - clipboard_type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard : QClipboard::Selection); + clipboard_type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); if (!mimeData) return; const QByteArray customData = mimeData->data(QString::fromLatin1(ui::kMimeTypeWebCustomData)); @@ -305,7 +305,7 @@ void ClipboardQt::ReadData(const ui::ClipboardFormatType &format, std::string *r uint64_t ClipboardQt::GetSequenceNumber(ui::ClipboardType type) const { - return clipboardChangeObserver()->getSequenceNumber(type == ui::CLIPBOARD_TYPE_COPY_PASTE ? QClipboard::Clipboard + return clipboardChangeObserver()->getSequenceNumber(type == ui::ClipboardType::kCopyPaste ? QClipboard::Clipboard : QClipboard::Selection); } diff --git a/src/core/common/extensions/extensions_client_qt.cpp b/src/core/common/extensions/extensions_client_qt.cpp index 6c6200eb0..dd1de1483 100644 --- a/src/core/common/extensions/extensions_client_qt.cpp +++ b/src/core/common/extensions/extensions_client_qt.cpp @@ -135,20 +135,6 @@ bool ExtensionsClientQt::IsScriptableURL(const GURL &url, std::string *error) co return true; } -// Determines if certain fatal extensions errors should be surpressed -// (i.e., only logged) or allowed (i.e., logged before crashing). -bool ExtensionsClientQt::ShouldSuppressFatalErrors() const -{ - return true; -} - -// Records that a fatal error was caught and suppressed. It is expected that -// embedders will only do so if ShouldSuppressFatalErrors at some point -// returned true. -void ExtensionsClientQt::RecordDidSuppressFatalError() -{ -} - // Returns the base webstore URL prefix. const GURL &ExtensionsClientQt::GetWebstoreBaseURL() const { diff --git a/src/core/common/extensions/extensions_client_qt.h b/src/core/common/extensions/extensions_client_qt.h index 657487277..e689f76b7 100644 --- a/src/core/common/extensions/extensions_client_qt.h +++ b/src/core/common/extensions/extensions_client_qt.h @@ -102,15 +102,6 @@ public: // Returns false if content scripts are forbidden from running on |url|. bool IsScriptableURL(const GURL &url, std::string *error) const override; - // Determines if certain fatal extensions errors should be surpressed - // (i.e., only logged) or allowed (i.e., logged before crashing). - bool ShouldSuppressFatalErrors() const override; - - // Records that a fatal error was caught and suppressed. It is expected that - // embedders will only do so if ShouldSuppressFatalErrors at some point - // returned true. - void RecordDidSuppressFatalError() override; - // Returns the base webstore URL prefix. const GURL &GetWebstoreBaseURL() const override; diff --git a/src/core/compositor/compositor.cpp b/src/core/compositor/compositor.cpp index 56693961c..1578e431e 100644 --- a/src/core/compositor/compositor.cpp +++ b/src/core/compositor/compositor.cpp @@ -128,7 +128,7 @@ QSGNode *Compositor::updatePaintNode(QSGNode *oldNode, RenderWidgetHostViewQtDel m_updatePaintNodeShouldCommit = false; gfx::PresentationFeedback dummyFeedback(base::TimeTicks::Now(), base::TimeDelta(), gfx::PresentationFeedback::Flags::kVSync); - m_presentations.insert({m_committedFrame.metadata.frame_token, dummyFeedback}); + m_presentations.emplace(m_committedFrame.metadata.frame_token, viz::FrameTimingDetails{dummyFeedback}); m_resourceTracker->commitResources(); frameNode->commit(m_pendingFrame, m_committedFrame, m_resourceTracker.get(), viewDelegate); @@ -161,7 +161,8 @@ void Compositor::notifyFrameCommitted() void Compositor::sendPresentationFeedback(uint frame_token) { gfx::PresentationFeedback dummyFeedback(base::TimeTicks::Now(), base::TimeDelta(), gfx::PresentationFeedback::Flags::kVSync); - m_presentations.insert({frame_token, dummyFeedback}); + viz::FrameTimingDetails dummyDetails = {dummyFeedback}; + m_presentations.emplace(frame_token, dummyDetails); } bool Compositor::OnBeginFrameDerivedImpl(const viz::BeginFrameArgs &args) diff --git a/src/core/compositor/compositor.h b/src/core/compositor/compositor.h index 6d88dc054..36e62c17a 100644 --- a/src/core/compositor/compositor.h +++ b/src/core/compositor/compositor.h @@ -41,9 +41,9 @@ #define COMPOSITOR_H #include "base/memory/weak_ptr.h" +#include "components/viz/common/frame_timing_details.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/quads/compositor_frame.h" -#include "ui/gfx/presentation_feedback.h" #include <QtCore/qglobal.h> #include <QtCore/qshareddata.h> @@ -115,7 +115,7 @@ private: std::unique_ptr<CompositorResourceTracker> m_resourceTracker; content::RenderWidgetHost *m_host; std::unique_ptr<viz::SyntheticBeginFrameSource> m_beginFrameSource; - base::flat_map<uint32_t, gfx::PresentationFeedback> m_presentations; + base::flat_map<uint32_t, viz::FrameTimingDetails> m_presentations; viz::mojom::CompositorFrameSinkClient *m_frameSinkClient = nullptr; bool m_updatePaintNodeShouldCommit = false; bool m_needsBeginFrames = false; diff --git a/src/core/compositor/delegated_frame_node.cpp b/src/core/compositor/delegated_frame_node.cpp index 19e8d1b82..2a0df3acd 100644 --- a/src/core/compositor/delegated_frame_node.cpp +++ b/src/core/compositor/delegated_frame_node.cpp @@ -570,10 +570,10 @@ static bool areRenderPassStructuresEqual(const viz::CompositorFrame *frameData, if (quad->material != prevQuad->material) return false; #ifndef QT_NO_OPENGL - if (quad->material == viz::DrawQuad::YUV_VIDEO_CONTENT) + if (quad->material == viz::DrawQuad::Material::kYuvVideoContent) return false; #ifdef GL_OES_EGL_image_external - if (quad->material == viz::DrawQuad::STREAM_VIDEO_CONTENT) + if (quad->material == viz::DrawQuad::Material::kStreamVideoContent) return false; #endif // GL_OES_EGL_image_external #endif // QT_NO_OPENGL @@ -840,7 +840,7 @@ void DelegatedFrameNode::handleQuad( RenderWidgetHostViewQtDelegate *apiDelegate) { switch (quad->material) { - case viz::DrawQuad::RENDER_PASS: { + case viz::DrawQuad::Material::kRenderPass: { const viz::RenderPassDrawQuad *renderPassQuad = viz::RenderPassDrawQuad::MaterialCast(quad); if (!renderPassQuad->mask_texture_size.IsEmpty()) { const CompositorResource *resource = findAndHoldResource(renderPassQuad->mask_resource_id(), resourceTracker); @@ -854,7 +854,7 @@ void DelegatedFrameNode::handleQuad( break; } - case viz::DrawQuad::TEXTURE_CONTENT: { + case viz::DrawQuad::Material::kTextureContent: { const viz::TextureDrawQuad *tquad = viz::TextureDrawQuad::MaterialCast(quad); const CompositorResource *resource = findAndHoldResource(tquad->resource_id(), resourceTracker); QSGTexture *texture = @@ -872,7 +872,7 @@ void DelegatedFrameNode::handleQuad( currentLayerChain); break; } - case viz::DrawQuad::SOLID_COLOR: { + case viz::DrawQuad::Material::kSolidColor: { const viz::SolidColorDrawQuad *scquad = viz::SolidColorDrawQuad::MaterialCast(quad); // Qt only supports MSAA and this flag shouldn't be needed. // If we ever want to use QSGRectangleNode::setAntialiasing for this we should @@ -882,7 +882,7 @@ void DelegatedFrameNode::handleQuad( break; #ifndef QT_NO_OPENGL } - case viz::DrawQuad::DEBUG_BORDER: { + case viz::DrawQuad::Material::kDebugBorder: { const viz::DebugBorderDrawQuad *dbquad = viz::DebugBorderDrawQuad::MaterialCast(quad); QSGGeometry *geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 4); @@ -905,7 +905,7 @@ void DelegatedFrameNode::handleQuad( break; #endif } - case viz::DrawQuad::TILED_CONTENT: { + case viz::DrawQuad::Material::kTiledContent: { const viz::TileDrawQuad *tquad = viz::TileDrawQuad::MaterialCast(quad); const CompositorResource *resource = findAndHoldResource(tquad->resource_id(), resourceTracker); nodeHandler->setupTextureContentNode( @@ -915,7 +915,7 @@ void DelegatedFrameNode::handleQuad( break; #ifndef QT_NO_OPENGL } - case viz::DrawQuad::YUV_VIDEO_CONTENT: { + case viz::DrawQuad::Material::kYuvVideoContent: { const viz::YUVVideoDrawQuad *vquad = viz::YUVVideoDrawQuad::MaterialCast(quad); const CompositorResource *yResource = findAndHoldResource(vquad->y_plane_resource_id(), resourceTracker); @@ -941,7 +941,7 @@ void DelegatedFrameNode::handleQuad( break; #ifdef GL_OES_EGL_image_external } - case viz::DrawQuad::STREAM_VIDEO_CONTENT: { + case viz::DrawQuad::Material::kStreamVideoContent: { const viz::StreamVideoDrawQuad *squad = viz::StreamVideoDrawQuad::MaterialCast(quad); const CompositorResource *resource = findAndHoldResource(squad->resource_id(), resourceTracker); MailboxTexture *texture = static_cast<MailboxTexture *>( @@ -954,10 +954,10 @@ void DelegatedFrameNode::handleQuad( #endif // GL_OES_EGL_image_external #endif // QT_NO_OPENGL } - case viz::DrawQuad::SURFACE_CONTENT: + case viz::DrawQuad::Material::kSurfaceContent: Q_UNREACHABLE(); default: - qWarning("Unimplemented quad material: %d", quad->material); + qWarning("Unimplemented quad material: %d", (int)quad->material); } } diff --git a/src/core/compositor/display_gl_output_surface.cpp b/src/core/compositor/display_gl_output_surface.cpp index 5a78b8322..0077af112 100644 --- a/src/core/compositor/display_gl_output_surface.cpp +++ b/src/core/compositor/display_gl_output_surface.cpp @@ -53,20 +53,19 @@ namespace QtWebEngineCore { -DisplayGLOutputSurface::DisplayGLOutputSurface( - scoped_refptr<viz::VizProcessContextProvider> contextProvider, - viz::UpdateVSyncParametersCallback callback) +DisplayGLOutputSurface::DisplayGLOutputSurface(scoped_refptr<viz::VizProcessContextProvider> contextProvider) : OutputSurface(contextProvider) , m_commandBuffer(contextProvider->command_buffer()) , m_gl(contextProvider->ContextGL()) + , m_vizContextProvider(contextProvider) { capabilities_.uses_default_gl_framebuffer = false; m_gl->GenFramebuffers(1, &m_fboId); - contextProvider->SetUpdateVSyncParametersCallback(std::move(callback)); } DisplayGLOutputSurface::~DisplayGLOutputSurface() { + m_vizContextProvider->SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback()); m_gl->DeleteFramebuffers(1, &m_fboId); if (m_sink) m_sink->disconnect(this); @@ -224,9 +223,10 @@ void DisplayGLOutputSurface::swapBuffersOnVizThread() m_backBuffer = std::move(m_middleBuffer); } - m_display->DidReceiveSwapBuffersAck(); + const auto now = base::TimeTicks::Now(); + m_display->DidReceiveSwapBuffersAck(gfx::SwapTimings{now, now}); m_display->DidReceivePresentationFeedback( - gfx::PresentationFeedback(base::TimeTicks::Now(), base::TimeDelta(), + gfx::PresentationFeedback(now, base::TimeDelta(), gfx::PresentationFeedback::Flags::kVSync)); } @@ -234,12 +234,6 @@ void DisplayGLOutputSurface::SetDrawRectangle(const gfx::Rect &) { } -// Returning nullptr here effectively disables viz::OverlayProcessor. -viz::OverlayCandidateValidator *DisplayGLOutputSurface::GetOverlayCandidateValidator() const -{ - return nullptr; -} - // Returning true here will cause viz::GLRenderer to try to render the output // surface as an overlay plane (see viz::DirectRenderer::DrawFrame and // viz::GLRenderer::ScheduleOverlays). @@ -289,4 +283,18 @@ unsigned DisplayGLOutputSurface::UpdateGpuFence() return 0; } +void DisplayGLOutputSurface::SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback callback) +{ + m_vizContextProvider->SetUpdateVSyncParametersCallback(std::move(callback)); +} + +void DisplayGLOutputSurface::SetDisplayTransformHint(gfx::OverlayTransform) +{ +} + +gfx::OverlayTransform DisplayGLOutputSurface::GetDisplayTransform() +{ + return gfx::OVERLAY_TRANSFORM_NONE; +} + } // namespace QtWebEngineCore diff --git a/src/core/compositor/display_gl_output_surface.h b/src/core/compositor/display_gl_output_surface.h index c42a6630a..67d987263 100644 --- a/src/core/compositor/display_gl_output_surface.h +++ b/src/core/compositor/display_gl_output_surface.h @@ -61,9 +61,7 @@ namespace QtWebEngineCore { class DisplayGLOutputSurface final : public viz::OutputSurface, public DisplayProducer { public: - DisplayGLOutputSurface( - scoped_refptr<viz::VizProcessContextProvider> contextProvider, - viz::UpdateVSyncParametersCallback callback); + DisplayGLOutputSurface(scoped_refptr<viz::VizProcessContextProvider> contextProvider); ~DisplayGLOutputSurface() override; // Overridden from viz::OutputSurface. @@ -72,7 +70,6 @@ public: void DiscardBackbuffer() override; void BindFramebuffer() override; void SetDrawRectangle(const gfx::Rect &drawRect) override; - viz::OverlayCandidateValidator *GetOverlayCandidateValidator() const override; bool IsDisplayedAsOverlayPlane() const override; unsigned GetOverlayTextureId() const override; gfx::BufferFormat GetOverlayBufferFormat() const override; @@ -86,6 +83,9 @@ public: uint32_t GetFramebufferCopyTextureFormat() override; void SwapBuffers(viz::OutputSurfaceFrame frame) override; unsigned UpdateGpuFence() override; + void SetUpdateVSyncParametersCallback(viz::UpdateVSyncParametersCallback callback) override; + void SetDisplayTransformHint(gfx::OverlayTransform transform) override; + gfx::OverlayTransform GetDisplayTransform() override; // Overridden from DisplayProducer. QSGNode *updatePaintNode(QSGNode *oldNode, RenderWidgetHostViewQtDelegate *delegate) override; @@ -141,6 +141,7 @@ private: std::unique_ptr<Buffer> m_middleBuffer; std::unique_ptr<Buffer> m_frontBuffer; scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner; + scoped_refptr<viz::VizProcessContextProvider> m_vizContextProvider; }; } // namespace QtWebEngineCore diff --git a/src/core/compositor/display_overrides.cpp b/src/core/compositor/display_overrides.cpp index 4547bb04b..5d999ab92 100644 --- a/src/core/compositor/display_overrides.cpp +++ b/src/core/compositor/display_overrides.cpp @@ -40,23 +40,20 @@ #include "display_gl_output_surface.h" #include "display_software_output_surface.h" -#include "components/viz/service/display_embedder/gpu_display_provider.h" +#include "components/viz/service/display_embedder/output_surface_provider_impl.h" #include "gpu/ipc/in_process_command_buffer.h" std::unique_ptr<viz::OutputSurface> -viz::GpuDisplayProvider::CreateGLOutputSurface( - scoped_refptr<VizProcessContextProvider> context_provider, - UpdateVSyncParametersCallback update_vsync_callback) +viz::OutputSurfaceProviderImpl::CreateGLOutputSurface( + scoped_refptr<VizProcessContextProvider> context_provider) { - return std::make_unique<QtWebEngineCore::DisplayGLOutputSurface>( - std::move(context_provider), std::move(update_vsync_callback)); + return std::make_unique<QtWebEngineCore::DisplayGLOutputSurface>(std::move(context_provider)); } std::unique_ptr<viz::OutputSurface> -viz::GpuDisplayProvider::CreateSoftwareOutputSurface( - UpdateVSyncParametersCallback update_vsync_callback) +viz::OutputSurfaceProviderImpl::CreateSoftwareOutputSurface() { - return std::make_unique<QtWebEngineCore::DisplaySoftwareOutputSurface>(std::move(update_vsync_callback)); + return std::make_unique<QtWebEngineCore::DisplaySoftwareOutputSurface>(); } void gpu::InProcessCommandBuffer::GetTextureQt( diff --git a/src/core/compositor/display_software_output_surface.cpp b/src/core/compositor/display_software_output_surface.cpp index 13f8e8f38..5d3c7a6f6 100644 --- a/src/core/compositor/display_software_output_surface.cpp +++ b/src/core/compositor/display_software_output_surface.cpp @@ -63,7 +63,7 @@ public: // Overridden from viz::SoftwareOutputDevice. void Resize(const gfx::Size &sizeInPixels, float devicePixelRatio) override; - void OnSwapBuffers(base::OnceClosure swapCompletionCallback) override; + void OnSwapBuffers(SwapBuffersCallback swap_ack_callback) override; // Overridden from DisplayProducer. QSGNode *updatePaintNode(QSGNode *oldNode, RenderWidgetHostViewQtDelegate *delegate) override; @@ -73,7 +73,7 @@ private: scoped_refptr<DisplayFrameSink> m_sink; float m_devicePixelRatio = 1.0; scoped_refptr<base::SingleThreadTaskRunner> m_taskRunner; - base::OnceClosure m_swapCompletionCallback; + SwapBuffersCallback m_swapCompletionCallback; QImage m_image; float m_imageDevicePixelRatio = 1.0; }; @@ -99,11 +99,11 @@ void DisplaySoftwareOutputSurface::Device::Resize(const gfx::Size &sizeInPixels, surface_ = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(sizeInPixels.width(), sizeInPixels.height())); } -void DisplaySoftwareOutputSurface::Device::OnSwapBuffers(base::OnceClosure swapCompletionCallback) +void DisplaySoftwareOutputSurface::Device::OnSwapBuffers(SwapBuffersCallback swap_ack_callback) { QMutexLocker locker(&m_mutex); m_taskRunner = base::ThreadTaskRunnerHandle::Get(); - m_swapCompletionCallback = std::move(swapCompletionCallback); + m_swapCompletionCallback = std::move(swap_ack_callback); m_sink->scheduleUpdate(); } @@ -143,7 +143,7 @@ QSGNode *DisplaySoftwareOutputSurface::Device::updatePaintNode( m_image.detach(); } m_imageDevicePixelRatio = m_devicePixelRatio; - m_taskRunner->PostTask(FROM_HERE, std::move(m_swapCompletionCallback)); + m_taskRunner->PostTask(FROM_HERE, base::BindOnce(std::move(m_swapCompletionCallback), toGfx(m_image.size()))); m_taskRunner.reset(); } @@ -155,8 +155,8 @@ QSGNode *DisplaySoftwareOutputSurface::Device::updatePaintNode( return node; } -DisplaySoftwareOutputSurface::DisplaySoftwareOutputSurface(viz::UpdateVSyncParametersCallback callback) - : SoftwareOutputSurface(std::make_unique<Device>(), std::move(callback)) +DisplaySoftwareOutputSurface::DisplaySoftwareOutputSurface() + : SoftwareOutputSurface(std::make_unique<Device>()) {} DisplaySoftwareOutputSurface::~DisplaySoftwareOutputSurface() {} diff --git a/src/core/compositor/display_software_output_surface.h b/src/core/compositor/display_software_output_surface.h index 6707c74dc..ae4b277dd 100644 --- a/src/core/compositor/display_software_output_surface.h +++ b/src/core/compositor/display_software_output_surface.h @@ -47,7 +47,7 @@ namespace QtWebEngineCore { class DisplaySoftwareOutputSurface final : public viz::SoftwareOutputSurface { public: - DisplaySoftwareOutputSurface(viz::UpdateVSyncParametersCallback callback); + DisplaySoftwareOutputSurface(); ~DisplaySoftwareOutputSurface() override; // Overridden from viz::SoftwareOutputSurface. diff --git a/src/core/configure.json b/src/core/configure.json index cf01b9914..9ee66bf61 100644 --- a/src/core/configure.json +++ b/src/core/configure.json @@ -6,7 +6,7 @@ "gui-private", "printsupport" ], - "condition": "features.webengine-core", + "condition": "features.build-qtwebengine-core && features.webengine-core-support", "testDir": "../../config.tests", "commandline": { "options": { @@ -113,12 +113,6 @@ "autoDetect": "tests.webengine-embedded-build", "output": [ "privateFeature" ] }, - "webengine-developer-build": { - "label": "Developer build", - "purpose": "Enables the developer build configuration.", - "autoDetect": "features.private_tests", - "output": [ "privateFeature" ] - }, "webengine-alsa": { "label": "Use ALSA", "condition": "config.unix && libs.webengine-alsa", @@ -282,10 +276,9 @@ "summary": [ { "section": "Qt WebEngineCore", - "condition": "features.webengine-core", + "condition": "features.build-qtwebengine-core", "entries": [ "webengine-embedded-build", - "webengine-developer-build", "webengine-full-debug-info", "webengine-pepper-plugins", "webengine-printing-and-pdf", diff --git a/src/core/content_browser_client_qt.cpp b/src/core/content_browser_client_qt.cpp index ee420d258..6fcd9ad5b 100644 --- a/src/core/content_browser_client_qt.cpp +++ b/src/core/content_browser_client_qt.cpp @@ -45,6 +45,7 @@ #include "base/message_loop/message_loop.h" #include "base/task/post_task.h" #include "base/threading/thread_restrictions.h" +#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #if QT_CONFIG(webengine_spellchecker) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" #endif @@ -75,6 +76,7 @@ #include "extensions/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/remote.h" #include "printing/buildflags/buildflags.h" #include "qtwebengine/browser/qtwebengine_content_browser_overlay_manifest.h" #include "qtwebengine/browser/qtwebengine_content_renderer_overlay_manifest.h" @@ -82,7 +84,6 @@ #include "qtwebengine/browser/qtwebengine_renderer_manifest.h" #include "net/ssl/client_cert_identity.h" #include "net/ssl/client_cert_store.h" -#include "services/proxy_resolver/proxy_resolver_service.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/sandbox/switches.h" @@ -123,6 +124,8 @@ #include "web_contents_delegate_qt.h" #include "web_engine_context.h" #include "web_engine_library_info.h" +#include "api/qwebenginecookiestore.h" +#include "api/qwebenginecookiestore_p.h" #if defined(Q_OS_LINUX) #include "global_descriptors_qt.h" @@ -149,10 +152,16 @@ #include "renderer_host/resource_dispatcher_host_delegate_qt.h" #endif +#if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) +#include "media/mojo/interfaces/constants.mojom.h" +#include "media/mojo/services/media_service_factory.h" +#endif + #include <QGuiApplication> #include <QLocale> -#ifndef QT_NO_OPENGL +#if QT_CONFIG(opengl) # include <QOpenGLContext> +# include <QOpenGLExtraFunctions> #endif #include <qpa/qplatformnativeinterface.h> @@ -195,13 +204,15 @@ public: } void* GetHandle() override { return m_handle; } - bool WasAllocatedUsingRobustnessExtension() override + unsigned int CheckStickyGraphicsResetStatus() override { #if QT_CONFIG(opengl) - if (QOpenGLContext *context = qt_gl_global_share_context()) - return context->format().testOption(QSurfaceFormat::ResetNotification); + if (QOpenGLContext *context = qt_gl_global_share_context()) { + if (context->format().testOption(QSurfaceFormat::ResetNotification)) + return context->extraFunctions()->glGetGraphicsResetStatus(); + } #endif - return false; + return 0 /*GL_NO_ERROR*/; } // We don't care about the rest, this context shouldn't be used except for its handle. @@ -248,7 +259,6 @@ void ShareGroupQtQuick::AboutToAddFirstContext() } ContentBrowserClientQt::ContentBrowserClientQt() - : m_browserMainParts(0) { } @@ -256,10 +266,9 @@ ContentBrowserClientQt::~ContentBrowserClientQt() { } -content::BrowserMainParts *ContentBrowserClientQt::CreateBrowserMainParts(const content::MainFunctionParams&) +std::unique_ptr<content::BrowserMainParts> ContentBrowserClientQt::CreateBrowserMainParts(const content::MainFunctionParams&) { - m_browserMainParts = new BrowserMainPartsQt(); - return m_browserMainParts; + return std::make_unique<BrowserMainPartsQt>(); } void ContentBrowserClientQt::RenderProcessWillLaunch(content::RenderProcessHost* host, @@ -290,16 +299,16 @@ void ContentBrowserClientQt::RenderProcessWillLaunch(content::RenderProcessHost* host->GetChannel()->GetRemoteAssociatedInterface(&renderer_configuration); renderer_configuration->SetInitialConfiguration(is_incognito_process); - service_manager::mojom::ServicePtr service; - *service_request = mojo::MakeRequest(&service); - service_manager::mojom::PIDReceiverPtr pid_receiver; + mojo::PendingRemote<service_manager::mojom::Service> service; + *service_request = service.InitWithNewPipeAndPassReceiver(); service_manager::Identity renderer_identity = host->GetChildIdentity(); + mojo::Remote<service_manager::mojom::ProcessMetadata> metadata; ServiceQt::GetInstance()->connector()->RegisterServiceInstance( service_manager::Identity("qtwebengine_renderer", renderer_identity.instance_group(), renderer_identity.instance_id(), base::Token::CreateRandom()), - std::move(service), mojo::MakeRequest(&pid_receiver)); + std::move(service), metadata.BindNewPipeAndPassReceiver()); } void ContentBrowserClientQt::ResourceDispatcherHostCreated() @@ -379,7 +388,7 @@ void ContentBrowserClientQt::AllowCertificateError(content::WebContents *webCont int cert_error, const net::SSLInfo &ssl_info, const GURL &request_url, - content::ResourceType resource_type, + bool is_main_frame_request, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(content::CertificateRequestResultType)> &callback) @@ -392,17 +401,18 @@ void ContentBrowserClientQt::AllowCertificateError(content::WebContents *webCont cert_error, ssl_info, request_url, - resource_type, - !IsCertErrorFatal(cert_error), + is_main_frame_request, + IsCertErrorFatal(cert_error), strict_enforcement, callback))); contentsDelegate->allowCertificateError(errorController); } -void ContentBrowserClientQt::SelectClientCertificate(content::WebContents *webContents, - net::SSLCertRequestInfo *certRequestInfo, - net::ClientCertIdentityList clientCerts, - std::unique_ptr<content::ClientCertificateDelegate> delegate) + +base::OnceClosure ContentBrowserClientQt::SelectClientCertificate(content::WebContents *webContents, + net::SSLCertRequestInfo *certRequestInfo, + net::ClientCertIdentityList clientCerts, + std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (!clientCerts.empty()) { WebContentsDelegateQt* contentsDelegate = static_cast<WebContentsDelegateQt*>(webContents->GetDelegate()); @@ -414,6 +424,8 @@ void ContentBrowserClientQt::SelectClientCertificate(content::WebContents *webCo } else { delegate->ContinueWithCertificate(nullptr, nullptr); } + // This is consistent with AwContentBrowserClient and CastContentBrowserClient: + return base::OnceClosure(); } std::unique_ptr<net::ClientCertStore> ContentBrowserClientQt::CreateClientCertStore(content::ResourceContext *resource_context) @@ -557,37 +569,45 @@ void ContentBrowserClientQt::BindInterfaceRequestFromFrame(content::RenderFrameH m_frameInterfaces->TryBindInterface(interface_name, &interface_pipe); } -void ContentBrowserClientQt::RegisterIOThreadServiceHandlers(content::ServiceManagerConnection *connection) +void ContentBrowserClientQt::RunServiceInstance(const service_manager::Identity &identity, + mojo::PendingReceiver<service_manager::mojom::Service> *receiver) { - connection->AddServiceRequestHandler( - "qtwebengine", - ServiceQt::GetInstance()->CreateServiceQtRequestHandler()); +#if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) + if (identity.name() == media::mojom::kMediaServiceName) { + service_manager::Service::RunAsyncUntilTermination(media::CreateMediaService(std::move(*receiver))); + return; + } +#endif + + content::ContentBrowserClient::RunServiceInstance(identity, receiver); } -void ContentBrowserClientQt::RegisterOutOfProcessServices(content::ContentBrowserClient::OutOfProcessServiceMap *services) +void ContentBrowserClientQt::RunServiceInstanceOnIOThread(const service_manager::Identity &identity, + mojo::PendingReceiver<service_manager::mojom::Service> *receiver) { - (*services)[proxy_resolver::mojom::kProxyResolverServiceName] = - base::BindRepeating(&base::ASCIIToUTF16, "V8 Proxy Resolver"); + if (identity.name() == "qtwebengine") { + ServiceQt::GetInstance()->CreateServiceQtRequestHandler().Run(std::move(*receiver)); + return; + } + + content::ContentBrowserClient::RunServiceInstance(identity, receiver); } base::Optional<service_manager::Manifest> ContentBrowserClientQt::GetServiceManifestOverlay(base::StringPiece name) { - if (name == content::mojom::kBrowserServiceName) { + if (name == content::mojom::kBrowserServiceName) return GetQtWebEngineContentBrowserOverlayManifest(); - } else if (name == content::mojom::kPackagedServicesServiceName) { - service_manager::Manifest overlay; - overlay.packaged_services = GetQtWebEnginePackagedServiceManifests(); - return overlay; - } else if (name == content::mojom::kRendererServiceName) { + else if (name == content::mojom::kRendererServiceName) return GetQtWebEngineContentRendererOverlayManifest(); - } return base::nullopt; } std::vector<service_manager::Manifest> ContentBrowserClientQt::GetExtraServiceManifests() { - return std::vector<service_manager::Manifest>{GetQtWebEngineRendererManifest()}; + auto manifests = GetQtWebEnginePackagedServiceManifests(); + manifests.push_back(GetQtWebEngineRendererManifest()); + return manifests; } bool ContentBrowserClientQt::CanCreateWindow( @@ -639,13 +659,6 @@ std::unique_ptr<device::LocationProvider> ContentBrowserClientQt::OverrideSystem } #endif -scoped_refptr<net::URLRequestContextGetter> GetSystemRequestContextOnUIThread() -{ - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - return scoped_refptr<net::URLRequestContextGetter>( - ProfileAdapter::createDefaultProfileAdapter()->profile()->GetRequestContext()); -} - void ContentBrowserClientQt::AddNetworkHintsMessageFilter(int render_process_id, net::URLRequestContext *context) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -666,38 +679,42 @@ bool ContentBrowserClientQt::ShouldEnableStrictSiteIsolation() return false; } -bool ContentBrowserClientQt::AllowGetCookie(const GURL &url, - const GURL &first_party, - const net::CookieList & /*cookie_list*/, - content::ResourceContext *context, - int /*render_process_id*/, - int /*render_frame_id*/) -{ - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - return ProfileIODataQt::FromResourceContext(context)->canGetCookies(toQt(first_party), toQt(url)); +bool ContentBrowserClientQt::WillCreateRestrictedCookieManager(network::mojom::RestrictedCookieManagerRole role, + content::BrowserContext *browser_context, + const url::Origin &origin, + bool is_service_worker, + int process_id, + int routing_id, + network::mojom::RestrictedCookieManagerRequest *request) +{ + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&ProfileIODataQt::CreateRestrictedCookieManager, + ProfileIODataQt::FromBrowserContext(browser_context)->getWeakPtrOnUIThread(), + std::move(*request), + role, origin, is_service_worker, process_id, routing_id)); + return true; } -bool ContentBrowserClientQt::AllowSetCookie(const GURL &url, - const GURL &first_party, - const net::CanonicalCookie& /*cookie*/, - content::ResourceContext *context, - int /*render_process_id*/, - int /*render_frame_id*/) +bool ContentBrowserClientQt::AllowAppCacheOnIO(const GURL &manifest_url, + const GURL &first_party, + content::ResourceContext *context) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - return ProfileIODataQt::FromResourceContext(context)->canSetCookie(toQt(first_party), QByteArray(), toQt(url)); + return ProfileIODataQt::FromResourceContext(context)->canGetCookies(toQt(first_party), toQt(manifest_url)); } bool ContentBrowserClientQt::AllowAppCache(const GURL &manifest_url, const GURL &first_party, - content::ResourceContext *context) + content::BrowserContext *context) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - return ProfileIODataQt::FromResourceContext(context)->canGetCookies(toQt(first_party), toQt(manifest_url)); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + return static_cast<ProfileQt *>(context)->profileAdapter()->cookieStore()->d_func()->canAccessCookies(toQt(first_party), toQt(manifest_url)); } bool ContentBrowserClientQt::AllowServiceWorker(const GURL &scope, const GURL &first_party, + const GURL & /*script_url*/, content::ResourceContext *context, base::RepeatingCallback<content::WebContents*()> wc_getter) { @@ -747,16 +764,12 @@ bool ContentBrowserClientQt::HandleExternalProtocol( bool is_main_frame, ui::PageTransition page_transition, bool has_user_gesture, - const std::string &method, - const net::HttpRequestHeaders &headers, - network::mojom::URLLoaderFactoryRequest *factory_request, - network::mojom::URLLoaderFactory *&out_factory) + network::mojom::URLLoaderFactoryPtr *out_factory) { Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); Q_UNUSED(child_id); Q_UNUSED(navigation_data); - Q_UNUSED(method); - Q_UNUSED(headers); + Q_UNUSED(out_factory); base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LaunchURL, @@ -768,6 +781,71 @@ bool ContentBrowserClientQt::HandleExternalProtocol( return true; } +namespace { +// Copied from chrome/browser/chrome_content_browser_client.cc +template<class HandlerRegistry> +class ProtocolHandlerThrottle : public content::URLLoaderThrottle +{ +public: + explicit ProtocolHandlerThrottle(const HandlerRegistry &protocol_handler_registry) + : protocol_handler_registry_(protocol_handler_registry) + { + } + ~ProtocolHandlerThrottle() override = default; + + void WillStartRequest(network::ResourceRequest *request, bool *defer) override + { + TranslateUrl(&request->url); + } + + void WillRedirectRequest(net::RedirectInfo *redirect_info, + const network::ResourceResponseHead &response_head, bool *defer, + std::vector<std::string> *to_be_removed_headers, + net::HttpRequestHeaders *modified_headers) override + { + TranslateUrl(&redirect_info->new_url); + } + +private: + void TranslateUrl(GURL *url) + { + if (!protocol_handler_registry_->IsHandledProtocol(url->scheme())) + return; + GURL translated_url = protocol_handler_registry_->Translate(*url); + if (!translated_url.is_empty()) + *url = translated_url; + } + + HandlerRegistry protocol_handler_registry_; +}; +} // namespace + +std::vector<std::unique_ptr<content::URLLoaderThrottle>> +ContentBrowserClientQt::CreateURLLoaderThrottlesOnIO( + const network::ResourceRequest & /*request*/, content::ResourceContext *resource_context, + const base::RepeatingCallback<content::WebContents *()> & /*wc_getter*/, + content::NavigationUIData * /*navigation_ui_data*/, int /*frame_tree_node_id*/) +{ + std::vector<std::unique_ptr<content::URLLoaderThrottle>> result; + ProfileIODataQt *ioData = ProfileIODataQt::FromResourceContext(resource_context); + result.push_back(std::make_unique<ProtocolHandlerThrottle< + scoped_refptr<ProtocolHandlerRegistry::IOThreadDelegate>>>( + ioData->protocolHandlerRegistryIOThreadDelegate())); + return result; +} + +std::vector<std::unique_ptr<content::URLLoaderThrottle>> +ContentBrowserClientQt::CreateURLLoaderThrottles( + const network::ResourceRequest &request, content::BrowserContext *browser_context, + const base::RepeatingCallback<content::WebContents *()> &wc_getter, + content::NavigationUIData *navigation_ui_data, int frame_tree_node_id) +{ + std::vector<std::unique_ptr<content::URLLoaderThrottle>> result; + result.push_back(std::make_unique<ProtocolHandlerThrottle<ProtocolHandlerRegistry *>>( + ProtocolHandlerRegistryFactory::GetForBrowserContext(browser_context))); + return result; +} + std::unique_ptr<content::LoginDelegate> ContentBrowserClientQt::CreateLoginDelegate( const net::AuthChallengeInfo &authInfo, content::WebContents *web_contents, @@ -803,7 +881,7 @@ std::string ContentBrowserClientQt::getUserAgent() return content::BuildUserAgentFromProduct("QtWebEngine/" QTWEBENGINECORE_VERSION_STR " Chrome/" CHROMIUM_VERSION); } -std::string ContentBrowserClientQt::GetProduct() const +std::string ContentBrowserClientQt::GetProduct() { QString productName(qApp->applicationName() % '/' % qApp->applicationVersion()); return productName.toStdString(); diff --git a/src/core/content_browser_client_qt.h b/src/core/content_browser_client_qt.h index 7f31b7c85..f5b03a8d9 100644 --- a/src/core/content_browser_client_qt.h +++ b/src/core/content_browser_client_qt.h @@ -83,7 +83,7 @@ class ContentBrowserClientQt : public content::ContentBrowserClient { public: ContentBrowserClientQt(); ~ContentBrowserClientQt(); - content::BrowserMainParts* CreateBrowserMainParts(const content::MainFunctionParams&) override; + std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(const content::MainFunctionParams&) override; void RenderProcessWillLaunch(content::RenderProcessHost *host, service_manager::mojom::ServiceRequest* service_request) override; void ResourceDispatcherHostCreated() override; @@ -98,14 +98,14 @@ public: int cert_error, const net::SSLInfo &ssl_info, const GURL &request_url, - content::ResourceType resource_type, + bool is_main_frame_request, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(content::CertificateRequestResultType)> &callback) override; - void SelectClientCertificate(content::WebContents* web_contents, - net::SSLCertRequestInfo* cert_request_info, - net::ClientCertIdentityList client_certs, - std::unique_ptr<content::ClientCertificateDelegate> delegate) override; + base::OnceClosure SelectClientCertificate(content::WebContents* web_contents, + net::SSLCertRequestInfo* cert_request_info, + net::ClientCertIdentityList client_certs, + std::unique_ptr<content::ClientCertificateDelegate> delegate) override; std::unique_ptr<net::ClientCertStore> CreateClientCertStore(content::ResourceContext *resource_context) override; content::DevToolsManagerDelegate *GetDevToolsManagerDelegate() override; content::PlatformNotificationService * GetPlatformNotificationService(content::BrowserContext *browser_context) override; @@ -120,8 +120,11 @@ public: void BindInterfaceRequestFromFrame(content::RenderFrameHost* render_frame_host, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; - void RegisterIOThreadServiceHandlers(content::ServiceManagerConnection *connection) override; - void RegisterOutOfProcessServices(OutOfProcessServiceMap* services) override; + void RunServiceInstance(const service_manager::Identity &identity, + mojo::PendingReceiver<service_manager::mojom::Service> *receiver) override; + void RunServiceInstanceOnIOThread(const service_manager::Identity &identity, + mojo::PendingReceiver<service_manager::mojom::Service> *receiver) override; + std::vector<service_manager::Manifest> GetExtraServiceManifests() override; base::Optional<service_manager::Manifest> GetServiceManifestOverlay(base::StringPiece name) override; bool CanCreateWindow(content::RenderFrameHost *opener, @@ -139,26 +142,24 @@ public: bool *no_javascript_access) override; bool ShouldEnableStrictSiteIsolation() override; - bool AllowGetCookie(const GURL& url, - const GURL& first_party, - const net::CookieList& cookie_list, - content::ResourceContext* context, - int render_process_id, - int render_frame_id) override; - - bool AllowSetCookie(const GURL& url, - const GURL& first_party, - const net::CanonicalCookie& cookie, - content::ResourceContext* context, - int render_process_id, - int render_frame_id) override; - + bool WillCreateRestrictedCookieManager(network::mojom::RestrictedCookieManagerRole role, + content::BrowserContext *browser_context, + const url::Origin& origin, + bool is_service_worker, + int process_id, + int routing_id, + network::mojom::RestrictedCookieManagerRequest *request) override; + + bool AllowAppCacheOnIO(const GURL& manifest_url, + const GURL& first_party, + content::ResourceContext* context) override; bool AllowAppCache(const GURL& manifest_url, const GURL& first_party, - content::ResourceContext* context) override; + content::BrowserContext* context) override; bool AllowServiceWorker(const GURL& scope, const GURL& first_party, + const GURL& script_url, content::ResourceContext* context, base::RepeatingCallback<content::WebContents*()> wc_getter) override; @@ -194,6 +195,7 @@ public: scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) override; + bool HandleExternalProtocol( const GURL &url, content::ResourceRequestInfo::WebContentsGetter web_contents_getter, @@ -202,21 +204,27 @@ public: bool is_main_frame, ui::PageTransition page_transition, bool has_user_gesture, - const std::string &method, - const net::HttpRequestHeaders &headers, - network::mojom::URLLoaderFactoryRequest *factory_request, - network::mojom::URLLoaderFactory *&out_factory) override; + network::mojom::URLLoaderFactoryPtr *out_factory) override; + + std::vector<std::unique_ptr<content::URLLoaderThrottle>> CreateURLLoaderThrottlesOnIO( + const network::ResourceRequest &request, content::ResourceContext *resource_context, + const base::RepeatingCallback<content::WebContents *()> &wc_getter, + content::NavigationUIData *navigation_ui_data, int frame_tree_node_id) override; + + std::vector<std::unique_ptr<content::URLLoaderThrottle>> CreateURLLoaderThrottles( + const network::ResourceRequest &request, content::BrowserContext *browser_context, + const base::RepeatingCallback<content::WebContents *()> &wc_getter, + content::NavigationUIData *navigation_ui_data, int frame_tree_node_id) override; static std::string getUserAgent(); - std::string GetUserAgent() const override { return getUserAgent(); } - std::string GetProduct() const override; + std::string GetUserAgent() override { return getUserAgent(); } + std::string GetProduct() override; private: void InitFrameInterfaces(); void AddNetworkHintsMessageFilter(int render_process_id, net::URLRequestContext *context); - BrowserMainPartsQt* m_browserMainParts; std::unique_ptr<content::ResourceDispatcherHostDelegate> m_resourceDispatcherHostDelegate; scoped_refptr<ShareGroupQtQuick> m_shareGroupQtQuick; std::unique_ptr<service_manager::BinderRegistry> m_frameInterfaces; diff --git a/src/core/content_client_qt.cpp b/src/core/content_client_qt.cpp index 8e5fdf06c..554ee3e12 100644 --- a/src/core/content_client_qt.cpp +++ b/src/core/content_client_qt.cpp @@ -414,21 +414,27 @@ void ContentClientQt::AddAdditionalSchemes(Schemes* schemes) schemes->standard_schemes.push_back("chrome-extension"); } -base::StringPiece ContentClientQt::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const { +base::StringPiece ContentClientQt::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) +{ return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor); } -base::RefCountedMemory *ContentClientQt::GetDataResourceBytes(int resource_id) const +base::RefCountedMemory *ContentClientQt::GetDataResourceBytes(int resource_id) { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(resource_id); } -gfx::Image &ContentClientQt::GetNativeImageNamed(int resource_id) const +gfx::Image &ContentClientQt::GetNativeImageNamed(int resource_id) { return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id); } -base::string16 ContentClientQt::GetLocalizedString(int message_id) const +bool ContentClientQt::IsDataResourceGzipped(int resource_id) +{ + return ui::ResourceBundle::GetSharedInstance().IsGzipped(resource_id); +} + +base::string16 ContentClientQt::GetLocalizedString(int message_id) { return l10n_util::GetStringUTF16(message_id); } diff --git a/src/core/content_client_qt.h b/src/core/content_client_qt.h index 1f4ac0b63..581805a51 100644 --- a/src/core/content_client_qt.h +++ b/src/core/content_client_qt.h @@ -56,10 +56,11 @@ public: std::vector<media::CdmHostFilePath> *cdm_host_file_paths) override; void AddAdditionalSchemes(Schemes* schemes) override; - base::StringPiece GetDataResource(int, ui::ScaleFactor) const override; - base::RefCountedMemory* GetDataResourceBytes(int resource_id) const override; - gfx::Image &GetNativeImageNamed(int resource_id) const override; - base::string16 GetLocalizedString(int message_id) const override; + base::StringPiece GetDataResource(int, ui::ScaleFactor) override; + base::RefCountedMemory* GetDataResourceBytes(int resource_id) override; + gfx::Image &GetNativeImageNamed(int resource_id) override; + bool IsDataResourceGzipped(int resource_id) override; + base::string16 GetLocalizedString(int message_id) override; }; } // namespace QtWebEngineCore diff --git a/src/core/content_main_delegate_qt.cpp b/src/core/content_main_delegate_qt.cpp index 6df20896c..cb23a5287 100644 --- a/src/core/content_main_delegate_qt.cpp +++ b/src/core/content_main_delegate_qt.cpp @@ -130,7 +130,7 @@ static logging::LoggingDestination DetermineLogMode(const base::CommandLine& com enable_logging = !enable_logging; if (enable_logging) - return logging::LOG_TO_SYSTEM_DEBUG_LOG; + return logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; else return logging::LOG_NONE; } @@ -149,7 +149,9 @@ void ContentMainDelegateQt::PreSandboxStartup() base::CommandLine* parsedCommandLine = base::CommandLine::ForCurrentProcess(); logging::LoggingSettings settings; settings.logging_dest = DetermineLogMode(*parsedCommandLine); - logging::InitLogging(settings); + bool success = logging::InitLogging(settings); + if (!success) + qWarning("Failed to initialize Chromium logging"); // view the logs with process/thread IDs and timestamps logging::SetLogItems(true, //enable_process_id true, //enable_thread_id diff --git a/src/core/content_utility_client_qt.cpp b/src/core/content_utility_client_qt.cpp index 0b2dbd08e..12a538a07 100644 --- a/src/core/content_utility_client_qt.cpp +++ b/src/core/content_utility_client_qt.cpp @@ -39,9 +39,8 @@ #include "content_utility_client_qt.h" -#include "base/bind.h" -#include "content/public/utility/utility_thread.h" -#include "services/proxy_resolver/proxy_resolver_service.h" +#include "base/no_destructor.h" +#include "services/proxy_resolver/proxy_resolver_factory_impl.h" namespace QtWebEngineCore { @@ -51,41 +50,12 @@ ContentUtilityClientQt::ContentUtilityClientQt() ContentUtilityClientQt::~ContentUtilityClientQt() = default; -namespace { - -std::unique_ptr<service_manager::Service> CreateProxyResolverService(service_manager::mojom::ServiceRequest request) +void ContentUtilityClientQt::RunIOThreadService(mojo::GenericPendingReceiver *receiver) { - return std::make_unique<proxy_resolver::ProxyResolverService>(std::move(request)); -} - -using ServiceFactory = base::OnceCallback<std::unique_ptr<service_manager::Service>()>; -void RunServiceOnIOThread(ServiceFactory factory) -{ - base::OnceClosure terminate_process = base::BindOnce( - base::IgnoreResult(&base::SequencedTaskRunner::PostTask), - base::SequencedTaskRunnerHandle::Get(), FROM_HERE, - base::BindOnce([] { content::UtilityThread::Get()->ReleaseProcess(); })); - content::ChildThread::Get()->GetIOTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce( - [](ServiceFactory factory, base::OnceClosure terminate_process) { - service_manager::Service::RunAsyncUntilTermination( - std::move(factory).Run(), std::move(terminate_process)); - }, - std::move(factory), std::move(terminate_process))); -} - -} // namespace - -bool ContentUtilityClientQt::HandleServiceRequest(const std::string &service_name, - service_manager::mojom::ServiceRequest request) -{ - if (service_name == proxy_resolver::mojom::kProxyResolverServiceName) { - RunServiceOnIOThread(base::BindOnce(&CreateProxyResolverService, std::move(request))); - return true; + if (auto factory_receiver = receiver->As<proxy_resolver::mojom::ProxyResolverFactory>()) { + static base::NoDestructor<proxy_resolver::ProxyResolverFactoryImpl> factory(std::move(factory_receiver)); + return; } - - return false; } } // namespace diff --git a/src/core/content_utility_client_qt.h b/src/core/content_utility_client_qt.h index 79972adb8..2a9ecff93 100644 --- a/src/core/content_utility_client_qt.h +++ b/src/core/content_utility_client_qt.h @@ -53,8 +53,7 @@ public: ~ContentUtilityClientQt() override; // content::ContentUtilityClient: - bool HandleServiceRequest(const std::string &service_name, - service_manager::mojom::ServiceRequest request) override; + void RunIOThreadService(mojo::GenericPendingReceiver *receiver) override; }; diff --git a/src/core/core_chromium.pri b/src/core/core_chromium.pri index 810ec9a0f..9eab15456 100644 --- a/src/core/core_chromium.pri +++ b/src/core/core_chromium.pri @@ -86,6 +86,7 @@ SOURCES = \ net/network_delegate_qt.cpp \ net/proxy_config_service_qt.cpp \ net/qrc_url_scheme_handler.cpp \ + net/restricted_cookie_manager_qt.cpp \ net/ssl_host_state_delegate_qt.cpp \ net/url_request_context_getter_qt.cpp \ net/url_request_custom_job.cpp \ @@ -195,6 +196,7 @@ HEADERS = \ net/custom_protocol_handler.h \ net/network_delegate_qt.h \ net/qrc_url_scheme_handler.h \ + net/restricted_cookie_manager_qt.h \ net/ssl_host_state_delegate_qt.h \ net/url_request_context_getter_qt.h \ net/url_request_custom_job.h \ diff --git a/src/core/core_common.pri b/src/core/core_common.pri index 2a9dc90c0..e10d14267 100644 --- a/src/core/core_common.pri +++ b/src/core/core_common.pri @@ -18,6 +18,3 @@ CONFIG -= ltcg # Chromium requires C++14 CONFIG += c++14 -#QTBUG-73216 ci has to be updated with latest yocto -boot2qt: CONFIG -= use_gold_linker - diff --git a/src/core/delegated_frame_host_client_qt.cpp b/src/core/delegated_frame_host_client_qt.cpp index d3f5a4ade..817ea2fa5 100644 --- a/src/core/delegated_frame_host_client_qt.cpp +++ b/src/core/delegated_frame_host_client_qt.cpp @@ -61,6 +61,7 @@ SkColor DelegatedFrameHostClientQt::DelegatedFrameHostGetGutterColor() const void DelegatedFrameHostClientQt::OnBeginFrame(base::TimeTicks frame_time) { p->host()->ProgressFlingIfNeeded(frame_time); + p->UpdateNeedsBeginFramesInternal(); } void DelegatedFrameHostClientQt::OnFrameTokenChanged(uint32_t frame_token) diff --git a/src/core/devtools_frontend_qt.cpp b/src/core/devtools_frontend_qt.cpp index d3f46f648..1dcbd1e9d 100644 --- a/src/core/devtools_frontend_qt.cpp +++ b/src/core/devtools_frontend_qt.cpp @@ -103,7 +103,7 @@ std::unique_ptr<base::DictionaryValue> BuildObjectForResponse(const net::HttpRes static std::string GetFrontendURL() { - return "chrome-devtools://devtools/bundled/devtools_app.html"; + return "devtools://devtools/bundled/devtools_app.html"; } } // namespace diff --git a/src/core/extensions/component_extension_resource_manager_qt.cpp b/src/core/extensions/component_extension_resource_manager_qt.cpp index 09311c764..bb1dd045c 100644 --- a/src/core/extensions/component_extension_resource_manager_qt.cpp +++ b/src/core/extensions/component_extension_resource_manager_qt.cpp @@ -46,6 +46,9 @@ #include "base/logging.h" #include "base/path_service.h" +#include "base/stl_util.h" +#include "base/values.h" + #include "chrome/grit/component_extension_resources_map.h" namespace extensions { @@ -60,7 +63,7 @@ ComponentExtensionResourceManagerQt::~ComponentExtensionResourceManagerQt() {} bool ComponentExtensionResourceManagerQt::IsComponentExtensionResource(const base::FilePath &extension_path, const base::FilePath &resource_path, - ComponentExtensionResourceInfo* resource_info) const + int *resource_id) const { base::FilePath directory_path = extension_path; base::FilePath resources_dir; @@ -73,9 +76,9 @@ bool ComponentExtensionResourceManagerQt::IsComponentExtensionResource(const bas relative_path = relative_path.Append(resource_path); relative_path = relative_path.NormalizePathSeparators(); - auto entry = path_to_resource_info_.find(relative_path); - if (entry != path_to_resource_info_.end()) { - *resource_info = entry->second; + auto entry = path_to_resource_id_.find(relative_path); + if (entry != path_to_resource_id_.end()) { + *resource_id = entry->second; return true; } @@ -87,15 +90,14 @@ const ui::TemplateReplacements *ComponentExtensionResourceManagerQt::GetTemplate return nullptr; } -void ComponentExtensionResourceManagerQt::AddComponentResourceEntries(const GzippedGritResourceMap *entries, size_t size) +void ComponentExtensionResourceManagerQt::AddComponentResourceEntries(const GritResourceMap *entries, size_t size) { for (size_t i = 0; i < size; ++i) { base::FilePath resource_path = base::FilePath().AppendASCII(entries[i].name); resource_path = resource_path.NormalizePathSeparators(); - DCHECK(!base::ContainsKey(path_to_resource_info_, resource_path)); - path_to_resource_info_[resource_path] = { entries[i].value, - entries[i].gzipped }; + DCHECK(!base::Contains(path_to_resource_id_, resource_path)); + path_to_resource_id_[resource_path] = entries[i].value; } } diff --git a/src/core/extensions/component_extension_resource_manager_qt.h b/src/core/extensions/component_extension_resource_manager_qt.h index c44c23439..b719c8960 100644 --- a/src/core/extensions/component_extension_resource_manager_qt.h +++ b/src/core/extensions/component_extension_resource_manager_qt.h @@ -49,7 +49,7 @@ #include "base/files/file_path.h" #include "extensions/browser/component_extension_resource_manager.h" -struct GzippedGritResourceMap; +struct GritResourceMap; namespace extensions { @@ -62,15 +62,15 @@ public: // Overridden from ComponentExtensionResourceManager: bool IsComponentExtensionResource(const base::FilePath &extension_path, const base::FilePath &resource_path, - ComponentExtensionResourceInfo *resource_info) const override; - const ui::TemplateReplacements *GetTemplateReplacementsForExtension(const std::string& extension_id) const override; + int *resource_id) const override; + const ui::TemplateReplacements *GetTemplateReplacementsForExtension(const std::string &extension_id) const override; private: - void AddComponentResourceEntries(const GzippedGritResourceMap* entries, size_t size); + void AddComponentResourceEntries(const GritResourceMap *entries, size_t size); // A map from a resource path to the resource ID. Used by // IsComponentExtensionResource. - std::map<base::FilePath, ComponentExtensionResourceInfo> path_to_resource_info_; + std::map<base::FilePath, int> path_to_resource_id_; DISALLOW_COPY_AND_ASSIGN(ComponentExtensionResourceManagerQt); }; diff --git a/src/core/extensions/extension_system_qt.cpp b/src/core/extensions/extension_system_qt.cpp index 4ca407421..7278e50c1 100644 --- a/src/core/extensions/extension_system_qt.cpp +++ b/src/core/extensions/extension_system_qt.cpp @@ -137,8 +137,9 @@ class ContentVerifierDelegateQt // This should return what verification mode is appropriate for the given // extension, if any. - Mode ShouldBeVerified(const Extension& extension) override { - return NONE; + bool ShouldBeVerified(const Extension& extension) override + { + return false; } // Should return the public key to use for validating signatures via the two @@ -398,11 +399,6 @@ void ExtensionSystemQt::InitForRegularProfile(bool extensions_enabled) Init(extensions_enabled); } -void ExtensionSystemQt::InitForIncognitoProfile() -{ - NOTIMPLEMENTED(); -} - std::unique_ptr<ExtensionSet> ExtensionSystemQt::GetDependentExtensions(const Extension *extension) { return base::WrapUnique(new ExtensionSet()); diff --git a/src/core/extensions/extension_system_qt.h b/src/core/extensions/extension_system_qt.h index 712e0104d..4370f5cc3 100644 --- a/src/core/extensions/extension_system_qt.h +++ b/src/core/extensions/extension_system_qt.h @@ -85,7 +85,6 @@ public: // ExtensionSystem implementation: void InitForRegularProfile(bool extensions_enabled) override; - void InitForIncognitoProfile() override; ExtensionService *extension_service() override; RuntimeData *runtime_data() override; ManagementPolicy *management_policy() override; diff --git a/src/core/extensions/extensions_browser_client_qt.cpp b/src/core/extensions/extensions_browser_client_qt.cpp index fc1def3ca..eb8c12bff 100644 --- a/src/core/extensions/extensions_browser_client_qt.cpp +++ b/src/core/extensions/extensions_browser_client_qt.cpp @@ -109,12 +109,12 @@ public: URLRequestResourceBundleJob(net::URLRequest *request, net::NetworkDelegate *network_delegate, const base::FilePath &filename, - const extensions::ComponentExtensionResourceInfo &resource_info, + int resource_id, const std::string &content_security_policy, bool send_cors_header) : net::URLRequestSimpleJob(request, network_delegate) , filename_(filename) - , resource_info_(resource_info) + , resource_id_(resource_id) , weak_factory_(this) { // Leave cache headers out of resource bundle requests. @@ -126,7 +126,7 @@ public: net::CompletionOnceCallback callback) const override { const ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - *data = rb.LoadDataResourceBytes(resource_info_.resource_id); + *data = rb.LoadDataResourceBytes(resource_id_); // Add the Content-Length header now that we know the resource length. response_info_.headers->AddHeader( @@ -173,7 +173,7 @@ private: base::FilePath filename_; // The resource to load. - const extensions::ComponentExtensionResourceInfo resource_info_; + int resource_id_; net::HttpResponseInfo response_info_; @@ -267,14 +267,14 @@ net::URLRequestJob *ExtensionsBrowserClientQt::MaybeCreateResourceBundleRequestJ // extension relative path against resources_path. resources_path.AppendRelativePath(directory_path, &relative_path)) { base::FilePath request_path = extensions::file_util::ExtensionURLToRelativeFilePath(request->url()); - ComponentExtensionResourceInfo resource_info; - if (GetComponentExtensionResourceManager()->IsComponentExtensionResource(directory_path, request_path, &resource_info)) { + int resource_id = 0; + if (GetComponentExtensionResourceManager()->IsComponentExtensionResource(directory_path, request_path, &resource_id)) { relative_path = relative_path.Append(request_path); relative_path = relative_path.NormalizePathSeparators(); return new URLRequestResourceBundleJob(request, network_delegate, relative_path, - resource_info, + resource_id, content_security_policy, send_cors_header); } @@ -285,9 +285,9 @@ net::URLRequestJob *ExtensionsBrowserClientQt::MaybeCreateResourceBundleRequestJ // Return the resource relative path and id for the given request. base::FilePath ExtensionsBrowserClientQt::GetBundleResourcePath(const network::ResourceRequest &request, const base::FilePath &extension_resources_path, - ComponentExtensionResourceInfo *resource_info) const + int *resource_id) const { - *resource_info = {}; + *resource_id = 0; // |chrome_resources_path| corresponds to src/chrome/browser/resources in // source tree. base::FilePath resources_path; @@ -304,10 +304,10 @@ base::FilePath ExtensionsBrowserClientQt::GetBundleResourcePath(const network::R const base::FilePath request_relative_path = extensions::file_util::ExtensionURLToRelativeFilePath(request.url); if (!ExtensionsBrowserClient::Get()->GetComponentExtensionResourceManager()->IsComponentExtensionResource( - extension_resources_path, request_relative_path, resource_info)) { + extension_resources_path, request_relative_path, resource_id)) { return base::FilePath(); } - DCHECK_NE(0, resource_info->resource_id); + DCHECK_NE(0, *resource_id); return request_relative_path; } @@ -317,7 +317,7 @@ base::FilePath ExtensionsBrowserClientQt::GetBundleResourcePath(const network::R void ExtensionsBrowserClientQt::LoadResourceFromResourceBundle(const network::ResourceRequest &request, network::mojom::URLLoaderRequest loader, const base::FilePath &resource_relative_path, - const ComponentExtensionResourceInfo &resource_info, + int resource_id, const std::string &content_security_policy, network::mojom::URLLoaderClientPtr client, bool send_cors_header) @@ -356,7 +356,7 @@ PrefService *ExtensionsBrowserClientQt::GetPrefServiceForContext(BrowserContext } void ExtensionsBrowserClientQt::GetEarlyExtensionPrefsObservers(content::BrowserContext *context, - std::vector<ExtensionPrefsObserver *> *observers) const + std::vector<EarlyExtensionPrefsObserver *> *observers) const { } @@ -432,11 +432,6 @@ void ExtensionsBrowserClientQt::BroadcastEventToRenderers(events::HistogramValue // histogram_value, event_name, std::move(args), GURL()); } -net::NetLog *ExtensionsBrowserClientQt::GetNetLog() -{ - return nullptr; -} - ExtensionCache *ExtensionsBrowserClientQt::GetExtensionCache() { // Only used by Chrome via ExtensionService. diff --git a/src/core/extensions/extensions_browser_client_qt.h b/src/core/extensions/extensions_browser_client_qt.h index aa478461f..056e65c9e 100644 --- a/src/core/extensions/extensions_browser_client_qt.h +++ b/src/core/extensions/extensions_browser_client_qt.h @@ -87,8 +87,8 @@ public: const ExtensionSet &extensions, const ProcessMap &process_map) override; PrefService *GetPrefServiceForContext(content::BrowserContext *context) override; - void GetEarlyExtensionPrefsObservers(content::BrowserContext *context, std::vector<ExtensionPrefsObserver *> *observers) const - override; + void GetEarlyExtensionPrefsObservers(content::BrowserContext *context, + std::vector<EarlyExtensionPrefsObserver *> *observers) const override; ProcessManagerDelegate *GetProcessManagerDelegate() const override; std::unique_ptr<ExtensionHostDelegate> CreateExtensionHostDelegate() override; @@ -107,7 +107,6 @@ public: void BroadcastEventToRenderers(events::HistogramValue histogram_value, const std::string &event_name, std::unique_ptr<base::ListValue> args) override; - net::NetLog *GetNetLog() override; ExtensionCache *GetExtensionCache() override; bool IsBackgroundUpdateAllowed() override; bool IsMinBrowserVersionSupported(const std::string &min_version) override; @@ -124,14 +123,14 @@ public: // Return the resource relative path and id for the given request. base::FilePath GetBundleResourcePath(const network::ResourceRequest &request, const base::FilePath &extension_resources_path, - ComponentExtensionResourceInfo *resource_info) const override; + int *resource_id) const override; // Creates and starts a URLLoader to load an extension resource from the // embedder's resource bundle (.pak) files. Used for component extensions. void LoadResourceFromResourceBundle(const network::ResourceRequest &request, network::mojom::URLLoaderRequest loader, const base::FilePath &resource_relative_path, - const ComponentExtensionResourceInfo& resource_info, + int resource_id, const std::string &content_security_policy, network::mojom::URLLoaderClientPtr client, bool send_cors_header) override; diff --git a/src/core/file_picker_controller.cpp b/src/core/file_picker_controller.cpp index 3e64afd20..63b93c502 100644 --- a/src/core/file_picker_controller.cpp +++ b/src/core/file_picker_controller.cpp @@ -39,6 +39,9 @@ #include "file_picker_controller.h" #include "type_conversion.h" +#if defined(OS_WIN) +#include "base/files/file_path.h" +#endif #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/file_select_listener.h" @@ -64,12 +67,31 @@ FilePickerController::~FilePickerController() = default; void FilePickerController::accepted(const QStringList &files) { QStringList stringList; - - for (const QString &file : files) { - if (QDir(file).isAbsolute()) - stringList.append(file); - else - qWarning("Ignore invalid item in FilePickerController::accepted(QStringList): %s", qPrintable(file)); + stringList.reserve(files.count()); + + for (const QString &urlString : files) { + // We accept strings on both absolute-path and file-URL form: + if (QDir::isAbsolutePath(urlString)) { + QString absolutePath = QDir::fromNativeSeparators(urlString); +#if defined(OS_WIN) + if (absolutePath.at(0).isLetter() && absolutePath.at(1) == QLatin1Char(':') && !base::FilePath::IsSeparator(absolutePath.at(2).toLatin1())) + qWarning("Ignoring invalid item in FilePickerController::accepted(QStringList): %s", qPrintable(urlString)); + else +#endif + stringList.append(absolutePath); + } else { + QUrl url(urlString, QUrl::StrictMode); + if (url.isLocalFile() && QDir::isAbsolutePath(url.toLocalFile())) { + QString absolutePath = url.toLocalFile(); +#if defined(OS_WIN) + if (absolutePath.at(0).isLetter() && absolutePath.at(1) == QLatin1Char(':') && !base::FilePath::IsSeparator(absolutePath.at(2).toLatin1())) + qWarning("Ignoring invalid item in FilePickerController::accepted(QStringList): %s", qPrintable(urlString)); + else +#endif + stringList.append(absolutePath); + } else + qWarning("Ignoring invalid item in FilePickerController::accepted(QStringList): %s", qPrintable(urlString)); + } } FilePickerController::filesSelectedInChooser(stringList); @@ -77,21 +99,10 @@ void FilePickerController::accepted(const QStringList &files) void FilePickerController::accepted(const QVariant &files) { - QStringList stringList; - QList<QUrl> urlList = QUrl::fromStringList(files.toStringList()); - - if (urlList.isEmpty()) { - FilePickerController::accepted(stringList); - } else { - for (const QUrl &url : qAsConst(urlList)) { - if (url.isValid() && url.scheme() == "file" && !url.path().isEmpty()) - stringList.append(url.path()); - else - qWarning("Ignore invalid item in FilePickerController::accepted(QVariant): %s", qPrintable(url.toString())); - } + if (!files.canConvert(QVariant::StringList)) + qWarning("An unhandled type '%s' was provided in FilePickerController::accepted(QVariant)", files.typeName()); - FilePickerController::accepted(stringList); - } + accepted(files.toStringList()); } void FilePickerController::rejected() diff --git a/src/core/login_delegate_qt.cpp b/src/core/login_delegate_qt.cpp index 7970b9b46..f63252112 100644 --- a/src/core/login_delegate_qt.cpp +++ b/src/core/login_delegate_qt.cpp @@ -50,7 +50,6 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_request_info.h" -#include "content/public/browser/stream_info.h" #include "extensions/buildflags/buildflags.h" #if BUILDFLAG(ENABLE_EXTENSIONS) #include "extensions/browser/info_map.h" diff --git a/src/core/media_capture_devices_dispatcher.cpp b/src/core/media_capture_devices_dispatcher.cpp index 55c0bb39b..04c68de4c 100644 --- a/src/core/media_capture_devices_dispatcher.cpp +++ b/src/core/media_capture_devices_dispatcher.cpp @@ -74,6 +74,8 @@ namespace QtWebEngineCore { using content::BrowserThread; +using blink::mojom::MediaStreamRequestResult; +using blink::mojom::MediaStreamType; namespace { @@ -94,16 +96,16 @@ void getDevicesForDesktopCapture(blink::MediaStreamDevices *devices, content::De DCHECK_CURRENTLY_ON(BrowserThread::UI); // Add selected desktop source to the list. - devices->push_back(blink::MediaStreamDevice(blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE, mediaId.ToString(), "Screen")); + devices->push_back(blink::MediaStreamDevice(MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE, mediaId.ToString(), "Screen")); if (captureAudio) { if (mediaId.type == content::DesktopMediaID::TYPE_WEB_CONTENTS) { devices->push_back( - blink::MediaStreamDevice(blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE, + blink::MediaStreamDevice(MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE, mediaId.ToString(), "Tab audio")); } else { // Use the special loopback device ID for system audio capture. devices->push_back(blink::MediaStreamDevice( - blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE, + MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE, media::AudioDeviceDescription::kLoopbackInputDeviceId, "System Audio")); } @@ -154,14 +156,14 @@ WebContentsAdapterClient::MediaRequestFlags mediaRequestFlagsForRequest(const co { WebContentsAdapterClient::MediaRequestFlags requestFlags = WebContentsAdapterClient::MediaNone; - if (request.audio_type == blink::MEDIA_DEVICE_AUDIO_CAPTURE) + if (request.audio_type == MediaStreamType::DEVICE_AUDIO_CAPTURE) requestFlags |= WebContentsAdapterClient::MediaAudioCapture; - else if (request.audio_type == blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE) + else if (request.audio_type == MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE) requestFlags |= WebContentsAdapterClient::MediaDesktopAudioCapture; - if (request.video_type == blink::MEDIA_DEVICE_VIDEO_CAPTURE) + if (request.video_type == MediaStreamType::DEVICE_VIDEO_CAPTURE) requestFlags |= WebContentsAdapterClient::MediaVideoCapture; - else if (request.video_type == blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE) + else if (request.video_type == MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE) requestFlags |= WebContentsAdapterClient::MediaDesktopVideoCapture; return requestFlags; @@ -185,7 +187,7 @@ public: } private: - gfx::NativeViewId OnStarted(base::OnceClosure, base::RepeatingClosure) override + gfx::NativeViewId OnStarted(base::OnceClosure, SourceCallback) override { DCHECK(!m_started); m_started = true; @@ -234,13 +236,13 @@ void MediaCaptureDevicesDispatcher::handleMediaAccessPermissionResponse(content: qWarning("Security origin mismatch for media access permission: %s requested and %s provided\n", qPrintable(requestSecurityOrigin.toString()), qPrintable(securityOrigin.toString())); bool microphoneRequested = - (request.audio_type && authorizationFlags & WebContentsAdapterClient::MediaAudioCapture); + (request.audio_type != MediaStreamType::NO_SERVICE && (authorizationFlags & WebContentsAdapterClient::MediaAudioCapture)); bool webcamRequested = - (request.video_type && authorizationFlags & WebContentsAdapterClient::MediaVideoCapture); + (request.video_type != MediaStreamType::NO_SERVICE && (authorizationFlags & WebContentsAdapterClient::MediaVideoCapture)); bool desktopAudioRequested = - (request.audio_type && authorizationFlags & WebContentsAdapterClient::MediaDesktopAudioCapture); + (request.audio_type != MediaStreamType::NO_SERVICE && (authorizationFlags & WebContentsAdapterClient::MediaDesktopAudioCapture)); bool desktopVideoRequested = - (request.video_type && authorizationFlags & WebContentsAdapterClient::MediaDesktopVideoCapture); + (request.video_type != MediaStreamType::NO_SERVICE && (authorizationFlags & WebContentsAdapterClient::MediaDesktopVideoCapture)); if (securityOriginsMatch) { if (microphoneRequested || webcamRequested) { @@ -273,10 +275,10 @@ void MediaCaptureDevicesDispatcher::handleMediaAccessPermissionResponse(content: } if (devices.empty()) - std::move(callback).Run(devices, blink::MEDIA_DEVICE_INVALID_STATE, + std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); else - std::move(callback).Run(devices, blink::MEDIA_DEVICE_OK, + std::move(callback).Run(devices, MediaStreamRequestResult::OK, std::make_unique<MediaStreamUIQt>(webContents, devices)); } @@ -314,17 +316,17 @@ void MediaCaptureDevicesDispatcher::processMediaAccessRequest(WebContentsAdapter DCHECK_CURRENTLY_ON(BrowserThread::UI); // Let's not support tab capture for now. - if (request.video_type == blink::MEDIA_GUM_TAB_VIDEO_CAPTURE || request.audio_type == blink::MEDIA_GUM_TAB_AUDIO_CAPTURE) { - std::move(callback).Run(blink::MediaStreamDevices(), blink::MEDIA_DEVICE_NOT_SUPPORTED, std::unique_ptr<content::MediaStreamUI>()); + if (request.video_type == MediaStreamType::GUM_TAB_VIDEO_CAPTURE || request.audio_type == MediaStreamType::GUM_TAB_AUDIO_CAPTURE) { + std::move(callback).Run(blink::MediaStreamDevices(), MediaStreamRequestResult::NOT_SUPPORTED, std::unique_ptr<content::MediaStreamUI>()); return; } - if (request.video_type == blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE || request.audio_type == blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE) { + if (request.video_type == MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE || request.audio_type == MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE) { const bool screenCaptureEnabled = adapterClient->webEngineSettings()->testAttribute(WebEngineSettings::ScreenCaptureEnabled); const bool originIsSecure = content::IsOriginSecure(request.security_origin); if (!screenCaptureEnabled || !originIsSecure) { - std::move(callback).Run(blink::MediaStreamDevices(), blink::MEDIA_DEVICE_INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); + std::move(callback).Run(blink::MediaStreamDevices(), MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); return; } @@ -344,8 +346,8 @@ void MediaCaptureDevicesDispatcher::processDesktopCaptureAccessRequest(content:: { blink::MediaStreamDevices devices; - if (request.video_type != blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE || request.requested_video_device_id.empty()) { - std::move(callback).Run(devices, blink::MEDIA_DEVICE_INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); + if (request.video_type != MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE || request.requested_video_device_id.empty()) { + std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); return; } @@ -366,20 +368,20 @@ void MediaCaptureDevicesDispatcher::processDesktopCaptureAccessRequest(content:: // Received invalid device id. if (mediaId.type == content::DesktopMediaID::TYPE_NONE) { - std::move(callback).Run(devices, blink::MEDIA_DEVICE_INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); + std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); return; } // Audio is only supported for screen capture streams. - bool capture_audio = (mediaId.type == content::DesktopMediaID::TYPE_SCREEN && request.audio_type == blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE); + bool capture_audio = (mediaId.type == content::DesktopMediaID::TYPE_SCREEN && request.audio_type == MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE); getDevicesForDesktopCapture(&devices, mediaId, capture_audio); if (devices.empty()) - std::move(callback).Run(devices, blink::MEDIA_DEVICE_INVALID_STATE, + std::move(callback).Run(devices, MediaStreamRequestResult::INVALID_STATE, std::unique_ptr<content::MediaStreamUI>()); else - std::move(callback).Run(devices, blink::MEDIA_DEVICE_OK, + std::move(callback).Run(devices, MediaStreamRequestResult::OK, std::make_unique<MediaStreamUIQt>(webContents, devices)); } @@ -433,7 +435,7 @@ void MediaCaptureDevicesDispatcher::getDefaultDevices(const std::string &audioDe } } -void MediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(int render_process_id, int render_frame_id, int page_request_id, const GURL &security_origin, blink::MediaStreamType stream_type, content::MediaRequestState state) +void MediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(int render_process_id, int render_frame_id, int page_request_id, const GURL &security_origin, blink::mojom::MediaStreamType stream_type, content::MediaRequestState state) { DCHECK_CURRENTLY_ON(BrowserThread::IO); base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, @@ -446,7 +448,7 @@ void MediaCaptureDevicesDispatcher::updateMediaRequestStateOnUIThread(int render int render_frame_id, int page_request_id, const GURL & /*security_origin*/, - blink::MediaStreamType /*stream_type*/, + blink::mojom::MediaStreamType /*stream_type*/, content::MediaRequestState state) { DCHECK_CURRENTLY_ON(BrowserThread::UI); diff --git a/src/core/media_capture_devices_dispatcher.h b/src/core/media_capture_devices_dispatcher.h index 07afd54bf..6a67a53e9 100644 --- a/src/core/media_capture_devices_dispatcher.h +++ b/src/core/media_capture_devices_dispatcher.h @@ -81,20 +81,20 @@ private: int render_frame_id, int page_request_id, const GURL &security_origin, - blink::MediaStreamType stream_type, + blink::mojom::MediaStreamType stream_type, content::MediaRequestState state) override; void OnCreatingAudioStream(int /*render_process_id*/, int /*render_frame_id*/) override {} void OnSetCapturingLinkSecured(int /*render_process_id*/, int /*render_frame_id*/, int /*page_request_id*/, - blink::MediaStreamType /*stream_type*/, + blink::mojom::MediaStreamType /*stream_type*/, bool /*is_secure*/) override {} friend struct base::DefaultSingletonTraits<MediaCaptureDevicesDispatcher>; typedef base::RepeatingCallback<void(const blink::MediaStreamDevices &devices, - blink::MediaStreamRequestResult result, + blink::mojom::MediaStreamRequestResult result, std::unique_ptr<content::MediaStreamUI> ui)> RepeatingMediaResponseCallback; @@ -121,7 +121,7 @@ private: // Called by the MediaObserver() functions, executed on UI thread. void updateMediaRequestStateOnUIThread(int render_process_id, int render_frame_id, int page_request_id, const GURL &security_origin, - blink::MediaStreamType stream_type, content::MediaRequestState state); + blink::mojom::MediaStreamType stream_type, content::MediaRequestState state); RequestsQueues m_pendingRequests; diff --git a/src/core/net/restricted_cookie_manager_qt.cpp b/src/core/net/restricted_cookie_manager_qt.cpp new file mode 100644 index 000000000..e01969f4d --- /dev/null +++ b/src/core/net/restricted_cookie_manager_qt.cpp @@ -0,0 +1,184 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +// originally based on android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc: +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "restricted_cookie_manager_qt.h" + +#include "api/qwebenginecookiestore.h" +#include "api/qwebenginecookiestore_p.h" +#include "profile_adapter.h" +#include "profile_qt.h" +#include "type_conversion.h" + +#include "base/memory/ptr_util.h" +#include "base/task/post_task.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "mojo/public/cpp/bindings/strong_binding.h" + +namespace QtWebEngineCore { + +class RestrictedCookieManagerListenerQt : public network::mojom::CookieChangeListener { +public: + RestrictedCookieManagerListenerQt(const GURL &url, + const GURL &site_for_cookies, + base::WeakPtr<RestrictedCookieManagerQt> restricted_cookie_manager, + network::mojom::CookieChangeListenerPtr client_listener) + : url_(url) + , site_for_cookies_(site_for_cookies) + , restricted_cookie_manager_(restricted_cookie_manager) + , client_listener_(std::move(client_listener)) + {} + + void OnCookieChange(const net::CanonicalCookie &cookie, network::mojom::CookieChangeCause cause) override + { + if (restricted_cookie_manager_ && restricted_cookie_manager_->allowCookies(url_, site_for_cookies_)) + client_listener_->OnCookieChange(cookie, cause); + } + +private: + const GURL url_; + const GURL site_for_cookies_; + base::WeakPtr<RestrictedCookieManagerQt> restricted_cookie_manager_; + network::mojom::CookieChangeListenerPtr client_listener_; +}; + +RestrictedCookieManagerQt::RestrictedCookieManagerQt(base::WeakPtr<ProfileIODataQt> profileIoData, + network::mojom::RestrictedCookieManagerRole role, + net::CookieStore *cookie_store, + network::CookieSettings *cookie_settings, + const url::Origin &origin, + bool is_service_worker, + int32_t process_id, + int32_t frame_id) + : network::RestrictedCookieManager(role, cookie_store, cookie_settings, origin, + nullptr, is_service_worker, process_id, frame_id) + , m_profileIoData(profileIoData) + , weak_factory_(this) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +} + +RestrictedCookieManagerQt::~RestrictedCookieManagerQt() +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +} + +void RestrictedCookieManagerQt::GetAllForUrl(const GURL &url, + const GURL &site_for_cookies, + network::mojom::CookieManagerGetOptionsPtr options, + GetAllForUrlCallback callback) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + if (allowCookies(url, site_for_cookies)) { + network::RestrictedCookieManager::GetAllForUrl(url, site_for_cookies, std::move(options), std::move(callback)); + } else { + std::move(callback).Run(std::vector<net::CanonicalCookie>()); + } +} + +void RestrictedCookieManagerQt::SetCanonicalCookie(const net::CanonicalCookie &cookie, + const GURL &url, + const GURL &site_for_cookies, + SetCanonicalCookieCallback callback) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + if (allowCookies(url, site_for_cookies)) { + network::RestrictedCookieManager::SetCanonicalCookie(cookie, url, site_for_cookies, std::move(callback)); + } else { + std::move(callback).Run(false); + } +} + +void RestrictedCookieManagerQt::AddChangeListener(const GURL &url, + const GURL &site_for_cookies, + network::mojom::CookieChangeListenerPtr listener, + AddChangeListenerCallback callback) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + network::mojom::CookieChangeListenerPtr proxy_listener_ptr; + auto proxy_listener = + std::make_unique<RestrictedCookieManagerListenerQt>( + url, site_for_cookies, weak_factory_.GetWeakPtr(), + std::move(listener)); + + mojo::MakeStrongBinding(std::move(proxy_listener), + mojo::MakeRequest(&proxy_listener_ptr)); + + network::RestrictedCookieManager::AddChangeListener( + url, site_for_cookies, std::move(proxy_listener_ptr), + std::move(callback)); +} + +void RestrictedCookieManagerQt::GetCookiesString(const GURL &url, + const GURL &site_for_cookies, + GetCookiesStringCallback callback) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + if (allowCookies(url, site_for_cookies)) { + network::RestrictedCookieManager::GetCookiesString(url, site_for_cookies, std::move(callback)); + } else { + std::move(callback).Run(""); + } +} + +void RestrictedCookieManagerQt::CookiesEnabledFor(const GURL &url, + const GURL &site_for_cookies, + CookiesEnabledForCallback callback) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + std::move(callback).Run(allowCookies(url, site_for_cookies)); +} + +bool RestrictedCookieManagerQt::allowCookies(const GURL &url, const GURL &site_for_cookies) const +{ + if (!m_profileIoData) + return false; + return m_profileIoData->canGetCookies(toQt(site_for_cookies), toQt(url)); +} + +} // namespace QtWebEngineCore diff --git a/src/core/net/restricted_cookie_manager_qt.h b/src/core/net/restricted_cookie_manager_qt.h new file mode 100644 index 000000000..a277c7c96 --- /dev/null +++ b/src/core/net/restricted_cookie_manager_qt.h @@ -0,0 +1,100 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtWebEngine module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef RESTRICTED_COOKIE_MANAGER_QT_H +#define RESTRICTED_COOKIE_MANAGER_QT_H + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "services/network/restricted_cookie_manager.h" +#include "url/gurl.h" + +namespace QtWebEngineCore { + +class ProfileIODataQt; + +class RestrictedCookieManagerQt : public network::RestrictedCookieManager +{ +public: + RestrictedCookieManagerQt(base::WeakPtr<ProfileIODataQt> profileIoData, + network::mojom::RestrictedCookieManagerRole role, + net::CookieStore *cookie_store, + network::CookieSettings *cookie_settings, + const url::Origin &origin, + bool is_service_worker, + int32_t process_id, + int32_t frame_id); + ~RestrictedCookieManagerQt() override; + + // network::mojom::RestrictedCookieManager interface: + void GetAllForUrl(const GURL &url, + const GURL &site_for_cookies, + network::mojom::CookieManagerGetOptionsPtr options, + GetAllForUrlCallback callback) override; + void SetCanonicalCookie(const net::CanonicalCookie& cookie, + const GURL &url, + const GURL &site_for_cookies, + SetCanonicalCookieCallback callback) override; + void AddChangeListener(const GURL &url, + const GURL &site_for_cookies, + network::mojom::CookieChangeListenerPtr listener, + AddChangeListenerCallback callback) override; + + void GetCookiesString(const GURL &url, + const GURL &site_for_cookies, + GetCookiesStringCallback callback) override; + + void CookiesEnabledFor(const GURL &url, + const GURL &site_for_cookies, + CookiesEnabledForCallback callback) override; + + // Internal: + bool allowCookies(const GURL& url, const GURL &site_for_cookies) const; + +private: + base::WeakPtr<ProfileIODataQt> m_profileIoData; + + base::WeakPtrFactory<RestrictedCookieManagerQt> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(RestrictedCookieManagerQt); +}; + +} // namespace QtWebEngineCore + +#endif // RESTRICTED_COOKIE_MANAGER_QT_H diff --git a/src/core/net/ssl_host_state_delegate_qt.cpp b/src/core/net/ssl_host_state_delegate_qt.cpp index ecc3c681e..b6cdf68dc 100644 --- a/src/core/net/ssl_host_state_delegate_qt.cpp +++ b/src/core/net/ssl_host_state_delegate_qt.cpp @@ -120,7 +120,7 @@ void SSLHostStateDelegateQt::HostRanInsecureContent(const std::string &host, int } // Returns whether the specified host ran insecure content. -bool SSLHostStateDelegateQt::DidHostRunInsecureContent(const std::string &host, int pid, InsecureContentType content_type) const +bool SSLHostStateDelegateQt::DidHostRunInsecureContent(const std::string &host, int pid, InsecureContentType content_type) { return false; } @@ -136,7 +136,7 @@ void SSLHostStateDelegateQt::RevokeUserAllowExceptions(const std::string &host) // |host|. This does not mean that *all* certificate errors are allowed, just // that there exists an exception. To see if a particular certificate and // error combination exception is allowed, use QueryPolicy(). -bool SSLHostStateDelegateQt::HasAllowException(const std::string &host) const +bool SSLHostStateDelegateQt::HasAllowException(const std::string &host) { auto policy_iterator = m_certPolicyforHost.find(host); return policy_iterator != m_certPolicyforHost.end() && diff --git a/src/core/net/ssl_host_state_delegate_qt.h b/src/core/net/ssl_host_state_delegate_qt.h index b1b49bcf3..28e239304 100644 --- a/src/core/net/ssl_host_state_delegate_qt.h +++ b/src/core/net/ssl_host_state_delegate_qt.h @@ -69,9 +69,9 @@ public: CertJudgment QueryPolicy(const std::string &host, const net::X509Certificate &cert, int error, bool *expired_previous_decision) override; void HostRanInsecureContent(const std::string& host, int child_id, InsecureContentType content_type) override; - bool DidHostRunInsecureContent(const std::string& host, int child_id, InsecureContentType content_type) const override; + bool DidHostRunInsecureContent(const std::string& host, int child_id, InsecureContentType content_type) override; void RevokeUserAllowExceptions(const std::string &host) override; - bool HasAllowException(const std::string &host) const override; + bool HasAllowException(const std::string &host) override; private: std::map<std::string, CertPolicy> m_certPolicyforHost; diff --git a/src/core/net/url_request_custom_job.cpp b/src/core/net/url_request_custom_job.cpp index dd213d4f8..56ba79f35 100644 --- a/src/core/net/url_request_custom_job.cpp +++ b/src/core/net/url_request_custom_job.cpp @@ -159,7 +159,7 @@ void URLRequestCustomJob::GetResponseInfo(HttpResponseInfo* info) headers += "Access-Control-Allow-Credentials: true\n"; } - info->headers = new HttpResponseHeaders(HttpUtil::AssembleRawHeaders(headers.c_str(), headers.size())); + info->headers = new HttpResponseHeaders(HttpUtil::AssembleRawHeaders(headers)); } bool URLRequestCustomJob::IsRedirectResponse(GURL* location, int* http_status_code, bool* /*insecure_scheme_was_upgraded*/) diff --git a/src/core/net/webui_controller_factory_qt.cpp b/src/core/net/webui_controller_factory_qt.cpp index 92bb8854f..2bfd242e7 100644 --- a/src/core/net/webui_controller_factory_qt.cpp +++ b/src/core/net/webui_controller_factory_qt.cpp @@ -175,24 +175,24 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co namespace QtWebEngineCore { -WebUI::TypeID WebUIControllerFactoryQt::GetWebUIType(content::BrowserContext *browser_context, const GURL &url) const +WebUI::TypeID WebUIControllerFactoryQt::GetWebUIType(content::BrowserContext *browser_context, const GURL &url) { Profile *profile = Profile::FromBrowserContext(browser_context); WebUIFactoryFunction function = GetWebUIFactoryFunction(nullptr, profile, url); return function ? reinterpret_cast<WebUI::TypeID>(function) : WebUI::kNoWebUI; } -bool WebUIControllerFactoryQt::UseWebUIForURL(content::BrowserContext *browser_context, const GURL &url) const +bool WebUIControllerFactoryQt::UseWebUIForURL(content::BrowserContext *browser_context, const GURL &url) { return GetWebUIType(browser_context, url) != WebUI::kNoWebUI; } -bool WebUIControllerFactoryQt::UseWebUIBindingsForURL(content::BrowserContext *browser_context, const GURL &url) const +bool WebUIControllerFactoryQt::UseWebUIBindingsForURL(content::BrowserContext *browser_context, const GURL &url) { return UseWebUIForURL(browser_context, url); } -std::unique_ptr<WebUIController> WebUIControllerFactoryQt::CreateWebUIControllerForURL(WebUI *web_ui, const GURL &url) const +std::unique_ptr<WebUIController> WebUIControllerFactoryQt::CreateWebUIControllerForURL(WebUI *web_ui, const GURL &url) { Profile *profile = Profile::FromWebUI(web_ui); WebUIFactoryFunction function = GetWebUIFactoryFunction(web_ui, profile, url); diff --git a/src/core/net/webui_controller_factory_qt.h b/src/core/net/webui_controller_factory_qt.h index 4038e6538..20ea62193 100644 --- a/src/core/net/webui_controller_factory_qt.h +++ b/src/core/net/webui_controller_factory_qt.h @@ -57,10 +57,10 @@ namespace QtWebEngineCore { class WebUIControllerFactoryQt : public content::WebUIControllerFactory { public: - content::WebUI::TypeID GetWebUIType(content::BrowserContext *browserContext, const GURL &url) const override; - bool UseWebUIForURL(content::BrowserContext *browserContext, const GURL &url) const override; - bool UseWebUIBindingsForURL(content::BrowserContext *browserContext, const GURL &url) const override; - std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(content::WebUI *webUi, const GURL &url) const override; + content::WebUI::TypeID GetWebUIType(content::BrowserContext *browserContext, const GURL &url) override; + bool UseWebUIForURL(content::BrowserContext *browserContext, const GURL &url) override; + bool UseWebUIBindingsForURL(content::BrowserContext *browserContext, const GURL &url) override; + std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(content::WebUI *webUi, const GURL &url) override; static WebUIControllerFactoryQt *GetInstance(); diff --git a/src/core/ozone/gl_surface_egl_qt.cpp b/src/core/ozone/gl_surface_egl_qt.cpp index 97c6cdee6..a6988bbf3 100644 --- a/src/core/ozone/gl_surface_egl_qt.cpp +++ b/src/core/ozone/gl_surface_egl_qt.cpp @@ -169,6 +169,11 @@ bool GLSurfaceEGL::IsPixelFormatFloatSupported() return false; } +bool GLSurfaceEGL::IsANGLEFeatureControlSupported() +{ + return false; +} + void GLSurfaceEGL::ShutdownOneOff() { } diff --git a/src/core/ozone/gl_surface_qt.cpp b/src/core/ozone/gl_surface_qt.cpp index 82f8cd0e5..58a225b4e 100644 --- a/src/core/ozone/gl_surface_qt.cpp +++ b/src/core/ozone/gl_surface_qt.cpp @@ -63,7 +63,7 @@ #if defined(OS_WIN) #include "ozone/gl_surface_wgl_qt.h" -#include "gpu/ipc/service/direct_composition_surface_win.h" +#include "ui/gl/direct_composition_surface_win.h" #include "ui/gl/vsync_provider_win.h" #endif @@ -219,11 +219,24 @@ scoped_refptr<gl::GLSurface> ImageTransportSurface::CreateNativeSurface(base::We QT_NOT_USED return scoped_refptr<gl::GLSurface>(); } +} // namespace gpu + +namespace gl { + +bool DirectCompositionSurfaceWin::IsDirectCompositionSupported() +{ + return false; +} + +bool DirectCompositionSurfaceWin::IsDecodeSwapChainSupported() +{ + return false; +} bool DirectCompositionSurfaceWin::IsHDRSupported() { return false; } -} // namespace gpu +} // namespace gl #endif #endif // !defined(OS_MACOSX) diff --git a/src/core/ozone/ozone_platform_qt.cpp b/src/core/ozone/ozone_platform_qt.cpp index eb7610c0f..2ab274b8f 100644 --- a/src/core/ozone/ozone_platform_qt.cpp +++ b/src/core/ozone/ozone_platform_qt.cpp @@ -40,14 +40,15 @@ #include "ozone_platform_qt.h" #if defined(USE_OZONE) +#include "ui/base/ime/input_method.h" #include "ui/display/types/native_display_delegate.h" -#include "ui/events/system_input_injector.h" #include "ui/ozone/common/stub_client_native_pixmap_factory.h" #include "ui/ozone/common/stub_overlay_manager.h" #include "ui/ozone/public/cursor_factory_ozone.h" #include "ui/ozone/public/gpu_platform_support_host.h" #include "ui/ozone/public/input_controller.h" #include "ui/ozone/public/ozone_platform.h" +#include "ui/ozone/public/system_input_injector.h" #include "ui/platform_window/platform_window_delegate.h" #include "ui/platform_window/platform_window_init_properties.h" #include "ui/platform_window/platform_window.h" @@ -72,6 +73,7 @@ public: ui::InputController* GetInputController() override; std::unique_ptr<ui::SystemInputInjector> CreateSystemInputInjector() override; ui::OverlayManagerOzone* GetOverlayManager() override; + std::unique_ptr<InputMethod> CreateInputMethod(internal::InputMethodDelegate *delegate) override; private: void InitializeUI(const ui::OzonePlatform::InitParams &) override; @@ -146,6 +148,12 @@ void OzonePlatformQt::InitializeGPU(const ui::OzonePlatform::InitParams &) surface_factory_ozone_.reset(new QtWebEngineCore::SurfaceFactoryQt()); } +std::unique_ptr<InputMethod> OzonePlatformQt::CreateInputMethod(internal::InputMethodDelegate *) +{ + NOTREACHED(); + return nullptr; +} + } // namespace OzonePlatform* CreateOzonePlatformQt() { return new OzonePlatformQt; } diff --git a/src/core/ozone/platform_window_qt.h b/src/core/ozone/platform_window_qt.h index bb2fc714b..ca4a00313 100644 --- a/src/core/ozone/platform_window_qt.h +++ b/src/core/ozone/platform_window_qt.h @@ -70,13 +70,14 @@ public: void Maximize() override { } void Minimize() override { } void Restore() override { } - PlatformWindowState GetPlatformWindowState() const override { return PLATFORM_WINDOW_STATE_UNKNOWN; } + PlatformWindowState GetPlatformWindowState() const override { return PlatformWindowState::kUnknown; } void SetCursor(PlatformCursor) override { } void MoveCursorTo(const gfx::Point&) override { } void ConfineCursorToBounds(const gfx::Rect&) override { } - PlatformImeController* GetPlatformImeController() override { return nullptr; } void SetRestoredBoundsInPixels(const gfx::Rect& bounds) override { } gfx::Rect GetRestoredBoundsInPixels() const override { return gfx::Rect(); } + void Activate() override { } + void Deactivate() override { } // PlatformEventDispatcher: bool CanDispatchEvent(const PlatformEvent& event) override; diff --git a/src/core/permission_manager_qt.cpp b/src/core/permission_manager_qt.cpp index be4d6e598..9e8687a47 100644 --- a/src/core/permission_manager_qt.cpp +++ b/src/core/permission_manager_qt.cpp @@ -78,6 +78,9 @@ ProfileAdapter::PermissionType toQt(content::PermissionType type) case content::PermissionType::PAYMENT_HANDLER: case content::PermissionType::BACKGROUND_FETCH: case content::PermissionType::IDLE_DETECTION: + case content::PermissionType::PERIODIC_BACKGROUND_SYNC: + case content::PermissionType::WAKE_LOCK_SCREEN: + case content::PermissionType::WAKE_LOCK_SYSTEM: case content::PermissionType::NUM: NOTIMPLEMENTED() << "Unsupported permission type: " << static_cast<int>(type); break; @@ -104,15 +107,15 @@ void PermissionManagerQt::permissionRequestReply(const QUrl &origin, ProfileAdap auto it = m_requests.begin(); while (it != m_requests.end()) { if (it->origin == origin && it->type == type) { - it->callback.Run(status); + std::move(it->callback).Run(status); it = m_requests.erase(it); } else ++it; } } - for (const RequestOrSubscription &subscriber : qAsConst(m_subscribers)) { - if (subscriber.origin == origin && subscriber.type == type) - subscriber.callback.Run(status); + for (const auto &it: m_subscribers) { + if (it.second.origin == origin && it.second.type == type) + it.second.callback.Run(status); } auto it = m_multiRequests.begin(); @@ -139,7 +142,7 @@ void PermissionManagerQt::permissionRequestReply(const QUrl &origin, ProfileAdap result.push_back(blink::mojom::PermissionStatus::DENIED); } if (answerable) { - it->callback.Run(result); + std::move(it->callback).Run(result); it = m_multiRequests.erase(it); continue; } @@ -158,7 +161,7 @@ int PermissionManagerQt::RequestPermission(content::PermissionType permission, content::RenderFrameHost *frameHost, const GURL& requesting_origin, bool /*user_gesture*/, - const base::Callback<void(blink::mojom::PermissionStatus)>& callback) + base::OnceCallback<void(blink::mojom::PermissionStatus)> callback) { WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>( content::WebContents::FromRenderFrameHost(frameHost)->GetDelegate()); @@ -166,15 +169,15 @@ int PermissionManagerQt::RequestPermission(content::PermissionType permission, ProfileAdapter::PermissionType permissionType = toQt(permission); if (permissionType == ProfileAdapter::UnsupportedPermission) { - callback.Run(blink::mojom::PermissionStatus::DENIED); + std::move(callback).Run(blink::mojom::PermissionStatus::DENIED); return content::PermissionController::kNoPendingOperation; } else if (permissionType == ProfileAdapter::ClipboardRead) { WebEngineSettings *settings = contentsDelegate->webEngineSettings(); if (settings->testAttribute(WebEngineSettings::JavascriptCanAccessClipboard) && settings->testAttribute(WebEngineSettings::JavascriptCanPaste)) - callback.Run(blink::mojom::PermissionStatus::GRANTED); + std::move(callback).Run(blink::mojom::PermissionStatus::GRANTED); else - callback.Run(blink::mojom::PermissionStatus::DENIED); + std::move(callback).Run(blink::mojom::PermissionStatus::DENIED); return content::PermissionController::kNoPendingOperation; } // Audio and video-capture should not come this way currently @@ -182,16 +185,12 @@ int PermissionManagerQt::RequestPermission(content::PermissionType permission, && permissionType != ProfileAdapter::VideoCapturePermission); int request_id = ++m_requestIdCount; - RequestOrSubscription request = { - permissionType, - toQt(requesting_origin), - callback - }; - m_requests.insert(request_id, request); + auto requestOrigin = toQt(requesting_origin); + m_requests.push_back({ request_id, permissionType, requestOrigin, std::move(callback) }); if (permissionType == ProfileAdapter::GeolocationPermission) - contentsDelegate->requestGeolocationPermission(request.origin); + contentsDelegate->requestGeolocationPermission(requestOrigin); else if (permissionType == ProfileAdapter::NotificationPermission) - contentsDelegate->requestUserNotificationPermission(request.origin); + contentsDelegate->requestUserNotificationPermission(requestOrigin); return request_id; } @@ -200,7 +199,7 @@ int PermissionManagerQt::RequestPermissions(const std::vector<content::Permissio content::RenderFrameHost* frameHost, const GURL& requesting_origin, bool /*user_gesture*/, - const base::Callback<void(const std::vector<blink::mojom::PermissionStatus>&)>& callback) + base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback) { WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>( content::WebContents::FromRenderFrameHost(frameHost)->GetDelegate()); @@ -226,23 +225,19 @@ int PermissionManagerQt::RequestPermissions(const std::vector<content::Permissio } } if (answerable) { - callback.Run(result); + std::move(callback).Run(result); return content::PermissionController::kNoPendingOperation; } int request_id = ++m_requestIdCount; - MultiRequest request = { - permissions, - toQt(requesting_origin), - callback - }; - m_multiRequests.insert(request_id, request); + auto requestOrigin = toQt(requesting_origin); + m_multiRequests.push_back({ request_id, permissions, requestOrigin, std::move(callback) }); for (content::PermissionType permission : permissions) { const ProfileAdapter::PermissionType permissionType = toQt(permission); if (permissionType == ProfileAdapter::GeolocationPermission) - contentsDelegate->requestGeolocationPermission(request.origin); + contentsDelegate->requestGeolocationPermission(requestOrigin); else if (permissionType == ProfileAdapter::NotificationPermission) - contentsDelegate->requestUserNotificationPermission(request.origin); + contentsDelegate->requestUserNotificationPermission(requestOrigin); } return request_id; } @@ -304,21 +299,17 @@ int PermissionManagerQt::SubscribePermissionStatusChange( content::PermissionType permission, content::RenderFrameHost * /* render_frame_host */, const GURL& requesting_origin, - const base::Callback<void(blink::mojom::PermissionStatus)>& callback) + base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback) { int subscriber_id = ++m_subscriberIdCount; - RequestOrSubscription subscriber = { - toQt(permission), - toQt(requesting_origin), - callback - }; - m_subscribers.insert(subscriber_id, subscriber); + m_subscribers.insert( { subscriber_id, + Subscription { toQt(permission), toQt(requesting_origin), std::move(callback) } }); return subscriber_id; } void PermissionManagerQt::UnsubscribePermissionStatusChange(int subscription_id) { - if (!m_subscribers.remove(subscription_id)) + if (!m_subscribers.erase(subscription_id)) LOG(WARNING) << "PermissionManagerQt::UnsubscribePermissionStatusChange called on unknown subscription id" << subscription_id; } diff --git a/src/core/permission_manager_qt.h b/src/core/permission_manager_qt.h index 89eb6cf85..6ab071237 100644 --- a/src/core/permission_manager_qt.h +++ b/src/core/permission_manager_qt.h @@ -45,7 +45,7 @@ #include "profile_adapter.h" -#include <QHash> +#include <map> namespace QtWebEngineCore { @@ -65,7 +65,7 @@ public: content::RenderFrameHost* render_frame_host, const GURL& requesting_origin, bool user_gesture, - const base::Callback<void(blink::mojom::PermissionStatus)>& callback) override; + base::OnceCallback<void(blink::mojom::PermissionStatus)> callback) override; blink::mojom::PermissionStatus GetPermissionStatus( content::PermissionType permission, @@ -87,32 +87,39 @@ public: content::RenderFrameHost* render_frame_host, const GURL& requesting_origin, bool user_gesture, - const base::Callback<void( - const std::vector<blink::mojom::PermissionStatus>&)>& callback) override; + base::OnceCallback<void( + const std::vector<blink::mojom::PermissionStatus>&)> callback) override; int SubscribePermissionStatusChange( content::PermissionType permission, content::RenderFrameHost* render_frame_host, const GURL& requesting_origin, - const base::Callback<void(blink::mojom::PermissionStatus)>& callback) override; + const base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback) override; void UnsubscribePermissionStatusChange(int subscription_id) override; private: QHash<QPair<QUrl, PermissionType>, bool> m_permissions; - struct RequestOrSubscription { + struct Request { + int id; PermissionType type; QUrl origin; - base::Callback<void(blink::mojom::PermissionStatus)> callback; + base::OnceCallback<void(blink::mojom::PermissionStatus)> callback; }; struct MultiRequest { + int id; std::vector<content::PermissionType> types; QUrl origin; - base::Callback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback; + base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)> callback; }; - QHash<int, RequestOrSubscription> m_requests; - QHash<int, RequestOrSubscription> m_subscribers; - QHash<int, MultiRequest> m_multiRequests; + struct Subscription { + PermissionType type; + QUrl origin; + base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback; + }; + std::vector<Request> m_requests; + std::vector<MultiRequest> m_multiRequests; + std::map<int, Subscription> m_subscribers; int m_requestIdCount; int m_subscriberIdCount; diff --git a/src/core/pref_service_adapter.cpp b/src/core/pref_service_adapter.cpp index 8a33a4b60..ca4be87df 100644 --- a/src/core/pref_service_adapter.cpp +++ b/src/core/pref_service_adapter.cpp @@ -106,6 +106,7 @@ void PrefServiceAdapter::setup(const ProfileAdapter &profileAdapter) registry->RegisterBooleanPref(spellcheck::prefs::kSpellCheckUseSpellingService, false); #endif // QT_CONFIG(webengine_spellchecker) registry->RegisterBooleanPref(prefs::kShowInternalAccessibilityTree, false); + registry->RegisterBooleanPref(prefs::kAccessibilityImageLabelsEnabled, false); registry->RegisterIntegerPref(prefs::kNotificationNextPersistentId, 10000); #if BUILDFLAG(ENABLE_EXTENSIONS) diff --git a/src/core/printing/print_view_manager_base_qt.cpp b/src/core/printing/print_view_manager_base_qt.cpp index 52f4481bb..4516f10b2 100644 --- a/src/core/printing/print_view_manager_base_qt.cpp +++ b/src/core/printing/print_view_manager_base_qt.cpp @@ -343,9 +343,10 @@ void PrintViewManagerBaseQt::ShouldQuitFromInnerMessageLoop() } } -bool PrintViewManagerBaseQt::CreateNewPrintJob(printing::PrinterQuery *job) +bool PrintViewManagerBaseQt::CreateNewPrintJob(std::unique_ptr<printing::PrinterQuery> query) { DCHECK(!m_isInsideInnerMessageLoop); + DCHECK(query); // Disconnect the current |m_printJob|. DisconnectFromCurrentPrintJob(); @@ -359,12 +360,9 @@ bool PrintViewManagerBaseQt::CreateNewPrintJob(printing::PrinterQuery *job) // Ask the renderer to generate the print preview, create the print preview // view and switch to it, initialize the printer and show the print dialog. DCHECK(!m_printJob.get()); - DCHECK(job); - if (!job) - return false; m_printJob = base::MakeRefCounted<printing::PrintJob>(); - m_printJob->Initialize(job, RenderSourceName(), number_pages_); + m_printJob->Initialize(std::move(query), RenderSourceName(), number_pages_); m_registrar.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<printing::PrintJob>(m_printJob.get())); m_didPrintingSucceed = false; @@ -482,13 +480,13 @@ bool PrintViewManagerBaseQt::OpportunisticallyCreatePrintJob(int cookie) // The job was initiated by a script. Time to get the corresponding worker // thread. - scoped_refptr<printing::PrinterQuery> queued_query = m_printerQueriesQueue->PopPrinterQuery(cookie); - if (!queued_query.get()) { + std::unique_ptr<printing::PrinterQuery> queued_query = m_printerQueriesQueue->PopPrinterQuery(cookie); + if (!queued_query) { NOTREACHED(); return false; } - if (!CreateNewPrintJob(queued_query.get())) { + if (!CreateNewPrintJob(std::move(queued_query))) { // Don't kill anything. return false; } @@ -512,23 +510,23 @@ void PrintViewManagerBaseQt::ReleasePrinterQuery() if (!printJobManager) return; - scoped_refptr<printing::PrinterQuery> printerQuery; + std::unique_ptr<printing::PrinterQuery> printerQuery; printerQuery = m_printerQueriesQueue->PopPrinterQuery(cookie); - if (!printerQuery.get()) + if (!printerQuery) return; base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&printing::PrinterQuery::StopWorker, printerQuery.get())); + base::BindOnce(&printing::PrinterQuery::StopWorker, std::move(printerQuery))); } // Originally from print_preview_message_handler.cc: void PrintViewManagerBaseQt::StopWorker(int documentCookie) { if (documentCookie <= 0) return; - scoped_refptr<printing::PrinterQuery> printer_query = + std::unique_ptr<printing::PrinterQuery> printer_query = m_printerQueriesQueue->PopPrinterQuery(documentCookie); if (printer_query.get()) { base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&printing::PrinterQuery::StopWorker, printer_query)); + base::BindOnce(&printing::PrinterQuery::StopWorker, std::move(printer_query))); } } diff --git a/src/core/printing/print_view_manager_base_qt.h b/src/core/printing/print_view_manager_base_qt.h index 3ade02f0d..31e0a1778 100644 --- a/src/core/printing/print_view_manager_base_qt.h +++ b/src/core/printing/print_view_manager_base_qt.h @@ -147,7 +147,7 @@ protected: void TerminatePrintJob(bool cancel); void DisconnectFromCurrentPrintJob(); - bool CreateNewPrintJob(printing::PrinterQuery *job); + bool CreateNewPrintJob(std::unique_ptr<printing::PrinterQuery> query); void ReleasePrintJob(); void ReleasePrinterQuery(); @@ -164,7 +164,7 @@ private: bool m_didPrintingSucceed; scoped_refptr<printing::PrintQueriesQueue> m_printerQueriesQueue; // The current RFH that is printing with a system printing dialog. - content::RenderFrameHost* m_printingRFH; + content::RenderFrameHost *m_printingRFH; DISALLOW_COPY_AND_ASSIGN(PrintViewManagerBaseQt); }; diff --git a/src/core/printing/printing_message_filter_qt.cpp b/src/core/printing/printing_message_filter_qt.cpp index d1e86343f..5b9228d20 100644 --- a/src/core/printing/printing_message_filter_qt.cpp +++ b/src/core/printing/printing_message_filter_qt.cpp @@ -92,10 +92,10 @@ bool PrintingMessageFilterQt::OnMessageReceived(const IPC::Message& message) { void PrintingMessageFilterQt::OnGetDefaultPrintSettings(IPC::Message* reply_msg) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - scoped_refptr<printing::PrinterQuery> printer_query; + std::unique_ptr<printing::PrinterQuery> printer_query; printer_query = queue_->PopPrinterQuery(0); - if (!printer_query.get()) { + if (!printer_query) { printer_query = queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id()); } @@ -109,14 +109,14 @@ void PrintingMessageFilterQt::OnGetDefaultPrintSettings(IPC::Message* reply_msg) printing::DEFAULT_MARGINS, false, false, - base::Bind(&PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply, - this, - printer_query, - reply_msg)); + base::BindOnce(&PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply, + this, + std::move(printer_query), + reply_msg)); } void PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply( - scoped_refptr<printing::PrinterQuery> printer_query, + std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg) { PrintMsg_Print_Params params; if (!printer_query.get() || @@ -132,7 +132,7 @@ void PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply( if (printer_query.get()) { // If user hasn't cancelled. if (printer_query->cookie() && printer_query->settings().dpi()) { - queue_->QueuePrinterQuery(printer_query.get()); + queue_->QueuePrinterQuery(std::move(printer_query)); } else { printer_query->StopWorker(); } @@ -142,7 +142,7 @@ void PrintingMessageFilterQt::OnGetDefaultPrintSettingsReply( void PrintingMessageFilterQt::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, IPC::Message* reply_msg) { - scoped_refptr<printing::PrinterQuery> printer_query = + std::unique_ptr<printing::PrinterQuery> printer_query = queue_->PopPrinterQuery(params.cookie); if (!printer_query.get()) { printer_query = @@ -155,14 +155,14 @@ void PrintingMessageFilterQt::OnScriptedPrint( params.margin_type, params.is_scripted, params.is_modifiable, - base::Bind(&PrintingMessageFilterQt::OnScriptedPrintReply, - this, - printer_query, - reply_msg)); + base::BindOnce(&PrintingMessageFilterQt::OnScriptedPrintReply, + this, + std::move(printer_query), + reply_msg)); } void PrintingMessageFilterQt::OnScriptedPrintReply( - scoped_refptr<printing::PrinterQuery> printer_query, + std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg) { PrintMsg_PrintPages_Params params; @@ -177,7 +177,7 @@ void PrintingMessageFilterQt::OnScriptedPrintReply( PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params); Send(reply_msg); if (!params.params.dpi.IsEmpty() && params.params.document_cookie) { - queue_->QueuePrinterQuery(printer_query.get()); + queue_->QueuePrinterQuery(std::move(printer_query)); } else { printer_query->StopWorker(); } @@ -186,7 +186,7 @@ void PrintingMessageFilterQt::OnScriptedPrintReply( void PrintingMessageFilterQt::OnUpdatePrintSettings(int document_cookie, base::Value job_settings, IPC::Message* reply_msg) { - scoped_refptr<printing::PrinterQuery> printer_query; + std::unique_ptr<printing::PrinterQuery> printer_query; printer_query = queue_->PopPrinterQuery(document_cookie); if (!printer_query.get()) { printer_query = queue_->CreatePrinterQuery( @@ -194,12 +194,11 @@ void PrintingMessageFilterQt::OnUpdatePrintSettings(int document_cookie, } printer_query->SetSettings( std::move(job_settings), - base::Bind(&PrintingMessageFilterQt::OnUpdatePrintSettingsReply, this, - printer_query, reply_msg)); + base::BindOnce(&PrintingMessageFilterQt::OnUpdatePrintSettingsReply, this, + std::move(printer_query), reply_msg)); } -void PrintingMessageFilterQt::OnUpdatePrintSettingsReply( - scoped_refptr<printing::PrinterQuery> printer_query, +void PrintingMessageFilterQt::OnUpdatePrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg) { PrintMsg_PrintPages_Params params; if (!printer_query.get() || @@ -218,9 +217,9 @@ void PrintingMessageFilterQt::OnUpdatePrintSettingsReply( (printer_query->last_status() == printing::PrintingContext::CANCEL)); Send(reply_msg); // If user hasn't cancelled. - if (printer_query.get()) { + if (printer_query) { if (printer_query->cookie() && printer_query->settings().dpi()) { - queue_->QueuePrinterQuery(printer_query.get()); + queue_->QueuePrinterQuery(std::move(printer_query)); } else { printer_query->StopWorker(); } diff --git a/src/core/printing/printing_message_filter_qt.h b/src/core/printing/printing_message_filter_qt.h index f1a3514c5..88559d3df 100644 --- a/src/core/printing/printing_message_filter_qt.h +++ b/src/core/printing/printing_message_filter_qt.h @@ -95,7 +95,7 @@ class PrintingMessageFilterQt : public content::BrowserMessageFilter { // Get the default print setting. void OnGetDefaultPrintSettings(IPC::Message* reply_msg); - void OnGetDefaultPrintSettingsReply(scoped_refptr<printing::PrinterQuery> printer_query, + void OnGetDefaultPrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg); // The renderer host have to show to the user the print dialog and returns @@ -103,7 +103,7 @@ class PrintingMessageFilterQt : public content::BrowserMessageFilter { // thread and the UI thread. The reply occurs on the IO thread. void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params, IPC::Message* reply_msg); - void OnScriptedPrintReply(scoped_refptr<printing::PrinterQuery> printer_query, + void OnScriptedPrintReply(std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg); // Modify the current print settings based on |job_settings|. The task is @@ -112,7 +112,7 @@ class PrintingMessageFilterQt : public content::BrowserMessageFilter { void OnUpdatePrintSettings(int document_cookie, base::Value job_settings, IPC::Message* reply_msg); - void OnUpdatePrintSettingsReply(scoped_refptr<printing::PrinterQuery> printer_query, + void OnUpdatePrintSettingsReply(std::unique_ptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg); // Check to see if print preview has been cancelled. diff --git a/src/core/profile_io_data_qt.cpp b/src/core/profile_io_data_qt.cpp index 38fe56f7d..2e0e378ac 100644 --- a/src/core/profile_io_data_qt.cpp +++ b/src/core/profile_io_data_qt.cpp @@ -55,6 +55,8 @@ #include "net/cert/ct_log_verifier.h" #include "net/cert/ct_policy_enforcer.h" #include "net/cert/multi_log_ct_verifier.h" +#include "net/cert_net/cert_net_fetcher_impl.h" +#include "net/ftp/ftp_auth_cache.h" #include "net/dns/host_resolver_manager.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_scheme.h" @@ -67,8 +69,6 @@ #include "net/proxy_resolution/pac_file_fetcher_impl.h" #include "net/proxy_resolution/proxy_config_service.h" #include "net/proxy_resolution/proxy_resolution_service.h" -#include "net/ssl/channel_id_service.h" -#include "net/ssl/default_channel_id_store.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/file_protocol_handler.h" @@ -79,6 +79,7 @@ #include "net/url_request/url_request_intercepting_job_factory.h" #include "services/file/user_id_map.h" #include "services/network/proxy_service_mojo.h" +#include "services/network/restricted_cookie_manager.h" #include "net/client_cert_override.h" #include "net/client_cert_store_data.h" @@ -86,6 +87,7 @@ #include "net/custom_protocol_handler.h" #include "net/network_delegate_qt.h" #include "net/proxy_config_service_qt.h" +#include "net/restricted_cookie_manager_qt.h" #include "net/url_request_context_getter_qt.h" #include "profile_qt.h" #include "resource_context_qt.h" @@ -104,6 +106,8 @@ namespace QtWebEngineCore { +static scoped_refptr<net::CertNetFetcherImpl> s_certNetFetcher; + static bool doNetworkSessionParamsMatch(const net::HttpNetworkSession::Params &first, const net::HttpNetworkSession::Params &second) { @@ -182,13 +186,18 @@ ProfileIODataQt::~ProfileIODataQt() #if defined(USE_NSS_CERTS) net::SetURLRequestContextForNSSHttpIO(nullptr); #endif -#if defined(OS_LINUX) ||defined(OS_MACOSX) - net::ShutdownGlobalCertNetFetcher(); -#endif + if (s_certNetFetcher) { + s_certNetFetcher->Shutdown(); + s_certNetFetcher.reset(); + } } - if (m_urlRequestContext && m_urlRequestContext->proxy_resolution_service()) - m_urlRequestContext->proxy_resolution_service()->OnShutdown(); + if (m_urlRequestContext) { + if (m_urlRequestContext->proxy_resolution_service()) + m_urlRequestContext->proxy_resolution_service()->OnShutdown(); + m_restrictedCookieManagerBindings.CloseAllBindings(); + cancelAllUrlRequests(); + } m_resourceContext.reset(); if (m_cookieDelegate) @@ -236,12 +245,20 @@ extensions::ExtensionSystemQt* ProfileIODataQt::GetExtensionSystem() } #endif // BUILDFLAG(ENABLE_EXTENSIONS) +base::WeakPtr<ProfileIODataQt> ProfileIODataQt::getWeakPtrOnUIThread() +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + return m_weakPtr; +} + void ProfileIODataQt::initializeOnIOThread() { m_networkDelegate.reset(new NetworkDelegateQt(this)); + m_hostResolver = net::HostResolver::CreateStandaloneResolver(nullptr); m_urlRequestContext.reset(new net::URLRequestContext()); m_urlRequestContext->set_network_delegate(m_networkDelegate.get()); - m_urlRequestContext->set_enable_brotli(base::FeatureList::IsEnabled(features::kBrotliEncoding)); + m_urlRequestContext->set_enable_brotli(true); + m_urlRequestContext->set_host_resolver(m_hostResolver.get()); // this binds factory to io thread m_weakPtr = m_weakPtrFactory.GetWeakPtr(); const std::lock_guard<QRecursiveMutex> lock(m_mutex); @@ -259,8 +276,7 @@ void ProfileIODataQt::initializeOnUIThread() ProtocolHandlerRegistry* protocolHandlerRegistry = ProtocolHandlerRegistryFactory::GetForBrowserContext(m_profile); DCHECK(protocolHandlerRegistry); - m_protocolHandlerInterceptor = - protocolHandlerRegistry->CreateJobInterceptorFactory(); + m_protocolHandlerRegistryIOThreadDelegate = protocolHandlerRegistry->io_thread_delegate(); m_cookieDelegate = new CookieMonsterDelegateQt(); m_cookieDelegate->setClient(m_profile->profileAdapter()->cookieStore()); createProxyConfig(); @@ -301,6 +317,7 @@ void ProfileIODataQt::generateStorage() // We must stop all requests before deleting their backends. if (m_storage) { m_urlRequestContext->proxy_resolution_service()->OnShutdown(); + m_restrictedCookieManagerBindings.CloseAllBindings(); m_cookieDelegate->setCookieMonster(nullptr); m_storage->set_cookie_store(nullptr); cancelAllUrlRequests(); @@ -315,7 +332,7 @@ void ProfileIODataQt::generateStorage() net::ProxyConfigService *proxyConfigService = m_proxyConfigService.fetchAndStoreAcquire(0); Q_ASSERT(proxyConfigService); - std::unique_ptr<net::CertVerifier> cert_verifier = net::CertVerifier::CreateDefault(); + std::unique_ptr<net::CertVerifier> cert_verifier = net::CertVerifier::CreateDefault(s_certNetFetcher); net::CertVerifier::Config config; // Enable revocation checking: config.enable_rev_checking = true; @@ -329,8 +346,7 @@ void ProfileIODataQt::generateStorage() for (const auto &ct_log : certificate_transparency::GetKnownLogs()) { scoped_refptr<const net::CTLogVerifier> log_verifier = net::CTLogVerifier::Create(std::string(ct_log.log_key, ct_log.log_key_length), - ct_log.log_name, - ct_log.log_dns_domain); + ct_log.log_name); if (!log_verifier) continue; ct_logs.push_back(std::move(log_verifier)); @@ -338,11 +354,6 @@ void ProfileIODataQt::generateStorage() ct_verifier->AddLogs(ct_logs); m_storage->set_cert_transparency_verifier(std::move(ct_verifier)); m_storage->set_ct_policy_enforcer(base::WrapUnique(new net::DefaultCTPolicyEnforcer())); -// static std::unique_ptr<net::HostResolverManager> s_hostResolverManager = -// std::make_unique<net::HostResolverManager>(net::HostResolver::Options(), nullptr); -// m_storage->set_host_resolver(net::HostResolver::CreateResolver(s_hostResolverManager.get())); - m_storage->set_host_resolver(net::HostResolver::CreateStandaloneResolver(nullptr)); - m_storage->set_ssl_config_service(std::make_unique<net::SSLConfigServiceDefaults>()); if (!m_httpAuthPreferences) { m_httpAuthPreferences.reset(new net::HttpAuthPreferences()); @@ -383,6 +394,8 @@ void ProfileIODataQt::generateStorage() m_urlRequestContext->host_resolver(), nullptr /* NetLog */, m_urlRequestContext->network_delegate())); + + m_storage->set_ftp_auth_cache(std::make_unique<net::FtpAuthCache>()); } @@ -393,9 +406,7 @@ void ProfileIODataQt::generateCookieStore() const std::lock_guard<QRecursiveMutex> lock(m_mutex); - // FIXME: Add code to remove the old database. - m_storage->set_channel_id_service( - std::make_unique<net::ChannelIDService>(new net::DefaultChannelIDStore(nullptr))); + // FIXME: Add code to remove the old channel-id database. std::unique_ptr<net::CookieStore> cookieStore; switch (m_persistentCookiesPolicy) { @@ -429,7 +440,6 @@ void ProfileIODataQt::generateCookieStore() } net::CookieMonster * const cookieMonster = static_cast<net::CookieMonster*>(cookieStore.get()); - cookieStore->SetChannelIDServiceID(m_urlRequestContext->channel_id_service()->GetUniqueID()); m_cookieDelegate->setCookieMonster(cookieMonster); m_storage->set_cookie_store(std::move(cookieStore)); @@ -492,7 +502,6 @@ void ProfileIODataQt::generateHttpCache() if (!m_httpNetworkSession || !doNetworkSessionParamsMatch(network_session_params, m_httpNetworkSession->params()) || !doNetworkSessionContextMatch(network_session_context, m_httpNetworkSession->context())) { - cancelAllUrlRequests(); m_httpNetworkSession.reset(new net::HttpNetworkSession(network_session_params, network_session_context)); } @@ -526,7 +535,7 @@ void ProfileIODataQt::generateJobFactory() jobFactory->SetProtocolHandler(url::kFileScheme, std::make_unique<net::FileProtocolHandler>(taskRunner)); jobFactory->SetProtocolHandler(url::kFtpScheme, - net::FtpProtocolHandler::Create(m_urlRequestContext->host_resolver())); + net::FtpProtocolHandler::Create(m_urlRequestContext->host_resolver(), m_urlRequestContext->ftp_auth_cache())); m_installedCustomSchemes = m_customUrlSchemes; for (const QByteArray &scheme : qAsConst(m_installedCustomSchemes)) { @@ -547,11 +556,6 @@ void ProfileIODataQt::generateJobFactory() m_requestInterceptors.clear(); - if (m_protocolHandlerInterceptor) { - m_protocolHandlerInterceptor->Chain(std::move(topJobFactory)); - topJobFactory = std::move(m_protocolHandlerInterceptor); - } - m_jobFactory = std::move(topJobFactory); m_urlRequestContext->set_job_factory(m_jobFactory.get()); @@ -591,9 +595,9 @@ void ProfileIODataQt::setGlobalCertificateVerification() // Set request context used by NSS for OCSP requests. net::SetURLRequestContextForNSSHttpIO(m_urlRequestContext.get()); #endif -#if defined(OS_LINUX) || defined(OS_MACOSX) - net::SetGlobalCertNetFetcher(net::CreateCertNetFetcher(m_urlRequestContext.get())); -#endif + if (!s_certNetFetcher) + s_certNetFetcher = base::MakeRefCounted<net::CertNetFetcherImpl>(); + s_certNetFetcher->SetURLRequestContext(m_urlRequestContext.get()); } } @@ -651,7 +655,7 @@ void ProfileIODataQt::createProxyConfig() base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO})), initialConfig, initialConfigState); //pass interface to io thread - m_proxyResolverFactoryInterface = ChromeMojoProxyResolverFactory::CreateWithStrongBinding().PassInterface(); + m_proxyResolverFactoryInterface = ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver(); } void ProfileIODataQt::updateStorageSettings() @@ -774,6 +778,8 @@ void ProfileIODataQt::updateUsedForGlobalCertificateVerification() { Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); const std::lock_guard<QRecursiveMutex> lock(m_mutex); + if (m_useForGlobalCertificateVerification == m_profileAdapter->isUsedForGlobalCertificateVerification()) + return; m_useForGlobalCertificateVerification = m_profileAdapter->isUsedForGlobalCertificateVerification(); if (m_useForGlobalCertificateVerification) @@ -797,9 +803,34 @@ std::unique_ptr<net::ClientCertStore> ProfileIODataQt::CreateClientCertStore() #endif } +void ProfileIODataQt::CreateRestrictedCookieManager(network::mojom::RestrictedCookieManagerRequest request, + network::mojom::RestrictedCookieManagerRole role, + const url::Origin &origin, + bool is_service_worker, + int32_t process_id, + int32_t routing_id) +{ + Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); + m_restrictedCookieManagerBindings.AddBinding( + std::make_unique<RestrictedCookieManagerQt>( + m_weakPtr, + role, urlRequestContext()->cookie_store(), + &m_cookieSettings, origin, + is_service_worker, process_id, routing_id), + std::move(request)); +} + +// static +ProfileIODataQt *ProfileIODataQt::FromBrowserContext(content::BrowserContext *browser_context) +{ + Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + return static_cast<ProfileQt *>(browser_context)->m_profileIOData.get(); +} + // static ProfileIODataQt *ProfileIODataQt::FromResourceContext(content::ResourceContext *resource_context) { + Q_ASSERT(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); return static_cast<ResourceContextQt *>(resource_context)->m_io_data; } diff --git a/src/core/profile_io_data_qt.h b/src/core/profile_io_data_qt.h index 4a5b9f77d..8f11a9ce2 100644 --- a/src/core/profile_io_data_qt.h +++ b/src/core/profile_io_data_qt.h @@ -42,9 +42,13 @@ #include "profile_adapter.h" #include "content/public/browser/browsing_data_remover.h" +#include "content/public/common/url_loader_throttle.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "extensions/buildflags/buildflags.h" +#include "mojo/public/cpp/bindings/strong_binding_set.h" +#include "services/network/cookie_settings.h" +#include "services/network/public/mojom/restricted_cookie_manager.mojom.h" #include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h" #include <QtCore/QString> @@ -56,6 +60,7 @@ class ClientCertStore; class DhcpPacFileFetcherFactory; class HttpAuthPreferences; class HttpNetworkSession; +class HostResolver; class NetworkDelegate; class ProxyConfigService; class URLRequestContext; @@ -103,6 +108,11 @@ public: extensions::ExtensionSystemQt* GetExtensionSystem(); #endif // BUILDFLAG(ENABLE_EXTENSIONS) + ProtocolHandlerRegistry::IOThreadDelegate *protocolHandlerRegistryIOThreadDelegate() + { + return m_protocolHandlerRegistryIOThreadDelegate.get(); + } + void initializeOnIOThread(); void initializeOnUIThread(); // runs on ui thread void shutdownOnUIThread(); // runs on ui thread @@ -138,11 +148,22 @@ public: void updateUsedForGlobalCertificateVerification(); // runs on ui thread bool hasPageInterceptors(); + void CreateRestrictedCookieManager(network::mojom::RestrictedCookieManagerRequest request, + network::mojom::RestrictedCookieManagerRole role, + const url::Origin &origin, + bool is_service_worker, + int32_t process_id, + int32_t routing_id); + #if QT_CONFIG(ssl) ClientCertificateStoreData *clientCertificateStoreData(); #endif std::unique_ptr<net::ClientCertStore> CreateClientCertStore(); + static ProfileIODataQt *FromBrowserContext(content::BrowserContext *browser_context); static ProfileIODataQt *FromResourceContext(content::ResourceContext *resource_context); + + base::WeakPtr<ProfileIODataQt> getWeakPtrOnUIThread(); + private: void removeBrowsingDataRemoverObserver(); @@ -152,11 +173,13 @@ private: std::unique_ptr<content::ResourceContext> m_resourceContext; std::unique_ptr<net::URLRequestContext> m_urlRequestContext; std::unique_ptr<net::HttpNetworkSession> m_httpNetworkSession; - std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> m_protocolHandlerInterceptor; + scoped_refptr<ProtocolHandlerRegistry::IOThreadDelegate> + m_protocolHandlerRegistryIOThreadDelegate; std::unique_ptr<net::DhcpPacFileFetcherFactory> m_dhcpPacFileFetcherFactory; std::unique_ptr<net::HttpAuthPreferences> m_httpAuthPreferences; std::unique_ptr<net::URLRequestJobFactory> m_jobFactory; std::unique_ptr<net::TransportSecurityPersister> m_transportSecurityPersister; + std::unique_ptr<net::HostResolver> m_hostResolver; base::WeakPtr<ProfileIODataQt> m_weakPtr; scoped_refptr<CookieMonsterDelegateQt> m_cookieDelegate; content::URLRequestInterceptorScopedVector m_requestInterceptors; @@ -166,6 +189,8 @@ private: QAtomicPointer<net::ProxyConfigService> m_proxyConfigService; QPointer<ProfileAdapter> m_profileAdapter; // never dereferenced in IO thread and it is passed by qpointer ProfileAdapter::PersistentCookiesPolicy m_persistentCookiesPolicy; + mojo::StrongBindingSet<network::mojom::RestrictedCookieManager> m_restrictedCookieManagerBindings; + #if QT_CONFIG(ssl) ClientCertificateStoreData *m_clientCertificateStoreData; #endif @@ -177,6 +202,7 @@ private: QList<QByteArray> m_customUrlSchemes; QList<QByteArray> m_installedCustomSchemes; QWebEngineUrlRequestInterceptor* m_requestInterceptor = nullptr; + network::CookieSettings m_cookieSettings; #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) QMutex m_mutex{QMutex::Recursive}; using QRecursiveMutex = QMutex; diff --git a/src/core/profile_qt.cpp b/src/core/profile_qt.cpp index 19d54df62..94b22fbea 100644 --- a/src/core/profile_qt.cpp +++ b/src/core/profile_qt.cpp @@ -130,7 +130,7 @@ const PrefService* ProfileQt::GetPrefs() const return m_prefServiceAdapter.prefService(); } -base::FilePath ProfileQt::GetPath() const +base::FilePath ProfileQt::GetPath() { return toFilePath(m_profileAdapter->dataPath()); } @@ -140,7 +140,7 @@ base::FilePath ProfileQt::GetCachePath() const return toFilePath(m_profileAdapter->cachePath()); } -bool ProfileQt::IsOffTheRecord() const +bool ProfileQt::IsOffTheRecord() { return m_profileAdapter->isOffTheRecord(); } @@ -155,12 +155,6 @@ net::URLRequestContextGetter *ProfileQt::CreateMediaRequestContext() return m_urlRequestContextGetter.get(); } -net::URLRequestContextGetter *ProfileQt::CreateMediaRequestContextForStoragePartition(const base::FilePath&, bool) -{ - Q_UNIMPLEMENTED(); - return nullptr; -} - content::ResourceContext *ProfileQt::GetResourceContext() { return m_profileIOData->resourceContext(); @@ -234,9 +228,9 @@ net::URLRequestContextGetter *ProfileQt::CreateRequestContext( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!m_urlRequestContextGetter.get()); #if BUILDFLAG(ENABLE_EXTENSIONS) - extensions::InfoMap* extension_info_map = GetExtensionSystem()->info_map(); + extensions::InfoMap *extension_info_map = GetExtensionSystem()->info_map(); (*protocol_handlers)[extensions::kExtensionScheme] = - extensions::CreateExtensionProtocolHandler(IsOffTheRecord(),extension_info_map); + extensions::CreateExtensionProtocolHandler(IsOffTheRecord(), extension_info_map); #endif m_profileIOData->setRequestContextData(protocol_handlers, std::move(request_interceptors)); @@ -245,15 +239,6 @@ net::URLRequestContextGetter *ProfileQt::CreateRequestContext( return m_urlRequestContextGetter.get(); } -net::URLRequestContextGetter *ProfileQt::CreateRequestContextForStoragePartition( - const base::FilePath& partition_path, bool in_memory, - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors) -{ - Q_UNIMPLEMENTED(); - return nullptr; -} - content::ClientHintsControllerDelegate *ProfileQt::GetClientHintsControllerDelegate() { return nullptr; @@ -270,7 +255,7 @@ void ProfileQt::SetCorsOriginAccessListForOrigin(const url::Origin &source_origi std::move(closure)); } -const content::SharedCorsOriginAccessList *ProfileQt::GetSharedCorsOriginAccessList() const +content::SharedCorsOriginAccessList *ProfileQt::GetSharedCorsOriginAccessList() { return m_sharedCorsOriginAccessList.get(); } diff --git a/src/core/profile_qt.h b/src/core/profile_qt.h index b6ff0a0db..f5dc59717 100644 --- a/src/core/profile_qt.h +++ b/src/core/profile_qt.h @@ -76,13 +76,10 @@ public: base::FilePath GetCachePath() const; // BrowserContext implementation: - base::FilePath GetPath() const override; - bool IsOffTheRecord() const override; + base::FilePath GetPath() override; + bool IsOffTheRecord() override; net::URLRequestContextGetter *CreateMediaRequestContext() override; - net::URLRequestContextGetter *CreateMediaRequestContextForStoragePartition( - const base::FilePath &partition_path, - bool in_memory) override; content::ResourceContext *GetResourceContext() override; content::DownloadManagerDelegate *GetDownloadManagerDelegate() override; content::BrowserPluginGuestManager *GetGuestManager() override; @@ -92,10 +89,6 @@ public: net::URLRequestContextGetter *CreateRequestContext( content::ProtocolHandlerMap *protocol_handlers, content::URLRequestInterceptorScopedVector request_interceptors) override; - net::URLRequestContextGetter *CreateRequestContextForStoragePartition( - const base::FilePath &partition_path, bool in_memory, - content::ProtocolHandlerMap *protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors) override; std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate( const base::FilePath &partition_path) override; content::PermissionControllerDelegate * GetPermissionControllerDelegate() override; @@ -107,7 +100,7 @@ public: std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns, std::vector<network::mojom::CorsOriginPatternPtr> block_patterns, base::OnceClosure closure) override; - const content::SharedCorsOriginAccessList* GetSharedCorsOriginAccessList() const override; + content::SharedCorsOriginAccessList *GetSharedCorsOriginAccessList() override; std::string GetMediaDeviceIDSalt() override; // Profile implementation: @@ -137,6 +130,7 @@ public: private: friend class ContentBrowserClientQt; + friend class ProfileIODataQt; friend class WebContentsAdapter; scoped_refptr<net::URLRequestContextGetter> m_urlRequestContextGetter; std::unique_ptr<BrowsingDataRemoverDelegateQt> m_removerDelegate; diff --git a/src/core/qtwebengine.gni b/src/core/qtwebengine.gni index d9e01a5b8..cd8514352 100644 --- a/src/core/qtwebengine.gni +++ b/src/core/qtwebengine.gni @@ -65,10 +65,6 @@ if (enable_extensions) { ] } -assert_no_deps = [ - "//ui/views/mus", -] - defines = [ "CHROMIUM_VERSION=\"" + chromium_version[0] + "\"" ] diff --git a/src/core/qtwebengine_sources.gni b/src/core/qtwebengine_sources.gni index 8441ca095..b4a6b3b83 100644 --- a/src/core/qtwebengine_sources.gni +++ b/src/core/qtwebengine_sources.gni @@ -46,6 +46,7 @@ source_set("qtwebengine_sources") { ] deps = [ + "//build:branding_buildflags", "//chrome/common:buildflags", "//components/nacl/common:buildflags", "//extensions/buildflags:buildflags", @@ -116,9 +117,10 @@ source_set("qtwebengine_sources") { "//chrome/common/extensions/permissions/chrome_permission_message_rules.h", ] } else { + deps += [ + "//extensions/common:common_constants", + ] sources += [ - "//extensions/common/constants.cc", - "//extensions/common/constants.h", "//extensions/common/url_pattern.cc", "//extensions/common/url_pattern.h", ] diff --git a/src/core/render_widget_host_view_qt.cpp b/src/core/render_widget_host_view_qt.cpp index 2918fd8bc..7633aa44c 100644 --- a/src/core/render_widget_host_view_qt.cpp +++ b/src/core/render_widget_host_view_qt.cpp @@ -120,8 +120,7 @@ static inline ui::LatencyInfo CreateLatencyInfo(const blink::WebInputEvent& even if (!event.TimeStamp().is_null()) { latency_info.AddLatencyNumberWithTimestamp( ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, - event.TimeStamp(), - 1); + event.TimeStamp()); } return latency_info; } @@ -280,6 +279,7 @@ RenderWidgetHostViewQt::RenderWidgetHostViewQt(content::RenderWidgetHost *widget , m_touchMotionStarted(false) , m_enableViz(features::IsVizDisplayCompositorEnabled()) , m_visible(false) + , m_needsBeginFrames(false) , m_loadVisuallyCommittedState(NotCommitted) , m_adapterClient(0) , m_imeInProgress(false) @@ -340,6 +340,7 @@ RenderWidgetHostViewQt::RenderWidgetHostViewQt(content::RenderWidgetHost *widget // May call SetNeedsBeginFrames host()->SetView(this); + host()->GetProcess()->AddObserver(this); } RenderWidgetHostViewQt::~RenderWidgetHostViewQt() @@ -353,6 +354,7 @@ RenderWidgetHostViewQt::~RenderWidgetHostViewQt() if (text_input_manager_) text_input_manager_->RemoveObserver(this); + host()->GetProcess()->RemoveObserver(this); m_touchSelectionController.reset(); m_touchSelectionControllerClient.reset(); @@ -536,110 +538,110 @@ void RenderWidgetHostViewQt::DisplayCursor(const content::WebCursor &webCursor) ui::CursorType auraType = ui::CursorType::kNull; #endif switch (cursorInfo.type) { - case blink::WebCursorInfo::kTypePointer: + case ui::CursorType::kPointer: shape = Qt::ArrowCursor; break; - case blink::WebCursorInfo::kTypeCross: + case ui::CursorType::kCross: shape = Qt::CrossCursor; break; - case blink::WebCursorInfo::kTypeHand: + case ui::CursorType::kHand: shape = Qt::PointingHandCursor; break; - case blink::WebCursorInfo::kTypeIBeam: + case ui::CursorType::kIBeam: shape = Qt::IBeamCursor; break; - case blink::WebCursorInfo::kTypeWait: + case ui::CursorType::kWait: shape = Qt::WaitCursor; break; - case blink::WebCursorInfo::kTypeHelp: + case ui::CursorType::kHelp: shape = Qt::WhatsThisCursor; break; - case blink::WebCursorInfo::kTypeEastResize: - case blink::WebCursorInfo::kTypeWestResize: - case blink::WebCursorInfo::kTypeEastWestResize: - case blink::WebCursorInfo::kTypeEastPanning: - case blink::WebCursorInfo::kTypeWestPanning: + case ui::CursorType::kEastResize: + case ui::CursorType::kWestResize: + case ui::CursorType::kEastWestResize: + case ui::CursorType::kEastPanning: + case ui::CursorType::kWestPanning: shape = Qt::SizeHorCursor; break; - case blink::WebCursorInfo::kTypeNorthResize: - case blink::WebCursorInfo::kTypeSouthResize: - case blink::WebCursorInfo::kTypeNorthSouthResize: - case blink::WebCursorInfo::kTypeNorthPanning: - case blink::WebCursorInfo::kTypeSouthPanning: + case ui::CursorType::kNorthResize: + case ui::CursorType::kSouthResize: + case ui::CursorType::kNorthSouthResize: + case ui::CursorType::kNorthPanning: + case ui::CursorType::kSouthPanning: shape = Qt::SizeVerCursor; break; - case blink::WebCursorInfo::kTypeNorthEastResize: - case blink::WebCursorInfo::kTypeSouthWestResize: - case blink::WebCursorInfo::kTypeNorthEastSouthWestResize: - case blink::WebCursorInfo::kTypeNorthEastPanning: - case blink::WebCursorInfo::kTypeSouthWestPanning: + case ui::CursorType::kNorthEastResize: + case ui::CursorType::kSouthWestResize: + case ui::CursorType::kNorthEastSouthWestResize: + case ui::CursorType::kNorthEastPanning: + case ui::CursorType::kSouthWestPanning: shape = Qt::SizeBDiagCursor; break; - case blink::WebCursorInfo::kTypeNorthWestResize: - case blink::WebCursorInfo::kTypeSouthEastResize: - case blink::WebCursorInfo::kTypeNorthWestSouthEastResize: - case blink::WebCursorInfo::kTypeNorthWestPanning: - case blink::WebCursorInfo::kTypeSouthEastPanning: + case ui::CursorType::kNorthWestResize: + case ui::CursorType::kSouthEastResize: + case ui::CursorType::kNorthWestSouthEastResize: + case ui::CursorType::kNorthWestPanning: + case ui::CursorType::kSouthEastPanning: shape = Qt::SizeFDiagCursor; break; - case blink::WebCursorInfo::kTypeColumnResize: + case ui::CursorType::kColumnResize: shape = Qt::SplitHCursor; break; - case blink::WebCursorInfo::kTypeRowResize: + case ui::CursorType::kRowResize: shape = Qt::SplitVCursor; break; - case blink::WebCursorInfo::kTypeMiddlePanning: - case blink::WebCursorInfo::kTypeMove: + case ui::CursorType::kMiddlePanning: + case ui::CursorType::kMove: shape = Qt::SizeAllCursor; break; - case blink::WebCursorInfo::kTypeProgress: + case ui::CursorType::kProgress: shape = Qt::BusyCursor; break; - case blink::WebCursorInfo::kTypeCopy: + case ui::CursorType::kCopy: shape = Qt::DragCopyCursor; break; - case blink::WebCursorInfo::kTypeAlias: + case ui::CursorType::kAlias: shape = Qt::DragLinkCursor; break; #if defined(USE_AURA) - case blink::WebCursorInfo::kTypeVerticalText: + case ui::CursorType::kVerticalText: auraType = ui::CursorType::kVerticalText; break; - case blink::WebCursorInfo::kTypeCell: + case ui::CursorType::kCell: auraType = ui::CursorType::kCell; break; - case blink::WebCursorInfo::kTypeContextMenu: + case ui::CursorType::kContextMenu: auraType = ui::CursorType::kContextMenu; break; - case blink::WebCursorInfo::kTypeZoomIn: + case ui::CursorType::kZoomIn: auraType = ui::CursorType::kZoomIn; break; - case blink::WebCursorInfo::kTypeZoomOut: + case ui::CursorType::kZoomOut: auraType = ui::CursorType::kZoomOut; break; #else - case blink::WebCursorInfo::kTypeVerticalText: - case blink::WebCursorInfo::kTypeCell: - case blink::WebCursorInfo::kTypeContextMenu: - case blink::WebCursorInfo::kTypeZoomIn: - case blink::WebCursorInfo::kTypeZoomOut: + case ui::CursorType::kVerticalText: + case ui::CursorType::kCell: + case ui::CursorType::kContextMenu: + case ui::CursorType::kZoomIn: + case ui::CursorType::kZoomOut: // FIXME: Support on OS X break; #endif - case blink::WebCursorInfo::kTypeNoDrop: - case blink::WebCursorInfo::kTypeNotAllowed: + case ui::CursorType::kNoDrop: + case ui::CursorType::kNotAllowed: shape = Qt::ForbiddenCursor; break; - case blink::WebCursorInfo::kTypeNone: + case ui::CursorType::kNone: shape = Qt::BlankCursor; break; - case blink::WebCursorInfo::kTypeGrab: + case ui::CursorType::kGrab: shape = Qt::OpenHandCursor; break; - case blink::WebCursorInfo::kTypeGrabbing: + case ui::CursorType::kGrabbing: shape = Qt::ClosedHandCursor; break; - case blink::WebCursorInfo::kTypeCustom: + case ui::CursorType::kCustom: if (cursorInfo.custom_image.colorType() == SkColorType::kN32_SkColorType) { QImage cursor = toQImage(cursorInfo.custom_image, QImage::Format_ARGB32); m_delegate->updateCursor(QCursor(QPixmap::fromImage(cursor), cursorInfo.hotspot.x(), cursorInfo.hotspot.y())); @@ -693,15 +695,20 @@ void RenderWidgetHostViewQt::ImeCompositionRangeChanged(const gfx::Range&, const QT_NOT_YET_IMPLEMENTED } -void RenderWidgetHostViewQt::RenderProcessGone(base::TerminationStatus terminationStatus, - int exitCode) +void RenderWidgetHostViewQt::RenderProcessExited(content::RenderProcessHost *host, + const content::ChildProcessTerminationInfo &info) { + Q_UNUSED(host); // RenderProcessHost::FastShutdownIfPossible results in TERMINATION_STATUS_STILL_RUNNING - if (m_adapterClient && terminationStatus != base::TERMINATION_STATUS_STILL_RUNNING) { + if (m_adapterClient && info.status != base::TERMINATION_STATUS_STILL_RUNNING) { m_adapterClient->renderProcessTerminated( - m_adapterClient->renderProcessExitStatus(terminationStatus), - exitCode); + m_adapterClient->renderProcessExitStatus(info.status), + info.exit_code); } +} + +void RenderWidgetHostViewQt::RenderProcessGone() +{ Destroy(); } @@ -769,8 +776,11 @@ void RenderWidgetHostViewQt::OnUpdateTextInputStateCalled(content::TextInputMana } ui::TextInputType type = getTextInputType(); +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) m_delegate->setInputMethodHints(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText | Qt::ImhNoTextHandles | Qt::ImhNoEditMenu); - +#else + m_delegate->setInputMethodHints(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText); +#endif m_surroundingText = toQt(state->value); // Remove IME composition text from the surrounding text if (state->composition_start != -1 && state->composition_end != -1) @@ -824,7 +834,7 @@ void RenderWidgetHostViewQt::OnTextSelectionChanged(content::TextInputManager *t #if defined(USE_OZONE) if (!selection->selected_text().empty() && selection->user_initiated()) { // Set the CLIPBOARD_TYPE_SELECTION to the ui::Clipboard. - ui::ScopedClipboardWriter clipboard_writer(ui::CLIPBOARD_TYPE_SELECTION); + ui::ScopedClipboardWriter clipboard_writer(ui::ClipboardType::kSelection); clipboard_writer.WriteText(selection->selected_text()); } #endif // defined(USE_OZONE) @@ -1005,11 +1015,9 @@ void RenderWidgetHostViewQt::notifyShown() m_delegatedFrameHost->AttachToCompositor(m_uiCompositor.get()); m_delegatedFrameHost->WasShown(GetLocalSurfaceIdAllocation().local_surface_id(), m_viewRectInDips.size(), - false /* record_presentation_time */); - host()->WasShown(false); - } else { - host()->WasShown(false); + base::nullopt); } + host()->WasShown(base::nullopt); } void RenderWidgetHostViewQt::notifyHidden() @@ -1019,7 +1027,7 @@ void RenderWidgetHostViewQt::notifyHidden() return; m_visible = false; host()->WasHidden(); - m_delegatedFrameHost->WasHidden(); + m_delegatedFrameHost->WasHidden(content::DelegatedFrameHost::HiddenCause::kOther); m_delegatedFrameHost->DetachFromCompositor(); } else { host()->WasHidden(); @@ -1199,7 +1207,11 @@ QVariant RenderWidgetHostViewQt::inputMethodQuery(Qt::InputMethodQuery query) // TODO: Implement this return QVariant(); // No limit. case Qt::ImHints: +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return int(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText | Qt::ImhNoTextHandles | Qt::ImhNoEditMenu); +#else + return int(toQtInputMethodHints(getTextInputType()) | Qt::ImhNoPredictiveText); +#endif default: return QVariant(); } @@ -1741,8 +1753,8 @@ void RenderWidgetHostViewQt::handleFocusEvent(QFocusEvent *ev) void RenderWidgetHostViewQt::SetNeedsBeginFrames(bool needs_begin_frames) { - DCHECK(!m_enableViz); - m_compositor->setNeedsBeginFrames(needs_begin_frames); + m_needsBeginFrames = needs_begin_frames; + UpdateNeedsBeginFramesInternal(); } content::RenderFrameHost *RenderWidgetHostViewQt::getFocusedFrameHost() @@ -1777,6 +1789,8 @@ ui::TextInputType RenderWidgetHostViewQt::getTextInputType() const void RenderWidgetHostViewQt::SetWantsAnimateOnlyBeginFrames() { + if (m_enableViz) + m_delegatedFrameHost->SetWantsAnimateOnlyBeginFrames(); } viz::SurfaceId RenderWidgetHostViewQt::GetCurrentSurfaceId() const @@ -1877,4 +1891,12 @@ std::unique_ptr<content::SyntheticGestureTarget> RenderWidgetHostViewQt::CreateS return nullptr; } +void RenderWidgetHostViewQt::UpdateNeedsBeginFramesInternal() +{ + if (m_enableViz) + m_delegatedFrameHost->SetNeedsBeginFrames(m_needsBeginFrames); + else + m_compositor->setNeedsBeginFrames(m_needsBeginFrames); +} + } // namespace QtWebEngineCore diff --git a/src/core/render_widget_host_view_qt.h b/src/core/render_widget_host_view_qt.h index 5935f477a..76807b37a 100644 --- a/src/core/render_widget_host_view_qt.h +++ b/src/core/render_widget_host_view_qt.h @@ -52,6 +52,7 @@ #include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/text_input_manager.h" +#include "content/public/browser/render_process_host_observer.h" #include "gpu/ipc/common/gpu_messages.h" #include "ui/events/gesture_detection/filtered_gesture_provider.h" @@ -101,6 +102,7 @@ struct MultipleMouseClickHelper class RenderWidgetHostViewQt : public content::RenderWidgetHostViewBase + , public content::RenderProcessHostObserver , public ui::GestureProviderClient , public RenderWidgetHostViewQtDelegateClient , public base::SupportsWeakPtr<RenderWidgetHostViewQt> @@ -147,7 +149,7 @@ public: void SetIsLoading(bool) override; void ImeCancelComposition() override; void ImeCompositionRangeChanged(const gfx::Range&, const std::vector<gfx::Rect>&) override; - void RenderProcessGone(base::TerminationStatus, int) override; + void RenderProcessGone() override; void Destroy() override; void SetTooltipText(const base::string16 &tooltip_text) override; void DisplayTooltipText(const base::string16& tooltip_text) override; @@ -174,6 +176,10 @@ public: void DidStopFlinging() override; std::unique_ptr<content::SyntheticGestureTarget> CreateSyntheticGestureTarget() override; + // RenderProcessHostObserver implementation. + void RenderProcessExited(content::RenderProcessHost *host, + const content::ChildProcessTerminationInfo &info) override; + // Overridden from ui::GestureProviderClient. void OnGestureEvent(const ui::GestureEventData& gesture) override; @@ -214,6 +220,7 @@ public: void ShowDefinitionForSelection() override { QT_NOT_YET_IMPLEMENTED } #endif // defined(OS_MACOSX) + void UpdateNeedsBeginFramesInternal(); // Overridden from content::BrowserAccessibilityDelegate content::BrowserAccessibilityManager* CreateBrowserAccessibilityManager(content::BrowserAccessibilityDelegate* delegate, bool for_root_frame) override; @@ -269,6 +276,7 @@ private: const bool m_enableViz; bool m_visible; + bool m_needsBeginFrames; DelegatedFrameHostClientQt m_delegatedFrameHostClient{this}; std::unique_ptr<content::DelegatedFrameHost> m_delegatedFrameHost; std::unique_ptr<ui::Layer> m_rootLayer; diff --git a/src/core/renderer/content_renderer_client_qt.cpp b/src/core/renderer/content_renderer_client_qt.cpp index 092e6845d..b9b199087 100644 --- a/src/core/renderer/content_renderer_client_qt.cpp +++ b/src/core/renderer/content_renderer_client_qt.cpp @@ -153,14 +153,18 @@ void ContentRendererClientQt::RenderThreadStarted() // Allow XMLHttpRequests from qrc to file. blink::WebURL qrc(blink::KURL("qrc:")); blink::WebString file(blink::WebString::FromASCII("file")); - blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(qrc, file, blink::WebString(), true, + blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(qrc, file, blink::WebString(), 0, + network::mojom::CorsDomainMatchMode::kAllowSubdomains, + network::mojom::CorsPortMatchMode::kAllowAnyPort, network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority); #if BUILDFLAG(ENABLE_EXTENSIONS) // Allow the pdf viewer extension to access chrome resources blink::WebURL pdfViewerExtension(blink::KURL("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai")); blink::WebString chromeResources(blink::WebString::FromASCII("chrome")); - blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(pdfViewerExtension, chromeResources, blink::WebString(), true, + blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(pdfViewerExtension, chromeResources, blink::WebString(), 0, + network::mojom::CorsDomainMatchMode::kAllowSubdomains, + network::mojom::CorsPortMatchMode::kAllowAnyPort, network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority); ExtensionsRendererClientQt::GetInstance()->RenderThreadStarted(); @@ -170,13 +174,14 @@ void ContentRendererClientQt::RenderThreadStarted() void ContentRendererClientQt::RenderViewCreated(content::RenderView* render_view) { // RenderViewObservers destroy themselves with their RenderView. - new RenderViewObserverQt(render_view, m_webCacheImpl.data()); + new RenderViewObserverQt(render_view); UserResourceController::instance()->renderViewCreated(render_view); } void ContentRendererClientQt::RenderFrameCreated(content::RenderFrame* render_frame) { - QtWebEngineCore::RenderFrameObserverQt *render_frame_observer = new QtWebEngineCore::RenderFrameObserverQt(render_frame); + QtWebEngineCore::RenderFrameObserverQt *render_frame_observer = + new QtWebEngineCore::RenderFrameObserverQt(render_frame, m_webCacheImpl.data()); #if QT_CONFIG(webengine_webchannel) if (render_frame->IsMainFrame()) new WebChannelIPCTransport(render_frame); @@ -293,7 +298,8 @@ void ContentRendererClientQt::GetNavigationErrorStringsInternal(content::RenderF resourceId = IDR_NET_ERROR_HTML; - const base::StringPiece template_html(ui::ResourceBundle::GetSharedInstance().GetRawDataResource(resourceId)); + std::string extracted_string = ui::ResourceBundle::GetSharedInstance().DecompressDataResource(resourceId); + const base::StringPiece template_html(extracted_string.data(), extracted_string.size()); if (template_html.empty()) NOTREACHED() << "unable to load template. ID: " << resourceId; else // "t" is the id of the templates root node. @@ -518,7 +524,7 @@ static void AddWidevine(std::vector<std::unique_ptr<media::KeySystemProperties>> } // Session types. - bool cdm_supports_temporary_session = base::ContainsValue(capability->session_types, media::CdmSessionType::kTemporary); + bool cdm_supports_temporary_session = base::Contains(capability->session_types, media::CdmSessionType::kTemporary); if (!cdm_supports_temporary_session) { DVLOG(1) << "Temporary session must be supported."; return; diff --git a/src/core/renderer/extensions/extensions_renderer_client_qt.cpp b/src/core/renderer/extensions/extensions_renderer_client_qt.cpp index c25494590..7d4c9a83c 100644 --- a/src/core/renderer/extensions/extensions_renderer_client_qt.cpp +++ b/src/core/renderer/extensions/extensions_renderer_client_qt.cpp @@ -56,6 +56,8 @@ #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" #include "extensions/common/constants.h" +#include "extensions/common/extension.h" +#include "extensions/common/manifest_handlers/background_info.h" #include "extensions/common/switches.h" #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/extension_frame_helper.h" @@ -120,6 +122,28 @@ void ExtensionsRendererClientQt::OnExtensionUnloaded(const extensions::Extension resource_request_policy_->OnExtensionUnloaded(extension_id); } +bool ExtensionsRendererClientQt::ExtensionAPIEnabledForServiceWorkerScript(const GURL &scope, const GURL &script_url) const +{ + if (!script_url.SchemeIs(extensions::kExtensionScheme)) + return false; + + if (!extensions::ExtensionsClient::Get()->ExtensionAPIEnabledInExtensionServiceWorkers()) + return false; + + const extensions::Extension* extension = + extensions::RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(script_url); + + if (!extension || !extensions::BackgroundInfo::IsServiceWorkerBased(extension)) + return false; + + if (scope != extension->url()) + return false; + + const std::string& sw_script = extensions::BackgroundInfo::GetBackgroundServiceWorkerScript(extension); + + return extension->GetResourceURL(sw_script) == script_url; +} + void ExtensionsRendererClientQt::RenderThreadStarted() { content::RenderThread *thread = content::RenderThread::Get(); diff --git a/src/core/renderer/extensions/extensions_renderer_client_qt.h b/src/core/renderer/extensions/extensions_renderer_client_qt.h index 2d45d255a..87e324213 100644 --- a/src/core/renderer/extensions/extensions_renderer_client_qt.h +++ b/src/core/renderer/extensions/extensions_renderer_client_qt.h @@ -113,6 +113,8 @@ public: const std::string &mime_type, const GURL &original_url); + bool ExtensionAPIEnabledForServiceWorkerScript(const GURL &scope, const GURL &script_url) const override; + void RunScriptsAtDocumentStart(content::RenderFrame *render_frame); void RunScriptsAtDocumentEnd(content::RenderFrame *render_frame); void RunScriptsAtDocumentIdle(content::RenderFrame *render_frame); diff --git a/src/core/renderer/render_frame_observer_qt.cpp b/src/core/renderer/render_frame_observer_qt.cpp index 5a630357c..c48ef3b5c 100644 --- a/src/core/renderer/render_frame_observer_qt.cpp +++ b/src/core/renderer/render_frame_observer_qt.cpp @@ -46,6 +46,8 @@ #include "base/memory/ptr_util.h" #include "chrome/renderer/pepper/pepper_shared_memory_message_filter.h" +#include "components/web_cache/renderer/web_cache_impl.h" +#include "content/public/renderer/render_frame.h" #include "content/public/renderer/renderer_ppapi_host.h" #include "ppapi/host/ppapi_host.h" @@ -53,10 +55,12 @@ namespace QtWebEngineCore { -RenderFrameObserverQt::RenderFrameObserverQt(content::RenderFrame* render_frame) +RenderFrameObserverQt::RenderFrameObserverQt(content::RenderFrame* render_frame, + web_cache::WebCacheImpl* web_cache_impl) : RenderFrameObserver(render_frame) , RenderFrameObserverTracker<RenderFrameObserverQt>(render_frame) , m_isFrameDetached(false) + , m_web_cache_impl(web_cache_impl) { } @@ -88,4 +92,10 @@ bool RenderFrameObserverQt::isFrameDetached() const return m_isFrameDetached; } +void RenderFrameObserverQt::ReadyToCommitNavigation(blink::WebDocumentLoader *) +{ + if (render_frame()->IsMainFrame() && m_web_cache_impl) + m_web_cache_impl->ExecutePendingClearCache(); +} + } // namespace QtWebEngineCore diff --git a/src/core/renderer/render_frame_observer_qt.h b/src/core/renderer/render_frame_observer_qt.h index 4c05422bb..3c54761f3 100644 --- a/src/core/renderer/render_frame_observer_qt.h +++ b/src/core/renderer/render_frame_observer_qt.h @@ -50,6 +50,9 @@ namespace content { class RenderFrame; } +namespace web_cache { +class WebCacheImpl; +} namespace QtWebEngineCore { @@ -58,7 +61,8 @@ class RenderFrameObserverQt , public content::RenderFrameObserverTracker<RenderFrameObserverQt> { public: - explicit RenderFrameObserverQt(content::RenderFrame* render_frame); + explicit RenderFrameObserverQt(content::RenderFrame* render_frame, + web_cache::WebCacheImpl* web_cache_impl); ~RenderFrameObserverQt(); #if QT_CONFIG(webengine_pepper_plugins) @@ -74,8 +78,11 @@ public: private: DISALLOW_COPY_AND_ASSIGN(RenderFrameObserverQt); + void ReadyToCommitNavigation(blink::WebDocumentLoader *); + bool m_isFrameDetached; service_manager::BinderRegistry registry_; + web_cache::WebCacheImpl *m_web_cache_impl; }; } // namespace QtWebEngineCore diff --git a/src/core/renderer/render_view_observer_qt.cpp b/src/core/renderer/render_view_observer_qt.cpp index 2795de4b9..7e7c7bdf8 100644 --- a/src/core/renderer/render_view_observer_qt.cpp +++ b/src/core/renderer/render_view_observer_qt.cpp @@ -41,7 +41,6 @@ #include "common/qt_messages.h" -#include "components/web_cache/renderer/web_cache_impl.h" #include "content/public/renderer/render_view.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_element.h" @@ -52,10 +51,8 @@ #include "third_party/blink/public/web/web_view.h" RenderViewObserverQt::RenderViewObserverQt( - content::RenderView* render_view, - web_cache::WebCacheImpl* web_cache_impl) + content::RenderView* render_view) : content::RenderViewObserver(render_view) - , m_web_cache_impl(web_cache_impl) { } @@ -99,9 +96,3 @@ bool RenderViewObserverQt::OnMessageReceived(const IPC::Message& message) IPC_END_MESSAGE_MAP() return handled; } - -void RenderViewObserverQt::Navigate(const GURL &) -{ - if (m_web_cache_impl) - m_web_cache_impl->ExecutePendingClearCache(); -} diff --git a/src/core/renderer/render_view_observer_qt.h b/src/core/renderer/render_view_observer_qt.h index abb472f02..a878eebe8 100644 --- a/src/core/renderer/render_view_observer_qt.h +++ b/src/core/renderer/render_view_observer_qt.h @@ -43,14 +43,9 @@ #include <QtGlobal> -namespace web_cache { -class WebCacheImpl; -} - class RenderViewObserverQt : public content::RenderViewObserver { public: - RenderViewObserverQt(content::RenderView* render_view, - web_cache::WebCacheImpl* web_cache_impl); + RenderViewObserverQt(content::RenderView* render_view); private: void onFetchDocumentMarkup(quint64 requestId); @@ -60,9 +55,6 @@ private: void OnDestruct() override; bool OnMessageReceived(const IPC::Message& message) override; - void Navigate(const GURL& url) override; - - web_cache::WebCacheImpl* m_web_cache_impl; DISALLOW_COPY_AND_ASSIGN(RenderViewObserverQt); }; diff --git a/src/core/renderer/user_resource_controller.cpp b/src/core/renderer/user_resource_controller.cpp index 701614341..781c10840 100644 --- a/src/core/renderer/user_resource_controller.cpp +++ b/src/core/renderer/user_resource_controller.cpp @@ -71,7 +71,7 @@ static const int afterLoadTimeout = 500; static int validUserScriptSchemes() { - return URLPattern::SCHEME_HTTP | URLPattern::SCHEME_HTTPS | URLPattern::SCHEME_FILE; + return URLPattern::SCHEME_HTTP | URLPattern::SCHEME_HTTPS | URLPattern::SCHEME_FILE | URLPattern::SCHEME_QRC; } static bool regexMatchesURL(const std::string &pat, const GURL &url) { diff --git a/src/core/renderer/web_channel_ipc_transport.cpp b/src/core/renderer/web_channel_ipc_transport.cpp index 745fe8b1e..108686068 100644 --- a/src/core/renderer/web_channel_ipc_transport.cpp +++ b/src/core/renderer/web_channel_ipc_transport.cpp @@ -92,15 +92,18 @@ void WebChannelTransport::Install(blink::WebLocalFrame *frame, uint worldId) gin::Handle<WebChannelTransport> transport = gin::CreateHandle(isolate, new WebChannelTransport); v8::Local<v8::Object> global = context->Global(); - v8::Local<v8::Value> qtObjectValue = global->Get(gin::StringToV8(isolate, "qt")); + v8::MaybeLocal<v8::Value> qtObjectValue = global->Get(context, gin::StringToV8(isolate, "qt")); v8::Local<v8::Object> qtObject; - if (qtObjectValue.IsEmpty() || !qtObjectValue->IsObject()) { + if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject()) { qtObject = v8::Object::New(isolate); - global->Set(gin::StringToV8(isolate, "qt"), qtObject); + auto whocares = global->Set(context, gin::StringToV8(isolate, "qt"), qtObject); + // FIXME: Perhaps error out, but the return value is V8 internal... + Q_UNUSED(whocares); } else { - qtObject = v8::Local<v8::Object>::Cast(qtObjectValue); + qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked()); } - qtObject->Set(gin::StringToV8(isolate, "webChannelTransport"), transport.ToV8()); + auto whocares = qtObject->Set(context, gin::StringToV8(isolate, "webChannelTransport"), transport.ToV8()); + Q_UNUSED(whocares); } void WebChannelTransport::Uninstall(blink::WebLocalFrame *frame, uint worldId) @@ -115,11 +118,11 @@ void WebChannelTransport::Uninstall(blink::WebLocalFrame *frame, uint worldId) v8::Context::Scope contextScope(context); v8::Local<v8::Object> global(context->Global()); - v8::Local<v8::Value> qtObjectValue = global->Get(gin::StringToV8(isolate, "qt")); - if (qtObjectValue.IsEmpty() || !qtObjectValue->IsObject()) + v8::MaybeLocal<v8::Value> qtObjectValue = global->Get(context, gin::StringToV8(isolate, "qt")); + if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject()) return; - v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue); - // FIXME: ? + v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked()); + // FIXME: We can't do anything about a failure, so why the .. is it nodiscard? auto whocares = qtObject->Delete(context, gin::StringToV8(isolate, "webChannelTransport")); Q_UNUSED(whocares); } @@ -235,16 +238,16 @@ void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t v8::Context::Scope contextScope(context); v8::Local<v8::Object> global(context->Global()); - v8::Local<v8::Value> qtObjectValue(global->Get(gin::StringToV8(isolate, "qt"))); - if (qtObjectValue.IsEmpty() || !qtObjectValue->IsObject()) + v8::MaybeLocal<v8::Value> qtObjectValue(global->Get(context, gin::StringToV8(isolate, "qt"))); + if (qtObjectValue.IsEmpty() || !qtObjectValue.ToLocalChecked()->IsObject()) return; - v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue); - v8::Local<v8::Value> webChannelObjectValue(qtObject->Get(gin::StringToV8(isolate, "webChannelTransport"))); - if (webChannelObjectValue.IsEmpty() || !webChannelObjectValue->IsObject()) + v8::Local<v8::Object> qtObject = v8::Local<v8::Object>::Cast(qtObjectValue.ToLocalChecked()); + v8::MaybeLocal<v8::Value> webChannelObjectValue(qtObject->Get(context, gin::StringToV8(isolate, "webChannelTransport"))); + if (webChannelObjectValue.IsEmpty() || !webChannelObjectValue.ToLocalChecked()->IsObject()) return; - v8::Local<v8::Object> webChannelObject = v8::Local<v8::Object>::Cast(webChannelObjectValue); - v8::Local<v8::Value> callbackValue(webChannelObject->Get(gin::StringToV8(isolate, "onmessage"))); - if (callbackValue.IsEmpty() || !callbackValue->IsFunction()) { + v8::Local<v8::Object> webChannelObject = v8::Local<v8::Object>::Cast(webChannelObjectValue.ToLocalChecked()); + v8::MaybeLocal<v8::Value> callbackValue(webChannelObject->Get(context, gin::StringToV8(isolate, "onmessage"))); + if (callbackValue.IsEmpty() || !callbackValue.ToLocalChecked()->IsFunction()) { LOG(WARNING) << "onmessage is not a callable property of qt.webChannelTransport. Some things might not work as expected."; return; } @@ -252,12 +255,12 @@ void WebChannelIPCTransport::DispatchWebChannelMessage(const std::vector<uint8_t v8::Local<v8::Object> messageObject(v8::Object::New(isolate)); v8::Maybe<bool> wasSet = messageObject->DefineOwnProperty( context, - v8::String::NewFromUtf8(isolate, "data"), - v8::String::NewFromUtf8(isolate, json.constData(), v8::String::kNormalString, json.size()), + v8::String::NewFromUtf8(isolate, "data").ToLocalChecked(), + v8::String::NewFromUtf8(isolate, json.constData(), v8::NewStringType::kNormal, json.size()).ToLocalChecked(), v8::PropertyAttribute(v8::ReadOnly | v8::DontDelete)); DCHECK(!wasSet.IsNothing() && wasSet.FromJust()); - v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(callbackValue); + v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(callbackValue.ToLocalChecked()); v8::Local<v8::Value> argv[] = { messageObject }; frame->CallFunctionEvenIfScriptDisabled(callback, webChannelObject, 1, argv); } diff --git a/src/core/renderer_host/resource_dispatcher_host_delegate_qt.cpp b/src/core/renderer_host/resource_dispatcher_host_delegate_qt.cpp index eba835cd7..a08e2cf88 100644 --- a/src/core/renderer_host/resource_dispatcher_host_delegate_qt.cpp +++ b/src/core/renderer_host/resource_dispatcher_host_delegate_qt.cpp @@ -98,7 +98,7 @@ void OnPdfStreamIntercepted( // external viewer, trigger the download. std::unique_ptr<download::DownloadUrlParameters> params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( - web_contents, original_url, NO_TRAFFIC_ANNOTATION_YET)); + web_contents, original_url, MISSING_TRAFFIC_ANNOTATION)); content::BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()) ->DownloadUrl(std::move(params)); return; diff --git a/src/core/touch_selection_controller_client_qt.cpp b/src/core/touch_selection_controller_client_qt.cpp index da3c78b8a..0f44210d1 100644 --- a/src/core/touch_selection_controller_client_qt.cpp +++ b/src/core/touch_selection_controller_client_qt.cpp @@ -315,7 +315,7 @@ void TouchSelectionControllerClientQt::showMenu() WebContentsAdapterClient *adapterClient = m_rwhv->adapterClient(); Q_ASSERT(adapterClient); - adapterClient->showTouchSelectionMenu(m_menuController.get(), + adapterClient->showTouchSelectionMenu(m_menuController.data(), QRect(toQt(gfx::ToEnclosingRect(anchor_rect))), QSize(toQt(gfx::ToRoundedSize(max_handle_size)))); m_menuShowing = true; diff --git a/src/core/web_contents_adapter.cpp b/src/core/web_contents_adapter.cpp index 85e63c5a4..3eb52409d 100644 --- a/src/core/web_contents_adapter.cpp +++ b/src/core/web_contents_adapter.cpp @@ -334,6 +334,7 @@ static void deserializeNavigationHistory(QDataStream &input, int *currentIndex, std::unique_ptr<content::NavigationEntry> entry = content::NavigationController::CreateNavigationEntry( toGurl(virtualUrl), content::Referrer(toGurl(referrerUrl), static_cast<network::mojom::ReferrerPolicy>(referrerPolicy)), + base::nullopt, // optional initiator_origin // Use a transition type of reload so that we don't incorrectly // increase the typed count. ui::PAGE_TRANSITION_RELOAD, diff --git a/src/core/web_contents_delegate_qt.cpp b/src/core/web_contents_delegate_qt.cpp index 9855e3859..255ff0034 100644 --- a/src/core/web_contents_delegate_qt.cpp +++ b/src/core/web_contents_delegate_qt.cpp @@ -89,15 +89,17 @@ namespace QtWebEngineCore { -// Maps the LogSeverity defines in base/logging.h to the web engines message levels. -static WebContentsAdapterClient::JavaScriptConsoleMessageLevel mapToJavascriptConsoleMessageLevel(int32_t messageLevel) +static WebContentsAdapterClient::JavaScriptConsoleMessageLevel mapToJavascriptConsoleMessageLevel(blink::mojom::ConsoleMessageLevel log_level) { - if (messageLevel < 1) + switch (log_level) { + case blink::mojom::ConsoleMessageLevel::kVerbose: + case blink::mojom::ConsoleMessageLevel::kInfo: return WebContentsAdapterClient::Info; - else if (messageLevel > 1) + case blink::mojom::ConsoleMessageLevel::kWarning: + return WebContentsAdapterClient::Warning; + case blink::mojom::ConsoleMessageLevel::kError: return WebContentsAdapterClient::Error; - - return WebContentsAdapterClient::Warning; + } } WebContentsDelegateQt::WebContentsDelegateQt(content::WebContents *webContents, WebContentsAdapterClient *adapterClient) @@ -537,7 +539,7 @@ void WebContentsDelegateQt::ExitFullscreenModeForTab(content::WebContents *web_c m_viewClient->requestFullScreenMode(toQt(web_contents->GetLastCommittedURL().GetOrigin()), false); } -bool WebContentsDelegateQt::IsFullscreenForTabOrPending(const content::WebContents* web_contents) const +bool WebContentsDelegateQt::IsFullscreenForTabOrPending(const content::WebContents* web_contents) { Q_UNUSED(web_contents); return m_viewClient->isFullScreenMode(); @@ -566,10 +568,11 @@ void WebContentsDelegateQt::RunFileChooser(content::RenderFrameHost * /*frameHos }); } -bool WebContentsDelegateQt::DidAddMessageToConsole(content::WebContents *source, int32_t level, const base::string16 &message, int32_t line_no, const base::string16 &source_id) +bool WebContentsDelegateQt::DidAddMessageToConsole(content::WebContents *source, blink::mojom::ConsoleMessageLevel log_level, + const base::string16 &message, int32_t line_no, const base::string16 &source_id) { Q_UNUSED(source) - m_viewClient->javaScriptConsoleMessage(mapToJavascriptConsoleMessageLevel(level), toQt(message), static_cast<int>(line_no), toQt(source_id)); + m_viewClient->javaScriptConsoleMessage(mapToJavascriptConsoleMessageLevel(log_level), toQt(message), static_cast<int>(line_no), toQt(source_id)); return false; } @@ -726,12 +729,12 @@ void WebContentsDelegateQt::BeforeUnloadFired(bool proceed, const base::TimeTick Q_UNUSED(proceed_time); } -bool WebContentsDelegateQt::CheckMediaAccessPermission(content::RenderFrameHost *, const GURL& security_origin, blink::MediaStreamType type) +bool WebContentsDelegateQt::CheckMediaAccessPermission(content::RenderFrameHost *, const GURL& security_origin, blink::mojom::MediaStreamType type) { switch (type) { - case blink::MEDIA_DEVICE_AUDIO_CAPTURE: + case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE: return m_viewClient->profileAdapter()->checkPermission(toQt(security_origin), ProfileAdapter::AudioCapturePermission); - case blink::MEDIA_DEVICE_VIDEO_CAPTURE: + case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE: return m_viewClient->profileAdapter()->checkPermission(toQt(security_origin), ProfileAdapter::VideoCapturePermission); default: LOG(INFO) << "WebContentsDelegateQt::CheckMediaAccessPermission: " @@ -830,28 +833,28 @@ void WebContentsDelegateQt::setLoadingState(LoadingState state) webContentsAdapter()->updateRecommendedState(); } -int &WebContentsDelegateQt::streamCount(blink::MediaStreamType type) +int &WebContentsDelegateQt::streamCount(blink::mojom::MediaStreamType type) { // Based on MediaStreamCaptureIndicator::WebContentsDeviceUsage::GetStreamCount switch (type) { - case blink::MEDIA_DEVICE_AUDIO_CAPTURE: + case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE: return m_audioStreamCount; - case blink::MEDIA_DEVICE_VIDEO_CAPTURE: + case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE: return m_videoStreamCount; - case blink::MEDIA_GUM_TAB_AUDIO_CAPTURE: - case blink::MEDIA_GUM_TAB_VIDEO_CAPTURE: + case blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE: + case blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE: return m_mirroringStreamCount; - case blink::MEDIA_GUM_DESKTOP_VIDEO_CAPTURE: - case blink::MEDIA_GUM_DESKTOP_AUDIO_CAPTURE: - case blink::MEDIA_DISPLAY_VIDEO_CAPTURE: - case blink::MEDIA_DISPLAY_AUDIO_CAPTURE: + case blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE: + case blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE: + case blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE: + case blink::mojom::MediaStreamType::DISPLAY_AUDIO_CAPTURE: return m_desktopStreamCount; - case blink::MEDIA_NO_SERVICE: - case blink::NUM_MEDIA_TYPES: + case blink::mojom::MediaStreamType::NO_SERVICE: + case blink::mojom::MediaStreamType::NUM_MEDIA_TYPES: NOTREACHED(); return m_videoStreamCount; } diff --git a/src/core/web_contents_delegate_qt.h b/src/core/web_contents_delegate_qt.h index f1d5ed76c..ba8c6b5a1 100644 --- a/src/core/web_contents_delegate_qt.h +++ b/src/core/web_contents_delegate_qt.h @@ -130,11 +130,12 @@ public: content::JavaScriptDialogManager *GetJavaScriptDialogManager(content::WebContents *source) override; void EnterFullscreenModeForTab(content::WebContents *web_contents, const GURL &origin, const blink::WebFullscreenOptions &) override; void ExitFullscreenModeForTab(content::WebContents*) override; - bool IsFullscreenForTabOrPending(const content::WebContents* web_contents) const override; + bool IsFullscreenForTabOrPending(const content::WebContents* web_contents) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, std::unique_ptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; - bool DidAddMessageToConsole(content::WebContents* source, int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) override; + bool DidAddMessageToConsole(content::WebContents *source, blink::mojom::ConsoleMessageLevel log_level, + const base::string16 &message, int32_t line_no, const base::string16 &source_id) override; void FindReply(content::WebContents *source, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestMediaAccessPermission(content::WebContents *web_contents, const content::MediaStreamRequest &request, @@ -143,7 +144,7 @@ public: void UpdateTargetURL(content::WebContents* source, const GURL& url) override; void RequestToLockMouse(content::WebContents *web_contents, bool user_gesture, bool last_unlocked_by_target) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; - bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::MediaStreamType type) override; + bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RegisterProtocolHandler(content::WebContents* web_contents, const std::string& protocol, const GURL& url, bool user_gesture) override; void UnregisterProtocolHandler(content::WebContents* web_contents, const std::string& protocol, const GURL& url, bool user_gesture) override; bool TakeFocus(content::WebContents *source, bool reverse) override; @@ -208,7 +209,7 @@ private: LoadingState determineLoadingState(content::WebContents *contents); void setLoadingState(LoadingState state); - int &streamCount(blink::MediaStreamType type); + int &streamCount(blink::mojom::MediaStreamType type); WebContentsAdapterClient *m_viewClient; QVector<int64_t> m_loadingErrorFrameList; diff --git a/src/core/web_engine_context.cpp b/src/core/web_engine_context.cpp index a42565c2b..d4dfaba28 100644 --- a/src/core/web_engine_context.cpp +++ b/src/core/web_engine_context.cpp @@ -53,10 +53,13 @@ #include "chrome/browser/printing/print_job_manager.h" #include "components/printing/browser/features.h" #endif +#include "components/discardable_memory/service/discardable_shared_memory_manager.h" #include "components/viz/common/features.h" #include "components/web_cache/browser/web_cache_manager.h" +#include "content/app/service_manager_environment.h" #include "content/browser/devtools/devtools_http_handler.h" #include "content/browser/scheduler/browser_task_executor.h" +#include "content/browser/startup_data_impl.h" #include "content/browser/startup_helper.h" #include "content/public/app/content_main.h" #include "content/public/app/content_main_runner.h" @@ -72,7 +75,6 @@ #include "content/public/common/main_function_params.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/command_buffer/service/sync_point_manager.h" -#include "gpu/ipc/host/gpu_switches.h" #include "media/audio/audio_manager.h" #include "media/base/media_switches.h" #include "mojo/core/embedder/embedder.h" @@ -82,6 +84,7 @@ #include "services/network/public/cpp/network_switches.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" #include "services/service_manager/sandbox/switches.h" +#include "services/tracing/public/cpp/tracing_features.h" #include "third_party/blink/public/common/features.h" #include "ui/events/event_switches.h" #include "ui/native_theme/native_theme_features.h" @@ -91,6 +94,10 @@ #include "content/public/app/sandbox_helper_win.h" #endif // OS_WIN +#if defined(Q_OS_MACOS) +#include "base/mac/foundation_util.h" +#endif + #ifndef QT_NO_ACCESSIBILITY #include "accessibility_activation_observer.h" #endif @@ -278,6 +285,11 @@ void WebEngineContext::destroy() // Destroy the main runner, this stops main message loop m_browserRunner.reset(); + // These would normally be in the content-runner, but we allocated them separately: + m_startupData.reset(); + m_serviceManagerEnvironment.reset(); + m_discardableSharedMemoryManager.reset(); + // Destroying content-runner will force Chromium at_exit calls to run, and // reap child processes. m_contentRunner.reset(); @@ -390,7 +402,13 @@ WebEngineContext::WebEngineContext() : m_mainDelegate(new ContentMainDelegateQt) , m_globalQObject(new QObject()) { - base::ThreadPool::Create("Browser"); +#if defined(Q_OS_MACOS) + // The bundled handling is currently both completely broken in Chromium, + // and unnecessary for us. + base::mac::SetOverrideAmIBundled(false); +#endif + + base::ThreadPoolInstance::Create("Browser"); m_contentRunner.reset(content::ContentMainRunner::Create()); m_browserRunner = content::BrowserMainRunner::Create(); @@ -460,8 +478,6 @@ WebEngineContext::WebEngineContext() parsedCommandLine->AppendSwitch(switches::kDisableAcceleratedVideoDecode); // Same problem with Pepper using OpenGL images. parsedCommandLine->AppendSwitch(switches::kDisablePepper3DImageChromium); - // Same problem with select popups. - parsedCommandLine->AppendSwitch(switches::kDisableNativeGpuMemoryBuffers); #endif #if defined(Q_OS_WIN) @@ -505,10 +521,11 @@ WebEngineContext::WebEngineContext() // This is deprecated behavior, and will be removed in a future Chromium version, as per // upstream Chromium commit ba52f56207a4b9d70b34880fbff2352e71a06422. appendToFeatureList(enableFeatures, features::kAllowContentInitiatedDataUrlNavigations.name); + + appendToFeatureList(enableFeatures, features::kTracingServiceInProcess.name); + // The video-capture service is not functioning at this moment (since 69) appendToFeatureList(disableFeatures, features::kMojoVideoCapture.name); - // Breaks WebEngineNewViewRequest.userInitiated API (since 73) - appendToFeatureList(disableFeatures, features::kUserActivationV2.name); // We do not yet support the network-service, but it is enabled by default since 75. appendToFeatureList(disableFeatures, network::features::kNetworkService.name); @@ -522,6 +539,7 @@ WebEngineContext::WebEngineContext() // Explicitly tell Chromium about default-on features we do not support appendToFeatureList(disableFeatures, features::kBackgroundFetch.name); appendToFeatureList(disableFeatures, features::kOriginTrials.name); + appendToFeatureList(disableFeatures, features::kSmsReceiver.name); appendToFeatureList(disableFeatures, features::kWebAuth.name); appendToFeatureList(disableFeatures, features::kWebAuthCable.name); appendToFeatureList(disableFeatures, features::kWebPayments.name); @@ -536,8 +554,6 @@ WebEngineContext::WebEngineContext() } if (!enableViz) { - // Surface synchronization breaks our current graphics integration (since 65) - appendToFeatureList(disableFeatures, features::kEnableSurfaceSynchronization.name); // Viz Display Compositor is enabled by default since 73. Doesn't work for us (also implies SurfaceSynchronization) appendToFeatureList(disableFeatures, features::kVizDisplayCompositor.name); // VideoSurfaceLayer is enabled by default since 75. We don't support it. @@ -644,21 +660,27 @@ WebEngineContext::WebEngineContext() #endif m_contentRunner->Initialize(contentMainParams); - mojo::core::Init(); + mojo::core::Configuration mojoConfiguration; + mojoConfiguration.is_broker_process = true; + mojo::core::Init(mojoConfiguration); // This block mirrors ContentMainRunnerImpl::RunServiceManager(): m_mainDelegate->PreCreateMainMessageLoop(); - base::MessageLoop::InitMessagePumpForUIFactory(messagePumpFactory); + base::MessagePump::OverrideMessagePumpForUIFactory(messagePumpFactory); content::BrowserTaskExecutor::Create(); m_mainDelegate->PostEarlyInitialization(false); content::StartBrowserThreadPool(); content::BrowserTaskExecutor::PostFeatureListSetup(); + m_discardableSharedMemoryManager = std::make_unique<discardable_memory::DiscardableSharedMemoryManager>(); + m_serviceManagerEnvironment = std::make_unique<content::ServiceManagerEnvironment>(content::BrowserTaskExecutor::CreateIOThread()); + m_startupData = m_serviceManagerEnvironment->CreateBrowserStartupData(); // Once the MessageLoop has been created, attach a top-level RunLoop. m_runLoop.reset(new base::RunLoop); m_runLoop->BeforeRun(); content::MainFunctionParams mainParams(*base::CommandLine::ForCurrentProcess()); + mainParams.startup_data = m_startupData.get(); m_browserRunner->Initialize(mainParams); m_devtoolsServer.reset(new DevToolsServerQt()); diff --git a/src/core/web_engine_context.h b/src/core/web_engine_context.h index 2364bacbe..5892017c5 100644 --- a/src/core/web_engine_context.h +++ b/src/core/web_engine_context.h @@ -56,6 +56,12 @@ class ContentMainRunner; class GpuProcess; class GpuThreadController; class InProcessChildThreadParams; +class ServiceManagerEnvironment; +struct StartupData; +} + +namespace discardable_memory { +class DiscardableSharedMemoryManager; } namespace gpu { @@ -116,6 +122,9 @@ private: std::unique_ptr<ContentMainDelegateQt> m_mainDelegate; std::unique_ptr<content::ContentMainRunner> m_contentRunner; std::unique_ptr<content::BrowserMainRunner> m_browserRunner; + std::unique_ptr<discardable_memory::DiscardableSharedMemoryManager> m_discardableSharedMemoryManager; + std::unique_ptr<content::StartupData> m_startupData; + std::unique_ptr<content::ServiceManagerEnvironment> m_serviceManagerEnvironment; std::unique_ptr<QObject> m_globalQObject; std::unique_ptr<ProfileAdapter> m_defaultProfileAdapter; std::unique_ptr<DevToolsServerQt> m_devtoolsServer; diff --git a/src/core/web_event_factory.cpp b/src/core/web_event_factory.cpp index 7f5306e67..3598c1c78 100644 --- a/src/core/web_event_factory.cpp +++ b/src/core/web_event_factory.cpp @@ -926,7 +926,7 @@ static ui::DomKey domKeyForQtKey(int qtKey) return ui::DomKey::ZENKAKU; case Qt::Key_Zenkaku_Hankaku: return ui::DomKey::ZENKAKU_HANKAKU; - +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) // Dead keys (ui/events/keycodes/keyboard_code_conversion_xkb.cc) case Qt::Key_Dead_Grave: return ui::DomKey::DeadKeyFromCombiningCharacter(0x0300); @@ -994,7 +994,7 @@ static ui::DomKey domKeyForQtKey(int qtKey) return ui::DomKey::DeadKeyFromCombiningCharacter(0x00A4); case Qt::Key_Dead_Greek: return ui::DomKey::DeadKeyFromCombiningCharacter(0x037E); - +#endif // General-Purpose Function Keys case Qt::Key_F1: return ui::DomKey::F1; diff --git a/src/src.pro b/src/src.pro index 99967fd82..de88878a6 100644 --- a/src/src.pro +++ b/src/src.pro @@ -1,16 +1,18 @@ -load(platform) +load(functions) include($$QTWEBENGINE_OUT_ROOT/src/buildtools/qtbuildtools-config.pri) -QT_FOR_CONFIG += buildtools-private +include($$QTWEBENGINE_OUT_ROOT/src/core/qtwebenginecore-config.pri) +include($$QTWEBENGINE_OUT_ROOT/src/webengine/qtwebengine-config.pri) +include($$QTWEBENGINE_OUT_ROOT/src/webenginewidgets/qtwebenginewidgets-config.pri) + +QT_FOR_CONFIG += buildtools-private webenginecore webenginecore-private webengine-private \ + webenginewidgets-private TEMPLATE = subdirs -isWebEngineCoreBuild():qtConfig(webengine-core) { - include($$QTWEBENGINE_OUT_ROOT/src/core/qtwebenginecore-config.pri) - include($$QTWEBENGINE_OUT_ROOT/src/webengine/qtwebengine-config.pri) - include($$QTWEBENGINE_OUT_ROOT/src/webenginewidgets/qtwebenginewidgets-config.pri) - QT_FOR_CONFIG += webenginecore webenginecore-private webengine-private webenginewidgets-private +qtConfig(build-qtwebengine-core):qtConfig(webengine-core-support) { + core.depends = buildtools process.depends = core webengine.depends = core webenginewidgets.depends = core webengine @@ -18,16 +20,12 @@ isWebEngineCoreBuild():qtConfig(webengine-core) { webengine_plugin.target = sub-webengine-plugin webengine_plugin.depends = webengine - core.depends = buildtools - - SUBDIRS += buildtools \ - core \ - process + SUBDIRS += buildtools core process qtConfig(webengine-spellchecker):!qtConfig(webengine-native-spellchecker):!cross_compile { - SUBDIRS += qwebengine_convert_dict - qwebengine_convert_dict.subdir = tools/qwebengine_convert_dict - qwebengine_convert_dict.depends = core + SUBDIRS += qwebengine_convert_dict + qwebengine_convert_dict.subdir = tools/qwebengine_convert_dict + qwebengine_convert_dict.depends = core } qtConfig(webengine-qml) { @@ -38,13 +36,14 @@ isWebEngineCoreBuild():qtConfig(webengine-core) { SUBDIRS += plugins webenginewidgets plugins.depends = webenginewidgets } -} else { - !isEmpty(skipBuildReason):!build_pass { - log(QtWebEngine will not be built. $${skipBuildReason} $${EOL}) - errorbuild.commands = @echo QtWebEngine will not be built. $${skipBuildReason} - errorbuild.CONFIG = phony - QMAKE_EXTRA_TARGETS += errorbuild - first.depends += errorbuild - QMAKE_EXTRA_TARGETS += first - } +} + +!qtConfig(webengine-core-support): qtConfig(build-qtwebengine-core) { + !qtwebengine_makeCheckError():!isEmpty(skipBuildReason):!build_pass { + errorbuild.commands = @echo Modules will not be built. $${skipBuildReason} + errorbuild.CONFIG = phony + QMAKE_EXTRA_TARGETS += errorbuild + first.depends += errorbuild + QMAKE_EXTRA_TARGETS += first + } } diff --git a/src/tools/qwebengine_convert_dict/qwebengine_convert_dict.pro b/src/tools/qwebengine_convert_dict/qwebengine_convert_dict.pro index 27edd66d8..57f79f582 100644 --- a/src/tools/qwebengine_convert_dict/qwebengine_convert_dict.pro +++ b/src/tools/qwebengine_convert_dict/qwebengine_convert_dict.pro @@ -30,8 +30,12 @@ win32: QMAKE_CXXFLAGS_WARN_ON = -wd4577 # Issue with some template compliation, smb smart should look at it win32: DEFINES += NOMINMAX +# To avoid conflict between windows.h and BoringSSL headers +win32: DEFINES += WIN32_LEAN_AND_MEAN + CHROMIUM_SRC_DIR = $$QTWEBENGINE_ROOT/$$getChromiumSrcDir() INCLUDEPATH += $$CHROMIUM_SRC_DIR \ + $$CHROMIUM_SRC_DIR/third_party/boringssl/src/include \ $$OUT_PWD/../../core/$$getConfigDir()/gen SOURCES += \ diff --git a/src/webengine/api/qquickwebenginedownloaditem.cpp b/src/webengine/api/qquickwebenginedownloaditem.cpp index f9b305e88..878dddadb 100644 --- a/src/webengine/api/qquickwebenginedownloaditem.cpp +++ b/src/webengine/api/qquickwebenginedownloaditem.cpp @@ -420,6 +420,9 @@ QString QQuickWebEngineDownloadItem::mimeType() const \qmlproperty string WebEngineDownloadItem::path \obsolete + Use \l suggestedFileName, \l downloadDirectory, and + \l downloadFileName instead. + Holds the full target path where data is being downloaded to. The path includes the file name. The default suggested path is the standard @@ -463,7 +466,7 @@ void QQuickWebEngineDownloadItem::setPath(QString path) newDirectory = QStringLiteral(""); newFileName = path; } else { - newDirectory = QFileInfo(path).filePath(); + newDirectory = QFileInfo(path).path(); newFileName = QFileInfo(path).fileName(); } @@ -500,7 +503,7 @@ QString QQuickWebEngineDownloadItem::downloadDirectory() const return d->downloadDirectory; } -void QQuickWebEngineDownloadItem::setDownloadDirectory(QString directory) +void QQuickWebEngineDownloadItem::setDownloadDirectory(const QString &directory) { Q_D(QQuickWebEngineDownloadItem); if (d->downloadState != QQuickWebEngineDownloadItem::DownloadRequested) { @@ -548,7 +551,7 @@ QString QQuickWebEngineDownloadItem::downloadFileName() const return d->downloadFileName; } -void QQuickWebEngineDownloadItem::setDownloadFileName(QString fileName) +void QQuickWebEngineDownloadItem::setDownloadFileName(const QString &fileName) { Q_D(QQuickWebEngineDownloadItem); if (d->downloadState != QQuickWebEngineDownloadItem::DownloadRequested) { diff --git a/src/webengine/api/qquickwebenginedownloaditem_p.h b/src/webengine/api/qquickwebenginedownloaditem_p.h index cef99e534..96ef0daf0 100644 --- a/src/webengine/api/qquickwebenginedownloaditem_p.h +++ b/src/webengine/api/qquickwebenginedownloaditem_p.h @@ -152,8 +152,8 @@ public: qint64 totalBytes() const; qint64 receivedBytes() const; QString mimeType() const; - QString Q_DECL_DEPRECATED path() const; - void Q_DECL_DEPRECATED setPath(QString path); + QString path() const; + void setPath(QString path); SavePageFormat savePageFormat() const; void setSavePageFormat(SavePageFormat format); DownloadType Q_DECL_DEPRECATED type() const; @@ -166,9 +166,9 @@ public: QUrl url() const; QString suggestedFileName() const; QString downloadDirectory() const; - void setDownloadDirectory(QString directory); + void setDownloadDirectory(const QString &directory); QString downloadFileName() const; - void setDownloadFileName(QString fileName); + void setDownloadFileName(const QString &fileName); Q_SIGNALS: void stateChanged(); @@ -176,7 +176,7 @@ Q_SIGNALS: void receivedBytesChanged(); void totalBytesChanged(); Q_REVISION(1) void mimeTypeChanged(); - void Q_DECL_DEPRECATED pathChanged(); + void pathChanged(); Q_REVISION(3) void typeChanged(); Q_REVISION(4) void interruptReasonChanged(); Q_REVISION(5) void isFinishedChanged(); diff --git a/src/webengine/api/qquickwebengineprofile.cpp b/src/webengine/api/qquickwebengineprofile.cpp index 57434e296..edad7ec44 100644 --- a/src/webengine/api/qquickwebengineprofile.cpp +++ b/src/webengine/api/qquickwebengineprofile.cpp @@ -157,7 +157,10 @@ ASSERT_ENUMS_MATCH(QQuickWebEngineDownloadItem::MimeHtmlSaveFormat, QtWebEngineC \fn QQuickWebEngineProfile::presentNotification(QWebEngineNotification *notification) This signal is emitted whenever there is a newly created user notification. - The \a notification argument holds the notification instance to query data and interact with. + The \a notification argument holds the \l {QWebEngineNotification} instance + to query data and interact with. + + \sa WebEngineProfile::presentNotification */ QQuickWebEngineProfilePrivate::QQuickWebEngineProfilePrivate(ProfileAdapter *profileAdapter) @@ -395,7 +398,8 @@ void QQuickWebEngineProfilePrivate::userScripts_clear(QQmlListProperty<QQuickWeb \since QtWebEngine 1.9 This signal is emitted whenever there is a newly created user notification. - The \a notification argument holds the notification instance to query data and interact with. + The \a notification argument holds the \l {WebEngineNotification} instance + to query data and interact with. */ /*! diff --git a/src/webengine/api/qquickwebenginesettings.cpp b/src/webengine/api/qquickwebenginesettings.cpp index 93a3668ed..9a102a504 100644 --- a/src/webengine/api/qquickwebenginesettings.cpp +++ b/src/webengine/api/qquickwebenginesettings.cpp @@ -250,7 +250,7 @@ bool QQuickWebEngineSettings::pluginsEnabled() const Tells the web engine whether fullscreen is supported in this application or not. - Enabled by default. + Disabled by default. */ bool QQuickWebEngineSettings::fullScreenSupportEnabled() const { diff --git a/src/webengine/api/qquickwebengineview.cpp b/src/webengine/api/qquickwebengineview.cpp index 58d950cd9..8a1a3c516 100644 --- a/src/webengine/api/qquickwebengineview.cpp +++ b/src/webengine/api/qquickwebengineview.cpp @@ -297,7 +297,7 @@ void QQuickWebEngineViewPrivate::allowCertificateError(const QSharedPointer<Cert // mark the object for gc by creating temporary jsvalue qmlEngine(q)->newQObject(quickController); Q_EMIT q->certificateError(quickController); - if (!quickController->deferred() && !quickController->answered()) + if (!quickController->overridable() || (!quickController->deferred() && !quickController->answered())) quickController->rejectCertificate(); else m_certificateErrorControllers.append(errorController); @@ -1152,9 +1152,7 @@ void QQuickWebEngineViewPrivate::updateAdapter() adapter->setClient(this); if (wasInitialized) { if (!m_html.isEmpty()) - adapter->setContent(m_html.toUtf8(), defaultMimeType, m_url); - else if (m_url.isValid()) - adapter->load(m_url); + adapter->setContent(m_html.toUtf8(), defaultMimeType, activeUrl); else if (activeUrl.isValid()) adapter->load(activeUrl); else diff --git a/src/webengine/doc/src/qtwebengine-features.qdoc b/src/webengine/doc/src/qtwebengine-features.qdoc index 08c189740..22eb72408 100644 --- a/src/webengine/doc/src/qtwebengine-features.qdoc +++ b/src/webengine/doc/src/qtwebengine-features.qdoc @@ -45,12 +45,13 @@ \li \l{Native Dialogs} \li \l{Pepper Plugin API} \li \l{PDF File Viewing} + \li \l{Page Lifecycle API} \li \l{Print to PDF} \li \l{Process Models} \li \l{Spellchecker} \li \l{Touch} \li \l{View Source} - \li \l{WebRTC} + \li \l{webrtc_feature}{WebRTC} \li \l{Web Notifications} \endlist @@ -126,7 +127,9 @@ so uniquely identifies the user and might violate privacy expectations. To activate support for client certificates, an application needs to listen to - the QWebEnginePage::selectClientCertificate signal and select one of the offered + the QWebEnginePage::selectClientCertificate or + \l{WebEnginePage::selectClientCertificate}{WebEnginePage.selectClientCertificate} + signals and select one of the offered certificates. For applications that can navigate to untrusted web sites, it is recommended to always give the user a choice before uniquely identifying them to a remote server. @@ -335,6 +338,83 @@ Support for this feature was added in Qt 5.13.0. + \section1 Page Lifecycle API + + \QWE supports the \l {https://wicg.github.io/page-lifecycle/spec.html}{Page + Lifecycle API specification}, a work-in-progress extension to the HTML + standard for allowing user agents to reduce their resource consumption by + freezing or discarding background pages. The feature is exposed both in the + Widgets and QML APIs. + + For an example of the QML API in use, see the \l {WebEngine Lifecycle + Example}. + + Support for this feature was added in Qt 5.14.0. + + \section2 Overview of Lifecycle States + + Each \l {WebEngineView} item (or \l {QWebEnginePage} object) can be in one + of three \e {lifecycle states}: active, frozen, or discarded. These states, + like the sleep states of a CPU, control the resource usage of web views. + + The \e {active} state is the normal, unrestricted state of a web view. All + visible web views are always in the active state, as are all web views that + have not yet finished loading. Only invisible, idle web views can be + transitioned to other lifecycle states. + + The \e {frozen} state is a low CPU usage state. In this state, most HTML + task sources are suspended (frozen) and, as a result, most DOM event + processing and JavaScript execution will also be suspended. The web view + must be invisible in order to be frozen as rendering is not possible in this + state. + + The \e {discarded} state is an extreme resource-saving state. In this state, + the browsing context of the web view will be discarded and the corresponding + renderer subprocess shut down. CPU and memory usage in this state is reduced + virtually to zero. On exiting this state the web page will be automatically + reloaded. The process of entering and exiting the discarded state is similar + to serializing the browsing history of the web view and destroying the view, + then creating a new view and restoring its history. + + See also \l {WebEngineView::LifecycleState}. The equivalent in the Widgets + API is \l {QWebEnginePage::LifecycleState}. + + \section2 The \c {lifecycleState} and \c {recommendedState} Properties + + The \l {WebEngineView::}{lifecycleState} property of the \l {WebEngineView} + type is a read-write property that controls the current lifecycle state of + the web view. This property is designed to place as few restrictions as + possible on what states can be transitioned to. For example, it is allowed + to freeze a web view that is currently playing music in the background, + stopping the music. In order to implement a less aggressive resource-saving + strategy that avoids interrupting user-visible background activity, the \l + {WebEngineView::} {recommendedState} property must be used. + + The \l {WebEngineView::}{recommendedState} property of the \l + {WebEngineView} type is a read-only property that calculates a safe limit on + the \l {WebEngineView::}{lifecycleState} property, taking into account the + current activity of the web view. So, in the example of a web view playing + music in the background, the recommended state will be \c {Active} since a + more aggressive state would stop the music. If the application wants to + avoid interrupting background activity, then it should avoid putting the web + view into a more aggressively resource-saving lifecycle state than what's + given by \l {WebEngineView::}{recommendedState}. + + See also \l {WebEngineView::lifecycleState} and \l + {WebEngineView::recommendedState}. The equivalents in the Widgets API are \l + {QWebEnginePage::lifecycleState} and \l {QWebEnginePage::recommendedState}. + + \section2 The DOM Extensions + + The \l {WebEngineView::}{lifecycleState} property is connected to the \l + {https://wicg.github.io/page-lifecycle/spec.html}{Page Lifecycle API + specification}, which specifies two new DOM events, \c {freeze} and \c + {resume}, and adds a new \c {Document.wasDiscarded} boolean property. The \c + {freeze} and \c {resume} events are fired when transitioning from the \c + {Active} to the \c {Frozen state}, and vice-versa. The \c + {Document.wasDiscarded} property is set to \c {true} when transitioning from + the \c {Discarded} state to the \c {Active} state. + \section1 Print to PDF \QWE supports printing a web page to a PDF file. For more @@ -519,6 +599,7 @@ Support for this feature was added in Qt 5.8.0. + \target webrtc_feature \section1 WebRTC WebRTC provides browsers with Real-Time Communications (RTC) capabilities diff --git a/src/webengine/doc/src/qtwebengine-platform-notes.qdoc b/src/webengine/doc/src/qtwebengine-platform-notes.qdoc index 5b7d750ff..5d32fa6c7 100644 --- a/src/webengine/doc/src/qtwebengine-platform-notes.qdoc +++ b/src/webengine/doc/src/qtwebengine-platform-notes.qdoc @@ -73,6 +73,8 @@ \list \li Visual Studio 2017 version 15.8 or later + \li Active Template Library (ATL), usually included in the Visual Studio + installation \li Windows 10 SDK \endlist diff --git a/src/webengine/doc/src/qtwebengine-qmlmodule.qdoc b/src/webengine/doc/src/qtwebengine-qmlmodule.qdoc index 540d74035..44e6c7e27 100644 --- a/src/webengine/doc/src/qtwebengine-qmlmodule.qdoc +++ b/src/webengine/doc/src/qtwebengine-qmlmodule.qdoc @@ -26,7 +26,7 @@ ****************************************************************************/ /*! - \qmlmodule QtWebEngine 1.9 + \qmlmodule QtWebEngine 1.10 \title Qt WebEngine QML Types \brief Provides QML types for rendering web content within a QML application. \ingroup qtwebengine-modules @@ -36,7 +36,7 @@ your .qml file: \badcode - import QtWebEngine 1.9 + import QtWebEngine 1.10 \endcode To link against the module, add the following QT variable to your qmake .pro diff --git a/src/webengine/doc/src/webengineview_lgpl.qdoc b/src/webengine/doc/src/webengineview_lgpl.qdoc index 8f03774c8..3a7717bd2 100644 --- a/src/webengine/doc/src/webengineview_lgpl.qdoc +++ b/src/webengine/doc/src/webengineview_lgpl.qdoc @@ -396,7 +396,7 @@ runJavaScript("document.title", function(result) { console.log(result); }); \endcode - Only "plain data" can be returned from JavaScript as the result value. + 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}. @@ -407,7 +407,8 @@ \warning Do not execute lengthy routines in the callback function, because it might block the rendering of the web content. - See WebEngineView::userScripts for an alternative API to inject scripts. + For more information about injecting scripts, see \l {Script Injection}. + For an alternative way to inject scripts, see WebEngineView::userScripts. */ /*! @@ -444,14 +445,13 @@ To clear the search highlight, just pass an empty string. - The \a resultCallback must take a boolean parameter. It will be called with - a value of true if the \a subString was found; otherwise the callback value - will be false. + The \a resultCallback must take an integer parameter. It will be called with + the number of found occurrences of the \a subString. \code - findText("Qt", WebEngineView.FindCaseSensitively, function(success) { - if (success) - console.log("Qt was found!"); + findText("Qt", WebEngineView.FindCaseSensitively, function(matchCount) { + if (matchCount > 0) + console.log("'Qt' tokens found:", matchCount); }); \endcode @@ -1530,7 +1530,7 @@ /*! \qmlproperty enumeration WebEngineView::LifecycleState - \since QtWebEngine 1.11 + \since QtWebEngine 1.10 This enum describes the lifecycle state of the page: @@ -1541,12 +1541,12 @@ \value WebEngineView.LifecycleState.Discarded Very low resource usage state where the entire browsing context is discarded. - \sa lifecycleState + \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ /*! \qmlproperty LifecycleState WebEngineView::lifecycleState - \since QtWebEngine 1.11 + \since QtWebEngine 1.10 \brief The current lifecycle state of the page. @@ -1563,12 +1563,12 @@ These are the only hard limits on the lifecycle state, but see also \l{recommendedState} for the recommended soft limits. - \sa recommendedState, {WebEngine Lifecycle Example} + \sa recommendedState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ /*! \qmlproperty LifecycleState WebEngineView::recommendedState - \since QtWebEngine 1.11 + \since QtWebEngine 1.10 \brief The recommended limit for the lifecycle state of the page. @@ -1577,14 +1577,14 @@ playback or loss of HTML form input. Setting the lifecycle state to a higher resource state is however completely safe. - \sa lifecycleState, {WebEngine Lifecycle Example} + \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ /*! \qmltype FindTextResult \instantiates QWebEngineFindTextResult \inqmlmodule QtWebEngine - \since QtWebEngine 1.11 + \since QtWebEngine 1.10 \brief A utility type for encapsulating the result of a string search on a page. diff --git a/src/webengine/plugin/plugin.cpp b/src/webengine/plugin/plugin.cpp index e47a46a95..5fb48d867 100644 --- a/src/webengine/plugin/plugin.cpp +++ b/src/webengine/plugin/plugin.cpp @@ -164,10 +164,12 @@ public: qmlRegisterUncreatableType<QWebEngineRegisterProtocolHandlerRequest>(uri, 1, 7, "RegisterProtocolHandlerRequest", msgUncreatableType("RegisterProtocolHandlerRequest")); qmlRegisterUncreatableType<QQuickWebEngineAction>(uri, 1, 8, "WebEngineAction", msgUncreatableType("WebEngineAction")); +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) qmlRegisterUncreatableType<QQuickWebEngineClientCertificateSelection>(uri, 1, 9, "WebEngineClientCertificateSelection", msgUncreatableType("WebEngineClientCertificateSelection")); qmlRegisterUncreatableType<QQuickWebEngineClientCertificateOption>(uri, 1, 9, "WebEngineClientCertificateOption", msgUncreatableType("WebEngineClientCertificateOption")); +#endif qmlRegisterUncreatableType<QWebEngineNotification>(uri, 1, 9, "WebEngineNotification", msgUncreatableType("WebEngineNotification")); qmlRegisterUncreatableType<QQuickWebEngineTooltipRequest>(uri, 1, 10, "TooltipRequest", msgUncreatableType("TooltipRequest")); diff --git a/src/webengine/render_widget_host_view_qt_delegate_quick.cpp b/src/webengine/render_widget_host_view_qt_delegate_quick.cpp index 3a103b9aa..ac32671aa 100644 --- a/src/webengine/render_widget_host_view_qt_delegate_quick.cpp +++ b/src/webengine/render_widget_host_view_qt_delegate_quick.cpp @@ -106,7 +106,11 @@ QRectF RenderWidgetHostViewQtDelegateQuick::viewGeometry() const const QPointF p2 = mapToGlobal(mapFromScene(QPointF(width(), height()))); QRectF geometry = QRectF(p1, p2).normalized(); // But keep the size untransformed to behave like other QQuickItems. +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) geometry.setSize(size()); +#else + geometry.setSize(QSizeF(width(), height())); +#endif return geometry; } diff --git a/src/webengine/render_widget_host_view_qt_delegate_quickwindow.cpp b/src/webengine/render_widget_host_view_qt_delegate_quickwindow.cpp index 23b9e02c2..d3ebdbf27 100644 --- a/src/webengine/render_widget_host_view_qt_delegate_quickwindow.cpp +++ b/src/webengine/render_widget_host_view_qt_delegate_quickwindow.cpp @@ -48,7 +48,7 @@ RenderWidgetHostViewQtDelegateQuickWindow::RenderWidgetHostViewQtDelegateQuickWi : m_realDelegate(realDelegate) , m_virtualParent(nullptr) { - setFlags(Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus); + setFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus); } RenderWidgetHostViewQtDelegateQuickWindow::~RenderWidgetHostViewQtDelegateQuickWindow() diff --git a/src/webengine/ui/ToolTip.qml b/src/webengine/ui/ToolTip.qml index 96033e8f1..2bfe9eaf5 100644 --- a/src/webengine/ui/ToolTip.qml +++ b/src/webengine/ui/ToolTip.qml @@ -47,8 +47,9 @@ Item { visible: false property alias text: toolTip.text - property int delayTimerInterval: 1000 - property int hideTimerInterval: 1500 + property int delayTimerInterval: 500 + property int hideTimerInterval: 10000 + property int toolTipMaxWidth: 400 Timer { id: delayTimer @@ -77,7 +78,8 @@ Item { Text { id: toolTip anchors {fill: parent; margins: 5} - wrapMode: Text.WrapAnywhere + wrapMode: Text.Wrap + width: Math.min(toolTipMaxWidth, (toolTip.text.length +1) * 8) } } diff --git a/src/webenginewidgets/api/qwebenginecertificateerror.cpp b/src/webenginewidgets/api/qwebenginecertificateerror.cpp index a61d98f94..45277e19d 100644 --- a/src/webenginewidgets/api/qwebenginecertificateerror.cpp +++ b/src/webenginewidgets/api/qwebenginecertificateerror.cpp @@ -110,9 +110,9 @@ QWebEngineCertificateError::QWebEngineCertificateError(const QSharedPointer<Cert d->chain = controller->chain(); } -QWebEngineCertificateError::QWebEngineCertificateError(const QWebEngineCertificateError &other) = default; +QWebEngineCertificateError::QWebEngineCertificateError(const QWebEngineCertificateError &) = default; -QWebEngineCertificateError& QWebEngineCertificateError::operator=(const QWebEngineCertificateError &other) = default; +QWebEngineCertificateError& QWebEngineCertificateError::operator=(const QWebEngineCertificateError &) = default; /*! \internal */ @@ -190,6 +190,8 @@ QString QWebEngineCertificateError::errorDescription() const } /*! + \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 ignore a @@ -207,6 +209,8 @@ void QWebEngineCertificateError::defer() } /*! + \since 5.14 + Returns whether the decision for error handling was delayed and the URL load was halted. */ bool QWebEngineCertificateError::deferred() const @@ -215,6 +219,8 @@ bool QWebEngineCertificateError::deferred() const } /*! + \since 5.14 + Ignores the certificate error and continues the loading of the requested URL. */ void QWebEngineCertificateError::ignoreCertificateError() @@ -223,6 +229,8 @@ void QWebEngineCertificateError::ignoreCertificateError() } /*! + \since 5.14 + Rejects the certificate and aborts the loading of the requested URL. */ void QWebEngineCertificateError::rejectCertificate() @@ -231,7 +239,9 @@ void QWebEngineCertificateError::rejectCertificate() } /*! - Returns \c true if the error was explicitly rejected or accepted. + \since 5.14 + + Returns \c true if the error was explicitly rejected or ignored. */ bool QWebEngineCertificateError::answered() const { @@ -239,7 +249,9 @@ bool QWebEngineCertificateError::answered() const } /*! - Returns the peer's chain of digital certificates + \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. */ diff --git a/src/webenginewidgets/api/qwebenginedownloaditem.cpp b/src/webenginewidgets/api/qwebenginedownloaditem.cpp index 7b0cfe074..724249208 100644 --- a/src/webenginewidgets/api/qwebenginedownloaditem.cpp +++ b/src/webenginewidgets/api/qwebenginedownloaditem.cpp @@ -560,7 +560,7 @@ void QWebEngineDownloadItem::setPath(QString path) d->downloadDirectory = QStringLiteral(""); d->downloadFileName = path; } else { - d->downloadDirectory = QFileInfo(path).filePath(); + d->downloadDirectory = QFileInfo(path).path(); d->downloadFileName = QFileInfo(path).fileName(); } } @@ -588,7 +588,7 @@ QString QWebEngineDownloadItem::downloadDirectory() const download item's state. */ -void QWebEngineDownloadItem::setDownloadDirectory(QString directory) +void QWebEngineDownloadItem::setDownloadDirectory(const QString &directory) { Q_D(QWebEngineDownloadItem); if (d->downloadState != QWebEngineDownloadItem::DownloadRequested) { @@ -626,7 +626,7 @@ QString QWebEngineDownloadItem::downloadFileName() const download item's state. */ -void QWebEngineDownloadItem::setDownloadFileName(QString fileName) +void QWebEngineDownloadItem::setDownloadFileName(const QString &fileName) { Q_D(QWebEngineDownloadItem); if (d->downloadState != QWebEngineDownloadItem::DownloadRequested) { diff --git a/src/webenginewidgets/api/qwebenginedownloaditem.h b/src/webenginewidgets/api/qwebenginedownloaditem.h index 169d80553..27fca6f8a 100644 --- a/src/webenginewidgets/api/qwebenginedownloaditem.h +++ b/src/webenginewidgets/api/qwebenginedownloaditem.h @@ -130,9 +130,9 @@ public: bool isSavePageDownload() const; QString suggestedFileName() const; QString downloadDirectory() const; - void setDownloadDirectory(QString directory); + void setDownloadDirectory(const QString &directory); QString downloadFileName() const; - void setDownloadFileName(QString fileName); + void setDownloadFileName(const QString &fileName); QWebEnginePage *page() const; diff --git a/src/webenginewidgets/api/qwebenginepage.cpp b/src/webenginewidgets/api/qwebenginepage.cpp index b22d47916..db3efa521 100644 --- a/src/webenginewidgets/api/qwebenginepage.cpp +++ b/src/webenginewidgets/api/qwebenginepage.cpp @@ -178,7 +178,6 @@ QWebEnginePagePrivate::QWebEnginePagePrivate(QWebEngineProfile *_profile) wasShownTimer.setSingleShot(true); QObject::connect(&wasShownTimer, &QTimer::timeout, [this](){ ensureInitialized(); - adapter->setVisible(true); }); profile->d_ptr->addWebContentsAdapterClient(this); @@ -442,7 +441,7 @@ void QWebEnginePagePrivate::didPrintPage(quint64 requestId, QSharedPointer<QByte printerThread->start(); PrinterWorker *printerWorker = new PrinterWorker(result, currentPrinter); - QObject::connect(printerWorker, &PrinterWorker::resultReady, q, [=](bool success) { + QObject::connect(printerWorker, &PrinterWorker::resultReady, q, [requestId, this](bool success) { currentPrinter = nullptr; m_callbacks.invoke(requestId, success); }); @@ -1720,8 +1719,8 @@ void QWebEnginePagePrivate::allowCertificateError(const QSharedPointer<Certifica accepted = q->certificateError(error); if (error.deferred() && !error.answered()) m_certificateErrorControllers.append(controller); - else if (!error.answered() && error.isOverridable()) - controller->accept(accepted); + else if (!error.answered()) + controller->accept(error.isOverridable() && accepted); } void QWebEnginePagePrivate::selectClientCert(const QSharedPointer<ClientCertSelectController> &controller) @@ -1817,7 +1816,7 @@ void QWebEnginePagePrivate::setToolTip(const QString &toolTipText) } // Update tooltip if text was changed. - QString wrappedTip = QLatin1String("<p style=\"white-space:pre\">") + QString wrappedTip = QLatin1String("<p style=\"white-space:pre-wrap\">") % toolTipText.toHtmlEscaped().left(MaxTooltipLength) % QLatin1String("</p>"); if (view->toolTip() != wrappedTip) @@ -2178,7 +2177,7 @@ void QWebEnginePage::runJavaScript(const QString& scriptSource, quint32 worldId, In addition, a page might also execute scripts added through QWebEngineProfile::scripts(). - \sa QWebEngineScriptCollection, QWebEngineScript + \sa QWebEngineScriptCollection, QWebEngineScript, {Script Injection} */ QWebEngineScriptCollection &QWebEnginePage::scripts() @@ -2544,7 +2543,7 @@ const QWebEngineContextMenuData &QWebEnginePage::contextMenuData() const \value Discarded Very low resource usage state where the entire browsing context is discarded. - \sa lifecycleState, {WebEngine Lifecycle Example} + \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ /*! @@ -2566,7 +2565,7 @@ const QWebEngineContextMenuData &QWebEnginePage::contextMenuData() const These are the only hard limits on the lifecycle state, but see also \l{recommendedState} for the recommended soft limits. - \sa recommendedState, {WebEngine Lifecycle Example} + \sa recommendedState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ QWebEnginePage::LifecycleState QWebEnginePage::lifecycleState() const @@ -2592,7 +2591,7 @@ void QWebEnginePage::setLifecycleState(LifecycleState state) playback or loss of HTML form input. Setting the lifecycle state to a higher resource state is however completely safe. - \sa lifecycleState + \sa lifecycleState, {Page Lifecycle API}, {WebEngine Lifecycle Example} */ QWebEnginePage::LifecycleState QWebEnginePage::recommendedState() const diff --git a/src/webenginewidgets/api/qwebengineprofile.cpp b/src/webenginewidgets/api/qwebengineprofile.cpp index 4a77eb8cf..09f5ce2fd 100644 --- a/src/webenginewidgets/api/qwebengineprofile.cpp +++ b/src/webenginewidgets/api/qwebengineprofile.cpp @@ -661,7 +661,8 @@ bool QWebEngineProfile::visitedLinksContainsUrl(const QUrl &url) const Returns the collection of scripts that are injected into all pages that share this profile. - \sa QWebEngineScriptCollection, QWebEngineScript, QWebEnginePage::scripts() + \sa QWebEngineScriptCollection, QWebEngineScript, QWebEnginePage::scripts(), + {Script Injection} */ QWebEngineScriptCollection *QWebEngineProfile::scripts() const { diff --git a/src/webenginewidgets/api/qwebenginescript.cpp b/src/webenginewidgets/api/qwebenginescript.cpp index d1e996b3a..af6b9aa8d 100644 --- a/src/webenginewidgets/api/qwebenginescript.cpp +++ b/src/webenginewidgets/api/qwebenginescript.cpp @@ -67,6 +67,8 @@ using QtWebEngineCore::UserScript; 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 diff --git a/src/webenginewidgets/api/qwebenginescriptcollection.cpp b/src/webenginewidgets/api/qwebenginescriptcollection.cpp index 5ef0ffd44..8cbeeb804 100644 --- a/src/webenginewidgets/api/qwebenginescriptcollection.cpp +++ b/src/webenginewidgets/api/qwebenginescriptcollection.cpp @@ -55,6 +55,8 @@ using QtWebEngineCore::UserScript; 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} */ /*! diff --git a/src/webenginewidgets/api/qwebengineview.cpp b/src/webenginewidgets/api/qwebengineview.cpp index ac979e766..de81448a9 100644 --- a/src/webenginewidgets/api/qwebengineview.cpp +++ b/src/webenginewidgets/api/qwebengineview.cpp @@ -61,6 +61,7 @@ void QWebEngineViewPrivate::pageChanged(QWebEnginePage *oldPage, QWebEnginePage Q_Q(QWebEngineView); if (oldPage) { + oldPage->setVisible(false); oldPage->disconnect(q); } @@ -74,6 +75,7 @@ void QWebEngineViewPrivate::pageChanged(QWebEnginePage *oldPage, QWebEnginePage QObject::connect(newPage, &QWebEnginePage::loadFinished, q, &QWebEngineView::loadFinished); QObject::connect(newPage, &QWebEnginePage::selectionChanged, q, &QWebEngineView::selectionChanged); QObject::connect(newPage, &QWebEnginePage::renderProcessTerminated, q, &QWebEngineView::renderProcessTerminated); + newPage->setVisible(q->isVisible()); } auto oldUrl = oldPage ? oldPage->url() : QUrl(); diff --git a/src/webenginewidgets/doc/src/qwebenginepage_lgpl.qdoc b/src/webenginewidgets/doc/src/qwebenginepage_lgpl.qdoc index 699d7f181..7701b9b3d 100644 --- a/src/webenginewidgets/doc/src/qwebenginepage_lgpl.qdoc +++ b/src/webenginewidgets/doc/src/qwebenginepage_lgpl.qdoc @@ -767,10 +767,15 @@ \fn void QWebEnginePage::runJavaScript(const QString &scriptSource, const QWebEngineCallback<const QVariant &> &resultCallback) \since 5.7 - Runs the JavaScript code contained in \a scriptSource in the world specified by \a worldId. - The world ID values are the same as provided by QWebEngineScript::ScriptWorldId, and between \c 0 - and \c 256. Using the \e runJavaScript() versions without the world ID is the same as running the - script in the \c MainWorld. + Runs the JavaScript code contained in \a scriptSource without checking + whether the DOM of the page has been constructed. If you need more + control over how the script is run, consider using \l scripts() instead. + + To avoid conflicts with other scripts executed on the page, the world in + which the script is run is specified by \a worldId. The world ID values are + the same as provided by QWebEngineScript::ScriptWorldId, and between \c 0 + and \c 256. If you leave out the \c world ID, the script is run in the + \c MainWorld. When the script has been executed, \a resultCallback is called with the result of the last executed statement. \c resultCallback can be any of a function pointer, a functor or a lambda, @@ -780,7 +785,7 @@ page.runJavaScript("document.title", [](const QVariant &v) { qDebug() << v.toString(); }); \endcode - Only "plain data" can be returned from JavaScript as the result value. + 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}. @@ -792,9 +797,7 @@ 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. - See scripts() for an alternative API to inject scripts. - - \sa QWebEngineScript::ScriptWorldId + \sa scripts(), QWebEngineScript::ScriptWorldId, {Script Injection} */ /*! diff --git a/tests/auto/quick/qmltests/data/tst_download.qml b/tests/auto/quick/qmltests/data/tst_download.qml index c38018ffd..e049f3621 100644 --- a/tests/auto/quick/qmltests/data/tst_download.qml +++ b/tests/auto/quick/qmltests/data/tst_download.qml @@ -47,6 +47,7 @@ TestWebEngineView { property string downloadDirectory: "" property string downloadFileName: "" property string downloadedPath: "" + property string downloadedSetPath: "" property int downloadDirectoryChanged: 0 property int downloadFileNameChanged: 0 property int downloadPathChanged: 0 @@ -94,14 +95,19 @@ TestWebEngineView { } else { totalBytes = download.totalBytes - download.downloadDirectory = downloadDirectory.length != 0 ? testDownloadProfile.downloadPath + downloadDirectory : testDownloadProfile.downloadPath - download.downloadFileName = downloadFileName.length != 0 ? downloadFileName : "testfile.zip" + if (downloadedSetPath.length != 0) { + download.path = testDownloadProfile.downloadPath + downloadedSetPath + downloadedPath = download.path + } else { + download.downloadDirectory = downloadDirectory.length != 0 ? testDownloadProfile.downloadPath + downloadDirectory : testDownloadProfile.downloadPath + download.downloadFileName = downloadFileName.length != 0 ? downloadFileName : "testfile.zip" + downloadedPath = download.downloadDirectory + download.downloadFileName + } download.accept() } downloadUrl = download.url suggestedFileName = download.suggestedFileName - downloadedPath = download.downloadDirectory + download.downloadFileName } onDownloadFinished: { receivedBytes = download.receivedBytes; @@ -126,6 +132,7 @@ TestWebEngineView { downloadDirectory = "" downloadFileName = "" downloadedPath = "" + downloadedSetPath = "" } function test_downloadRequest() { @@ -211,5 +218,27 @@ TestWebEngineView { tryCompare(downloadState, "2", WebEngineDownloadItem.DownloadCompleted); verify(!downloadInterruptReason); } + + function test_downloadWithSetPath() { + compare(downLoadRequestedSpy.count, 0); + compare(downloadDirectoryChanged, 0); + compare(downloadFileNameChanged, 0); + downloadedSetPath = "/test/test.zip"; + webEngineView.url = Qt.resolvedUrl("download.zip"); + downLoadRequestedSpy.wait(); + compare(downLoadRequestedSpy.count, 1); + compare(downloadUrl, webEngineView.url); + compare(suggestedFileName, "download.zip"); + compare(downloadState[0], WebEngineDownloadItem.DownloadRequested); + tryCompare(downloadState, "1", WebEngineDownloadItem.DownloadInProgress); + compare(downloadedPath, testDownloadProfile.downloadPath + downloadedSetPath); + compare(downloadDirectoryChanged, 1); + compare(downloadFileNameChanged, 1); + compare(downloadPathChanged, 2); + downloadFinishedSpy.wait(); + compare(totalBytes, receivedBytes); + tryCompare(downloadState, "2", WebEngineDownloadItem.DownloadCompleted); + verify(!downloadInterruptReason); + } } } diff --git a/tests/auto/quick/qmltests/data/tst_filePicker.qml b/tests/auto/quick/qmltests/data/tst_filePicker.qml index 2f813b966..fad81273c 100644 --- a/tests/auto/quick/qmltests/data/tst_filePicker.qml +++ b/tests/auto/quick/qmltests/data/tst_filePicker.qml @@ -36,6 +36,12 @@ TestWebEngineView { width: 400 height: 300 + function driveLetter() { + if (Qt.platform.os !== "windows") + return ""; + return "C:/"; + } + SignalSpy { id: titleSpy target: webEngineView @@ -72,27 +78,25 @@ TestWebEngineView { function test_acceptSingleFileSelection_data() { return [ - { tag: "/test.txt)", input: "/test.txt", passDefaultDialog: false, passCustomDialog: true }, - { tag: "/tést.txt", input: "/tést.txt", passDefaultDialog: false, passCustomDialog: true }, - { tag: "file:///test.txt", input: "file:///test.txt", passDefaultDialog: true, passCustomDialog: false }, - { tag: "file:///tést.txt", input: "file:///tést.txt", passDefaultDialog: true, passCustomDialog: false }, - { tag: "file:///t%C3%A9st.txt", input: "file:///t%C3%A9st.txt", passDefaultDialog: true, passCustomDialog: false }, - { tag: "file://test.txt", input: "file://test.txt", passDefaultDialog: false, passCustomDialog: false }, - { tag: "file:/test.txt", input: "file:/test.txt", passDefaultDialog: true, passCustomDialog: false }, - { tag: "file:test//test.txt", input: "file:test//test.txt", passDefaultDialog: false, passCustomDialog: false }, - { tag: "http://test.txt", input: "http://test.txt", passDefaultDialog: false, passCustomDialog: false }, - { tag: "qrc:/test.txt", input: "qrc:/test.txt", passDefaultDialog: false, passCustomDialog: false }, + { tag: driveLetter() + "/test.txt", input: driveLetter() + "/test.txt", expected: "test.txt" }, + { tag: driveLetter() + "test.txt", input: driveLetter() + "test.txt", expected: "Failed to Upload" }, + { tag: driveLetter() + "/tést.txt", input: driveLetter() + "/tést.txt", expected: "tést.txt" }, + { tag: driveLetter() + "/t%65st.txt", input: driveLetter() + "/t%65st.txt", expected: "t%65st.txt" }, + { tag: "file:///" + driveLetter() + "test.txt", input: "file:///" + driveLetter() + "test.txt", expected: "test.txt" }, + { tag: "file:///" + driveLetter() + "tést.txt", input: "file:///" + driveLetter() + "tést.txt", expected: "tést.txt" }, + { tag: "file:///" + driveLetter() + "t%65st.txt", input: "file:///" + driveLetter() + "t%65st.txt", expected: "test.txt" }, + { tag: "file://" + driveLetter() + "test.txt", input: "file://" + driveLetter() + "test.txt", expected: "test.txt" }, + { tag: "file:/" + driveLetter() + "test.txt", input: "file:/" + driveLetter() + "test.txt", expected: "test.txt"}, + { tag: "file:test//test.txt", input: "file:test//test.txt", expected: "Failed to Upload" }, + { tag: "http://test.txt", input: "http://test.txt", expected: "Failed to Upload" }, + { tag: "qrc:/test.txt", input: "qrc:/test.txt", expected: "Failed to Upload" }, ]; } function test_acceptSingleFileSelection(row) { var expectedFileName; - // Default dialog (expects URL). - expectedFileName = "Failed to Upload"; - if (row.passDefaultDialog) - expectedFileName = row.input.slice(row.input.lastIndexOf('/') + 1); - + // Default dialog webEngineView.url = Qt.resolvedUrl("singlefileupload.html"); verify(webEngineView.waitForLoadSucceeded()); @@ -101,16 +105,12 @@ TestWebEngineView { keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. tryCompare(FilePickerParams, "filePickerOpened", true); - tryCompare(webEngineView, "title", decodeURIComponent(expectedFileName)); + tryCompare(webEngineView, "title", row.expected); - // Custom dialog (expects absolute path). + // Custom dialog var finished = false; - expectedFileName = "Failed to Upload"; - if (row.passCustomDialog) - expectedFileName = row.input.slice(row.input.lastIndexOf('/') + 1); - function acceptedFileHandler(request) { request.accepted = true; request.dialogAccept(row.input); @@ -123,7 +123,7 @@ TestWebEngineView { keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. tryVerify(function() { return finished; }); - tryCompare(webEngineView, "title", expectedFileName); + tryCompare(webEngineView, "title", row.expected); webEngineView.fileDialogRequested.disconnect(acceptedFileHandler); } @@ -165,14 +165,14 @@ TestWebEngineView { function test_acceptMultipleFilesWithCustomDialog_data() { return [ - { tag: "path", input: ["/test1.txt", "/test2.txt"], expectedValueForDefaultDialog: "Failed to Upload", expectedValueForCustomDialog: "test1.txt,test2.txt" }, - { tag: "file", input: ["file:///test1.txt", "file:///test2.txt"], expectedValueForDefaultDialog: "test1.txt,test2.txt", expectedValueForCustomDialog: "Failed to Upload" }, - { tag: "mixed", input: ["file:///test1.txt", "/test2.txt"], expectedValueForDefaultDialog: "test1.txt", expectedValueForCustomDialog: "test2.txt" }, + { tag: "path", input: [driveLetter() + "/test1.txt", driveLetter() + "/test2.txt"], expectedValue: "test1.txt,test2.txt" }, + { tag: "file", input: ["file:///" + driveLetter() + "test1.txt", "file:/" + driveLetter() + "test2.txt"], expectedValue: "test1.txt,test2.txt" }, + { tag: "mixed", input: ["file:///" + driveLetter() + "test1.txt", driveLetter() + "/test2.txt"], expectedValue: "test1.txt,test2.txt" }, ]; } function test_acceptMultipleFilesWithCustomDialog(row) { - // Default dialog (expects URL). + // Default dialog webEngineView.url = Qt.resolvedUrl("multifileupload.html"); verify(webEngineView.waitForLoadSucceeded()); @@ -181,10 +181,10 @@ TestWebEngineView { keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. tryCompare(FilePickerParams, "filePickerOpened", true); - tryCompare(webEngineView, "title", row.expectedValueForDefaultDialog); + tryCompare(webEngineView, "title", row.expectedValue); - // Custom dialog (expects absolute path). + // Custom dialog var finished = false; function acceptedFileHandler(request) { @@ -199,7 +199,65 @@ TestWebEngineView { keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. tryVerify(function() { return finished; }); - tryCompare(webEngineView, "title", row.expectedValueForCustomDialog); + tryCompare(webEngineView, "title", row.expectedValue); + webEngineView.fileDialogRequested.disconnect(acceptedFileHandler); + } + + function test_acceptFileOnWindows_data() { + return [ + { tag: "C:test.txt", input: "C:test.txt", expected: "Failed to Upload"}, + { tag: "C:test:txt", input: "C:test:txt", expected: "Failed to Upload"}, + { tag: "C:/test.txt", input: "C:/test.txt", expected: "test.txt"}, + { tag: "C:\\test.txt", input: "C:\\test.txt", expected: "test.txt"}, + { tag: "C:\\Documents and Settings\\test\\test.txt", input: "C:\\Documents and Settings\\test\\test.txt", expected: "test.txt"}, + { tag: "\\\\applib\\products\\a%2Db\\ abc%5F9\\t.est\\test.txt", input: "file://applib/products/a%2Db/ abc%5F9/4148.920a/media/test.txt", expected: "test.txt"}, + { tag: "file://applib/products/a%2Db/ abc%5F9/t.est/test.txt", input: "file://applib/products/a%2Db/ abc%5F9/4148.920a/media/test.txt", expected: "test.txt"}, + { tag: "file://applib/products/a-b/abc_1/t.est/test.txt", input: "file://applib/products/a-b/abc_1/t.est/test.txt", expected: "test.txt"}, + { tag: "file:\\\\applib\\products\\a-b\\abc_1\\t:est\\test.txt", input: "file:\\\\applib\\products\\a-b\\abc_1\\t:est\\test.txt", expected: "test.txt"}, + { tag: "file:C:/test.txt", input: "file:C:/test.txt", expected: "Failed to Upload"}, + { tag: "file:/C:/test.txt", input: "file:/C:/test.txt", expected: "Failed to Upload"}, + { tag: "file://C:/test.txt", input: "file://C:/test.txt", expected: "Failed to Upload"}, + { tag: "file:///C:test.txt", input: "file:///C:test.txt", expected: "Failed to Upload"}, + { tag: "file:///C:/test.txt", input: "file:///C:/test.txt", expected: "test.txt"}, + { tag: "file:///C:\\test.txt", input: "file:///C:\\test.txt", expected: "test.txt"}, + { tag: "file:\\//C:/test.txt", input: "file:\\//C:/test.txt", expected: "test.txt"}, + { tag: "file:\\\\/C:\\test.txt", input: "file:\\\\/C:\\test.txt", expected: "test.txt"}, + { tag: "\\\\?\\C:/test.txt", input: "\\\\?\\C:/test.txt", expected: "Failed to Upload"}, + ]; + } + + function test_acceptFileOnWindows(row) { + if (Qt.platform.os !== "windows") + skip("Windows-only test"); + + // Default dialog + webEngineView.url = Qt.resolvedUrl("singlefileupload.html"); + verify(webEngineView.waitForLoadSucceeded()); + + FilePickerParams.selectFiles = true; + FilePickerParams.selectedFilesUrl.push(row.input); + + keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. + tryCompare(FilePickerParams, "filePickerOpened", true); + tryCompare(webEngineView, "title", row.expected); + + + // Custom dialog + var finished = false; + + function acceptedFileHandler(request) { + request.accepted = true; + request.dialogAccept(row.input); + finished = true; + } + + webEngineView.fileDialogRequested.connect(acceptedFileHandler); + webEngineView.url = Qt.resolvedUrl("singlefileupload.html"); + verify(webEngineView.waitForLoadSucceeded()); + + keyClick(Qt.Key_Enter); // Focus is on the button. Open FileDialog. + tryVerify(function() { return finished; }); + tryCompare(webEngineView, "title", row.expected); webEngineView.fileDialogRequested.disconnect(acceptedFileHandler); } } diff --git a/tests/auto/quick/qquickwebengineview/tst_qquickwebengineview.cpp b/tests/auto/quick/qquickwebengineview/tst_qquickwebengineview.cpp index 74c04635f..5572515a1 100644 --- a/tests/auto/quick/qquickwebengineview/tst_qquickwebengineview.cpp +++ b/tests/auto/quick/qquickwebengineview/tst_qquickwebengineview.cpp @@ -91,6 +91,7 @@ private Q_SLOTS: void userScripts(); void javascriptClipboard_data(); void javascriptClipboard(); + void setProfile(); private: inline QQuickWebEngineView *newWebEngineView(); @@ -1148,5 +1149,18 @@ void tst_QQuickWebEngineView::javascriptClipboard() QTRY_COMPARE(evaluateJavaScriptSync(view, "accessPrompt").toBool(), false); } +void tst_QQuickWebEngineView::setProfile() { + QSignalSpy loadSpy(webEngineView(), SIGNAL(loadingChanged(QQuickWebEngineLoadRequest*))); + webEngineView()->setUrl(urlFromTestPath("html/basic_page.html")); + QVERIFY(waitForLoadSucceeded(webEngineView())); + QCOMPARE(loadSpy.size(), 2); + webEngineView()->setUrl(urlFromTestPath("html/basic_page2.html")); + QVERIFY(waitForLoadSucceeded(webEngineView())); + QCOMPARE(loadSpy.size(), 4); + QQuickWebEngineProfile *profile = new QQuickWebEngineProfile(); + webEngineView()->setProfile(profile); + QTRY_COMPARE(webEngineView()->url() ,urlFromTestPath("html/basic_page2.html")); +} + QTEST_MAIN(tst_QQuickWebEngineView) #include "tst_qquickwebengineview.moc" diff --git a/tests/auto/widgets/proxypac/tst_proxypac.cpp b/tests/auto/widgets/proxypac/tst_proxypac.cpp index f9340341b..934e23fde 100644 --- a/tests/auto/widgets/proxypac/tst_proxypac.cpp +++ b/tests/auto/widgets/proxypac/tst_proxypac.cpp @@ -46,6 +46,10 @@ private slots: void tst_ProxyPac::proxypac() { + const QString fromEnv = QString::fromLocal8Bit(qgetenv("QTWEBENGINE_CHROMIUM_FLAGS")); + if (!fromEnv.contains("--proxy-pac-url")) + qFatal("--proxy-pac-url argument is not passed."); + ProxyServer proxyServer1; proxyServer1.setPort(5551); proxyServer1.run(); diff --git a/tests/auto/widgets/qwebenginepage/BLACKLIST b/tests/auto/widgets/qwebenginepage/BLACKLIST index e6fad8b20..7857ee818 100644 --- a/tests/auto/widgets/qwebenginepage/BLACKLIST +++ b/tests/auto/widgets/qwebenginepage/BLACKLIST @@ -4,9 +4,5 @@ osx [mouseMovementProperties] windows -[runJavaScriptFromSlot] -osx -linux - [fullScreenRequested] windows diff --git a/tests/auto/widgets/qwebenginepage/tst_qwebenginepage.cpp b/tests/auto/widgets/qwebenginepage/tst_qwebenginepage.cpp index dbb15ba10..5edd778e2 100644 --- a/tests/auto/widgets/qwebenginepage/tst_qwebenginepage.cpp +++ b/tests/auto/widgets/qwebenginepage/tst_qwebenginepage.cpp @@ -1824,24 +1824,22 @@ void tst_QWebEnginePage::runJavaScriptFromSlot() { QWebEngineProfile profile; QWebEnginePage page(&profile); - page.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true); QSignalSpy loadFinishedSpy(&page, &QWebEnginePage::loadFinished); page.setHtml("<html><body>" " <input type='text' id='input1' value='QtWebEngine' size='50' />" "</body></html>"); QTRY_COMPARE(loadFinishedSpy.count(), 1); - // Workaround for QTBUG-74718 - QTRY_VERIFY(page.action(QWebEnginePage::SelectAll)->isEnabled()); - QVariant result(-1); + bool done = false; connect(&page, &QWebEnginePage::selectionChanged, [&]() { - result = evaluateJavaScriptSync(&page, QStringLiteral("2+2")); + QTRY_COMPARE(evaluateJavaScriptSync(&page, QStringLiteral("2+2")), QVariant(4)); + done = true; }); evaluateJavaScriptSync(&page, QStringLiteral("const input = document.getElementById('input1');" "input.focus();" "input.select();")); - QTRY_COMPARE(result, QVariant(4)); + QTRY_VERIFY(done); } void tst_QWebEnginePage::fullScreenRequested() diff --git a/tests/auto/widgets/qwebenginescript/tst_qwebenginescript.cpp b/tests/auto/widgets/qwebenginescript/tst_qwebenginescript.cpp index 90361f2c9..2e8687d9b 100644 --- a/tests/auto/widgets/qwebenginescript/tst_qwebenginescript.cpp +++ b/tests/auto/widgets/qwebenginescript/tst_qwebenginescript.cpp @@ -71,6 +71,7 @@ private Q_SLOTS: #endif void noTransportWithoutWebChannel(); void scriptsInNestedIframes(); + void matchQrcUrl(); }; void tst_QWebEngineScript::domEditing() @@ -589,6 +590,33 @@ void tst_QWebEngineScript::webChannelWithBadString() QCOMPARE(host.text(), data); } #endif + +void tst_QWebEngineScript::matchQrcUrl() +{ + QWebEnginePage page; + QWebEngineView view; + view.setPage(&page); + QWebEngineScript s; + s.setInjectionPoint(QWebEngineScript::DocumentReady); + s.setWorldId(QWebEngineScript::MainWorld); + + + s.setSourceCode(QStringLiteral(R"( +// ==UserScript== +// @match qrc:/*main.html +// ==/UserScript== + +document.title = 'New title'; + )")); + + page.scripts().insert(s); + page.load(QUrl("qrc:/resources/test_iframe_main.html")); + view.show(); + QSignalSpy spyFinished(&page, &QWebEnginePage::loadFinished); + QVERIFY(spyFinished.wait()); + QCOMPARE(page.title(), "New title"); +} + QTEST_MAIN(tst_QWebEngineScript) #include "tst_qwebenginescript.moc" diff --git a/tests/auto/widgets/qwebengineview/BLACKLIST b/tests/auto/widgets/qwebengineview/BLACKLIST index 9087067f5..266f08886 100644 --- a/tests/auto/widgets/qwebengineview/BLACKLIST +++ b/tests/auto/widgets/qwebengineview/BLACKLIST @@ -3,3 +3,6 @@ osx [textSelectionOutOfInputField] * + +[visibilityState3] +windows diff --git a/tests/auto/widgets/qwebengineview/tst_qwebengineview.cpp b/tests/auto/widgets/qwebengineview/tst_qwebengineview.cpp index 827ac2757..71c4aa9b5 100644 --- a/tests/auto/widgets/qwebengineview/tst_qwebengineview.cpp +++ b/tests/auto/widgets/qwebengineview/tst_qwebengineview.cpp @@ -192,6 +192,8 @@ private Q_SLOTS: void webUIURLs_data(); void webUIURLs(); void visibilityState(); + void visibilityState2(); + void visibilityState3(); void jsKeyboardEvent(); void deletePage(); void closeOpenerTab(); @@ -3140,6 +3142,38 @@ void tst_QWebEngineView::visibilityState() QCOMPARE(evaluateJavaScriptSync(view.page(), "document.visibilityState").toString(), QStringLiteral("visible")); } +void tst_QWebEngineView::visibilityState2() +{ + QWebEngineView view; + QSignalSpy spy(&view, &QWebEngineView::loadFinished); + view.show(); + view.load(QStringLiteral("about:blank")); + view.hide(); + QVERIFY(spy.count() || spy.wait()); + QVERIFY(spy.takeFirst().takeFirst().toBool()); + QCOMPARE(evaluateJavaScriptSync(view.page(), "document.visibilityState").toString(), QStringLiteral("hidden")); +} + +void tst_QWebEngineView::visibilityState3() +{ + QWebEnginePage page1; + QWebEnginePage page2; + QSignalSpy spy1(&page1, &QWebEnginePage::loadFinished); + QSignalSpy spy2(&page2, &QWebEnginePage::loadFinished); + page1.load(QStringLiteral("about:blank")); + page2.load(QStringLiteral("about:blank")); + QVERIFY(spy1.count() || spy1.wait()); + QVERIFY(spy2.count() || spy2.wait()); + QWebEngineView view; + view.setPage(&page1); + view.show(); + QCOMPARE(evaluateJavaScriptSync(&page1, "document.visibilityState").toString(), QStringLiteral("visible")); + QCOMPARE(evaluateJavaScriptSync(&page2, "document.visibilityState").toString(), QStringLiteral("hidden")); + view.setPage(&page2); + QCOMPARE(evaluateJavaScriptSync(&page1, "document.visibilityState").toString(), QStringLiteral("hidden")); + QCOMPARE(evaluateJavaScriptSync(&page2, "document.visibilityState").toString(), QStringLiteral("visible")); +} + void tst_QWebEngineView::jsKeyboardEvent() { QWebEngineView view; diff --git a/tests/auto/widgets/widgets.pro b/tests/auto/widgets/widgets.pro index df553df55..6d65eecb5 100644 --- a/tests/auto/widgets/widgets.pro +++ b/tests/auto/widgets/widgets.pro @@ -4,7 +4,6 @@ QT_FOR_CONFIG += webenginecore webenginecore-private TEMPLATE = subdirs SUBDIRS += \ - certificateerror \ defaultsurfaceformat \ devtools \ faviconmanager \ @@ -31,6 +30,10 @@ qtConfig(webengine-printing-and-pdf) { SUBDIRS += printing } +qtConfig(ssl) { + SUBDIRS += certificateerror +} + qtConfig(webengine-spellchecker):!cross_compile { !qtConfig(webengine-native-spellchecker) { SUBDIRS += spellchecking diff --git a/tools/scripts/take_snapshot.py b/tools/scripts/take_snapshot.py index 3f21dda9c..741979a9e 100755 --- a/tools/scripts/take_snapshot.py +++ b/tools/scripts/take_snapshot.py @@ -176,8 +176,9 @@ def isInChromiumBlacklist(file_path): or file_path.startswith('third_party/google_') or file_path.startswith('third_party/grpc/') or file_path.startswith('third_party/hunspell_dictionaries') - or (file_path.startswith('third_party/icu') and file_path.endswith('icudtl_dat.S')) or file_path.startswith('third_party/icu/android') + or file_path.startswith('third_party/icu/cast') + or file_path.startswith('third_party/icu/chromeos') or file_path.startswith('third_party/icu/ios') or file_path.startswith('third_party/instrumented_libraries') or file_path.startswith('third_party/jsr-305') @@ -192,9 +193,8 @@ def isInChromiumBlacklist(file_path): or file_path.startswith('third_party/libwebm/source/webm_parser/fuzzing') or file_path.startswith('third_party/logilab') or file_path.startswith('third_party/markdown') - or (file_path.startswith('third_party/polymer') and - not file_path.startswith('third_party/polymer/v1_0/components-chromium/')) or file_path.startswith('third_party/openh264/src/res') + or file_path.startswith('third_party/openscreen/src/third_party/boringssl/') or file_path.startswith('third_party/pdfium/testing/resources') or file_path.startswith('third_party/pdfium/tools') or file_path.startswith('third_party/perl') @@ -206,7 +206,7 @@ def isInChromiumBlacklist(file_path): or file_path.startswith('third_party/sqlite/sqlite-src-') or file_path.startswith('third_party/speech-dispatcher') or file_path.startswith('third_party/spirv-cross/') - or file_path.startswith('third_party/swiftshader/third_party/llvm') + or file_path.startswith('third_party/swiftshader/third_party/') or file_path.startswith('third_party/wayland') or file_path.startswith('third_party/webgl') or file_path.startswith('third_party/webrtc/resources/') diff --git a/tools/scripts/version_resolver.py b/tools/scripts/version_resolver.py index 532da34e3..2cdc1e3fb 100644 --- a/tools/scripts/version_resolver.py +++ b/tools/scripts/version_resolver.py @@ -38,8 +38,8 @@ import json import urllib2 import git_submodule as GitSubmodule -chromium_version = '75.0.3770.56' -chromium_branch = '3770' +chromium_version = '77.0.3865.98' +chromium_branch = '3865' ninja_version = 'v1.9.0' json_url = 'http://omahaproxy.appspot.com/all.json' |