diff --git a/AUTHORS b/AUTHORS index aa1ca40..bbba25d3 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -240,6 +240,7 @@ Eriq Augustine <eriq.augustine@gmail.com> Ernesto Mudu <ernesto.mudu@gmail.com> Etienne Laurin <etienne@atnnn.com> +Euisang Lim <eui-sang.lim@samsung.com> Evan Peterson <evan.peterson.ep@gmail.com> Evan Wallace <evan.exe@gmail.com> Evangelos Foutras <evangelos@foutrelis.com>
diff --git a/DEPS b/DEPS index 6fa2d73..3401ca4 100644 --- a/DEPS +++ b/DEPS
@@ -29,7 +29,6 @@ gclient_gn_args_file = 'src/build/config/gclient_args.gni' gclient_gn_args = [ 'checkout_android', - 'checkout_android_native_support', 'checkout_libaom', 'checkout_nacl', 'checkout_oculus_sdk', @@ -43,10 +42,6 @@ # purposes. 'checkout_configuration': 'default', - # Pull in Android native toolchain dependencies for Chrome OS too, so we can - # build ARC++ support libraries. - 'checkout_android_native_support': 'checkout_android or checkout_chromeos', - # By default, do not check out android sdk sources. This can be overridden # e.g. with custom_vars. 'checkout_android_sdk_sources': False, @@ -95,11 +90,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '7df62b559a657b661171d44ebf6c5ea2623fd737', + 'skia_revision': 'efb4d08dd43cd07e0e1d2f2d5819046259a5d340', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '909429600110aa84b66a72d7929315ab1b23c3c0', + 'v8_revision': 'b77ccdf1ab26182be3a88e0ced1991bce755c5c5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -343,7 +338,7 @@ 'src/third_party/android_ndk': { 'url': Var('chromium_git') + '/android_ndk.git' + '@' + '635bc380968a76f6948fee65f80a0b28db53ae81', - 'condition': 'checkout_android_native_support', + 'condition': 'checkout_android', }, 'src/third_party/android_support_test_runner': { @@ -370,7 +365,7 @@ 'src/third_party/android_tools': { 'url': Var('chromium_git') + '/android_tools.git' + '@' + 'c22a664c39af72dd8f89200220713dcad811300a', - 'condition': 'checkout_android_native_support', + 'condition': 'checkout_android', }, 'src/third_party/android_sdk/public': { @@ -494,7 +489,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '7c0757b099e511215d22e82e6b04100e883f3bb9', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '64133ee653fbc7bfe176eb55e13b931a52bedabb', 'condition': 'checkout_linux', }, @@ -529,7 +524,7 @@ 'src/third_party/elfutils/src': { 'url': Var('chromium_git') + '/external/elfutils.git' + '@' + '249673729a7e5dbd5de4f3760bdcaa3d23d154d7', - 'condition': 'checkout_android_native_support', + 'condition': 'checkout_android', }, 'src/third_party/errorprone/lib': { @@ -777,7 +772,7 @@ }, 'src/third_party/mesa/src': - Var('chromium_git') + '/chromium/deps/mesa.git' + '@' + '803b1132096707417736df8d167176a33813aa9f', + Var('chromium_git') + '/chromium/deps/mesa.git' + '@' + '9d9b0710470f581cb5485b02b6acd8415cc093e8', # GNU binutils assembler for x86-64. 'src/third_party/mingw-w64/mingw/bin': { @@ -964,7 +959,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '7c0541da63f571512c49758cbc0767117997a270', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'e80689fcabde179e4a9af7cd18d06dcc6c6331ee', # commit position 21742 + Var('webrtc_git') + '/src.git' + '@' + '28899d0791c4a0257bca78d4d38d32dd29a4f2e0', # commit position 21742 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -998,7 +993,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0cbdbd28b5084e2af39968c71974835c98d550cf', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@5148f0652738c9e18940b2e5781d92668d562053', 'condition': 'checkout_src_internal', },
diff --git a/WATCHLISTS b/WATCHLISTS index 480b066e..8f72d1c2 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -546,7 +546,7 @@ 'filepath': 'chrome/browser/bookmarks/' \ '|chrome/browser/extensions/api/bookmark_manager_private/' \ '|chrome/browser/extensions/api/bookmarks/' \ - '|chrome/browser/resources/bookmark_manager/' \ + '|chrome/browser/resources/md_bookmarks/' \ '|chrome/browser/ui/bookmarks/' \ '|chrome/browser/ui/cocoa/bookmarks/' \ '|chrome/browser/ui/views/bookmarks/' \
diff --git a/android_webview/glue/java/DEPS b/android_webview/glue/java/DEPS index 2c49ba1..2f1c15c 100644 --- a/android_webview/glue/java/DEPS +++ b/android_webview/glue/java/DEPS
@@ -5,6 +5,5 @@ "-content/public/android/java", "+content/public/android/java/src/org/chromium/content_public", - "!content/public/android/java/src/org/chromium/content/browser/AppWebMessagePort.java", "!content/public/android/java/src/org/chromium/content/browser/selection/LGEmailActionModeWorkaround.java", ]
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebMessagePortAdapter.java b/android_webview/glue/java/src/com/android/webview/chromium/WebMessagePortAdapter.java index 7d343b8..634e91a 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebMessagePortAdapter.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebMessagePortAdapter.java
@@ -10,7 +10,6 @@ import android.webkit.WebMessage; import android.webkit.WebMessagePort; -import org.chromium.content.browser.AppWebMessagePort; import org.chromium.content_public.browser.MessagePort; /** @@ -66,7 +65,7 @@ public static MessagePort[] toMessagePorts(WebMessagePort[] webMessagePorts) { if (webMessagePorts == null) return null; - MessagePort[] ports = new AppWebMessagePort[webMessagePorts.length]; + MessagePort[] ports = new MessagePort[webMessagePorts.length]; for (int i = 0; i < webMessagePorts.length; i++) { ports[i] = ((WebMessagePortAdapter) webMessagePorts[i]).getPort(); }
diff --git a/android_webview/java/DEPS b/android_webview/java/DEPS index 6347b68..e985e273 100644 --- a/android_webview/java/DEPS +++ b/android_webview/java/DEPS
@@ -10,7 +10,6 @@ "-content/public/android/java", "+content/public/android/java/src/org/chromium/content_public", - "!content/public/android/java/src/org/chromium/content/browser/AppWebMessagePort.java", "!content/public/android/java/src/org/chromium/content/browser/BrowserStartupController.java", "!content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParams.java", "!content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java",
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index d9e3d99..63edf48 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -63,7 +63,6 @@ import org.chromium.components.autofill.AutofillProvider; import org.chromium.components.navigation_interception.InterceptNavigationDelegate; import org.chromium.components.navigation_interception.NavigationParams; -import org.chromium.content.browser.AppWebMessagePort; import org.chromium.content.browser.ContentViewStatics; import org.chromium.content_public.browser.ChildProcessImportance; import org.chromium.content_public.browser.ContentViewCore; @@ -2413,10 +2412,10 @@ /** * Creates a message channel and returns the ports for each end of the channel. */ - public AppWebMessagePort[] createMessageChannel() { + public MessagePort[] createMessageChannel() { if (TRACE) Log.i(TAG, "%s createMessageChannel", this); if (isDestroyedOrNoOperation(WARN)) return null; - return AppWebMessagePort.createPair(); + return MessagePort.createPair(); } public boolean hasAccessedInitialDocument() {
diff --git a/android_webview/javatests/DEPS b/android_webview/javatests/DEPS index 32a0d3d..36a9498 100644 --- a/android_webview/javatests/DEPS +++ b/android_webview/javatests/DEPS
@@ -9,7 +9,6 @@ "-content/public/android/java", "+content/public/android/java/src/org/chromium/content_public", - "!content/public/android/java/src/org/chromium/content/browser/AppWebMessagePort.java", "!content/public/android/java/src/org/chromium/content/browser/ContentVideoView.java", "!content/public/android/java/src/org/chromium/content/browser/ContentViewStatics.java", "!content/public/android/java/src/org/chromium/content/common/ContentSwitches.java",
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/PostMessageTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/PostMessageTest.java index cbd2b5a..563ec04b 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/PostMessageTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/PostMessageTest.java
@@ -26,10 +26,10 @@ import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; -import org.chromium.content.browser.AppWebMessagePort; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper; +import org.chromium.content_public.browser.MessagePort; import org.chromium.net.test.util.TestWebServer; import java.util.concurrent.CountDownLatch; @@ -210,13 +210,13 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel[1]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); // Retransfer the port. This should fail with an exception. try { - mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, "2", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -238,11 +238,11 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channel[1].postMessage("1", null); try { - mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, "2", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -260,13 +260,13 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); // set a web event handler, this puts the port in a started state. channel[1].setMessageCallback((message, sentPorts) -> { }, null); try { - mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, "2", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -285,11 +285,11 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel1 = mAwContents.createMessageChannel(); + MessagePort[] channel1 = mAwContents.createMessageChannel(); channel1[1].postMessage("1", null); - AppWebMessagePort[] channel2 = mAwContents.createMessageChannel(); + MessagePort[] channel2 = mAwContents.createMessageChannel(); try { - channel2[0].postMessage("2", new AppWebMessagePort[]{channel1[1]}); + channel2[0].postMessage("2", new MessagePort[] {channel1[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -307,13 +307,13 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel1 = mAwContents.createMessageChannel(); + MessagePort[] channel1 = mAwContents.createMessageChannel(); // set a web event handler, this puts the port in a started state. channel1[1].setMessageCallback((message, sentPorts) -> { }, null); - AppWebMessagePort[] channel2 = mAwContents.createMessageChannel(); + MessagePort[] channel2 = mAwContents.createMessageChannel(); try { - channel2[0].postMessage("1", new AppWebMessagePort[]{channel1[1]}); + channel2[0].postMessage("1", new MessagePort[] {channel1[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -338,9 +338,9 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); try { - channel[0].postMessage("1", new AppWebMessagePort[]{channel[0]}); + channel[0].postMessage("1", new MessagePort[] {channel[0]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -358,11 +358,11 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channel[1].close(); try { - mAwContents.postMessageToFrame(null, "1", mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -380,11 +380,11 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel1 = mAwContents.createMessageChannel(); - AppWebMessagePort[] channel2 = mAwContents.createMessageChannel(); + MessagePort[] channel1 = mAwContents.createMessageChannel(); + MessagePort[] channel2 = mAwContents.createMessageChannel(); channel2[1].close(); try { - channel1[0].postMessage("1", new AppWebMessagePort[]{channel2[1]}); + channel1[0].postMessage("1", new MessagePort[] {channel2[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; @@ -402,7 +402,7 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channel[0].close(); try { channel[0].postMessage("1", null); @@ -422,9 +422,9 @@ public void testMessagesPostedBeforeClosingPortAreTransferred() throws Throwable { loadPage(TITLE_FROM_POSTMESSAGE_TO_CHANNEL); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel[1]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage("2", null); channel[0].postMessage("3", null); channel[0].close(); @@ -440,9 +440,9 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel[1]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); try { channel[1].close(); } catch (IllegalStateException ex) { @@ -462,11 +462,11 @@ loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel1 = mAwContents.createMessageChannel(); + MessagePort[] channel1 = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel1[1]}); - AppWebMessagePort[] channel2 = mAwContents.createMessageChannel(); - channel1[0].postMessage("2", new AppWebMessagePort[]{channel2[0]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel1[1]}); + MessagePort[] channel2 = mAwContents.createMessageChannel(); + channel1[0].postMessage("2", new MessagePort[] {channel2[0]}); try { channel2[0].close(); } catch (IllegalStateException ex) { @@ -486,18 +486,18 @@ public void testPendingPortCanBeTransferredInPendingPort() throws Throwable { loadPage(TITLE_FROM_POSTMESSAGE_TO_CHANNEL); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel1 = mAwContents.createMessageChannel(); + MessagePort[] channel1 = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel1[1]}); - AppWebMessagePort[] channel2 = mAwContents.createMessageChannel(); - channel1[0].postMessage("2", new AppWebMessagePort[]{channel2[0]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel1[1]}); + MessagePort[] channel2 = mAwContents.createMessageChannel(); + channel1[0].postMessage("2", new MessagePort[] {channel2[0]}); }); expectTitle("2"); } private static class ChannelContainer { private boolean mReady; - private AppWebMessagePort[] mChannel; + private MessagePort[] mChannel; private final Object mLock = new Object(); private String mMessage = ""; private Looper mLastLooper; @@ -512,10 +512,10 @@ mWaitCount = n; } - public void set(AppWebMessagePort[] channel) { + public void set(MessagePort[] channel) { mChannel = channel; } - public AppWebMessagePort[] get() { + public MessagePort[] get() { return mChannel; } @@ -566,13 +566,13 @@ loadPage(TEST_PAGE); final ChannelContainer channelContainer = new ChannelContainer(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); // verify communication from JS to Java. channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); }); mMessageObject.waitForMessage(); Assert.assertEquals(WEBVIEW_MESSAGE, mMessageObject.getData()); @@ -613,14 +613,14 @@ public void testMessageChannelUsingInitializedPort() throws Throwable { final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); - final AppWebMessagePort[] channel = + final MessagePort[] channel = ThreadUtils.runOnUiThreadBlocking(() -> mAwContents.createMessageChannel()); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage(HELLO, null); }); // wait for the asynchronous response from JS @@ -640,11 +640,11 @@ final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage(HELLO, null); }); // Wait for the asynchronous response from JS. @@ -661,7 +661,7 @@ final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channel[1].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); channel[0].postMessage(HELLO, null); @@ -679,9 +679,9 @@ public void testPostMessageToFrameNotReordersMessages() throws Throwable { loadPage(TITLE_FROM_POSTMESSAGE_TO_FRAME); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel[1]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), null); mAwContents.postMessageToFrame(null, "3", mWebServer.getBaseUrl(), null); }); @@ -718,9 +718,9 @@ public void testCanUseReceivedAwMessagePortFromJS() throws Throwable { loadPage(RECEIVE_JS_MESSAGE_CHANNEL_PAGE); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame( - null, "1", mWebServer.getBaseUrl(), new AppWebMessagePort[]{channel[1]}); + null, "1", mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].setMessageCallback((message, p) -> { p[0].setMessageCallback((message1, q) -> { Assert.assertEquals("3", message1); @@ -775,9 +775,9 @@ CommonResources.getTextJavascriptHeaders(true)); loadPage(TEST_PAGE_FOR_PORT_TRANSFER); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[0], channel[1]}); + new MessagePort[] {channel[0], channel[1]}); }); mMessageObject.waitForMessage(); Assert.assertEquals(WORKER_MESSAGE, mMessageObject.getData()); @@ -821,12 +821,12 @@ final ChannelContainer channelContainer = new ChannelContainer(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage(HELLO, null); }); channelContainer.waitForMessage(); @@ -845,12 +845,12 @@ final ChannelContainer channelContainer = new ChannelContainer(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage(HELLO, null); }); channelContainer.waitForMessage(); @@ -880,12 +880,12 @@ loadPage(TEST_PAGE_FOR_UNSUPPORTED_MESSAGES); final ChannelContainer channelContainer = new ChannelContainer(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); }); channelContainer.waitForMessage(); Assert.assertEquals(JS_MESSAGE, channelContainer.getMessage()); @@ -910,12 +910,12 @@ loadPage(TEST_TRANSFER_EMPTY_PORTS); final ChannelContainer channelContainer = new ChannelContainer(2); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[]{channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); }); channelContainer.waitForMessage(); Assert.assertEquals("12", channelContainer.getMessage()); @@ -937,12 +937,12 @@ final String longMessage = longMessageBuilder.toString(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer.setMessage(message), null); - mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), - new AppWebMessagePort[] {channel[1]}); + mAwContents.postMessageToFrame( + null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[] {channel[1]}); channel[0].postMessage(longMessage, null); }); channelContainer.waitForMessage(); @@ -959,7 +959,7 @@ final HandlerThread thread = new HandlerThread("test-thread"); thread.start(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer1.set(channel); channelContainer2.set(channel); channel[0].setMessageCallback( @@ -987,7 +987,7 @@ final HandlerThread thread = new HandlerThread("test-thread"); thread.start(); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = mAwContents.createMessageChannel(); + MessagePort[] channel = mAwContents.createMessageChannel(); channelContainer.set(channel); channel[0].setMessageCallback((message, sentPorts) -> channelContainer.setMessage(message), @@ -999,7 +999,7 @@ Assert.assertEquals(thread.getLooper(), channelContainer.getLastLooper()); final ChannelContainer channelContainer2 = new ChannelContainer(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - AppWebMessagePort[] channel = channelContainer.get(); + MessagePort[] channel = channelContainer.get(); channel[0].setMessageCallback( (message, sentPorts) -> channelContainer2.setMessage(message), null); channel[1].postMessage("bar", null);
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 7eacdaf5..e03bd5b9 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1933,6 +1933,7 @@ "//content/public/browser", "//content/test:test_support", "//skia", + "//ui/views/controls/webview", ] }
diff --git a/ash/content/display/DEPS b/ash/content/display/DEPS index 251f2b2..2069ccc75 100644 --- a/ash/content/display/DEPS +++ b/ash/content/display/DEPS
@@ -2,9 +2,10 @@ "screen_orientation_controller_chromeos_unittest.cc": [ "+content/public/browser/browser_context.h", "+content/public/browser/web_contents.h", - "+third_party/blink/public/common/screen_orientation/web_screen_orientation_lock_type.h", + "+third_party/blink/public/common/screen_orientation/web_screen_orientation_lock_type.h", ], ".*test\.cc": [ - "+content/public/test/test_browser_context.h" + "+content/public/test/test_browser_context.h", + "+content/public/test/web_contents_tester.h", ], }
diff --git a/ash/content/display/screen_orientation_controller_chromeos_unittest.cc b/ash/content/display/screen_orientation_controller_chromeos_unittest.cc index b69c0ba..dd50062 100644 --- a/ash/content/display/screen_orientation_controller_chromeos_unittest.cc +++ b/ash/content/display/screen_orientation_controller_chromeos_unittest.cc
@@ -27,6 +27,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "content/public/test/test_browser_context.h" +#include "content/public/test/web_contents_tester.h" #include "third_party/blink/public/common/screen_orientation/web_screen_orientation_lock_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" @@ -118,11 +119,11 @@ // Creates and initializes and empty content::WebContents that is backed by a // content::BrowserContext and that has an aura::Window. - content::WebContents* CreateWebContents(); + std::unique_ptr<content::WebContents> CreateWebContents(); // Creates a secondary content::WebContents, with a separate // content::BrowserContext. - content::WebContents* CreateSecondaryWebContents(); + std::unique_ptr<content::WebContents> CreateSecondaryWebContents(); // AshTestBase: void SetUp() override; @@ -171,16 +172,17 @@ ScreenOrientationControllerTest::~ScreenOrientationControllerTest() = default; -content::WebContents* ScreenOrientationControllerTest::CreateWebContents() { - return views::ViewsDelegate::GetInstance()->CreateWebContents( - ShellContentState::GetInstance()->GetActiveBrowserContext(), nullptr); +std::unique_ptr<content::WebContents> +ScreenOrientationControllerTest::CreateWebContents() { + return base::WrapUnique(content::WebContentsTester::CreateTestWebContents( + ShellContentState::GetInstance()->GetActiveBrowserContext(), nullptr)); } -content::WebContents* +std::unique_ptr<content::WebContents> ScreenOrientationControllerTest::CreateSecondaryWebContents() { secondary_browser_context_.reset(new content::TestBrowserContext()); - return views::ViewsDelegate::GetInstance()->CreateWebContents( - secondary_browser_context_.get(), nullptr); + return base::WrapUnique(content::WebContentsTester::CreateTestWebContents( + secondary_browser_context_.get(), nullptr)); } void ScreenOrientationControllerTest::SetUp() {
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view.cc b/ash/frame/caption_buttons/frame_caption_button_container_view.cc index 0e58755..6cdda6e 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view.cc
@@ -177,6 +177,7 @@ : 0); layout->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); + layout->set_main_axis_alignment(views::BoxLayout::MAIN_AXIS_ALIGNMENT_END); SetLayoutManager(std::move(layout)); tablet_mode_animation_.reset(new gfx::SlideAnimation(this)); tablet_mode_animation_->SetTweenType(gfx::Tween::LINEAR); @@ -322,6 +323,11 @@ // pushes the buttons to the left of the size button into the center. if (tablet_mode_animation_->is_animating()) AnimationProgressed(tablet_mode_animation_.get()); + + // The top right corner must be occupied by the close button for easy mouse + // access. This check is agnostic to RTL layout. + DCHECK_EQ(close_button_->y(), 0); + DCHECK_EQ(close_button_->bounds().right(), width()); } const char* FrameCaptionButtonContainerView::GetClassName() const { @@ -332,16 +338,18 @@ PreferredSizeChanged(); } +void FrameCaptionButtonContainerView::ChildVisibilityChanged(View* child) { + PreferredSizeChanged(); +} + void FrameCaptionButtonContainerView::AnimationEnded( const gfx::Animation* animation) { // Ensure that position is calculated at least once. AnimationProgressed(animation); double current_value = tablet_mode_animation_->GetCurrentValue(); - if (current_value == 0.0) { + if (current_value == 0.0) size_button_->SetVisible(false); - PreferredSizeChanged(); - } } void FrameCaptionButtonContainerView::AnimationProgressed(
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view.h b/ash/frame/caption_buttons/frame_caption_button_container_view.h index 3947c3a..380bf41 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view.h +++ b/ash/frame/caption_buttons/frame_caption_button_container_view.h
@@ -115,6 +115,7 @@ void Layout() override; const char* GetClassName() const override; void ChildPreferredSizeChanged(View* child) override; + void ChildVisibilityChanged(View* child) override; // gfx::AnimationDelegate: void AnimationEnded(const gfx::Animation* animation) override;
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc index 44c7c40..59e84d62 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc
@@ -11,6 +11,7 @@ #include "ash/test/ash_test_base.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ui/gfx/geometry/rect.h" +#include "ui/views/test/test_views.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" @@ -151,8 +152,7 @@ // Add an extra button to the left of the size button to verify that it is // repositioned similarly to the minimize button. This simulates the PWA menu // button being added to the left of the minimize button. - FrameCaptionButton* extra_button = - new FrameCaptionButton(&container, CAPTION_BUTTON_ICON_BACK); + views::View* extra_button = new views::StaticSizedView(gfx::Size(32, 32)); container.AddChildViewAt(extra_button, 0); InitContainer(&container);
diff --git a/ash/shell.cc b/ash/shell.cc index 104fa202..a3d3b08 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -1450,12 +1450,12 @@ break; case session_manager::SessionState::LOGGED_IN_NOT_ACTIVE: case session_manager::SessionState::ACTIVE: - // Recreate the keyboard on user profile change, to refresh keyboard + // Reload the keyboard on user profile change to refresh keyboard // extensions with the new profile and ensure the extensions call the // proper IME. |LOGGED_IN_NOT_ACTIVE| is needed so that the virtual // keyboard works on supervised user creation, http://crbug.com/712873. // |ACTIVE| is also needed for guest user workflow. - CreateKeyboard(); + ReloadKeyboard(); break; default: break;
diff --git a/ash/test/ash_test_environment_content.cc b/ash/test/ash_test_environment_content.cc index 469eaf7..05c1547 100644 --- a/ash/test/ash_test_environment_content.cc +++ b/ash/test/ash_test_environment_content.cc
@@ -14,22 +14,11 @@ namespace ash { namespace { -class AshTestViewsDelegateContent : public AshTestViewsDelegate { - public: - AshTestViewsDelegateContent() = default; - ~AshTestViewsDelegateContent() override = default; - - // AshTestViewsDelegate: - content::WebContents* CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance) override { - return content::WebContentsTester::CreateTestWebContents(browser_context, - site_instance); - } - - private: - DISALLOW_COPY_AND_ASSIGN(AshTestViewsDelegateContent); -}; +std::unique_ptr<content::WebContents> CreateWebContents( + content::BrowserContext* browser_context) { + return base::WrapUnique(content::WebContentsTester::CreateTestWebContents( + browser_context, nullptr)); +} } // namespace @@ -54,16 +43,20 @@ test_shell_content_state_ = new TestShellContentState; content_state = test_shell_content_state_; } + scoped_web_contents_creator_ = + std::make_unique<views::WebView::ScopedWebContentsCreatorForTesting>( + base::BindRepeating(&CreateWebContents)); ShellContentState::SetInstance(content_state); } void AshTestEnvironmentContent::TearDown() { + scoped_web_contents_creator_.reset(); ShellContentState::DestroyInstance(); } std::unique_ptr<AshTestViewsDelegate> AshTestEnvironmentContent::CreateViewsDelegate() { - return std::make_unique<AshTestViewsDelegateContent>(); + return std::make_unique<AshTestViewsDelegate>(); } } // namespace ash
diff --git a/ash/test/ash_test_environment_content.h b/ash/test/ash_test_environment_content.h index ec13f13..5e18b0ee 100644 --- a/ash/test/ash_test_environment_content.h +++ b/ash/test/ash_test_environment_content.h
@@ -7,6 +7,7 @@ #include "ash/test/ash_test_environment.h" #include "base/macros.h" +#include "ui/views/controls/webview/webview.h" namespace content { class TestBrowserThreadBundle; @@ -37,6 +38,8 @@ private: std::unique_ptr<content::TestBrowserThreadBundle> thread_bundle_; + std::unique_ptr<views::WebView::ScopedWebContentsCreatorForTesting> + scoped_web_contents_creator_; // An implementation of ShellContentState supplied by the user prior to // SetUp().
diff --git a/ash/wm/overview/window_selector_item.cc b/ash/wm/overview/window_selector_item.cc index 70ceb83..50c3e7c 100644 --- a/ash/wm/overview/window_selector_item.cc +++ b/ash/wm/overview/window_selector_item.cc
@@ -303,6 +303,16 @@ WindowSelectorItem::OverviewCloseButton::~OverviewCloseButton() = default; +std::unique_ptr<views::InkDrop> +WindowSelectorItem::OverviewCloseButton::CreateInkDrop() { + std::unique_ptr<views::InkDropImpl> ink_drop = + std::make_unique<views::InkDropImpl>(this, size()); + ink_drop->SetAutoHighlightMode( + views::InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE); + ink_drop->SetShowHighlightOnHover(true); + return ink_drop; +} + std::unique_ptr<views::InkDropRipple> WindowSelectorItem::OverviewCloseButton::CreateInkDropRipple() const { return std::make_unique<views::FloodFillInkDropRipple>(
diff --git a/ash/wm/overview/window_selector_item.h b/ash/wm/overview/window_selector_item.h index 902a674..3668331d 100644 --- a/ash/wm/overview/window_selector_item.h +++ b/ash/wm/overview/window_selector_item.h
@@ -49,7 +49,8 @@ void ResetListener() { listener_ = nullptr; } protected: - // views::ImageButton: + // views::Button: + std::unique_ptr<views::InkDrop> CreateInkDrop() override; std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override; std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight() const override;
diff --git a/base/BUILD.gn b/base/BUILD.gn index cba9b37..46ee3376 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -2545,6 +2545,10 @@ } deps += [ "//base/test:malloc_wrapper" ] + defines += [ + # This library is used by ElfReaderTest to test reading elf files. + "MALLOC_WRAPPER_LIB=\"${shlib_prefix}malloc_wrapper${shlib_extension}\"", + ] if (!is_component_build) { # Set rpath to find libmalloc_wrapper.so even in a non-component build.
diff --git a/base/base_paths_fuchsia.cc b/base/base_paths_fuchsia.cc index e0bc009..44a1162 100644 --- a/base/base_paths_fuchsia.cc +++ b/base/base_paths_fuchsia.cc
@@ -43,18 +43,12 @@ } case DIR_SOURCE_ROOT: *result = GetPackageRoot(); - if (result->empty()) { - *result = FilePath("/system"); - } return true; case DIR_CACHE: *result = FilePath("/data"); return true; case DIR_ASSETS: *result = GetPackageRoot(); - if (result->empty()) { - return PathService::Get(DIR_EXE, result); - } return true; } return false;
diff --git a/base/debug/elf_reader_linux.cc b/base/debug/elf_reader_linux.cc index 9a1d3f04..cdf8193 100644 --- a/base/debug/elf_reader_linux.cc +++ b/base/debug/elf_reader_linux.cc
@@ -21,14 +21,18 @@ #if __SIZEOF_POINTER__ == 4 using Ehdr = Elf32_Ehdr; +using Dyn = Elf32_Dyn; using Half = Elf32_Half; using Nhdr = Elf32_Nhdr; using Phdr = Elf32_Phdr; +using Word = Elf32_Word; #else using Ehdr = Elf64_Ehdr; +using Dyn = Elf64_Dyn; using Half = Elf64_Half; using Nhdr = Elf64_Nhdr; using Phdr = Elf64_Phdr; +using Word = Elf64_Word; #endif using ElfSegment = span<const char>; @@ -84,7 +88,7 @@ Optional<std::string> ReadElfBuildId(const void* elf_base) { // Elf program headers can have multiple PT_NOTE arrays. - std::vector<ElfSegment> segs = FindElfSegments(&elf_base, PT_NOTE); + std::vector<ElfSegment> segs = FindElfSegments(elf_base, PT_NOTE); if (segs.empty()) return nullopt; Optional<std::string> id; @@ -97,5 +101,32 @@ return nullopt; } +Optional<std::string> ReadElfLibraryName(const void* elf_base) { + std::vector<ElfSegment> segs = FindElfSegments(elf_base, PT_DYNAMIC); + if (segs.empty()) + return nullopt; + DCHECK_EQ(1u, segs.size()); + + const ElfSegment& dynamic_seg = segs.front(); + const Dyn* dynamic_start = reinterpret_cast<const Dyn*>(dynamic_seg.data()); + const Dyn* dynamic_end = reinterpret_cast<const Dyn*>( + dynamic_seg.data() + dynamic_seg.size_bytes()); + Optional<std::string> soname; + Word soname_strtab_offset = 0; + const char* strtab_addr = 0; + for (const Dyn* dynamic_iter = dynamic_start; dynamic_iter < dynamic_end; + ++dynamic_iter) { + if (dynamic_iter->d_tag == DT_STRTAB) { + strtab_addr = + dynamic_iter->d_un.d_ptr + reinterpret_cast<const char*>(elf_base); + } else if (dynamic_iter->d_tag == DT_SONAME) { + soname_strtab_offset = dynamic_iter->d_un.d_val; + } + } + if (soname_strtab_offset && strtab_addr) + return std::string(strtab_addr + soname_strtab_offset); + return nullopt; +} + } // namespace debug } // namespace base
diff --git a/base/debug/elf_reader_linux.h b/base/debug/elf_reader_linux.h index 20d4463..4086dfb 100644 --- a/base/debug/elf_reader_linux.h +++ b/base/debug/elf_reader_linux.h
@@ -18,6 +18,10 @@ // in memory. Optional<std::string> BASE_EXPORT ReadElfBuildId(const void* elf_base); +// Returns the library name from the ELF file mapped at |elf_base|, if present. +// The caller must ensure that the file is fully mapped in memory. +Optional<std::string> BASE_EXPORT ReadElfLibraryName(const void* elf_base); + } // namespace debug } // namespace base
diff --git a/base/debug/elf_reader_linux_unittest.cc b/base/debug/elf_reader_linux_unittest.cc index 96cc8f41..c24be15 100644 --- a/base/debug/elf_reader_linux_unittest.cc +++ b/base/debug/elf_reader_linux_unittest.cc
@@ -4,7 +4,11 @@ #include "base/debug/elf_reader_linux.h" +#include <dlfcn.h> + +#include "base/files/memory_mapped_file.h" #include "base/strings/string_util.h" +#include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" extern char __executable_start; @@ -28,5 +32,37 @@ } #endif +TEST(ElfReaderTest, ReadElfLibraryName) { +#if defined(OS_ANDROID) + // On Android the library loader memory maps the full so file. + const char kLibraryName[] = "lib_base_unittests__library.so"; + const void* addr = &__executable_start; +#else + // On Linux the executable does not contain soname and is not mapped till + // dynamic segment. So, use malloc wrapper so file on which the test already + // depends on. + const char kLibraryName[] = MALLOC_WRAPPER_LIB; + // Find any symbol in the loaded file. + void* handle = dlopen(kLibraryName, RTLD_NOW | RTLD_LOCAL); + const void* init_addr = dlsym(handle, "_init"); + // Use this symbol to get full path to the loaded library. + Dl_info info; + int res = dladdr(init_addr, &info); + ASSERT_NE(0, res); + std::string filename(info.dli_fname); + EXPECT_FALSE(filename.empty()); + EXPECT_NE(std::string::npos, filename.find(kLibraryName)); + + // Memory map the so file and use it to test reading so name. + MemoryMappedFile file; + file.Initialize(FilePath(filename)); + const void* addr = file.data(); +#endif + + auto name = ReadElfLibraryName(addr); + ASSERT_TRUE(name); + EXPECT_EQ(kLibraryName, *name); +} + } // namespace debug } // namespace base
diff --git a/base/native_library_fuchsia.cc b/base/native_library_fuchsia.cc index 1d68cbd..1d74273c 100644 --- a/base/native_library_fuchsia.cc +++ b/base/native_library_fuchsia.cc
@@ -40,15 +40,7 @@ return nullptr; } - // Fuchsia libraries must live under the "lib" directory, which may be located - // in /system/lib or /pkg/lib depending on whether the executable is running - // inside a package. - // TODO(https://crbug.com/805057): Remove the non-package codepath when bootfs - // is deprecated. FilePath computed_path = base::GetPackageRoot(); - if (computed_path.empty()) { - CHECK(PathService::Get(DIR_EXE, &computed_path)); - } computed_path = computed_path.AppendASCII("lib").Append(components[0]); base::File library(computed_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
diff --git a/base/process/process_util_unittest.cc b/base/process/process_util_unittest.cc index afe3c8c0e..88890c8 100644 --- a/base/process/process_util_unittest.cc +++ b/base/process/process_util_unittest.cc
@@ -242,11 +242,6 @@ } TEST_F(ProcessUtilTest, SelectivelyClonedDir) { - // Selective cloning only works if the test executable is deployed as a - // package. - if (GetPackageRoot().empty()) - return; - const std::string signal_file = ProcessUtilTest::GetSignalFilePath(kSignalFileClone); remove(signal_file.c_str()); @@ -269,11 +264,6 @@ // error code if it detects a directory other than "/tmp", so we can use that as // a signal that it successfully detected another entry in the root namespace. TEST_F(ProcessUtilTest, CloneAlternateDir) { - // Selective cloning only works if the test executable is deployed as a - // package. - if (GetPackageRoot().empty()) - return; - const std::string signal_file = ProcessUtilTest::GetSignalFilePath(kSignalFileClone); remove(signal_file.c_str());
diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index 187f76cb..717cc28f 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn
@@ -78,13 +78,7 @@ if (use_nss_certs) { defines += [ "USE_NSS_CERTS=1" ] } - if (use_ozone && !is_android) { - # Note that some Chrome OS builds unconditionally set |use_ozone| to true, - # but they also build some targets with the Android toolchain. This ensures - # that Android targets still build with USE_OZONE=0 in such cases. - # - # TODO(crbug.com/837032): Maybe this can be cleaned up if we can avoid - # setting use_ozone globally. + if (use_ozone) { defines += [ "USE_OZONE=1" ] } if (use_x11) {
diff --git a/build/config/BUILDCONFIG.gn b/build/config/BUILDCONFIG.gn index 656b995f..162f7a7 100644 --- a/build/config/BUILDCONFIG.gn +++ b/build/config/BUILDCONFIG.gn
@@ -205,12 +205,18 @@ } else if (host_os == "mac") { host_toolchain = "//build/toolchain/mac:clang_$host_cpu" } else if (host_os == "win") { - # On Windows always use the target CPU for host builds. On the + # On Windows always use the target CPU for host builds for x86/x64. On the # configurations we support this will always work and it saves build steps. - if (is_clang) { - host_toolchain = "//build/toolchain/win:win_clang_$target_cpu" + if (target_cpu == "x86" || target_cpu == "x64") { + if (is_clang) { + host_toolchain = "//build/toolchain/win:win_clang_$target_cpu" + } else { + host_toolchain = "//build/toolchain/win:$target_cpu" + } + } else if (is_clang) { + host_toolchain = "//build/toolchain/win:win_clang_$host_cpu" } else { - host_toolchain = "//build/toolchain/win:$target_cpu" + host_toolchain = "//build/toolchain/win:$host_cpu" } } else if (host_os == "aix") { host_toolchain = "//build/toolchain/aix:$host_cpu"
diff --git a/build/config/android/abi.gni b/build/config/android/abi.gni index dc25b498..877c3f74 100644 --- a/build/config/android/abi.gni +++ b/build/config/android/abi.gni
@@ -5,10 +5,7 @@ # Logic separated out from config.gni so that it can be used by compiler.gni # without introducing a circular dependency. -# NOTE: Because Chrome OS builds may depend on targets built with the Android -# toolchain, this GNI file may be read and processed from within Chrome OS -# toolchains. Checking |is_android| here would therefore be too restrictive. -assert(is_android || is_chromeos) +assert(is_android) declare_args() { # Adds intrumentation to each function. Writes a file with the order that
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index 8b5d273..4dcd5b1 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -4,10 +4,7 @@ # This file contains common system config stuff for the Android build. -# NOTE: Because Chrome OS builds may depend on targets built with the Android -# toolchain, this GNI file may be read and processed from within Chrome OS -# toolchains. Checking |is_android| here would therefore be too restrictive. -if (is_android || is_chromeos) { +if (is_android) { import("//build_overrides/build.gni") import("abi.gni") @@ -16,11 +13,9 @@ # heavily but don't write gclient args files. import("//build/config/gclient_args.gni") - if (defined(checkout_android_native_support)) { - assert(checkout_android_native_support, - "Missing native Android toolchain support. |target_os| in your " + - ".gclient configuration must include \"android\" and/or " + - "\"chromeos\".") + if (defined(checkout_android)) { + assert(checkout_android, + "target_os in your .gclient configuration must include android.") } }
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 7ce97ad..ccc2bc80 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -416,14 +416,7 @@ ldflags += [ "--gcc-toolchain=$_rebased_android_toolchain_root" ] } - if (((is_posix || is_fuchsia) && use_lld && !is_nacl) || - (target_os == "chromeos" && is_android)) { - # NOTE: Some Chrome OS builds globally disable LLD, but they also build some - # targets against Android toolchains which should use LLD. Therefore we - # explicitly select LLD in these cases. - # - # TODO(https://crbug.com/837095): This should be cleaned up if/when LLD can - # work properly for Chrome OS builds. + if ((is_posix || is_fuchsia) && use_lld && !is_nacl) { ldflags += [ "-fuse-ld=lld" ] if (current_cpu == "arm64") { # Reduce the page size from 65536 in order to reduce binary size slightly @@ -2123,13 +2116,7 @@ } cflags += [ "-g2" ] } - if (use_debug_fission && !is_nacl && !is_android) { - # NOTE: Some Chrome OS builds globally set |use_debug_fission| to true, - # but they also build some targets against Android toolchains which aren't - # compatible with it. - # - # TODO(https://crbug.com/837032): See if we can clean this up by e.g. not - # setting use_debug_fission globally. + if (use_debug_fission && !is_nacl) { cflags += [ "-gsplit-dwarf" ] } asmflags = cflags
diff --git a/build/config/compiler/compiler.gni b/build/config/compiler/compiler.gni index 79838c08..a33d421b 100644 --- a/build/config/compiler/compiler.gni +++ b/build/config/compiler/compiler.gni
@@ -225,9 +225,7 @@ } # Assert that the configuration isn't going to hit https://crbug.com/648948. -# An exception is made when target_os == "chromeos" as we only use the Android -# toolchain there to build relatively small binaries. -assert(ignore_elf32_limitations || !is_android || target_os == "chromeos" || +assert(ignore_elf32_limitations || !is_android || (android_64bit_target_cpu && !build_apk_secondary_abi) || is_component_build || symbol_level < 2, "Android 32-bit non-component builds cannot have symbol_level=2 " +
diff --git a/build/config/win/BUILD.gn b/build/config/win/BUILD.gn index a5411c98c..ee8e5e8 100644 --- a/build/config/win/BUILD.gn +++ b/build/config/win/BUILD.gn
@@ -187,6 +187,7 @@ # :runtime_library vs. :compiler. config("runtime_library") { cflags = [] + cflags_cc = [] # Defines that set up the CRT. defines = [ @@ -219,7 +220,8 @@ } if (use_custom_libcxx) { - cflags_cc = [ "-I" + rebase_path("$libcxx_prefix/include", root_build_dir) ] + cflags_cc += + [ "-I" + rebase_path("$libcxx_prefix/include", root_build_dir) ] if (libcpp_is_static) { defines += [ "_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS" ] }
diff --git a/build/toolchain/toolchain.gni b/build/toolchain/toolchain.gni index 21adefc..cb0b9b0f 100644 --- a/build/toolchain/toolchain.gni +++ b/build/toolchain/toolchain.gni
@@ -36,7 +36,7 @@ assert( is_official_build, "Linker map files should only be generated when is_official_build = true") - assert(current_os == "android" || current_os == "linux", + assert(target_os == "android" || target_os == "linux", "Linker map files should only be generated for Android and Linux") }
diff --git a/build/toolchain/win/BUILD.gn b/build/toolchain/win/BUILD.gn index 3652350..4d9d1f4 100644 --- a/build/toolchain/win/BUILD.gn +++ b/build/toolchain/win/BUILD.gn
@@ -334,42 +334,47 @@ clang_cl = "clang-cl" } -# x86, arm and arm64 toolchains for Windows (not WinUWP). Only define when the -# target architecture is one of these architectures since we don't do any arm -# cross compiles when targeting 64-bit (the build does generate some 64-bit -# stuff from 32-bit/arm/arm64 target builds). -if (target_os == "win" && - (target_cpu == "x86" || target_cpu == "arm" || target_cpu == "arm64")) { - target_cpu_toolchain_data = exec_script("setup_toolchain.py", - [ - visual_studio_path, - windows_sdk_path, - visual_studio_runtime_dirs, - target_os, - target_cpu, - "environment." + target_cpu, - ], - "scope") +if (target_cpu == "x86" || target_cpu == "x64") { + win_build_host_cpu = target_cpu +} else { + win_build_host_cpu = host_cpu +} - msvc_toolchain(target_cpu) { - environment = "environment." + target_cpu - cl = "${goma_prefix}\"${target_cpu_toolchain_data.vc_bin_dir}/cl.exe\"" +# x86, arm and arm64 build cpu toolchains for Windows (not WinUWP). Only +# define when the build cpu is one of these architectures since we don't +# do any cross compiles when targeting x64-bit (the build does generate +# some 64-bit stuff from x86/arm/arm64 target builds). +if (win_build_host_cpu != "x64") { + build_cpu_toolchain_data = exec_script("setup_toolchain.py", + [ + visual_studio_path, + windows_sdk_path, + visual_studio_runtime_dirs, + host_os, + win_build_host_cpu, + "environment." + win_build_host_cpu, + ], + "scope") + + msvc_toolchain(win_build_host_cpu) { + environment = "environment." + win_build_host_cpu + cl = "${goma_prefix}\"${build_cpu_toolchain_data.vc_bin_dir}/cl.exe\"" toolchain_args = { current_os = "win" - current_cpu = target_cpu + current_cpu = win_build_host_cpu is_clang = false } } - msvc_toolchain("win_clang_" + target_cpu) { - environment = "environment." + target_cpu + msvc_toolchain("win_clang_" + win_build_host_cpu) { + environment = "environment." + win_build_host_cpu prefix = rebase_path("$clang_base_path/bin", root_build_dir) cl = "${goma_prefix}$prefix/${clang_cl}" - sys_include_flags = "${target_cpu_toolchain_data.include_flags_imsvc}" + sys_include_flags = "${build_cpu_toolchain_data.include_flags_imsvc}" toolchain_args = { current_os = "win" - current_cpu = target_cpu + current_cpu = win_build_host_cpu is_clang = true } }
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 721834c..009a281d 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -299,10 +299,7 @@ } if (is_chromeos) { - data_deps += [ - "//mojo/edk:mojo_core", - "//mojo/edk:mojo_core_for_arc", - ] + data_deps += [ "//mojo/edk:mojo_core" ] } # These files are used by the installer so we need a public dep.
diff --git a/chrome/VERSION b/chrome/VERSION index 5e2c2ab..dd910a4 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=68 MINOR=0 -BUILD=3414 +BUILD=3416 PATCH=0
diff --git a/chrome/android/java/DEPS b/chrome/android/java/DEPS index 7e55b37..d48b564 100644 --- a/chrome/android/java/DEPS +++ b/chrome/android/java/DEPS
@@ -22,7 +22,6 @@ "!content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java", "!content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibility.java", "!content/public/android/java/src/org/chromium/content/browser/ActivityContentVideoViewEmbedder.java", - "!content/public/android/java/src/org/chromium/content/browser/AppWebMessagePort.java", "!content/public/android/java/src/org/chromium/content/browser/BrowserStartupController.java", "!content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParams.java", "!content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/PostMessageHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/PostMessageHandler.java index 2c8587b..1cdf5dbc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/PostMessageHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/PostMessageHandler.java
@@ -16,7 +16,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.browserservices.OriginVerifier.OriginVerificationListener; import org.chromium.chrome.browser.tab.Tab; -import org.chromium.content.browser.AppWebMessagePort; import org.chromium.content_public.browser.MessagePort; import org.chromium.content_public.browser.MessagePort.MessageCallback; import org.chromium.content_public.browser.WebContents; @@ -31,7 +30,7 @@ private WebContents mWebContents; private boolean mMessageChannelCreated; private boolean mBoundToService; - private AppWebMessagePort[] mChannel; + private MessagePort[] mChannel; private Uri mPostMessageUri; private String mPackageName; @@ -121,11 +120,11 @@ } private void initializeWithWebContents(final WebContents webContents) { - mChannel = (AppWebMessagePort[]) webContents.createMessageChannel(); + mChannel = webContents.createMessageChannel(); mChannel[0].setMessageCallback(mMessageCallback, null); webContents.postMessageToFrame( - null, "", mPostMessageUri.toString(), "", new AppWebMessagePort[] {mChannel[1]}); + null, "", mPostMessageUri.toString(), "", new MessagePort[] {mChannel[1]}); mMessageChannelCreated = true; if (mBoundToService) notifyMessageChannelReady(null);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 6d2689a..cd458bc 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -1557,6 +1557,7 @@ */ @Test @SmallTest + @DisableIf.Build(sdk_is_less_than = Build.VERSION_CODES.LOLLIPOP, message = "crbug.com/837998") @Feature({"ContextualSearch"}) public void testLongPressGestureFollowedByTapDoesntSelect() throws InterruptedException, TimeoutException {
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 6f76ad1..5b284b3 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-68.0.3410.0_rc-r1.afdo.bz2 \ No newline at end of file +chromeos-chrome-amd64-68.0.3415.0_rc-r2.afdo.bz2 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 7d0adb6..7f5f6e4 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2628,6 +2628,8 @@ "resource_coordinator/site_characteristics_data_store.h", "resource_coordinator/tab_activity_watcher.cc", "resource_coordinator/tab_activity_watcher.h", + "resource_coordinator/tab_features.cc", + "resource_coordinator/tab_features.h", "resource_coordinator/tab_lifecycle_observer.h", "resource_coordinator/tab_lifecycle_unit.cc", "resource_coordinator/tab_lifecycle_unit.h",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 829278d..9475415 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2416,10 +2416,6 @@ autofill::switches::kEnableOfferUploadCreditCards, autofill::switches::kDisableOfferUploadCreditCards)}, #endif // TOOLKIT_VIEWS || OS_ANDROID - {"enable-md-bookmarks", - flag_descriptions::kEnableMaterialDesignBookmarksName, - flag_descriptions::kEnableMaterialDesignBookmarksDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kMaterialDesignBookmarks)}, {"enable-md-incognito-ntp", flag_descriptions::kMaterialDesignIncognitoNTPName, flag_descriptions::kMaterialDesignIncognitoNTPDescription, kOsAndroid,
diff --git a/chrome/browser/android/web_contents_factory.cc b/chrome/browser/android/web_contents_factory.cc index e1c4f9d..18296b6 100644 --- a/chrome/browser/android/web_contents_factory.cc +++ b/chrome/browser/android/web_contents_factory.cc
@@ -27,5 +27,6 @@ content::WebContents::CreateParams params(profile); params.initially_hidden = static_cast<bool>(initially_hidden); params.initialize_renderer = static_cast<bool>(initialize_renderer); - return content::WebContents::Create(params)->GetJavaWebContents(); + // Ownership is passed into java, and then to TabAndroid::InitWebContents. + return content::WebContents::Create(params).release()->GetJavaWebContents(); }
diff --git a/chrome/browser/background/background_contents.cc b/chrome/browser/background/background_contents.cc index 1eca1ed..709dc7a 100644 --- a/chrome/browser/background/background_contents.cc +++ b/chrome/browser/background/background_contents.cc
@@ -63,7 +63,7 @@ web_contents_.reset(WebContents::CreateWithSessionStorage( create_params, session_storage_namespace_map)); } else { - web_contents_.reset(WebContents::Create(create_params)); + web_contents_ = WebContents::Create(create_params); } extensions::SetViewType( web_contents_.get(), extensions::VIEW_TYPE_BACKGROUND_CONTENTS);
diff --git a/chrome/browser/bookmarks/bookmark_model_factory.cc b/chrome/browser/bookmarks/bookmark_model_factory.cc index fa04f62a..7bc5ce0 100644 --- a/chrome/browser/bookmarks/bookmark_model_factory.cc +++ b/chrome/browser/bookmarks/bookmark_model_factory.cc
@@ -27,21 +27,6 @@ using bookmarks::BookmarkModel; -namespace { - -bool IsBookmarkUndoServiceEnabled() { - bool register_bookmark_undo_service_as_observer = true; -#if !defined(OS_ANDROID) - register_bookmark_undo_service_as_observer = - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableBookmarkUndo) || - MdBookmarksUI::IsEnabled(); -#endif // !defined(OS_ANDROID) - return register_bookmark_undo_service_as_observer; -} - -} // namespace - // static BookmarkModel* BookmarkModelFactory::GetForBrowserContext( content::BrowserContext* context) { @@ -84,8 +69,7 @@ ->GetBookmarkTaskRunner(), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI)); - if (IsBookmarkUndoServiceEnabled()) - BookmarkUndoServiceFactory::GetForProfile(profile)->Start(bookmark_model); + BookmarkUndoServiceFactory::GetForProfile(profile)->Start(bookmark_model); return bookmark_model; }
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 42ea5d9..c8d7188 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -112,7 +112,6 @@ <include name="IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS" file="resources\bluetooth_internals\sidebar.js" type="BINDATA" compress="gzip" /> <include name="IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS" file="resources\bluetooth_internals\snackbar.js" type="BINDATA" compress="gzip" /> <include name="IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS" file="resources\bluetooth_internals\value_control.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BOOKMARKS_MANIFEST" file="resources\bookmark_manager\manifest.json" type="BINDATA" /> <if expr="is_posix and not is_macosx"> <include name="IDR_CERTIFICATE_VIEWER_HTML" file="resources\certificate_viewer.html" type="BINDATA" /> <include name="IDR_CERTIFICATE_VIEWER_JS" file="resources\certificate_viewer.js" type="BINDATA" />
diff --git a/chrome/browser/chromeos/assistant/assistant_card_renderer.cc b/chrome/browser/chromeos/assistant/assistant_card_renderer.cc index 22b0ceb2..e6f43cf 100644 --- a/chrome/browser/chromeos/assistant/assistant_card_renderer.cc +++ b/chrome/browser/chromeos/assistant/assistant_card_renderer.cc
@@ -75,9 +75,9 @@ private: void InitWebContents(Profile* profile, ash::mojom::AssistantCardParamsPtr params) { - web_contents_.reset( + web_contents_ = content::WebContents::Create(content::WebContents::CreateParams( - profile, content::SiteInstance::Create(profile)))); + profile, content::SiteInstance::Create(profile))); // Use a transparent background. views::WebContentsSetBackgroundColor::CreateForWebContentsWithColor(
diff --git a/chrome/browser/chromeos/crostini/crostini_registry_service.cc b/chrome/browser/chromeos/crostini/crostini_registry_service.cc index 07ccc230..8eb795d 100644 --- a/chrome/browser/chromeos/crostini/crostini_registry_service.cc +++ b/chrome/browser/chromeos/crostini/crostini_registry_service.cc
@@ -457,6 +457,38 @@ RequestIcon(app_id, scale_factor); } +void CrostiniRegistryService::ClearApplicationList( + const std::string& vm_name, + const std::string& container_name) { + std::vector<std::string> removed_apps; + // The DictionaryPrefUpdate should be destructed before calling the observer. + { + DictionaryPrefUpdate update(prefs_, kCrostiniRegistryPref); + base::DictionaryValue* apps = update.Get(); + + for (const auto& item : apps->DictItems()) { + if (item.first == kCrostiniTerminalId) + continue; + if (item.second.FindKey(kAppVmNameKey)->GetString() == vm_name && + item.second.FindKey(kAppContainerNameKey)->GetString() == + container_name) { + removed_apps.push_back(item.first); + } + } + for (const std::string& removed_app : removed_apps) { + RemoveAppData(removed_app); + apps->RemoveKey(removed_app); + } + } + + if (removed_apps.empty()) + return; + std::vector<std::string> updated_apps; + std::vector<std::string> inserted_apps; + for (Observer& obs : observers_) + obs.OnRegistryUpdated(this, updated_apps, removed_apps, inserted_apps); +} + void CrostiniRegistryService::UpdateApplicationList( const vm_tools::apps::ApplicationList& app_list) { if (app_list.vm_name().empty()) {
diff --git a/chrome/browser/chromeos/crostini/crostini_registry_service.h b/chrome/browser/chromeos/crostini/crostini_registry_service.h index 9d0ad63f..d30ec6f 100644 --- a/chrome/browser/chromeos/crostini/crostini_registry_service.h +++ b/chrome/browser/chromeos/crostini/crostini_registry_service.h
@@ -156,6 +156,10 @@ void MaybeRequestIcon(const std::string& app_id, ui::ScaleFactor scale_factor); + // Remove all apps from the named container. Used in the uninstall process. + void ClearApplicationList(const std::string& vm_name, + const std::string& container_name); + // The existing list of apps is replaced by |application_list|. void UpdateApplicationList(const vm_tools::apps::ApplicationList& app_list);
diff --git a/chrome/browser/chromeos/crostini/crostini_registry_service_unittest.cc b/chrome/browser/chromeos/crostini/crostini_registry_service_unittest.cc index 72b08466..195d0ce 100644 --- a/chrome/browser/chromeos/crostini/crostini_registry_service_unittest.cc +++ b/chrome/browser/chromeos/crostini/crostini_registry_service_unittest.cc
@@ -238,6 +238,30 @@ kCrostiniTerminalId)); } +// Test that ClearApplicationList works, and only removes apps from the +// specified container. +TEST_F(CrostiniRegistryServiceTest, ClearApplicationList) { + service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 1")); + service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 2")); + ApplicationList app_list = BasicAppList("app", "vm 2", "container 1"); + *app_list.add_apps() = BasicApp("app 2"); + service()->UpdateApplicationList(app_list); + std::string app_id_1 = GenerateAppId("app", "vm 1", "container 1"); + std::string app_id_2 = GenerateAppId("app", "vm 1", "container 2"); + std::string app_id_3 = GenerateAppId("app", "vm 2", "container 1"); + std::string app_id_4 = GenerateAppId("app 2", "vm 2", "container 1"); + + EXPECT_THAT(service()->GetRegisteredAppIds(), + testing::UnorderedElementsAre(app_id_1, app_id_2, app_id_3, + app_id_4, kCrostiniTerminalId)); + + service()->ClearApplicationList("vm 2", "container 1"); + + EXPECT_THAT( + service()->GetRegisteredAppIds(), + testing::UnorderedElementsAre(app_id_1, app_id_2, kCrostiniTerminalId)); +} + TEST_F(CrostiniRegistryServiceTest, GetCrostiniAppIdNoStartupID) { ApplicationList app_list = BasicAppList("app", "vm", "container"); *app_list.add_apps() = BasicApp("cool.app");
diff --git a/chrome/browser/chromeos/crostini/crostini_remover.cc b/chrome/browser/chromeos/crostini/crostini_remover.cc index cd57dfd..f425353d 100644 --- a/chrome/browser/chromeos/crostini/crostini_remover.cc +++ b/chrome/browser/chromeos/crostini/crostini_remover.cc
@@ -6,6 +6,8 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/crostini/crostini_pref_names.h" +#include "chrome/browser/chromeos/crostini/crostini_registry_service.h" +#include "chrome/browser/chromeos/crostini/crostini_registry_service_factory.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/component_updater/cros_component_installer.h" #include "chrome/browser/profiles/profile.h" @@ -53,6 +55,9 @@ void CrostiniRemover::StopVmFinished(crostini::ConciergeClientResult result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (result == crostini::ConciergeClientResult::SUCCESS) { + crostini::CrostiniRegistryServiceFactory::GetForProfile(profile_) + ->ClearApplicationList(kCrostiniDefaultVmName, + kCrostiniDefaultContainerName); crostini::CrostiniManager::GetInstance()->DestroyDiskImage( CryptohomeIdForProfile(profile_), base::FilePath(kCrostiniDefaultVmName),
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index 4991132..dc38f09 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -27,6 +27,15 @@ public FileManagerBrowserTestBase, public ::testing::WithParamInterface<TestParameter> { public: + void SetUpCommandLine(base::CommandLine* command_line) override { + FileManagerBrowserTestBase::SetUpCommandLine(command_line); + + if (shouldEnableLegacyEventDispatch()) { + command_line->AppendSwitchASCII("disable-blink-features", + "TrustedEventsDefaultAction"); + } + } + GuestMode GetGuestModeParam() const override { return std::get<0>(GetParam()); } @@ -38,6 +47,13 @@ const char* GetTestManifestName() const override { return "file_manager_test_manifest.json"; } + + private: + bool shouldEnableLegacyEventDispatch() { + const std::string test_case_name = GetTestCaseNameParam(); + // crbug.com/482121 crbug.com/480491 + return test_case_name.find("tabindex") != std::string::npos; + } }; IN_PROC_BROWSER_TEST_P(FileManagerBrowserTest, Test) { @@ -428,30 +444,26 @@ ::testing::Values(TestParameter(NOT_IN_GUEST_MODE, "tabindexFocusDirectorySelected"))); -// Fails on official cros trunk build. http://crbug.com/480491 -// TODO(crbug.com/836254) test broken when DISABLE removed. #if defined(DISABLE_SLOW_FILESAPP_TESTS) || defined(OFFICIAL_BUILD) #define MAYBE_TabindexOpenDialog DISABLED_TabindexOpenDialog #else #define MAYBE_TabindexOpenDialog TabindexOpenDialog #endif WRAPPED_INSTANTIATE_TEST_CASE_P( - DISABLED_TabindexOpenDialog, + MAYBE_TabindexOpenDialog, FileManagerBrowserTest, ::testing::Values( TestParameter(NOT_IN_GUEST_MODE, "tabindexOpenDialogDrive"), TestParameter(NOT_IN_GUEST_MODE, "tabindexOpenDialogDownloads"), TestParameter(IN_GUEST_MODE, "tabindexOpenDialogDownloads"))); -// Fails on official build. http://crbug.com/482121. -// TODO(crbug.com/836254) test broken when DISABLE removed. #if defined(DISABLE_SLOW_FILESAPP_TESTS) || defined(OFFICIAL_BUILD) #define MAYBE_TabindexSaveFileDialog DISABLED_TabindexSaveFileDialog #else #define MAYBE_TabindexSaveFileDialog TabindexSaveFileDialog #endif WRAPPED_INSTANTIATE_TEST_CASE_P( - DISABLED_TabindexSaveFileDialog, + MAYBE_TabindexSaveFileDialog, FileManagerBrowserTest, ::testing::Values( TestParameter(NOT_IN_GUEST_MODE, "tabindexSaveFileDialogDrive"), @@ -508,13 +520,8 @@ TestParameter(IN_GUEST_MODE, "showGridViewDownloads"), TestParameter(NOT_IN_GUEST_MODE, "showGridViewDrive"))); -#if defined(DISABLE_SLOW_FILESAPP_TESTS) -#define MAYBE_Providers DISABLED_Providers -#else -#define MAYBE_Providers Providers -#endif WRAPPED_INSTANTIATE_TEST_CASE_P( - MAYBE_Providers, + Providers, FileManagerBrowserTest, ::testing::Values( TestParameter(NOT_IN_GUEST_MODE, "requestMount"),
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc index aee67a2..181f0876 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc
@@ -30,6 +30,7 @@ #include "chromeos/chromeos_switches.h" #include "components/drive/chromeos/file_system_interface.h" #include "components/drive/service/fake_drive_service.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/test/test_api.h" @@ -60,61 +61,7 @@ SHARED, }; -// Obtains file manager test data directory. -base::FilePath GetTestFilePath(const std::string& relative_path) { - base::FilePath path; - if (!PathService::Get(base::DIR_SOURCE_ROOT, &path)) - return base::FilePath(); - path = path.AppendASCII("chrome") - .AppendASCII("test") - .AppendASCII("data") - .AppendASCII("chromeos") - .AppendASCII("file_manager") - .Append(base::FilePath::FromUTF8Unsafe(relative_path)); - return path; -} - -// Maps the given string to EntryType. Returns true on success. -bool MapStringToEntryType(base::StringPiece value, EntryType* output) { - if (value == "file") - *output = FILE; - else if (value == "directory") - *output = DIRECTORY; - else - return false; - return true; -} - -// Maps the given string to SharedOption. Returns true on success. -bool MapStringToSharedOption(base::StringPiece value, SharedOption* output) { - if (value == "shared") - *output = SHARED; - else if (value == "none") - *output = NONE; - else - return false; - return true; -} - -// Maps the given string to TargetVolume. Returns true on success. -bool MapStringToTargetVolume(base::StringPiece value, TargetVolume* output) { - if (value == "drive") - *output = DRIVE_VOLUME; - else if (value == "local") - *output = LOCAL_VOLUME; - else if (value == "usb") - *output = USB_VOLUME; - else - return false; - return true; -} - -// Maps the given string to base::Time. Returns true on success. -bool MapStringToTime(base::StringPiece value, base::Time* time) { - return base::Time::FromString(value.as_string().c_str(), time); -} - -// Test data of file or directory. +// Test data file or directory entry info. struct TestEntryInfo { TestEntryInfo() : type(FILE), shared_option(NONE) {} @@ -125,63 +72,99 @@ SharedOption shared_option, const base::Time& last_modified_time) : type(type), + shared_option(shared_option), source_file_name(source_file_name), target_path(target_path), mime_type(mime_type), - shared_option(shared_option), last_modified_time(last_modified_time) {} - EntryType type; - std::string source_file_name; // Source file name to be used as a prototype. - std::string target_path; // Target file or directory path. - std::string mime_type; - SharedOption shared_option; - base::Time last_modified_time; + EntryType type; // Entry type: file or directory. + SharedOption shared_option; // File entry sharing option. + std::string source_file_name; // Source file name prototype. + std::string target_path; // Target file or directory path. + std::string mime_type; // File entry content mime type. + base::Time last_modified_time; // Entry last modified time. // Registers the member information to the given converter. static void RegisterJSONConverter( - base::JSONValueConverter<TestEntryInfo>* converter); -}; + base::JSONValueConverter<TestEntryInfo>* converter) { + converter->RegisterCustomField("type", &TestEntryInfo::type, + &MapStringToEntryType); + converter->RegisterStringField("sourceFileName", + &TestEntryInfo::source_file_name); + converter->RegisterStringField("targetPath", &TestEntryInfo::target_path); + converter->RegisterStringField("mimeType", &TestEntryInfo::mime_type); + converter->RegisterCustomField("sharedOption", + &TestEntryInfo::shared_option, + &MapStringToSharedOption); + converter->RegisterCustomField("lastModifiedTime", + &TestEntryInfo::last_modified_time, + &MapStringToTime); + } -// static -void TestEntryInfo::RegisterJSONConverter( - base::JSONValueConverter<TestEntryInfo>* converter) { - converter->RegisterCustomField("type", &TestEntryInfo::type, - &MapStringToEntryType); - converter->RegisterStringField("sourceFileName", - &TestEntryInfo::source_file_name); - converter->RegisterStringField("targetPath", &TestEntryInfo::target_path); - converter->RegisterStringField("mimeType", &TestEntryInfo::mime_type); - converter->RegisterCustomField("sharedOption", &TestEntryInfo::shared_option, - &MapStringToSharedOption); - converter->RegisterCustomField( - "lastModifiedTime", &TestEntryInfo::last_modified_time, &MapStringToTime); -} + // Maps |value| to an EntryType. Returns true on success. + static bool MapStringToEntryType(base::StringPiece value, EntryType* type) { + if (value == "file") + *type = FILE; + else if (value == "directory") + *type = DIRECTORY; + else + return false; + return true; + } + + // Maps |value| to SharedOption. Returns true on success. + static bool MapStringToSharedOption(base::StringPiece value, + SharedOption* option) { + if (value == "shared") + *option = SHARED; + else if (value == "none") + *option = NONE; + else + return false; + return true; + } + + // Maps |value| to base::Time. Returns true on success. + static bool MapStringToTime(base::StringPiece value, base::Time* time) { + return base::Time::FromString(value.as_string().c_str(), time); + } +}; // Message from JavaScript to add entries. struct AddEntriesMessage { - // Target volume to be added the |entries|. - TargetVolume volume; - // Entries to be added. std::vector<std::unique_ptr<TestEntryInfo>> entries; + // Target volume to add |entries| to. + TargetVolume volume; + // Registers the member information to the given converter. static void RegisterJSONConverter( - base::JSONValueConverter<AddEntriesMessage>* converter); + base::JSONValueConverter<AddEntriesMessage>* converter) { + converter->RegisterCustomField("volume", &AddEntriesMessage::volume, + &MapStringToTargetVolume); + converter->RegisterRepeatedMessage<TestEntryInfo>( + "entries", &AddEntriesMessage::entries); + } + + // Maps |value| to TargetVolume. Returns true on success. + static bool MapStringToTargetVolume(base::StringPiece value, + TargetVolume* volume) { + if (value == "drive") + *volume = DRIVE_VOLUME; + else if (value == "local") + *volume = LOCAL_VOLUME; + else if (value == "usb") + *volume = USB_VOLUME; + else + return false; + return true; + } }; -// static -void AddEntriesMessage::RegisterJSONConverter( - base::JSONValueConverter<AddEntriesMessage>* converter) { - converter->RegisterCustomField("volume", &AddEntriesMessage::volume, - &MapStringToTargetVolume); - converter->RegisterRepeatedMessage<TestEntryInfo>( - "entries", &AddEntriesMessage::entries); -} - -// Listener to obtain the test relative messages synchronously. -class FileManagerTestListener : public content::NotificationObserver { +// Listens for chrome.test messages: PASS, FAIL, and SendMessage. +class FileManagerTestMessageListener : public content::NotificationObserver { public: struct Message { int type; @@ -189,7 +172,7 @@ scoped_refptr<extensions::TestSendMessageFunction> function; }; - FileManagerTestListener() { + FileManagerTestMessageListener() { registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_TEST_PASSED, content::NotificationService::AllSources()); registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_TEST_FAILED, @@ -199,32 +182,49 @@ } Message GetNextMessage() { - if (messages_.empty()) - content::RunMessageLoop(); - const Message entry = messages_.front(); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + if (messages_.empty()) { + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + } + + DCHECK(!messages_.empty()); + const Message next = messages_.front(); messages_.pop_front(); - return entry; + return next; } void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override { - Message entry; - entry.type = type; - entry.message = type != extensions::NOTIFICATION_EXTENSION_TEST_PASSED - ? *content::Details<std::string>(details).ptr() - : std::string(); - if (type == extensions::NOTIFICATION_EXTENSION_TEST_MESSAGE) { - entry.function = - content::Source<extensions::TestSendMessageFunction>(source).ptr(); - *content::Details<std::pair<std::string, bool*>>(details).ptr()->second = - true; + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + Message message{type, std::string(), nullptr}; + if (type == extensions::NOTIFICATION_EXTENSION_TEST_PASSED) { + test_complete_ = true; + } else if (type == extensions::NOTIFICATION_EXTENSION_TEST_FAILED) { + message.message = *content::Details<std::string>(details).ptr(); + test_complete_ = true; + } else if (type == extensions::NOTIFICATION_EXTENSION_TEST_MESSAGE) { + message.message = *content::Details<std::string>(details).ptr(); + using SendMessage = content::Source<extensions::TestSendMessageFunction>; + message.function = SendMessage(source).ptr(); + using WillReply = content::Details<std::pair<std::string, bool*>>; + *WillReply(details).ptr()->second = true; // http:/crbug.com/668680 + CHECK(!test_complete_) << "LATE MESSAGE: " << message.message; } - messages_.push_back(entry); - base::RunLoop::QuitCurrentWhenIdleDeprecated(); + + messages_.push_back(message); + if (quit_closure_) { + std::move(quit_closure_).Run(); + } } private: + bool test_complete_ = false; + base::OnceClosure quit_closure_; base::circular_deque<Message> messages_; content::NotificationRegistrar registrar_; }; @@ -238,7 +238,6 @@ bool CreateRootDirectory(const Profile* profile) { if (root_initialized_) return true; - root_initialized_ = root_.Set(profile->GetPath().Append(name_)); return root_initialized_; } @@ -246,6 +245,19 @@ const std::string& name() const { return name_; } const base::FilePath& root_path() const { return root_.GetPath(); } + static base::FilePath GetTestDataFilePath(const std::string& file_name) { + // Get the path to file manager's test data directory. + base::FilePath source; + CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &source)); + auto test_data_path = source.AppendASCII("chrome") + .AppendASCII("test") + .AppendASCII("data") + .AppendASCII("chromeos") + .AppendASCII("file_manager"); + // Return full test data path to the given |file_name|. + return test_data_path.Append(base::FilePath::FromUTF8Unsafe(file_name)); + } + private: std::string name_; base::ScopedTempDir root_; @@ -254,16 +266,13 @@ } // anonymous namespace -// The local volume class for test. -// This class provides the operations for a test volume that simulates local -// drive. +// LocalTestVolume: test volume for a local drive. class LocalTestVolume : public TestVolume { public: explicit LocalTestVolume(const std::string& name) : TestVolume(name) {} ~LocalTestVolume() override {} - // Adds this volume to the file system as a local volume. Returns true on - // success. + // Adds this local volume. Returns true on success. virtual bool Mount(Profile* profile) = 0; void CreateEntry(const TestEntryInfo& entry) { @@ -274,7 +283,7 @@ switch (entry.type) { case FILE: { const base::FilePath source_path = - GetTestFilePath(entry.source_file_name); + TestVolume::GetTestDataFilePath(entry.source_file_name); ASSERT_TRUE(base::CopyFile(source_path, target_path)) << "Copy from " << source_path.value() << " to " << target_path.value() << " failed."; @@ -312,19 +321,21 @@ std::map<base::FilePath, const TestEntryInfo> entries_; }; +// DownloadsTestVolume: local test volume for the "Downloads" directory. class DownloadsTestVolume : public LocalTestVolume { public: DownloadsTestVolume() : LocalTestVolume("Downloads") {} ~DownloadsTestVolume() override {} bool Mount(Profile* profile) override { - return CreateRootDirectory(profile) && - VolumeManager::Get(profile) - ->RegisterDownloadsDirectoryForTesting(root_path()); + if (!CreateRootDirectory(profile)) + return false; + auto* volume = VolumeManager::Get(profile); + return volume->RegisterDownloadsDirectoryForTesting(root_path()); } }; -// Test volume for mimicing a specified type of volumes by a local folder. +// FakeTestVolume: local test volume with a specified volume and device type. class FakeTestVolume : public LocalTestVolume { public: FakeTestVolume(const std::string& name, @@ -371,9 +382,7 @@ const chromeos::DeviceType device_type_; }; -// The drive volume class for test. -// This class provides the operations for a test volume that simulates Google -// drive. +// DriveTestVolume: test volume for Google Drive. class DriveTestVolume : public TestVolume { public: DriveTestVolume() : TestVolume("drive"), integration_service_(NULL) {} @@ -443,8 +452,9 @@ std::string content_data; if (!source_file_name.empty()) { - base::FilePath source_file_path = GetTestFilePath(source_file_name); - ASSERT_TRUE(base::ReadFileToString(source_file_path, &content_data)); + base::FilePath source_path = + TestVolume::GetTestDataFilePath(source_file_name); + ASSERT_TRUE(base::ReadFileToString(source_path, &content_data)); } std::unique_ptr<google_apis::FileResource> entry; @@ -498,11 +508,9 @@ drive::DriveIntegrationService* integration_service_; }; -FileManagerBrowserTestBase::FileManagerBrowserTestBase() { -} +FileManagerBrowserTestBase::FileManagerBrowserTestBase() = default; -FileManagerBrowserTestBase::~FileManagerBrowserTestBase() { -} +FileManagerBrowserTestBase::~FileManagerBrowserTestBase() = default; void FileManagerBrowserTestBase::SetUp() { net::NetworkChangeNotifier::SetTestNotificationsOnly(true); @@ -528,6 +536,7 @@ ExtensionApiTest::SetUpInProcessBrowserTestFixture(); local_volume_.reset(new DownloadsTestVolume); + if (GetGuestModeParam() != IN_GUEST_MODE) { create_drive_integration_service_ = base::Bind(&FileManagerBrowserTestBase::CreateDriveIntegrationService, @@ -600,9 +609,9 @@ void FileManagerBrowserTestBase::RunTestMessageLoop() { // Handle the messages from JavaScript. // The while loop is break when the test is passed or failed. - FileManagerTestListener listener; + FileManagerTestMessageListener listener; while (true) { - FileManagerTestListener::Message entry = listener.GetNextMessage(); + FileManagerTestMessageListener::Message entry = listener.GetNextMessage(); if (entry.type == extensions::NOTIFICATION_EXTENSION_TEST_PASSED) { // Test succeed. break;
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h index f659922..584bc149 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h
@@ -44,24 +44,36 @@ void SetUpInProcessBrowserTestFixture() override; void SetUpOnMainThread() override; - // Loads our testing extension and sends it a string identifying the current - // test. - virtual void StartTest(); + // Load the test extension from GetTestManifestName(), and use it drive the + // testing of the actual FileManager component extension under test. + void StartTest(); - // Overriding point for test configurations. - virtual const char* GetTestManifestName() const = 0; + // Overrides for each FileManagerBrowserTest test extension type. virtual GuestMode GetGuestModeParam() const = 0; virtual const char* GetTestCaseNameParam() const = 0; + virtual const char* GetTestManifestName() const = 0; private: - // Installs an extension at the specified |path| by |manifest_name|. + // Called during setup if needed, to create a drive integration service for + // the given |profile|. Caller owns the return result. + drive::DriveIntegrationService* CreateDriveIntegrationService( + Profile* profile); + + // Installs the test extension with manifest |manifest_name|. The extension + // manifest_name file should reside in the specified |path| relative to the + // Chromium src directory. void InstallExtension(const base::FilePath& path, const char* manifest_name); - // TODO(noel): describe this function. + + // Runs the test: awaits chrome.test messsage commands and chrome.test PASS + // or FAIL messsages to process. |OnMessage| is used to handle the commands + // sent from the test extension. Returns on test PASS or FAIL. void RunTestMessageLoop(); - // TODO(noel): describe this function. - virtual void OnMessage(const std::string& name, - const base::DictionaryValue& value, - std::string* output); + + // Process test extension command |name|, with arguments |value|. Write the + // results to |output|. + void OnMessage(const std::string& name, + const base::DictionaryValue& value, + std::string* output); std::unique_ptr<LocalTestVolume> local_volume_; linked_ptr<DriveTestVolume> drive_volume_; @@ -69,8 +81,6 @@ std::unique_ptr<FakeTestVolume> usb_volume_; std::unique_ptr<FakeTestVolume> mtp_volume_; - drive::DriveIntegrationService* CreateDriveIntegrationService( - Profile* profile); drive::DriveIntegrationServiceFactory::FactoryCallback create_drive_integration_service_; std::unique_ptr<drive::DriveIntegrationServiceFactory::ScopedFactoryForTest>
diff --git a/chrome/browser/chromeos/first_run/drive_first_run_controller.cc b/chrome/browser/chromeos/first_run/drive_first_run_controller.cc index 374c4f5..39676a0 100644 --- a/chrome/browser/chromeos/first_run/drive_first_run_controller.cc +++ b/chrome/browser/chromeos/first_run/drive_first_run_controller.cc
@@ -178,7 +178,7 @@ content::WebContents::CreateParams create_params( profile_, content::SiteInstance::CreateForURL(profile_, url)); - web_contents_.reset(content::WebContents::Create(create_params)); + web_contents_ = content::WebContents::Create(create_params); web_contents_->SetDelegate(this); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_.get());
diff --git a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc index e916878..62c310d3 100644 --- a/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc +++ b/chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_impl.cc
@@ -38,7 +38,8 @@ void Start(const std::string& token); // GaiaAuthConsumer: - void OnOAuth2RevokeTokenCompleted() override; + void OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) override; private: GaiaAuthFetcher gaia_fetcher_; @@ -57,7 +58,8 @@ gaia_fetcher_.StartRevokeOAuth2Token(token); } -void TokenRevoker::OnOAuth2RevokeTokenCompleted() { +void TokenRevoker::OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) { base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); }
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc index 3033263..c4c7fee 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc
@@ -334,14 +334,14 @@ } static enterprise_management::PolicyFetchResponse BuildTestComponentPolicy() { - ComponentPolicyBuilder builder; + ComponentCloudPolicyBuilder builder; MakeTestComponentPolicyBuilder(&builder); return builder.policy(); } static enterprise_management::ExternalPolicyData BuildTestComponentPolicyPayload() { - ComponentPolicyBuilder builder; + ComponentCloudPolicyBuilder builder; MakeTestComponentPolicyBuilder(&builder); return builder.payload(); } @@ -354,7 +354,8 @@ session_manager_client()->set_device_policy(device_policy()->GetBlob()); } - static void MakeTestComponentPolicyBuilder(ComponentPolicyBuilder* builder) { + static void MakeTestComponentPolicyBuilder( + ComponentCloudPolicyBuilder* builder) { builder->policy_data().set_policy_type( dm_protocol::kChromeSigninExtensionPolicyType); builder->policy_data().set_settings_entity_id(kTestExtensionId);
diff --git a/chrome/browser/devtools/devtools_window.cc b/chrome/browser/devtools/devtools_window.cc index 8140cbd..f8e1976 100644 --- a/chrome/browser/devtools/devtools_window.cc +++ b/chrome/browser/devtools/devtools_window.cc
@@ -1011,8 +1011,8 @@ // Create WebContents with devtools. GURL url(GetDevToolsURL(profile, frontend_type, frontend_url, can_dock, panel, has_other_clients)); - std::unique_ptr<WebContents> main_web_contents( - WebContents::Create(WebContents::CreateParams(profile))); + std::unique_ptr<WebContents> main_web_contents = + WebContents::Create(WebContents::CreateParams(profile)); main_web_contents->GetController().LoadURL( DecorateFrontendURL(url), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string());
diff --git a/chrome/browser/dom_distiller/tab_utils.cc b/chrome/browser/dom_distiller/tab_utils.cc index 7a4e180..8df3776 100644 --- a/chrome/browser/dom_distiller/tab_utils.cc +++ b/chrome/browser/dom_distiller/tab_utils.cc
@@ -148,7 +148,7 @@ content::WebContents::CreateParams create_params( old_web_contents->GetBrowserContext()); std::unique_ptr<content::WebContents> new_web_contents = - base::WrapUnique(content::WebContents::Create(create_params)); + content::WebContents::Create(create_params); DCHECK(new_web_contents); // Copy all navigation state from the old WebContents to the new one.
diff --git a/chrome/browser/dom_distiller/tab_utils_browsertest.cc b/chrome/browser/dom_distiller/tab_utils_browsertest.cc index 457cc9f..aa2bdb96 100644 --- a/chrome/browser/dom_distiller/tab_utils_browsertest.cc +++ b/chrome/browser/dom_distiller/tab_utils_browsertest.cc
@@ -141,7 +141,7 @@ content::WebContents::CreateParams create_params( source_web_contents->GetBrowserContext()); std::unique_ptr<content::WebContents> destination_web_contents = - base::WrapUnique(content::WebContents::Create(create_params)); + content::WebContents::Create(create_params); content::WebContents* raw_destination_web_contents = destination_web_contents.get(); DCHECK(raw_destination_web_contents);
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 70650940..49c56fad 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -1759,9 +1759,8 @@ // Open a new tab for the download content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> new_tab = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(tab->GetBrowserContext()))); + std::unique_ptr<content::WebContents> new_tab = content::WebContents::Create( + content::WebContents::CreateParams(tab->GetBrowserContext())); content::WebContents* raw_new_tab = new_tab.get(); ASSERT_TRUE(raw_new_tab); ASSERT_TRUE(raw_new_tab->GetController().IsInitialNavigation());
diff --git a/chrome/browser/extensions/api/chrome_extensions_api_client.cc b/chrome/browser/extensions/api/chrome_extensions_api_client.cc index 4dc4225..c1a95cd 100644 --- a/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chrome/browser/extensions/api/chrome_extensions_api_client.cc
@@ -35,6 +35,7 @@ #include "chrome/browser/search/instant_io_context.h" #include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h" #include "chrome/browser/ui/webui/devtools_ui.h" +#include "chrome/common/webui_url_constants.h" #include "components/pdf/browser/pdf_web_contents_helper.h" #include "components/signin/core/browser/signin_header_helper.h" #include "content/public/browser/browser_context.h" @@ -110,16 +111,25 @@ const WebRequestInfo& request) const { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - bool is_protected_devtools_request = - request.render_process_id == -1 && - request.type != content::RESOURCE_TYPE_MAIN_FRAME && - DevToolsUI::IsFrontendResourceURL(request.url); + // Exclude main frame navigation requests. + bool is_browser_request = request.render_process_id == -1 && + request.type != content::RESOURCE_TYPE_MAIN_FRAME; - // Hide requests made by Devtools frontend and the NTP Instant renderer from - // extensions. - return is_protected_devtools_request || - InstantIOContext::IsInstantProcess(request.resource_context, - request.render_process_id); + // Hide requests made by the Devtools frontend. + bool is_sensitive_request = + is_browser_request && DevToolsUI::IsFrontendResourceURL(request.url); + + // Hide requests made by the browser on behalf of the NTP. + is_sensitive_request |= + (is_browser_request && + request.initiator == + url::Origin::Create(GURL(chrome::kChromeUINewTabURL))); + + // Hide requests made by the NTP Instant renderer. + is_sensitive_request |= InstantIOContext::IsInstantProcess( + request.resource_context, request.render_process_id); + + return is_sensitive_request; } AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate()
diff --git a/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc b/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc index 8e2738c0..45762a579 100644 --- a/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc +++ b/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
@@ -4,13 +4,26 @@ #include "chrome/browser/extensions/api/chrome_extensions_api_client.h" +#include "base/macros.h" +#include "chrome/common/webui_url_constants.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "extensions/browser/api/web_request/web_request_info.h" #include "google_apis/gaia/gaia_urls.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace extensions { -TEST(TestChromeExtensionsAPIClient, ShouldHideResponseHeader) { +class ChromeExtensionsAPIClientTest : public testing::Test { + public: + ChromeExtensionsAPIClientTest() = default; + + private: + content::TestBrowserThreadBundle thread_bundle_; + DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClientTest); +}; + +TEST_F(ChromeExtensionsAPIClientTest, ShouldHideResponseHeader) { ChromeExtensionsAPIClient client; EXPECT_TRUE(client.ShouldHideResponseHeader( GaiaUrls::GetInstance()->gaia_url(), "X-Chrome-ID-Consistency-Response")); @@ -22,4 +35,26 @@ GaiaUrls::GetInstance()->gaia_url(), "Google-Accounts-SignOut")); } +TEST_F(ChromeExtensionsAPIClientTest, ShouldHideBrowserNetworkRequest) { + ChromeExtensionsAPIClient client; + + // Requests made by the browser with chrome://newtab as its initiator should + // not be visible to extensions. + WebRequestInfo request; + request.url = GURL("https://example.com/script.js"); + request.initiator = url::Origin::Create(GURL(chrome::kChromeUINewTabURL)); + request.render_process_id = -1; + request.type = content::ResourceType::RESOURCE_TYPE_SCRIPT; + EXPECT_TRUE(client.ShouldHideBrowserNetworkRequest(request)); + + // Main frame requests should always be visible to extensions. + request.type = content::ResourceType::RESOURCE_TYPE_MAIN_FRAME; + EXPECT_FALSE(client.ShouldHideBrowserNetworkRequest(request)); + + // Similar requests made by the renderer should be visible to extensions. + request.type = content::ResourceType::RESOURCE_TYPE_SCRIPT; + request.render_process_id = 2; + EXPECT_FALSE(client.ShouldHideBrowserNetworkRequest(request)); +} + } // namespace extensions
diff --git a/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index 7f97643b..fa6bd5b 100644 --- a/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc
@@ -841,9 +841,8 @@ WebContentsWithoutTabAddedNotificationAtOnLoaded) { // Add a web contents to the tab strip in a way that doesn't trigger // NOTIFICATION_TAB_ADDED. - std::unique_ptr<content::WebContents> contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(profile()))); + std::unique_ptr<content::WebContents> contents = content::WebContents::Create( + content::WebContents::CreateParams(profile())); browser()->tab_strip_model()->AppendWebContents(std::move(contents), false); // The actual extension contents don't matter here -- we're just looking to
diff --git a/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc b/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc index 61a9d2e..f58748ea 100644 --- a/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc +++ b/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc
@@ -118,7 +118,7 @@ if (!optional_presentation_id.empty()) params.starting_sandbox_flags = blink::kPresentationReceiverSandboxFlags; - offscreen_tab_web_contents_.reset(WebContents::Create(params)); + offscreen_tab_web_contents_ = WebContents::Create(params); offscreen_tab_web_contents_->SetDelegate(this); WebContentsObserver::Observe(offscreen_tab_web_contents_.get());
diff --git a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc index 82ffe51c..e3abe7e 100644 --- a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
@@ -126,7 +126,7 @@ // keyboard gets the correct state of the hotrod keyboard through // chrome.virtualKeyboardPrivate.getKeyboardConfig. if (keyboard::IsKeyboardEnabled()) - ash::Shell::Get()->CreateKeyboard(); + ash::Shell::Get()->ReloadKeyboard(); } bool ChromeVirtualKeyboardDelegate::LockKeyboard(bool state) { @@ -338,7 +338,7 @@ // chrome.virtualKeyboardPrivate.getKeyboardConfig. // TODO(oka): Extension should reload on it's own by receiving event if (keyboard::IsKeyboardEnabled()) - ash::Shell::Get()->CreateKeyboard(); + ash::Shell::Get()->ReloadKeyboard(); } return update; }
diff --git a/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chrome/browser/extensions/api/web_request/web_request_apitest.cc index 639d8ff..a55b8f38 100644 --- a/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_apitest.cc
@@ -3,13 +3,16 @@ // found in the LICENSE file. #include <memory> +#include <utility> #include "base/command_line.h" +#include "base/feature_list.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" +#include "base/synchronization/lock.h" #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "build/build_config.h" @@ -25,6 +28,9 @@ #include "chrome/browser/net/profile_network_context_service.h" #include "chrome/browser/net/profile_network_context_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search/one_google_bar/one_google_bar_fetcher.h" +#include "chrome/browser/search/one_google_bar/one_google_bar_service.h" +#include "chrome/browser/search/one_google_bar/one_google_bar_service_factory.h" #include "chrome/browser/search/search.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/browser.h" @@ -32,11 +38,13 @@ #include "chrome/browser/ui/login/login_handler.h" #include "chrome/browser/ui/search/local_ntp_test_utils.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/search_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/login/scoped_test_public_session_login_state.h" +#include "components/google/core/browser/google_switches.h" #include "components/prefs/pref_service.h" #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_config_pref_names.h" @@ -1357,12 +1365,15 @@ NTPRendererRequestsHidden) { // Loads an extension which tries to intercept requests to // "fake_ntp_script.js", which will be loaded as part of the NTP renderer. - ExtensionTestMessageListener listener("ready", false /*will_reply*/); + ExtensionTestMessageListener listener("ready", true /*will_reply*/); const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("extension")); ASSERT_TRUE(extension); EXPECT_TRUE(listener.WaitUntilSatisfied()); + // Have the extension listen for requests to |fake_ntp_script.js|. + listener.Reply(https_test_server()->GetURL("/fake_ntp_script.js").spec()); + // Returns true if the given extension was able to intercept the request to // "fake_ntp_script.js". auto was_script_request_intercepted = @@ -1404,6 +1415,139 @@ EXPECT_TRUE(was_script_request_intercepted(extension->id())); } +// Test fixture testing that requests made for the OneGoogleBar on behalf of +// the local NTP can't be intercepted by extensions. +class LocalNTPInterceptionWebRequestAPITest + : public ExtensionApiTest, + public OneGoogleBarServiceObserver { + public: + LocalNTPInterceptionWebRequestAPITest() + : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} + + // ExtensionApiTest override: + void SetUp() override { + https_test_server_.RegisterRequestMonitor(base::BindRepeating( + &LocalNTPInterceptionWebRequestAPITest::MonitorRequest, + base::Unretained(this))); + ASSERT_TRUE(https_test_server_.InitializeAndListen()); + ExtensionApiTest::SetUp(); + feature_list_.InitWithFeatures( + {::features::kUseGoogleLocalNtp, ::features::kOneGoogleBarOnLocalNtp}, + {}); + } + void SetUpCommandLine(base::CommandLine* command_line) override { + ExtensionApiTest::SetUpCommandLine(command_line); + command_line->AppendSwitchASCII(switches::kGoogleBaseURL, + https_test_server_.base_url().spec()); + } + void SetUpOnMainThread() override { + ExtensionApiTest::SetUpOnMainThread(); + + https_test_server_.StartAcceptingConnections(); + + one_google_bar_url_ = one_google_bar_service() + ->fetcher_for_testing() + ->GetFetchURLForTesting(); + + // Can't declare |runloop_| as a data member on the stack since it needs to + // be be constructed from a single-threaded context. + runloop_ = std::make_unique<base::RunLoop>(); + one_google_bar_service()->AddObserver(this); + } + + // OneGoogleBarServiceObserver overrides: + void OnOneGoogleBarDataUpdated() override { runloop_->Quit(); } + void OnOneGoogleBarServiceShuttingDown() override { + one_google_bar_service()->RemoveObserver(this); + } + + GURL one_google_bar_url() const { return one_google_bar_url_; } + + // Waits for OneGoogleBar data to be updated. Should only be used once. + void WaitForOneGoogleBarDataUpdate() { runloop_->Run(); } + + bool GetAndResetOneGoogleBarRequestSeen() { + base::AutoLock lock(lock_); + bool result = one_google_bar_request_seen_; + one_google_bar_request_seen_ = false; + return result; + } + + private: + OneGoogleBarService* one_google_bar_service() { + return OneGoogleBarServiceFactory::GetForProfile(profile()); + } + + void MonitorRequest(const net::test_server::HttpRequest& request) { + if (request.GetURL() == one_google_bar_url_) { + base::AutoLock lock(lock_); + one_google_bar_request_seen_ = true; + } + } + + net::EmbeddedTestServer https_test_server_; + base::test::ScopedFeatureList feature_list_; + std::unique_ptr<base::RunLoop> runloop_; + + // Initialized on the UI thread in SetUpOnMainThread. Read on UI and Embedded + // Test Server IO thread thereafter. + GURL one_google_bar_url_; + + // Accessed on multiple threads- UI and Embedded Test Server IO thread. Access + // requires acquiring |lock_|. + bool one_google_bar_request_seen_ = false; + + base::Lock lock_; + + DISALLOW_COPY_AND_ASSIGN(LocalNTPInterceptionWebRequestAPITest); +}; + +IN_PROC_BROWSER_TEST_F(LocalNTPInterceptionWebRequestAPITest, + OneGoogleBarRequestsHidden) { + // Loads an extension which tries to intercept requests to the OneGoogleBar. + ExtensionTestMessageListener listener("ready", true /*will_reply*/); + const Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("webrequest") + .AppendASCII("ntp_request_interception") + .AppendASCII("extension")); + ASSERT_TRUE(extension); + EXPECT_TRUE(listener.WaitUntilSatisfied()); + + // Have the extension listen for requests to |one_google_bar_url()|. + listener.Reply(one_google_bar_url().spec()); + + // Returns true if the given extension was able to intercept the request to + // |one_google_bar_url()|. + auto was_script_request_intercepted = + [this](const std::string& extension_id) { + const std::string result = ExecuteScriptInBackgroundPage( + extension_id, "getAndResetRequestIntercepted();"); + EXPECT_TRUE(result == "true" || result == "false") + << "Unexpected result " << result; + return result == "true"; + }; + + WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + ASSERT_FALSE(GetAndResetOneGoogleBarRequestSeen()); + ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); + ASSERT_TRUE(search::IsInstantNTP(web_contents)); + ASSERT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), + web_contents->GetController().GetVisibleEntry()->GetURL()); + WaitForOneGoogleBarDataUpdate(); + ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen()); + + // Ensure that the extension wasn't able to intercept the request. + EXPECT_FALSE(was_script_request_intercepted(extension->id())); + + // A normal request to |one_google_bar_url()| (i.e. not made by + // OneGoogleBarFetcher) should be intercepted by extensions. + ui_test_utils::NavigateToURL(browser(), one_google_bar_url()); + EXPECT_TRUE(was_script_request_intercepted(extension->id())); + ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen()); +} + // Ensure that devtools frontend requests are hidden from the webRequest API. IN_PROC_BROWSER_TEST_F(DevToolsFrontendInWebRequestApiTest, HiddenRequests) { // Test expectations differ with the Network Service because of the way
diff --git a/chrome/browser/extensions/bookmark_app_helper.cc b/chrome/browser/extensions/bookmark_app_helper.cc index 63f43cb..2e4a39a 100644 --- a/chrome/browser/extensions/bookmark_app_helper.cc +++ b/chrome/browser/extensions/bookmark_app_helper.cc
@@ -251,8 +251,8 @@ // contents for all pending synced bookmark apps. This will avoid // pathological cases where n renderers for n bookmark apps are spun up on // first sign-in to a new machine. - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(service_->profile()))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(service_->profile())); Observe(web_contents_.get()); // Load about:blank so that the process actually starts.
diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc index d80d473..b2aee377 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc
@@ -582,14 +582,6 @@ if (!extension) return; - if (extension->id() == extension_misc::kBookmarkManagerId && - ui::PageTransitionCoreTypeIs(*transition, ui::PAGE_TRANSITION_LINK)) { - // Link clicks in the bookmark manager count as bookmarks and as browser- - // initiated navigations. - *transition = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - *is_renderer_initiated = false; - } - // Hide the referrer for extension pages. We don't want sites to see a // referrer of chrome-extension://<...>. if (extension->is_extension())
diff --git a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc index 15ee5b3..9bd55fd 100644 --- a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc +++ b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc
@@ -59,7 +59,6 @@ bool IsComponentExtensionWhitelisted(int manifest_resource_id) { switch (manifest_resource_id) { // Please keep the list in alphabetical order. - case IDR_BOOKMARKS_MANIFEST: #if BUILDFLAG(ENABLE_APP_LIST) case IDR_CHROME_APP_MANIFEST: #endif
diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index a6de22b..c8cbcf2 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/pdf/pdf_extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h" #include "chrome/common/buildflags.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths.h" @@ -463,23 +462,11 @@ // Skip all other extensions that require user session presence. if (!skip_session_components) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(chromeos::switches::kGuestSession) && - !MdBookmarksUI::IsEnabled()) { - Add(IDR_BOOKMARKS_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("bookmark_manager"))); - } - Add(IDR_CROSH_BUILTIN_MANIFEST, base::FilePath(FILE_PATH_LITERAL( "/usr/share/chromeos-assets/crosh_builtin"))); } #else // defined(OS_CHROMEOS) DCHECK(!skip_session_components); - if (!MdBookmarksUI::IsEnabled()) { - Add(IDR_BOOKMARKS_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("bookmark_manager"))); - } #if BUILDFLAG(ENABLE_PRINTING) // Cloud Print component app. Not required on Chrome OS. Add(IDR_CLOUDPRINT_MANIFEST,
diff --git a/chrome/browser/extensions/extension_url_rewrite_browsertest.cc b/chrome/browser/extensions/extension_url_rewrite_browsertest.cc index 1eedce7..08417d3a 100644 --- a/chrome/browser/extensions/extension_url_rewrite_browsertest.cc +++ b/chrome/browser/extensions/extension_url_rewrite_browsertest.cc
@@ -102,32 +102,6 @@ extensions::kExtensionScheme)); } -IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURL) { - if (MdBookmarksUI::IsEnabled()) - return; - - // Navigate to chrome://bookmarks and check that the location bar URL is - // what was entered and the internal URL uses the chrome-extension:// scheme. - const GURL bookmarks_url(chrome::kChromeUIBookmarksURL); - ui_test_utils::NavigateToURL(browser(), bookmarks_url); - // The default chrome://bookmarks implementation will append /#1 to the URL - // once loaded. Use |GetWithEmptyPath()| to avoid flakyness. - EXPECT_EQ(bookmarks_url, GetLocationBarTextAsURL().GetWithEmptyPath()); - NavigationEntry* navigation = GetNavigationEntry(); - EXPECT_EQ(bookmarks_url, navigation->GetVirtualURL().GetWithEmptyPath()); - EXPECT_TRUE(navigation->GetURL().SchemeIs(extensions::kExtensionScheme)); -} - -IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLWithRef) { - if (MdBookmarksUI::IsEnabled()) - return; - - // Navigate to chrome://bookmarks/#1 and check that the location bar URL is - // what was entered and the internal URL uses the chrome-extension:// scheme. - GURL url_with_ref(chrome::kChromeUIBookmarksURL + std::string("#1")); - TestExtensionURLOverride(url_with_ref); -} - IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLOverride) { // Load an extension that overrides chrome://bookmarks. ASSERT_TRUE(LoadExtension(GetTestExtensionPath("bookmarks")));
diff --git a/chrome/browser/extensions/tab_helper.cc b/chrome/browser/extensions/tab_helper.cc index 2b58f6b..c925a5b 100644 --- a/chrome/browser/extensions/tab_helper.cc +++ b/chrome/browser/extensions/tab_helper.cc
@@ -199,7 +199,7 @@ } bool TabHelper::CanCreateBookmarkApp() const { - return !profile_->IsGuestSession() && + return !profile_->IsGuestSession() && !profile_->IsOffTheRecord() && !profile_->IsSystemProfile() && IsValidBookmarkAppUrl(web_contents()->GetURL()); }
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 4e4d217..dcad8624 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -460,12 +460,6 @@ "might contain generation fallbacks or 'Show all saved passwords' " "fallback."; -const char kEnableMaterialDesignBookmarksName[] = - "Enable Material Design bookmarks"; -const char kEnableMaterialDesignBookmarksDescription[] = - "If enabled, the chrome://bookmarks/ URL loads the Material Design " - "bookmarks page."; - const char kEnableMaterialDesignExtensionsName[] = "Enable Material Design extensions"; const char kEnableMaterialDesignExtensionsDescription[] =
diff --git a/chrome/browser/media/encrypted_media_browsertest.cc b/chrome/browser/media/encrypted_media_browsertest.cc index a9acadd..673a21c 100644 --- a/chrome/browser/media/encrypted_media_browsertest.cc +++ b/chrome/browser/media/encrypted_media_browsertest.cc
@@ -81,13 +81,13 @@ const char kWebMVorbisAudioVp8Video[] = "video/webm; codecs=\"vorbis, vp8\""; const char kWebMOpusAudioVp9Video[] = "video/webm; codecs=\"opus, vp9\""; const char kWebMVp9VideoOnly[] = "video/webm; codecs=\"vp9\""; +const char kMp4Vp9VideoOnly[] = + "video/mp4; codecs=\"vp09.00.10.08.01.02.02.02.00\""; #if BUILDFLAG(ENABLE_LIBRARY_CDMS) const char kWebMVp8VideoOnly[] = "video/webm; codecs=\"vp8\""; #endif #if BUILDFLAG(USE_PROPRIETARY_CODECS) const char kMp4Avc1VideoOnly[] = "video/mp4; codecs=\"avc1.64001E\""; -const char kMp4Vp9VideoOnly[] = - "video/mp4; codecs=\"vp09.00.10.08.01.02.02.02.00\""; #endif // BUILDFLAG(USE_PROPRIETARY_CODECS) // Sessions to load. @@ -580,6 +580,15 @@ TestMultiplePlayback("bear-320x240-av_enc-av.webm", kWebMVorbisAudioVp8Video); } +IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_VideoOnly_MP4_VP9) { + // MP4 without MSE is not support yet, http://crbug.com/170793. + if (CurrentSourceType() != SrcType::MSE) { + DVLOG(0) << "Skipping test; Can only play MP4 encrypted streams by MSE."; + return; + } + TestSimplePlayback("bear-320x240-v_frag-vp9-cenc.mp4", kMp4Vp9VideoOnly); +} + IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, InvalidResponseKeyError) { RunInvalidResponseTest(); } @@ -648,15 +657,6 @@ TestSimplePlayback("bear-640x360-v_frag-cenc-mdat.mp4", kMp4Avc1VideoOnly); } -IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_VideoOnly_MP4_VP9) { - // MP4 without MSE is not support yet, http://crbug.com/170793. - if (CurrentSourceType() != SrcType::MSE) { - DVLOG(0) << "Skipping test; Can only play MP4 encrypted streams by MSE."; - return; - } - TestSimplePlayback("bear-320x240-v_frag-vp9-cenc.mp4", kMp4Vp9VideoOnly); -} - IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_EncryptedVideo_MP4_ClearAudio_WEBM) { TestDifferentContainers(EncryptedContainer::ENCRYPTED_MP4, @@ -755,14 +755,14 @@ kExternalClearKeyDecryptOnlyKeySystem, SrcType::MSE); } -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - IN_PROC_BROWSER_TEST_P(ECKEncryptedMediaTest, DecryptOnly_VideoOnly_MP4_VP9) { RunSimpleEncryptedMediaTest( "bear-320x240-v_frag-vp9-cenc.mp4", kMp4Vp9VideoOnly, kExternalClearKeyDecryptOnlyKeySystem, SrcType::MSE); } +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + // Encryption Scheme tests. ClearKey key system is covered in // content/browser/media/encrypted_media_browsertest.cc. IN_PROC_BROWSER_TEST_P(ECKEncryptedMediaTest, Playback_Encryption_CENC) {
diff --git a/chrome/browser/media/encrypted_media_supported_types_browsertest.cc b/chrome/browser/media/encrypted_media_supported_types_browsertest.cc index a06c58b..dada6598 100644 --- a/chrome/browser/media/encrypted_media_supported_types_browsertest.cc +++ b/chrome/browser/media/encrypted_media_supported_types_browsertest.cc
@@ -324,8 +324,7 @@ // For ClearKey, nothing additional is required. class EncryptedMediaSupportedTypesClearKeyTest - : public EncryptedMediaSupportedTypesTest { -}; + : public EncryptedMediaSupportedTypesTest {}; // For ExternalClearKey tests, ensure that the ClearKey adapter is loaded. class EncryptedMediaSupportedTypesExternalClearKeyTest @@ -506,13 +505,13 @@ // Valid video types. EXPECT_PROPRIETARY( IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, video_mp4_codecs())); - EXPECT_PROPRIETARY(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, - video_common_codecs())); - EXPECT_PROPRIETARY(IsSupportedByKeySystem( + EXPECT_SUCCESS(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, + video_common_codecs())); + EXPECT_SUCCESS(IsSupportedByKeySystem( kClearKey, kVideoMP4MimeType, clear_key_exclusive_video_common_codecs())); - // High 10-bit Profile is supported when using ClearKey if - // it is supported for clear content on this platform. +// High 10-bit Profile is supported when using ClearKey if it is supported for +// clear content on this platform. #if BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS) EXPECT_PROPRIETARY(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, video_mp4_hi10p_codecs())); @@ -684,10 +683,8 @@ // Valid video types. EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( kExternalClearKey, kVideoMP4MimeType, video_mp4_codecs())); - EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( - kExternalClearKey, kVideoMP4MimeType, video_common_codecs())); - EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( - kClearKey, kVideoMP4MimeType, clear_key_exclusive_video_common_codecs())); + EXPECT_ECK(IsSupportedByKeySystem(kExternalClearKey, kVideoMP4MimeType, + video_common_codecs())); // High 10-bit Profile is not supported when using ExternalClearKey. EXPECT_UNSUPPORTED(IsSupportedByKeySystem( @@ -698,6 +695,9 @@ kExternalClearKey, kVideoMP4MimeType, audio_mp4_codecs())); // Invalid or non-MP4 codecs. + EXPECT_UNSUPPORTED( + IsSupportedByKeySystem(kExternalClearKey, kVideoMP4MimeType, + clear_key_exclusive_video_common_codecs())); EXPECT_UNSUPPORTED(IsSupportedByKeySystem( kExternalClearKey, kVideoMP4MimeType, invalid_codecs())); EXPECT_UNSUPPORTED(IsSupportedByKeySystem( @@ -868,8 +868,8 @@ // Valid video types. EXPECT_WV_PROPRIETARY( IsSupportedByKeySystem(kWidevine, kVideoMP4MimeType, video_mp4_codecs())); - EXPECT_WV_PROPRIETARY(IsSupportedByKeySystem(kWidevine, kVideoMP4MimeType, - video_common_codecs())); + EXPECT_WV_SUCCESS(IsSupportedByKeySystem(kWidevine, kVideoMP4MimeType, + video_common_codecs())); // High 10-bit Profile is not supported when using Widevine. EXPECT_UNSUPPORTED(IsSupportedByKeySystem(kWidevine, kVideoMP4MimeType,
diff --git a/chrome/browser/net/websocket_browsertest.cc b/chrome/browser/net/websocket_browsertest.cc index 7726621..8797460 100644 --- a/chrome/browser/net/websocket_browsertest.cc +++ b/chrome/browser/net/websocket_browsertest.cc
@@ -186,8 +186,8 @@ content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); std::unique_ptr<content::WebContents> new_tab = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(tab->GetBrowserContext()))); + content::WebContents::Create( + content::WebContents::CreateParams(tab->GetBrowserContext())); content::WebContents* raw_new_tab = new_tab.get(); browser()->tab_strip_model()->AppendWebContents(std::move(new_tab), true); ASSERT_EQ(raw_new_tab, browser()->tab_strip_model()->GetWebContentsAt(1));
diff --git a/chrome/browser/offline_pages/offline_page_request_job_unittest.cc b/chrome/browser/offline_pages/offline_page_request_job_unittest.cc index 256b0c77..3900d635 100644 --- a/chrome/browser/offline_pages/offline_page_request_job_unittest.cc +++ b/chrome/browser/offline_pages/offline_page_request_job_unittest.cc
@@ -545,8 +545,8 @@ profile_ = profile_manager_.CreateTestingProfile("Profile 1"); // Create a test web contents. - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile_))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile_)); OfflinePageTabHelper::CreateForWebContents(web_contents_.get()); offline_page_tab_helper_ = OfflinePageTabHelper::FromWebContents(web_contents_.get());
diff --git a/chrome/browser/offline_pages/offline_page_utils_unittest.cc b/chrome/browser/offline_pages/offline_page_utils_unittest.cc index c3f7a3f4..d8b91ace 100644 --- a/chrome/browser/offline_pages/offline_page_utils_unittest.cc +++ b/chrome/browser/offline_pages/offline_page_utils_unittest.cc
@@ -138,8 +138,8 @@ void OfflinePageUtilsTest::SetUp() { // Create a test web contents. - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile()))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile())); OfflinePageTabHelper::CreateForWebContents(web_contents_.get()); // Set up the factory for testing.
diff --git a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.cc index 74b24a5..8914989 100644 --- a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.cc
@@ -32,6 +32,17 @@ break; \ } +// Finds the RenderFrameHost for the handle, possibly using the FrameTreeNode +// ID directly if the the handle has not been committed. +// NOTE: Unsafe with respect to security privileges. +content::RenderFrameHost* FindFrameMaybeUnsafe( + content::NavigationHandle* handle) { + return handle->HasCommitted() + ? handle->GetRenderFrameHost() + : handle->GetWebContents()->UnsafeFindFrameByFrameTreeNodeId( + handle->GetFrameTreeNodeId()); +} + bool DetectGoogleAd(content::NavigationHandle* navigation_handle) { // Because sub-resource filtering isn't always enabled, and doesn't work // well in monitoring mode (no CSS enforcement), it's difficult to identify @@ -44,12 +55,9 @@ // ID. It returns the committed frame host or the initial frame host for the // frame if no committed host exists. Using a previous host is fine because // once a frame has an ad we always consider it to have an ad. - // We use the unsafe method of FindFrameByFrameTreeNodeId because we're not - // concerned with which process the frame lives on (we're just measuring - // bytes and not granting security priveleges). + // NOTE: Just used for measuring bytes, does not grant security privileges. content::RenderFrameHost* current_frame_host = - navigation_handle->GetWebContents()->UnsafeFindFrameByFrameTreeNodeId( - navigation_handle->GetFrameTreeNodeId()); + FindFrameMaybeUnsafe(navigation_handle); if (current_frame_host) { const std::string& frame_name = current_frame_host->GetFrameName(); if (base::StartsWith(frame_name, "google_ads_iframe", @@ -78,12 +86,12 @@ AdsPageLoadMetricsObserver::AdFrameData::AdFrameData( FrameTreeNodeId frame_tree_node_id, AdTypes ad_types, - bool cross_origin) + AdOriginStatus origin_status) : frame_bytes(0u), frame_bytes_uncached(0u), frame_tree_node_id(frame_tree_node_id), ad_types(ad_types), - cross_origin(cross_origin) {} + origin_status(origin_status) {} // static std::unique_ptr<AdsPageLoadMetricsObserver> @@ -172,17 +180,22 @@ AdFrameData* ad_data = parent_id_and_data->second; + // This frame is not nested within an ad frame but is itself an ad. if (!ad_data && ad_types.any()) { - // This frame is not nested within an ad frame but is itself an ad. - // TODO(csharrison): Replace/remove url::Origin::Create, provide direct - // access through the navigation_handle. - bool cross_origin = !navigation_handle->GetWebContents() - ->GetMainFrame() - ->GetLastCommittedOrigin() - .IsSameOriginWith(url::Origin::Create( - navigation_handle->GetURL())); + AdOriginStatus origin_status = AdOriginStatus::kUnknown; + // NOTE: frame look-up only used for determining cross-origin status, not + // granting security permissions. + content::RenderFrameHost* ad_host = FindFrameMaybeUnsafe(navigation_handle); + if (ad_host) { + content::RenderFrameHost* main_host = + navigation_handle->GetWebContents()->GetMainFrame(); + origin_status = main_host->GetLastCommittedOrigin().IsSameOriginWith( + ad_host->GetLastCommittedOrigin()) + ? AdOriginStatus::kSame + : AdOriginStatus::kCross; + } ad_frames_data_storage_.emplace_back(frame_tree_node_id, ad_types, - cross_origin); + origin_status); ad_data = &ad_frames_data_storage_.back(); } @@ -337,12 +350,13 @@ "Bytes.AdFrames.PerFrame.PercentNetwork", UMA_HISTOGRAM_PERCENTAGE, ad_type, ad_frame_data.frame_bytes_uncached * 100 / ad_frame_data.frame_bytes); - ADS_HISTOGRAM("FrameCounts.AdFrames.PerFrame.CrossOrigin", - UMA_HISTOGRAM_BOOLEAN, ad_type, ad_frame_data.cross_origin); + ADS_HISTOGRAM("FrameCounts.AdFrames.PerFrame.OriginStatus", + UMA_HISTOGRAM_ENUMERATION, ad_type, + ad_frame_data.origin_status); } // TODO(ericrobinson): Consider renaming this to match - // 'FrameCounts.AdFrames.PerFrame.CrossOrigin'. + // 'FrameCounts.AdFrames.PerFrame.OriginStatus'. ADS_HISTOGRAM("FrameCounts.AnyParentFrame.AdFrames", UMA_HISTOGRAM_COUNTS_1000, ad_type, non_zero_ad_frames);
diff --git a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.h b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.h index ae80dec..7563c7cb2 100644 --- a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.h
@@ -33,6 +33,16 @@ AD_TYPE_MAX = AD_TYPE_ALL }; + // The origin of the ad relative to the main frame's origin. + // Note: Logged to UMA, keep in sync with CrossOriginAdStatus in enums.xml. + // Add new entries to the end, and do not renumber. + enum class AdOriginStatus { + kUnknown = 0, + kSame = 1, + kCross = 2, + kMaxValue = kCross, + }; + using AdTypes = std::bitset<AD_TYPE_MAX>; // Returns a new AdsPageLoadMetricObserver. If the feature is disabled it @@ -62,12 +72,12 @@ struct AdFrameData { AdFrameData(FrameTreeNodeId frame_tree_node_id, AdTypes ad_types, - bool cross_origin); + AdOriginStatus origin_status); size_t frame_bytes; size_t frame_bytes_uncached; const FrameTreeNodeId frame_tree_node_id; AdTypes ad_types; - bool cross_origin; + AdOriginStatus origin_status; }; // subresource_filter::SubresourceFilterObserver:
diff --git a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_browsertest.cc index 991dcb70..d6c7a71 100644 --- a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer.h" #include "chrome/browser/subresource_filter/subresource_filter_browser_test_harness.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/in_process_browser_test.h" @@ -21,6 +22,11 @@ #include "url/gurl.h" #include "url/url_constants.h" +namespace { +const char kCrossOriginHistogramId[] = + "PageLoad.Clients.Ads.Google.FrameCounts.AdFrames.PerFrame.OriginStatus"; +} // namespace + class AdsPageLoadMetricsObserverBrowserTest : public subresource_filter::SubresourceFilterBrowserTest { public: @@ -36,6 +42,63 @@ DISALLOW_COPY_AND_ASSIGN(AdsPageLoadMetricsObserverBrowserTest); }; +// Test that an embedded ad is same origin. +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + OriginStatusMetricEmbedded) { + base::HistogramTester histogram_tester; + ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL("/ads_observer/srcdoc_embedded_ad.html")); + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + histogram_tester.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kSame, 1); +} + +// Test that an empty embedded ad isn't reported at all. +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + OriginStatusMetricEmbeddedEmpty) { + base::HistogramTester histogram_tester; + ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL( + "/ads_observer/srcdoc_embedded_ad_empty.html")); + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + histogram_tester.ExpectTotalCount(kCrossOriginHistogramId, 0); +} + +// Test that an ad with the same origin as the main page is same origin. +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + OriginStatusMetricSame) { + base::HistogramTester histogram_tester; + ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL("/ads_observer/same_origin_ad.html")); + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + histogram_tester.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kSame, 1); +} + +// Test that an ad with a different origin as the main page is cross origin. +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + OriginStatusMetricCross) { + // Note: Cannot navigate cross-origin without dynamically generating the URL. + base::HistogramTester histogram_tester; + ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/iframe_blank.html")); + // Note that the initial iframe is not an ad, so the metric doesn't observe + // it initially as same origin. However, on re-navigating to a cross + // origin site that has an ad at its origin, the ad on that page is cross + // origin from the original page. + NavigateIframeToURL(web_contents(), "test", + embedded_test_server()->GetURL( + "a.com", "/ads_observer/same_origin_ad.html")); + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + histogram_tester.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kCross, 1); +} + // Test that a subframe that aborts (due to doc.write) doesn't cause a crash // if it continues to load resources. IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
diff --git a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_unittest.cc index 0b2ae380..1ce71fb 100644 --- a/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ads_page_load_metrics_observer_unittest.cc
@@ -460,54 +460,61 @@ // Test that the cross-origin ad subframe navigation metric works as it's // supposed to, triggering a false addition with each ad that's in the same // origin as the main page, and a true when when the ad has a separate origin. -TEST_F(AdsPageLoadMetricsObserverTest, CrossOriginAdsMetrics) { - const char cross_origin_histogram_id[] = - "PageLoad.Clients.Ads.Google.FrameCounts.AdFrames.PerFrame.CrossOrigin"; - const base::HistogramTester& histograms = histogram_tester(); +TEST_F(AdsPageLoadMetricsObserverTest, AdsOriginStatusMetrics) { + const char kCrossOriginHistogramId[] = + "PageLoad.Clients.Ads.Google.FrameCounts.AdFrames.PerFrame.OriginStatus"; // Test that when the main frame origin is different from a direct ad // subframe it is correctly identified as cross-origin, but do not count // indirect ad subframes. - RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); - RenderFrameHost* ad_sub_frame = - CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame); - LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); - LoadResource(ad_sub_frame, ResourceCached::NOT_CACHED, 10); - LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, ad_sub_frame), - ResourceCached::NOT_CACHED, 10); - // Trigger histograms, set up for next test with different ad origin. - main_frame = NavigateFrame(kNonAdUrl, main_frame); - // Check the histogram values. - histograms.ExpectTotalCount(cross_origin_histogram_id, 1); - histograms.ExpectBucketCount(cross_origin_histogram_id, true, 1); - histograms.ExpectBucketCount(cross_origin_histogram_id, false, 0); + { + base::HistogramTester histograms; + RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); + RenderFrameHost* ad_sub_frame = + CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame); + LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); + LoadResource(ad_sub_frame, ResourceCached::NOT_CACHED, 10); + LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, ad_sub_frame), + ResourceCached::NOT_CACHED, 10); + // Trigger histograms by navigating away, then test them. + NavigateFrame(kAdUrl, main_frame); + histograms.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kCross, 1); + } // Add a non-ad subframe and an ad subframe and make sure the total count // only adjusts by one. - LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); - LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame), - ResourceCached::NOT_CACHED, 10); - LoadResource(CreateAndNavigateSubFrame(kNonAdUrl, kNonAdName, main_frame), - ResourceCached::NOT_CACHED, 10); - // Trigger histograms, set up for next test with same origin as ad. - main_frame = NavigateFrame(kNonAdUrlSameOrigin, main_frame); - // Check the histogram values. - histograms.ExpectTotalCount(cross_origin_histogram_id, 2); - histograms.ExpectBucketCount(cross_origin_histogram_id, true, 2); - histograms.ExpectBucketCount(cross_origin_histogram_id, false, 0); + { + base::HistogramTester histograms; + RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); + LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); + LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame), + ResourceCached::NOT_CACHED, 10); + LoadResource(CreateAndNavigateSubFrame(kNonAdUrl, kNonAdName, main_frame), + ResourceCached::NOT_CACHED, 10); + // Trigger histograms by navigating away, then test them. + NavigateFrame(kAdUrl, main_frame); + histograms.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kCross, 1); + } // Add an ad subframe in the same origin as the parent frame and make sure it // gets identified as non-cross-origin. Note: top-level navigations are never // considered to be ads. - LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); - LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame), - ResourceCached::NOT_CACHED, 10); - // Trigger histograms. - main_frame = NavigateFrame(kNonAdUrl, main_frame); - // Check the histogram values. - histograms.ExpectTotalCount(cross_origin_histogram_id, 3); - histograms.ExpectBucketCount(cross_origin_histogram_id, true, 2); - histograms.ExpectBucketCount(cross_origin_histogram_id, false, 1); + { + base::HistogramTester histograms; + RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrlSameOrigin); + LoadResource(main_frame, ResourceCached::NOT_CACHED, 10); + LoadResource(CreateAndNavigateSubFrame(kAdUrl, kNonAdName, main_frame), + ResourceCached::NOT_CACHED, 10); + // Trigger histograms by navigating away, then test them. + NavigateFrame(kAdUrl, main_frame); + histograms.ExpectUniqueSample( + kCrossOriginHistogramId, + AdsPageLoadMetricsObserver::AdOriginStatus::kSame, 1); + } } TEST_F(AdsPageLoadMetricsObserverTest, PageWithAdFrameThatRenavigates) {
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index 2b3780b..09ae1540 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -606,9 +606,9 @@ // gracefully. TEST_F(ChromePasswordManagerClientTest, BindCredentialManager_MissingInstance) { // Create a WebContent without tab helpers. - std::unique_ptr<content::WebContents> web_contents( + std::unique_ptr<content::WebContents> web_contents = content::WebContents::Create( - content::WebContents::CreateParams(profile()))); + content::WebContents::CreateParams(profile())); // In particular, this WebContent should not have the // ChromePasswordManagerClient. ASSERT_FALSE(
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index b1e0f0e..685f3b6e 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -3363,8 +3363,8 @@ IN_PROC_BROWSER_TEST_P(PasswordManagerBrowserTestWithViewsFeature, ReattachWebContents) { - auto detached_web_contents = base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(WebContents()->GetBrowserContext()))); + auto detached_web_contents = content::WebContents::Create( + content::WebContents::CreateParams(WebContents()->GetBrowserContext())); NavigationObserver observer(detached_web_contents.get()); detached_web_contents->GetController().LoadURL( embedded_test_server()->GetURL("/password/multi_frames.html"),
diff --git a/chrome/browser/password_manager/password_manager_test_base.cc b/chrome/browser/password_manager/password_manager_test_base.cc index b13acdb..f7ffcad 100644 --- a/chrome/browser/password_manager/password_manager_test_base.cc +++ b/chrome/browser/password_manager/password_manager_test_base.cc
@@ -431,8 +431,8 @@ content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); std::unique_ptr<content::WebContents> owned_web_contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(tab->GetBrowserContext()))); + content::WebContents::Create( + content::WebContents::CreateParams(tab->GetBrowserContext())); web_contents_ = owned_web_contents.get(); ASSERT_TRUE(web_contents_);
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index adb01bd..8b91f916 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -453,12 +453,9 @@ } // Verifies that access to the given url |spec| is blocked. -void CheckURLIsBlocked(Browser* browser, const std::string& spec) { - GURL url(spec); - ui_test_utils::NavigateToURL(browser, url); - content::WebContents* contents = - browser->tab_strip_model()->GetActiveWebContents(); - EXPECT_EQ(url, contents->GetURL()); +void CheckURLIsBlockedInWebContents(content::WebContents* web_contents, + const GURL& url) { + EXPECT_EQ(url, web_contents->GetURL()); base::string16 blocked_page_title; if (url.has_host()) { @@ -467,12 +464,12 @@ // Local file paths show the full URL. blocked_page_title = base::UTF8ToUTF16(url.spec()); } - EXPECT_EQ(blocked_page_title, contents->GetTitle()); + EXPECT_EQ(blocked_page_title, web_contents->GetTitle()); // Verify that the expected error page is being displayed. bool result = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( - contents, + web_contents, "var textContent = document.body.textContent;" "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;" "domAutomationController.send(hasError);", @@ -480,6 +477,15 @@ EXPECT_TRUE(result); } +// Verifies that access to the given url |spec| is blocked. +void CheckURLIsBlocked(Browser* browser, const std::string& spec) { + GURL url(spec); + ui_test_utils::NavigateToURL(browser, url); + content::WebContents* contents = + browser->tab_strip_model()->GetActiveWebContents(); + CheckURLIsBlockedInWebContents(contents, url); +} + // Downloads a file named |file| and expects it to be saved to |dir|, which // must be empty. void DownloadAndVerifyFile(Browser* browser, @@ -3293,9 +3299,8 @@ namespace { -static const char* kRestoredURLs[] = { - "http://aaa.com/empty.html", - "http://bbb.com/empty.html", +constexpr const char* kRestoredURLs[] = { + "http://aaa.com/empty.html", "http://bbb.com/empty.html", }; bool IsNonSwitchArgument(const base::CommandLine::StringType& s) { @@ -3391,7 +3396,32 @@ expected_urls_.push_back(GURL(kRestoredURLs[i])); } + void Blocked() { + // Verifies that URLs are blocked during session restore. + PolicyMap policies; + policies.Set( + key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, + POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(SessionStartupPref::kPrefValueLast), + nullptr); + auto urls = std::make_unique<base::Value>(base::Value::Type::LIST); + for (const auto* url_string : kRestoredURLs) + urls->GetList().emplace_back(url_string); + policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, + POLICY_SOURCE_CLOUD, std::move(urls), nullptr); + provider_.UpdateChromePolicy(policies); + // This should restore the tabs opened at PRE_RunTest below, yet all should + // be blocked. + blocked_ = true; + for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) + expected_urls_.emplace_back(kRestoredURLs[i]); + } + + // URLs that are expected to be loaded. std::vector<GURL> expected_urls_; + + // True if the loaded URLs should be blocked by policy. + bool blocked_ = false; }; IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) { @@ -3419,22 +3449,34 @@ } } -// Flaky(crbug.com/701023) -IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, DISABLED_RunTest) { +// Flaky on Linux; see https://crbug.com/701023. +#if defined(OS_LINUX) +#define MAYBE_RunTest DISABLED_RunTest +#else +#define MAYBE_RunTest RunTest +#endif +IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, MAYBE_RunTest) { TabStripModel* model = browser()->tab_strip_model(); int size = static_cast<int>(expected_urls_.size()); EXPECT_EQ(size, model->count()); for (int i = 0; i < size && i < model->count(); ++i) { - EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL()); + content::WebContents* web_contents = model->GetWebContentsAt(i); + content::WaitForLoadStop(web_contents); + if (blocked_) + CheckURLIsBlockedInWebContents(web_contents, expected_urls_[i]); + else if (expected_urls_[i] == GURL(chrome::kChromeUINewTabURL)) + EXPECT_TRUE(search::IsInstantNTP(web_contents)); + else + EXPECT_EQ(expected_urls_[i], web_contents->GetURL()); } } -INSTANTIATE_TEST_CASE_P( - RestoreOnStartupPolicyTestInstance, - RestoreOnStartupPolicyTest, - testing::Values(&RestoreOnStartupPolicyTest::ListOfURLs, - &RestoreOnStartupPolicyTest::NTP, - &RestoreOnStartupPolicyTest::Last)); +INSTANTIATE_TEST_CASE_P(RestoreOnStartupPolicyTestInstance, + RestoreOnStartupPolicyTest, + testing::Values(&RestoreOnStartupPolicyTest::ListOfURLs, + &RestoreOnStartupPolicyTest::NTP, + &RestoreOnStartupPolicyTest::Last, + &RestoreOnStartupPolicyTest::Blocked)); // Similar to PolicyTest but sets a couple of policies before the browser is // started.
diff --git a/chrome/browser/profile_resetter/profile_resetter_unittest.cc b/chrome/browser/profile_resetter/profile_resetter_unittest.cc index 761f0bf..8da2ac4 100644 --- a/chrome/browser/profile_resetter/profile_resetter_unittest.cc +++ b/chrome/browser/profile_resetter/profile_resetter_unittest.cc
@@ -161,7 +161,7 @@ protected: void SetUp() override; - content::WebContents* CreateWebContents(); + std::unique_ptr<content::WebContents> CreateWebContents(); }; void PinnedTabsResetTest::SetUp() { @@ -169,7 +169,7 @@ resetter_.reset(new ProfileResetter(profile())); } -content::WebContents* PinnedTabsResetTest::CreateWebContents() { +std::unique_ptr<content::WebContents> PinnedTabsResetTest::CreateWebContents() { return content::WebContents::Create( content::WebContents::CreateParams(profile())); }
diff --git a/chrome/browser/renderer_host/site_per_process_text_input_browsertest.cc b/chrome/browser/renderer_host/site_per_process_text_input_browsertest.cc index a0440a6..25e404eb 100644 --- a/chrome/browser/renderer_host/site_per_process_text_input_browsertest.cc +++ b/chrome/browser/renderer_host/site_per_process_text_input_browsertest.cc
@@ -1349,9 +1349,9 @@ // Test is flaky: http://crbug.com/710842 IN_PROC_BROWSER_TEST_F(SitePerProcessCustomTextInputManagerFilteringTest, DISABLED_LookUpStringForRangeRoutesToFocusedWidget) { - std::unique_ptr<content::WebContents> new_contents = base::WrapUnique( + std::unique_ptr<content::WebContents> new_contents = content::WebContents::Create(content::WebContents::CreateParams( - active_contents()->GetBrowserContext(), nullptr))); + active_contents()->GetBrowserContext(), nullptr)); content::WebContents* raw_new_contents = new_contents.get(); browser()->tab_strip_model()->InsertWebContentsAt(1, std::move(new_contents), TabStripModel::ADD_ACTIVE); @@ -1430,9 +1430,9 @@ IN_PROC_BROWSER_TEST_F( SitePerProcessCustomTextInputManagerFilteringTest, DoNotCrashBrowserInWordLookUpForDestroyedWidget_ChildFrame) { - std::unique_ptr<content::WebContents> new_contents = base::WrapUnique( + std::unique_ptr<content::WebContents> new_contents = content::WebContents::Create(content::WebContents::CreateParams( - active_contents()->GetBrowserContext(), nullptr))); + active_contents()->GetBrowserContext(), nullptr)); content::WebContents* raw_new_contents = new_contents.get(); browser()->tab_strip_model()->InsertWebContentsAt(1, std::move(new_contents), TabStripModel::ADD_ACTIVE); @@ -1501,9 +1501,9 @@ IN_PROC_BROWSER_TEST_F( SitePerProcessCustomTextInputManagerFilteringTest, DoNotCrashBrowserInWordLookUpForDestroyedWidget_MainFrame) { - std::unique_ptr<content::WebContents> new_contents = base::WrapUnique( + std::unique_ptr<content::WebContents> new_contents = content::WebContents::Create(content::WebContents::CreateParams( - active_contents()->GetBrowserContext(), nullptr))); + active_contents()->GetBrowserContext(), nullptr)); content::WebContents* raw_new_contents = new_contents.get(); browser()->tab_strip_model()->InsertWebContentsAt(1, std::move(new_contents), TabStripModel::ADD_ACTIVE);
diff --git a/chrome/browser/resource_coordinator/tab_features.cc b/chrome/browser/resource_coordinator/tab_features.cc new file mode 100644 index 0000000..3e0861f --- /dev/null +++ b/chrome/browser/resource_coordinator/tab_features.cc
@@ -0,0 +1,15 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/resource_coordinator/tab_features.h" + +namespace resource_coordinator { + +TabFeatures::TabFeatures() = default; + +TabFeatures::~TabFeatures() = default; + +TabFeatures::TabFeatures(const TabFeatures& other) = default; + +} // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/tab_features.h b/chrome/browser/resource_coordinator/tab_features.h new file mode 100644 index 0000000..a9afec38 --- /dev/null +++ b/chrome/browser/resource_coordinator/tab_features.h
@@ -0,0 +1,49 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_FEATURES_H_ +#define CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_FEATURES_H_ + +#include <stdint.h> +#include <string> + +#include "base/optional.h" +#include "chrome/browser/resource_coordinator/tab_metrics_event.pb.h" +#include "ui/base/page_transition_types.h" + +namespace resource_coordinator { + +// Tab features used for logging a Tab Ranker example to UKM or calculating a +// Tab Ranker score. +struct TabFeatures { + TabFeatures(); + ~TabFeatures(); + + TabFeatures(const TabFeatures& other); + + // Keep properties in alphabetical order to match the order in + // TabMetricsLogger::LogBackgroundTab() and make it easier to check which + // properties are sent via UKM. + metrics::TabMetricsEvent::ContentType content_type = + metrics::TabMetricsEvent::CONTENT_TYPE_UNKNOWN; + bool has_before_unload_handler = false; + bool has_form_entry = false; + bool is_extension_protected = false; + bool is_pinned = false; + int32_t key_event_count = 0; + int32_t mouse_event_count = 0; + int32_t navigation_entry_count = 0; + // Null if the value is not one of the core values logged to UKM. + base::Optional<ui::PageTransition> page_transition_core_type; + bool page_transition_from_address_bar = false; + bool page_transition_is_redirect = false; + // Null if the SiteEngagementService is disabled. + base::Optional<int32_t> site_engagement_score; + int32_t touch_event_count = 0; + bool was_recently_audible = false; +}; + +} // namespace resource_coordinator + +#endif // CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_FEATURES_H_
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc b/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc index d2c364d..120efbc 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc
@@ -228,7 +228,7 @@ create_params.initially_hidden = old_contents->GetVisibility() == content::Visibility::HIDDEN; std::unique_ptr<content::WebContents> null_contents = - base::WrapUnique(content::WebContents::Create(create_params)); + content::WebContents::Create(create_params); content::WebContents* raw_null_contents = null_contents.get(); // Copy over the state from the navigation controller to preserve the // back/forward history and to continue to display the correct title/favicon.
diff --git a/chrome/browser/resource_coordinator/tab_metrics_logger.cc b/chrome/browser/resource_coordinator/tab_metrics_logger.cc index dbfb021..ec81b94b 100644 --- a/chrome/browser/resource_coordinator/tab_metrics_logger.cc +++ b/chrome/browser/resource_coordinator/tab_metrics_logger.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/resource_coordinator/tab_features.h" #include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -89,8 +90,8 @@ } // Populates navigation-related metrics. -void PopulatePageTransitionMetrics(ukm::builders::TabManager_TabMetrics* entry, - ui::PageTransition page_transition) { +void PopulatePageTransitionFeatures(resource_coordinator::TabFeatures* tab, + ui::PageTransition page_transition) { // We only report the following core types. // Note: Redirects unrelated to clicking a link still get the "link" type. if (ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_LINK) || @@ -100,14 +101,14 @@ ui::PAGE_TRANSITION_FORM_SUBMIT) || ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_RELOAD)) { - entry->SetPageTransitionCoreType( - ui::PageTransitionStripQualifier(page_transition)); + tab->page_transition_core_type = + ui::PageTransitionStripQualifier(page_transition); } - entry->SetPageTransitionFromAddressBar( - (page_transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) != 0); - entry->SetPageTransitionIsRedirect( - ui::PageTransitionIsRedirect(page_transition)); + tab->page_transition_from_address_bar = + (page_transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) != 0; + tab->page_transition_is_redirect = + ui::PageTransitionIsRedirect(page_transition); } // Logs the TabManager.Background.ForegroundedOrClosed event. @@ -184,6 +185,51 @@ return rounded_score; } +// static +resource_coordinator::TabFeatures TabMetricsLogger::GetTabFeatures( + const Browser* browser, + const TabMetricsLogger::TabMetrics& tab_metrics) { + DCHECK(browser); + const TabStripModel* tab_strip_model = browser->tab_strip_model(); + content::WebContents* web_contents = tab_metrics.web_contents; + + resource_coordinator::TabFeatures tab; + + TabMetricsEvent::ContentType content_type = + GetContentTypeFromMimeType(web_contents->GetContentsMimeType()); + tab.content_type = content_type; + tab.has_before_unload_handler = + web_contents->GetMainFrame()->GetSuddenTerminationDisablerState( + blink::kBeforeUnloadHandler); + tab.has_form_entry = + web_contents->GetPageImportanceSignals().had_form_interaction; + tab.is_extension_protected = + !resource_coordinator::TabLifecycleUnitExternal::FromWebContents( + web_contents) + ->IsAutoDiscardable(); + + int index = tab_strip_model->GetIndexOfWebContents(web_contents); + DCHECK_NE(index, TabStripModel::kNoTab); + tab.is_pinned = tab_strip_model->IsTabPinned(index); + + tab.key_event_count = tab_metrics.page_metrics.key_event_count; + tab.mouse_event_count = tab_metrics.page_metrics.mouse_event_count; + tab.navigation_entry_count = web_contents->GetController().GetEntryCount(); + + PopulatePageTransitionFeatures(&tab, tab_metrics.page_transition); + + if (SiteEngagementService::IsEnabled()) { + tab.site_engagement_score = GetSiteEngagementScore(web_contents); + } + + tab.touch_event_count = tab_metrics.page_metrics.touch_event_count; + + // This checks if the tab was audible within the past two seconds, same as the + // audio indicator in the tab strip. + tab.was_recently_audible = web_contents->WasRecentlyAudible(); + return tab; +} + void TabMetricsLogger::LogBackgroundTab(ukm::SourceId ukm_source_id, const TabMetrics& tab_metrics) { if (!ukm_source_id) @@ -211,46 +257,36 @@ DCHECK_NE(index, TabStripModel::kNoTab); ukm::builders::TabManager_TabMetrics entry(ukm_source_id); + resource_coordinator::TabFeatures tab = GetTabFeatures(browser, tab_metrics); + + PopulateProtocolHandlers(web_contents, &entry); + + // Keep these Set functions in alphabetical order so they're easy to check + // against the list of metrics in the UKM event. + // TODO(michaelpg): Add PluginType field if mime type matches "application/*" + // using PluginUMAReporter. + entry.SetContentType(tab.content_type); + entry.SetHasBeforeUnloadHandler(tab.has_before_unload_handler); + entry.SetHasFormEntry(tab.has_form_entry); + entry.SetIsExtensionProtected(tab.is_extension_protected); + entry.SetIsPinned(tab.is_pinned); + entry.SetKeyEventCount(tab.key_event_count); + entry.SetMouseEventCount(tab.mouse_event_count); + entry.SetNavigationEntryCount(tab.navigation_entry_count); + if (tab.page_transition_core_type.has_value()) + entry.SetPageTransitionCoreType(tab.page_transition_core_type.value()); + entry.SetPageTransitionFromAddressBar(tab.page_transition_from_address_bar); + entry.SetPageTransitionIsRedirect(tab.page_transition_is_redirect); + entry.SetSequenceId(++sequence_id_); + if (tab.site_engagement_score.has_value()) + entry.SetSiteEngagementScore(tab.site_engagement_score.value()); + entry.SetTouchEventCount(tab.touch_event_count); + entry.SetWasRecentlyAudible(tab.was_recently_audible); // The browser window logs its own usage UKMs with its session ID. entry.SetWindowId(browser->session_id().id()); - entry.SetKeyEventCount(tab_metrics.page_metrics.key_event_count) - .SetMouseEventCount(tab_metrics.page_metrics.mouse_event_count) - .SetTouchEventCount(tab_metrics.page_metrics.touch_event_count); - - PopulateProtocolHandlers(web_contents, &entry); - - const int engagement_score = GetSiteEngagementScore(web_contents); - if (engagement_score >= 0) { - entry.SetSiteEngagementScore(engagement_score); - } - - TabMetricsEvent::ContentType content_type = - GetContentTypeFromMimeType(web_contents->GetContentsMimeType()); - entry.SetContentType(static_cast<int>(content_type)); - // TODO(michaelpg): Add PluginType field if mime type matches "application/*" - // using PluginUMAReporter. - - // This checks if the tab was audible within the past two seconds, same as the - // audio indicator in the tab strip. - entry.SetWasRecentlyAudible(web_contents->WasRecentlyAudible()); - - PopulatePageTransitionMetrics(&entry, tab_metrics.page_transition); - entry - .SetHasBeforeUnloadHandler( - web_contents->GetMainFrame()->GetSuddenTerminationDisablerState( - blink::kBeforeUnloadHandler)) - .SetHasFormEntry( - web_contents->GetPageImportanceSignals().had_form_interaction) - .SetIsExtensionProtected( - !resource_coordinator::TabLifecycleUnitExternal::FromWebContents( - web_contents) - ->IsAutoDiscardable()) - .SetIsPinned(tab_strip_model->IsTabPinned(index)) - .SetNavigationEntryCount(web_contents->GetController().GetEntryCount()) - .SetSequenceId(++sequence_id_) - .Record(ukm::UkmRecorder::Get()); + entry.Record(ukm::UkmRecorder::Get()); } void TabMetricsLogger::LogBackgroundTabShown(ukm::SourceId ukm_source_id,
diff --git a/chrome/browser/resource_coordinator/tab_metrics_logger.h b/chrome/browser/resource_coordinator/tab_metrics_logger.h index c90c816..78f8e5e 100644 --- a/chrome/browser/resource_coordinator/tab_metrics_logger.h +++ b/chrome/browser/resource_coordinator/tab_metrics_logger.h
@@ -10,6 +10,8 @@ #include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/base/page_transition_types.h" +class Browser; + namespace base { class TimeDelta; } // namespace base @@ -18,6 +20,10 @@ class WebContents; } // namespace content +namespace resource_coordinator { +struct TabFeatures; +} // namespace resource_coordinator + // Logs metrics for a tab and its WebContents when requested. // Must be used on the UI thread. class TabMetricsLogger { @@ -90,6 +96,14 @@ // to limit granularity. Returns -1 if site engagement service is disabled. static int GetSiteEngagementScore(const content::WebContents* web_contents); + // Creates TabFeatures for logging or scoring tabs. + // A common function for populating these features ensures that the same + // values are used for logging training examples to UKM and for locally + // scoring tabs. + static resource_coordinator::TabFeatures GetTabFeatures( + const Browser* browser, + const TabMetrics& tab_metrics); + private: // A counter to be incremented and logged with each UKM entry, used to // indicate the order that events within the same report were logged.
diff --git a/chrome/browser/resource_coordinator/tab_metrics_logger_unittest.cc b/chrome/browser/resource_coordinator/tab_metrics_logger_unittest.cc index 8485f64..787df4c 100644 --- a/chrome/browser/resource_coordinator/tab_metrics_logger_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_metrics_logger_unittest.cc
@@ -4,16 +4,125 @@ #include "chrome/browser/resource_coordinator/tab_metrics_logger.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/engagement/site_engagement_service.h" +#include "chrome/browser/resource_coordinator/tab_features.h" +#include "chrome/browser/resource_coordinator/tab_manager.h" #include "chrome/browser/resource_coordinator/tab_metrics_event.pb.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/tabs/tab_activity_simulator.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/test_browser_window.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" using metrics::TabMetricsEvent; +using content::WebContentsTester; // Sanity checks for functions in TabMetricsLogger. // See TabActivityWatcherTest for more thorough tab usage UKM tests. +using TabMetricsLoggerTest = ChromeRenderViewHostTestHarness; + +// Tests creating a flat TabFeatures structure for logging a tab and its +// TabMetrics state. +TEST_F(TabMetricsLoggerTest, TabFeatures) { + TabActivitySimulator tab_activity_simulator; + Browser::CreateParams params(profile(), true); + std::unique_ptr<Browser> browser = + CreateBrowserWithTestWindowForParams(¶ms); + TabStripModel* tab_strip_model = browser->tab_strip_model(); + + // Add a foreground tab. + tab_activity_simulator.AddWebContentsAndNavigate(tab_strip_model, + GURL("about://blank")); + tab_strip_model->ActivateTabAt(0, false); + + // Add a background tab to test. + content::WebContents* bg_contents = + tab_activity_simulator.AddWebContentsAndNavigate( + tab_strip_model, GURL("http://example.com/test.html")); + WebContentsTester::For(bg_contents)->TestSetIsLoading(false); + + { + TabMetricsLogger::TabMetrics bg_metrics; + bg_metrics.web_contents = bg_contents; + bg_metrics.page_transition = ui::PAGE_TRANSITION_FORM_SUBMIT; + + resource_coordinator::TabFeatures bg_features = + TabMetricsLogger::GetTabFeatures(browser.get(), bg_metrics); + EXPECT_EQ(TabMetricsEvent::CONTENT_TYPE_TEXT_HTML, + bg_features.content_type); + EXPECT_EQ(bg_features.has_before_unload_handler, false); + EXPECT_EQ(bg_features.has_form_entry, false); + EXPECT_EQ(bg_features.is_extension_protected, false); + EXPECT_EQ(bg_features.is_pinned, false); + EXPECT_EQ(bg_features.key_event_count, 0); + EXPECT_EQ(bg_features.mouse_event_count, 0); + EXPECT_EQ(bg_features.navigation_entry_count, 1); + ASSERT_TRUE(bg_features.page_transition_core_type.has_value()); + EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( + ui::PAGE_TRANSITION_FORM_SUBMIT, + bg_features.page_transition_core_type.value())); + EXPECT_EQ(bg_features.page_transition_from_address_bar, false); + EXPECT_EQ(bg_features.page_transition_is_redirect, false); + ASSERT_TRUE(bg_features.site_engagement_score.has_value()); + EXPECT_EQ(bg_features.site_engagement_score.value(), 0); + EXPECT_EQ(bg_features.touch_event_count, 0); + EXPECT_EQ(bg_features.was_recently_audible, false); + } + + // Update tab features. + ui::PageTransition page_transition = static_cast<ui::PageTransition>( + ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); + tab_activity_simulator.Navigate(bg_contents, GURL("https://www.chromium.org"), + page_transition); + tab_strip_model->SetTabPinned(1, true); + // Simulate an extension protecting a tab. + g_browser_process->GetTabManager()->SetTabAutoDiscardableState(bg_contents, + false); + SiteEngagementService::Get(profile())->ResetBaseScoreForURL( + GURL("https://www.chromium.org"), 91); + + { + TabMetricsLogger::TabMetrics bg_metrics; + bg_metrics.web_contents = bg_contents; + bg_metrics.page_transition = page_transition; + bg_metrics.page_metrics.key_event_count = 3; + bg_metrics.page_metrics.mouse_event_count = 42; + bg_metrics.page_metrics.touch_event_count = 10; + + resource_coordinator::TabFeatures bg_features = + TabMetricsLogger::GetTabFeatures(browser.get(), bg_metrics); + EXPECT_EQ(TabMetricsEvent::CONTENT_TYPE_TEXT_HTML, + bg_features.content_type); + EXPECT_EQ(bg_features.has_before_unload_handler, false); + EXPECT_EQ(bg_features.has_form_entry, false); + EXPECT_EQ(bg_features.is_extension_protected, true); + EXPECT_EQ(bg_features.is_pinned, true); + EXPECT_EQ(bg_features.key_event_count, 3); + EXPECT_EQ(bg_features.mouse_event_count, 42); + EXPECT_EQ(bg_features.navigation_entry_count, 2); + ASSERT_TRUE(bg_features.page_transition_core_type.has_value()); + EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( + ui::PAGE_TRANSITION_LINK, + bg_features.page_transition_core_type.value())); + EXPECT_EQ(bg_features.page_transition_from_address_bar, true); + EXPECT_EQ(bg_features.page_transition_is_redirect, false); + ASSERT_TRUE(bg_features.site_engagement_score.has_value()); + // Site engagement score should round down to the nearest 10. + EXPECT_EQ(bg_features.site_engagement_score.value(), 90); + EXPECT_EQ(bg_features.touch_event_count, 10); + EXPECT_EQ(bg_features.was_recently_audible, false); + } + + tab_strip_model->CloseAllTabs(); +} // Tests that protocol schemes are mapped to the correct enumerators. -TEST(TabMetricsLoggerTest, Schemes) { +TEST_F(TabMetricsLoggerTest, Schemes) { EXPECT_EQ(TabMetricsEvent::PROTOCOL_HANDLER_SCHEME_BITCOIN, TabMetricsLogger::GetSchemeValueFromString("bitcoin")); EXPECT_EQ(TabMetricsEvent::PROTOCOL_HANDLER_SCHEME_GEO, @@ -64,7 +173,7 @@ } // Tests non-whitelisted protocol schemes. -TEST(TabMetricsLoggerTest, NonWhitelistedSchemes) { +TEST_F(TabMetricsLoggerTest, NonWhitelistedSchemes) { // Native (non-web-based) handler. EXPECT_EQ(TabMetricsEvent::PROTOCOL_HANDLER_SCHEME_OTHER, TabMetricsLogger::GetSchemeValueFromString("foo"));
diff --git a/chrome/browser/resources/bookmark_manager/css/bmm.css b/chrome/browser/resources/bookmark_manager/css/bmm.css deleted file mode 100644 index a550ec56..0000000 --- a/chrome/browser/resources/bookmark_manager/css/bmm.css +++ /dev/null
@@ -1,392 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -<include src="../search_header.css"> - -html, -body { - cursor: default; - height: 100%; - margin: 0; - overflow: hidden; - width: 100%; -} - -body { - display: flex; - flex-direction: column; -} - -list { - display: block; - overflow-x: hidden; - overflow-y: visible; /* let the container do the scrolling */ -} - -list > * { - -webkit-padding-end: 20px; - -webkit-padding-start: 3px; - color: hsl(0, 0%, 70%); - display: flex; - line-height: 20px; - margin: 0; - overflow: visible; - padding-bottom: 0; - padding-top: 0; - text-decoration: none; - white-space: nowrap; -} - -list > * > * { - -webkit-padding-start: 20px; - background: 0 50% no-repeat; - box-sizing: border-box; - overflow: hidden; - text-overflow: ellipsis; - white-space: pre; -} - -list .label { - -webkit-padding-start: 0; - align-items: center; - display: flex; -} - -list .label-img-wrapper { - display: inline-block; /* Makes the image start-align in RTL. */ - width: 20px; - z-index: -1; -} - -<if expr="not is_macosx"> -html[dir=rtl] list > .folder .label-img-wrapper > * { - transform: scaleX(-1); -} -</if> - -list .label-text { - color: black; - flex: 1; - overflow: hidden; - text-overflow: ellipsis; -} - -/* We need to ensure that even empty labels take up space, or the row could be - * the wrong height. */ -list .label-text:empty::after { - content: ' '; - white-space: pre; -} - -list .url { - direction: ltr; - display: none; - flex: 1; -} - -list > :hover > .url, -list > [selected] > .url { - display: block; -} - -/* Handle proper padding for URL field in an RTL context, where field order is - * |div.url||div.label| - so we need padding at the right of URL, not at the - * left. And since url is always LTR, that is padding at the end, not the start. - */ -html[dir=rtl] list .url { - -webkit-padding-end: 20px; - -webkit-padding-start: 0; - text-align: right; -} - -list > * > button { - background: #fff no-repeat center center; - border: 1px solid hsl(214, 91%, 85%); - border-radius: 3px; - bottom: 1px; - display: none; - overflow: hidden; - padding: 0; - position: absolute; - right: 3px; - top: 1px; - transition: opacity 150ms; - width: 15px; -} - -list > [selected]:hover > button, -list > * > button[menu-shown] { - border-color: hsl(214, 91%, 65%); -} - -list > :hover > button { - display: block; -} - -list > * > button:hover, -list > * > button[menu-shown] { - display: block; -} - -html[dir=rtl] list > * > button { - left: 3px; - right: auto; -} - -/* Edit mode */ - -list [editing] .label-text input, -list [editing] .url input { - -webkit-margin-end: 4px; - -webkit-margin-start: -4px; - -webkit-padding-end: 3px; - -webkit-padding-start: 3px; - box-sizing: content-box; - font-family: inherit; - font-size: inherit; - font-weight: inherit; - /* Do not inherit the line-height. */ - line-height: normal; - margin-bottom: 0; - margin-top: 0; - min-height: 0; - text-decoration: none; - vertical-align: baseline; -} - -.tree-item [editing] input { - line-height: normal; - margin: 0; - min-height: 0; - padding: 1px 0; -} - -<if expr="is_macosx"> -list .label-text input, -list .url input { - outline: none; -} -</if> - -list > [editing] { - overflow: visible; -} - -list [editing] .label-text, -list [editing] .url, -list [editing] > * { - overflow: visible; -} - -list [editing] .url { - -webkit-padding-start: 5px; -} - -list [editing] input { - padding: 1px 0; -} - -/* end editing */ - -.main { - border-top: 1px solid rgb(156, 194, 239); - display: flex; - flex: 1; - min-height: 0; -} - -.pane, -.splitter { - display: flex; - flex-direction: column; -} - -.pane > :first-child, -.splitter > :first-child { - background-color: rgb(235, 239, 249); - flex: none; - padding: 5px 10px; - white-space: nowrap; -} - -.splitter > :first-child { - overflow: hidden; - padding-left: 0; - padding-right: 0; - width: 15px; -} - -.splitter button { - visibility: hidden; /* This button is only used for height matching. */ -} - -#tree-pane { - /* min-width and max-width are used by the split pane. */ - max-width: 50%; - min-width: 150px; - width: 200px; -} - -#list-pane { - flex: 1; - min-width: 0; -} - -#list-pane > :first-child { - -webkit-padding-start: 0; /* Accounts for extra splitter resize width. */ -} - -#tree-container { - overflow: auto; -} - -#list, -#tree-container { - flex: 1; -} - -#tree, -#list { - -webkit-padding-end: 5px; - box-sizing: border-box; - display: inline-block; - min-width: 100%; - padding-bottom: 5px; - padding-top: 5px; -} - -#tree { - /* Only pad the tree as the splitter adds a lot of whitespace for the list. */ - -webkit-padding-start: 10px; -} - -.tree-item > .tree-row { - line-height: 20px; -} - -.tree-row .expand-icon { - top: 2px; -} - -/* TODO(pkasting): Convert the tree widget to use the same resources as the - * list, and remove this block. */ -<if expr="is_macosx"> -.tree-label, -.tree-row[may-have-children] > .tree-label, -.tree-item[expanded] > .tree-row > .tree-label { - background-image: -webkit-image-set( - url(../../../../app/theme/default_100_percent/mac/bookmark_bar_folder.png) 1x, - url(../../../../app/theme/default_200_percent/mac/bookmark_bar_folder.png) 2x); -} -</if> - -.splitter { - border-left: 5px solid rgb(235, 239, 249); - cursor: e-resize; -<if expr="is_macosx"> - cursor: col-resize; -</if> - overflow-x: hidden; -} - -.tree-row.drag-on, -.drag-on { - background-color: hsla(214, 91%, 85%, .5); - border: 1px solid hsl(214, 91%, 85%); - border-radius: 3px; - box-sizing: border-box; -} - -.drag-above::before, -.drag-below::after { - background-clip: padding-box; - background-color: black; - border: 3px solid black; - border-bottom-color: transparent; - border-radius: 0; - border-top-color: transparent; - box-sizing: border-box; - content: ''; - display: block; - height: 8px; - left: 0; - position: absolute; - right: 0; - z-index: 10; -} - -.drag-above::before { - top: calc((8px/2 + 1px) * -1) -} - -.drag-below::after { - bottom: calc((8px/2 + 1px) * -1) -} - -list.drag-above::before { - top: 0 -} - -list > .drag-below, -list > .drag-above { - overflow: visible; -} - -.summary > * { - font-size: 100%; - margin: 0; -} - -#folders-button, -#organize-button, -.splitter button { - -webkit-appearance: none; - -webkit-padding-end: 11px; - -webkit-padding-start: 0; - background: transparent no-repeat right center; - border: 0; - font: inherit; - font-weight: bold; - padding-bottom: 0; - padding-top: 0; -} - -list > * > button, -[i18n-processed] #folders-button, -[i18n-processed] #organize-button, -[i18n-processed] .splitter button { - background-image: - url(../../../../../ui/webui/resources/images/drop_down_arrow_black.svg); - background-size: 9px 4px; -} - -#folders-button { - -webkit-margin-start: 16px; -} - -#organize-button { - -webkit-margin-start: 4px; -} - -html[dir=rtl] #folders-button, -html[dir=rtl] #organize-button { - background-position: left center; -} - -@media (pointer:coarse) { - list > *, - cr-menu > button, - .tree-item > .tree-row { - line-height: 28px; - } - - list [editing] input, - .tree-item [editing] input { - padding: 3px 0; - } - - .tree-row .expand-icon { - top: 6px; - } -}
diff --git a/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search.png b/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search.png deleted file mode 100644 index 438c6782..0000000 --- a/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search_rtl.png b/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search_rtl.png deleted file mode 100644 index 439055ba..0000000 --- a/chrome/browser/resources/bookmark_manager/images/2x/bookmark_manager_search_rtl.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/images/2x/bookmarks_section_32.png b/chrome/browser/resources/bookmark_manager/images/2x/bookmarks_section_32.png deleted file mode 100644 index 5455818..0000000 --- a/chrome/browser/resources/bookmark_manager/images/2x/bookmarks_section_32.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search.png b/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search.png deleted file mode 100644 index 46b88a7..0000000 --- a/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search_rtl.png b/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search_rtl.png deleted file mode 100644 index 2ad79680..0000000 --- a/chrome/browser/resources/bookmark_manager/images/bookmark_manager_search_rtl.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/images/bookmarks_section_32.png b/chrome/browser/resources/bookmark_manager/images/bookmarks_section_32.png deleted file mode 100644 index 555d340..0000000 --- a/chrome/browser/resources/bookmark_manager/images/bookmarks_section_32.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/bookmark_manager/js/bmm.js b/chrome/browser/resources/bookmark_manager/js/bmm.js deleted file mode 100644 index a981cb9..0000000 --- a/chrome/browser/resources/bookmark_manager/js/bmm.js +++ /dev/null
@@ -1,261 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('bmm', function() { - 'use strict'; - - /** - * Whether a node contains another node. - * TODO(yosin): Once JavaScript style guide is updated and linter follows - * that, we'll remove useless documentations for |parent| and |descendant|. - * TODO(yosin): bmm.contains() should be method of BookmarkTreeNode. - * @param {!BookmarkTreeNode} parent . - * @param {!BookmarkTreeNode} descendant . - * @return {boolean} Whether the parent contains the descendant. - */ - function contains(parent, descendant) { - if (descendant.parentId == parent.id) - return true; - // the bmm.treeLookup contains all folders - var parentTreeItem = bmm.treeLookup[descendant.parentId]; - if (!parentTreeItem || !parentTreeItem.bookmarkNode) - return false; - return this.contains(parent, parentTreeItem.bookmarkNode); - } - - /** - * @param {!BookmarkTreeNode} node The node to test. - * @return {boolean} Whether a bookmark node is a folder. - */ - function isFolder(node) { - return !('url' in node); - } - - var loadingPromises = {}; - - /** - * Promise version of chrome.bookmarkManagerPrivate.getSubtree. - * @param {string} id . - * @param {boolean} foldersOnly . - * @return {!Promise<!Array<!BookmarkTreeNode>>} . - */ - function getSubtreePromise(id, foldersOnly) { - return new Promise(function(resolve, reject) { - chrome.bookmarkManagerPrivate.getSubtree(id, foldersOnly, function(node) { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - return; - } - resolve(node); - }); - }); - } - - /** - * Loads a subtree of the bookmark tree and returns a {@code Promise} that - * will be fulfilled when done. This reuses multiple loads so that we do not - * load the same subtree more than once at the same time. - * @return {!Promise<!BookmarkTreeNode>} The future promise for the load. - */ - function loadSubtree(id) { - if (!loadingPromises[id]) { - loadingPromises[id] = getSubtreePromise(id, false).then(function(nodes) { - return nodes && nodes[0]; - }, function(error) { - console.error(error.message); - }); - loadingPromises[id].then(function() { - delete loadingPromises[id]; - }); - } - return loadingPromises[id]; - } - - /** - * Loads the entire bookmark tree and returns a {@code Promise} that will - * be fulfilled when done. This reuses multiple loads so that we do not load - * the same tree more than once at the same time. - * @return {!Promise<!BookmarkTreeNode>} The future promise for the load. - */ - function loadTree() { - return loadSubtree(''); - } - - var bookmarkCache = { - /** - * Removes the cached item from both the list and tree lookups. - */ - remove: function(id) { - var treeItem = bmm.treeLookup[id]; - if (treeItem) { - var items = treeItem.items; // is an HTMLCollection - for (var i = 0; i < items.length; ++i) { - var item = items[i]; - var bookmarkNode = item.bookmarkNode; - delete bmm.treeLookup[bookmarkNode.id]; - } - delete bmm.treeLookup[id]; - } - }, - - /** - * Updates the underlying bookmark node for the tree items and list items by - * querying the bookmark backend. - * @param {string} id The id of the node to update the children for. - * @param {Function=} opt_f A funciton to call when done. - */ - updateChildren: function(id, opt_f) { - function updateItem(bookmarkNode) { - var treeItem = bmm.treeLookup[bookmarkNode.id]; - if (treeItem) { - treeItem.bookmarkNode = bookmarkNode; - } - } - - chrome.bookmarks.getChildren(id, function(children) { - if (children) - children.forEach(updateItem); - - if (opt_f) - opt_f(children); - }); - } - }; - - /** - * Called when the title of a bookmark changes. - * @param {string} id The id of changed bookmark node. - * @param {!Object} changeInfo The information about how the node changed. - */ - function handleBookmarkChanged(id, changeInfo) { - if (bmm.tree) - bmm.tree.handleBookmarkChanged(id, changeInfo); - if (bmm.list) - bmm.list.handleBookmarkChanged(id, changeInfo); - } - - /** - * Callback for when the user reorders by title. - * @param {string} id The id of the bookmark folder that was reordered. - * @param {!Object} reorderInfo The information about how the items where - * reordered. - */ - function handleChildrenReordered(id, reorderInfo) { - if (bmm.tree) - bmm.tree.handleChildrenReordered(id, reorderInfo); - if (bmm.list) - bmm.list.handleChildrenReordered(id, reorderInfo); - bookmarkCache.updateChildren(id); - } - - /** - * Callback for when a bookmark node is created. - * @param {string} id The id of the newly created bookmark node. - * @param {!Object} bookmarkNode The new bookmark node. - */ - function handleCreated(id, bookmarkNode) { - if (bmm.list) - bmm.list.handleCreated(id, bookmarkNode); - if (bmm.tree) - bmm.tree.handleCreated(id, bookmarkNode); - bookmarkCache.updateChildren(bookmarkNode.parentId); - } - - /** - * Callback for when a bookmark node is moved. - * @param {string} id The id of the moved bookmark node. - * @param {!Object} moveInfo The information about move. - */ - function handleMoved(id, moveInfo) { - if (bmm.list) - bmm.list.handleMoved(id, moveInfo); - if (bmm.tree) - bmm.tree.handleMoved(id, moveInfo); - - bookmarkCache.updateChildren(moveInfo.parentId); - if (moveInfo.parentId != moveInfo.oldParentId) - bookmarkCache.updateChildren(moveInfo.oldParentId); - } - - /** - * Callback for when a bookmark node is removed. - * @param {string} id The id of the removed bookmark node. - * @param {!Object} removeInfo The information about removed. - */ - function handleRemoved(id, removeInfo) { - if (bmm.list) - bmm.list.handleRemoved(id, removeInfo); - if (bmm.tree) - bmm.tree.handleRemoved(id, removeInfo); - - bookmarkCache.updateChildren(removeInfo.parentId); - bookmarkCache.remove(id); - } - - /** - * Callback for when all bookmark nodes have been deleted. - */ - function handleRemoveAll() { - // Reload the list and the tree. - if (bmm.list) - bmm.list.reload(); - if (bmm.tree) - bmm.tree.reload(); - } - - /** - * Callback for when importing bookmark is started. - */ - function handleImportBegan() { - chrome.bookmarks.onCreated.removeListener(handleCreated); - chrome.bookmarks.onChanged.removeListener(handleBookmarkChanged); - } - - /** - * Callback for when importing bookmark node is finished. - */ - function handleImportEnded() { - // When importing is done we reload the tree and the list. - - function f() { - bmm.tree.removeEventListener('load', f); - - chrome.bookmarks.onCreated.addListener(handleCreated); - chrome.bookmarks.onChanged.addListener(handleBookmarkChanged); - - if (!bmm.list) - return; - - // TODO(estade): this should navigate to the newly imported folder, which - // may be the bookmark bar if there were no previous bookmarks. - bmm.list.reload(); - } - - if (bmm.tree) { - bmm.tree.addEventListener('load', f); - bmm.tree.reload(); - } - } - - /** - * Adds the listeners for the bookmark model change events. - */ - function addBookmarkModelListeners() { - chrome.bookmarks.onChanged.addListener(handleBookmarkChanged); - chrome.bookmarks.onChildrenReordered.addListener(handleChildrenReordered); - chrome.bookmarks.onCreated.addListener(handleCreated); - chrome.bookmarks.onMoved.addListener(handleMoved); - chrome.bookmarks.onRemoved.addListener(handleRemoved); - chrome.bookmarks.onImportBegan.addListener(handleImportBegan); - chrome.bookmarks.onImportEnded.addListener(handleImportEnded); - } - - return { - contains: contains, - isFolder: isFolder, - loadSubtree: loadSubtree, - loadTree: loadTree, - addBookmarkModelListeners: addBookmarkModelListeners - }; -});
diff --git a/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_list.js b/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_list.js deleted file mode 100644 index 089b77a..0000000 --- a/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_list.js +++ /dev/null
@@ -1,658 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(arv): Now that this is driven by a data model, implement a data model -// that handles the loading and the events from the bookmark backend. - -/** - * @typedef {{childIds: Array<string>}} - * - * @see chrome/common/extensions/api/bookmarks.json - */ -var ReorderInfo; - -/** - * @typedef {{parentId: string, - * index: number, - * oldParentId: string, - * oldIndex: number}} - * - * @see chrome/common/extensions/api/bookmarks.json - */ -var MoveInfo; - -cr.define('bmm', function() { - 'use strict'; - - var List = cr.ui.List; - var ListItem = cr.ui.ListItem; - var ArrayDataModel = cr.ui.ArrayDataModel; - var ContextMenuButton = cr.ui.ContextMenuButton; - - /** - * Basic array data model for use with bookmarks. - * @param {!Array<!BookmarkTreeNode>} items The bookmark items. - * @constructor - * @extends {ArrayDataModel} - */ - function BookmarksArrayDataModel(items) { - ArrayDataModel.call(this, items); - } - - BookmarksArrayDataModel.prototype = { - __proto__: ArrayDataModel.prototype, - - /** - * Finds the index of the bookmark with the given ID. - * @param {string} id The ID of the bookmark node to find. - * @return {number} The index of the found node or -1 if not found. - */ - findIndexById: function(id) { - for (var i = 0; i < this.length; i++) { - if (this.item(i).id == id) - return i; - } - return -1; - } - }; - - /** - * Removes all children and appends a new child. - * @param {!Node} parent The node to remove all children from. - * @param {!Node} newChild The new child to append. - */ - function replaceAllChildren(parent, newChild) { - var n; - while ((n = parent.lastChild)) { - parent.removeChild(n); - } - parent.appendChild(newChild); - } - - /** - * Creates a new bookmark list. - * @param {Object=} opt_propertyBag Optional properties. - * @constructor - * @extends {cr.ui.List} - */ - var BookmarkList = cr.ui.define('list'); - - BookmarkList.prototype = { - __proto__: List.prototype, - - /** @override */ - decorate: function() { - List.prototype.decorate.call(this); - this.addEventListener('mousedown', this.handleMouseDown_); - - // HACK(arv): http://crbug.com/40902 - window.addEventListener('resize', this.redraw.bind(this)); - - // We could add the ContextMenuButton in the BookmarkListItem but it slows - // down redraws a lot so we do this on mouseovers instead. - this.addEventListener('mouseover', this.handleMouseOver_.bind(this)); - - bmm.list = this; - }, - - /** - * @param {!BookmarkTreeNode} bookmarkNode - * @override - */ - createItem: function(bookmarkNode) { - return new BookmarkListItem(bookmarkNode); - }, - - /** @private {string} */ - parentId_: '', - - /** @private {number} */ - loadCount_: 0, - - /** - * Reloads the list from the bookmarks backend. - */ - reload: function() { - var parentId = this.parentId; - - var callback = this.handleBookmarkCallback_.bind(this); - - this.loadCount_++; - - if (!parentId) - callback([]); - else if (/^q=/.test(parentId)) - chrome.bookmarks.search(parentId.slice(2), callback); - else - chrome.bookmarks.getChildren(parentId, callback); - }, - - /** - * Callback function for loading items. - * @param {Array<!BookmarkTreeNode>} items The loaded items. - * @private - */ - handleBookmarkCallback_: function(items) { - this.loadCount_--; - if (this.loadCount_) - return; - - if (!items) { - // Failed to load bookmarks. Most likely due to the bookmark being - // removed. - cr.dispatchSimpleEvent(this, 'invalidId'); - return; - } - - this.dataModel = new BookmarksArrayDataModel(items); - - this.fixWidth_(); - cr.dispatchSimpleEvent(this, 'load'); - - // Use the same histogram configuration as UMA_HISTOGRAM_COUNTS_1000(). - chrome.metricsPrivate.recordValue({ - 'metricName': 'Bookmarks.BookmarksInFolder', - 'type': chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LOG, - 'min': 1, - 'max': 1000, - 'buckets': 50 - }, this.dataModel.length); - }, - - /** - * The bookmark node that the list is currently displaying. If we are - * currently displaying search this returns null. - * @type {BookmarkTreeNode} - */ - get bookmarkNode() { - if (this.isSearch()) - return null; - var treeItem = bmm.treeLookup[this.parentId]; - return treeItem && treeItem.bookmarkNode; - }, - - /** - * @return {boolean} Whether we are currently showing search results. - */ - isSearch: function() { - return this.parentId_[0] == 'q'; - }, - - /** - * @return {boolean} Whether we are editing an ephemeral item. - */ - hasEphemeral: function() { - var dataModel = this.dataModel; - for (var i = 0; i < dataModel.array_.length; i++) { - if (dataModel.array_[i].id == 'new') - return true; - } - return false; - }, - - /** - * Handles mouseover on the list so that we can add the context menu button - * lazily. - * @private - * @param {!Event} e The mouseover event object. - */ - handleMouseOver_: function(e) { - var el = e.target; - while (el && el.parentNode != this) { - el = el.parentNode; - } - - if (el && el.parentNode == this && - !el.editing && - !(el.lastChild instanceof ContextMenuButton)) { - el.appendChild(new ContextMenuButton); - } - }, - - /** - * Dispatches an urlClicked event which is used to open URLs in new - * tabs etc. - * @private - * @param {string} url The URL that was clicked. - * @param {!Event} originalEvent The original click event object. - */ - dispatchUrlClickedEvent_: function(url, originalEvent) { - var event = new Event('urlClicked', {bubbles: true}); - event.url = url; - event.originalEvent = originalEvent; - this.dispatchEvent(event); - }, - - /** - * Handles mousedown events so that we can prevent the auto scroll as - * necessary. - * @private - * @param {!Event} e The mousedown event object. - */ - handleMouseDown_: function(e) { - e = /** @type {!MouseEvent} */(e); - if (e.button == 1) { - // WebKit no longer fires click events for middle clicks so we manually - // listen to mouse up to dispatch a click event. - this.addEventListener('mouseup', this.handleMiddleMouseUp_); - - // When the user does a middle click we need to prevent the auto scroll - // in case the user is trying to middle click to open a bookmark in a - // background tab. - // We do not do this in case the target is an input since middle click - // is also paste on Linux and we don't want to break that. - if (e.target.tagName != 'INPUT') - e.preventDefault(); - } - }, - - /** - * WebKit no longer dispatches click events for middle clicks so we need - * to emulate it. - * @private - * @param {!Event} e The mouse up event object. - */ - handleMiddleMouseUp_: function(e) { - e = /** @type {!MouseEvent} */(e); - this.removeEventListener('mouseup', this.handleMiddleMouseUp_); - if (e.button == 1) { - var el = e.target; - while (el.parentNode != this) { - el = el.parentNode; - } - var node = el.bookmarkNode; - if (node && !bmm.isFolder(node)) - this.dispatchUrlClickedEvent_(node.url, e); - } - e.preventDefault(); - }, - - // Bookmark model update callbacks - handleBookmarkChanged: function(id, changeInfo) { - var dataModel = this.dataModel; - var index = dataModel.findIndexById(id); - if (index != -1) { - var bookmarkNode = this.dataModel.item(index); - bookmarkNode.title = changeInfo.title; - if ('url' in changeInfo) - bookmarkNode.url = changeInfo['url']; - - dataModel.updateIndex(index); - } - }, - - /** - * @param {string} id - * @param {ReorderInfo} reorderInfo - */ - handleChildrenReordered: function(id, reorderInfo) { - if (this.parentId == id) { - // We create a new data model with updated items in the right order. - var dataModel = this.dataModel; - var items = {}; - for (var i = this.dataModel.length - 1; i >= 0; i--) { - var bookmarkNode = dataModel.item(i); - items[bookmarkNode.id] = bookmarkNode; - } - var newArray = []; - for (var i = 0; i < reorderInfo.childIds.length; i++) { - newArray[i] = items[reorderInfo.childIds[i]]; - newArray[i].index = i; - } - - this.dataModel = new BookmarksArrayDataModel(newArray); - } - }, - - handleCreated: function(id, bookmarkNode) { - if (this.parentId == bookmarkNode.parentId) - this.dataModel.splice(bookmarkNode.index, 0, bookmarkNode); - }, - - /** - * @param {string} id - * @param {MoveInfo} moveInfo - */ - handleMoved: function(id, moveInfo) { - if (moveInfo.parentId == this.parentId || - moveInfo.oldParentId == this.parentId) { - - var dataModel = this.dataModel; - - if (moveInfo.oldParentId == moveInfo.parentId) { - // Reorder within this folder - - this.startBatchUpdates(); - - var bookmarkNode = this.dataModel.item(moveInfo.oldIndex); - this.dataModel.splice(moveInfo.oldIndex, 1); - this.dataModel.splice(moveInfo.index, 0, bookmarkNode); - - this.endBatchUpdates(); - } else { - if (moveInfo.oldParentId == this.parentId) { - // Move out of this folder - - var index = dataModel.findIndexById(id); - if (index != -1) - dataModel.splice(index, 1); - } - - if (moveInfo.parentId == this.parentId) { - // Move to this folder - var self = this; - chrome.bookmarks.get(id, function(bookmarkNodes) { - var bookmarkNode = bookmarkNodes[0]; - dataModel.splice(bookmarkNode.index, 0, bookmarkNode); - }); - } - } - } - }, - - handleRemoved: function(id, removeInfo) { - var dataModel = this.dataModel; - var index = dataModel.findIndexById(id); - if (index != -1) - dataModel.splice(index, 1); - }, - - /** - * Workaround for http://crbug.com/40902 - * @private - */ - fixWidth_: function() { - var list = bmm.list; - if (this.loadCount_ || !list) - return; - - // The width of the list is wrong after its content has changed. - // Fortunately the reported offsetWidth is correct so we can detect the - //incorrect width. - if (list.offsetWidth != list.parentNode.clientWidth - list.offsetLeft) { - // Set the width to the correct size. This causes the relayout. - list.style.width = list.parentNode.clientWidth - list.offsetLeft + 'px'; - // Remove the temporary style.width in a timeout. Once the timer fires - // the size should not change since we already fixed the width. - window.setTimeout(function() { - list.style.width = ''; - }, 0); - } - } - }; - - /** - * The ID of the bookmark folder we are displaying. - */ - cr.defineProperty(BookmarkList, 'parentId', cr.PropertyKind.JS, - function() { - this.reload(); - }); - - /** - * The contextMenu property. - */ - cr.ui.contextMenuHandler.addContextMenuProperty(BookmarkList); - /** @type {cr.ui.Menu} */ - BookmarkList.prototype.contextMenu; - - /** - * Creates a new bookmark list item. - * @param {!BookmarkTreeNode} bookmarkNode The bookmark node this represents. - * @constructor - * @extends {cr.ui.ListItem} - */ - function BookmarkListItem(bookmarkNode) { - var el = cr.doc.createElement('div'); - el.bookmarkNode = bookmarkNode; - BookmarkListItem.decorate(el); - return el; - } - - /** - * Decorates an element as a bookmark list item. - * @param {!HTMLElement} el The element to decorate. - */ - BookmarkListItem.decorate = function(el) { - el.__proto__ = BookmarkListItem.prototype; - el.decorate(); - }; - - BookmarkListItem.prototype = { - __proto__: ListItem.prototype, - - /** @override */ - decorate: function() { - ListItem.prototype.decorate.call(this); - - var bookmarkNode = this.bookmarkNode; - - this.draggable = true; - - var labelEl = this.ownerDocument.createElement('div'); - labelEl.className = 'label'; - var labelImgWrapper = this.ownerDocument.createElement('div'); - labelImgWrapper.className = 'label-img-wrapper'; - var labelImg = this.ownerDocument.createElement('div'); - var labelText = this.ownerDocument.createElement('div'); - labelText.className = 'label-text'; - labelText.textContent = bookmarkNode.title; - - var urlEl = this.ownerDocument.createElement('div'); - urlEl.className = 'url'; - - if (bmm.isFolder(bookmarkNode)) { - this.className = 'folder'; - // TODO(pkasting): Condense folder icon resources together. - labelImg.style.content = cr.icon.getImage( - cr.isMac ? - 'chrome://theme/IDR_BOOKMARK_BAR_FOLDER' : - 'chrome://theme/IDR_FOLDER_CLOSED'); - } else { - labelImg.style.content = cr.icon.getFavicon(bookmarkNode.url); - urlEl.textContent = bookmarkNode.url; - } - - labelImgWrapper.appendChild(labelImg); - labelEl.appendChild(labelImgWrapper); - labelEl.appendChild(labelText); - this.appendChild(labelEl); - this.appendChild(urlEl); - - // Initially the ContextMenuButton was added here but it slowed down - // rendering a lot so it is now added using mouseover. - }, - - /** - * The ID of the bookmark folder we are currently showing or loading. - * @type {string} - */ - get bookmarkId() { - return this.bookmarkNode.id; - }, - - /** - * Whether the user is currently able to edit the list item. - * @type {boolean} - */ - get editing() { - return this.hasAttribute('editing'); - }, - set editing(editing) { - var oldEditing = this.editing; - if (oldEditing == editing) - return; - - var url = this.bookmarkNode.url; - var title = this.bookmarkNode.title; - var isFolder = bmm.isFolder(this.bookmarkNode); - var listItem = this; - var labelInput, urlInput; - - // Handles enter and escape which trigger reset and commit respectively. - function handleKeydown(e) { - // Make sure that the tree does not handle the key. - e.stopPropagation(); - - // Calling list.focus blurs the input which will stop editing the list - // item. - switch (e.key) { - case 'Escape': // Esc - labelInput.value = title; - if (!isFolder) - urlInput.value = url; - // fall through - cr.dispatchSimpleEvent(listItem, 'canceledit', true); - case 'Enter': - if (listItem.parentNode) - listItem.parentNode.focus(); - break; - case 'Tab': // Tab - // urlInput is the last focusable element in the page. If we - // allowed Tab focus navigation and the page loses focus, we - // couldn't give focus on urlInput programatically. So, we prevent - // Tab focus navigation. - if (document.activeElement == urlInput && !e.ctrlKey && - !e.metaKey && !e.shiftKey && !getValidURL(urlInput)) { - e.preventDefault(); - urlInput.blur(); - } - break; - } - } - - function getValidURL(input) { - var originalValue = input.value; - if (!originalValue) - return null; - if (input.validity.valid) - return originalValue; - // Blink does not do URL fix up so we manually test if prepending - // 'http://' would make the URL valid. - // https://bugs.webkit.org/show_bug.cgi?id=29235 - input.value = 'http://' + originalValue; - if (input.validity.valid) - return input.value; - // still invalid - input.value = originalValue; - return null; - } - - function handleBlur(e) { - // When the blur event happens we do not know who is getting focus so we - // delay this a bit since we want to know if the other input got focus - // before deciding if we should exit edit mode. - var doc = e.target.ownerDocument; - window.setTimeout(function() { - var activeElement = doc.hasFocus() && doc.activeElement; - if (activeElement != urlInput && activeElement != labelInput) { - listItem.editing = false; - } - }, 50); - } - - var doc = this.ownerDocument; - var labelTextEl = queryRequiredElement('.label-text', this); - var urlEl = queryRequiredElement('.url', this); - if (editing) { - this.setAttribute('editing', ''); - this.draggable = false; - - labelInput = /** @type {HTMLElement} */(doc.createElement('input')); - labelInput.placeholder = - loadTimeData.getString('name_input_placeholder'); - replaceAllChildren(labelTextEl, labelInput); - labelInput.value = title; - - if (!isFolder) { - urlInput = /** @type {HTMLElement} */(doc.createElement('input')); - urlInput.type = 'url'; - urlInput.required = true; - urlInput.placeholder = - loadTimeData.getString('url_input_placeholder'); - - // We also need a name for the input for the CSS to work. - urlInput.name = '-url-input-' + cr.createUid(); - replaceAllChildren(assert(urlEl), urlInput); - urlInput.value = url; - } - - var stopPropagation = function(e) { - e.stopPropagation(); - }; - - var eventsToStop = - ['mousedown', 'mouseup', 'contextmenu', 'dblclick', 'paste']; - eventsToStop.forEach(function(type) { - labelInput.addEventListener(type, stopPropagation); - }); - labelInput.addEventListener('keydown', handleKeydown); - labelInput.addEventListener('blur', handleBlur); - cr.ui.limitInputWidth(labelInput, this, 100, 0.5); - labelInput.focus(); - labelInput.select(); - - if (!isFolder) { - eventsToStop.forEach(function(type) { - urlInput.addEventListener(type, stopPropagation); - }); - urlInput.addEventListener('keydown', handleKeydown); - urlInput.addEventListener('blur', handleBlur); - cr.ui.limitInputWidth(urlInput, this, 200, 0.5); - } - - } else { - // Check that we have a valid URL and if not we do not change the - // editing mode. - if (!isFolder) { - var urlInput = this.querySelector('.url input'); - var newUrl = urlInput.value; - if (!newUrl) { - cr.dispatchSimpleEvent(this, 'canceledit', true); - return; - } - - newUrl = getValidURL(urlInput); - if (!newUrl) { - // In case the item was removed before getting here we should - // not alert. - if (listItem.parentNode) { - // Select the item again. - var dataModel = this.parentNode.dataModel; - var index = dataModel.indexOf(this.bookmarkNode); - var sm = this.parentNode.selectionModel; - sm.selectedIndex = sm.leadIndex = sm.anchorIndex = index; - - alert(loadTimeData.getString('invalid_url')); - } - urlInput.focus(); - urlInput.select(); - return; - } - urlEl.textContent = this.bookmarkNode.url = newUrl; - } - - this.removeAttribute('editing'); - this.draggable = true; - - labelInput = this.querySelector('.label input'); - var newLabel = labelInput.value; - labelTextEl.textContent = this.bookmarkNode.title = newLabel; - - if (isFolder) { - if (newLabel != title) { - cr.dispatchSimpleEvent(this, 'rename', true); - } - } else if (newLabel != title || newUrl != url) { - cr.dispatchSimpleEvent(this, 'edit', true); - } - } - } - }; - - return { - BookmarkList: BookmarkList, - list: /** @type {Element} */(null), // Set when decorated. - }; -});
diff --git a/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_tree.js b/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_tree.js deleted file mode 100644 index fbd74c5..0000000 --- a/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_tree.js +++ /dev/null
@@ -1,323 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - - -cr.define('bmm', function() { - 'use strict'; - - /** - * The id of the bookmark root. - * @type {string} - * @const - */ - var ROOT_ID = '0'; - - /** @const */ var Tree = cr.ui.Tree; - /** @const */ var TreeItem = cr.ui.TreeItem; - /** @const */ var localStorage = window.localStorage; - - var treeLookup = {}; - - // Manager for persisting the expanded state. - var expandedManager = /** @type {EventListener} */({ - /** - * A map of the collapsed IDs. - * @type {Object} - */ - map: 'bookmarkTreeState' in localStorage ? - /** @type {Object} */(JSON.parse(localStorage['bookmarkTreeState'])) : - {}, - - /** - * Set the collapsed state for an ID. - * @param {string} id The bookmark ID of the tree item that was expanded or - * collapsed. - * @param {boolean} expanded Whether the tree item was expanded. - */ - set: function(id, expanded) { - if (expanded) - delete this.map[id]; - else - this.map[id] = 1; - - this.save(); - }, - - /** - * @param {string} id The bookmark ID. - * @return {boolean} Whether the tree item should be expanded. - */ - get: function(id) { - return !(id in this.map); - }, - - /** - * Callback for the expand and collapse events from the tree. - * @param {!Event} e The collapse or expand event. - */ - handleEvent: function(e) { - this.set(e.target.bookmarkId, e.type == 'expand'); - }, - - /** - * Cleans up old bookmark IDs. - */ - cleanUp: function() { - for (var id in this.map) { - // If the id is no longer in the treeLookup the bookmark no longer - // exists. - if (!(id in treeLookup)) - delete this.map[id]; - } - this.save(); - }, - - timer: null, - - /** - * Saves the expanded state to the localStorage. - */ - save: function() { - clearTimeout(this.timer); - var map = this.map; - // Save in a timeout so that we can coalesce multiple changes. - this.timer = setTimeout(function() { - localStorage['bookmarkTreeState'] = JSON.stringify(map); - }, 100); - } - }); - - // Clean up once per session but wait until things settle down a bit. - setTimeout(expandedManager.cleanUp.bind(expandedManager), 1e4); - - /** - * Creates a new tree item for a bookmark node. - * @param {!Object} bookmarkNode The bookmark node. - * @constructor - * @extends {TreeItem} - */ - function BookmarkTreeItem(bookmarkNode) { - var ti = new TreeItem({ - label: bookmarkNode.title, - bookmarkNode: bookmarkNode, - // Bookmark toolbar and Other bookmarks are not draggable. - draggable: bookmarkNode.parentId != ROOT_ID - }); - ti.__proto__ = BookmarkTreeItem.prototype; - treeLookup[bookmarkNode.id] = ti; - return ti; - } - - BookmarkTreeItem.prototype = { - __proto__: TreeItem.prototype, - - /** - * The ID of the bookmark this tree item represents. - * @type {string} - */ - get bookmarkId() { - return this.bookmarkNode.id; - } - }; - - /** - * Asynchronousy adds a tree item at the correct index based on the bookmark - * backend. - * - * Since the bookmark tree only contains folders the index we get from certain - * callbacks is not very useful so we therefore have this async call which - * gets the children of the parent and adds the tree item at the desired - * index. - * - * This also exoands the parent so that newly added children are revealed. - * - * @param {!cr.ui.TreeItem} parent The parent tree item. - * @param {!cr.ui.TreeItem} treeItem The tree item to add. - * @param {Function=} opt_f A function which gets called after the item has - * been added at the right index. - */ - function addTreeItem(parent, treeItem, opt_f) { - chrome.bookmarks.getChildren(parent.bookmarkNode.id, function(children) { - var isFolder = /** - * @type {function (BookmarkTreeNode, number, - * Array<(BookmarkTreeNode)>)} - */(bmm.isFolder); - var index = children.filter(isFolder).map(function(item) { - return item.id; - }).indexOf(treeItem.bookmarkNode.id); - parent.addAt(treeItem, index); - parent.expanded = true; - if (opt_f) - opt_f(); - }); - } - - - /** - * Creates a new bookmark list. - * @param {Object=} opt_propertyBag Optional properties. - * @constructor - * @extends {cr.ui.Tree} - */ - var BookmarkTree = cr.ui.define('tree'); - - BookmarkTree.prototype = { - __proto__: Tree.prototype, - - decorate: function() { - Tree.prototype.decorate.call(this); - this.addEventListener('expand', expandedManager); - this.addEventListener('collapse', expandedManager); - - bmm.tree = this; - }, - - handleBookmarkChanged: function(id, changeInfo) { - var treeItem = treeLookup[id]; - if (treeItem) - treeItem.label = treeItem.bookmarkNode.title = changeInfo.title; - }, - - /** - * @param {string} id - * @param {ReorderInfo} reorderInfo - */ - handleChildrenReordered: function(id, reorderInfo) { - var parentItem = treeLookup[id]; - // The tree only contains folders. - var dirIds = reorderInfo.childIds.filter(function(id) { - return id in treeLookup; - }).forEach(function(id, i) { - parentItem.addAt(treeLookup[id], i); - }); - }, - - handleCreated: function(id, bookmarkNode) { - if (bmm.isFolder(bookmarkNode)) { - var parentItem = treeLookup[bookmarkNode.parentId]; - var newItem = new BookmarkTreeItem(bookmarkNode); - addTreeItem(parentItem, newItem); - } - }, - - /** - * @param {string} id - * @param {MoveInfo} moveInfo - */ - handleMoved: function(id, moveInfo) { - var treeItem = treeLookup[id]; - if (treeItem) { - var oldParentItem = treeLookup[moveInfo.oldParentId]; - oldParentItem.remove(treeItem); - var newParentItem = treeLookup[moveInfo.parentId]; - // The tree only shows folders so the index is not the index we want. We - // therefore get the children need to adjust the index. - addTreeItem(newParentItem, treeItem); - } - }, - - handleRemoved: function(id, removeInfo) { - var parentItem = treeLookup[removeInfo.parentId]; - var itemToRemove = treeLookup[id]; - if (parentItem && itemToRemove) - parentItem.remove(itemToRemove); - }, - - insertSubtree: function(folder) { - if (!bmm.isFolder(folder)) - return; - var children = folder.children; - this.handleCreated(folder.id, folder); - for (var i = 0; i < children.length; i++) { - var child = children[i]; - this.insertSubtree(child); - } - }, - - /** - * Returns the bookmark node with the given ID. The tree only maintains - * folder nodes. - * @param {string} id The ID of the node to find. - * @return {BookmarkTreeNode} The bookmark tree node or null if not found. - */ - getBookmarkNodeById: function(id) { - var treeItem = treeLookup[id]; - if (treeItem) - return treeItem.bookmarkNode; - return null; - }, - - /** - * Returns the selected bookmark folder node as an array. - * @type {!Array} Array of bookmark nodes. - */ - get selectedFolders() { - return this.selectedItem && this.selectedItem.bookmarkNode ? - [this.selectedItem.bookmarkNode] : []; - }, - - /** - * Fetches the bookmark items and builds the tree control. - */ - reload: function() { - /** - * Recursive helper function that adds all the directories to the - * parentTreeItem. - * @param {!cr.ui.Tree|!cr.ui.TreeItem} parentTreeItem The parent tree - * element to append to. - * @param {!Array<BookmarkTreeNode>} bookmarkNodes A list of bookmark - * nodes to be added. - * @return {boolean} Whether any directories where added. - */ - function buildTreeItems(parentTreeItem, bookmarkNodes) { - var hasDirectories = false; - for (var i = 0, bookmarkNode; bookmarkNode = bookmarkNodes[i]; i++) { - if (bmm.isFolder(bookmarkNode)) { - hasDirectories = true; - var item = new BookmarkTreeItem(bookmarkNode); - parentTreeItem.add(item); - var children = assert(bookmarkNode.children); - var anyChildren = buildTreeItems(item, children); - item.expanded = anyChildren && expandedManager.get(bookmarkNode.id); - } - } - return hasDirectories; - } - - var self = this; - chrome.bookmarkManagerPrivate.getSubtree('', true, function(root) { - self.clear(); - buildTreeItems(self, root[0].children); - cr.dispatchSimpleEvent(self, 'load'); - }); - }, - - /** - * Clears the tree. - */ - clear: function() { - // Remove all fields without recreating the object since other code - // references it. - for (var id in treeLookup) { - delete treeLookup[id]; - } - this.textContent = ''; - }, - - /** @override */ - remove: function(child) { - Tree.prototype.remove.call(this, child); - if (child.bookmarkNode) - delete treeLookup[child.bookmarkNode.id]; - } - }; - - return { - BookmarkTree: BookmarkTree, - BookmarkTreeItem: BookmarkTreeItem, - treeLookup: treeLookup, - tree: /** @type {Element} */(null), // Set when decorated. - ROOT_ID: ROOT_ID - }; -});
diff --git a/chrome/browser/resources/bookmark_manager/js/bmm_test.html b/chrome/browser/resources/bookmark_manager/js/bmm_test.html deleted file mode 100644 index 00d4108..0000000 --- a/chrome/browser/resources/bookmark_manager/js/bmm_test.html +++ /dev/null
@@ -1,113 +0,0 @@ -<!doctype html> -<html> -<head> -<!-- TODO(arv): Check in Closure unit tests and make this run as part of the - tests --> -<link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> -<script src="https://cdn.rawgit.com/google/closure-library/master/closure/goog/base.js"></script> -<script src="../../../../../ui/webui/resources/js/cr.js"></script> -<script src="bmm.js"></script> -<title>Bookmark Manager Loading Test</title> -<script> - -goog.require('goog.testing.jsunit'); -goog.require('goog.testing.AsyncTestCase'); - -</script> -</head> -<body> -<script> - -var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(document.title); - -var tree = { - id: 0, - children: [ - { - id: 1, - children: [ - {id: 2}, - {id: 3, children: []} - ] - }, - {id: 4}, - {id: 5} - ] -}; - -// Mock chrome.bookmarkManagerPrivate.getSubtree -chrome = chrome || {}; -chrome.bookmarkManagerPrivate = chrome.bookmarkManagerPrivate || {}; - -var callbacks = {}; - -chrome.bookmarkManagerPrivate.getSubtree = function(id, foldersOnly, callback) { - callbacks[id] = callbacks[id] || []; - callbacks[id].push(callback); - callbacks[id].$calls = callbacks[id].$calls ? callbacks[id].$calls++ : 1; -}; - -chrome.bookmarkManagerPrivate.getSubtree.load = function(node) { - // getSubtree gets the root tree when id is ''. - var id = node.id; - if (id == tree.id) - id = ''; - for (var i = 0; i < callbacks[id].length; i++) { - callbacks[id][i].call(null, [node]); - } -}; - -function continueTesting() { - asyncTestCase.continueTesting(); -} - -function testLoad() { - var calls1 = 0; - var calls2 = 0; - function f1(node) { - calls1++; - assertEquals(tree, node); - } - function f2(node) { - calls2++; - assertEquals(tree, node); - } - - var p = bmm.loadTree(); - var p2 = bmm.loadTree(); - var r = [ - p.then(f1), - p2.then(f2), - ]; - - chrome.bookmarkManagerPrivate.getSubtree.load(tree); - - var root = Promise.all(r).then(function() { - assertEquals(1, calls1); - assertEquals(1, calls2); - assertEquals(1, callbacks[''].$calls); - }); - - - var calls3 = 0; - function f3(node) { - calls3++; - assertEquals(tree.children[0], node); - } - - var p3 = bmm.loadSubtree(1); - var s = p3.then(f3); - - chrome.bookmarkManagerPrivate.getSubtree.load(tree.children[0]); - - var subtree = s.then(function() { - assertEquals(1, calls3); - assertEquals(1, callbacks[1].$calls); - }); - - Promise.all([root, subtree]).then(continueTesting); -} - -</script> -</body> -</html>
diff --git a/chrome/browser/resources/bookmark_manager/js/compiled_resources2.gyp b/chrome/browser/resources/bookmark_manager/js/compiled_resources2.gyp deleted file mode 100644 index 49b0ce3..0000000 --- a/chrome/browser/resources/bookmark_manager/js/compiled_resources2.gyp +++ /dev/null
@@ -1,59 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -{ - 'targets': [ - { - 'target_name': 'bookmark_manager', - 'variables': { - 'script_args': ['--custom_sources'], - 'source_files': [ - '<(DEPTH)/third_party/jstemplate/util.js', - '<(DEPTH)/ui/webui/resources/js/assert.js', - '<(DEPTH)/third_party/jstemplate/jsevalcontext.js', - '<(DEPTH)/third_party/jstemplate/jstemplate.js', - '<(DEPTH)/ui/webui/resources/js/cr.js', - '<(DEPTH)/ui/webui/resources/js/cr/event_target.js', - '<(DEPTH)/ui/webui/resources/js/cr/link_controller.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/array_data_model.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/command.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/context_menu_button.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/context_menu_handler.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_outline_manager.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/list.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/list_item.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_controller.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_model.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/menu.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_button.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_item.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/position_util.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/splitter.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/touch_handler.js', - '<(DEPTH)/ui/webui/resources/js/cr/ui/tree.js', - '<(DEPTH)/ui/webui/resources/js/event_tracker.js', - '<(DEPTH)/ui/webui/resources/js/i18n_template_no_process.js', - '<(DEPTH)/ui/webui/resources/js/load_time_data.js', - '<(DEPTH)/ui/webui/resources/js/parse_html_subset.js', - '<(DEPTH)/ui/webui/resources/js/promise_resolver.js', - '<(DEPTH)/ui/webui/resources/js/util.js', - '<(DEPTH)/ui/webui/resources/js/icon.js', - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/bmm.js', - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_list.js', - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_tree.js', - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/dnd.js', - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/main.js', - '<(DEPTH)/third_party/closure_compiler/externs/bookmark_manager_private.js', - '<(DEPTH)/third_party/closure_compiler/externs//chrome.js', - '<(DEPTH)/third_party/closure_compiler/externs//chrome_send.js', - '<(DEPTH)/third_party/closure_compiler/externs//chrome_extensions.js', - '<(DEPTH)/third_party/closure_compiler/externs//metrics_private.js', - '<(DEPTH)/third_party/closure_compiler/externs//system_private.js', - '<(DEPTH)/ui/webui/resources/js/template_data_externs.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], - } - ], -}
diff --git a/chrome/browser/resources/bookmark_manager/js/dnd.js b/chrome/browser/resources/bookmark_manager/js/dnd.js deleted file mode 100644 index 9a97faf0..0000000 --- a/chrome/browser/resources/bookmark_manager/js/dnd.js +++ /dev/null
@@ -1,562 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('dnd', function() { - 'use strict'; - - /** @const */ var BookmarkList = bmm.BookmarkList; - /** @const */ var ListItem = cr.ui.ListItem; - /** @const */ var TreeItem = cr.ui.TreeItem; - - /** - * Enumeration of valid drop locations relative to an element. These are - * bit masks to allow combining multiple locations in a single value. - * @enum {number} - * @const - */ - var DropPosition = { - NONE: 0, - ABOVE: 1, - ON: 2, - BELOW: 4 - }; - - /** - * @type {Object} Drop information calculated in |handleDragOver|. - */ - var dropDestination = null; - - /** - * @type {number} Timer id used to help minimize flicker. - */ - var removeDropIndicatorTimer; - - /** - * The element currently targeted by a touch. - * @type {Element} - */ - var currentTouchTarget; - - /** - * The element that had a style applied it to indicate the drop location. - * This is used to easily remove the style when necessary. - * @type {Element} - */ - var lastIndicatorElement; - - /** - * The style that was applied to indicate the drop location. - * @type {?string} - */ - var lastIndicatorClassName; - - var dropIndicator = { - /** - * Applies the drop indicator style on the target element and stores that - * information to easily remove the style in the future. - */ - addDropIndicatorStyle: function(indicatorElement, position) { - var indicatorStyleName = position == DropPosition.ABOVE ? 'drag-above' : - position == DropPosition.BELOW ? 'drag-below' : - 'drag-on'; - - lastIndicatorElement = indicatorElement; - lastIndicatorClassName = indicatorStyleName; - - indicatorElement.classList.add(indicatorStyleName); - }, - - /** - * Clears the drop indicator style from the last element was the drop target - * so the drop indicator is no longer for that element. - */ - removeDropIndicatorStyle: function() { - if (!lastIndicatorElement || !lastIndicatorClassName) - return; - lastIndicatorElement.classList.remove(lastIndicatorClassName); - lastIndicatorElement = null; - lastIndicatorClassName = null; - }, - - /** - * Displays the drop indicator on the current drop target to give the - * user feedback on where the drop will occur. - */ - update: function(dropDest) { - window.clearTimeout(removeDropIndicatorTimer); - - var indicatorElement = dropDest.element; - var position = dropDest.position; - if (dropDest.element instanceof BookmarkList) { - // For an empty bookmark list use 'drop-above' style. - position = DropPosition.ABOVE; - } else if (dropDest.element instanceof TreeItem) { - indicatorElement = indicatorElement.querySelector('.tree-row'); - } - dropIndicator.removeDropIndicatorStyle(); - dropIndicator.addDropIndicatorStyle(indicatorElement, position); - }, - - /** - * Stop displaying the drop indicator. - */ - finish: function() { - // The use of a timeout is in order to reduce flickering as we move - // between valid drop targets. - window.clearTimeout(removeDropIndicatorTimer); - removeDropIndicatorTimer = window.setTimeout(function() { - dropIndicator.removeDropIndicatorStyle(); - }, 100); - } - }; - - /** - * Delay for expanding folder when pointer hovers on folder in tree view in - * milliseconds. - * @type {number} - * @const - */ - // TODO(yosin): EXPAND_FOLDER_DELAY should follow system settings. 400ms is - // taken from Windows default settings. - var EXPAND_FOLDER_DELAY = 400; - - /** - * The timestamp when the mouse was over a folder during a drag operation. - * Used to open the hovered folder after a certain time. - * @type {number} - */ - var lastHoverOnFolderTimeStamp = 0; - - /** - * Expand a folder if the user has hovered for longer than the specified - * time during a drag action. - */ - function updateAutoExpander(eventTimeStamp, overElement) { - // Expands a folder in tree view when pointer hovers on it longer than - // EXPAND_FOLDER_DELAY. - var hoverOnFolderTimeStamp = lastHoverOnFolderTimeStamp; - lastHoverOnFolderTimeStamp = 0; - if (hoverOnFolderTimeStamp) { - if (eventTimeStamp - hoverOnFolderTimeStamp >= EXPAND_FOLDER_DELAY) - overElement.expanded = true; - else - lastHoverOnFolderTimeStamp = hoverOnFolderTimeStamp; - } else if (overElement instanceof TreeItem && - bmm.isFolder(overElement.bookmarkNode) && - overElement.hasChildren && - !overElement.expanded) { - lastHoverOnFolderTimeStamp = eventTimeStamp; - } - } - - /** - * Stores the information about the bookmark and folders being dragged. - * @type {Object} - */ - var dragData = null; - var dragInfo = { - handleChromeDragEnter: function(newDragData) { - dragData = newDragData; - }, - clearDragData: function() { - dragData = null; - }, - isDragValid: function() { - return !!dragData; - }, - isSameProfile: function() { - return dragData && dragData.sameProfile; - }, - isDraggingFolders: function() { - return dragData && dragData.elements.some(function(node) { - return !node.url; - }); - }, - isDraggingBookmark: function(bookmarkId) { - return dragData && dragData.elements.some(function(node) { - return node.id == bookmarkId; - }); - }, - isDraggingChildBookmark: function(folderId) { - return dragData && dragData.elements.some(function(node) { - return node.parentId == folderId; - }); - }, - isDraggingFolderToDescendant: function(bookmarkNode) { - return dragData && dragData.elements.some(function(node) { - var dragFolder = bmm.treeLookup[node.id]; - var dragFolderNode = dragFolder && dragFolder.bookmarkNode; - return dragFolderNode && bmm.contains(dragFolderNode, bookmarkNode); - }); - } - }; - - /** - * External function to select folders or bookmarks after a drop action. - * @type {?Function} - */ - var selectItemsAfterUserAction = null; - - function getBookmarkElement(el) { - while (el && !el.bookmarkNode) { - el = el.parentNode; - } - return el; - } - - // If we are over the list and the list is showing search result, we cannot - // drop. - function isOverSearch(overElement) { - return bmm.list.isSearch() && bmm.list.contains(overElement); - } - - /** - * Determines the valid drop positions for the given target element. - * @param {!HTMLElement} overElement The element that we are currently - * dragging over. - * @return {DropPosition} An bit field enumeration of valid drop locations. - */ - function calculateValidDropTargets(overElement) { - // Don't allow dropping if there is an ephemeral item being edited. - if (bmm.list.hasEphemeral()) - return DropPosition.NONE; - - if (!dragInfo.isDragValid() || isOverSearch(overElement)) - return DropPosition.NONE; - - if (dragInfo.isSameProfile() && - (dragInfo.isDraggingBookmark(overElement.bookmarkNode.id) || - dragInfo.isDraggingFolderToDescendant(overElement.bookmarkNode))) { - return DropPosition.NONE; - } - - var canDropInfo = calculateDropAboveBelow(overElement); - if (canDropOn(overElement)) - canDropInfo |= DropPosition.ON; - - return canDropInfo; - } - - function calculateDropAboveBelow(overElement) { - if (overElement instanceof BookmarkList) - return DropPosition.NONE; - - // We cannot drop between Bookmarks bar and Other bookmarks. - if (overElement.bookmarkNode.parentId == bmm.ROOT_ID) - return DropPosition.NONE; - - var isOverTreeItem = overElement instanceof TreeItem; - var isOverExpandedTree = isOverTreeItem && overElement.expanded; - var isDraggingFolders = dragInfo.isDraggingFolders(); - - // We can only drop between items in the tree if we have any folders. - if (isOverTreeItem && !isDraggingFolders) - return DropPosition.NONE; - - // When dragging from a different profile we do not need to consider - // conflicts between the dragged items and the drop target. - if (!dragInfo.isSameProfile()) { - // Don't allow dropping below an expanded tree item since it is confusing - // to the user anyway. - return isOverExpandedTree ? DropPosition.ABOVE : - (DropPosition.ABOVE | DropPosition.BELOW); - } - - var resultPositions = DropPosition.NONE; - - // Cannot drop above if the item above is already in the drag source. - var previousElem = overElement.previousElementSibling; - if (!previousElem || !dragInfo.isDraggingBookmark(previousElem.bookmarkId)) - resultPositions |= DropPosition.ABOVE; - - // Don't allow dropping below an expanded tree item since it is confusing - // to the user anyway. - if (isOverExpandedTree) - return resultPositions; - - // Cannot drop below if the item below is already in the drag source. - var nextElement = overElement.nextElementSibling; - if (!nextElement || !dragInfo.isDraggingBookmark(nextElement.bookmarkId)) - resultPositions |= DropPosition.BELOW; - - return resultPositions; - } - - /** - * Determine whether we can drop the dragged items on the drop target. - * @param {!HTMLElement} overElement The element that we are currently - * dragging over. - * @return {boolean} Whether we can drop the dragged items on the drop - * target. - */ - function canDropOn(overElement) { - // We can only drop on a folder. - if (!bmm.isFolder(overElement.bookmarkNode)) - return false; - - if (!dragInfo.isSameProfile()) - return true; - - if (overElement instanceof BookmarkList) { - // We are trying to drop an item past the last item. This is - // only allowed if dragged item is different from the last item - // in the list. - var listItems = bmm.list.items; - var len = listItems.length; - if (!len || !dragInfo.isDraggingBookmark(listItems[len - 1].bookmarkId)) - return true; - } - - return !dragInfo.isDraggingChildBookmark(overElement.bookmarkNode.id); - } - - /** - * Callback for the dragstart event. - * @param {Event} e The dragstart event. - */ - function handleDragStart(e) { - // Determine the selected bookmarks. - var target = e.target; - var draggedNodes = []; - var isFromTouch = target == currentTouchTarget; - - if (target instanceof ListItem) { - // Use selected items. - draggedNodes = - /** @type {cr.ui.List} */ (target.parentNode).selectedItems; - } else if (target instanceof TreeItem) { - draggedNodes.push(target.bookmarkNode); - } - - // We manage starting the drag by using the extension API. - e.preventDefault(); - - // Do not allow dragging if there is an ephemeral item being edited at the - // moment. - if (bmm.list.hasEphemeral()) - return; - - if (draggedNodes.length) { - // If we are dragging a single link, we can do the *Link* effect. - // Otherwise, we only allow copy and move. - e.dataTransfer.effectAllowed = draggedNodes.length == 1 && - !bmm.isFolder(draggedNodes[0]) ? 'copyMoveLink' : 'copyMove'; - - chrome.bookmarkManagerPrivate.startDrag(draggedNodes.map(function(node) { - return node.id; - }), isFromTouch); - var dragTarget = getBookmarkElement(e.target); - if (dragTarget instanceof ListItem || - dragTarget instanceof BookmarkList) { - chrome.metricsPrivate.recordUserAction( - 'BookmarkManager_StartDragFromList'); - } else if (dragTarget instanceof TreeItem) { - chrome.metricsPrivate.recordUserAction( - 'BookmarkManager_StartDragFromTree'); - } - - chrome.metricsPrivate.recordSmallCount( - 'BookmarkManager.NumDragged', draggedNodes.length); - } - } - - function handleDragEnter(e) { - e.preventDefault(); - } - - /** - * Calback for the dragover event. - * @param {Event} e The dragover event. - */ - function handleDragOver(e) { - // Allow DND on text inputs. - if (e.target.tagName != 'INPUT') { - // The default operation is to allow dropping links etc to do navigation. - // We never want to do that for the bookmark manager. - e.preventDefault(); - - // Set to none. This will get set to something if we can do the drop. - e.dataTransfer.dropEffect = 'none'; - } - - if (!dragInfo.isDragValid()) - return; - - var overElement = getBookmarkElement(e.target) || - (e.target == bmm.list ? bmm.list : null); - if (!overElement) - return; - - updateAutoExpander(e.timeStamp, overElement); - - var canDropInfo = calculateValidDropTargets(overElement); - if (canDropInfo == DropPosition.NONE) - return; - - // Now we know that we can drop. Determine if we will drop above, on or - // below based on mouse position etc. - - dropDestination = calcDropPosition(e.clientY, overElement, canDropInfo); - if (!dropDestination) { - e.dataTransfer.dropEffect = 'none'; - return; - } - - e.dataTransfer.dropEffect = dragInfo.isSameProfile() ? 'move' : 'copy'; - dropIndicator.update(dropDestination); - } - - /** - * This function determines where the drop will occur relative to the element. - * @return {?Object} If no valid drop position is found, null, otherwise - * an object containing the following parameters: - * element - The target element that will receive the drop. - * position - A |DropPosition| relative to the |element|. - */ - function calcDropPosition(elementClientY, overElement, canDropInfo) { - if (overElement instanceof BookmarkList) { - // Dropping on the BookmarkList either means dropping below the last - // bookmark element or on the list itself if it is empty. - var length = overElement.items.length; - if (length) - return { - element: overElement.getListItemByIndex(length - 1), - position: DropPosition.BELOW - }; - return {element: overElement, position: DropPosition.ON}; - } - - var above = canDropInfo & DropPosition.ABOVE; - var below = canDropInfo & DropPosition.BELOW; - var on = canDropInfo & DropPosition.ON; - var rect = overElement.getBoundingClientRect(); - var yRatio = (elementClientY - rect.top) / rect.height; - - if (above && (yRatio <= .25 || yRatio <= .5 && (!below || !on))) - return {element: overElement, position: DropPosition.ABOVE}; - if (below && (yRatio > .75 || yRatio > .5 && (!above || !on))) - return {element: overElement, position: DropPosition.BELOW}; - if (on) - return {element: overElement, position: DropPosition.ON}; - return null; - } - - function calculateDropInfo(eventTarget, dropDestination) { - if (!dropDestination || !dragInfo.isDragValid()) - return null; - - var dropPos = dropDestination.position; - var relatedNode = dropDestination.element.bookmarkNode; - var dropInfoResult = { - selectTarget: null, - selectedTreeId: -1, - parentId: dropPos == DropPosition.ON ? relatedNode.id : - relatedNode.parentId, - index: -1, - relatedIndex: -1 - }; - - // Try to find the index in the dataModel so we don't have to always keep - // the index for the list items up to date. - var overElement = getBookmarkElement(eventTarget); - if (overElement instanceof ListItem) { - dropInfoResult.relatedIndex = - overElement.parentNode.dataModel.indexOf(relatedNode); - dropInfoResult.selectTarget = bmm.list; - } else if (overElement instanceof BookmarkList) { - dropInfoResult.relatedIndex = overElement.dataModel.length - 1; - dropInfoResult.selectTarget = bmm.list; - } else { - // Tree - dropInfoResult.relatedIndex = relatedNode.index; - dropInfoResult.selectTarget = bmm.tree; - dropInfoResult.selectedTreeId = - bmm.tree.selectedItem ? bmm.tree.selectedItem.bookmarkId : null; - } - - if (dropPos == DropPosition.ABOVE) - dropInfoResult.index = dropInfoResult.relatedIndex; - else if (dropPos == DropPosition.BELOW) - dropInfoResult.index = dropInfoResult.relatedIndex + 1; - - return dropInfoResult; - } - - function handleDragLeave(e) { - dropIndicator.finish(); - } - - function handleDrop(e) { - var dropInfo = calculateDropInfo(e.target, dropDestination); - if (dropInfo) { - selectItemsAfterUserAction(dropInfo.selectTarget, - dropInfo.selectedTreeId); - if (dropInfo.index != -1) - chrome.bookmarkManagerPrivate.drop(dropInfo.parentId, dropInfo.index); - else - chrome.bookmarkManagerPrivate.drop(dropInfo.parentId); - - e.preventDefault(); - - var dragTarget = getBookmarkElement(e.target); - var action; - if (dragTarget instanceof ListItem || - dragTarget instanceof BookmarkList) { - action = 'BookmarkManager_DropToList'; - if (dropDestination.position == DropPosition.ON) - action = 'BookmarkManager_DropToListItem'; - } else if (dragTarget instanceof TreeItem) { - action = 'BookmarkManager_DropToTree'; - if (dropDestination.position == DropPosition.ON) - action = 'BookmarkManager_DropToTreeItem'; - } - if (action) - chrome.metricsPrivate.recordUserAction(action); - } - dropDestination = null; - dropIndicator.finish(); - } - - function setCurrentTouchTarget(e) { - // Only set a new target for a single touch point. - if (e.touches.length == 1) - currentTouchTarget = getBookmarkElement(e.target); - } - - function clearCurrentTouchTarget(e) { - if (getBookmarkElement(e.target) == currentTouchTarget) - currentTouchTarget = null; - } - - function clearDragData() { - dragInfo.clearDragData(); - dropDestination = null; - } - - function init(selectItemsAfterUserActionFunction) { - function deferredClearData() { - setTimeout(clearDragData, 0); - } - - selectItemsAfterUserAction = selectItemsAfterUserActionFunction; - - document.addEventListener('dragstart', handleDragStart); - document.addEventListener('dragenter', handleDragEnter); - document.addEventListener('dragover', handleDragOver); - document.addEventListener('dragleave', handleDragLeave); - document.addEventListener('drop', handleDrop); - document.addEventListener('dragend', deferredClearData); - document.addEventListener('mouseup', deferredClearData); - document.addEventListener('mousedown', clearCurrentTouchTarget); - document.addEventListener('touchcancel', clearCurrentTouchTarget); - document.addEventListener('touchend', clearCurrentTouchTarget); - document.addEventListener('touchstart', setCurrentTouchTarget); - - chrome.bookmarkManagerPrivate.onDragEnter.addListener( - dragInfo.handleChromeDragEnter); - chrome.bookmarkManagerPrivate.onDragLeave.addListener(deferredClearData); - chrome.bookmarkManagerPrivate.onDrop.addListener(deferredClearData); - } - return {init: init}; -});
diff --git a/chrome/browser/resources/bookmark_manager/js/main.js b/chrome/browser/resources/bookmark_manager/js/main.js deleted file mode 100644 index 9da605a..0000000 --- a/chrome/browser/resources/bookmark_manager/js/main.js +++ /dev/null
@@ -1,1547 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -(function() { -'use strict'; - -/** @const */ var BookmarkList = bmm.BookmarkList; -/** @const */ var BookmarkTree = bmm.BookmarkTree; -/** @const */ var Command = cr.ui.Command; -/** @const */ var LinkKind = cr.LinkKind; -/** @const */ var ListItem = cr.ui.ListItem; -/** @const */ var Menu = cr.ui.Menu; -/** @const */ var MenuButton = cr.ui.MenuButton; -/** @const */ var Splitter = cr.ui.Splitter; -/** @const */ var TreeItem = cr.ui.TreeItem; - -/** - * An array containing the BookmarkTreeNodes that were deleted in the last - * deletion action. This is used for implementing undo. - * @type {?{nodes: Array<Array<BookmarkTreeNode>>, target: EventTarget}} - */ -var lastDeleted; - -/** - * - * Holds the last DOMTimeStamp when mouse pointer hovers on folder in tree - * view. Zero means pointer doesn't hover on folder. - * @type {number} - */ -var lastHoverOnFolderTimeStamp = 0; - -/** - * Holds a function that will undo that last action, if global undo is enabled. - * @type {Function} - */ -var performGlobalUndo; - -/** - * Holds a link controller singleton. Use getLinkController() rarther than - * accessing this variabie. - * @type {cr.LinkController} - */ -var linkController; - -/** - * Incognito mode availability can take the following values: , - * - 'enabled' for when both normal and incognito modes are available; - * - 'disabled' for when incognito mode is disabled; - * - 'forced' for when incognito mode is forced (normal mode is unavailable). - */ -var incognitoModeAvailability = 'enabled'; - -/** - * Whether bookmarks can be modified. - * @type {boolean} - */ -var canEdit = true; - -/** - * @type {TreeItem} - * @const - */ -var searchTreeItem = new TreeItem({ - bookmarkId: 'q=' -}); - -/** - * @type {boolean} - */ -var firstLoad = true; - -/** - * Command shortcut mapping. - * @const - */ -var commandShortcutMap = cr.isMac ? { - 'edit': 'Enter', - // On Mac we also allow Meta+Backspace. - 'delete': 'Delete Backspace Meta|Backspace', - 'open-in-background-tab': 'Meta|Enter', - 'open-in-new-tab': 'Shift|Meta|Enter', - 'open-in-same-window': 'Meta|Down', - 'open-in-new-window': 'Shift|Enter', - 'rename-folder': 'Enter', - // Global undo is Command-Z. It is not in any menu. - 'undo': 'Meta|z', -} : { - 'edit': 'F2', - 'delete': 'Delete', - 'open-in-background-tab': 'Ctrl|Enter', - 'open-in-new-tab': 'Shift|Ctrl|Enter', - 'open-in-same-window': 'Enter', - 'open-in-new-window': 'Shift|Enter', - 'rename-folder': 'F2', - // Global undo is Ctrl-Z. It is not in any menu. - 'undo': 'Ctrl|z', -}; - -/** - * Mapping for folder id to suffix of UMA. These names will be appeared - * after "BookmarkManager_NavigateTo_" in UMA dashboard. - * @const - */ -var folderMetricsNameMap = { - '1': 'BookmarkBar', - '2': 'Other', - '3': 'Mobile', - 'q=': 'Search', - 'subfolder': 'SubFolder', -}; - -/** - * Adds an event listener to a node that will remove itself after firing once. - * @param {!Element} node The DOM node to add the listener to. - * @param {string} name The name of the event listener to add to. - * @param {function(Event)} handler Function called when the event fires. - */ -function addOneShotEventListener(node, name, handler) { - var f = function(e) { - handler(e); - node.removeEventListener(name, f); - }; - node.addEventListener(name, f); -} - -// Get the localized strings from the backend via bookmakrManagerPrivate API. -function loadLocalizedStrings(data) { - // The strings may contain & which we need to strip. - for (var key in data) { - data[key] = data[key].replace(/&/, ''); - } - - loadTimeData.data = data; - i18nTemplate.process(document, loadTimeData); - - searchTreeItem.label = loadTimeData.getString('search'); - searchTreeItem.icon = isRTL() ? 'images/bookmark_manager_search_rtl.png' : - 'images/bookmark_manager_search.png'; -} - -/** - * Updates the location hash to reflect the current state of the application. - */ -function updateHash() { - window.location.hash = bmm.tree.selectedItem.bookmarkId; - updateAllCommands(); -} - -/** - * Navigates to a bookmark ID. - * @param {string} id The ID to navigate to. - * @param {function()=} opt_callback Function called when list view loaded or - * displayed specified folder. - */ -function navigateTo(id, opt_callback) { - window.location.hash = id; - - var sameParent = bmm.list.parentId == id; - if (!sameParent) - updateParentId(id); - - updateAllCommands(); - - var metricsId = folderMetricsNameMap[id.replace(/^q=.*/, 'q=')] || - folderMetricsNameMap['subfolder']; - chrome.metricsPrivate.recordUserAction( - 'BookmarkManager_NavigateTo_' + metricsId); - - if (opt_callback) { - if (sameParent) - opt_callback(); - else - addOneShotEventListener(bmm.list, 'load', opt_callback); - } -} - -/** - * Updates the parent ID of the bookmark list and selects the correct tree item. - * @param {string} id The id. - */ -function updateParentId(id) { - // Setting list.parentId fires 'load' event. - bmm.list.parentId = id; - - // When tree.selectedItem changed, tree view calls navigatTo() then it - // calls updateHash() when list view displayed specified folder. - bmm.tree.selectedItem = bmm.treeLookup[id] || bmm.tree.selectedItem; -} - -// Process the location hash. This is called by onhashchange and when the page -// is first loaded. -function processHash() { - var wasFirstLoad = firstLoad; - firstLoad = false; - var id = window.location.hash.slice(1); - if (!id) { - // If we do not have a hash, select first item in the tree. - id = bmm.tree.items[0].bookmarkId; - } - - var valid = false; - if (/^e=/.test(id)) { - id = id.slice(2); - - // If hash contains e=, edit the item specified. - chrome.bookmarks.get(id, function(bookmarkNodes) { - // Verify the node to edit is a valid node. - if (!bookmarkNodes || bookmarkNodes.length != 1) - return; - var bookmarkNode = bookmarkNodes[0]; - - // After the list reloads, edit the desired bookmark. - var editBookmark = function() { - var index = bmm.list.dataModel.findIndexById(bookmarkNode.id); - if (index != -1) { - var sm = bmm.list.selectionModel; - sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; - scrollIntoViewAndMakeEditable(index); - } - }; - - var parentId = assert(bookmarkNode.parentId); - navigateTo(parentId, editBookmark); - }); - - // We handle the two cases of navigating to the bookmark to be edited - // above. Don't run the standard navigation code below. - return; - } else if (/^q=/.test(id)) { - // In case we got a search hash, update the text input and the - // bmm.treeLookup to use the new id. - setSearch(id.slice(2)); - valid = true; - } - - // Navigate to bookmark 'id' (which may be a query of the form q=query). - if (valid) { - updateParentId(id); - } else { - // We need to verify that this is a correct ID. - chrome.bookmarks.get(id, function(items) { - if (items && items.length == 1) - updateParentId(id); - - if (wasFirstLoad) { - setTimeout(function() { - chrome.metricsPrivate.recordTime( - 'BookmarkManager.ResultsRenderedTime', - Math.floor(window.performance.now())); - }); - } - }); - } -} - -// Activate is handled by the open-in-same-window-command. -function handleDoubleClickForList(e) { - if (e.button == 0) - /** @type {Command} */ ($('open-in-same-window-command')).execute(); -} - -// The list dispatches an event when the user clicks on the URL or the Show in -// folder part. -function handleUrlClickedForList(e) { - getLinkController().openUrlFromEvent(e.url, e.originalEvent); - chrome.bookmarkManagerPrivate.recordLaunch(); -} - -function handleSearch(e) { - setSearch(this.value); -} - -/** - * Navigates to the search results for the search text. - * @param {string} searchText The text to search for. - */ -function setSearch(searchText) { - if (searchText) { - // Only update search item if we have a search term. We never want the - // search item to be for an empty search. - delete bmm.treeLookup[searchTreeItem.bookmarkId]; - var id = searchTreeItem.bookmarkId = 'q=' + searchText; - bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; - } - - var input = $('term'); - // Do not update the input if the user is actively using the text input. - if (document.activeElement != input) - input.value = searchText; - - if (searchText) { - bmm.tree.add(searchTreeItem); - bmm.tree.selectedItem = searchTreeItem; - } else { - // Go "home". - bmm.tree.selectedItem = bmm.tree.items[0]; - id = bmm.tree.selectedItem.bookmarkId; - } - - navigateTo(id); -} - -/** - * This returns the user visible path to the folder where the bookmark is - * located. - * @param {number} parentId The ID of the parent folder. - * @return {string|undefined} The path to the the bookmark, - */ -function getFolder(parentId) { - var parentNode = bmm.tree.getBookmarkNodeById(parentId); - if (parentNode) { - var s = parentNode.title; - if (parentNode.parentId != bmm.ROOT_ID) { - return getFolder(parentNode.parentId) + '/' + s; - } - return s; - } -} - -function handleLoadForTree(e) { - processHash(); -} - -/** - * Returns a promise for all the URLs in the {@code nodes} and the direct - * children of {@code nodes}. - * @param {!Array<BookmarkTreeNode>} nodes . - * @return {!Promise<Array<string>>} . - */ -function getAllUrls(nodes) { - var urls = []; - - // Adds the node and all its direct children. - // TODO(deepak.m1): Here node should exist. When we delete the nodes then - // datamodel gets updated but still it shows deleted items as selected items - // and accessing those nodes throws chrome.runtime.lastError. This cause - // undefined value for node. Please refer https://crbug.com/480935. - function addNodes(node) { - if (!node || node.id == 'new') - return; - - if (node.children) { - node.children.forEach(function(child) { - if (!bmm.isFolder(child)) - urls.push(child.url); - }); - } else { - urls.push(node.url); - } - } - - // Get a future promise for the nodes. - var promises = nodes.map(function(node) { - if (bmm.isFolder(assert(node))) - return bmm.loadSubtree(node.id); - // Not a folder so we already have all the data we need. - return Promise.resolve(node); - }); - - return Promise.all(promises).then(function(nodes) { - nodes.forEach(addNodes); - return urls; - }); -} - -/** - * Returns the nodes (non recursive) to use for the open commands. - * @param {HTMLElement} target - * @return {!Array<BookmarkTreeNode>} - */ -function getNodesForOpen(target) { - if (target == bmm.tree) { - if (bmm.tree.selectedItem != searchTreeItem) - return bmm.tree.selectedFolders; - // Fall through to use all nodes in the list. - } else { - var items = bmm.list.selectedItems; - if (items.length) - return items; - } - - // The list starts off with a null dataModel. We can get here during startup. - if (!bmm.list.dataModel) - return []; - - // Return an array based on the dataModel. - return bmm.list.dataModel.slice(); -} - -/** - * Returns a promise that will contain all URLs of all the selected bookmarks - * and the nested bookmarks for use with the open commands. - * @param {HTMLElement} target The target list or tree. - * @return {Promise<Array<string>>} . - */ -function getUrlsForOpenCommands(target) { - return getAllUrls(getNodesForOpen(target)); -} - -function notNewNode(node) { - return node.id != 'new'; -} - -/** - * Helper function that updates the canExecute and labels for the open-like - * commands. - * @param {!cr.ui.CanExecuteEvent} e The event fired by the command system. - * @param {!cr.ui.Command} command The command we are currently processing. - * @param {string} singularId The string id of singular form of the menu label. - * @param {string} pluralId The string id of menu label if the singular form is - not used. - * @param {boolean} commandDisabled Whether the menu item should be disabled - no matter what bookmarks are selected. - */ -function updateOpenCommand(e, command, singularId, pluralId, commandDisabled) { - if (singularId) { - // The command label reflects the selection which might not reflect - // how many bookmarks will be opened. For example if you right click an - // empty area in a folder with 1 bookmark the text should still say "all". - var selectedNodes = getSelectedBookmarkNodes(e.target).filter(notNewNode); - var singular = selectedNodes.length == 1 && !bmm.isFolder(selectedNodes[0]); - command.label = loadTimeData.getString(singular ? singularId : pluralId); - } - - if (commandDisabled) { - command.disabled = true; - e.canExecute = false; - return; - } - - getUrlsForOpenCommands(assertInstanceof(e.target, HTMLElement)).then( - function(urls) { - var disabled = !urls.length; - command.disabled = disabled; - e.canExecute = !disabled; - }); -} - -/** - * Calls the backend to figure out if we can paste the clipboard into the active - * folder. - * @param {Function=} opt_f Function to call after the state has been updated. - */ -function updatePasteCommand(opt_f) { - function update(commandId, canPaste) { - $(commandId).disabled = !canPaste; - } - - var promises = []; - - // The folders menu. - // We can not paste into search item in tree. - if (bmm.tree.selectedItem && bmm.tree.selectedItem != searchTreeItem) { - promises.push(new Promise(function(resolve) { - var id = bmm.tree.selectedItem.bookmarkId; - chrome.bookmarkManagerPrivate.canPaste(id, function(canPaste) { - update('paste-from-folders-menu-command', canPaste); - resolve(canPaste); - }); - })); - } else { - // Tree's not loaded yet. - update('paste-from-folders-menu-command', false); - } - - // The organize menu. - var listId = bmm.list.parentId; - if (bmm.list.isSearch() || !listId) { - // We cannot paste into search view or the list isn't ready. - update('paste-from-organize-menu-command', false); - } else { - promises.push(new Promise(function(resolve) { - chrome.bookmarkManagerPrivate.canPaste(listId, function(canPaste) { - update('paste-from-organize-menu-command', canPaste); - resolve(canPaste); - }); - })); - } - - Promise.all(promises).then(function() { - var cmd; - if (document.activeElement == bmm.list) - cmd = 'paste-from-organize-menu-command'; - else if (document.activeElement == bmm.tree) - cmd = 'paste-from-folders-menu-command'; - - if (cmd) - update('paste-from-context-menu-command', !$(cmd).disabled); - - if (opt_f) opt_f(); - }); -} - -function handleCanExecuteForSearchBox(e) { - var command = e.command; - switch (command.id) { - case 'delete-command': - case 'undo-command': - // Pass the delete and undo commands through - // (fixes http://crbug.com/278112). - e.canExecute = false; - break; - } -} - -function handleCanExecuteForDocument(e) { - var command = e.command; - switch (command.id) { - case 'import-menu-command': - e.canExecute = canEdit; - break; - - case 'export-menu-command': - // We can always execute the export-menu command. - e.canExecute = true; - break; - - case 'sort-command': - e.canExecute = !bmm.list.isSearch() && - bmm.list.dataModel && bmm.list.dataModel.length > 1 && - !isUnmodifiable(bmm.tree.getBookmarkNodeById(bmm.list.parentId)); - break; - - case 'undo-command': - // Because the global undo command has no visible UI, always enable it, - // and just make it a no-op if undo is not possible. - e.canExecute = true; - break; - - default: - canExecuteForList(e); - if (!e.defaultPrevented) - canExecuteForTree(e); - break; - } -} - -/** - * Helper function for handling canExecute for the list and the tree. - * @param {!cr.ui.CanExecuteEvent} e Can execute event object. - * @param {boolean} isSearch Whether the user is trying to do a command on - * search. - */ -function canExecuteShared(e, isSearch) { - var command = e.command; - switch (command.id) { - case 'paste-from-folders-menu-command': - case 'paste-from-organize-menu-command': - case 'paste-from-context-menu-command': - updatePasteCommand(); - break; - - case 'add-new-bookmark-command': - case 'new-folder-command': - case 'new-folder-from-folders-menu-command': - var parentId = computeParentFolderForNewItem(); - var unmodifiable = isUnmodifiable( - bmm.tree.getBookmarkNodeById(parentId)); - e.canExecute = !isSearch && canEdit && !unmodifiable; - break; - - case 'open-in-new-tab-command': - updateOpenCommand(e, command, 'open_in_new_tab', 'open_all', false); - break; - - case 'open-in-background-tab-command': - updateOpenCommand(e, command, '', '', false); - break; - - case 'open-in-new-window-command': - updateOpenCommand(e, command, - 'open_in_new_window', 'open_all_new_window', - // Disabled when incognito is forced. - incognitoModeAvailability == 'forced'); - break; - - case 'open-incognito-window-command': - updateOpenCommand(e, command, - 'open_incognito', 'open_all_incognito', - // Not available when incognito is disabled. - incognitoModeAvailability == 'disabled'); - break; - - case 'undo-delete-command': - e.canExecute = !!lastDeleted; - break; - } -} - -/** - * Helper function for handling canExecute for the list and document. - * @param {!cr.ui.CanExecuteEvent} e Can execute event object. - */ -function canExecuteForList(e) { - function hasSelected() { - return !!bmm.list.selectedItem; - } - - function hasSingleSelected() { - return bmm.list.selectedItems.length == 1; - } - - function canCopyItem(item) { - return item.id != 'new'; - } - - function canCopyItems() { - var selectedItems = bmm.list.selectedItems; - return selectedItems && selectedItems.some(canCopyItem); - } - - function isSearch() { - return bmm.list.isSearch(); - } - - var command = e.command; - switch (command.id) { - case 'rename-folder-command': - // Show rename if a single folder is selected. - var items = bmm.list.selectedItems; - if (items.length != 1) { - e.canExecute = false; - command.hidden = true; - } else { - var isFolder = bmm.isFolder(items[0]); - e.canExecute = isFolder && canEdit && !hasUnmodifiable(items); - command.hidden = !isFolder; - } - break; - - case 'edit-command': - // Show the edit command if not a folder. - var items = bmm.list.selectedItems; - if (items.length != 1) { - e.canExecute = false; - command.hidden = false; - } else { - var isFolder = bmm.isFolder(items[0]); - e.canExecute = !isFolder && canEdit && !hasUnmodifiable(items); - command.hidden = isFolder; - } - break; - - case 'show-in-folder-command': - e.canExecute = isSearch() && hasSingleSelected(); - break; - - case 'delete-command': - case 'cut-command': - e.canExecute = canCopyItems() && canEdit && - !hasUnmodifiable(bmm.list.selectedItems); - break; - - case 'copy-command': - e.canExecute = canCopyItems(); - break; - - case 'open-in-same-window-command': - e.canExecute = (e.target == bmm.list) && hasSelected(); - break; - - default: - canExecuteShared(e, isSearch()); - } -} - -// Update canExecute for the commands when the list is the active element. -function handleCanExecuteForList(e) { - if (e.target != bmm.list) return; - canExecuteForList(e); -} - -// Update canExecute for the commands when the tree is the active element. -function handleCanExecuteForTree(e) { - if (e.target != bmm.tree) return; - canExecuteForTree(e); -} - -function canExecuteForTree(e) { - function hasSelected() { - return !!bmm.tree.selectedItem; - } - - function isSearch() { - return bmm.tree.selectedItem == searchTreeItem; - } - - function isTopLevelItem() { - return bmm.tree.selectedItem && - bmm.tree.selectedItem.parentNode == bmm.tree; - } - - var command = e.command; - switch (command.id) { - case 'rename-folder-command': - case 'rename-folder-from-folders-menu-command': - command.hidden = false; - e.canExecute = hasSelected() && !isTopLevelItem() && canEdit && - !hasUnmodifiable(bmm.tree.selectedFolders); - break; - - case 'edit-command': - command.hidden = true; - e.canExecute = false; - break; - - case 'delete-command': - case 'delete-from-folders-menu-command': - case 'cut-command': - case 'cut-from-folders-menu-command': - e.canExecute = hasSelected() && !isTopLevelItem() && canEdit && - !hasUnmodifiable(bmm.tree.selectedFolders); - break; - - case 'copy-command': - case 'copy-from-folders-menu-command': - e.canExecute = hasSelected() && !isTopLevelItem(); - break; - - case 'undo-delete-from-folders-menu-command': - e.canExecute = lastDeleted && lastDeleted.target == bmm.tree; - break; - - default: - canExecuteShared(e, isSearch()); - } -} - -/** - * Update the canExecute state of all the commands. - */ -function updateAllCommands() { - var commands = - /** @type {NodeList<Command>} */ (document.querySelectorAll('command')); - for (var i = 0; i < commands.length; i++) { - commands[i].canExecuteChange(); - } -} - -function updateEditingCommands() { - var editingCommands = [ - 'add-new-bookmark', - 'cut', - 'cut-from-folders-menu', - 'delete', - 'edit', - 'new-folder', - 'paste-from-context-menu', - 'paste-from-folders-menu', - 'paste-from-organize-menu', - 'rename-folder', - 'sort', - ]; - - chrome.bookmarkManagerPrivate.canEdit(function(result) { - if (result != canEdit) { - canEdit = result; - editingCommands.forEach(function(baseId) { - /** @type {Command} */ ($(baseId + '-command')).canExecuteChange(); - }); - } - }); -} - -function handleChangeForTree(e) { - navigateTo(bmm.tree.selectedItem.bookmarkId); -} - -function handleMenuButtonClicked(e) { - updateEditingCommands(); - - if (e.currentTarget.id == 'folders-menu') { - /** @type {Command} */ ($('copy-from-folders-menu-command')) - .canExecuteChange(); - /** @type {Command} */ ($('undo-delete-from-folders-menu-command')) - .canExecuteChange(); - } else { - /** @type {Command} */ ($('copy-command')).canExecuteChange(); - } -} - -function handleRename(e) { - var item = e.target; - var bookmarkNode = item.bookmarkNode; - chrome.bookmarks.update(bookmarkNode.id, {title: item.label}); - performGlobalUndo = null; // This can't be undone, so disable global undo. -} - -function handleEdit(e) { - var item = e.target; - var bookmarkNode = item.bookmarkNode; - var context = { - title: bookmarkNode.title - }; - if (!bmm.isFolder(bookmarkNode)) - context.url = bookmarkNode.url; - - if (bookmarkNode.id == 'new') { - selectItemsAfterUserAction(/** @type {BookmarkList} */(bmm.list)); - - // New page - context.parentId = bookmarkNode.parentId; - chrome.bookmarks.create(context, function(node) { - // A new node was created and will get added to the list due to the - // handler. - var dataModel = bmm.list.dataModel; - var index = dataModel.indexOf(bookmarkNode); - dataModel.splice(index, 1); - - // Select new item. - var newIndex = dataModel.findIndexById(node.id); - if (newIndex != -1) { - var sm = bmm.list.selectionModel; - bmm.list.scrollIndexIntoView(newIndex); - sm.leadIndex = sm.anchorIndex = sm.selectedIndex = newIndex; - } - }); - } else { - // Edit - chrome.bookmarks.update(bookmarkNode.id, context); - } - performGlobalUndo = null; // This can't be undone, so disable global undo. -} - -function handleCancelEdit(e) { - var item = e.target; - var bookmarkNode = item.bookmarkNode; - if (bookmarkNode.id == 'new') { - var dataModel = bmm.list.dataModel; - var index = dataModel.findIndexById('new'); - dataModel.splice(index, 1); - } -} - -/** - * Navigates to the folder that the selected item is in and selects it. This is - * used for the show-in-folder command. - */ -function showInFolder() { - var bookmarkNode = bmm.list.selectedItem; - if (!bookmarkNode) - return; - var parentId = bookmarkNode.parentId; - - // After the list is loaded we should select the revealed item. - function selectItem() { - var index = bmm.list.dataModel.findIndexById(bookmarkNode.id); - if (index == -1) - return; - var sm = bmm.list.selectionModel; - sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; - bmm.list.scrollIndexIntoView(index); - } - - var treeItem = bmm.treeLookup[parentId]; - treeItem.reveal(); - - navigateTo(parentId, selectItem); -} - -/** - * @return {!cr.LinkController} The link controller used to open links based on - * user clicks and keyboard actions. - */ -function getLinkController() { - return linkController || - (linkController = new cr.LinkController(loadTimeData)); -} - -/** - * Returns the selected bookmark nodes of the provided tree or list. - * If |opt_target| is not provided or null the active element is used. - * Only call this if the list or the tree is focused. - * @param {EventTarget=} opt_target The target list or tree. - * @return {!Array} Array of bookmark nodes. - */ -function getSelectedBookmarkNodes(opt_target) { - return (opt_target || document.activeElement) == bmm.tree ? - bmm.tree.selectedFolders : bmm.list.selectedItems; -} - -/** - * @param {EventTarget=} opt_target The target list or tree. - * @return {!Array<string>} An array of the selected bookmark IDs. - */ -function getSelectedBookmarkIds(opt_target) { - var selectedNodes = getSelectedBookmarkNodes(opt_target); - selectedNodes.sort(function(a, b) { return a.index - b.index; }); - return selectedNodes.map(function(node) { - return node.id; - }); -} - -/** - * @param {BookmarkTreeNode} node The node to test. - * @return {boolean} Whether the given node is unmodifiable. - */ -function isUnmodifiable(node) { - return !!(node && node.unmodifiable); -} - -/** - * @param {Array<BookmarkTreeNode>} nodes A list of BookmarkTreeNodes. - * @return {boolean} Whether any of the nodes is managed. - */ -function hasUnmodifiable(nodes) { - return nodes.some(isUnmodifiable); -} - -/** - * Opens the selected bookmarks. - * @param {cr.LinkKind} kind The kind of link we want to open. - * @param {HTMLElement=} opt_eventTarget The target of the user initiated event. - */ -function openBookmarks(kind, opt_eventTarget) { - // If we have selected any folders, we need to find all the bookmarks one - // level down. We use multiple async calls to getSubtree instead of getting - // the whole tree since we would like to minimize the amount of data sent. - - var urlsP = getUrlsForOpenCommands(opt_eventTarget ? opt_eventTarget : null); - urlsP.then(function(urls) { - getLinkController().openUrls(assert(urls), kind); - chrome.bookmarkManagerPrivate.recordLaunch(); - }); -} - -/** - * Opens an item in the list. - */ -function openItem() { - var bookmarkNodes = getSelectedBookmarkNodes(); - // If we double clicked or pressed enter on a single folder, navigate to it. - if (bookmarkNodes.length == 1 && bmm.isFolder(bookmarkNodes[0])) - navigateTo(bookmarkNodes[0].id); - else - openBookmarks(LinkKind.FOREGROUND_TAB); -} - -/** - * Refreshes search results after delete or undo-delete. - * This ensures children of deleted folders do not remain in results - */ -function updateSearchResults() { - if (bmm.list.isSearch()) - bmm.list.reload(); -} - -/** - * Deletes the selected bookmarks. The bookmarks are saved in memory in case - * the user needs to undo the deletion. - * @param {EventTarget=} opt_target The deleter of bookmarks. - */ -function deleteBookmarks(opt_target) { - var selectedIds = getSelectedBookmarkIds(opt_target); - if (!selectedIds.length) - return; - - var filteredIds = getFilteredSelectedBookmarkIds(opt_target); - lastDeleted = {nodes: [], target: opt_target || document.activeElement}; - - function performDelete() { - // Only remove filtered ids. - chrome.bookmarkManagerPrivate.removeTrees(filteredIds); - /** @type {Command} */ ($('undo-delete-command')).canExecuteChange(); - /** @type {Command} */ ($('undo-delete-from-folders-menu-command')) - .canExecuteChange(); - performGlobalUndo = undoDelete; - } - - // First, store information about the bookmarks being deleted. - // Store all selected ids. - selectedIds.forEach(function(id) { - chrome.bookmarks.getSubTree(id, function(results) { - lastDeleted.nodes.push(results); - - // When all nodes have been saved, perform the deletion. - if (lastDeleted.nodes.length === selectedIds.length) { - performDelete(); - updateSearchResults(); - } - }); - }); -} - -/** - * Restores a tree of bookmarks under a specified folder. - * @param {BookmarkTreeNode} node The node to restore. - * @param {(string|number)=} opt_parentId If a string is passed, it's the ID of - * the folder to restore under. If not specified or a number is passed, the - * original parentId of the node will be used. - */ -function restoreTree(node, opt_parentId) { - var bookmarkInfo = { - parentId: typeof opt_parentId == 'string' ? opt_parentId : node.parentId, - title: node.title, - index: node.index, - url: node.url - }; - - chrome.bookmarks.create(bookmarkInfo, function(result) { - if (!result) { - console.error('Failed to restore bookmark.'); - return; - } - - if (node.children) { - // Restore the children using the new ID for this node. - node.children.forEach(function(child) { - restoreTree(child, result.id); - }); - } - - updateSearchResults(); - }); -} - -/** - * Restores the last set of bookmarks that was deleted. - */ -function undoDelete() { - lastDeleted.nodes.forEach(function(arr) { - arr.forEach(restoreTree); - }); - lastDeleted = null; - /** @type {Command} */ ($('undo-delete-command')).canExecuteChange(); - /** @type {Command} */ ($('undo-delete-from-folders-menu-command')) - .canExecuteChange(); - - // Only a single level of undo is supported, so disable global undo now. - performGlobalUndo = null; -} - -/** - * Computes folder for "Add Page" and "Add Folder". - * @return {string} The id of folder node where we'll create new page/folder. - */ -function computeParentFolderForNewItem() { - if (document.activeElement == bmm.tree) - return bmm.list.parentId; - var selectedItem = bmm.list.selectedItem; - return selectedItem && bmm.isFolder(selectedItem) ? - selectedItem.id : bmm.list.parentId; -} - -/** - * Callback for rename folder and edit command. This starts editing for - * the passed in target, or the selected item. - * @param {EventTarget=} opt_target The target to start editing. If absent or - * null, the selected item will be edited instead. - */ -function editItem(opt_target) { - if ((opt_target || document.activeElement) == bmm.tree) { - bmm.tree.selectedItem.editing = true; - } else { - var li = bmm.list.getListItem(bmm.list.selectedItem); - if (li) - li.editing = true; - } -} - -/** - * Callback for the new folder command. This creates a new folder and starts - * a rename of it. - * @param {EventTarget=} opt_target The target to create a new folder in. - */ -function newFolder(opt_target) { - performGlobalUndo = null; // This can't be undone, so disable global undo. - - var parentId = computeParentFolderForNewItem(); - var selectedItems = bmm.list.selectedItems; - var newIndex; - // Callback is called after tree and list data model updated. - function createFolder(callback) { - if (selectedItems.length == 1 && document.activeElement != bmm.tree && - !bmm.isFolder(selectedItems[0]) && selectedItems[0].id != 'new') { - newIndex = bmm.list.dataModel.indexOf(selectedItems[0]) + 1; - } - chrome.bookmarks.create({ - title: loadTimeData.getString('new_folder_name'), - parentId: parentId, - index: newIndex - }, callback); - } - - if ((opt_target || document.activeElement) == bmm.tree) { - createFolder(function(newNode) { - navigateTo(newNode.id, function() { - bmm.treeLookup[newNode.id].editing = true; - }); - }); - return; - } - - function editNewFolderInList() { - createFolder(function(newNode) { - var index = newNode.index; - var sm = bmm.list.selectionModel; - sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; - scrollIntoViewAndMakeEditable(index); - }); - } - - navigateTo(parentId, editNewFolderInList); -} - -/** - * Scrolls the list item into view and makes it editable. - * @param {number} index The index of the item to make editable. - */ -function scrollIntoViewAndMakeEditable(index) { - bmm.list.scrollIndexIntoView(index); - // onscroll is now dispatched asynchronously so we have to postpone - // the rest. - setTimeout(function() { - var item = bmm.list.getListItemByIndex(index); - if (item) - item.editing = true; - }, 0); -} - -/** - * Adds a page to the current folder. This is called by the - * add-new-bookmark-command handler. - */ -function addPage() { - var parentId = computeParentFolderForNewItem(); - var selectedItems = bmm.list.selectedItems; - var newIndex; - function editNewBookmark() { - if (selectedItems.length == 1 && document.activeElement != bmm.tree && - !bmm.isFolder(selectedItems[0])) { - newIndex = bmm.list.dataModel.indexOf(selectedItems[0]) + 1; - } - - var fakeNode = { - title: '', - url: '', - parentId: parentId, - index: newIndex, - id: 'new' - }; - var dataModel = bmm.list.dataModel; - var index = dataModel.length; - if (newIndex != undefined) - index = newIndex; - dataModel.splice(index, 0, fakeNode); - var sm = bmm.list.selectionModel; - sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; - scrollIntoViewAndMakeEditable(index); - } - - navigateTo(parentId, editNewBookmark); -} - -/** - * This function is used to select items after a user action such as paste, drop - * add page etc. - * @param {BookmarkList|BookmarkTree} target The target of the user action. - * @param {string=} opt_selectedTreeId If provided, then select that tree id. - */ -function selectItemsAfterUserAction(target, opt_selectedTreeId) { - // We get one onCreated event per item so we delay the handling until we get - // no more events coming. - - var ids = []; - var timer; - - function handle(id, bookmarkNode) { - clearTimeout(timer); - if (opt_selectedTreeId || bmm.list.parentId == bookmarkNode.parentId) - ids.push(id); - timer = setTimeout(handleTimeout, 50); - } - - function handleTimeout() { - chrome.bookmarks.onCreated.removeListener(handle); - chrome.bookmarks.onMoved.removeListener(handle); - - if (opt_selectedTreeId && ids.indexOf(opt_selectedTreeId) != -1) { - var index = ids.indexOf(opt_selectedTreeId); - if (index != -1 && opt_selectedTreeId in bmm.treeLookup) { - bmm.tree.selectedItem = bmm.treeLookup[opt_selectedTreeId]; - } - } else if (target == bmm.list) { - var dataModel = bmm.list.dataModel; - var firstIndex = dataModel.findIndexById(ids[0]); - var lastIndex = dataModel.findIndexById(ids[ids.length - 1]); - if (firstIndex != -1 && lastIndex != -1) { - var selectionModel = bmm.list.selectionModel; - selectionModel.selectedIndex = -1; - selectionModel.selectRange(firstIndex, lastIndex); - selectionModel.anchorIndex = selectionModel.leadIndex = lastIndex; - bmm.list.focus(); - } - } - - bmm.list.endBatchUpdates(); - } - - bmm.list.startBatchUpdates(); - - chrome.bookmarks.onCreated.addListener(handle); - chrome.bookmarks.onMoved.addListener(handle); - timer = setTimeout(handleTimeout, 300); -} - -/** - * Record user action. - * @param {string} name An user action name. - */ -function recordUserAction(name) { - chrome.metricsPrivate.recordUserAction('BookmarkManager_Command_' + name); -} - -/** - * The currently selected bookmark, based on where the user is clicking. - * @return {string} The ID of the currently selected bookmark (could be from - * tree view or list view). - */ -function getSelectedId() { - if (document.activeElement == bmm.tree) - return bmm.tree.selectedItem.bookmarkId; - var selectedItem = bmm.list.selectedItem; - return selectedItem && bmm.isFolder(selectedItem) ? - selectedItem.id : bmm.tree.selectedItem.bookmarkId; -} - -/** - * Pastes the copied/cutted bookmark into the right location depending whether - * if it was called from Organize Menu or from Context Menu. - * @param {string} id The id of the element being pasted from. - */ -function pasteBookmark(id) { - recordUserAction('Paste'); - selectItemsAfterUserAction(/** @type {BookmarkList} */(bmm.list)); - chrome.bookmarkManagerPrivate.paste(id, getSelectedBookmarkIds()); -} - -/** - * Returns true if child is contained in another selected folder. - * Traces parent nodes up the tree until a selected ancestor or root is found. - */ -function hasSelectedAncestor(parentNode) { - function contains(arr, item) { - for (var i = 0; i < arr.length; i++) - if (arr[i] === item) - return true; - return false; - } - - // Don't search top level, cannot select permanent nodes in search. - if (parentNode == null || parentNode.id <= 2) - return false; - - // Found selected ancestor. - if (contains(getSelectedBookmarkNodes(), parentNode)) - return true; - - // Keep digging. - return hasSelectedAncestor( - bmm.tree.getBookmarkNodeById(parentNode.parentId)); -} - -/** - * @param {EventTarget=} opt_target A target to get bookmark IDs from. - * @return {Array<string>} An array of bookmarks IDs. - */ -function getFilteredSelectedBookmarkIds(opt_target) { - // Remove duplicates from filteredIds and return. - var filteredIds = []; - // Selected nodes to iterate through for matches. - var nodes = getSelectedBookmarkNodes(opt_target); - - for (var i = 0; i < nodes.length; i++) - if (!hasSelectedAncestor(bmm.tree.getBookmarkNodeById(nodes[i].parentId))) - filteredIds.splice(0, 0, nodes[i].id); - - return filteredIds; -} - -/** - * Handler for the command event. This is used for context menu of list/tree - * and organized menu. - * @param {!Event} e The event object. - */ -function handleCommand(e) { - var command = e.command; - var target = assertInstanceof(e.target, HTMLElement); - switch (command.id) { - case 'import-menu-command': - recordUserAction('Import'); - chrome.bookmarks.import(); - break; - - case 'export-menu-command': - recordUserAction('Export'); - chrome.bookmarks.export(); - break; - - case 'undo-command': - if (performGlobalUndo) { - recordUserAction('UndoGlobal'); - performGlobalUndo(); - } else { - recordUserAction('UndoNone'); - } - break; - - case 'show-in-folder-command': - recordUserAction('ShowInFolder'); - showInFolder(); - break; - - case 'open-in-new-tab-command': - case 'open-in-background-tab-command': - recordUserAction('OpenInNewTab'); - openBookmarks(LinkKind.BACKGROUND_TAB, target); - break; - - case 'open-in-new-window-command': - recordUserAction('OpenInNewWindow'); - openBookmarks(LinkKind.WINDOW, target); - break; - - case 'open-incognito-window-command': - recordUserAction('OpenIncognito'); - openBookmarks(LinkKind.INCOGNITO, target); - break; - - case 'delete-from-folders-menu-command': - target = bmm.tree; - case 'delete-command': - recordUserAction('Delete'); - deleteBookmarks(target); - break; - - case 'copy-from-folders-menu-command': - target = bmm.tree; - case 'copy-command': - recordUserAction('Copy'); - chrome.bookmarkManagerPrivate.copy(getSelectedBookmarkIds(target), - updatePasteCommand); - break; - - case 'cut-from-folders-menu-command': - target = bmm.tree; - case 'cut-command': - recordUserAction('Cut'); - chrome.bookmarkManagerPrivate.cut(getSelectedBookmarkIds(target), - function() { - updatePasteCommand(); - updateSearchResults(); - }); - break; - - case 'paste-from-organize-menu-command': - pasteBookmark(bmm.list.parentId); - break; - - case 'paste-from-folders-menu-command': - pasteBookmark(bmm.tree.selectedItem.bookmarkId); - break; - - case 'paste-from-context-menu-command': - pasteBookmark(getSelectedId()); - break; - - case 'sort-command': - recordUserAction('Sort'); - chrome.bookmarkManagerPrivate.sortChildren(bmm.list.parentId); - break; - - - case 'rename-folder-from-folders-menu-command': - target = bmm.tree; - case 'rename-folder-command': - editItem(target); - break; - - case 'edit-command': - recordUserAction('Edit'); - editItem(); - break; - - case 'new-folder-from-folders-menu-command': - target = bmm.tree; - case 'new-folder-command': - recordUserAction('NewFolder'); - newFolder(target); - break; - - case 'add-new-bookmark-command': - recordUserAction('AddPage'); - addPage(); - break; - - case 'open-in-same-window-command': - recordUserAction('OpenInSame'); - openItem(); - break; - - case 'undo-delete-command': - case 'undo-delete-from-folders-menu-command': - recordUserAction('UndoDelete'); - undoDelete(); - break; - } -} - -// Execute the copy, cut and paste commands when those events are dispatched by -// the browser. This allows us to rely on the browser to handle the keyboard -// shortcuts for these commands. -function installEventHandlerForCommand(eventName, commandId) { - function handle(e) { - if (document.activeElement != bmm.list && - document.activeElement != bmm.tree) - return; - var command = /** @type {Command} */ ($(commandId)); - if (!command.disabled) { - command.execute(); - if (e) - e.preventDefault(); // Prevent the system beep. - } - } - if (eventName == 'paste') { - // Paste is a bit special since we need to do an async call to see if we - // can paste because the paste command might not be up to date. - document.addEventListener(eventName, function(e) { - updatePasteCommand(handle); - }); - } else { - document.addEventListener(eventName, handle); - } -} - -function initializeSplitter() { - var splitter = document.querySelector('.main > .splitter'); - Splitter.decorate(splitter); - - var splitterStyle = splitter.previousElementSibling.style; - - // The splitter persists the size of the left component in the local store. - if ('treeWidth' in window.localStorage) - splitterStyle.width = window.localStorage['treeWidth']; - - splitter.addEventListener('resize', function(e) { - window.localStorage['treeWidth'] = splitterStyle.width; - }); -} - -function initializeBookmarkManager() { - // Sometimes the extension API is not initialized. - if (!chrome.bookmarks) - console.error('Bookmarks extension API is not available'); - - chrome.bookmarkManagerPrivate.getStrings(continueInitializeBookmarkManager); -} - -function continueInitializeBookmarkManager(localizedStrings) { - loadLocalizedStrings(localizedStrings); - - bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; - - cr.ui.decorate('cr-menu', Menu); - cr.ui.decorate('button[menu]', MenuButton); - cr.ui.decorate('command', Command); - BookmarkList.decorate($('list')); - BookmarkTree.decorate($('tree')); - - bmm.list.addEventListener('canceledit', handleCancelEdit); - bmm.list.addEventListener('canExecute', handleCanExecuteForList); - bmm.list.addEventListener('change', updateAllCommands); - bmm.list.addEventListener('contextmenu', updateEditingCommands); - bmm.list.addEventListener('dblclick', handleDoubleClickForList); - bmm.list.addEventListener('edit', handleEdit); - bmm.list.addEventListener('rename', handleRename); - bmm.list.addEventListener('urlClicked', handleUrlClickedForList); - - bmm.tree.addEventListener('canExecute', handleCanExecuteForTree); - bmm.tree.addEventListener('change', handleChangeForTree); - bmm.tree.addEventListener('contextmenu', updateEditingCommands); - bmm.tree.addEventListener('rename', handleRename); - bmm.tree.addEventListener('load', handleLoadForTree); - - cr.ui.contextMenuHandler.addContextMenuProperty( - /** @type {!Element} */(bmm.tree)); - bmm.list.contextMenu = $('context-menu'); - bmm.tree.contextMenu = $('context-menu'); - - // We listen to hashchange so that we can update the currently shown folder - // when // the user goes back and forward in the history. - window.addEventListener('hashchange', processHash); - - document.querySelector('header form').onsubmit = - /** @type {function(Event=)} */(function(e) { - setSearch($('term').value); - e.preventDefault(); - }); - - $('term').addEventListener('search', handleSearch); - $('term').addEventListener('canExecute', handleCanExecuteForSearchBox); - - $('folders-button').addEventListener('click', handleMenuButtonClicked); - $('organize-button').addEventListener('click', handleMenuButtonClicked); - - document.addEventListener('canExecute', handleCanExecuteForDocument); - document.addEventListener('command', handleCommand); - - // Listen to copy, cut and paste events and execute the associated commands. - installEventHandlerForCommand('copy', 'copy-command'); - installEventHandlerForCommand('cut', 'cut-command'); - installEventHandlerForCommand('paste', 'paste-from-organize-menu-command'); - - // Install shortcuts - for (var name in commandShortcutMap) { - $(name + '-command').shortcut = commandShortcutMap[name]; - } - - // Disable almost all commands at startup. - var commands = document.querySelectorAll('command'); - for (var i = 0, command; command = commands[i]; ++i) { - if (command.id != 'import-menu-command' && - command.id != 'export-menu-command') { - command.disabled = true; - } - } - - chrome.bookmarkManagerPrivate.canEdit(function(result) { - canEdit = result; - }); - - chrome.systemPrivate.getIncognitoModeAvailability(function(result) { - // TODO(rustema): propagate policy value to the bookmark manager when it - // changes. - incognitoModeAvailability = result; - }); - - cr.ui.FocusOutlineManager.forDocument(document); - initializeSplitter(); - bmm.addBookmarkModelListeners(); - dnd.init(selectItemsAfterUserAction); - bmm.tree.reload(); -} - -initializeBookmarkManager(); -})();
diff --git a/chrome/browser/resources/bookmark_manager/main.html b/chrome/browser/resources/bookmark_manager/main.html deleted file mode 100644 index 8a5e831..0000000 --- a/chrome/browser/resources/bookmark_manager/main.html +++ /dev/null
@@ -1,207 +0,0 @@ -<!doctype html> -<html i18n-values="dir:textdirection;lang:language"> -<!-- - -Copyright (c) 2012 The Chromium Authors. All rights reserved. -Use of this source code is governed by a BSD-style license that can be -found in the LICENSE file. - ---> -<head> -<meta name="google" value="notranslate"> -<meta charset="utf-8"> -<title i18n-content="title"></title> - -<link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> -<link rel="stylesheet" href="chrome://resources/css/i18n_process.css"> -<link rel="stylesheet" href="chrome://resources/css/list.css"> -<link rel="stylesheet" href="chrome://resources/css/tree.css"> -<link rel="stylesheet" href="chrome://resources/css/menu.css"> -<link rel="stylesheet" href="chrome://resources/css/menu_button.css"> -<link rel="stylesheet" href="chrome://resources/css/widgets.css"> -<link rel="stylesheet" href="css/bmm.css"> - -<script src="chrome://resources/js/event_tracker.js"></script> - -<script src="chrome://resources/js/cr.js"></script> -<script src="chrome://resources/js/cr/event_target.js"></script> -<script src="chrome://resources/js/cr/link_controller.js"></script> -<script src="chrome://resources/js/cr/ui.js"></script> -<script src="chrome://resources/js/cr/ui/touch_handler.js"></script> -<script src="chrome://resources/js/cr/ui/array_data_model.js"></script> -<script src="chrome://resources/js/cr/ui/command.js"></script> -<script src="chrome://resources/js/cr/ui/focus_outline_manager.js"></script> -<script src="chrome://resources/js/cr/ui/menu_item.js"></script> -<script src="chrome://resources/js/cr/ui/menu.js"></script> -<script src="chrome://resources/js/cr/ui/position_util.js"></script> -<script src="chrome://resources/js/cr/ui/menu_button.js"></script> -<script src="chrome://resources/js/cr/ui/context_menu_button.js"></script> -<script src="chrome://resources/js/cr/ui/context_menu_handler.js"></script> -<script src="chrome://resources/js/cr/ui/list_selection_model.js"></script> -<script src="chrome://resources/js/cr/ui/list_selection_controller.js"></script> -<script src="chrome://resources/js/cr/ui/list_item.js"></script> -<script src="chrome://resources/js/cr/ui/list.js"></script> -<script src="chrome://resources/js/cr/ui/tree.js"></script> -<script src="chrome://resources/js/cr/ui/splitter.js"></script> - -<script src="chrome://resources/js/i18n_template_no_process.js"></script> -<script src="chrome://resources/js/icon.js"></script> -<script src="chrome://resources/js/load_time_data.js"></script> -<script src="chrome://resources/js/util.js"></script> - -<script src="js/bmm.js"></script> -<script src="js/bmm/bookmark_list.js"></script> -<script src="js/bmm/bookmark_tree.js"></script> -<script src="js/dnd.js"></script> -</head> -<body> - -<header> - <h1 i18n-content="title"></h1> - <form> - <input type="search" id="term" i18n-values="placeholder:search_button" - autofocus incremental> - </form> -</header> - -<div class="main"> - <div id="tree-pane" class="pane"> - <div> - <button menu="#folders-menu" i18n-content="folders_menu" - id="folders-button" class="custom-appearance"></button> - </div> - <div id="tree-container"> - <tree id="tree" role="tree"></tree> - </div> - </div> - <div class="splitter"> - <div> - <!-- Used to occupy the correct amount of vertical space. --> - <button menu="#no-menu" i18n-content="folders_menu" - class="custom-appearance"></button> - </div> - </div> - <div id="list-pane" class="pane"> - <div> - <button menu="#organize-menu" i18n-content="organize_menu" - id="organize-button" class="custom-appearance"></button> - </div> - <!-- The list doesn't use a scroll container as it truncates horizontally - and handles its own vertical overflow. --> - <list id="list"></list> - </div> -</div> - -<!-- Organize menu --> -<command i18n-values=".label:rename_folder" id="rename-folder-command"> -</command> -<command i18n-values=".label:edit" id="edit-command"></command> -<command i18n-values=".label:show_in_folder" id="show-in-folder-command"> -</command> -<command i18n-values=".label:cut" id="cut-command"></command> -<command i18n-values=".label:copy" id="copy-command"></command> -<command i18n-values=".label:paste" id="paste-from-organize-menu-command"> -</command> -<command i18n-values=".label:delete" id="delete-command"></command> -<command i18n-values=".label:undo_delete" id="undo-delete-command"></command> -<command i18n-values=".label:sort" id="sort-command"></command> -<command i18n-values=".label:add_new_bookmark" id="add-new-bookmark-command"> -</command> -<command i18n-values=".label:new_folder" id="new-folder-command"></command> - -<!-- Folders menu --> -<command i18n-values=".label:cut" id="cut-from-folders-menu-command"></command> -<command i18n-values=".label:copy" id="copy-from-folders-menu-command"> -</command> -<command i18n-values=".label:paste" id="paste-from-folders-menu-command"> -</command> -<command i18n-values=".label:new_folder" - id="new-folder-from-folders-menu-command"></command> -<command i18n-values=".label:delete" id="delete-from-folders-menu-command"> -</command> -<command i18n-values=".label:undo_delete" - id="undo-delete-from-folders-menu-command"></command> - -<!-- Tools menu --> -<command i18n-values=".label:import_menu" id="import-menu-command"></command> -<command i18n-values=".label:export_menu" id="export-menu-command"></command> - -<!-- Context menu --> -<command i18n-values=".label:paste" id="paste-from-context-menu-command"> -</command> - -<!-- open * are handled in canExecute handler --> -<command id="open-in-new-tab-command"></command> -<command id="open-in-background-tab-command"></command> -<command id="open-in-new-window-command"></command> -<command id="open-incognito-window-command"></command> -<command id="open-in-same-window-command"></command> - -<command id="undo-command"></command> - -<command i18n-values=".label:rename_folder" - id="rename-folder-from-folders-menu-command"></command> -<command i18n-values=".label:paste" id="paste-from-folders-menu-command"> -</command> - -<!-- TODO(arv): I think the commands might be better created in code? --> - -<cr-menu id="folders-menu"> - <button command="#new-folder-from-folders-menu-command"></button> - <hr> - <button command="#rename-folder-from-folders-menu-command"></button> - <hr> - <button command="#cut-from-folders-menu-command"></button> - <button command="#copy-from-folders-menu-command"></button> - <button command="#paste-from-folders-menu-command"></button> - <hr> - <button command="#delete-from-folders-menu-command"></button> - <button command="#undo-delete-from-folders-menu-command"></button> -</cr-menu> - -<cr-menu id="no-menu"></cr-menu> - -<cr-menu id="organize-menu"> - <button command="#add-new-bookmark-command"></button> - <button command="#new-folder-command"></button> - <hr> - <button command="#rename-folder-command"></button> - <button command="#edit-command"></button> - <button command="#show-in-folder-command"></button> - <hr> - <button command="#cut-command"></button> - <button command="#copy-command"></button> - <button command="#paste-from-organize-menu-command"></button> - <hr> - <button command="#delete-command"></button> - <button command="#undo-delete-command"></button> - <hr> - <button command="#sort-command"></button> - <hr> - <button command="#import-menu-command"></button> - <button command="#export-menu-command"></button> -</cr-menu> - -<cr-menu id="context-menu"> - <button command="#open-in-new-tab-command"></button> - <button command="#open-in-new-window-command"></button> - <button command="#open-incognito-window-command"></button> - <hr> - <button command="#rename-folder-command"></button> - <button command="#edit-command"></button> - <button command="#show-in-folder-command"></button> - <hr> - <button command="#cut-command"></button> - <button command="#copy-command"></button> - <button command="#paste-from-context-menu-command"></button> - <hr> - <button command="#delete-command"></button> - <button command="#undo-delete-command"></button> - <hr> - <button command="#add-new-bookmark-command"></button> - <button command="#new-folder-command"></button> -</cr-menu> - -<script src="js/main.js"></script> -</body> -</html>
diff --git a/chrome/browser/resources/bookmark_manager/manifest.json b/chrome/browser/resources/bookmark_manager/manifest.json deleted file mode 100644 index 23222d0..0000000 --- a/chrome/browser/resources/bookmark_manager/manifest.json +++ /dev/null
@@ -1,25 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQcByy+eN9jzazWF/DPn7NW47sW7lgmpk6eKc0BQM18q8hvEM3zNm2n7HkJv/R6fU+X5mtqkDuKvq5skF6qqUF4oEyaleWDFhd1xFwV7JV+/DU7bZ00w2+6gzqsabkerFpoP33ZRIw7OviJenP0c0uWqDWF8EGSyMhB3txqhOtiQIDAQAB", - "name": "Bookmark Manager", - "version": "0.1", - "manifest_version": 2, - "description": "Bookmark Manager", - "icons": { - // The favicon is loaded directly from resources.pak. - }, - "incognito" : "split", - "permissions": [ - "bookmarks", - "bookmarkManagerPrivate", - "metricsPrivate", - "systemPrivate", - "tabs", - "chrome://favicon/", - "chrome://resources/" - ], - "chrome_url_overrides": { - "bookmarks": "main.html" - }, - "content_security_policy": - "object-src 'none'; script-src chrome://resources 'self' blob: filesystem:" -}
diff --git a/chrome/browser/resources/chromeos/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/chromevox/BUILD.gn index 55a31485..c20da9a2 100644 --- a/chrome/browser/resources/chromeos/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/chromevox/BUILD.gn
@@ -136,6 +136,7 @@ "cvox2/background/desktop_automation_handler.js", "cvox2/background/earcon_engine.js", "cvox2/background/editing.js", + "cvox2/background/event_source.js", "cvox2/background/find_handler.js", "cvox2/background/gesture_command_data.js", "cvox2/background/gesture_command_handler.js",
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js index de92683..35ce91d 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js
@@ -8,6 +8,7 @@ goog.provide('BrailleCommandHandler'); +goog.require('EventSourceState'); goog.require('BackgroundKeyboardHandler'); goog.require('DesktopAutomationHandler'); @@ -33,6 +34,8 @@ if (!BrailleCommandHandler.enabled_) return true; + EventSourceState.set(EventSourceType.BRAILLE_KEYBOARD); + // Note: panning within content occurs earlier in event dispatch. Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH); switch (evt.command) {
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/event_source.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/event_source.js new file mode 100644 index 0000000..56aa3af --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/event_source.js
@@ -0,0 +1,39 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Tracks event sources. + */ + +goog.provide('EventSourceState'); +goog.provide('EventSourceType'); + +/** @enum {string} */ +EventSourceType = { + NONE: 'none', + BRAILLE_KEYBOARD: 'brailleKeyboard', + STANDARD_KEYBOARD: 'standardKeyboard', + TOUCH_GESTURE: 'touchGesture' +}; + +/** + * Sets the current event source. + * @param {EventSourceType} source + */ +EventSourceState.set = function(source) { + EventSource.current_ = source; +}; + +/** + * Gets the current event source. + * @return {EventSourceType} + */ +EventSourceState.get = function() { + return EventSource.current_; +}; + +/** + * @private {EventSourceType} + */ +EventSourceState.current_ = EventSourceType.NONE;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/gesture_command_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/gesture_command_handler.js index a33b74e..8776020 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/gesture_command_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/gesture_command_handler.js
@@ -9,6 +9,7 @@ goog.provide('GestureCommandHandler'); goog.require('CommandHandler'); +goog.require('EventSourceState'); goog.require('GestureCommandData'); /** @@ -37,6 +38,8 @@ if (!GestureCommandHandler.enabled_ || !ChromeVoxState.instance.currentRange) return; + EventSourceState.set(EventSourceType.TOUCH_GESTURE); + var commandData = GestureCommandData.GESTURE_COMMAND_MAP[gesture]; if (!commandData) return;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js index 13c0068..41fd5ab4 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js
@@ -9,6 +9,7 @@ goog.provide('BackgroundKeyboardHandler'); goog.require('ChromeVoxState'); +goog.require('EventSourceState'); goog.require('Output'); goog.require('cvox.ChromeVoxKbHandler'); goog.require('cvox.ChromeVoxPrefs'); @@ -36,6 +37,7 @@ * @return {boolean} True if the default action should be performed. */ onKeyDown: function(evt) { + EventSourceState.set(EventSourceType.STANDARD_KEYBOARD); evt.stickyMode = cvox.ChromeVox.isStickyModeOn() && cvox.ChromeVox.isActive; if (cvox.ChromeVox.passThroughMode) return false;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index ad81633..c96c2aa 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -11,6 +11,7 @@ goog.require('AutomationTreeWalker'); goog.require('EarconEngine'); +goog.require('EventSourceState'); goog.require('Spannable'); goog.require('constants'); goog.require('cursors.Cursor'); @@ -1010,7 +1011,7 @@ else this.range_(range, prevRange, type, buff); - this.hint_(range, uniqueAncestors, buff); + this.hint_(range, uniqueAncestors, type, buff); }, /** @@ -1776,7 +1777,16 @@ this.locations_.push(loc); }, - hint_: function(range, uniqueAncestors, buff) { + /** + * Renders the given range using optional context previous range and event + * type. + * @param {!cursors.Range} range + * @param {!Array<AutomationNode>} uniqueAncestors + * @param {EventType|Output.EventType} type + * @param {!Array<Spannable>} buff Buffer to receive rendered output. + * @private + */ + hint_: function(range, uniqueAncestors, type, buff) { if (!this.enableHints_ || localStorage['useVerboseMode'] != 'true') return; @@ -1792,6 +1802,13 @@ return; } + if (type == EventType.HOVER || + EventSourceState.get() == EventSourceType.TOUCH_GESTURE) { + if (node.defaultActionVerb != 'none') + this.format_(node, '@hint_double_tap', buff); + return; + } + if (node.state[StateType.EDITABLE] && cvox.ChromeVox.isStickyPrefOn) this.format_(node, '@sticky_mode_enabled', buff);
diff --git a/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd b/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd index 4f67c6f..b866bd0 100644 --- a/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd +++ b/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
@@ -2834,6 +2834,9 @@ <message desc="A hint to the user about the special behavior of the Search key with arrows within a text field. This text will be spoken using text to speech along with a description of the text field's name and value. The text is intentionally in fragments to reduce the time needed to convey this information via text to speech. Keys are capitalized and do not contain plus separators because it adds to the spoken announcement's duration. As a general guide, try to read the string aloud." name="IDS_CHROMEVOX_HINT_SEARCH_WITHIN_TEXT_FIELD"> Use Search Left or Right for Home or End, Search Control Left or Right for Control Home or End, Search Up or Down for Page Up or Down. </message> + <message desc="A hint to the user controls that can be double tapped." name="IDS_CHROMEVOX_HINT_DOUBLE_TAP"> + Double tap to activate + </message> </messages> </release> </grit>
diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index e5765f69..50b729b 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd
@@ -12,7 +12,6 @@ </outputs> <release seq="1"> <structures> - <structure name="IDR_BOOKMARK_MANAGER_MAIN" file="bookmark_manager/main.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> <if expr="chromeos"> <structure name="IDR_WALLPAPER_MANAGER_MAIN" file="chromeos/wallpaper_manager/main.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> <if expr="not _google_chrome"> @@ -31,13 +30,6 @@ <include name="IDR_BRAILLE_IME_MAIN_JS" file="chromeos/braille_ime/main.js" type="BINDATA" /> </if> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_MANAGER_SEARCH" file="bookmark_manager/images/bookmark_manager_search.png" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_MANAGER_SEARCH_RTL" file="bookmark_manager/images/bookmark_manager_search_rtl.png" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_MAIN_JS" file="bookmark_manager/js/main.js" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_BMM_LIST_JS" file="bookmark_manager/js/bmm/bookmark_list.js" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_BMM_TREE_JS" file="bookmark_manager/js/bmm/bookmark_tree.js" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_DND_JS" file="bookmark_manager/js/dnd.js" type="BINDATA" /> - <include name="IDR_BOOKMARK_MANAGER_BOOKMARK_BMM_JS" file="bookmark_manager/js/bmm.js" type="BINDATA" /> <!-- Material Design Bookmarks --> <include name="IDR_COMPONENT_MD_BOOKMARKS_BOOKMARKS_HTML" file="md_bookmarks/bookmarks.html" type="BINDATA" /> <!-- Gaia auth extension -->
diff --git a/chrome/browser/resources/settings/crostini_page/crostini_subpage.html b/chrome/browser/resources/settings/crostini_page/crostini_subpage.html index 9c0cf7c0..244b6215 100644 --- a/chrome/browser/resources/settings/crostini_page/crostini_subpage.html +++ b/chrome/browser/resources/settings/crostini_page/crostini_subpage.html
@@ -2,6 +2,7 @@ <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html"> <link rel="import" href="crostini_browser_proxy.html"> <link rel="import" href="../i18n_setup.html"> <link rel="import" href="../prefs/prefs_behavior.html"> @@ -9,7 +10,11 @@ <dom-module id="settings-crostini-subpage"> <template> - <style include="settings-shared"></style> + <style include="settings-shared"> + paper-spinner-lite { + margin: 0 8px; + } + </style> <div id="remove" class="settings-box first" actionable on-click="onRemoveTap_"> <div class="start">$i18n{crostiniRemove}</div> @@ -30,11 +35,15 @@ <div>$i18n{crostiniRemoveDialogMessageOtherDevicesUnaffected}</div> </div> <div slot="button-container"> - <paper-button class="cancel-button" + <paper-spinner-lite id="removeSpinner" + hidden="[[!removingInProgress_]]" + active="[[removingInProgress_]]"> + </paper-spinner-lite> + <paper-button id="cancelButton" class="cancel-button" on-click="onRemoveDialogCancel_"> - $i18n{cancel} + [[cancelButtonText_]] </paper-button> - <paper-button class="action-button" + <paper-button class="action-button" disabled="[[removingInProgress_]]" on-click="onRemoveDialogAccept_"> $i18n{crostiniRemoveDialogAccept} </paper-button>
diff --git a/chrome/browser/resources/settings/crostini_page/crostini_subpage.js b/chrome/browser/resources/settings/crostini_page/crostini_subpage.js index 7dfdef8..8f5fbfb 100644 --- a/chrome/browser/resources/settings/crostini_page/crostini_subpage.js +++ b/chrome/browser/resources/settings/crostini_page/crostini_subpage.js
@@ -10,7 +10,7 @@ Polymer({ is: 'settings-crostini-subpage', - behaviors: [PrefsBehavior], + behaviors: [I18nBehavior, PrefsBehavior], properties: { /** Preferences state. */ @@ -24,12 +24,29 @@ type: Boolean, value: false, }, + + /** @private */ + removingInProgress_: Boolean, + + /** @private */ + cancelButtonText_: { + type: String, + computed: 'computeCancelButtonText_(removingInProgress_)', + }, }, observers: ['onCrostiniEnabledChanged_(prefs.crostini.enabled.value)'], /** @private */ + computeCancelButtonText_() { + return this.i18n(this.removingInProgress_ ? 'close' : 'cancel'); + }, + + /** @private */ onCrostiniEnabledChanged_: function(enabled) { + if (this.$$('#removeDialog')) + this.$$('#removeDialog').close(); + this.removingInProgress_ = false; if (!enabled && settings.getCurrentRoute() == settings.routes.CROSTINI_DETAILS) { settings.navigateToPreviousRoute(); @@ -52,9 +69,11 @@ */ onRemoveDialogAccept_: function() { settings.CrostiniBrowserProxyImpl.getInstance().requestRemoveCrostini(); - this.$$('#removeDialog').close(); + this.removingInProgress_ = true; + // Sub-page will be closed in onCrostiniEnabledChanged_ call. }, + // TODO(rjwright): Make this actually cancel the uninstall. /** * Handles the remove confirmation dialog 'Cancel' button or a cancel * event.
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h b/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h index 94b5a2b..64e7a26 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h +++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher.h
@@ -8,6 +8,7 @@ #include "base/callback_forward.h" #include "base/optional.h" +class GURL; struct OneGoogleBarData; // Interface for fetching OneGoogleBarData over the network. @@ -32,6 +33,9 @@ // Initiates a fetch from the network. On completion (successful or not), the // callback will be called with the result, which will be nullopt on failure. virtual void Fetch(OneGoogleCallback callback) = 0; + + // Retrieves the URL from which OneGoogleBarData will be fetched. + virtual GURL GetFetchURLForTesting() const = 0; }; #endif // CHROME_BROWSER_SEARCH_ONE_GOOGLE_BAR_ONE_GOOGLE_BAR_FETCHER_H_
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc index 353f7c58..6e15628c3 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc
@@ -13,6 +13,7 @@ #include "base/values.h" #include "chrome/browser/search/one_google_bar/one_google_bar_data.h" #include "chrome/common/chrome_content_client.h" +#include "chrome/common/webui_url_constants.h" #include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/browser/google_util.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" @@ -133,9 +134,7 @@ using FetchDoneCallback = base::OnceCallback<void(const net::URLFetcher*)>; AuthenticatedURLFetcher(net::URLRequestContextGetter* request_context, - const GURL& google_base_url, - const std::string& application_locale, - const base::Optional<std::string>& api_url_override, + GURL api_url, bool account_consistency_mirror_required, FetchDoneCallback callback); ~AuthenticatedURLFetcher() override = default; @@ -143,16 +142,13 @@ void Start(); private: - GURL GetApiUrl() const; - std::string GetExtraRequestHeaders(const GURL& url) const; + std::string GetExtraRequestHeaders() const; // URLFetcherDelegate implementation. void OnURLFetchComplete(const net::URLFetcher* source) override; net::URLRequestContextGetter* const request_context_; - const GURL google_base_url_; - const std::string application_locale_; - const base::Optional<std::string> api_url_override_; + const GURL api_url_; #if defined(OS_CHROMEOS) const bool account_consistency_mirror_required_; #endif @@ -165,43 +161,23 @@ OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::AuthenticatedURLFetcher( net::URLRequestContextGetter* request_context, - const GURL& google_base_url, - const std::string& application_locale, - const base::Optional<std::string>& api_url_override, + GURL api_url, bool account_consistency_mirror_required, FetchDoneCallback callback) : request_context_(request_context), - google_base_url_(google_base_url), - application_locale_(application_locale), - api_url_override_(api_url_override), + api_url_(std::move(api_url)), #if defined(OS_CHROMEOS) account_consistency_mirror_required_(account_consistency_mirror_required), #endif callback_(std::move(callback)) {} -GURL OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetApiUrl() const { - GURL api_url = - google_base_url_.Resolve(api_url_override_.value_or(kNewTabOgbApiPath)); - - // Add the "hl=" parameter. - api_url = net::AppendQueryParameter(api_url, "hl", application_locale_); - - // Add the "async=" parameter. We can't use net::AppendQueryParameter for - // this because we need the ":" to remain unescaped. - GURL::Replacements replacements; - std::string query = api_url.query(); - query += "&async=fixed:0"; - replacements.SetQueryStr(query); - return api_url.ReplaceComponents(replacements); -} - std::string -OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetExtraRequestHeaders( - const GURL& url) const { +OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::GetExtraRequestHeaders() + const { net::HttpRequestHeaders headers; // Note: It's OK to pass SignedIn::kNo if it's unknown, as it does not affect // transmission of experiments coming from the variations server. - variations::AppendVariationHeaders(url, variations::InIncognito::kNo, + variations::AppendVariationHeaders(api_url_, variations::InIncognito::kNo, variations::SignedIn::kNo, &headers); #if defined(OS_CHROMEOS) signin::ChromeConnectedHeaderHelper chrome_connected_header_helper( @@ -218,7 +194,7 @@ } std::string chrome_connected_header_value = chrome_connected_header_helper.BuildRequestHeader( - /*is_header_request=*/true, url, + /*is_header_request=*/true, api_url_, // Account ID is only needed for (drive|docs).google.com. /*account_id=*/std::string(), profile_mode); if (!chrome_connected_header_value.empty()) { @@ -230,7 +206,6 @@ } void OneGoogleBarFetcherImpl::AuthenticatedURLFetcher::Start() { - GURL url = GetApiUrl(); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("one_google_bar_service", R"( semantics { @@ -255,12 +230,15 @@ } } })"); - url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this, - traffic_annotation); + url_fetcher_ = net::URLFetcher::Create(0, api_url_, net::URLFetcher::GET, + this, traffic_annotation); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_AUTH_DATA); - url_fetcher_->SetExtraRequestHeaders(GetExtraRequestHeaders(url)); + url_fetcher_->SetExtraRequestHeaders(GetExtraRequestHeaders()); + + url_fetcher_->SetInitiator( + url::Origin::Create(GURL(chrome::kChromeUINewTabURL))); url_fetcher_->Start(); } @@ -288,20 +266,39 @@ void OneGoogleBarFetcherImpl::Fetch(OneGoogleCallback callback) { callbacks_.push_back(std::move(callback)); + // Note: If there is an ongoing request, abandon it. It's possible that + // something has changed in the meantime (e.g. signin state) that would make + // the result obsolete. + pending_request_ = std::make_unique<AuthenticatedURLFetcher>( + request_context_, GetApiUrl(), account_consistency_mirror_required_, + base::BindOnce(&OneGoogleBarFetcherImpl::FetchDone, + base::Unretained(this))); + pending_request_->Start(); +} + +GURL OneGoogleBarFetcherImpl::GetFetchURLForTesting() const { + return GetApiUrl(); +} + +GURL OneGoogleBarFetcherImpl::GetApiUrl() const { GURL google_base_url = google_util::CommandLineGoogleBaseURL(); if (!google_base_url.is_valid()) { google_base_url = google_url_tracker_->google_url(); } - // Note: If there is an ongoing request, abandon it. It's possible that - // something has changed in the meantime (e.g. signin state) that would make - // the result obsolete. - pending_request_ = std::make_unique<AuthenticatedURLFetcher>( - request_context_, google_base_url, application_locale_, api_url_override_, - account_consistency_mirror_required_, - base::BindOnce(&OneGoogleBarFetcherImpl::FetchDone, - base::Unretained(this))); - pending_request_->Start(); + GURL api_url = + google_base_url.Resolve(api_url_override_.value_or(kNewTabOgbApiPath)); + + // Add the "hl=" parameter. + api_url = net::AppendQueryParameter(api_url, "hl", application_locale_); + + // Add the "async=" parameter. We can't use net::AppendQueryParameter for + // this because we need the ":" to remain unescaped. + GURL::Replacements replacements; + std::string query = api_url.query(); + query += "&async=fixed:0"; + replacements.SetQueryStr(query); + return api_url.ReplaceComponents(replacements); } void OneGoogleBarFetcherImpl::FetchDone(const net::URLFetcher* source) {
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h index 01042721..2542ef8de 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h +++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.h
@@ -46,6 +46,9 @@ private: class AuthenticatedURLFetcher; + GURL GetFetchURLForTesting() const override; + GURL GetApiUrl() const; + void FetchDone(const net::URLFetcher* source); void JsonParsed(std::unique_ptr<base::Value> value);
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc b/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc index 3d6080b9..2670127 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc
@@ -33,6 +33,8 @@ callbacks_.push_back(std::move(callback)); } + GURL GetFetchURLForTesting() const override { return GURL(); } + size_t GetCallbackCount() const { return callbacks_.size(); } void RespondToAllCallbacks(Status status,
diff --git a/chrome/browser/sessions/session_restore_android.cc b/chrome/browser/sessions/session_restore_android.cc index 8ef694a..7e4fec56 100644 --- a/chrome/browser/sessions/session_restore_android.cc +++ b/chrome/browser/sessions/session_restore_android.cc
@@ -34,8 +34,7 @@ sessions::ContentSerializedNavigationBuilder::ToNavigationEntries( session_tab.navigations, profile); std::unique_ptr<content::WebContents> new_web_contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(context))); + content::WebContents::Create(content::WebContents::CreateParams(context)); content::WebContents* raw_new_web_contents = new_web_contents.get(); int selected_index = session_tab.normalized_navigation_index(); new_web_contents->GetController().Restore(
diff --git a/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate.cc b/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate.cc index 64c1329..2d3afb6 100644 --- a/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate.cc +++ b/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate.cc
@@ -32,7 +32,7 @@ const char kAccountIdPrefix[] = "AccountId-"; const size_t kAccountIdPrefixLength = 10; -// Used to records token state transitions in histograms. +// Used to record token state transitions in histograms. // Do not change existing values, new values can only be added at the end. enum class TokenStateTransition { // Update events. @@ -68,6 +68,21 @@ NUM_LOAD_TOKEN_FROM_DB_STATUS }; +// Used to record events related to token revocation requests in histograms. +// Do not change existing values, new values can only be added at the end. +enum class TokenRevocationRequestProgress { + // The request was created. + kRequestCreated = 0, + // The request was sent over the network. + kRequestStarted = 1, + // The network request completed with a failure. + kRequestFailed = 2, + // The network request completed with a success. + kRequestSucceeded = 3, + + kMaxValue = kRequestSucceeded +}; + // Adds a sample to the TokenStateTransition histogram. Encapsuled in a function // to reduce executable size, because histogram macros may generate a lot of // code. @@ -76,6 +91,15 @@ TokenStateTransition::kCount); } +// Adds a sample to the TokenRevocationRequestProgress histogram. Encapsuled in +// a function to reduce executable size, because histogram macros may generate a +// lot of code. +void RecordRefreshTokenRevocationRequestEvent( + TokenRevocationRequestProgress event) { + UMA_HISTOGRAM_ENUMERATION("Signin.RefreshTokenRevocationRequestProgress", + event); +} + // Record metrics when a token was updated. void RecordTokenChanged(const std::string& existing_token, const std::string& new_token) { @@ -212,7 +236,8 @@ private: // GaiaAuthConsumer overrides: - void OnOAuth2RevokeTokenCompleted() override; + void OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) override; MutableProfileOAuth2TokenServiceDelegate* token_service_delegate_; GaiaAuthFetcher fetcher_; @@ -231,6 +256,8 @@ GaiaConstants::kChromeSource, token_service_delegate_->GetRequestContext()), weak_ptr_factory_(this) { + RecordRefreshTokenRevocationRequestEvent( + TokenRevocationRequestProgress::kRequestCreated); client->DelayNetworkCall( base::Bind(&MutableProfileOAuth2TokenServiceDelegate:: RevokeServerRefreshToken::Start, @@ -243,6 +270,8 @@ const std::string& refresh_token) { if (!rsrt) return; + RecordRefreshTokenRevocationRequestEvent( + TokenRevocationRequestProgress::kRequestStarted); rsrt->fetcher_.StartRevokeOAuth2Token(refresh_token); } @@ -251,7 +280,13 @@ } void MutableProfileOAuth2TokenServiceDelegate::RevokeServerRefreshToken:: - OnOAuth2RevokeTokenCompleted() { + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) { + RecordRefreshTokenRevocationRequestEvent( + (status == GaiaAuthConsumer::TokenRevocationStatus::kSuccess) + ? TokenRevocationRequestProgress::kRequestSucceeded + : TokenRevocationRequestProgress::kRequestFailed); + UMA_HISTOGRAM_ENUMERATION("Signin.RefreshTokenRevocationStatus", status); // |this| pointer will be deleted when removed from the vector, so don't // access any members after call to erase(). token_service_delegate_->server_revokes_.erase(std::find_if(
diff --git a/chrome/browser/signin/token_revoker_test_utils.cc b/chrome/browser/signin/token_revoker_test_utils.cc index a5b1967..b93cf77e 100644 --- a/chrome/browser/signin/token_revoker_test_utils.cc +++ b/chrome/browser/signin/token_revoker_test_utils.cc
@@ -26,7 +26,8 @@ message_loop_runner_->Run(); } -void RefreshTokenRevoker::OnOAuth2RevokeTokenCompleted() { +void RefreshTokenRevoker::OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) { DVLOG(1) << "TokenRevoker OnOAuth2RevokeTokenCompleted"; message_loop_runner_->Quit(); }
diff --git a/chrome/browser/signin/token_revoker_test_utils.h b/chrome/browser/signin/token_revoker_test_utils.h index e60624a..8e75d9e 100644 --- a/chrome/browser/signin/token_revoker_test_utils.h +++ b/chrome/browser/signin/token_revoker_test_utils.h
@@ -25,7 +25,8 @@ void Revoke(const std::string& token); // Called when token is revoked. - void OnOAuth2RevokeTokenCompleted() override; + void OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) override; private: GaiaAuthFetcher gaia_fetcher_;
diff --git a/chrome/browser/site_per_process_interactive_browsertest.cc b/chrome/browser/site_per_process_interactive_browsertest.cc index 5ba88173..a9d0e9b 100644 --- a/chrome/browser/site_per_process_interactive_browsertest.cc +++ b/chrome/browser/site_per_process_interactive_browsertest.cc
@@ -1213,11 +1213,11 @@ // Add a fresh new WebContents for which we add our own version of the // ChromePasswordManagerClient that uses a custom TestAutofillClient. std::unique_ptr<content::WebContents> new_contents = - base::WrapUnique(content::WebContents::Create( + content::WebContents::Create( content::WebContents::CreateParams(browser() ->tab_strip_model() ->GetActiveWebContents() - ->GetBrowserContext()))); + ->GetBrowserContext())); ASSERT_TRUE(new_contents); ASSERT_FALSE( ChromePasswordManagerClient::FromWebContents(new_contents.get()));
diff --git a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc index 3ea91e2..12a52d1 100644 --- a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc +++ b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
@@ -1596,9 +1596,9 @@ Browser::CreateParams(browser()->profile(), true)); content::WebContents* original_contents = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); raw_contents->SetDelegate(delegate); @@ -1674,9 +1674,9 @@ Browser::CreateParams(browser()->profile(), true)); content::WebContents* original_contents = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); raw_contents->SetDelegate(delegate); @@ -1768,9 +1768,9 @@ Browser::CreateParams(browser()->profile(), true)); content::WebContents* original_contents = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); raw_contents->SetDelegate(delegate); @@ -1849,8 +1849,8 @@ ASSERT_TRUE(tab); std::unique_ptr<content::WebContents> new_contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(tab->GetBrowserContext()))); + content::WebContents::Create( + content::WebContents::CreateParams(tab->GetBrowserContext())); content::NavigationController& controller = new_contents->GetController(); SecurityStateTabHelper::CreateForWebContents(new_contents.get()); CheckSecurityInfoForNonSecure(new_contents.get()); @@ -2031,9 +2031,9 @@ Browser::CreateParams(browser()->profile(), true)); content::WebContents* original_contents = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); ASSERT_TRUE(raw_contents->GetBrowserContext()->IsOffTheRecord()); @@ -2094,9 +2094,9 @@ Browser::CreateParams(browser()->profile(), true)); content::WebContents* original_contents = browser()->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); ASSERT_TRUE(raw_contents->GetBrowserContext()->IsOffTheRecord()); @@ -2178,9 +2178,9 @@ Browser::CreateParams(guest_browser->profile(), true)); content::WebContents* original_contents = guest_browser->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> contents = base::WrapUnique( + std::unique_ptr<content::WebContents> contents = content::WebContents::Create(content::WebContents::CreateParams( - original_contents->GetBrowserContext()))); + original_contents->GetBrowserContext())); content::WebContents* raw_contents = contents.get(); ASSERT_TRUE(raw_contents); ASSERT_TRUE(raw_contents->GetBrowserContext()->IsOffTheRecord());
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index 15654c8..eb15ad97 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -5472,8 +5472,7 @@ restored_entry->SetPageState(entry->GetPageState()); WebContents::CreateParams params(tab->GetBrowserContext()); - std::unique_ptr<WebContents> tab2 = - base::WrapUnique(WebContents::Create(params)); + std::unique_ptr<WebContents> tab2 = WebContents::Create(params); WebContents* raw_tab2 = tab2.get(); tab->GetDelegate()->AddNewContents(nullptr, std::move(tab2), WindowOpenDisposition::NEW_FOREGROUND_TAB,
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 4c98a31..da90ef0 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1529,8 +1529,6 @@ "unload_controller.h", "webui/app_launcher_login_handler.cc", "webui/app_launcher_login_handler.h", - "webui/bookmarks_ui.cc", - "webui/bookmarks_ui.h", "webui/browsing_history_handler.cc", "webui/browsing_history_handler.h", "webui/chrome_web_contents_handler.cc",
diff --git a/chrome/browser/ui/android/tab_model/android_live_tab_context.cc b/chrome/browser/ui/android/tab_model/android_live_tab_context.cc index 6afed5d7..cf2cd82 100644 --- a/chrome/browser/ui/android/tab_model/android_live_tab_context.cc +++ b/chrome/browser/ui/android/tab_model/android_live_tab_context.cc
@@ -92,15 +92,17 @@ navigations, profile); // Restore web contents with navigation history. - content::WebContents* web_contents = content::WebContents::Create( - content::WebContents::CreateParams(profile)); + std::unique_ptr<content::WebContents> web_contents = + content::WebContents::Create(content::WebContents::CreateParams(profile)); + content::WebContents* raw_web_contents = web_contents.get(); web_contents->GetController().Restore( selected_navigation, content::RestoreType::CURRENT_SESSION, &nav_entries); - // Create new tab. - tab_model_->CreateTab(nullptr, web_contents, -1); - web_contents->GetController().LoadIfNecessary(); - return sessions::ContentLiveTab::GetForWebContents(web_contents); + // Create new tab. Ownership is passed into java, which in turn creates a new + // TabAndroid instance to own the WebContents. + tab_model_->CreateTab(nullptr, web_contents.release(), -1); + raw_web_contents->GetController().LoadIfNecessary(); + return sessions::ContentLiveTab::GetForWebContents(raw_web_contents); } // Currently does nothing.
diff --git a/chrome/browser/ui/app_list/crostini/crostini_app_item.cc b/chrome/browser/ui/app_list/crostini/crostini_app_item.cc index 5bfa195..7c3ae4a1 100644 --- a/chrome/browser/ui/app_list/crostini/crostini_app_item.cc +++ b/chrome/browser/ui/app_list/crostini/crostini_app_item.cc
@@ -47,8 +47,14 @@ void CrostiniAppItem::Activate(int event_flags) { LaunchCrostiniApp(profile(), id()); - // TODO(timloh): Detect and do something if launching failed, as otherwise - // the app launcher remains open and there's no feedback. + + // TODO(timloh): Launching Crostini apps can take a few seconds if the + // container is not currently running. Hiding the launcher at least provides + // the user some feedback that they actually clicked an icon. We should make + // this better, e.g. by showing some sort of spinner. We also need to handle + // failures to start the container or app, as those are currently ignored. + if (!GetController()->IsHomeLauncherEnabledInTabletMode()) + GetController()->DismissView(); } void CrostiniAppItem::GetContextMenuModel(GetMenuModelCallback callback) {
diff --git a/chrome/browser/ui/app_list/crostini/crostini_installer_view.cc b/chrome/browser/ui/app_list/crostini/crostini_installer_view.cc index 1941def..4bbcc93 100644 --- a/chrome/browser/ui/app_list/crostini/crostini_installer_view.cc +++ b/chrome/browser/ui/app_list/crostini/crostini_installer_view.cc
@@ -102,7 +102,6 @@ progress_bar_ = new views::ProgressBar(); AddChildView(progress_bar_); - GetWidget()->SetSize(GetWidget()->non_client_view()->GetPreferredSize()); StepProgress(); // Kick off the Crostini Restart sequence. We will be added as an observer. @@ -142,7 +141,8 @@ views::LayoutProvider* provider = views::LayoutProvider::Get(); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, - provider->GetInsetsMetric(views::InsetsMetric::INSETS_DIALOG))); + provider->GetInsetsMetric(views::InsetsMetric::INSETS_DIALOG), + provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL))); set_margins(provider->GetDialogInsetsForContentType( views::DialogContentType::TEXT, views::DialogContentType::TEXT)); @@ -173,6 +173,7 @@ } SetMessageLabel(); DialogModelChanged(); + GetWidget()->SetSize(GetWidget()->non_client_view()->GetPreferredSize()); } void CrostiniInstallerView::HandleError(const base::string16& error_message) {
diff --git a/chrome/browser/ui/ash/chrome_keyboard_ui.cc b/chrome/browser/ui/ash/chrome_keyboard_ui.cc index 1c7d482..53803e1 100644 --- a/chrome/browser/ui/ash/chrome_keyboard_ui.cc +++ b/chrome/browser/ui/ash/chrome_keyboard_ui.cc
@@ -312,7 +312,7 @@ aura::Window* ChromeKeyboardUI::GetContentsWindow() { if (!keyboard_contents_) { - keyboard_contents_.reset(CreateWebContents()); + keyboard_contents_ = CreateWebContents(); keyboard_contents_->SetDelegate(new ChromeKeyboardContentsDelegate(this)); SetupWebContents(keyboard_contents_.get()); LoadContents(GetVirtualKeyboardUrl()); @@ -438,7 +438,7 @@ return keyboard_contents_->GetNativeView()->GetRootWindow(); } -content::WebContents* ChromeKeyboardUI::CreateWebContents() { +std::unique_ptr<content::WebContents> ChromeKeyboardUI::CreateWebContents() { content::BrowserContext* context = browser_context(); return content::WebContents::Create(content::WebContents::CreateParams( context,
diff --git a/chrome/browser/ui/ash/chrome_keyboard_ui.h b/chrome/browser/ui/ash/chrome_keyboard_ui.h index d2de99e6c..52c19e4 100644 --- a/chrome/browser/ui/ash/chrome_keyboard_ui.h +++ b/chrome/browser/ui/ash/chrome_keyboard_ui.h
@@ -80,7 +80,7 @@ const aura::Window* GetKeyboardRootWindow() const; - virtual content::WebContents* CreateWebContents(); + virtual std::unique_ptr<content::WebContents> CreateWebContents(); private: friend class TestApi;
diff --git a/chrome/browser/ui/ash/chrome_keyboard_ui_unittest.cc b/chrome/browser/ui/ash/chrome_keyboard_ui_unittest.cc index b98694ef..ab13bf8f 100644 --- a/chrome/browser/ui/ash/chrome_keyboard_ui_unittest.cc +++ b/chrome/browser/ui/ash/chrome_keyboard_ui_unittest.cc
@@ -15,9 +15,9 @@ class TestChromeKeyboardUI : public ChromeKeyboardUI { public: - TestChromeKeyboardUI(content::BrowserContext* context, - content::WebContents* contents) - : ChromeKeyboardUI(context), contents_(contents) {} + explicit TestChromeKeyboardUI(std::unique_ptr<content::WebContents> contents) + : ChromeKeyboardUI(contents->GetBrowserContext()), + contents_(std::move(contents)) {} ~TestChromeKeyboardUI() override {} ui::InputMethod* GetInputMethod() override { return nullptr; } @@ -25,10 +25,12 @@ const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) {} - content::WebContents* CreateWebContents() override { return contents_; } + std::unique_ptr<content::WebContents> CreateWebContents() override { + return std::move(contents_); + } private: - content::WebContents* contents_; + std::unique_ptr<content::WebContents> contents_; DISALLOW_COPY_AND_ASSIGN(TestChromeKeyboardUI); }; @@ -39,8 +41,9 @@ // A test for crbug.com/734534 TEST_F(ChromeKeyboardUITest, DoesNotCrashWhenParentDoesNotExist) { - content::WebContents* contents = CreateTestWebContents(); - TestChromeKeyboardUI keyboard_ui(contents->GetBrowserContext(), contents); + std::unique_ptr<content::WebContents> contents = + base::WrapUnique(CreateTestWebContents()); + TestChromeKeyboardUI keyboard_ui(std::move(contents)); EXPECT_FALSE(keyboard_ui.HasContentsWindow()); aura::Window* view = keyboard_ui.GetContentsWindow();
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc index 15ae192..645d988 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc
@@ -555,7 +555,7 @@ if (!ash_util::IsRunningInMash()) { // Force on-screen keyboard to reset. if (keyboard::IsKeyboardEnabled()) - ash::Shell::Get()->CreateKeyboard(); + ash::Shell::Get()->ReloadKeyboard(); } }
diff --git a/chrome/browser/ui/ash/launcher/crostini_shelf_context_menu.cc b/chrome/browser/ui/ash/launcher/crostini_shelf_context_menu.cc index 805ccae..77afe7b 100644 --- a/chrome/browser/ui/ash/launcher/crostini_shelf_context_menu.cc +++ b/chrome/browser/ui/ash/launcher/crostini_shelf_context_menu.cc
@@ -5,6 +5,8 @@ #include "chrome/browser/ui/ash/launcher/crostini_shelf_context_menu.h" #include "ash/public/cpp/shelf_item.h" +#include "chrome/browser/chromeos/crostini/crostini_registry_service.h" +#include "chrome/browser/chromeos/crostini/crostini_registry_service_factory.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/grit/generated_resources.h" #include "ui/base/ui_base_features.h" @@ -20,6 +22,14 @@ CrostiniShelfContextMenu::~CrostiniShelfContextMenu() {} void CrostiniShelfContextMenu::Init() { + const crostini::CrostiniRegistryService* registry_service = + crostini::CrostiniRegistryServiceFactory::GetForProfile( + controller()->profile()); + std::unique_ptr<crostini::CrostiniRegistryService::Registration> + registration = registry_service->GetRegistration(item().id.app_id); + if (registration) + AddPinMenu(); + if (controller()->IsOpen(item().id)) AddItemWithStringId(MENU_CLOSE, IDS_LAUNCHER_CONTEXT_MENU_CLOSE); else
diff --git a/chrome/browser/ui/bookmarks/bookmark_unittest.cc b/chrome/browser/ui/bookmarks/bookmark_unittest.cc index 0d5633c5..800f5fa7 100644 --- a/chrome/browser/ui/bookmarks/bookmark_unittest.cc +++ b/chrome/browser/ui/bookmarks/bookmark_unittest.cc
@@ -28,8 +28,8 @@ TEST_F(BookmarkTest, DetachedBookmarkBarOnCustomNTP) { // Create a empty commited web contents. std::unique_ptr<content::WebContents> web_contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(browser()->profile()))); + content::WebContents::Create( + content::WebContents::CreateParams(browser()->profile())); web_contents->GetController().LoadURL(GURL(url::kAboutBlankURL), content::Referrer(), ui::PAGE_TRANSITION_LINK,
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index ffcf36b0..ee9ce25 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -1083,8 +1083,8 @@ ui_test_utils::NavigateToURL(browser(), url); - std::unique_ptr<WebContents> app_contents = base::WrapUnique( - WebContents::Create(WebContents::CreateParams(browser()->profile()))); + std::unique_ptr<WebContents> app_contents = + WebContents::Create(WebContents::CreateParams(browser()->profile())); extensions::TabHelper::CreateForWebContents(app_contents.get()); extensions::TabHelper* extensions_tab_helper = extensions::TabHelper::FromWebContents(app_contents.get());
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index e817173df..c79e9c6 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -413,7 +413,7 @@ #endif std::unique_ptr<WebContents> target_contents = - base::WrapUnique(WebContents::Create(create_params)); + WebContents::Create(create_params); // New tabs can have WebUI URLs that will make calls back to arbitrary // tab helpers, so the entire set of tab helpers needs to be set up
diff --git a/chrome/browser/ui/browser_navigator_browsertest.cc b/chrome/browser/ui/browser_navigator_browsertest.cc index 4bcf9eb..e291f041 100644 --- a/chrome/browser/ui/browser_navigator_browsertest.cc +++ b/chrome/browser/ui/browser_navigator_browsertest.cc
@@ -159,7 +159,7 @@ create_params.initial_size = base_web_contents->GetContainerBounds().size(); } - return base::WrapUnique(WebContents::Create(create_params)); + return WebContents::Create(create_params); } void BrowserNavigatorTest::RunSuppressTest(WindowOpenDisposition disposition) {
diff --git a/chrome/browser/ui/chrome_pages.cc b/chrome/browser/ui/chrome_pages.cc index 6c629b3..0dc6fdc 100644 --- a/chrome/browser/ui/chrome_pages.cc +++ b/chrome/browser/ui/chrome_pages.cc
@@ -70,8 +70,7 @@ void OpenBookmarkManagerForNode(Browser* browser, int64_t node_id) { GURL url = GURL(kChromeUIBookmarksURL) .Resolve(base::StringPrintf( - MdBookmarksUI::IsEnabled() ? "/?id=%s" : "/#%s", - base::Int64ToString(node_id).c_str())); + "/?id=%s", base::Int64ToString(node_id).c_str())); NavigateParams params(GetSingletonTabNavigateParams(browser, url)); params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE; ShowSingletonTabOverwritingNTP(browser, std::move(params));
diff --git a/chrome/browser/ui/cocoa/infobars/confirm_infobar_controller_unittest.mm b/chrome/browser/ui/cocoa/infobars/confirm_infobar_controller_unittest.mm index 4a73c86..f4180ac6 100644 --- a/chrome/browser/ui/cocoa/infobars/confirm_infobar_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/infobars/confirm_infobar_controller_unittest.mm
@@ -57,13 +57,12 @@ public: void SetUp() override { CocoaProfileTest::SetUp(); - web_contents_.reset( - WebContents::Create(WebContents::CreateParams(profile()))); - InfoBarService::CreateForWebContents(web_contents_.get()); + web_contents_ = WebContents::Create(WebContents::CreateParams(profile())); + InfoBarService::CreateForWebContents(web_contents_.get()); - std::unique_ptr<infobars::InfoBarDelegate> delegate( - new MockConfirmInfoBarDelegate(this)); - infobar_ = new InfoBarCocoa(std::move(delegate)); + std::unique_ptr<infobars::InfoBarDelegate> delegate( + new MockConfirmInfoBarDelegate(this)); + infobar_ = new InfoBarCocoa(std::move(delegate)); infobar_->SetOwner(InfoBarService::FromWebContents(web_contents_.get())); controller_.reset([[TestConfirmInfoBarController alloc]
diff --git a/chrome/browser/ui/cocoa/infobars/infobar_container_controller_unittest.mm b/chrome/browser/ui/cocoa/infobars/infobar_container_controller_unittest.mm index 2fa1141..d83e6e0 100644 --- a/chrome/browser/ui/cocoa/infobars/infobar_container_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/infobars/infobar_container_controller_unittest.mm
@@ -25,8 +25,8 @@ class InfoBarContainerControllerTest : public CocoaProfileTest { void SetUp() override { CocoaProfileTest::SetUp(); - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile()))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile())); InfoBarService::CreateForWebContents(web_contents_.get()); resizeDelegate_.reset([[ViewResizerPong alloc] init]);
diff --git a/chrome/browser/ui/cocoa/infobars/translate_infobar_unittest.mm b/chrome/browser/ui/cocoa/infobars/translate_infobar_unittest.mm index 1c17930..620a14c 100644 --- a/chrome/browser/ui/cocoa/infobars/translate_infobar_unittest.mm +++ b/chrome/browser/ui/cocoa/infobars/translate_infobar_unittest.mm
@@ -80,8 +80,7 @@ void SetUp() override { translate::TranslateLanguageList::DisableUpdate(); CocoaProfileTest::SetUp(); - web_contents_.reset( - WebContents::Create(WebContents::CreateParams(profile()))); + web_contents_ = WebContents::Create(WebContents::CreateParams(profile())); InfoBarService::CreateForWebContents(web_contents_.get()); ChromeTranslateClient::CreateForWebContents(web_contents_.get()); }
diff --git a/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm b/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm index 657865bc..85155ca6 100644 --- a/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm +++ b/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm
@@ -193,8 +193,8 @@ if ((self = [super initWithWindow:window])) { webContents_ = webContents; - dialogWebContents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile))); + dialogWebContents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile)); window.get().contentView = dialogWebContents_->GetNativeView(); webContentsDelegate_.reset(new UserManagerProfileDialogDelegate()); dialogWebContents_->SetDelegate(webContentsDelegate_.get()); @@ -300,8 +300,8 @@ userManagerObserver_ = userManagerObserver; // Initialize the web view. - webContents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile))); + webContents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile)); window.contentView = webContents_->GetNativeView(); // When a window has layer-backed subviews, its contentView must be
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm b/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm index 7f519f59..5280270 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm
@@ -171,8 +171,8 @@ TabView* CreateTab() { std::unique_ptr<WebContents> web_contents = - base::WrapUnique(WebContents::Create(content::WebContents::CreateParams( - profile(), SiteInstance::Create(profile())))); + WebContents::Create(content::WebContents::CreateParams( + profile(), SiteInstance::Create(profile()))); model_->AppendWebContents(std::move(web_contents), true); const NSUInteger tab_count = [controller_.get() viewsCount]; return static_cast<TabView*>([controller_.get() viewAtIndex:tab_count - 1]);
diff --git a/chrome/browser/ui/cocoa/translate/translate_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/translate/translate_bubble_controller_unittest.mm index a16f6176..25e5769 100644 --- a/chrome/browser/ui/cocoa/translate/translate_bubble_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/translate/translate_bubble_controller_unittest.mm
@@ -59,9 +59,9 @@ } content::WebContents* AppendToTabStrip() { - std::unique_ptr<content::WebContents> web_contents = base::WrapUnique( + std::unique_ptr<content::WebContents> web_contents = content::WebContents::Create(content::WebContents::CreateParams( - profile(), site_instance_.get()))); + profile(), site_instance_.get())); content::WebContents* raw_web_contents = web_contents.get(); browser()->tab_strip_model()->AppendWebContents(std::move(web_contents), /*foreground=*/true);
diff --git a/chrome/browser/ui/content_settings/content_setting_image_model_browsertest.cc b/chrome/browser/ui/content_settings/content_setting_image_model_browsertest.cc index 88333b1..d95c425 100644 --- a/chrome/browser/ui/content_settings/content_setting_image_model_browsertest.cc +++ b/chrome/browser/ui/content_settings/content_setting_image_model_browsertest.cc
@@ -103,7 +103,7 @@ Profile* profile = browser()->profile(); WebContents::CreateParams create_params(profile); std::unique_ptr<WebContents> other_web_contents = - base::WrapUnique(WebContents::Create(create_params)); + WebContents::Create(create_params); content::WebContents* raw_other_web_contents = other_web_contents.get(); browser()->tab_strip_model()->AppendWebContents(std::move(other_web_contents), true);
diff --git a/chrome/browser/ui/exclusive_access/fullscreen_controller_state_unittest.cc b/chrome/browser/ui/exclusive_access/fullscreen_controller_state_unittest.cc index 0d5c6b3..2627ee6 100644 --- a/chrome/browser/ui/exclusive_access/fullscreen_controller_state_unittest.cc +++ b/chrome/browser/ui/exclusive_access/fullscreen_controller_state_unittest.cc
@@ -461,8 +461,8 @@ ASSERT_TRUE(browser()->window()->IsFullscreen()); std::unique_ptr<content::WebContents> new_web_contents = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(profile()))); + content::WebContents::Create( + content::WebContents::CreateParams(profile())); std::unique_ptr<content::WebContents> old_web_contents = browser()->tab_strip_model()->ReplaceWebContentsAt( 0, std::move(new_web_contents));
diff --git a/chrome/browser/ui/extensions/hosted_app_browsertest.cc b/chrome/browser/ui/extensions/hosted_app_browsertest.cc index 86060d2..302d1b2b 100644 --- a/chrome/browser/ui/extensions/hosted_app_browsertest.cc +++ b/chrome/browser/ui/extensions/hosted_app_browsertest.cc
@@ -496,6 +496,23 @@ browser()->tab_strip_model()->GetActiveWebContents()); } +// Tests that creating bookmark apps is disabled in incognito. +IN_PROC_BROWSER_TEST_P(HostedAppTest, CreateShortcutDisabledInIncognito) { + ASSERT_TRUE(https_server()->Start()); + ASSERT_TRUE(embedded_test_server()->Start()); + + Browser* incognito_browser = + OpenURLOffTheRecord(profile(), GetSecureAppURL()); + auto app_menu_model = + std::make_unique<AppMenuModel>(nullptr, incognito_browser); + app_menu_model->Init(); + ui::MenuModel* model = app_menu_model.get(); + int index = -1; + EXPECT_TRUE(app_menu_model->GetModelAndIndexForCommandId( + IDC_CREATE_HOSTED_APP, &model, &index)); + EXPECT_FALSE(model->IsEnabledAt(index)); +} + // Check that the location bar is shown correctly. IN_PROC_BROWSER_TEST_P(HostedAppTest, ShouldShowLocationBar) { ASSERT_TRUE(https_server()->Start());
diff --git a/chrome/browser/ui/ime/ime_window.cc b/chrome/browser/ui/ime/ime_window.cc index fc0148bc..b9be39d 100644 --- a/chrome/browser/ui/ime/ime_window.cc +++ b/chrome/browser/ui/ime/ime_window.cc
@@ -70,7 +70,7 @@ create_params.opener_render_frame_id = opener_render_frame_host->GetRoutingID(); } - web_contents_.reset(content::WebContents::Create(create_params)); + web_contents_ = content::WebContents::Create(create_params); web_contents_->SetDelegate(this); content::OpenURLParams params(gurl, content::Referrer(), WindowOpenDisposition::SINGLETON_TAB,
diff --git a/chrome/browser/ui/omnibox/omnibox_theme.cc b/chrome/browser/ui/omnibox/omnibox_theme.cc index 3f3d1f3..69fcd07 100644 --- a/chrome/browser/ui/omnibox/omnibox_theme.cc +++ b/chrome/browser/ui/omnibox/omnibox_theme.cc
@@ -25,17 +25,6 @@ ui::NativeTheme::kColorId_NumColors; template <class T> -constexpr T NormalHoveredSelectedOrBoth(OmniboxPartState state, - T normal, - T hovered, - T selected, - T hovered_and_selected) { - const T args[] = {normal, hovered, selected, hovered_and_selected}; - DCHECK_LT(static_cast<size_t>(state), arraysize(args)); - return args[static_cast<size_t>(state)]; -} - -template <class T> constexpr T NormalHoveredSelected(OmniboxPartState state, T normal, T hovered, @@ -240,7 +229,7 @@ // background for the best text AA result. return color_utils::BlendTowardOppositeLuma( dark ? gfx::kGoogleGrey800 : SK_ColorWHITE, - NormalHoveredSelectedOrBoth<SkAlpha>(state, 0x00, 0x0F, 0x14, 0x24)); + gfx::ToRoundedInt(GetOmniboxStateAlpha(state) * 0xff)); case OmniboxPart::LOCATION_BAR_TEXT_DEFAULT: case OmniboxPart::RESULTS_TEXT_DEFAULT: return dark ? gfx::kGoogleGrey100 : gfx::kGoogleGrey800; @@ -272,3 +261,23 @@ } return gfx::kPlaceholderColor; } + +float GetOmniboxStateAlpha(OmniboxPartState state) { + // Use default alphas in non-newer Material style. + DCHECK(ui::MaterialDesignController::IsNewerMaterialUi()); + + switch (state) { + case OmniboxPartState::NORMAL: + return 0; + case OmniboxPartState::HOVERED: + return 0.08f; + case OmniboxPartState::SELECTED: + return 0.06f; + case OmniboxPartState::HOVERED_AND_SELECTED: + return GetOmniboxStateAlpha(OmniboxPartState::HOVERED) + + GetOmniboxStateAlpha(OmniboxPartState::SELECTED); + default: + NOTREACHED(); + return 0; + } +}
diff --git a/chrome/browser/ui/omnibox/omnibox_theme.h b/chrome/browser/ui/omnibox/omnibox_theme.h index 88e484c..001bd45e 100644 --- a/chrome/browser/ui/omnibox/omnibox_theme.h +++ b/chrome/browser/ui/omnibox/omnibox_theme.h
@@ -53,4 +53,6 @@ OmniboxTint tint, OmniboxPartState state = OmniboxPartState::NORMAL); +float GetOmniboxStateAlpha(OmniboxPartState state); + #endif // CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_THEME_H_
diff --git a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc index 227e112..2ee9b09a 100644 --- a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc
@@ -36,6 +36,8 @@ std::move(callback).Run(Status::OK, one_google_bar_data_); } + GURL GetFetchURLForTesting() const override { return GURL(); } + void set_one_google_bar_data( const base::Optional<OneGoogleBarData>& one_google_bar_data) { one_google_bar_data_ = one_google_bar_data;
diff --git a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc index 556f9868..f118701b 100644 --- a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc +++ b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc
@@ -176,16 +176,14 @@ class TabStripModelTest : public ChromeRenderViewHostTestHarness { public: std::unique_ptr<WebContents> CreateWebContents() { - return base::WrapUnique( - WebContents::Create(WebContents::CreateParams(profile()))); + return WebContents::Create(WebContents::CreateParams(profile())); } std::unique_ptr<WebContents> CreateWebContentsWithSharedRPH( WebContents* web_contents) { WebContents::CreateParams create_params( profile(), web_contents->GetRenderViewHost()->GetSiteInstance()); - std::unique_ptr<WebContents> retval = - base::WrapUnique(WebContents::Create(create_params)); + std::unique_ptr<WebContents> retval = WebContents::Create(create_params); EXPECT_EQ(retval->GetMainFrame()->GetProcess(), web_contents->GetMainFrame()->GetProcess()); return retval;
diff --git a/chrome/browser/ui/toolbar/app_menu_model.cc b/chrome/browser/ui/toolbar/app_menu_model.cc index be49c40..5c8a704 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.cc +++ b/chrome/browser/ui/toolbar/app_menu_model.cc
@@ -772,7 +772,9 @@ if (extensions::util::IsNewBookmarkAppsEnabled() && banners::AppBannerManager::IsExperimentalAppBannersEnabled()) { const extensions::Extension* pwa = - extensions::util::GetPwaForSecureActiveTab(browser_); + base::FeatureList::IsEnabled(features::kDesktopPWAWindowing) + ? extensions::util::GetPwaForSecureActiveTab(browser_) + : nullptr; if (pwa) { AddItem( IDC_OPEN_IN_PWA_WINDOW,
diff --git a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc index 6298338a..e4ec9fc7 100644 --- a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc +++ b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc
@@ -242,8 +242,6 @@ void BrowserFrameHeaderAsh::LayoutHeaderInternal() { UpdateCaptionButtons(); - caption_button_container_->Layout(); - const gfx::Size caption_button_container_size = caption_button_container_->GetPreferredSize(); caption_button_container_->SetBounds( @@ -251,6 +249,8 @@ caption_button_container_size.width(), caption_button_container_size.height()); + caption_button_container_->Layout(); + if (!window_icon_) return;
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc index 33459ae..28c2a09 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc
@@ -393,6 +393,11 @@ AlignVerticalCenterWith(&text_bounds, caption_button_container_->bounds()); frame_header_origin_text_->SetBoundsRect(text_bounds); } + + // The top right corner must be occupied by a caption button for easy mouse + // access. This check is agnostic to RTL layout. + DCHECK_EQ(caption_button_container_->y(), 0); + DCHECK_EQ(caption_button_container_->bounds().right(), width()); } const char* BrowserNonClientFrameViewAsh::GetClassName() const {
diff --git a/chrome/browser/ui/views/location_bar/bubble_icon_view.cc b/chrome/browser/ui/views/location_bar/bubble_icon_view.cc index 3c181dd..af140ea 100644 --- a/chrome/browser/ui/views/location_bar/bubble_icon_view.cc +++ b/chrome/browser/ui/views/location_bar/bubble_icon_view.cc
@@ -6,11 +6,13 @@ #include "chrome/browser/command_updater.h" #include "chrome/browser/ui/layout_constants.h" +#include "chrome/browser/ui/omnibox/omnibox_theme.h" #include "chrome/browser/ui/views/location_bar/background_with_1_px_border.h" #include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/material_design/material_design_controller.h" #include "ui/events/event.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/paint_vector_icon.h" @@ -41,6 +43,11 @@ suppress_mouse_released_action_(false) { SetBorder(views::CreateEmptyBorder( gfx::Insets(GetLayoutConstant(LOCATION_BAR_ICON_INTERIOR_PADDING)))); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + // Ink drop ripple opacity. + set_ink_drop_visible_opacity( + GetOmniboxStateAlpha(OmniboxPartState::SELECTED)); + } } BubbleIconView::~BubbleIconView() {} @@ -195,13 +202,25 @@ std::unique_ptr<views::InkDropHighlight> BubbleIconView::CreateInkDropHighlight() const { - return CreateDefaultInkDropHighlight( - gfx::RectF(GetMirroredRect(GetContentsBounds())).CenterPoint(), size()); + std::unique_ptr<views::InkDropHighlight> highlight = + CreateDefaultInkDropHighlight( + gfx::RectF(GetMirroredRect(GetContentsBounds())).CenterPoint(), + size()); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + highlight->set_visible_opacity( + GetOmniboxStateAlpha(OmniboxPartState::HOVERED)); + } + return highlight; } SkColor BubbleIconView::GetInkDropBaseColor() const { - return color_utils::DeriveDefaultIconColor(GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TextfieldDefaultColor)); + const SkColor ink_color_opaque = GetNativeTheme()->GetSystemColor( + ui::NativeTheme::kColorId_TextfieldDefaultColor); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + // Opacity of the ink drop is set elsewhere, so just use full opacity here. + return ink_color_opaque; + } + return color_utils::DeriveDefaultIconColor(ink_color_opaque); } std::unique_ptr<views::InkDropMask> BubbleIconView::CreateInkDropMask() const {
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc index a39d76c..fefeebe 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc
@@ -7,6 +7,7 @@ #include <memory> #include "chrome/browser/ui/layout_constants.h" +#include "chrome/browser/ui/omnibox/omnibox_theme.h" #include "chrome/browser/ui/views/location_bar/background_with_1_px_border.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "ui/accessibility/ax_node_data.h" @@ -121,6 +122,11 @@ AddChildView(ink_drop_container_); ink_drop_container_->SetVisible(false); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + // Ink drop ripple opacity. + set_ink_drop_visible_opacity( + GetOmniboxStateAlpha(OmniboxPartState::SELECTED)); + } // Bubbles are given the full internal height of the location bar so that all // child views in the location bar have the same height. The visible height of @@ -295,14 +301,25 @@ std::unique_ptr<views::InkDropHighlight> IconLabelBubbleView::CreateInkDropHighlight() const { - return InkDropHostView::CreateDefaultInkDropHighlight( - gfx::RectF(ink_drop_container_->bounds()).CenterPoint(), - ink_drop_container_->size()); + std::unique_ptr<views::InkDropHighlight> highlight = + CreateDefaultInkDropHighlight( + gfx::RectF(ink_drop_container_->bounds()).CenterPoint(), + ink_drop_container_->size()); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + highlight->set_visible_opacity( + GetOmniboxStateAlpha(OmniboxPartState::HOVERED)); + } + return highlight; } SkColor IconLabelBubbleView::GetInkDropBaseColor() const { - return color_utils::DeriveDefaultIconColor(GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TextfieldDefaultColor)); + const SkColor ink_color_opaque = GetNativeTheme()->GetSystemColor( + ui::NativeTheme::kColorId_TextfieldDefaultColor); + if (ui::MaterialDesignController::IsNewerMaterialUi()) { + // Opacity of the ink drop is set elsewhere, so just use full opacity here. + return ink_color_opaque; + } + return color_utils::DeriveDefaultIconColor(ink_color_opaque); } std::unique_ptr<views::InkDropMask> IconLabelBubbleView::CreateInkDropMask()
diff --git a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc index dd760299..d3085a8 100644 --- a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc
@@ -162,9 +162,8 @@ // Open a new tab with modified ManagePasswordsUIController. content::WebContents* tab = browser->tab_strip_model()->GetActiveWebContents(); - std::unique_ptr<content::WebContents> new_tab = - base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(tab->GetBrowserContext()))); + std::unique_ptr<content::WebContents> new_tab = content::WebContents::Create( + content::WebContents::CreateParams(tab->GetBrowserContext())); content::WebContents* raw_new_tab = new_tab.get(); EXPECT_TRUE(raw_new_tab);
diff --git a/chrome/browser/ui/webui/bookmarks_ui.cc b/chrome/browser/ui/webui/bookmarks_ui.cc deleted file mode 100644 index 1b7347e2..0000000 --- a/chrome/browser/ui/webui/bookmarks_ui.cc +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/bookmarks_ui.h" - -#include "base/memory/ref_counted_memory.h" -#include "base/message_loop/message_loop.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/theme_resources.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_ui.h" -#include "ui/base/resource/resource_bundle.h" - -//////////////////////////////////////////////////////////////////////////////// -// -// BookmarksUIHTMLSource -// -//////////////////////////////////////////////////////////////////////////////// - -BookmarksUIHTMLSource::BookmarksUIHTMLSource() { -} - -std::string BookmarksUIHTMLSource::GetSource() const { - return chrome::kChromeUIBookmarksHost; -} - -void BookmarksUIHTMLSource::StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& callback) { - NOTREACHED() << "We should never get here since the extension should have" - << "been triggered"; - - callback.Run(NULL); -} - -std::string BookmarksUIHTMLSource::GetMimeType(const std::string& path) const { - NOTREACHED() << "We should never get here since the extension should have" - << "been triggered"; - return "text/html"; -} - -BookmarksUIHTMLSource::~BookmarksUIHTMLSource() {} - -//////////////////////////////////////////////////////////////////////////////// -// -// BookmarksUI -// -//////////////////////////////////////////////////////////////////////////////// - -BookmarksUI::BookmarksUI(content::WebUI* web_ui) : WebUIController(web_ui) { - BookmarksUIHTMLSource* html_source = new BookmarksUIHTMLSource(); - - // Set up the chrome://bookmarks/ source. - Profile* profile = Profile::FromWebUI(web_ui); - content::URLDataSource::Add(profile, html_source); -} - -// static -base::RefCountedMemory* BookmarksUI::GetFaviconResourceBytes( - ui::ScaleFactor scale_factor) { - return ui::ResourceBundle::GetSharedInstance(). - LoadDataResourceBytesForScale(IDR_BOOKMARKS_FAVICON, scale_factor); -}
diff --git a/chrome/browser/ui/webui/bookmarks_ui.h b/chrome/browser/ui/webui/bookmarks_ui.h deleted file mode 100644 index f4d2ab6..0000000 --- a/chrome/browser/ui/webui/bookmarks_ui.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_BOOKMARKS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_BOOKMARKS_UI_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_ui_controller.h" -#include "ui/base/layout.h" - -namespace base { -class RefCountedMemory; -} - -// This class provides the source for chrome://bookmarks/ -class BookmarksUIHTMLSource : public content::URLDataSource { - public: - BookmarksUIHTMLSource(); - - // content::URLDataSource implementation. - std::string GetSource() const override; - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& callback) override; - std::string GetMimeType(const std::string& path) const override; - - private: - ~BookmarksUIHTMLSource() override; - - DISALLOW_COPY_AND_ASSIGN(BookmarksUIHTMLSource); -}; - -// This class is used to hook up chrome://bookmarks/ which in turn gets -// overridden by an extension. -class BookmarksUI : public content::WebUIController { - public: - explicit BookmarksUI(content::WebUI* web_ui); - - static base::RefCountedMemory* GetFaviconResourceBytes( - ui::ScaleFactor scale_factor); - - private: - DISALLOW_COPY_AND_ASSIGN(BookmarksUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_BOOKMARKS_UI_H_
diff --git a/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc b/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc deleted file mode 100644 index 132edd2..0000000 --- a/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc +++ /dev/null
@@ -1,120 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_timeouts.h" -#include "build/build_config.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_navigation_observer.h" - -class BookmarksTest : public InProcessBrowserTest { - public: - BookmarksTest() {} - - void SetUpOnMainThread() override { - // Re-enable accessibility checks when audit failures are resolved. - // AX_TEXT_01: http://crbug.com/559201 - // AX_ARIA_08: http://crbug.com/559202 - // EnableAccessibilityChecksForTestCase(true); - } - - void OpenBookmarksManager() { - content::TestNavigationObserver navigation_observer( - browser()->tab_strip_model()->GetActiveWebContents(), - MdBookmarksUI::IsEnabled() ? 1 : 2); - navigation_observer.StartWatchingNewWebContents(); - - // Bring up the bookmarks manager tab. - chrome::ShowBookmarkManager(browser()); - navigation_observer.Wait(); - } - - void AssertIsBookmarksPage(content::WebContents* tab) { - GURL url; - std::string out; - - if (MdBookmarksUI::IsEnabled()) { - ASSERT_TRUE(content::ExecuteScriptAndExtractString( - tab, "domAutomationController.send(location.href)", &out)); - ASSERT_EQ("chrome://bookmarks/", out); - return; - } - - ASSERT_TRUE(content::ExecuteScriptAndExtractString( - tab, - "domAutomationController.send(location.protocol)", - &out)); - ASSERT_EQ("chrome-extension:", out); - ASSERT_TRUE(content::ExecuteScriptAndExtractString( - tab, - "domAutomationController.send(location.pathname)", - &out)); - ASSERT_EQ("/main.html", out); - } -}; - -IN_PROC_BROWSER_TEST_F(BookmarksTest, CommandOpensBookmarksTab) { - ASSERT_EQ(1, browser()->tab_strip_model()->count()); - - // Bring up the bookmarks manager tab. - OpenBookmarksManager(); - ASSERT_EQ(1, browser()->tab_strip_model()->count()); - AssertIsBookmarksPage(browser()->tab_strip_model()->GetActiveWebContents()); -} - -// Flaky on Mac: https://crbug.com/524216 -#if defined(OS_MACOSX) || defined(OS_LINUX) -#define MAYBE_CommandAgainGoesBackToBookmarksTab \ - DISABLED_CommandAgainGoesBackToBookmarksTab -#else -#define MAYBE_CommandAgainGoesBackToBookmarksTab \ - CommandAgainGoesBackToBookmarksTab -#endif - -IN_PROC_BROWSER_TEST_F(BookmarksTest, - MAYBE_CommandAgainGoesBackToBookmarksTab) { - ui_test_utils::NavigateToURL( - browser(), - ui_test_utils::GetTestUrl(base::FilePath(), - base::FilePath().AppendASCII("simple.html"))); - ASSERT_EQ(1, browser()->tab_strip_model()->count()); - - // Bring up the bookmarks manager tab. - OpenBookmarksManager(); - ASSERT_EQ(2, browser()->tab_strip_model()->count()); - - AssertIsBookmarksPage(browser()->tab_strip_model()->GetActiveWebContents()); - - // Switch to first tab and run command again. - browser()->tab_strip_model()->ActivateTabAt(0, true); - chrome::ShowBookmarkManager(browser()); - - // Ensure the bookmarks ui tab is active. - ASSERT_EQ(1, browser()->tab_strip_model()->active_index()); - ASSERT_EQ(2, browser()->tab_strip_model()->count()); -} - -IN_PROC_BROWSER_TEST_F(BookmarksTest, TwoCommandsOneTab) { - content::TestNavigationObserver navigation_observer( - browser()->tab_strip_model()->GetActiveWebContents()); - chrome::ShowBookmarkManager(browser()); - chrome::ShowBookmarkManager(browser()); - navigation_observer.Wait(); - - ASSERT_EQ(1, browser()->tab_strip_model()->count()); -} - -IN_PROC_BROWSER_TEST_F(BookmarksTest, BookmarksLoaded) { - ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIBookmarksURL)); - ASSERT_EQ(1, browser()->tab_strip_model()->count()); - AssertIsBookmarksPage(browser()->tab_strip_model()->GetActiveWebContents()); -}
diff --git a/chrome/browser/ui/webui/browsing_history_handler_unittest.cc b/chrome/browser/ui/webui/browsing_history_handler_unittest.cc index 09476c54..efe43ca 100644 --- a/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chrome/browser/ui/webui/browsing_history_handler_unittest.cc
@@ -115,8 +115,8 @@ web_history_service_ = static_cast<history::FakeWebHistoryService*>( WebHistoryServiceFactory::GetForProfile(profile_.get())); - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile_.get()))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile_.get())); web_ui_.reset(new content::TestWebUI); web_ui_->set_web_contents(web_contents_.get()); }
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 9c60ba8..5a90dc35 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -24,7 +24,6 @@ #include "chrome/browser/ui/history_ui.h" #include "chrome/browser/ui/webui/about_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" -#include "chrome/browser/ui/webui/bookmarks_ui.h" #include "chrome/browser/ui/webui/components_ui.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" #include "chrome/browser/ui/webui/crashes_ui.h" @@ -420,10 +419,8 @@ return &NewWebUI<PageNotAvailableForGuestUI>; } // Bookmarks are part of NTP on Android. - if (url.host_piece() == chrome::kChromeUIBookmarksHost) { - return MdBookmarksUI::IsEnabled() ? &NewWebUI<MdBookmarksUI> - : &NewWebUI<BookmarksUI>; - } + if (url.host_piece() == chrome::kChromeUIBookmarksHost) + return &NewWebUI<MdBookmarksUI>; // Downloads list on Android uses the built-in download manager. if (url.host_piece() == chrome::kChromeUIDownloadsHost) return &NewWebUI<MdDownloadsUI>; @@ -711,10 +708,8 @@ #if BUILDFLAG(ENABLE_EXTENSIONS) ExtensionWebUI::HandleChromeURLOverride(&url, profile); - // All extensions but the bookmark manager get their favicon from the icons - // part of the manifest. - if (url.SchemeIs(extensions::kExtensionScheme) && - url.host_piece() != extension_misc::kBookmarkManagerId) { + // All extensions get their favicon from the icons part of the manifest. + if (url.SchemeIs(extensions::kExtensionScheme)) { ExtensionWebUI::GetFaviconForURL(profile, url, callback); return; } @@ -775,14 +770,7 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( const GURL& page_url, ui::ScaleFactor scale_factor) const { -#if !defined(OS_ANDROID) // Bookmarks are part of NTP on Android. - // The bookmark manager is a chrome extension, so we have to check for it - // before we check for extension scheme. - if (page_url.host_piece() == extension_misc::kBookmarkManagerId || - page_url.host_piece() == chrome::kChromeUIBookmarksHost) { - return BookmarksUI::GetFaviconResourceBytes(scale_factor); - } - +#if !defined(OS_ANDROID) // The extension scheme is handled in GetFaviconForURL. if (page_url.SchemeIs(extensions::kExtensionScheme)) { NOTREACHED(); @@ -818,6 +806,10 @@ return AppLauncherPageUI::GetFaviconResourceBytes(scale_factor); #endif // !defined(OS_CHROMEOS) + // Bookmarks are part of NTP on Android. + if (page_url.host_piece() == chrome::kChromeUIBookmarksHost) + return MdBookmarksUI::GetFaviconResourceBytes(scale_factor); + // Flash is not available on android. if (page_url.host_piece() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(scale_factor);
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc index c42de33..af018abc9 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc +++ b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc
@@ -31,9 +31,9 @@ web_dialog_delegate_(delegate), closed_via_webui_(false) { CHECK(delegate); - web_contents_ = + web_contents_holder_ = WebContents::Create(WebContents::CreateParams(browser_context)); - web_contents_holder_.reset(web_contents_); + web_contents_ = web_contents_holder_.get(); WebContentsObserver::Observe(web_contents_); zoom::ZoomController::CreateForWebContents(web_contents_); if (tab_delegate) {
diff --git a/chrome/browser/ui/webui/identity_internals_ui.cc b/chrome/browser/ui/webui/identity_internals_ui.cc index 6a524d4..ecd1b1f 100644 --- a/chrome/browser/ui/webui/identity_internals_ui.cc +++ b/chrome/browser/ui/webui/identity_internals_ui.cc
@@ -119,7 +119,8 @@ const std::string& extension_id() const { return extension_id_; } // GaiaAuthConsumer implementation. - void OnOAuth2RevokeTokenCompleted() override; + void OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) override; private: // An object used to start a token revoke request. @@ -286,7 +287,8 @@ IdentityInternalsTokenRevoker::~IdentityInternalsTokenRevoker() {} -void IdentityInternalsTokenRevoker::OnOAuth2RevokeTokenCompleted() { +void IdentityInternalsTokenRevoker::OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) { consumer_->OnTokenRevokerDone(this); }
diff --git a/chrome/browser/ui/webui/log_web_ui_url.cc b/chrome/browser/ui/webui/log_web_ui_url.cc index d4d3ba99..cb42bf24 100644 --- a/chrome/browser/ui/webui/log_web_ui_url.cc +++ b/chrome/browser/ui/webui/log_web_ui_url.cc
@@ -26,11 +26,6 @@ bool should_log = web_ui_url.SchemeIs(content::kChromeUIScheme) || web_ui_url.SchemeIs(content::kChromeDevToolsScheme); -#if BUILDFLAG(ENABLE_EXTENSIONS) - if (web_ui_url.SchemeIs(extensions::kExtensionScheme)) - should_log = web_ui_url.host() == extension_misc::kBookmarkManagerId; -#endif - if (should_log) { uint32_t hash = base::Hash(web_ui_url.GetOrigin().spec()); base::UmaHistogramSparse(kWebUICreatedForUrl,
diff --git a/chrome/browser/ui/webui/log_web_ui_url_unittest.cc b/chrome/browser/ui/webui/log_web_ui_url_unittest.cc index 8c9bd36..3af0dde 100644 --- a/chrome/browser/ui/webui/log_web_ui_url_unittest.cc +++ b/chrome/browser/ui/webui/log_web_ui_url_unittest.cc
@@ -17,12 +17,6 @@ // Developer tools scheme. EXPECT_TRUE(webui::LogWebUIUrl(GURL("chrome-devtools://devtools"))); - -#if BUILDFLAG(ENABLE_EXTENSIONS) - // Bookmarks Manager (the only currently allowed extension). - EXPECT_TRUE(webui::LogWebUIUrl(GURL( - "chrome-extension://eemcgdkfndhakfknompkggombfjjjeno"))); -#endif } TEST(LogWebUIUrlTest, InvalidUrls) { @@ -31,7 +25,7 @@ EXPECT_FALSE(webui::LogWebUIUrl(GURL("https://facebook.com"))); EXPECT_FALSE(webui::LogWebUIUrl(GURL("ftp://ftp.mysite.com"))); - // Extensions other than the Bookmarks Manager should also be ignored. + // Extensions schemes should also be ignored. EXPECT_FALSE(webui::LogWebUIUrl(GURL( "chrome-extension://mfehgcgbbipciphmccgaenjidiccnmng"))); }
diff --git a/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc b/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc index 63fcf51..06195fc97 100644 --- a/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc +++ b/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc
@@ -18,10 +18,12 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" +#include "chrome/grit/theme_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" namespace { @@ -226,6 +228,8 @@ } // static -bool MdBookmarksUI::IsEnabled() { - return base::FeatureList::IsEnabled(features::kMaterialDesignBookmarks); +base::RefCountedMemory* MdBookmarksUI::GetFaviconResourceBytes( + ui::ScaleFactor scale_factor) { + return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( + IDR_BOOKMARKS_FAVICON, scale_factor); }
diff --git a/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h b/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h index b864ad6..5b45d17 100644 --- a/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h +++ b/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h
@@ -7,12 +7,18 @@ #include "base/macros.h" #include "content/public/browser/web_ui_controller.h" +#include "ui/base/resource/scale_factor.h" + +namespace base { +class RefCountedMemory; +} class MdBookmarksUI : public content::WebUIController { public: explicit MdBookmarksUI(content::WebUI* web_ui); - static bool IsEnabled(); + static base::RefCountedMemory* GetFaviconResourceBytes( + ui::ScaleFactor scale_factor); private: DISALLOW_COPY_AND_ASSIGN(MdBookmarksUI);
diff --git a/chrome/browser/ui/webui/media/webrtc_logs_ui.cc b/chrome/browser/ui/webui/media/webrtc_logs_ui.cc index 5d33cde..69df161 100644 --- a/chrome/browser/ui/webui/media/webrtc_logs_ui.cc +++ b/chrome/browser/ui/webui/media/webrtc_logs_ui.cc
@@ -77,7 +77,7 @@ //////////////////////////////////////////////////////////////////////////////// // The handler for Javascript messages for the chrome://webrtc-logs/ page. -class WebRtcLogsDOMHandler : public WebUIMessageHandler { +class WebRtcLogsDOMHandler final : public WebUIMessageHandler { public: explicit WebRtcLogsDOMHandler(Profile* profile); ~WebRtcLogsDOMHandler() override;
diff --git a/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc b/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc index b63a5931..4652418 100644 --- a/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc +++ b/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc
@@ -172,8 +172,7 @@ void CreateMediaRouterUI(Profile* profile) { SessionTabHelper::CreateForWebContents(web_contents()); - web_ui_contents_.reset( - WebContents::Create(WebContents::CreateParams(profile))); + web_ui_contents_ = WebContents::Create(WebContents::CreateParams(profile)); web_ui_.set_web_contents(web_ui_contents_.get()); media_router_ui_ = std::make_unique<TestMediaRouterUI>(&web_ui_, &mock_router_); @@ -797,8 +796,7 @@ base::Unretained(&request_callbacks))); SessionTabHelper::CreateForWebContents(web_contents()); - web_ui_contents_.reset( - WebContents::Create(WebContents::CreateParams(profile()))); + web_ui_contents_ = WebContents::Create(WebContents::CreateParams(profile())); web_ui_.set_web_contents(web_ui_contents_.get()); media_router_ui_ = std::make_unique<TestMediaRouterUI>(&web_ui_, &mock_router_);
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc index 785b773..b8341ff 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc
@@ -248,11 +248,11 @@ PrintPreviewHandlerTest() { TestingProfile::Builder builder; profile_ = builder.Build(); - initiator_web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile_.get()))); + initiator_web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile_.get())); content::WebContents* initiator = initiator_web_contents_.get(); - preview_web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(profile_.get()))); + preview_web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(profile_.get())); printing::PrintViewManager::CreateForWebContents(initiator); printing::PrintViewManager::FromWebContents(initiator)->PrintPreviewNow( initiator->GetMainFrame(), false);
diff --git a/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc b/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc index 2014f38b..4478537 100644 --- a/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc +++ b/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc
@@ -109,8 +109,8 @@ protected: SyncInternalsMessageHandlerTest() { site_instance_ = content::SiteInstance::Create(&profile_); - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(&profile_, site_instance_.get()))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(&profile_, site_instance_.get())); web_ui_.set_web_contents(web_contents_.get()); test_sync_service_ = static_cast<TestSyncService*>( ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 4aa7e21d..63ac7d8 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -346,10 +346,6 @@ base::FEATURE_ENABLED_BY_DEFAULT}; #endif -// Enables or disables the Material Design version of chrome://bookmarks. -const base::Feature kMaterialDesignBookmarks{"MaterialDesignBookmarks", - base::FEATURE_ENABLED_BY_DEFAULT}; - #if defined(OS_MACOSX) // Enables the Material Design download shelf on Mac. const base::Feature kMacMaterialDesignDownloadShelf{
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 404d4b03..d97e6114 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -193,8 +193,6 @@ extern const base::Feature kMacSystemShareMenu; #endif -extern const base::Feature kMaterialDesignBookmarks; - #if defined(OS_MACOSX) extern const base::Feature kMacMaterialDesignDownloadShelf; #endif
diff --git a/chrome/common/extensions/api/_manifest_features.json b/chrome/common/extensions/api/_manifest_features.json index a04c5bbd..785d379 100644 --- a/chrome/common/extensions/api/_manifest_features.json +++ b/chrome/common/extensions/api/_manifest_features.json
@@ -65,7 +65,6 @@ "channel": "stable", "extension_types": ["extension"], "whitelist": [ - "CB2E4E7174A398FCB3AFA6840500C2E1D22DA7B2", // Bookmark Manager "D5736E4B5CF695CB93A2FB57E4FDC6E5AFAB6FE2", // http://crbug.com/312900 "D57DE394F36DC1C3220E7604C575D29C51A6C495", // http://crbug.com/319444 "3F65507A3B39259B38C8173C6FFA3D12DF64CCE9" // http://crbug.com/371562
diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 1bcc9f9..88afe22 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json
@@ -70,7 +70,6 @@ "channel": "stable", "extension_types": ["extension", "legacy_packaged_app"], "whitelist": [ - "CB2E4E7174A398FCB3AFA6840500C2E1D22DA7B2", // Bookmark Manager "D5736E4B5CF695CB93A2FB57E4FDC6E5AFAB6FE2", // http://crbug.com/312900 "D57DE394F36DC1C3220E7604C575D29C51A6C495", // http://crbug.com/319444 "3F65507A3B39259B38C8173C6FFA3D12DF64CCE9" // http://crbug.com/371562
diff --git a/chrome/common/extensions/docs/templates/articles/options.html b/chrome/common/extensions/docs/templates/articles/options.html index 2f3a8f1..063c7b3 100644 --- a/chrome/common/extensions/docs/templates/articles/options.html +++ b/chrome/common/extensions/docs/templates/articles/options.html
@@ -86,7 +86,7 @@ <p> There are two available types of extension options pages, <a href="#full_page">full page</a> and - <a href="embedded_options">embedded</a>. + <a href="#embedded_options">embedded</a>. The type of options is determined by how it is declared in the manifest. </p>
diff --git a/chrome/common/extensions/extension_constants.cc b/chrome/common/extensions/extension_constants.cc index 77e2522..3ea1b95a 100644 --- a/chrome/common/extensions/extension_constants.cc +++ b/chrome/common/extensions/extension_constants.cc
@@ -18,7 +18,6 @@ namespace extension_misc { -const char kBookmarkManagerId[] = "eemcgdkfndhakfknompkggombfjjjeno"; const char kCameraAppId[] = "hfhhnacclhffhdffklopdkcgdhifgngh"; const char kCalculatorAppId[] = "joodangkbfjnajiiifokapkpmhfnpleo"; const char kCalendarAppId[] = "ejjicmeblgpmajnghnpcppodonldlgfn";
diff --git a/chrome/common/extensions/extension_constants.h b/chrome/common/extensions/extension_constants.h index af78b7a..983b42ba 100644 --- a/chrome/common/extensions/extension_constants.h +++ b/chrome/common/extensions/extension_constants.h
@@ -27,9 +27,6 @@ namespace extension_misc { -// The extension id of the bookmark manager. -extern const char kBookmarkManagerId[]; - // The extension id of the Camera application. extern const char kCameraAppId[];
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 61b7a07..3ade7b3 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -848,7 +848,6 @@ "../browser/ui/views/content_setting_bubble_contents_browsertest.cc", "../browser/ui/views/device_chooser_browsertest.cc", "../browser/ui/views/try_chrome_dialog_win/try_chrome_dialog_browsertest.cc", - "../browser/ui/webui/bookmarks_ui_browsertest.cc", "../browser/ui/webui/chrome_url_data_manager_browsertest.cc", "../browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h", "../browser/ui/webui/constrained_web_dialog_ui_browsertest.cc",
diff --git a/chrome/test/data/ads_observer/same_origin_ad.html b/chrome/test/data/ads_observer/same_origin_ad.html new file mode 100644 index 0000000..8015b46 --- /dev/null +++ b/chrome/test/data/ads_observer/same_origin_ad.html
@@ -0,0 +1,6 @@ +<html> +<!-- Should be counted as a normal same-origin ad iframe. --> +<iframe id="src_frame_same_origin" name="google_ads_iframe" + src="pixel.png"> +</iframe> +</html>
diff --git a/chrome/test/data/ads_observer/srcdoc_embedded_ad.html b/chrome/test/data/ads_observer/srcdoc_embedded_ad.html new file mode 100644 index 0000000..07af0d2 --- /dev/null +++ b/chrome/test/data/ads_observer/srcdoc_embedded_ad.html
@@ -0,0 +1,6 @@ +<html> +<!-- Should be counted as same-origin even though it's about:contents. --> +<iframe id="srcdoc_frame_content" name="google_ads_iframe" + srcdoc="<hmtl> <img src=pixel.png> </html>"> +</iframe> +</html>
diff --git a/chrome/test/data/ads_observer/srcdoc_embedded_ad_empty.html b/chrome/test/data/ads_observer/srcdoc_embedded_ad_empty.html new file mode 100644 index 0000000..a2af28d8 --- /dev/null +++ b/chrome/test/data/ads_observer/srcdoc_embedded_ad_empty.html
@@ -0,0 +1,6 @@ +<html> +<!-- Shouldn't be counted at all, page has no bytes. --> +<iframe id="srcdoc_frame_no_content" name="google_ads_iframe" + srcdoc="<hmtl></html>"> +</iframe> +</html>
diff --git a/chrome/test/data/extensions/api_test/bookmark_manager/standard/test.js b/chrome/test/data/extensions/api_test/bookmark_manager/standard/test.js index b8fd3bd..49f7bc89 100644 --- a/chrome/test/data/extensions/api_test/bookmark_manager/standard/test.js +++ b/chrome/test/data/extensions/api_test/bookmark_manager/standard/test.js
@@ -43,13 +43,6 @@ }); var tests = [ - function getStrings() { - bookmarkManager.getStrings(pass(function(strings) { - assertEq('string', typeof strings['title']); - assertEq('string', typeof strings['search_button']); - })); - }, - function sortChildren() { folder = { parentId: '1',
diff --git a/chrome/test/data/extensions/api_test/webrequest/ntp_request_interception/extension/background.js b/chrome/test/data/extensions/api_test/webrequest/ntp_request_interception/extension/background.js index 9a16ad96..e063c49d 100644 --- a/chrome/test/data/extensions/api_test/webrequest/ntp_request_interception/extension/background.js +++ b/chrome/test/data/extensions/api_test/webrequest/ntp_request_interception/extension/background.js
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +var urlToIntercept; var interceptedRequest = false; chrome.webRequest.onBeforeRequest.addListener(function(details) { - if (details.url.endsWith('fake_ntp_script.js')) + if (urlToIntercept && details.url === urlToIntercept) interceptedRequest = true; }, { urls: ['<all_urls>'], @@ -16,4 +17,6 @@ interceptedRequest = false; } -chrome.test.sendMessage('ready'); +chrome.test.sendMessage('ready', function(url) { + urlToIntercept = url; +});
diff --git a/chrome/test/data/webui/md_bookmarks/md_bookmarks_browsertest.js b/chrome/test/data/webui/md_bookmarks/md_bookmarks_browsertest.js index 533783e..304d0f0 100644 --- a/chrome/test/data/webui/md_bookmarks/md_bookmarks_browsertest.js +++ b/chrome/test/data/webui/md_bookmarks/md_bookmarks_browsertest.js
@@ -11,7 +11,6 @@ [ROOT_PATH + 'chrome/test/data/webui/polymer_browser_test_base.js']); GEN('#include "chrome/browser/prefs/incognito_mode_prefs.h"'); GEN('#include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_browsertest.h"'); -GEN('#include "chrome/common/chrome_features.h"'); function MaterialBookmarksBrowserTest() {} @@ -20,8 +19,6 @@ browsePreload: 'chrome://bookmarks', - featureList: ['features::kMaterialDesignBookmarks', ''], - typedefCppFixture: 'MdBookmarksBrowserTest', extraLibraries: PolymerTest.getLibraries(ROOT_PATH).concat([
diff --git a/chrome/test/data/webui/md_bookmarks/md_bookmarks_focus_test.js b/chrome/test/data/webui/md_bookmarks/md_bookmarks_focus_test.js index e9d6c11..10b0427 100644 --- a/chrome/test/data/webui/md_bookmarks/md_bookmarks_focus_test.js +++ b/chrome/test/data/webui/md_bookmarks/md_bookmarks_focus_test.js
@@ -11,7 +11,6 @@ GEN_INCLUDE( [ROOT_PATH + 'chrome/test/data/webui/polymer_interactive_ui_test.js']); -GEN('#include "chrome/common/chrome_features.h"'); function MaterialBookmarksFocusTest() {} @@ -20,8 +19,6 @@ browsePreload: 'chrome://bookmarks', - featureList: ['features::kMaterialDesignBookmarks', ''], - extraLibraries: PolymerTest.getLibraries(ROOT_PATH).concat([ 'test_command_manager.js', 'test_store.js',
diff --git a/chromecast/browser/cast_web_view_default.cc b/chromecast/browser/cast_web_view_default.cc index be80904..8a3f2a3 100644 --- a/chromecast/browser/cast_web_view_default.cc +++ b/chromecast/browser/cast_web_view_default.cc
@@ -52,10 +52,7 @@ create_params.routing_id = MSG_ROUTING_NONE; create_params.initial_size = display_size; create_params.site_instance = site_instance; - content::WebContents* web_contents = - content::WebContents::Create(create_params); - - return base::WrapUnique(web_contents); + return content::WebContents::Create(create_params); } } // namespace
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 262b349c..cf07d43 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -10614.0.0 \ No newline at end of file +10631.0.0 \ No newline at end of file
diff --git a/components/autofill/core/common/form_field_data.cc b/components/autofill/core/common/form_field_data.cc index f84e8ac..06b712e 100644 --- a/components/autofill/core/common/form_field_data.cc +++ b/components/autofill/core/common/form_field_data.cc
@@ -186,7 +186,7 @@ IsCheckable(check_status) == IsCheckable(field.check_status); } -bool FormFieldData::IsTextField() const { +bool FormFieldData::IsTextInputElement() const { return form_control_type == "text" || form_control_type == "password" || form_control_type == "search" || form_control_type == "tel" || form_control_type == "url" || form_control_type == "email";
diff --git a/components/autofill/core/common/form_field_data.h b/components/autofill/core/common/form_field_data.h index 5a1d15f..d548b94 100644 --- a/components/autofill/core/common/form_field_data.h +++ b/components/autofill/core/common/form_field_data.h
@@ -84,8 +84,9 @@ // Returns true for all of textfield-looking types such as text, password, // search, email, url, and number. It must work the same way as Blink function - // WebInputElement::IsTextField(). - bool IsTextField() const; + // WebInputElement::IsTextField(), and it returns false if |*this| represents + // a textarea. + bool IsTextInputElement() const; // Note: operator==() performs a full-field-comparison(byte by byte), this is // different from SameFieldAs(), which ignores comparison for those "values"
diff --git a/components/autofill/core/common/form_field_data_unittest.cc b/components/autofill/core/common/form_field_data_unittest.cc index 5aceedb..648cf67b5 100644 --- a/components/autofill/core/common/form_field_data_unittest.cc +++ b/components/autofill/core/common/form_field_data_unittest.cc
@@ -338,7 +338,7 @@ EXPECT_TRUE(actual.SameFieldAs(empty)); } -TEST(FormFieldDataTest, IsTextField) { +TEST(FormFieldDataTest, IsTextInputElement) { struct TestData { const char* form_control_type; bool expected; @@ -348,12 +348,13 @@ {"email", true}, {"password", true}, {"select", false}, {"", false}, {"checkbox", false}, {"random_string", false}, + {"textarea", false}, }; for (const auto& test_case : test_data) { FormFieldData data; data.form_control_type = test_case.form_control_type; - EXPECT_EQ(test_case.expected, data.IsTextField()); + EXPECT_EQ(test_case.expected, data.IsTextInputElement()); } }
diff --git a/components/cdm/common/widevine_drm_delegate_android.cc b/components/cdm/common/widevine_drm_delegate_android.cc index 7d5af43..3bb5469 100644 --- a/components/cdm/common/widevine_drm_delegate_android.cc +++ b/components/cdm/common/widevine_drm_delegate_android.cc
@@ -6,7 +6,6 @@ #include "base/macros.h" #include "media/cdm/cenc_utils.h" -#include "media/media_buildflags.h" namespace cdm { @@ -35,13 +34,9 @@ if (init_data_type != media::EmeInitDataType::CENC) return true; -#if BUILDFLAG(USE_PROPRIETARY_CODECS) // Widevine MediaDrm plugin only accepts the "data" part of the PSSH box as // the init data when using MP4 container. return media::GetPsshData(init_data, GetUUID(), init_data_out); -#else - return false; -#endif } } // namespace cdm
diff --git a/components/cdm/renderer/android_key_systems.cc b/components/cdm/renderer/android_key_systems.cc index ec177e9..183a3f5f 100644 --- a/components/cdm/renderer/android_key_systems.cc +++ b/components/cdm/renderer/android_key_systems.cc
@@ -48,11 +48,7 @@ case EmeInitDataType::WEBM: return (supported_codecs_ & media::EME_CODEC_WEBM_ALL) != 0; case EmeInitDataType::CENC: -#if BUILDFLAG(USE_PROPRIETARY_CODECS) return (supported_codecs_ & media::EME_CODEC_MP4_ALL) != 0; -#else - return false; -#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) case EmeInitDataType::KEYIDS: case EmeInitDataType::UNKNOWN: return false; @@ -112,8 +108,8 @@ void AddAndroidWidevine( std::vector<std::unique_ptr<KeySystemProperties>>* concrete_key_systems) { - SupportedKeySystemResponse response = QueryKeySystemSupport( - kWidevineKeySystem); + SupportedKeySystemResponse response = + QueryKeySystemSupport(kWidevineKeySystem); // Since we do not control the implementation of the MediaDrm API on Android, // we assume that it can and will make use of persistence no matter whether
diff --git a/components/cdm/renderer/external_clear_key_key_system_properties.cc b/components/cdm/renderer/external_clear_key_key_system_properties.cc index 9ff56dc6..726daa13 100644 --- a/components/cdm/renderer/external_clear_key_key_system_properties.cc +++ b/components/cdm/renderer/external_clear_key_key_system_properties.cc
@@ -6,7 +6,6 @@ #include "base/logging.h" #include "media/base/eme_constants.h" -#include "media/media_buildflags.h" namespace cdm { @@ -23,17 +22,11 @@ bool ExternalClearKeyProperties::IsSupportedInitDataType( media::EmeInitDataType init_data_type) const { switch (init_data_type) { + case media::EmeInitDataType::CENC: case media::EmeInitDataType::WEBM: case media::EmeInitDataType::KEYIDS: return true; - case media::EmeInitDataType::CENC: -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - return true; -#else - return false; -#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) - case media::EmeInitDataType::UNKNOWN: return false; } @@ -42,11 +35,7 @@ } media::SupportedCodecs ExternalClearKeyProperties::GetSupportedCodecs() const { -#if BUILDFLAG(USE_PROPRIETARY_CODECS) return media::EME_CODEC_MP4_ALL | media::EME_CODEC_WEBM_ALL; -#else - return media::EME_CODEC_WEBM_ALL; -#endif } media::EmeConfigRule ExternalClearKeyProperties::GetRobustnessConfigRule(
diff --git a/components/cdm/renderer/widevine_key_system_properties.cc b/components/cdm/renderer/widevine_key_system_properties.cc index 3683fb8b5..b47bfc7 100644 --- a/components/cdm/renderer/widevine_key_system_properties.cc +++ b/components/cdm/renderer/widevine_key_system_properties.cc
@@ -4,7 +4,6 @@ #include "components/cdm/renderer/widevine_key_system_properties.h" -#include "media/media_buildflags.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. #if defined(WIDEVINE_CDM_AVAILABLE) @@ -72,10 +71,8 @@ // |init_data_type| x |container| pairings. if (init_data_type == EmeInitDataType::WEBM) return (supported_codecs_ & media::EME_CODEC_WEBM_ALL) != 0; -#if BUILDFLAG(USE_PROPRIETARY_CODECS) if (init_data_type == EmeInitDataType::CENC) return (supported_codecs_ & media::EME_CODEC_MP4_ALL) != 0; -#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) return false; }
diff --git a/components/cdm/renderer/widevine_key_system_properties.h b/components/cdm/renderer/widevine_key_system_properties.h index c758b84c..3567cbd 100644 --- a/components/cdm/renderer/widevine_key_system_properties.h +++ b/components/cdm/renderer/widevine_key_system_properties.h
@@ -7,7 +7,6 @@ #include "build/build_config.h" #include "media/base/key_system_properties.h" -#include "media/media_buildflags.h" namespace cdm {
diff --git a/components/dom_distiller/content/browser/distiller_page_web_contents.cc b/components/dom_distiller/content/browser/distiller_page_web_contents.cc index 9c821be..9dd3a81 100644 --- a/components/dom_distiller/content/browser/distiller_page_web_contents.cc +++ b/components/dom_distiller/content/browser/distiller_page_web_contents.cc
@@ -121,19 +121,20 @@ // Create new WebContents to use for distilling the content. content::WebContents::CreateParams create_params(browser_context_); create_params.initially_hidden = true; - content::WebContents* web_contents = + std::unique_ptr<content::WebContents> web_contents = content::WebContents::Create(create_params); DCHECK(web_contents); web_contents->SetDelegate(this); // Start observing WebContents and load the requested URL. - content::WebContentsObserver::Observe(web_contents); + content::WebContentsObserver::Observe(web_contents.get()); content::NavigationController::LoadURLParams params(url); web_contents->GetController().LoadURLWithParams(params); + // SourcePageHandleWebContents takes ownership of |web_contents|. source_page_handle_.reset( - new SourcePageHandleWebContents(web_contents, true)); + new SourcePageHandleWebContents(web_contents.release(), true)); } gfx::Size DistillerPageWebContents::GetSizeForNewRenderView(
diff --git a/components/guest_view/browser/guest_view_manager.cc b/components/guest_view/browser/guest_view_manager.cc index 0738b69..bb9675d6 100644 --- a/components/guest_view/browser/guest_view_manager.cc +++ b/components/guest_view/browser/guest_view_manager.cc
@@ -192,9 +192,13 @@ return nullptr; content::WebContents::CreateParams guest_create_params(create_params); guest_create_params.guest_delegate = guest; - auto* guest_web_contents = WebContents::Create(guest_create_params); - guest->InitWithWebContents(base::DictionaryValue(), guest_web_contents); - return guest_web_contents; + + // TODO(erikchen): Fix ownership semantics for this class. + // https://crbug.com/832879. + std::unique_ptr<content::WebContents> guest_web_contents = + WebContents::Create(guest_create_params); + guest->InitWithWebContents(base::DictionaryValue(), guest_web_contents.get()); + return guest_web_contents.release(); } content::WebContents* GuestViewManager::GetGuestByInstanceID(
diff --git a/components/offline_pages/content/background_loader/background_loader_contents.cc b/components/offline_pages/content/background_loader/background_loader_contents.cc index 0e66117..d59cec9c 100644 --- a/components/offline_pages/content/background_loader/background_loader_contents.cc +++ b/components/offline_pages/content/background_loader/background_loader_contents.cc
@@ -11,8 +11,8 @@ BackgroundLoaderContents::BackgroundLoaderContents( content::BrowserContext* browser_context) : browser_context_(browser_context) { - web_contents_.reset(content::WebContents::Create( - content::WebContents::CreateParams(browser_context_))); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(browser_context_)); web_contents_->SetAudioMuted(true); web_contents_->SetDelegate(this); }
diff --git a/components/password_manager/core/browser/form_parsing/ios_form_parser.cc b/components/password_manager/core/browser/form_parsing/ios_form_parser.cc index 2daa93d3..501a3b1 100644 --- a/components/password_manager/core/browser/form_parsing/ios_form_parser.cc +++ b/components/password_manager/core/browser/form_parsing/ios_form_parser.cc
@@ -70,8 +70,9 @@ // Returns text fields from |fields|. FieldPointersVector GetTextFields(const std::vector<FormFieldData>& fields) { FieldPointersVector result; + result.reserve(fields.size()); for (const auto& field : fields) { - if (field.IsTextField()) + if (field.IsTextInputElement()) result.push_back(&field); } return result; @@ -80,6 +81,7 @@ // Returns fields that do not have credit card related autocomplete attributes. FieldPointersVector GetNonCreditCardFields(const FieldPointersVector& fields) { FieldPointersVector result; + result.reserve(fields.size()); for (const auto* field : fields) { if (!HasCreditCardAutocompleteAttributes(*field)) result.push_back(field);
diff --git a/components/policy/core/browser/url_blacklist_manager.cc b/components/policy/core/browser/url_blacklist_manager.cc index a892193..5ad4453 100644 --- a/components/policy/core/browser/url_blacklist_manager.cc +++ b/components/policy/core/browser/url_blacklist_manager.cc
@@ -5,14 +5,19 @@ #include "components/policy/core/browser/url_blacklist_manager.h" #include <stdint.h> + +#include <algorithm> #include <limits> +#include <set> #include <utility> +#include <vector> #include "base/bind.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" +#include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -64,13 +69,12 @@ // Maximum filters per policy. Filters over this index are ignored. const size_t kMaxFiltersPerPolicy = 1000; -// A task that builds the blacklist on a background thread. -std::unique_ptr<URLBlacklist> BuildBlacklist( - std::unique_ptr<base::ListValue> block, - std::unique_ptr<base::ListValue> allow) { - std::unique_ptr<URLBlacklist> blacklist(new URLBlacklist); - blacklist->Block(block.get()); - blacklist->Allow(allow.get()); +// Returns a blacklist based on the given |block| and |allow| pattern lists. +std::unique_ptr<URLBlacklist> BuildBlacklist(const base::ListValue* block, + const base::ListValue* allow) { + auto blacklist = std::make_unique<URLBlacklist>(); + blacklist->Block(block); + blacklist->Allow(allow); return blacklist; } @@ -135,7 +139,11 @@ struct URLBlacklist::FilterComponents { FilterComponents() : port(0), match_subdomains(true), allow(true) {} - ~FilterComponents() {} + ~FilterComponents() = default; + FilterComponents(const FilterComponents&) = delete; + FilterComponents(FilterComponents&&) = default; + FilterComponents& operator=(const FilterComponents&) = delete; + FilterComponents& operator=(FilterComponents&&) = default; // Returns true if |this| represents the "*" filter in the blacklist. bool IsBlacklistWildcard() const { @@ -158,12 +166,12 @@ URLBlacklist::~URLBlacklist() {} -void URLBlacklist::AddFilters(bool allow, - const base::ListValue* list) { +void URLBlacklist::AddFilters(bool allow, const base::ListValue* list) { URLMatcherConditionSet::Vector all_conditions; size_t size = std::min(kMaxFiltersPerPolicy, list->GetSize()); + std::string pattern; + scoped_refptr<URLMatcherConditionSet> condition_set; for (size_t i = 0; i < size; ++i) { - std::string pattern; bool success = list->GetString(i, &pattern); DCHECK(success); FilterComponents components; @@ -179,20 +187,14 @@ continue; } - scoped_refptr<URLMatcherConditionSet> condition_set = - CreateConditionSet(url_matcher_.get(), - ++id_, - components.scheme, - components.host, - components.match_subdomains, - components.port, - components.path, - components.query, - allow); + condition_set = CreateConditionSet( + url_matcher_.get(), ++id_, components.scheme, components.host, + components.match_subdomains, components.port, components.path, + components.query, allow); components.number_of_key_value_pairs = condition_set->query_conditions().size(); - all_conditions.push_back(condition_set); - filters_[id_] = components; + all_conditions.push_back(std::move(condition_set)); + filters_[id_] = std::move(components); } url_matcher_->AddConditionSets(all_conditions); } @@ -390,9 +392,9 @@ port_filter.reset(new URLMatcherPortFilter(ranges)); } - return new URLMatcherConditionSet(id, conditions, query_conditions, - std::move(scheme_filter), - std::move(port_filter)); + return base::MakeRefCounted<URLMatcherConditionSet>( + id, conditions, query_conditions, std::move(scheme_filter), + std::move(port_filter)); } // static @@ -437,7 +439,7 @@ // |pref_service_| lives on. ui_task_runner_ = base::SequencedTaskRunnerHandle::Get(); background_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BACKGROUND}); + {base::TaskPriority::BACKGROUND}); pref_change_registrar_.Init(pref_service_); base::Closure callback = base::Bind(&URLBlacklistManager::ScheduleUpdate, @@ -448,8 +450,12 @@ // Start enforcing the policies without a delay when they are present at // startup. if (pref_service_->HasPrefPath(policy_prefs::kUrlBlacklist) || - pref_service_->HasPrefPath(policy_prefs::kUrlWhitelist)) - Update(); + pref_service_->HasPrefPath(policy_prefs::kUrlWhitelist)) { + SCOPED_UMA_HISTOGRAM_TIMER("URLBlacklistManager.ConstructorBuildTime"); + SetBlacklist( + BuildBlacklist(pref_service_->GetList(policy_prefs::kUrlBlacklist), + pref_service_->GetList(policy_prefs::kUrlWhitelist))); + } } URLBlacklistManager::~URLBlacklistManager() { @@ -472,18 +478,16 @@ void URLBlacklistManager::Update() { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - // The preferences can only be read on the UI thread. - std::unique_ptr<base::ListValue> block( - pref_service_->GetList(policy_prefs::kUrlBlacklist)->DeepCopy()); - std::unique_ptr<base::ListValue> allow( - pref_service_->GetList(policy_prefs::kUrlWhitelist)->DeepCopy()); - - // The URLBlacklist is built on a background task. Once it's ready, it is - // passed to the URLBlacklistManager on the same thread as the - // background_task_runner_. + // The URLBlacklist is built in the background. Once it's ready, it is passed + // to the URLBlacklistManager back on ui_task_runner_. base::PostTaskAndReplyWithResult( background_task_runner_.get(), FROM_HERE, - base::BindOnce(&BuildBlacklist, std::move(block), std::move(allow)), + base::BindOnce( + &BuildBlacklist, + base::Owned( + pref_service_->GetList(policy_prefs::kUrlBlacklist)->DeepCopy()), + base::Owned( + pref_service_->GetList(policy_prefs::kUrlWhitelist)->DeepCopy())), base::BindOnce(&URLBlacklistManager::SetBlacklist, ui_weak_ptr_factory_.GetWeakPtr())); }
diff --git a/components/policy/core/common/cloud/component_cloud_policy_service_unittest.cc b/components/policy/core/common/cloud/component_cloud_policy_service_unittest.cc index 664d9e3a..d54c3a6 100644 --- a/components/policy/core/common/cloud/component_cloud_policy_service_unittest.cc +++ b/components/policy/core/common/cloud/component_cloud_policy_service_unittest.cc
@@ -150,9 +150,7 @@ RunUntilIdle(); } - void RunUntilIdle() { - base::RunLoop().RunUntilIdle(); - } + void RunUntilIdle() { base::RunLoop().RunUntilIdle(); } void Connect() { client_ = new MockCloudPolicyClient(); @@ -161,7 +159,7 @@ client_, std::move(owned_cache_), request_context_, loop_.task_runner(), loop_.task_runner())); - client_->SetDMToken(ComponentPolicyBuilder::kFakeToken); + client_->SetDMToken(ComponentCloudPolicyBuilder::kFakeToken); EXPECT_EQ(1u, client_->types_to_fetch_.size()); core_.Connect(std::unique_ptr<CloudPolicyClient>(client_)); EXPECT_EQ(2u, client_->types_to_fetch_.size()); @@ -177,10 +175,10 @@ void LoadStore() { em::PolicyData* data = new em::PolicyData(); - data->set_username(ComponentPolicyBuilder::kFakeUsername); - data->set_request_token(ComponentPolicyBuilder::kFakeToken); - data->set_device_id(ComponentPolicyBuilder::kFakeDeviceId); - data->set_public_key_version(ComponentPolicyBuilder::kFakePublicKeyVersion); + data->set_username(PolicyBuilder::kFakeUsername); + data->set_request_token(PolicyBuilder::kFakeToken); + data->set_device_id(PolicyBuilder::kFakeDeviceId); + data->set_public_key_version(PolicyBuilder::kFakePublicKeyVersion); store_.policy_.reset(data); store_.policy_signature_public_key_ = public_key_; store_.NotifyStoreLoaded(); @@ -196,14 +194,14 @@ } void PopulateCache() { - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension, CreateSerializedResponse())); + EXPECT_TRUE(cache_->Store("extension-policy", kTestExtension, + CreateSerializedResponse())); EXPECT_TRUE( cache_->Store("extension-policy-data", kTestExtension, kTestPolicy)); builder_.policy_data().set_settings_entity_id(kTestExtension2); - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension2, CreateSerializedResponse())); + EXPECT_TRUE(cache_->Store("extension-policy", kTestExtension2, + CreateSerializedResponse())); EXPECT_TRUE( cache_->Store("extension-policy-data", kTestExtension2, kTestPolicy)); builder_.policy_data().set_settings_entity_id(kTestExtension); @@ -245,7 +243,7 @@ CloudPolicyCore core_; SchemaRegistry registry_; std::unique_ptr<ComponentCloudPolicyService> service_; - ComponentPolicyBuilder builder_; + ComponentCloudPolicyBuilder builder_; PolicyMap expected_policy_; std::string public_key_; }; @@ -580,10 +578,10 @@ // loaded, the other should be filtered out by the schema. builder_.payload().set_secure_hash( crypto::SHA256HashString(kInvalidTestPolicy)); - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension, CreateSerializedResponse())); - EXPECT_TRUE(cache_->Store( - "extension-policy-data", kTestExtension, kInvalidTestPolicy)); + EXPECT_TRUE(cache_->Store("extension-policy", kTestExtension, + CreateSerializedResponse())); + EXPECT_TRUE(cache_->Store("extension-policy-data", kTestExtension, + kInvalidTestPolicy)); LoadStore(); InitializeRegistry(); @@ -661,10 +659,9 @@ EXPECT_TRUE(service_->is_initialized()); // Send back a fake policy fetch response with the new signing key. - const int kNewPublicKeyVersion = - ComponentPolicyBuilder::kFakePublicKeyVersion + 1; + const int kNewPublicKeyVersion = PolicyBuilder::kFakePublicKeyVersion + 1; std::unique_ptr<crypto::RSAPrivateKey> new_signing_key = - ComponentPolicyBuilder::CreateTestOtherSigningKey(); + PolicyBuilder::CreateTestOtherSigningKey(); builder_.SetSigningKey(*new_signing_key); builder_.policy_data().set_public_key_version(kNewPublicKeyVersion); client_->SetPolicy(dm_protocol::kChromeExtensionPolicyType, kTestExtension,
diff --git a/components/policy/core/common/cloud/component_cloud_policy_store_unittest.cc b/components/policy/core/common/cloud/component_cloud_policy_store_unittest.cc index 8392495..9e39d31 100644 --- a/components/policy/core/common/cloud/component_cloud_policy_store_unittest.cc +++ b/components/policy/core/common/cloud/component_cloud_policy_store_unittest.cc
@@ -101,10 +101,10 @@ new ResourceCache(temp_dir_.GetPath(), base::MakeRefCounted<base::TestSimpleTaskRunner>())); store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, - ComponentPolicyBuilder::kFakeDeviceId, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + store_->SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); } std::unique_ptr<em::PolicyFetchResponse> CreateResponse() { @@ -150,7 +150,7 @@ std::unique_ptr<ResourceCache> cache_; std::unique_ptr<ComponentCloudPolicyStore> store_; MockComponentCloudPolicyStoreDelegate store_delegate_; - ComponentPolicyBuilder builder_; + ComponentCloudPolicyBuilder builder_; PolicyBundle expected_bundle_; std::string public_key_; @@ -177,7 +177,7 @@ const int64_t kPastTimestamp = (base::Time() + base::TimeDelta::FromDays(1)).ToJavaTime(); - CHECK_GT(ComponentPolicyBuilder::kFakeTimestamp, kPastTimestamp); + CHECK_GT(PolicyBuilder::kFakeTimestamp, kPastTimestamp); builder_.policy_data().set_timestamp(kPastTimestamp); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, @@ -243,7 +243,7 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyWrongPublicKey) { // Test against a policy signed with a wrong key. - builder_.SetSigningKey(*ComponentPolicyBuilder::CreateTestOtherSigningKey()); + builder_.SetSigningKey(*PolicyBuilder::CreateTestOtherSigningKey()); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -252,7 +252,7 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyWrongPublicKeyVersion) { // Test against a policy containing wrong public key version. builder_.policy_data().set_public_key_version( - ComponentPolicyBuilder::kFakePublicKeyVersion + 1); + PolicyBuilder::kFakePublicKeyVersion + 1); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -261,9 +261,9 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyDifferentPublicKey) { // Test against a policy signed with a different key and containing a new // public key version. - builder_.SetSigningKey(*ComponentPolicyBuilder::CreateTestOtherSigningKey()); + builder_.SetSigningKey(*PolicyBuilder::CreateTestOtherSigningKey()); builder_.policy_data().set_public_key_version( - ComponentPolicyBuilder::kFakePublicKeyVersion + 1); + PolicyBuilder::kFakePublicKeyVersion + 1); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -302,9 +302,9 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateNoCredentialsUser) { store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(AccountId(), ComponentPolicyBuilder::kFakeToken, - ComponentPolicyBuilder::kFakeDeviceId, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + store_->SetCredentials(AccountId(), PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -312,10 +312,10 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateNoCredentialsDMToken) { store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::GetFakeAccountIdForTesting(), + store_->SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), std::string() /* dm_token */, - ComponentPolicyBuilder::kFakeDeviceId, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -323,10 +323,10 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateNoCredentialsDeviceId) { store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, + store_->SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, std::string() /* device_id */, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + PolicyBuilder::kFakePublicKeyVersion); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -334,11 +334,10 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateNoCredentialsPublicKey) { store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, - ComponentPolicyBuilder::kFakeDeviceId, - std::string() /* public_key */, - ComponentPolicyBuilder::kFakePublicKeyVersion); + store_->SetCredentials( + PolicyBuilder::GetFakeAccountIdForTesting(), PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, std::string() /* public_key */, + PolicyBuilder::kFakePublicKeyVersion); EXPECT_FALSE(store_->ValidatePolicy(kTestPolicyNS, CreateResponse(), nullptr /* policy_data */, nullptr /* payload */)); @@ -348,9 +347,8 @@ StoreTestPolicy(store_.get()); ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - public_key_, -1 /* public_key_version */); + PolicyBuilder::GetFakeAccountIdForTesting(), PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, -1 /* public_key_version */); another_store.Load(); EXPECT_TRUE(IsStoreEmpty(another_store)); EXPECT_TRUE(LoadCacheExtensionsSubkeys().empty()); @@ -359,10 +357,10 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateWrongCredentialsDMToken) { StoreTestPolicy(store_.get()); ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), "wrongtoken", - ComponentPolicyBuilder::kFakeDeviceId, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + "wrongtoken", PolicyBuilder::kFakeDeviceId, + public_key_, + PolicyBuilder::kFakePublicKeyVersion); another_store.Load(); EXPECT_TRUE(IsStoreEmpty(another_store)); EXPECT_TRUE(LoadCacheExtensionsSubkeys().empty()); @@ -372,9 +370,8 @@ StoreTestPolicy(store_.get()); ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, "wrongdeviceid", public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + PolicyBuilder::GetFakeAccountIdForTesting(), PolicyBuilder::kFakeToken, + "wrongdeviceid", public_key_, PolicyBuilder::kFakePublicKeyVersion); another_store.Load(); EXPECT_TRUE(IsStoreEmpty(another_store)); EXPECT_TRUE(LoadCacheExtensionsSubkeys().empty()); @@ -383,10 +380,10 @@ TEST_F(ComponentCloudPolicyStoreTest, ValidateWrongCredentialsPublicKey) { StoreTestPolicy(store_.get()); ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - "wrongkey", ComponentPolicyBuilder::kFakePublicKeyVersion); + another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, "wrongkey", + PolicyBuilder::kFakePublicKeyVersion); another_store.Load(); EXPECT_TRUE(IsStoreEmpty(another_store)); EXPECT_TRUE(LoadCacheExtensionsSubkeys().empty()); @@ -396,10 +393,10 @@ ValidateWrongCredentialsPublicKeyVersion) { StoreTestPolicy(store_.get()); ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - public_key_, ComponentPolicyBuilder::kFakePublicKeyVersion + 1); + another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion + 1); another_store.Load(); EXPECT_TRUE(IsStoreEmpty(another_store)); EXPECT_TRUE(LoadCacheExtensionsSubkeys().empty()); @@ -456,10 +453,10 @@ // Loading from the cache validates the policy data again. ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - public_key_, ComponentPolicyBuilder::kFakePublicKeyVersion); + another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); another_store.Load(); EXPECT_TRUE(another_store.policy().Equals(expected_bundle_)); EXPECT_EQ(TestPolicyHash(), another_store.GetCachedHash(kTestPolicyNS)); @@ -507,10 +504,10 @@ ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); const PolicyBundle empty_bundle; EXPECT_TRUE(another_store.policy().Equals(empty_bundle)); - another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - public_key_, ComponentPolicyBuilder::kFakePublicKeyVersion); + another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); another_store.Load(); EXPECT_TRUE(another_store.policy().Equals(expected_bundle_)); @@ -524,10 +521,10 @@ // And they aren't loaded anymore either. ComponentCloudPolicyStore yet_another_store(&store_delegate_, cache_.get()); - yet_another_store.SetCredentials( - ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, ComponentPolicyBuilder::kFakeDeviceId, - public_key_, ComponentPolicyBuilder::kFakePublicKeyVersion); + yet_another_store.SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); yet_another_store.Load(); EXPECT_TRUE(yet_another_store.policy().Equals(empty_bundle)); }
diff --git a/components/policy/core/common/cloud/component_cloud_policy_updater_unittest.cc b/components/policy/core/common/cloud/component_cloud_policy_updater_unittest.cc index 5bc9ac6..4cf052f 100644 --- a/components/policy/core/common/cloud/component_cloud_policy_updater_unittest.cc +++ b/components/policy/core/common/cloud/component_cloud_policy_updater_unittest.cc
@@ -85,7 +85,7 @@ MockComponentCloudPolicyStoreDelegate store_delegate_; net::TestURLFetcherFactory fetcher_factory_; std::unique_ptr<ComponentCloudPolicyUpdater> updater_; - ComponentPolicyBuilder builder_; + ComponentCloudPolicyBuilder builder_; PolicyBundle expected_bundle_; private: @@ -119,17 +119,15 @@ task_runner_ = new base::TestMockTimeTaskRunner(); cache_.reset(new ResourceCache(temp_dir_.GetPath(), task_runner_)); store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::GetFakeAccountIdForTesting(), - ComponentPolicyBuilder::kFakeToken, - ComponentPolicyBuilder::kFakeDeviceId, public_key_, - ComponentPolicyBuilder::kFakePublicKeyVersion); + store_->SetCredentials(PolicyBuilder::GetFakeAccountIdForTesting(), + PolicyBuilder::kFakeToken, + PolicyBuilder::kFakeDeviceId, public_key_, + PolicyBuilder::kFakePublicKeyVersion); fetcher_factory_.set_remove_fetcher_on_delete(true); fetcher_backend_.reset(new ExternalPolicyDataFetcherBackend( - task_runner_, - scoped_refptr<net::URLRequestContextGetter>())); + task_runner_, scoped_refptr<net::URLRequestContextGetter>())); updater_.reset(new ComponentCloudPolicyUpdater( - task_runner_, - fetcher_backend_->CreateFrontend(task_runner_), + task_runner_, fetcher_backend_->CreateFrontend(task_runner_), store_.get())); ASSERT_EQ(store_->policy().end(), store_->policy().begin()); } @@ -205,8 +203,8 @@ updater_->UpdateExternalPolicy(kTestPolicyNS, CreateResponse()); // Submit two valid policy fetch responses. - builder_.policy_data().set_username(ComponentPolicyBuilder::kFakeUsername); - builder_.policy_data().set_gaia_id(ComponentPolicyBuilder::kFakeGaiaId); + builder_.policy_data().set_username(PolicyBuilder::kFakeUsername); + builder_.policy_data().set_gaia_id(PolicyBuilder::kFakeGaiaId); builder_.policy_data().set_settings_entity_id(kTestExtension2); builder_.payload().set_download_url(kTestDownload2); updater_->UpdateExternalPolicy( @@ -255,7 +253,7 @@ TEST_F(ComponentCloudPolicyUpdaterTest, PolicyFetchResponseWrongPublicKey) { // Submit a policy fetch response signed with a wrong signing key. - builder_.SetSigningKey(*ComponentPolicyBuilder::CreateTestOtherSigningKey()); + builder_.SetSigningKey(*PolicyBuilder::CreateTestOtherSigningKey()); updater_->UpdateExternalPolicy(kTestPolicyNS, CreateResponse()); task_runner_->RunUntilIdle(); @@ -268,7 +266,7 @@ PolicyFetchResponseWrongPublicKeyVersion) { // Submit a policy fetch response containing different public key version. builder_.policy_data().set_public_key_version( - ComponentPolicyBuilder::kFakePublicKeyVersion + 1); + PolicyBuilder::kFakePublicKeyVersion + 1); updater_->UpdateExternalPolicy(kTestPolicyNS, CreateResponse()); task_runner_->RunUntilIdle(); @@ -280,9 +278,9 @@ TEST_F(ComponentCloudPolicyUpdaterTest, PolicyFetchResponseDifferentPublicKey) { // Submit a policy fetch response signed with a different key and containing a // new public key version. - builder_.SetSigningKey(*ComponentPolicyBuilder::CreateTestOtherSigningKey()); + builder_.SetSigningKey(*PolicyBuilder::CreateTestOtherSigningKey()); builder_.policy_data().set_public_key_version( - ComponentPolicyBuilder::kFakePublicKeyVersion + 1); + PolicyBuilder::kFakePublicKeyVersion + 1); updater_->UpdateExternalPolicy(kTestPolicyNS, CreateResponse()); task_runner_->RunUntilIdle();
diff --git a/components/policy/core/common/cloud/policy_builder.cc b/components/policy/core/common/cloud/policy_builder.cc index a903546..748aefb 100644 --- a/components/policy/core/common/cloud/policy_builder.cc +++ b/components/policy/core/common/cloud/policy_builder.cc
@@ -251,8 +251,7 @@ // The new public key must be signed by the old key. std::unique_ptr<crypto::RSAPrivateKey> old_signing_key = GetSigningKey(); if (old_signing_key) { - SignData(policy_.new_public_key(), - old_signing_key.get(), + SignData(policy_.new_public_key(), old_signing_key.get(), policy_.mutable_new_public_key_signature()); } } else { @@ -370,7 +369,7 @@ return AccountId::FromUserEmailGaiaId(kFakeUsername, kFakeGaiaId); } -template<> +template <> TypedPolicyBuilder<em::CloudPolicySettings>::TypedPolicyBuilder() : payload_(new em::CloudPolicySettings()) { policy_data().set_policy_type(dm_protocol::kChromeUserPolicyType); @@ -380,7 +379,7 @@ template class TypedPolicyBuilder<em::CloudPolicySettings>; #if !defined(OS_ANDROID) && !defined(OS_IOS) -template<> +template <> TypedPolicyBuilder<em::ExternalPolicyData>::TypedPolicyBuilder() { CreatePayload(); policy_data().set_policy_type(dm_protocol::kChromeExtensionPolicyType); @@ -389,4 +388,13 @@ template class TypedPolicyBuilder<em::ExternalPolicyData>; #endif +#if defined(OS_CHROMEOS) +StringPolicyBuilder::StringPolicyBuilder() = default; + +void StringPolicyBuilder::Build() { + policy_data().set_policy_value(payload_); + PolicyBuilder::Build(); +} +#endif + } // namespace policy
diff --git a/components/policy/core/common/cloud/policy_builder.h b/components/policy/core/common/cloud/policy_builder.h index 48fea33..e2229f2 100644 --- a/components/policy/core/common/cloud/policy_builder.h +++ b/components/policy/core/common/cloud/policy_builder.h
@@ -152,7 +152,7 @@ // Type-parameterized PolicyBuilder extension that allows for building policy // blobs carrying protobuf payloads. -template<typename PayloadProto> +template <typename PayloadProto> class TypedPolicyBuilder : public PolicyBuilder { public: TypedPolicyBuilder(); @@ -178,12 +178,34 @@ DISALLOW_COPY_AND_ASSIGN(TypedPolicyBuilder); }; +// PolicyBuilder extension that allows for building policy blobs carrying string +// payloads. +class StringPolicyBuilder : public PolicyBuilder { + public: + StringPolicyBuilder(); + void set_payload(std::string payload) { payload_ = std::move(payload); } + const std::string& payload() const { return payload_; } + void clear_payload() { payload_.clear(); } + + // PolicyBuilder: + void Build() override; + + private: + std::string payload_; + + DISALLOW_COPY_AND_ASSIGN(StringPolicyBuilder); +}; + typedef TypedPolicyBuilder<enterprise_management::CloudPolicySettings> UserPolicyBuilder; #if !defined(OS_ANDROID) && !defined(OS_IOS) -typedef TypedPolicyBuilder<enterprise_management::ExternalPolicyData> - ComponentPolicyBuilder; +using ComponentCloudPolicyBuilder = + TypedPolicyBuilder<enterprise_management::ExternalPolicyData>; +#endif + +#if defined(OS_CHROMEOS) +using ComponentActiveDirectoryPolicyBuilder = StringPolicyBuilder; #endif } // namespace policy
diff --git a/components/sync/engine_impl/model_type_worker.cc b/components/sync/engine_impl/model_type_worker.cc index c33d55a2..0e88984d 100644 --- a/components/sync/engine_impl/model_type_worker.cc +++ b/components/sync/engine_impl/model_type_worker.cc
@@ -166,6 +166,7 @@ data.is_folder = update_entity.folder(); data.parent_id = update_entity.parent_id_string(); data.unique_position = update_entity.unique_position(); + data.server_defined_unique_tag = update_entity.server_defined_unique_tag(); // Deleted entities must use the default instance of EntitySpecifics in // order for EntityData to correctly reflect that they are deleted.
diff --git a/components/sync/engine_impl/model_type_worker_unittest.cc b/components/sync/engine_impl/model_type_worker_unittest.cc index accf82a2..7a2ac8f 100644 --- a/components/sync/engine_impl/model_type_worker_unittest.cc +++ b/components/sync/engine_impl/model_type_worker_unittest.cc
@@ -320,9 +320,10 @@ void TriggerTypeRootUpdateFromServer() { SyncEntity entity = server()->TypeRootUpdate(); - worker()->ProcessGetUpdatesResponse( - server()->GetProgress(), server()->GetContext(), {&entity}, nullptr); - worker()->PassiveApplyUpdates(nullptr); + worker()->ProcessGetUpdatesResponse(server()->GetProgress(), + server()->GetContext(), {&entity}, + &status_controller_); + worker()->PassiveApplyUpdates(&status_controller_); } void TriggerPartialUpdateFromServer(int64_t version_offset, @@ -336,15 +337,16 @@ entity.mutable_specifics()); } - worker()->ProcessGetUpdatesResponse( - server()->GetProgress(), server()->GetContext(), {&entity}, nullptr); + worker()->ProcessGetUpdatesResponse(server()->GetProgress(), + server()->GetContext(), {&entity}, + &status_controller_); } void TriggerUpdateFromServer(int64_t version_offset, const std::string& tag, const std::string& value) { TriggerPartialUpdateFromServer(version_offset, tag, value); - worker()->ApplyUpdates(nullptr); + worker()->ApplyUpdates(&status_controller_); } void TriggerTombstoneFromServer(int64_t version_offset, @@ -357,14 +359,15 @@ entity.mutable_specifics()); } - worker()->ProcessGetUpdatesResponse( - server()->GetProgress(), server()->GetContext(), {&entity}, nullptr); - worker()->ApplyUpdates(nullptr); + worker()->ProcessGetUpdatesResponse(server()->GetProgress(), + server()->GetContext(), {&entity}, + &status_controller_); + worker()->ApplyUpdates(&status_controller_); } // Simulates the end of a GU sync cycle and tells the worker to flush changes // to the processor. - void ApplyUpdates() { worker()->ApplyUpdates(nullptr); } + void ApplyUpdates() { worker()->ApplyUpdates(&status_controller_); } // Delivers specified protos as updates. // @@ -373,8 +376,9 @@ // protocol. Try to use the other, higher level methods if possible. void DeliverRawUpdates(const SyncEntityList& list) { worker()->ProcessGetUpdatesResponse(server()->GetProgress(), - server()->GetContext(), list, nullptr); - worker()->ApplyUpdates(nullptr); + server()->GetContext(), list, + &status_controller_); + worker()->ApplyUpdates(&status_controller_); } // By default, this harness behaves as if all tasks posted to the model @@ -419,7 +423,7 @@ sync_pb::ClientToServerResponse response = server()->DoSuccessfulCommit(message); - contribution->ProcessCommitResponse(response, nullptr); + contribution->ProcessCommitResponse(response, &status_controller_); contribution->CleanUp(); } @@ -487,6 +491,8 @@ base::ObserverList<TypeDebugInfoObserver> type_observers_; std::unique_ptr<NonBlockingTypeDebugInfoEmitter> emitter_; + + StatusController status_controller_; }; // Requests a commit and verifies the messages sent to the client and server as @@ -1155,7 +1161,8 @@ entity.set_folder(false); entity.mutable_unique_position()->set_custom_compressed_v1("POSITION"); entity.set_version(1); - entity.set_client_defined_unique_tag("TAG"); + entity.set_client_defined_unique_tag("CLIENT_TAG"); + entity.set_server_defined_unique_tag("SERVER_TAG"); entity.set_deleted(false); entity.mutable_specifics()->CopyFrom(GenerateSpecifics(kTag1, kValue1)); UpdateResponseData response_data; @@ -1171,7 +1178,8 @@ EXPECT_FALSE(data.parent_id.empty()); EXPECT_FALSE(data.is_folder); EXPECT_TRUE(data.unique_position.has_custom_compressed_v1()); - EXPECT_EQ("TAG", data.client_tag_hash); + EXPECT_EQ("CLIENT_TAG", data.client_tag_hash); + EXPECT_EQ("SERVER_TAG", data.server_defined_unique_tag); EXPECT_FALSE(data.is_deleted()); EXPECT_EQ(kTag1, data.specifics.preference().name()); EXPECT_EQ(kValue1, data.specifics.preference().value());
diff --git a/components/sync/engine_impl/non_blocking_type_commit_contribution.cc b/components/sync/engine_impl/non_blocking_type_commit_contribution.cc index 7d0a3f1..081a863 100644 --- a/components/sync/engine_impl/non_blocking_type_commit_contribution.cc +++ b/components/sync/engine_impl/non_blocking_type_commit_contribution.cc
@@ -90,6 +90,7 @@ case sync_pb::CommitResponse::CONFLICT: DVLOG(1) << "Server reports conflict for commit message."; ++conflicting_commits; + status->increment_num_server_conflicts(); break; case sync_pb::CommitResponse::SUCCESS: { ++successes; @@ -101,6 +102,12 @@ response_data.sequence_number = commit_request.sequence_number; response_data.specifics_hash = commit_request.specifics_hash; response_list.push_back(response_data); + + status->increment_num_successful_commits(); + if (commit_request.entity->specifics.has_bookmark()) { + status->increment_num_successful_bookmark_commits(); + } + break; } case sync_pb::CommitResponse::OVER_QUOTA:
diff --git a/components/viz/test/test_layer_tree_frame_sink.cc b/components/viz/test/test_layer_tree_frame_sink.cc index 4040997..c73b615 100644 --- a/components/viz/test/test_layer_tree_frame_sink.cc +++ b/components/viz/test/test_layer_tree_frame_sink.cc
@@ -160,16 +160,19 @@ gfx::Size frame_size = frame.size_in_pixels(); float device_scale_factor = frame.device_scale_factor(); - if (!local_surface_id_.is_valid() || frame_size != display_size_ || + LocalSurfaceId local_surface_id = + parent_local_surface_id_allocator_->GetCurrentLocalSurfaceId(); + + if (!local_surface_id.is_valid() || frame_size != display_size_ || device_scale_factor != device_scale_factor_) { - local_surface_id_ = parent_local_surface_id_allocator_->GenerateId(); - display_->SetLocalSurfaceId(local_surface_id_, device_scale_factor); + local_surface_id = parent_local_surface_id_allocator_->GenerateId(); + display_->SetLocalSurfaceId(local_surface_id, device_scale_factor); display_->Resize(frame_size); display_size_ = frame_size; device_scale_factor_ = device_scale_factor; } - support_->SubmitCompositorFrame(local_surface_id_, std::move(frame)); + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); // TODO(vmpstr): In layout tests, we request this call. However, with site // isolation we don't get an activation yet. Previously the call to the @@ -183,7 +186,7 @@ // https://crbug.com/667551 tracks the progress of fixing this. if (support_->last_activated_surface_id().is_valid()) { for (auto& copy_request : copy_requests_) - support_->RequestCopyOfOutput(local_surface_id_, std::move(copy_request)); + support_->RequestCopyOfOutput(local_surface_id, std::move(copy_request)); } copy_requests_.clear();
diff --git a/components/viz/test/test_layer_tree_frame_sink.h b/components/viz/test/test_layer_tree_frame_sink.h index b838d44..87586496 100644 --- a/components/viz/test/test_layer_tree_frame_sink.h +++ b/components/viz/test/test_layer_tree_frame_sink.h
@@ -140,7 +140,6 @@ std::unique_ptr<FrameSinkManagerImpl> frame_sink_manager_; std::unique_ptr<ParentLocalSurfaceIdAllocator> parent_local_surface_id_allocator_; - LocalSurfaceId local_surface_id_; gfx::Size display_size_; float device_scale_factor_ = 0; gfx::ColorSpace blending_color_space_ = gfx::ColorSpace::CreateSRGB();
diff --git a/components/zucchini/patch_reader.cc b/components/zucchini/patch_reader.cc index 90f35f4..7e0b815 100644 --- a/components/zucchini/patch_reader.cc +++ b/components/zucchini/patch_reader.cc
@@ -9,23 +9,11 @@ #include <utility> #include "base/numerics/safe_conversions.h" +#include "components/zucchini/algorithm.h" #include "components/zucchini/crc32.h" namespace zucchini { -namespace { - -bool RangeIsInRegion(offset_t begin, uint32_t size, BufferRegion region) { - // Return false if |begin + size > kOffsetBound|, without overflowing. - if (begin >= kOffsetBound || kOffsetBound - begin < size) - return false; - offset_t end = begin + size; - // Return false if |[begin, end]| leaks outside |region|. - return begin >= region.lo() && end <= region.hi(); -} - -} // namespace - namespace patch { bool ParseElementMatch(BufferSource* source, ElementMatch* element_match) { @@ -265,18 +253,18 @@ bool PatchElementReader::ValidateEquivalences() { EquivalenceSource equivalences_copy = equivalences_; - BufferRegion old_region = element_match_.old_element.region(); - BufferRegion new_region = element_match_.new_element.region(); + const size_t old_region_size = element_match_.old_element.size; + const size_t new_region_size = element_match_.new_element.size; // Validate that each |equivalence| falls within the bounds of the // |element_match_| and are in order. offset_t prev_dst_end = 0; for (auto equivalence = equivalences_copy.GetNext(); equivalence.has_value(); equivalence = equivalences_copy.GetNext()) { - if (!RangeIsInRegion(equivalence->src_offset, equivalence->length, - old_region) || - !RangeIsInRegion(equivalence->dst_offset, equivalence->length, - new_region)) { + if (!RangeIsBounded(equivalence->src_offset, equivalence->length, + old_region_size) || + !RangeIsBounded(equivalence->dst_offset, equivalence->length, + new_region_size)) { LOG(ERROR) << "Out of bounds equivalence detected."; return false; }
diff --git a/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc b/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc index bd37230..8fba2e4 100644 --- a/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc +++ b/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc
@@ -666,7 +666,7 @@ std::string credentials; bool should_run; } kTestCases[] = { - {true, "", false}, + {true, "", true}, {true, "omit", false}, {true, "same-origin", true}, {true, "include", true},
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index cfe018f6..e8f695a 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -2929,9 +2929,11 @@ const base::Time timestamp = base::Time::Now(); entry->SetTimestamp(timestamp); entries.push_back(std::move(entry)); - std::unique_ptr<WebContentsImpl> our_contents(static_cast<WebContentsImpl*>( - WebContents::Create(WebContents::CreateParams(browser_context())))); - NavigationControllerImpl& our_controller = our_contents->GetController(); + std::unique_ptr<WebContents> our_contents = + WebContents::Create(WebContents::CreateParams(browser_context())); + WebContentsImpl* raw_our_contents = + static_cast<WebContentsImpl*>(our_contents.get()); + NavigationControllerImpl& our_controller = raw_our_contents->GetController(); our_controller.Restore(0, RestoreType::LAST_SESSION_EXITED_CLEANLY, &entries); ASSERT_EQ(0u, entries.size()); @@ -2963,7 +2965,7 @@ params.method = "GET"; params.page_state = PageState::CreateFromURL(url); TestRenderFrameHost* main_rfh = - static_cast<TestRenderFrameHost*>(our_contents->GetMainFrame()); + static_cast<TestRenderFrameHost*>(raw_our_contents->GetMainFrame()); main_rfh->PrepareForCommit(); main_rfh->SendNavigateWithParams(¶ms, false); @@ -2996,9 +2998,11 @@ new_entry->SetTitle(base::ASCIIToUTF16("Title")); new_entry->SetPageState(PageState::CreateFromEncodedData("state")); entries.push_back(std::move(new_entry)); - std::unique_ptr<WebContentsImpl> our_contents(static_cast<WebContentsImpl*>( - WebContents::Create(WebContents::CreateParams(browser_context())))); - NavigationControllerImpl& our_controller = our_contents->GetController(); + std::unique_ptr<WebContents> our_contents = + WebContents::Create(WebContents::CreateParams(browser_context())); + WebContentsImpl* raw_our_contents = + static_cast<WebContentsImpl*>(our_contents.get()); + NavigationControllerImpl& our_controller = raw_our_contents->GetController(); our_controller.Restore(0, RestoreType::LAST_SESSION_EXITED_CLEANLY, &entries); ASSERT_EQ(0u, entries.size()); @@ -3043,7 +3047,7 @@ params.method = "GET"; params.page_state = PageState::CreateFromURL(url); TestRenderFrameHost* main_rfh = - static_cast<TestRenderFrameHost*>(our_contents->GetMainFrame()); + static_cast<TestRenderFrameHost*>(raw_our_contents->GetMainFrame()); main_rfh->PrepareForCommit(); main_rfh->SendNavigateWithParams(¶ms, false);
diff --git a/content/browser/loader/resource_dispatcher_host_unittest.cc b/content/browser/loader/resource_dispatcher_host_unittest.cc index 7e099c63..658ad0c 100644 --- a/content/browser/loader/resource_dispatcher_host_unittest.cc +++ b/content/browser/loader/resource_dispatcher_host_unittest.cc
@@ -671,8 +671,8 @@ HandleScheme("test"); scoped_refptr<SiteInstance> site_instance = SiteInstance::Create(browser_context_.get()); - web_contents_.reset( - WebContents::Create(WebContents::CreateParams(browser_context_.get()))); + web_contents_ = + WebContents::Create(WebContents::CreateParams(browser_context_.get())); web_contents_filter_ = new TestFilterSpecifyingChild( browser_context_->GetResourceContext(), web_contents_->GetMainFrame()->GetProcess()->GetID());
diff --git a/content/browser/media/encrypted_media_browsertest.cc b/content/browser/media/encrypted_media_browsertest.cc index 03ba85a..190ec7a7 100644 --- a/content/browser/media/encrypted_media_browsertest.cc +++ b/content/browser/media/encrypted_media_browsertest.cc
@@ -51,6 +51,8 @@ const char kWebMVp9VideoOnly[] = "video/webm; codecs=\"vp9\""; const char kWebMOpusAudioVp9Video[] = "video/webm; codecs=\"opus, vp9\""; const char kWebMVorbisAudioVp8Video[] = "video/webm; codecs=\"vorbis, vp8\""; +const char kMp4Vp9VideoOnly[] = + "video/mp4; codecs=\"vp09.00.10.08.01.02.02.02.00\""; #if BUILDFLAG(USE_PROPRIETARY_CODECS) const char kMp4Avc1VideoOnly[] = "video/mp4; codecs=\"avc1.64001E\""; #endif // BUILDFLAG(USE_PROPRIETARY_CODECS) @@ -256,6 +258,15 @@ TestSimplePlayback("bear-320x240-opus-av_enc-v.webm", kWebMOpusAudioVp9Video); } +IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_VideoOnly_MP4_VP9) { + // MP4 without MSE is not support yet, http://crbug.com/170793. + if (CurrentSourceType() != SrcType::MSE) { + DVLOG(0) << "Skipping test; Can only play MP4 encrypted streams by MSE."; + return; + } + TestSimplePlayback("bear-320x240-v_frag-vp9-cenc.mp4", kMp4Vp9VideoOnly); +} + // Strictly speaking this is not an "encrypted" media test. Keep it here for // completeness. IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, ConfigChangeVideo_ClearToClear) {
diff --git a/content/browser/renderer_host/input/input_router_config_helper.cc b/content/browser/renderer_host/input/input_router_config_helper.cc index 46fd57cf..f76d4df 100644 --- a/content/browser/renderer_host/input/input_router_config_helper.cc +++ b/content/browser/renderer_host/input/input_router_config_helper.cc
@@ -5,9 +5,7 @@ #include "content/browser/renderer_host/input/input_router_config_helper.h" #include "base/command_line.h" -#include "base/feature_list.h" #include "build/build_config.h" -#include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "ui/events/gesture_detection/gesture_configuration.h" #include "ui/events/gesture_detection/gesture_detector.h" @@ -30,12 +28,8 @@ base::TimeDelta::FromMilliseconds(kMobileTouchAckTimeoutDelayMs); #if defined(OS_ANDROID) - // For historical reasons only Android enables the touch ack timeout. The - // touch ack timeout will be replaced by an intervention which forces events - // to be non-blocking if the main thread is busy. This is currently behind a - // flag. - config.touch_ack_timeout_supported = !base::FeatureList::IsEnabled( - features::kMainThreadBusyScrollIntervention); + // For historical reasons only Android enables the touch ack timeout. + config.touch_ack_timeout_supported = true; #else config.touch_ack_timeout_supported = false; #endif
diff --git a/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc b/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc index f90fd14..afa16e9 100644 --- a/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc +++ b/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc
@@ -33,67 +33,6 @@ return ukm_recorder ? ukm_recorder->GetNewSourceID() : ukm::kInvalidSourceId; } -void RecordEQTAccuracy(base::TimeDelta queueing_time, - base::TimeDelta expected_queueing_time) { - float queueing_time_ms = queueing_time.InMillisecondsF(); - - if (queueing_time_ms < 10) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.10ms", - expected_queueing_time); - } - - if (queueing_time_ms < 150) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.150ms", - expected_queueing_time); - } - - if (queueing_time_ms < 300) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.300ms", - expected_queueing_time); - } - - if (queueing_time_ms < 450) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.450ms", - expected_queueing_time); - } - - if (queueing_time_ms > 10) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.10ms", - expected_queueing_time); - } - - if (queueing_time_ms > 150) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.150ms", - expected_queueing_time); - } - - if (queueing_time_ms > 300) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.300ms", - expected_queueing_time); - } - - if (queueing_time_ms > 450) { - UMA_HISTOGRAM_TIMES( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.450ms", - expected_queueing_time); - } -} - } // namespace RenderWidgetHostLatencyTracker::RenderWidgetHostLatencyTracker( @@ -167,10 +106,6 @@ UMA_HISTOGRAM_INPUT_LATENCY_MILLISECONDS( "Event.Latency.QueueingTime." + event_name + default_action_status, rwh_component, main_component); - - RecordEQTAccuracy( - main_component.last_event_time - rwh_component.first_event_time, - latency.expected_queueing_time_on_dispatch()); } }
diff --git a/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc b/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc index ab3b091..e307684 100644 --- a/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc +++ b/content/browser/renderer_host/input/render_widget_host_latency_tracker_unittest.cc
@@ -1174,90 +1174,4 @@ ElementsAre(Bucket(14, 1))); } -TEST_F(RenderWidgetHostLatencyTrackerTest, ExpectedQueueingTimeAccuracy) { - // These numbers are sensitive to where the histogram buckets are. - base::TimeTicks event_timestamp = - base::TimeTicks() + base::TimeDelta::FromMilliseconds(11); - int expected_queueing_time_ms = 1; - base::TimeDelta expected_queueing_time = - base::TimeDelta::FromMilliseconds(expected_queueing_time_ms); - - for (float queueing_time_ms : {2, 15, 200, 400}) { - base::TimeDelta queueing_time = - base::TimeDelta::FromMilliseconds(queueing_time_ms); - SyntheticWebTouchEvent event; - // Touch start. - event.PressPoint(1, 1); - - ui::LatencyInfo latency; - latency.set_source_event_type(ui::SourceEventType::TOUCH); - tracker()->OnInputEvent(event, &latency); - - ui::LatencyInfo fake_latency; - fake_latency.set_trace_id(kTraceEventId); - fake_latency.set_expected_queueing_time_on_dispatch(expected_queueing_time); - fake_latency.set_source_event_type(ui::SourceEventType::TOUCH); - fake_latency.AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, - tracker()->latency_component_id(), 0, event_timestamp, 1); - - fake_latency.AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT, 0, 0, - event_timestamp + queueing_time, 1); - - fake_latency.AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_ACK_RWH_COMPONENT, 0, 0, - event_timestamp + queueing_time, 1); - - // Call ComputeInputLatencyHistograms directly to avoid OnInputEventAck - // overwriting components. - tracker()->ComputeInputLatencyHistograms( - event.GetType(), tracker()->latency_component_id(), fake_latency, - INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - - tracker()->OnInputEventAck(event, &latency, - INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - } - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.10ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 1))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.150ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 2))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.300ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 3))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_LessThan.450ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 4))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.10ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 3))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.150ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 2))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.300ms"), - ElementsAre(Bucket(expected_queueing_time_ms, 1))); - - EXPECT_THAT(histogram_tester().GetAllSamples( - "RendererScheduler." - "ExpectedQueueingTimeWhenQueueingTime_GreaterThan.450ms"), - ElementsAre()); -} - } // namespace content
diff --git a/content/browser/site_instance_impl_unittest.cc b/content/browser/site_instance_impl_unittest.cc index dc9e5d9..7bcdf3b1 100644 --- a/content/browser/site_instance_impl_unittest.cc +++ b/content/browser/site_instance_impl_unittest.cc
@@ -195,10 +195,10 @@ // Ensure that instances are deleted when their RenderViewHosts are gone. std::unique_ptr<TestBrowserContext> browser_context(new TestBrowserContext()); { - std::unique_ptr<WebContentsImpl> web_contents(static_cast<WebContentsImpl*>( + std::unique_ptr<WebContents> web_contents( WebContents::Create(WebContents::CreateParams( browser_context.get(), - SiteInstance::Create(browser_context.get()))))); + SiteInstance::Create(browser_context.get())))); EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount()); EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount()); }
diff --git a/content/browser/web_contents/web_contents_delegate_unittest.cc b/content/browser/web_contents/web_contents_delegate_unittest.cc index 1845a66..3e2d270 100644 --- a/content/browser/web_contents/web_contents_delegate_unittest.cc +++ b/content/browser/web_contents/web_contents_delegate_unittest.cc
@@ -22,44 +22,48 @@ }; TEST_F(WebContentsDelegateTest, UnregisterInDestructor) { - std::unique_ptr<WebContentsImpl> contents_a(static_cast<WebContentsImpl*>( - WebContents::Create(WebContents::CreateParams(browser_context())))); - std::unique_ptr<WebContentsImpl> contents_b(static_cast<WebContentsImpl*>( - WebContents::Create(WebContents::CreateParams(browser_context())))); - EXPECT_EQ(nullptr, contents_a->GetDelegate()); - EXPECT_EQ(nullptr, contents_b->GetDelegate()); + std::unique_ptr<WebContents> contents_a( + WebContents::Create(WebContents::CreateParams(browser_context()))); + WebContentsImpl* raw_contents_a = + static_cast<WebContentsImpl*>(contents_a.get()); + std::unique_ptr<WebContents> contents_b( + WebContents::Create(WebContents::CreateParams(browser_context()))); + WebContentsImpl* raw_contents_b = + static_cast<WebContentsImpl*>(contents_b.get()); + EXPECT_EQ(nullptr, raw_contents_a->GetDelegate()); + EXPECT_EQ(nullptr, raw_contents_b->GetDelegate()); std::unique_ptr<MockWebContentsDelegate> delegate( new MockWebContentsDelegate()); // Setting a delegate should work correctly. - contents_a->SetDelegate(delegate.get()); - EXPECT_EQ(delegate.get(), contents_a->GetDelegate()); - EXPECT_TRUE(contents_b->GetDelegate() == nullptr); + raw_contents_a->SetDelegate(delegate.get()); + EXPECT_EQ(delegate.get(), raw_contents_a->GetDelegate()); + EXPECT_TRUE(raw_contents_b->GetDelegate() == nullptr); // A delegate can be a delegate to multiple WebContentsImpl. - contents_b->SetDelegate(delegate.get()); - EXPECT_EQ(delegate.get(), contents_a->GetDelegate()); - EXPECT_EQ(delegate.get(), contents_b->GetDelegate()); + raw_contents_b->SetDelegate(delegate.get()); + EXPECT_EQ(delegate.get(), raw_contents_a->GetDelegate()); + EXPECT_EQ(delegate.get(), raw_contents_b->GetDelegate()); // Setting the same delegate multiple times should work correctly. - contents_b->SetDelegate(delegate.get()); - EXPECT_EQ(delegate.get(), contents_a->GetDelegate()); - EXPECT_EQ(delegate.get(), contents_b->GetDelegate()); + raw_contents_b->SetDelegate(delegate.get()); + EXPECT_EQ(delegate.get(), raw_contents_a->GetDelegate()); + EXPECT_EQ(delegate.get(), raw_contents_b->GetDelegate()); // Setting delegate to NULL should work correctly. - contents_b->SetDelegate(nullptr); - EXPECT_EQ(delegate.get(), contents_a->GetDelegate()); - EXPECT_TRUE(contents_b->GetDelegate() == nullptr); + raw_contents_b->SetDelegate(nullptr); + EXPECT_EQ(delegate.get(), raw_contents_a->GetDelegate()); + EXPECT_TRUE(raw_contents_b->GetDelegate() == nullptr); // Destroying the delegate while it is still the delegate for a // WebContentsImpl should unregister it. - contents_b->SetDelegate(delegate.get()); - EXPECT_EQ(delegate.get(), contents_a->GetDelegate()); - EXPECT_EQ(delegate.get(), contents_b->GetDelegate()); + raw_contents_b->SetDelegate(delegate.get()); + EXPECT_EQ(delegate.get(), raw_contents_a->GetDelegate()); + EXPECT_EQ(delegate.get(), raw_contents_b->GetDelegate()); delegate.reset(nullptr); - EXPECT_TRUE(contents_a->GetDelegate() == nullptr); - EXPECT_TRUE(contents_b->GetDelegate() == nullptr); + EXPECT_TRUE(raw_contents_a->GetDelegate() == nullptr); + EXPECT_TRUE(raw_contents_b->GetDelegate() == nullptr); // Destroy the WebContentses and run the message loop to prevent leaks. contents_a.reset();
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 271a81a..a6e1cbe 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -264,8 +264,10 @@ } // namespace -WebContents* WebContents::Create(const WebContents::CreateParams& params) { - return WebContentsImpl::CreateWithOpener(params, FindOpenerRFH(params)); +std::unique_ptr<WebContents> WebContents::Create( + const WebContents::CreateParams& params) { + return base::WrapUnique( + WebContentsImpl::CreateWithOpener(params, FindOpenerRFH(params))); } WebContents* WebContents::CreateWithSessionStorage( @@ -1679,15 +1681,10 @@ void WebContentsImpl::NotifyPreferencesChanged() { std::set<RenderViewHost*> render_view_host_set; for (FrameTreeNode* node : frame_tree_.Nodes()) { - RenderWidgetHost* render_widget_host = - node->current_frame_host()->GetRenderWidgetHost(); - if (!render_widget_host) - continue; - RenderViewHost* render_view_host = RenderViewHost::From(render_widget_host); - if (!render_view_host) - continue; - render_view_host_set.insert(render_view_host); + render_view_host_set.insert( + node->current_frame_host()->GetRenderViewHost()); } + for (RenderViewHost* render_view_host : render_view_host_set) render_view_host->OnWebkitPreferencesChanged(); } @@ -2417,8 +2414,7 @@ if (!is_guest) { create_params.context = view_->GetNativeView(); create_params.initial_size = GetContainerBounds().size(); - new_contents.reset( - static_cast<WebContentsImpl*>(WebContents::Create(create_params))); + new_contents = WebContents::Create(create_params); } else { new_contents = base::WrapUnique( GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)); @@ -4133,7 +4129,7 @@ // Create a new WebContents, which is used to display the source code. std::unique_ptr<WebContents> view_source_contents = - base::WrapUnique(Create(CreateParams(GetBrowserContext()))); + Create(CreateParams(GetBrowserContext())); // Restore the previously created NavigationEntry. std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index 619bbf9..04f21bdd 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -37,6 +37,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" +#include "content/public/common/content_client.h" #include "content/public/common/content_paths.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" @@ -47,6 +48,7 @@ #include "content/public/test/url_loader_interceptor.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" +#include "content/test/test_content_browser_client.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -80,6 +82,28 @@ #endif // defined(OS_MACOSX) } +// Class to test that OverrideWebkitPrefs has been called for all relevant +// RenderViewHosts. +class NotifyPreferencesChangedTestContentBrowserClient + : public TestContentBrowserClient { + public: + NotifyPreferencesChangedTestContentBrowserClient() = default; + + void OverrideWebkitPrefs(RenderViewHost* render_view_host, + WebPreferences* prefs) override { + override_webkit_prefs_rvh_set_.insert(render_view_host); + } + + const std::unordered_set<RenderViewHost*>& override_webkit_prefs_rvh_set() { + return override_webkit_prefs_rvh_set_; + } + + private: + std::unordered_set<RenderViewHost*> override_webkit_prefs_rvh_set_; + + DISALLOW_COPY_AND_ASSIGN(NotifyPreferencesChangedTestContentBrowserClient); +}; + class WebContentsImplBrowserTest : public ContentBrowserTest { public: WebContentsImplBrowserTest() {} @@ -2240,6 +2264,34 @@ waiter.Wait(net::LOAD_STATE_IDLE, base::string16()); } +IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, NotifyPreferencesChanged) { + ASSERT_TRUE(embedded_test_server()->Start()); + WebContentsImpl* web_contents = + static_cast<WebContentsImpl*>(shell()->web_contents()); + RenderFrameHost* main_frame = web_contents->GetMainFrame(); + + // Navigate to a site with two iframes in different origins. + GURL url = embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b,c)"); + EXPECT_TRUE(NavigateToURL(shell(), url)); + + auto* main_frame_rvh = main_frame->GetRenderViewHost(); + auto* b_subframe_rvh = ChildFrameAt(main_frame, 0)->GetRenderViewHost(); + auto* c_subframe_rvh = ChildFrameAt(main_frame, 1)->GetRenderViewHost(); + + NotifyPreferencesChangedTestContentBrowserClient new_client; + ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client); + + web_contents->NotifyPreferencesChanged(); + + // We should have updated the preferences for all three RenderViewHosts. + EXPECT_EQ(std::unordered_set<RenderViewHost*>( + {main_frame_rvh, b_subframe_rvh, c_subframe_rvh}), + new_client.override_webkit_prefs_rvh_set()); + + SetBrowserClientForTesting(old_client); +} + IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, PausePageScheduledTasks) { EXPECT_TRUE(embedded_test_server()->Start());
diff --git a/content/common/sandbox_policy_fuchsia.cc b/content/common/sandbox_policy_fuchsia.cc index 08bd454..e4053c6 100644 --- a/content/common/sandbox_policy_fuchsia.cc +++ b/content/common/sandbox_policy_fuchsia.cc
@@ -25,31 +25,20 @@ } if (type != service_manager::SANDBOX_TYPE_NO_SANDBOX) { - auto package_root = base::GetPackageRoot(); - if (!package_root.empty()) { - // TODO(kmarshall): Build path mappings for each sandbox type. + // Map /pkg (read-only files deployed from the package) and /tmp into the + // child's namespace. + options->paths_to_map.push_back(base::GetPackageRoot().AsUTF8Unsafe()); + base::FilePath temp_dir; + base::GetTempDir(&temp_dir); + options->paths_to_map.push_back(temp_dir.AsUTF8Unsafe()); - // Map /pkg (read-only files deployed from the package) and /tmp into the - // child's namespace. - options->paths_to_map.push_back(package_root.AsUTF8Unsafe()); - base::FilePath temp_dir; - base::GetTempDir(&temp_dir); - options->paths_to_map.push_back(temp_dir.AsUTF8Unsafe()); + // Clear environmental variables to better isolate the child from + // this process. + options->clear_environ = true; - // Clear environmental variables to better isolate the child from - // this process. - options->clear_environ = true; - - // Propagate stdout/stderr/stdin to the child. - options->clone_flags = LP_CLONE_FDIO_STDIO; - return; - } - - // TODO(crbug.com/750938): Remove this once package deployments become - // mandatory. - LOG(ERROR) << "Sandboxing was requested but is not available because" - << "the parent process is not hosted within a package."; - type = service_manager::SANDBOX_TYPE_NO_SANDBOX; + // Propagate stdout/stderr/stdin to the child. + options->clone_flags = LP_CLONE_FDIO_STDIO; + return; } DCHECK_EQ(type, service_manager::SANDBOX_TYPE_NO_SANDBOX);
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/MessagePort.java b/content/public/android/java/src/org/chromium/content_public/browser/MessagePort.java index d78628afb..e962a65 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/MessagePort.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/MessagePort.java
@@ -7,6 +7,7 @@ import android.os.Handler; import org.chromium.base.annotations.UsedByReflection; +import org.chromium.content.browser.AppWebMessagePort; /** * Interface for message ports that handle postMessage requests. @@ -26,6 +27,14 @@ } /** + * Called to create an entangled pair of ports. + * @return An array of a pair of{@link MessagePort} instances. + */ + public static MessagePort[] createPair() { + return AppWebMessagePort.createPair(); + } + + /** * Close the port for use. */ void close();
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index 423362c..8d98ef0 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -178,7 +178,8 @@ }; // Creates a new WebContents. - CONTENT_EXPORT static WebContents* Create(const CreateParams& params); + CONTENT_EXPORT static std::unique_ptr<WebContents> Create( + const CreateParams& params); // Similar to Create() above but should be used when you need to prepopulate // the SessionStorageNamespaceMap of the WebContents. This can happen if
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index d4c0d80..ee512a36 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -180,11 +180,6 @@ const base::Feature kLowPriorityIframes{"LowPriorityIframes", base::FEATURE_DISABLED_BY_DEFAULT}; -// An experiment forcing events to be non-blocking when the main thread is -// deemed unresponsive. See https://crbug.com/599609. -const base::Feature kMainThreadBusyScrollIntervention{ - "MainThreadBusyScrollIntervention", base::FEATURE_DISABLED_BY_DEFAULT}; - // If this feature is enabled, media-device enumerations use a cache that is // invalidated upon notifications sent by base::SystemMonitor. If disabled, the // cache is considered invalid on every enumeration request.
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 8add9c1..b0ead2b 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -50,7 +50,6 @@ CONTENT_EXPORT extern const base::Feature kLazyInitializeMediaControls; CONTENT_EXPORT extern const base::Feature kLazyParseCSS; CONTENT_EXPORT extern const base::Feature kLowPriorityIframes; -CONTENT_EXPORT extern const base::Feature kMainThreadBusyScrollIntervention; CONTENT_EXPORT extern const base::Feature kMediaDevicesSystemMonitorCache; CONTENT_EXPORT extern const base::Feature kMemoryCoordinator; CONTENT_EXPORT extern const base::Feature kModuleScriptsDynamicImport;
diff --git a/content/public/test/test_utils.cc b/content/public/test/test_utils.cc index 8e79e3d..58b982d1 100644 --- a/content/public/test/test_utils.cc +++ b/content/public/test/test_utils.cc
@@ -268,7 +268,10 @@ WebContents::CreateParams inner_params(outer_contents->GetBrowserContext()); inner_params.guest_delegate = guest_delegate.get(); - WebContents* inner_contents = WebContents::Create(inner_params); + + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + WebContents* inner_contents = WebContents::Create(inner_params).release(); // Attach. |inner_contents| becomes owned by |outer_contents|. inner_contents->AttachToOuterWebContentsFrame(outer_contents, rfh);
diff --git a/content/renderer/input/main_thread_event_queue.cc b/content/renderer/input/main_thread_event_queue.cc index 08cf4fc9..60b53a5 100644 --- a/content/renderer/input/main_thread_event_queue.cc +++ b/content/renderer/input/main_thread_event_queue.cc
@@ -5,9 +5,7 @@ #include "content/renderer/input/main_thread_event_queue.h" #include "base/containers/circular_deque.h" -#include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" -#include "base/strings/string_number_conversions.h" #include "content/common/input/event_with_latency_info.h" #include "content/common/input_messages.h" #include "content/renderer/render_widget.h" @@ -213,32 +211,11 @@ last_touch_start_forced_nonblocking_due_to_fling_(false), enable_fling_passive_listener_flag_(base::FeatureList::IsEnabled( features::kPassiveEventListenersDueToFling)), - enable_non_blocking_due_to_main_thread_responsiveness_flag_( - base::FeatureList::IsEnabled( - features::kMainThreadBusyScrollIntervention)), needs_low_latency_(false), allow_raf_aligned_input_(allow_raf_aligned_input), main_task_runner_(main_task_runner), main_thread_scheduler_(main_thread_scheduler), use_raf_fallback_timer_(true) { - if (enable_non_blocking_due_to_main_thread_responsiveness_flag_) { - std::string group = base::FieldTrialList::FindFullName( - "MainThreadResponsivenessScrollIntervention"); - - // The group name will be of the form Enabled$THRESHOLD_MS. Trim the prefix - // "Enabled", and parse the threshold. - int threshold_ms = 0; - std::string prefix = "Enabled"; - group.erase(0, prefix.length()); - base::StringToInt(group, &threshold_ms); - - if (threshold_ms <= 0) { - enable_non_blocking_due_to_main_thread_responsiveness_flag_ = false; - } else { - main_thread_responsiveness_threshold_ = - base::TimeDelta::FromMilliseconds(threshold_ms); - } - } raf_fallback_timer_.SetTaskRunner(main_task_runner); event_predictor_ = @@ -297,17 +274,6 @@ } } - if (enable_non_blocking_due_to_main_thread_responsiveness_flag_ && - touch_event->dispatch_type == blink::WebInputEvent::kBlocking) { - bool passive_due_to_unresponsive_main = - main_thread_scheduler_->MainThreadSeemsUnresponsive( - main_thread_responsiveness_threshold_); - if (passive_due_to_unresponsive_main) { - touch_event->dispatch_type = blink::WebInputEvent:: - kListenersForcedNonBlockingDueToMainThreadResponsiveness; - non_blocking = true; - } - } // If the event is non-cancelable ACK it right away. if (!non_blocking && touch_event->dispatch_type != blink::WebInputEvent::kBlocking)
diff --git a/content/renderer/input/main_thread_event_queue.h b/content/renderer/input/main_thread_event_queue.h index 57ff9858..c9c25b7a 100644 --- a/content/renderer/input/main_thread_event_queue.h +++ b/content/renderer/input/main_thread_event_queue.h
@@ -135,8 +135,6 @@ MainThreadEventQueueClient* client_; bool last_touch_start_forced_nonblocking_due_to_fling_; bool enable_fling_passive_listener_flag_; - bool enable_non_blocking_due_to_main_thread_responsiveness_flag_; - base::TimeDelta main_thread_responsiveness_threshold_; bool needs_low_latency_; bool allow_raf_aligned_input_; bool needs_low_latency_until_pointer_up_ = false;
diff --git a/content/renderer/input/main_thread_event_queue_unittest.cc b/content/renderer/input/main_thread_event_queue_unittest.cc index d20c99e..dc259c9 100644 --- a/content/renderer/input/main_thread_event_queue_unittest.cc +++ b/content/renderer/input/main_thread_event_queue_unittest.cc
@@ -10,7 +10,6 @@ #include "base/auto_reset.h" #include "base/macros.h" -#include "base/metrics/field_trial.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/test/scoped_feature_list.h" @@ -233,7 +232,6 @@ } protected: - base::test::ScopedFeatureList feature_list_; scoped_refptr<base::TestSimpleTaskRunner> main_task_runner_; blink::scheduler::MockRendererScheduler renderer_scheduler_; scoped_refptr<MainThreadEventQueue> queue_; @@ -1077,16 +1075,7 @@ : public testing::Test, public MainThreadEventQueueClient { public: - MainThreadEventQueueInitializationTest() - : field_trial_list_(new base::FieldTrialList(nullptr)) {} - - base::TimeDelta main_thread_responsiveness_threshold() { - return queue_->main_thread_responsiveness_threshold_; - } - - bool enable_non_blocking_due_to_main_thread_responsiveness_flag() { - return queue_->enable_non_blocking_due_to_main_thread_responsiveness_flag_; - } + MainThreadEventQueueInitializationTest() {} void HandleInputEvent(const blink::WebCoalescedInputEvent& event, const ui::LatencyInfo& latency, @@ -1099,37 +1088,10 @@ protected: scoped_refptr<MainThreadEventQueue> queue_; - base::test::ScopedFeatureList feature_list_; blink::scheduler::MockRendererScheduler renderer_scheduler_; scoped_refptr<base::TestSimpleTaskRunner> main_task_runner_; - std::unique_ptr<base::FieldTrialList> field_trial_list_; }; -TEST_F(MainThreadEventQueueInitializationTest, - MainThreadResponsivenessThresholdEnabled) { - feature_list_.InitFromCommandLine( - features::kMainThreadBusyScrollIntervention.name, ""); - - base::FieldTrialList::CreateFieldTrial( - "MainThreadResponsivenessScrollIntervention", "Enabled123"); - queue_ = new MainThreadEventQueue(this, main_task_runner_, - &renderer_scheduler_, true); - EXPECT_TRUE(enable_non_blocking_due_to_main_thread_responsiveness_flag()); - EXPECT_EQ(base::TimeDelta::FromMilliseconds(123), - main_thread_responsiveness_threshold()); -} - -TEST_F(MainThreadEventQueueInitializationTest, - MainThreadResponsivenessThresholdDisabled) { - base::FieldTrialList::CreateFieldTrial( - "MainThreadResponsivenessScrollIntervention", "Control"); - queue_ = new MainThreadEventQueue(this, main_task_runner_, - &renderer_scheduler_, true); - EXPECT_FALSE(enable_non_blocking_due_to_main_thread_responsiveness_flag()); - EXPECT_EQ(base::TimeDelta::FromMilliseconds(0), - main_thread_responsiveness_threshold()); -} - TEST_F(MainThreadEventQueueTest, QueuingTwoClosures) { EXPECT_FALSE(main_task_runner_->HasPendingTask()); EXPECT_EQ(0u, event_queue().size());
diff --git a/content/renderer/input/render_widget_input_handler.cc b/content/renderer/input/render_widget_input_handler.cc index c9dbe0c..afefacc4 100644 --- a/content/renderer/input/render_widget_input_handler.cc +++ b/content/renderer/input/render_widget_input_handler.cc
@@ -79,6 +79,7 @@ WebInputEvent::DispatchType dispatch_type, base::TimeTicks event_timestamp, const ui::LatencyInfo& latency_info) { + // This enum is backing a histogram. Do not remove or reorder members. enum ListenerEnum { PASSIVE_LISTENER_UMA_ENUM_PASSIVE, PASSIVE_LISTENER_UMA_ENUM_UNCANCELABLE, @@ -86,7 +87,7 @@ PASSIVE_LISTENER_UMA_ENUM_CANCELABLE, PASSIVE_LISTENER_UMA_ENUM_CANCELABLE_AND_CANCELED, PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_FLING, - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS, + PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS_DEPRECATED, PASSIVE_LISTENER_UMA_ENUM_COUNT }; @@ -95,11 +96,6 @@ case WebInputEvent::kListenersForcedNonBlockingDueToFling: enum_value = PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_FLING; break; - case WebInputEvent:: - kListenersForcedNonBlockingDueToMainThreadResponsiveness: - enum_value = - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS; - break; case WebInputEvent::kListenersNonBlockingPassive: enum_value = PASSIVE_LISTENER_UMA_ENUM_PASSIVE; break; @@ -134,14 +130,6 @@ UMA_HISTOGRAM_CUSTOM_COUNTS( "Event.PassiveListeners.ForcedNonBlockingLatencyDueToFling", GetEventLatencyMicros(event_timestamp, now), 1, 10000000, 100); - } else if ( - enum_value == - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS) { - base::TimeTicks now = base::TimeTicks::Now(); - UMA_HISTOGRAM_CUSTOM_COUNTS( - "Event.PassiveListeners." - "ForcedNonBlockingLatencyDueToUnresponsiveMainThread", - GetEventLatencyMicros(event_timestamp, now), 1, 10000000, 50); } } } @@ -317,13 +305,6 @@ std::unique_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor; ui::LatencyInfo swap_latency_info(latency_info); - if (RenderThreadImpl::current()) { - swap_latency_info.set_expected_queueing_time_on_dispatch( - RenderThreadImpl::current() - ->GetWebMainThreadScheduler() - ->MostRecentExpectedQueueingTime()); - } - swap_latency_info.AddLatencyNumber( ui::LatencyComponentType::INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT, 0, 0);
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index c4c6a193..2ec4191 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -65,7 +65,7 @@ PASSIVE_LISTENER_UMA_ENUM_CANCELABLE, PASSIVE_LISTENER_UMA_ENUM_CANCELABLE_AND_CANCELED, PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_FLING, - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS, + PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS_DEPRECATED, PASSIVE_LISTENER_UMA_ENUM_COUNT }; @@ -311,12 +311,12 @@ touch.touch_start_or_first_touch_move = true; EXPECT_CALL(*widget()->mock_webwidget(), HandleInputEvent(_)) - .Times(7) + .Times(5) .WillRepeatedly( ::testing::Return(blink::WebInputEventResult::kNotHandled)); EXPECT_CALL(*widget()->mock_webwidget(), DispatchBufferedTouchEvents()) - .Times(7) + .Times(5) .WillRepeatedly( ::testing::Return(blink::WebInputEventResult::kNotHandled)); @@ -352,24 +352,6 @@ EVENT_LISTENER_RESULT_HISTOGRAM, PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_FLING, 2); - touch.dispatch_type = blink::WebInputEvent::DispatchType:: - kListenersForcedNonBlockingDueToMainThreadResponsiveness; - widget()->SendInputEvent(touch, HandledEventCallback()); - histogram_tester().ExpectBucketCount( - EVENT_LISTENER_RESULT_HISTOGRAM, - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS, - 1); - - touch.MovePoint(0, 10, 10); - touch.touch_start_or_first_touch_move = true; - touch.dispatch_type = blink::WebInputEvent::DispatchType:: - kListenersForcedNonBlockingDueToMainThreadResponsiveness; - widget()->SendInputEvent(touch, HandledEventCallback()); - histogram_tester().ExpectBucketCount( - EVENT_LISTENER_RESULT_HISTOGRAM, - PASSIVE_LISTENER_UMA_ENUM_FORCED_NON_BLOCKING_DUE_TO_MAIN_THREAD_RESPONSIVENESS, - 2); - EXPECT_CALL(*widget()->mock_webwidget(), HandleInputEvent(_)) .WillOnce(::testing::Return(blink::WebInputEventResult::kNotHandled)); EXPECT_CALL(*widget()->mock_webwidget(), DispatchBufferedTouchEvents())
diff --git a/content/shell/browser/shell.cc b/content/shell/browser/shell.cc index f963e02b..f452a79 100644 --- a/content/shell/browser/shell.cc +++ b/content/shell/browser/shell.cc
@@ -210,7 +210,7 @@ } create_params.initial_size = AdjustWindowSize(initial_size); std::unique_ptr<WebContents> web_contents = - base::WrapUnique(WebContents::Create(create_params)); + WebContents::Create(create_params); Shell* shell = CreateShell(std::move(web_contents), create_params.initial_size); if (!url.is_empty())
diff --git a/content/test/gpu/generate_buildbot_json.py b/content/test/gpu/generate_buildbot_json.py index 6b5e2b5e..5d1f6069 100755 --- a/content/test/gpu/generate_buildbot_json.py +++ b/content/test/gpu/generate_buildbot_json.py
@@ -2384,30 +2384,6 @@ 'shards': 20, }, }, - 'viz_screenshot_sync': { - 'target_name': 'screenshot_sync', - 'args': [ - '--dont-restore-color-profile-after-test', - ], - 'extra_browser_args': [ - # This test confirms that GPU compositing is working with OOP-D. - '--enable-features=VizDisplayCompositor', - ], - 'tester_configs': [ - { - 'predicate': Predicates.DEFAULT, - 'disabled_instrumentation_types': ['tsan'], - 'os_types': ['win', 'linux'], - }, - ], - 'disabled_tester_configs': [ - { - 'names': [ - 'Linux FYI Ozone (Intel)', - ], - }, - ], - }, } # These isolated tests don't use telemetry. They need to be placed in the
diff --git a/device/base/synchronization/one_writer_seqlock.cc b/device/base/synchronization/one_writer_seqlock.cc index b0eb381..7b855cf 100644 --- a/device/base/synchronization/one_writer_seqlock.cc +++ b/device/base/synchronization/one_writer_seqlock.cc
@@ -24,17 +24,6 @@ return version; } -void OneWriterSeqLock::TryRead(bool* can_read, - base::subtle::Atomic32* version) const { - DCHECK(can_read); - DCHECK(version); - - *version = base::subtle::NoBarrier_Load(&sequence_); - // If the counter is even, then the associated data might be in a - // consistent state, so we can try to read. - *can_read = (*version & 1) == 0; -} - bool OneWriterSeqLock::ReadRetry(base::subtle::Atomic32 version) const { // If the sequence number was updated then a read should be re-attempted. // -- Load fence, read membarrier
diff --git a/device/base/synchronization/one_writer_seqlock.h b/device/base/synchronization/one_writer_seqlock.h index 7be8405..867fb82b 100644 --- a/device/base/synchronization/one_writer_seqlock.h +++ b/device/base/synchronization/one_writer_seqlock.h
@@ -32,7 +32,6 @@ public: OneWriterSeqLock(); base::subtle::Atomic32 ReadBegin() const; - void TryRead(bool* can_read, base::subtle::Atomic32* version) const; bool ReadRetry(base::subtle::Atomic32 version) const; void WriteBegin(); void WriteEnd();
diff --git a/device/base/synchronization/shared_memory_seqlock_buffer.h b/device/base/synchronization/shared_memory_seqlock_buffer.h index 1ad5a8a..4835b09 100644 --- a/device/base/synchronization/shared_memory_seqlock_buffer.h +++ b/device/base/synchronization/shared_memory_seqlock_buffer.h
@@ -21,8 +21,6 @@ template <class Data> class SharedMemorySeqLockBuffer { public: - SharedMemorySeqLockBuffer() {} - explicit SharedMemorySeqLockBuffer(const Data& data) : data(data) {} OneWriterSeqLock seqlock; Data data; };
diff --git a/docs/README.md b/docs/README.md index 3997dff0..9a6ef6f6 100644 --- a/docs/README.md +++ b/docs/README.md
@@ -50,10 +50,9 @@ Cast for Android (on a Linux host) * [iOS Build Instructions](ios/build_instructions.md) - iOS target (on a MacOS host) +* [Chrome OS Build Instructions](chromeos_build_instructions.md) - Chrome OS * [Linux Chromium ARM Recipes](linux_chromium_arm.md) - Recipes for building Chromium for ARM on Linux. -* [Common Build Tasks](common_build_tasks.md) - Recipes for slightly more - advanced build tasks * [Chrome Component Build](component_build.md) - Faster builds using more libraries * [Using the BuildRunner](using_build_runner.md) - Scripts that extract build @@ -110,8 +109,6 @@ compiler * [Threading and Tasks in Chrome](threading_and_tasks.md) - How to run tasks and handle thread safety in Chrome. -* [Subtle Threading Bugs and Patterns to Avoid Them](subtle_threading_bugs.md) - - Threading pitfalls to avoid. * [Callback<> and Bind()](callback.md) - All about Callbacks, Closures, and Bind(). * [Views Platform Styling](ui/views/platform_style.md) - How views are styled @@ -158,7 +155,6 @@ Diagnosing and fixing layout test flakiness due to ordering dependencies. * [Running Layout Tests using `content_shell`](testing/layout_tests_in_content_shell.md) - Running layout tests by hand. -* [Testing Browser UI](testing/test_browser_ui.md) - Using TestBrowserUi * [Web Platform Tests](testing/web_platform_tests.md) - Shared tests across browser vendors * [Using Breakpad with `content_shell`](testing/using_breakpad_with_content_shell.md) - @@ -312,9 +308,6 @@ Chromium/IRC/Google * [Documentation Best Practices](documentation_best_practices.md) * [Documentation Guidelines](documentation_guidelines.md) -* [Shift-Based Development](shift_based_development.md) - An experiment in - handing off development of coordinated work between developers in different - time zones. * [Chromium Browser vs Google Chrome](chromium_browser_vs_google_chrome.md) - What's the difference between _Chromium Browser_ and _Google Chrome_? * [Proxy Auto Config using WPAD](proxy_auto_config.md) - How WPAD servers are @@ -325,7 +318,6 @@ directories are determined on all platforms. ### Probably Obsolete -* [Old Chrome OS build instructions](old_chromeos_build_instructions.md) * [TPM Quick Reference](tpm_quick_ref.md) - Trusted Platform Module notes. * [System Hardening Features](system_hardening_features.md) - A list of current and planned Chrome OS security features.
diff --git a/docs/get_the_code.md b/docs/get_the_code.md index 0d637d4..e4bb6e35 100644 --- a/docs/get_the_code.md +++ b/docs/get_the_code.md
@@ -10,9 +10,10 @@ you might want to build: * [Android](android_build_instructions.md) -* [Cast](old_cast_build_instructions.md) -* [Chrome OS](old_chromeos_build_instructions.md) +* [Android Cast](android_cast_build_instructions.md) +* [Chrome OS](chromeos_build_instructions.md) * [iOS](ios/build_instructions.md) * [Linux](linux_build_instructions.md) +* [Linux Cast](linux_cast_build_instructions.md) * [Mac](mac_build_instructions.md) * [Windows](windows_build_instructions.md)
diff --git a/extensions/browser/api_unittest.cc b/extensions/browser/api_unittest.cc index c442c39..186b6d3d 100644 --- a/extensions/browser/api_unittest.cc +++ b/extensions/browser/api_unittest.cc
@@ -51,10 +51,9 @@ GURL url = BackgroundInfo::GetBackgroundURL(extension()); if (url.is_empty()) url = GURL(url::kAboutBlankURL); - contents_.reset( - content::WebContents::Create(content::WebContents::CreateParams( - browser_context(), - content::SiteInstance::CreateForURL(browser_context(), url)))); + contents_ = content::WebContents::Create(content::WebContents::CreateParams( + browser_context(), + content::SiteInstance::CreateForURL(browser_context(), url))); } }
diff --git a/extensions/browser/app_window/app_window_contents.cc b/extensions/browser/app_window/app_window_contents.cc index 2c4759a..9285be93 100644 --- a/extensions/browser/app_window/app_window_contents.cc +++ b/extensions/browser/app_window/app_window_contents.cc
@@ -34,7 +34,7 @@ context, creator_frame->GetSiteInstance()); create_params.opener_render_process_id = creator_frame->GetProcess()->GetID(); create_params.opener_render_frame_id = creator_frame->GetRoutingID(); - web_contents_.reset(content::WebContents::Create(create_params)); + web_contents_ = content::WebContents::Create(create_params); Observe(web_contents_.get()); web_contents_->GetMutableRendererPrefs()->
diff --git a/extensions/browser/extension_host.cc b/extensions/browser/extension_host.cc index 0a8a8f1..294243d 100644 --- a/extensions/browser/extension_host.cc +++ b/extensions/browser/extension_host.cc
@@ -68,8 +68,8 @@ DCHECK(host_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE || host_type == VIEW_TYPE_EXTENSION_DIALOG || host_type == VIEW_TYPE_EXTENSION_POPUP); - host_contents_.reset(WebContents::Create( - WebContents::CreateParams(browser_context_, site_instance))), + host_contents_ = WebContents::Create( + WebContents::CreateParams(browser_context_, site_instance)), content::WebContentsObserver::Observe(host_contents_.get()); host_contents_->SetDelegate(this); SetViewType(host_contents_.get(), host_type);
diff --git a/extensions/browser/guest_view/app_view/app_view_guest.cc b/extensions/browser/guest_view/app_view/app_view_guest.cc index 6ca37ed2..af1c95c 100644 --- a/extensions/browser/guest_view/app_view/app_view_guest.cc +++ b/extensions/browser/guest_view/app_view/app_view_guest.cc
@@ -247,7 +247,9 @@ content::SiteInstance::CreateForURL(browser_context(), guest_extension->url())); params.guest_delegate = this; - callback.Run(WebContents::Create(params)); + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + callback.Run(WebContents::Create(params).release()); } void AppViewGuest::LaunchAppAndFireEvent(
diff --git a/extensions/browser/guest_view/extension_options/extension_options_guest.cc b/extensions/browser/guest_view/extension_options/extension_options_guest.cc index 8ad547f..943e225 100644 --- a/extensions/browser/guest_view/extension_options/extension_options_guest.cc +++ b/extensions/browser/guest_view/extension_options/extension_options_guest.cc
@@ -110,7 +110,9 @@ browser_context(), content::SiteInstance::CreateForURL(browser_context(), extension_url)); params.guest_delegate = this; - WebContents* wc = WebContents::Create(params); + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + WebContents* wc = WebContents::Create(params).release(); SetViewType(wc, VIEW_TYPE_EXTENSION_GUEST); callback.Run(wc); }
diff --git a/extensions/browser/guest_view/extension_view/extension_view_guest.cc b/extensions/browser/guest_view/extension_view/extension_view_guest.cc index 34a16b9..2d4dd61 100644 --- a/extensions/browser/guest_view/extension_view/extension_view_guest.cc +++ b/extensions/browser/guest_view/extension_view/extension_view_guest.cc
@@ -93,7 +93,9 @@ browser_context(), content::SiteInstance::CreateForURL(browser_context(), extension_url_)); params.guest_delegate = this; - callback.Run(WebContents::Create(params)); + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + callback.Run(WebContents::Create(params).release()); } void ExtensionViewGuest::DidInitialize(
diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc index 57e98ae..54c9b632 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc
@@ -193,7 +193,9 @@ WebContents::CreateParams params(browser_context(), guest_site_instance.get()); params.guest_delegate = this; - auto* web_contents = WebContents::Create(params); + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + auto* web_contents = WebContents::Create(params).release(); SetViewType(web_contents, VIEW_TYPE_EXTENSION_GUEST); callback.Run(web_contents);
diff --git a/extensions/browser/guest_view/web_view/web_view_guest.cc b/extensions/browser/guest_view/web_view/web_view_guest.cc index d9880065..077e4c0 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.cc +++ b/extensions/browser/guest_view/web_view/web_view_guest.cc
@@ -371,7 +371,9 @@ owner_render_process_host->GetBrowserContext(), std::move(guest_site_instance)); params.guest_delegate = this; - WebContents* new_contents = WebContents::Create(params); + // TODO(erikchen): Fix ownership semantics for guest views. + // https://crbug.com/832879. + WebContents* new_contents = WebContents::Create(params).release(); // Grant access to the origin of the embedder to the guest process. This // allows blob:/filesystem: URLs with the embedder origin to be created
diff --git a/google_apis/gaia/gaia_auth_consumer.h b/google_apis/gaia/gaia_auth_consumer.h index 542c145..1ec5bde 100644 --- a/google_apis/gaia/gaia_auth_consumer.h +++ b/google_apis/gaia/gaia_auth_consumer.h
@@ -65,6 +65,29 @@ bool is_child_account; }; + // Possible server responses to a token revocation request. + // Used in UMA, do not delete or reorder values. + enum class TokenRevocationStatus { + // Token revocation succeeded. + kSuccess = 0, + // Network connection was canceled, no response was received. + kConnectionCanceled = 1, + // Network connection failed, no response was received. + kConnectionFailed = 2, + // Network connection timed out, no response was received. + kConnectionTimeout = 3, + // The token is unknown or invalid. + kInvalidToken = 4, + // The request was malformed. + kInvalidRequest = 5, + // Internal server error. + kServerError = 6, + // Other error. + kUnknownError = 7, + + kMaxValue = kUnknownError + }; + virtual ~GaiaAuthConsumer() {} virtual void OnClientLoginSuccess(const ClientLoginResult& result) {} @@ -79,7 +102,7 @@ virtual void OnClientOAuthSuccess(const ClientOAuthResult& result) {} virtual void OnClientOAuthFailure(const GoogleServiceAuthError& error) {} - virtual void OnOAuth2RevokeTokenCompleted() {} + virtual void OnOAuth2RevokeTokenCompleted(TokenRevocationStatus status) {} virtual void OnGetUserInfoSuccess(const UserInfoMap& data) {} virtual void OnGetUserInfoFailure(const GoogleServiceAuthError& error) {}
diff --git a/google_apis/gaia/gaia_auth_fetcher.cc b/google_apis/gaia/gaia_auth_fetcher.cc index ce001b4..f4039e4 100644 --- a/google_apis/gaia/gaia_auth_fetcher.cc +++ b/google_apis/gaia/gaia_auth_fetcher.cc
@@ -33,6 +33,7 @@ #include "net/url_request/url_request_status.h" namespace { + const int kLoadFlagsIgnoreCookies = net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES; @@ -89,6 +90,34 @@ } } +// Parses server responses for token revocation. +GaiaAuthConsumer::TokenRevocationStatus +GetTokenRevocationStatusFromResponseData(const std::string& data, + int response_code) { + if (response_code == net::HTTP_OK) + return GaiaAuthConsumer::TokenRevocationStatus::kSuccess; + + if (response_code == net::HTTP_INTERNAL_SERVER_ERROR) + return GaiaAuthConsumer::TokenRevocationStatus::kServerError; + + std::unique_ptr<base::Value> value = base::JSONReader::Read(data); + if (!value.get() || value->type() != base::Value::Type::DICTIONARY) + return GaiaAuthConsumer::TokenRevocationStatus::kUnknownError; + + base::DictionaryValue* dict = + static_cast<base::DictionaryValue*>(value.get()); + std::string error; + if (!dict->GetStringWithoutPathExpansion("error", &error)) + return GaiaAuthConsumer::TokenRevocationStatus::kUnknownError; + + if (error == "invalid_token") + return GaiaAuthConsumer::TokenRevocationStatus::kInvalidToken; + if (error == "invalid_request") + return GaiaAuthConsumer::TokenRevocationStatus::kInvalidRequest; + + return GaiaAuthConsumer::TokenRevocationStatus::kUnknownError; +} + } // namespace // static @@ -971,7 +1000,30 @@ const std::string& data, const net::URLRequestStatus& status, int response_code) { - consumer_->OnOAuth2RevokeTokenCompleted(); + GaiaAuthConsumer::TokenRevocationStatus revocation_status = + GaiaAuthConsumer::TokenRevocationStatus::kUnknownError; + + switch (status.status()) { + case net::URLRequestStatus::SUCCESS: + revocation_status = + GetTokenRevocationStatusFromResponseData(data, response_code); + break; + case net::URLRequestStatus::IO_PENDING: + NOTREACHED(); + break; + case net::URLRequestStatus::FAILED: + revocation_status = + (status.ToNetError() == net::ERR_TIMED_OUT) + ? GaiaAuthConsumer::TokenRevocationStatus::kConnectionTimeout + : GaiaAuthConsumer::TokenRevocationStatus::kConnectionFailed; + break; + case net::URLRequestStatus::CANCELED: + revocation_status = + GaiaAuthConsumer::TokenRevocationStatus::kConnectionCanceled; + break; + } + + consumer_->OnOAuth2RevokeTokenCompleted(revocation_status); } void GaiaAuthFetcher::OnListAccountsFetched(const std::string& data,
diff --git a/google_apis/gaia/gaia_auth_fetcher_unittest.cc b/google_apis/gaia/gaia_auth_fetcher_unittest.cc index 68340c0..9f47cc8 100644 --- a/google_apis/gaia/gaia_auth_fetcher_unittest.cc +++ b/google_apis/gaia/gaia_auth_fetcher_unittest.cc
@@ -187,6 +187,8 @@ const GoogleServiceAuthError& error)); MOCK_METHOD1(OnClientOAuthFailure, void(const GoogleServiceAuthError& error)); + MOCK_METHOD1(OnOAuth2RevokeTokenCompleted, + void(GaiaAuthConsumer::TokenRevocationStatus status)); MOCK_METHOD1(OnMergeSessionFailure, void( const GoogleServiceAuthError& error)); MOCK_METHOD1(OnUberAuthTokenFailure, void( @@ -685,3 +687,110 @@ status, net::HTTP_OK, data, net::URLFetcher::GET, &auth); auth.OnURLFetchComplete(&mock_fetcher); } + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenSuccess) { + std::string data("{}"); + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kSuccess)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + net::HTTP_OK, data, net::URLFetcher::GET, &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenCanceled) { + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kConnectionCanceled)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + net::URLRequestStatus status(net::URLRequestStatus::CANCELED, + net::ERR_ABORTED); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + 0, std::string(), net::URLFetcher::GET, &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenFailed) { + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kConnectionFailed)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + int error_no = net::ERR_CERT_CONTAINS_ERRORS; + net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + 0, std::string(), net::URLFetcher::GET, &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenTimeout) { + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kConnectionTimeout)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + int error_no = net::ERR_TIMED_OUT; + net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + 0, std::string(), net::URLFetcher::GET, &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenInvalidToken) { + std::string data("{\"error\" : \"invalid_token\"}"); + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kInvalidToken)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + net::HTTP_BAD_REQUEST, data, net::URLFetcher::GET, + &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenInvalidRequest) { + std::string data("{\"error\" : \"invalid_request\"}"); + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kInvalidRequest)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + net::HTTP_BAD_REQUEST, data, net::URLFetcher::GET, + &auth); + auth.OnURLFetchComplete(&mock_fetcher); +} + +TEST_F(GaiaAuthFetcherTest, RevokeOAuth2TokenServerError) { + std::string data("{}"); + MockGaiaConsumer consumer; + EXPECT_CALL(consumer, + OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus::kServerError)) + .Times(1); + + GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext()); + net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); + MockFetcher mock_fetcher(GaiaUrls::GetInstance()->oauth2_revoke_url(), status, + net::HTTP_INTERNAL_SERVER_ERROR, data, + net::URLFetcher::GET, &auth); + auth.OnURLFetchComplete(&mock_fetcher); +}
diff --git a/gpu/command_buffer/tests/gl_oes_egl_image_unittest.cc b/gpu/command_buffer/tests/gl_oes_egl_image_unittest.cc index d9c2107..0ee1c8c 100644 --- a/gpu/command_buffer/tests/gl_oes_egl_image_unittest.cc +++ b/gpu/command_buffer/tests/gl_oes_egl_image_unittest.cc
@@ -43,6 +43,8 @@ }; #if defined(OS_LINUX) +// TODO(crbug.com/835072): re-enable this test on ASAN once bugs are fixed. +#if !defined(ADDRESS_SANITIZER) #define SHADER(Src) #Src @@ -172,6 +174,7 @@ glDeleteBuffers(1, &vbo); glDeleteTextures(1, &texture_id); } +#endif // !defined(ADDRESS_SANITIZER) #endif // defined(OS_LINUX) } // namespace
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 81b8e8ed..967fa48 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -257,9 +257,11 @@ nullptr); create_params.initial_size = builder->window_size_; + // TODO(erikchen): Refactor this class to use strong ownership semantics. + // https://crbug.com/832879. std::unique_ptr<HeadlessWebContentsImpl> headless_web_contents = base::WrapUnique(new HeadlessWebContentsImpl( - content::WebContents::Create(create_params), + content::WebContents::Create(create_params).release(), builder->browser_context_)); if (builder->tab_sockets_allowed_) {
diff --git a/media/base/eme_constants.h b/media/base/eme_constants.h index e4f898d..77289e30 100644 --- a/media/base/eme_constants.h +++ b/media/base/eme_constants.h
@@ -18,13 +18,10 @@ // Defines bitmask values that specify codecs used in Encrypted Media Extension // (EME). Each value represents a codec within a specific container. -// The mask values are stored in a SupportedCodecs. // // TODO(yucliu): Remove container name from the enum. See crbug.com/724362 for // more details. -enum EmeCodec { - // *_ALL values should only be used for masking, do not use them to specify - // codec support because they may be extended to include more codecs. +enum EmeCodec : uint32_t { EME_CODEC_NONE = 0, EME_CODEC_WEBM_OPUS = 1 << 0, EME_CODEC_WEBM_VORBIS = 1 << 1, @@ -39,53 +36,74 @@ EME_CODEC_MP4_DV_HEVC = 1 << 9, EME_CODEC_MP4_AC3 = 1 << 10, EME_CODEC_MP4_EAC3 = 1 << 11, - EME_CODEC_WEBM_AUDIO_ALL = EME_CODEC_WEBM_OPUS | EME_CODEC_WEBM_VORBIS, - EME_CODEC_WEBM_VIDEO_ALL = - (EME_CODEC_WEBM_VP8 | EME_CODEC_WEBM_VP9 | EME_CODEC_COMMON_VP9), - EME_CODEC_WEBM_ALL = (EME_CODEC_WEBM_AUDIO_ALL | EME_CODEC_WEBM_VIDEO_ALL), -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - EME_CODEC_MP4_AUDIO_ALL = (EME_CODEC_MP4_AAC -#if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) - | - EME_CODEC_MP4_AC3 | - EME_CODEC_MP4_EAC3 -#endif // BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) - ), - EME_CODEC_MP4_VIDEO_ALL = (EME_CODEC_MP4_AVC1 | EME_CODEC_COMMON_VP9 -#if BUILDFLAG(ENABLE_HEVC_DEMUXING) - | - EME_CODEC_MP4_HEVC -#endif // BUILDFLAG(ENABLE_HEVC_DEMUXING) -#if BUILDFLAG(ENABLE_DOLBY_VISION_DEMUXING) - | - EME_CODEC_MP4_DV_AVC -#if BUILDFLAG(ENABLE_HEVC_DEMUXING) - | - EME_CODEC_MP4_DV_HEVC -#endif // BUILDFLAG(ENABLE_HEVC_DEMUXING) -#endif // BUILDFLAG(ENABLE_DOLBY_VISION_DEMUXING) - ), - EME_CODEC_MP4_ALL = (EME_CODEC_MP4_AUDIO_ALL | EME_CODEC_MP4_VIDEO_ALL), -#if BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) - EME_CODEC_MP2T_VIDEO_ALL = EME_CODEC_MP4_AVC1, - EME_CODEC_MP2T_ALL = EME_CODEC_MP2T_VIDEO_ALL, - EME_CODEC_AUDIO_ALL = (EME_CODEC_WEBM_AUDIO_ALL | EME_CODEC_MP4_AUDIO_ALL), - EME_CODEC_VIDEO_ALL = (EME_CODEC_WEBM_VIDEO_ALL | EME_CODEC_MP4_VIDEO_ALL | - EME_CODEC_MP2T_VIDEO_ALL), - EME_CODEC_ALL = (EME_CODEC_WEBM_ALL | EME_CODEC_MP4_ALL | EME_CODEC_MP2T_ALL), -#else - EME_CODEC_AUDIO_ALL = (EME_CODEC_WEBM_AUDIO_ALL | EME_CODEC_MP4_AUDIO_ALL), - EME_CODEC_VIDEO_ALL = (EME_CODEC_WEBM_VIDEO_ALL | EME_CODEC_MP4_VIDEO_ALL), - EME_CODEC_ALL = (EME_CODEC_WEBM_ALL | EME_CODEC_MP4_ALL), -#endif // BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) -#else - EME_CODEC_AUDIO_ALL = EME_CODEC_WEBM_AUDIO_ALL, - EME_CODEC_VIDEO_ALL = EME_CODEC_WEBM_VIDEO_ALL, - EME_CODEC_ALL = EME_CODEC_WEBM_ALL, -#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) }; -typedef uint32_t SupportedCodecs; +// *_ALL values should only be used for masking, do not use them to specify +// codec support because they may be extended to include more codecs. + +using SupportedCodecs = uint32_t; + +constexpr SupportedCodecs GetMp4AudioCodecs() { + SupportedCodecs codecs = EME_CODEC_NONE; +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + codecs |= EME_CODEC_MP4_AAC; +#if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) + codecs |= EME_CODEC_MP4_AC3 | EME_CODEC_MP4_EAC3; +#endif // BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) + return codecs; +} + +constexpr SupportedCodecs GetMp4VideoCodecs() { + SupportedCodecs codecs = EME_CODEC_COMMON_VP9; +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + codecs |= EME_CODEC_MP4_AVC1; +#if BUILDFLAG(ENABLE_HEVC_DEMUXING) + codecs |= EME_CODEC_MP4_HEVC; +#endif // BUILDFLAG(ENABLE_HEVC_DEMUXING) +#if BUILDFLAG(ENABLE_DOLBY_VISION_DEMUXING) + codecs |= EME_CODEC_MP4_DV_AVC; +#if BUILDFLAG(ENABLE_HEVC_DEMUXING) + codecs |= EME_CODEC_MP4_DV_HEVC; +#endif // BUILDFLAG(ENABLE_HEVC_DEMUXING) +#endif // BUILDFLAG(ENABLE_DOLBY_VISION_DEMUXING) +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) + return codecs; +} + +constexpr SupportedCodecs EME_CODEC_WEBM_AUDIO_ALL = + EME_CODEC_WEBM_OPUS | EME_CODEC_WEBM_VORBIS; + +constexpr SupportedCodecs EME_CODEC_WEBM_VIDEO_ALL = + EME_CODEC_WEBM_VP8 | EME_CODEC_WEBM_VP9 | EME_CODEC_COMMON_VP9; + +constexpr SupportedCodecs EME_CODEC_WEBM_ALL = + EME_CODEC_WEBM_AUDIO_ALL | EME_CODEC_WEBM_VIDEO_ALL; + +constexpr SupportedCodecs EME_CODEC_MP4_AUDIO_ALL = GetMp4AudioCodecs(); +constexpr SupportedCodecs EME_CODEC_MP4_VIDEO_ALL = GetMp4VideoCodecs(); + +constexpr SupportedCodecs EME_CODEC_MP4_ALL = + EME_CODEC_MP4_AUDIO_ALL | EME_CODEC_MP4_VIDEO_ALL; + +constexpr SupportedCodecs EME_CODEC_AUDIO_ALL = + EME_CODEC_WEBM_AUDIO_ALL | EME_CODEC_MP4_AUDIO_ALL; + +constexpr SupportedCodecs EME_CODEC_VIDEO_ALL = + EME_CODEC_WEBM_VIDEO_ALL | EME_CODEC_MP4_VIDEO_ALL; + +constexpr SupportedCodecs EME_CODEC_ALL = + EME_CODEC_WEBM_ALL | EME_CODEC_MP4_ALL; + +#if BUILDFLAG(USE_PROPRIETARY_CODECS) +#if BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) +constexpr SupportedCodecs EME_CODEC_MP2T_VIDEO_ALL = EME_CODEC_MP4_AVC1; +static_assert( + (EME_CODEC_MP2T_VIDEO_ALL & EME_CODEC_VIDEO_ALL) == + EME_CODEC_MP2T_VIDEO_ALL, + "EME_CODEC_MP2T_VIDEO_ALL should be a subset of EME_CODEC_MP4_ALL"); +#endif // BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) enum class EmeSessionTypeSupport { // Invalid default value.
diff --git a/media/base/key_systems.cc b/media/base/key_systems.cc index 36f5f498..b121ca7 100644 --- a/media/base/key_systems.cc +++ b/media/base/key_systems.cc
@@ -31,28 +31,33 @@ const char kClearKeyKeySystemNameForUMA[] = "ClearKey"; const char kUnknownKeySystemNameForUMA[] = "Unknown"; -struct NamedCodec { - const char* name; - EmeCodec type; +struct MimeTypeToCodecs { + const char* mime_type; + SupportedCodecs codecs; }; // Mapping between containers and their codecs. // Only audio codecs can belong to a "audio/*" mime_type, and only video codecs // can belong to a "video/*" mime_type. -static const NamedCodec kMimeTypeToCodecMasks[] = { +static const MimeTypeToCodecs kMimeTypeToCodecsMap[] = { {"audio/webm", EME_CODEC_WEBM_AUDIO_ALL}, {"video/webm", EME_CODEC_WEBM_VIDEO_ALL}, -#if BUILDFLAG(USE_PROPRIETARY_CODECS) {"audio/mp4", EME_CODEC_MP4_AUDIO_ALL}, {"video/mp4", EME_CODEC_MP4_VIDEO_ALL}, +#if BUILDFLAG(USE_PROPRIETARY_CODECS) #if BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) {"video/mp2t", EME_CODEC_MP2T_VIDEO_ALL}, #endif // BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) #endif // BUILDFLAG(USE_PROPRIETARY_CODECS) +}; // namespace media + +struct NameToCodec { + const char* name; + EmeCodec codec; }; // Mapping between codec names and enum values. -static const NamedCodec kCodecStrings[] = { +static const NameToCodec kCodecMap[] = { {"opus", EME_CODEC_WEBM_OPUS}, // Opus. {"vorbis", EME_CODEC_WEBM_VORBIS}, // Vorbis. {"vp8", EME_CODEC_WEBM_VP8}, // VP8. @@ -88,11 +93,8 @@ std::string GetKeySystemName() const override { return kClearKeyKeySystem; } bool IsSupportedInitDataType(EmeInitDataType init_data_type) const override { -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - if (init_data_type == EmeInitDataType::CENC) - return true; -#endif - return init_data_type == EmeInitDataType::WEBM || + return init_data_type == EmeInitDataType::CENC || + init_data_type == EmeInitDataType::WEBM || init_data_type == EmeInitDataType::KEYIDS; } @@ -100,13 +102,7 @@ // On Android, Vorbis, VP8, AAC and AVC1 are supported in MediaCodec: // http://developer.android.com/guide/appendix/media-formats.html // VP9 support is device dependent. - SupportedCodecs codecs = EME_CODEC_WEBM_ALL; - -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - codecs |= EME_CODEC_MP4_ALL; -#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) - - return codecs; + return EME_CODEC_WEBM_ALL | EME_CODEC_MP4_ALL; } EmeConfigRule GetRobustnessConfigRule( @@ -235,14 +231,14 @@ void AddSupportedKeySystems( std::vector<std::unique_ptr<KeySystemProperties>> key_systems); - void RegisterMimeType(const std::string& mime_type, EmeCodec codecs_mask); + void RegisterMimeType(const std::string& mime_type, SupportedCodecs codecs); bool IsValidMimeTypeCodecsCombination(const std::string& mime_type, - SupportedCodecs codecs_mask) const; + SupportedCodecs codecs) const; typedef base::hash_map<std::string, std::unique_ptr<KeySystemProperties>> KeySystemPropertiesMap; - typedef base::hash_map<std::string, SupportedCodecs> MimeTypeCodecsMap; - typedef base::hash_map<std::string, EmeCodec> CodecsMap; + typedef base::hash_map<std::string, SupportedCodecs> MimeTypeToCodecsMap; + typedef base::hash_map<std::string, EmeCodec> CodecMap; typedef base::hash_map<std::string, EmeInitDataType> InitDataTypesMap; // TODO(sandersd): Separate container enum from codec mask value. @@ -256,8 +252,8 @@ KeySystemPropertiesMap key_system_properties_map_; // This member should only be modified by RegisterMimeType(). - MimeTypeCodecsMap mime_type_to_codec_mask_map_; - CodecsMap codec_string_map_; + MimeTypeToCodecsMap mime_type_to_codecs_map_; + CodecMap codec_map_; SupportedCodecs audio_codec_mask_; SupportedCodecs video_codec_mask_; @@ -279,14 +275,14 @@ KeySystemsImpl::KeySystemsImpl() : audio_codec_mask_(EME_CODEC_AUDIO_ALL), video_codec_mask_(EME_CODEC_VIDEO_ALL) { - for (size_t i = 0; i < arraysize(kCodecStrings); ++i) { - const std::string& name = kCodecStrings[i].name; - DCHECK(!codec_string_map_.count(name)); - codec_string_map_[name] = kCodecStrings[i].type; + for (size_t i = 0; i < arraysize(kCodecMap); ++i) { + const std::string& name = kCodecMap[i].name; + DCHECK(!codec_map_.count(name)); + codec_map_[name] = kCodecMap[i].codec; } - for (size_t i = 0; i < arraysize(kMimeTypeToCodecMasks); ++i) { - RegisterMimeType(kMimeTypeToCodecMasks[i].name, - kMimeTypeToCodecMasks[i].type); + for (size_t i = 0; i < arraysize(kMimeTypeToCodecsMap); ++i) { + RegisterMimeType(kMimeTypeToCodecsMap[i].mime_type, + kMimeTypeToCodecsMap[i].codecs); } // Always update supported key systems during construction. @@ -297,9 +293,9 @@ SupportedCodecs KeySystemsImpl::GetCodecMaskForMimeType( const std::string& container_mime_type) const { - MimeTypeCodecsMap::const_iterator iter = - mime_type_to_codec_mask_map_.find(container_mime_type); - if (iter == mime_type_to_codec_mask_map_.end()) + MimeTypeToCodecsMap::const_iterator iter = + mime_type_to_codecs_map_.find(container_mime_type); + if (iter == mime_type_to_codecs_map_.end()) return EME_CODEC_NONE; DCHECK(IsValidMimeTypeCodecsCombination(container_mime_type, iter->second)); @@ -307,8 +303,8 @@ } EmeCodec KeySystemsImpl::GetCodecForString(const std::string& codec) const { - CodecsMap::const_iterator iter = codec_string_map_.find(codec); - if (iter != codec_string_map_.end()) + CodecMap::const_iterator iter = codec_map_.find(codec); + if (iter != codec_map_.end()) return iter->second; return EME_CODEC_NONE; } @@ -440,14 +436,15 @@ } // Adds the MIME type with the codec mask after verifying the validity. -// Only this function should modify |mime_type_to_codec_mask_map_|. +// Only this function should modify |mime_type_to_codecs_map_|. void KeySystemsImpl::RegisterMimeType(const std::string& mime_type, - EmeCodec codecs_mask) { + SupportedCodecs codecs) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!mime_type_to_codec_mask_map_.count(mime_type)); - DCHECK(IsValidMimeTypeCodecsCombination(mime_type, codecs_mask)); + DCHECK(!mime_type_to_codecs_map_.count(mime_type)); + DCHECK(IsValidMimeTypeCodecsCombination(mime_type, codecs)) + << ": mime_type = " << mime_type << ", codecs = " << codecs; - mime_type_to_codec_mask_map_[mime_type] = static_cast<EmeCodec>(codecs_mask); + mime_type_to_codecs_map_[mime_type] = codecs; } // Returns whether |mime_type| follows a valid format and the specified codecs @@ -455,14 +452,15 @@ // Only audio/ or video/ MIME types with their respective codecs are allowed. bool KeySystemsImpl::IsValidMimeTypeCodecsCombination( const std::string& mime_type, - SupportedCodecs codecs_mask) const { + SupportedCodecs codecs) const { DCHECK(thread_checker_.CalledOnValidThread()); - if (!codecs_mask) - return false; + if (codecs == EME_CODEC_NONE) + return true; + if (base::StartsWith(mime_type, "audio/", base::CompareCase::SENSITIVE)) - return !(codecs_mask & ~audio_codec_mask_); + return !(codecs & ~audio_codec_mask_); if (base::StartsWith(mime_type, "video/", base::CompareCase::SENSITIVE)) - return !(codecs_mask & ~video_codec_mask_); + return !(codecs & ~video_codec_mask_); return false; } @@ -513,8 +511,8 @@ const std::string& codec, uint32_t mask) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!codec_string_map_.count(codec)); - codec_string_map_[codec] = static_cast<EmeCodec>(mask); + DCHECK(!codec_map_.count(codec)); + codec_map_[codec] = static_cast<EmeCodec>(mask); if (media_type == EmeMediaType::AUDIO) { audio_codec_mask_ |= mask; } else {
diff --git a/media/blink/webcontentdecryptionmodulesession_impl.cc b/media/blink/webcontentdecryptionmodulesession_impl.cc index b8b9970..4be9a0f 100644 --- a/media/blink/webcontentdecryptionmodulesession_impl.cc +++ b/media/blink/webcontentdecryptionmodulesession_impl.cc
@@ -23,18 +23,14 @@ #include "media/blink/cdm_result_promise_helper.h" #include "media/blink/cdm_session_adapter.h" #include "media/blink/webmediaplayer_util.h" +#include "media/cdm/cenc_utils.h" #include "media/cdm/json_web_key.h" -#include "media/media_buildflags.h" #include "third_party/blink/public/platform/web_data.h" #include "third_party/blink/public/platform/web_encrypted_media_key_information.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/platform/web_vector.h" -#if BUILDFLAG(USE_PROPRIETARY_CODECS) -#include "media/cdm/cenc_utils.h" -#endif - namespace media { namespace { @@ -107,17 +103,12 @@ return true; case EmeInitDataType::CENC: -#if BUILDFLAG(USE_PROPRIETARY_CODECS) sanitized_init_data->assign(init_data, init_data + init_data_length); if (!ValidatePsshInput(*sanitized_init_data)) { error_message->assign("Initialization data for CENC is incorrect."); return false; } return true; -#else - error_message->assign("Initialization data type CENC is not supported."); - return false; -#endif case EmeInitDataType::KEYIDS: { // Extract the keys and then rebuild the message. This ensures that any
diff --git a/mojo/edk/BUILD.gn b/mojo/edk/BUILD.gn index 8597307..4c4d927 100644 --- a/mojo/edk/BUILD.gn +++ b/mojo/edk/BUILD.gn
@@ -206,7 +206,7 @@ for_mojo_core = false } -if (is_chromeos || is_linux || is_android) { +if (is_chromeos || is_linux) { core_impl_source_set("impl_for_mojo_core") { for_mojo_core = true } @@ -223,69 +223,26 @@ configs += [ ":export_only_thunks_api" ] } - if (is_chromeos) { - if (target_cpu == "arm" || target_cpu == "arm64") { - android32_toolchain = "android_clang_arm" - android64_toolchain = "android_clang_arm64" - } else { - android32_toolchain = "android_clang_x86" - android64_toolchain = "android_clang_x64" - } - - group("mojo_core_for_arc") { - deps = [ - ":mojo_core_arc32", - ":mojo_core_arc64", - ] - } - - copy("mojo_core_arc32") { - sources = [ - "${root_out_dir}/${android32_toolchain}/libmojo_core.so", - ] - outputs = [ - "${root_out_dir}/libmojo_core_arc32.so", - ] - deps = [ - ":mojo_core(//build/toolchain/android:${android32_toolchain})", - ] - } - - copy("mojo_core_arc64") { - sources = [ - "${root_out_dir}/${android64_toolchain}/libmojo_core.so", - ] - outputs = [ - "${root_out_dir}/libmojo_core_arc64.so", - ] - deps = [ - ":mojo_core(//build/toolchain/android:${android64_toolchain})", - ] - } - } - config("export_only_thunks_api") { ldflags = [ "-Wl,--version-script=" + rebase_path("//mojo/edk/export_only_thunks_api.lst") ] } - if (is_chromeos || is_linux) { - test("mojo_core_unittests") { - sources = [ - "mojo_core_unittest.cc", - "run_all_core_unittests.cc", - ] + test("mojo_core_unittests") { + sources = [ + "mojo_core_unittest.cc", + "run_all_core_unittests.cc", + ] - deps = [ - "//base", - "//base/test:test_support", - "//mojo/public/c/system", - "//testing/gtest", - ] + deps = [ + "//base", + "//base/test:test_support", + "//mojo/public/c/system", + "//testing/gtest", + ] - data_deps = [ - ":mojo_core", - ] - } + data_deps = [ + ":mojo_core", + ] } }
diff --git a/net/quic/chromium/quic_chromium_client_session.cc b/net/quic/chromium/quic_chromium_client_session.cc index b44c027..46170ac 100644 --- a/net/quic/chromium/quic_chromium_client_session.cc +++ b/net/quic/chromium/quic_chromium_client_session.cc
@@ -1618,7 +1618,12 @@ !stream_factory_->migrate_sessions_on_network_change()) { return error_code; } - net_log_.AddEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_WRITE_ERROR); + NetworkChangeNotifier::NetworkHandle current_network = + GetDefaultSocket()->GetBoundNetwork(); + + net_log_.AddEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_WRITE_ERROR, + NetLog::Int64Callback("network", current_network)); + DCHECK(packet != nullptr); DCHECK_NE(ERR_IO_PENDING, error_code); DCHECK_GT(0, error_code); @@ -1765,7 +1770,8 @@ } net_log_.AddEvent( - NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS_AFTER_PROBING); + NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS_AFTER_PROBING, + NetLog::Int64Callback("migrate_to_network", network)); if (network == default_network_) { DVLOG(1) << "Client successfully migrated to default network."; CancelMigrateBackToDefaultNetworkTimer(); @@ -1808,7 +1814,8 @@ NetworkChangeNotifier::NetworkHandle network, const NetLogWithSource& net_log) { net_log_.AddEvent( - NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_CONNECTED); + NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_CONNECTED, + NetLog::Int64Callback("connected_network", network)); // If migration_pending_ is false, there was no migration pending or // an earlier task completed migration. if (!migration_pending_) @@ -1848,7 +1855,8 @@ NetworkChangeNotifier::NetworkHandle disconnected_network, const NetLogWithSource& migration_net_log) { net_log_.AddEvent( - NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_DISCONNECTED); + NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_DISCONNECTED, + NetLog::Int64Callback("disconnected_network", disconnected_network)); LogMetricsOnNetworkDisconnected(); if (!migrate_session_on_network_change_v2_) return; @@ -1882,7 +1890,8 @@ NetworkChangeNotifier::NetworkHandle new_network, const NetLogWithSource& migration_net_log) { net_log_.AddEvent( - NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_MADE_DEFAULT); + NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_MADE_DEFAULT, + NetLog::Int64Callback("new_default_network", new_network)); LogMetricsOnNetworkMadeDefault(); if (!migrate_session_on_network_change_ &&
diff --git a/net/test/spawned_test_server/remote_test_server_config.cc b/net/test/spawned_test_server/remote_test_server_config.cc index 55a49351..f6070d9 100644 --- a/net/test/spawned_test_server/remote_test_server_config.cc +++ b/net/test/spawned_test_server/remote_test_server_config.cc
@@ -29,14 +29,7 @@ #if defined(OS_ANDROID) PathService::Get(base::DIR_ANDROID_EXTERNAL_STORAGE, &dir); #elif defined(OS_FUCHSIA) - // TODO(https://crbug.com/805057): Remove conditional after bootfs turndown. - if (base::GetPackageRoot().empty()) { - // Bootfs runs. - dir = base::FilePath("/system"); - } else { - // Packaged runs. - dir = base::FilePath("/data"); - } + dir = base::FilePath("/data"); #else PathService::Get(base::DIR_TEMP, &dir); #endif
diff --git a/services/network/cors/preflight_controller.cc b/services/network/cors/preflight_controller.cc index 5ede5fd..5a2e306e 100644 --- a/services/network/cors/preflight_controller.cc +++ b/services/network/cors/preflight_controller.cc
@@ -318,11 +318,12 @@ } void HandleResponseBody(std::unique_ptr<std::string> response_body) { - // Reached only when the request fails without receiving headers. + // Reached only when the request fails without receiving headers, e.g. + // unknown hosts, unreachable remote, reset by peer, and so on. + // See https://crbug.com/826868 for related discussion. DCHECK(!response_body); - - // TODO(toyoshim): FinalizeLoader() and RemoveFromController() need to be - // called in this case. Try in the follow-up change. + FinalizeLoader(); + RemoveFromController(); } void FinalizeLoader() {
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index 337b0e9..033c096 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -4071,32 +4071,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-384.90", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -4710,33 +4684,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6613", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ], - "expiration": 10800 - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -5221,32 +5168,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:5912", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -5746,32 +5667,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-384.90", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -13261,32 +13156,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8816", - "os": "Windows-10", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -13997,32 +13866,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:5912", - "os": "Windows-10", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -15074,41 +14917,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8816", - "os": "Windows-10", - "pool": "Chrome-GPU" - } - ] - }, - "trigger_script": { - "args": [ - "--multiple-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", - "--multiple-dimension-script-verbose", - "True" - ], - "script": "//testing/trigger_scripts/trigger_multiple_dimensions.py" - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -16165,32 +15973,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6613", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -16821,32 +16603,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8792", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -17524,32 +17280,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6613", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -18454,41 +18184,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8792", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - }, - "trigger_script": { - "args": [ - "--multiple-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}]", - "--multiple-dimension-script-verbose", - "True" - ], - "script": "//testing/trigger_scripts/trigger_multiple_dimensions.py" - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -19272,32 +18967,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug_x64", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8792", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug_x64", @@ -19975,32 +19644,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release_x64", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8792", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release_x64",
diff --git a/testing/buildbot/chromium.gpu.json b/testing/buildbot/chromium.gpu.json index a8756c8f..c7ca2f8 100644 --- a/testing/buildbot/chromium.gpu.json +++ b/testing/buildbot/chromium.gpu.json
@@ -636,32 +636,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-384.90", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -1023,32 +997,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-384.90", - "os": "Ubuntu", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release", @@ -2838,32 +2786,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=debug", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8816", - "os": "Windows-10", - "pool": "Chrome-GPU" - } - ] - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=debug", @@ -3428,41 +3350,6 @@ }, { "args": [ - "screenshot_sync", - "--show-stdout", - "--browser=release", - "--passthrough", - "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --enable-features=VizDisplayCompositor", - "--dont-restore-color-profile-after-test" - ], - "isolate_name": "telemetry_gpu_integration_test", - "name": "viz_screenshot_sync_tests", - "override_compile_targets": [ - "telemetry_gpu_integration_test" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:1cb3-23.21.13.8816", - "os": "Windows-10", - "pool": "Chrome-GPU" - } - ] - }, - "trigger_script": { - "args": [ - "--multiple-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", - "--multiple-dimension-script-verbose", - "True" - ], - "script": "//testing/trigger_scripts/trigger_multiple_dimensions.py" - } - }, - { - "args": [ "webgl_conformance", "--show-stdout", "--browser=release",
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 567db1d..5fb962a 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -888,6 +888,26 @@ { "args": [ "--test-launcher-batch-limit=1", + "--test-launcher-print-test-stdio=always", + "--use-gpu-in-tests", + "--no-xvfb" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "10de:1cb3", + "os": "Ubuntu", + "pool": "Chrome-GPU" + } + ] + }, + "test": "gl_tests", + "use_xvfb": false + }, + { + "args": [ + "--test-launcher-batch-limit=1", "--test-launcher-print-test-stdio=always" ], "swarming": { @@ -1442,6 +1462,24 @@ } ] }, + "test": "gl_tests", + "use_xvfb": false + }, + { + "args": [ + "--use-gpu-in-tests", + "--no-xvfb" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "10de:1cb3", + "os": "Ubuntu", + "pool": "Chrome-GPU" + } + ] + }, "test": "gl_unittests", "use_xvfb": false }, @@ -3120,6 +3158,24 @@ "test": "gin_unittests" }, { + "args": [ + "--use-gpu-in-tests", + "--no-xvfb" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "10de:1cb3", + "os": "Ubuntu", + "pool": "Chrome-GPU" + } + ] + }, + "test": "gl_tests", + "use_xvfb": false + }, + { "swarming": { "can_use_on_swarming_builders": true },
diff --git a/testing/buildbot/filters/fuchsia.base_unittests.filter b/testing/buildbot/filters/fuchsia.base_unittests.filter index f771e49..50d14a6 100644 --- a/testing/buildbot/filters/fuchsia.base_unittests.filter +++ b/testing/buildbot/filters/fuchsia.base_unittests.filter
@@ -26,11 +26,6 @@ -SysInfoTest.AmountOfMem -SysInfoTest.AmountOfTotalDiskSpace -# Remove this filter once the migration to packages is complete. -# See crbug.com/805057. --NativeLibraryTest.LoadLibrary --NativeLibraryTest.LoadLibraryPreferOwnSymbols - # These tests are affected by an issue with cloning namespace entries from # inside a package. See https://crbug.com/826018 -ProcessUtilTest.CloneAlternateDir
diff --git a/testing/buildbot/filters/mash.browser_tests.filter b/testing/buildbot/filters/mash.browser_tests.filter index cb3426e..a509947 100644 --- a/testing/buildbot/filters/mash.browser_tests.filter +++ b/testing/buildbot/filters/mash.browser_tests.filter
@@ -337,6 +337,8 @@ -OpenVideoFiles/FileManagerBrowserTest.* -TabindexFocusDownloads/FileManagerBrowserTestWithLegacyEventDispatch.Test/0 -TabindexFocusDownloads/FileManagerBrowserTestWithLegacyEventDispatch.Test/1 +-TabindexOpenDialog/FileManagerBrowserTest.* +-TabindexSaveFileDialog/FileManagerBrowserTest.* -DeclarativeNetRequestResourceTypeBrowserTest.Test1/1 -DeclarativeNetRequestResourceTypeBrowserTest.Test2/0 -DeclarativeNetRequestResourceTypeBrowserTest.Test2/1
diff --git a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter index 9a2f098..654abc2d 100644 --- a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter +++ b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter
@@ -57,6 +57,10 @@ -ContentSettingsTest.RedirectLoopCookies # http://crbug.com/816684 Track Page Load Metrics. +-AdsPageLoadMetricsObserverBrowserTest.OriginStatusMetricEmbedded +-AdsPageLoadMetricsObserverBrowserTest.OriginStatusMetricEmbeddedEmpty +-AdsPageLoadMetricsObserverBrowserTest.OriginStatusMetricSame +-AdsPageLoadMetricsObserverBrowserTest.OriginStatusMetricCross -AdsPageLoadMetricsObserverBrowserTest.DocOverwritesNavigation -AdsPageLoadMetricsObserverBrowserTest.SubresourceFilter -PageLoadMetricsBrowserTest.LoadingMetrics @@ -154,6 +158,7 @@ -ExtensionWebRequestApiTest.WebRequestDeclarative2 -ExtensionWebRequestApiTest.WebRequestDiceHeaderProtection -ExtensionWebRequestApiTest.WebRequestTypes +-LocalNTPInterceptionWebRequestAPITest.OneGoogleBarRequestsHidden # https://crbug.com/721400 # WebSocket with the network service
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 6109e05..7ce427f 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1504,11 +1504,8 @@ 'Out of Process Profiling Linux', 'ThinLTO Linux ToT', # chromium.memory - 'Linux ASan LSan Tests (1)', # https://crbug.com/830659 - 'Linux CFI', # https://crbug.com/830659 'Linux MSan Tests', # https://crbug.com/830659 'Linux ChromiumOS MSan Tests', # https://crbug.com/830659 - 'Linux TSan Tests', # https://crbug.com/830659 ], 'modifications': { 'KitKat Tablet Tester': { @@ -1521,6 +1518,74 @@ 'hard_timeout': 120, }, }, + # chromium.memory + # https://crbug.com/830659 + # TODO(kbr): figure out a better way to specify blocks of + # arguments like this for tests on multiple machines. + 'Linux ASan LSan Tests (1)': { + 'args': [ + '--use-gpu-in-tests', + '--no-xvfb', + ], + 'swarming': { + 'dimension_sets': [ + { + 'gpu': '10de:1cb3', + 'os': 'Ubuntu', + 'pool': 'Chrome-GPU', + }, + ], + }, + 'use_xvfb': False, + }, + 'Linux ASan LSan Tests (1)': { + 'args': [ + '--use-gpu-in-tests', + '--no-xvfb', + ], + 'swarming': { + 'dimension_sets': [ + { + 'gpu': '10de:1cb3', + 'os': 'Ubuntu', + 'pool': 'Chrome-GPU', + }, + ], + }, + 'use_xvfb': False, + }, + 'Linux CFI': { + 'args': [ + '--use-gpu-in-tests', + '--no-xvfb', + ], + 'swarming': { + 'dimension_sets': [ + { + 'gpu': '10de:1cb3', + 'os': 'Ubuntu', + 'pool': 'Chrome-GPU', + }, + ], + }, + 'use_xvfb': False, + }, + 'Linux TSan Tests': { + 'args': [ + '--use-gpu-in-tests', + '--no-xvfb', + ], + 'swarming': { + 'dimension_sets': [ + { + 'gpu': '10de:1cb3', + 'os': 'Ubuntu', + 'pool': 'Chrome-GPU', + }, + ], + }, + 'use_xvfb': False, + }, }, }, 'gl_unittests': {
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 697bb6e4..15d363b 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -2313,6 +2313,7 @@ crbug.com/836627 external/wpt/content-security-policy/inside-worker/shared-inheritance.html [ Pass Failure ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 external/wpt/css/cssom-view/scroll-behavior-smooth.html [ Timeout ] crbug.com/626703 external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ Skip ] crbug.com/626703 virtual/outofblink-cors/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ Skip ] crbug.com/626703 external/wpt/css/css-text/overflow-wrap/overflow-wrap-break-word-003.html [ Failure ] @@ -3063,8 +3064,6 @@ crbug.com/707359 [ Mac ] fast/css-grid-layout/grid-self-baseline-vertical-rl-04.html [ Failure ] crbug.com/707359 [ Mac ] fast/css-grid-layout/grid-self-baseline-vertical-rl-05.html [ Failure ] -crbug.com/810176 http/tests/devtools/runtime/evaluate-timeout.js [ NeedsManualRebaseline ] - # [selectors-4] crbug.com/706118 external/wpt/css/selectors/focus-within-004.html [ Failure ] crbug.com/576815 external/wpt/css/selectors/selectors-dir-selector-ltr-001.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/VirtualTestSuites b/third_party/WebKit/LayoutTests/VirtualTestSuites index 141a2696..d10a41a3 100644 --- a/third_party/WebKit/LayoutTests/VirtualTestSuites +++ b/third_party/WebKit/LayoutTests/VirtualTestSuites
@@ -152,6 +152,15 @@ "--enable-viewport", "--disable-canvas-aa", "--disable-composited-antialiasing"] }, { + "prefix": "android", + "base": "frame-size", + "args": ["--enable-features=OverlayScrollbar", "--enable-threaded-compositing", + "--enable-fixed-position-compositing", "--enable-prefer-compositing-to-lcd-text", + "--enable-composited-scrolling-for-frames", "--enable-gesture-tap-highlight", "--enable-pinch", + "--force-overlay-fullscreen-video", "--enable-overscroll-notifications", + "--enable-viewport", "--disable-canvas-aa", "--disable-composited-antialiasing"] + }, + { "prefix": "media-gpu-accelerated", "base": "external/wpt/media-source", "args": ["--use-gpu-in-tests"]
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index 50ea1dcd..d3869fe1 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -9865,6 +9865,30 @@ {} ] ], + "css/CSS2/floats/new-fc-beside-adjoining-float.html": [ + [ + "/css/CSS2/floats/new-fc-beside-adjoining-float.html", + [ + [ + "/css/reference/ref-filled-green-200px-square.html", + "==" + ] + ], + {} + ] + ], + "css/CSS2/floats/new-fc-separates-from-float.html": [ + [ + "/css/CSS2/floats/new-fc-separates-from-float.html", + [ + [ + "/css/reference/ref-filled-green-200px-square.html", + "==" + ] + ], + {} + ] + ], "css/CSS2/floats/zero-width-floats.html": [ [ "/css/CSS2/floats/zero-width-floats.html", @@ -121672,6 +121696,11 @@ {} ] ], + "css/css-syntax/declarations-trim-whitespace-expected.txt": [ + [ + {} + ] + ], "css/css-tables/OWNERS": [ [ {} @@ -153547,6 +153576,11 @@ {} ] ], + "infrastructure/browsers/firefox/prefs-expected.txt": [ + [ + {} + ] + ], "infrastructure/expected-fail/failing-test-expected.txt": [ [ {} @@ -153557,6 +153591,16 @@ {} ] ], + "infrastructure/metadata/infrastructure/browsers/firefox/__dir__.ini": [ + [ + {} + ] + ], + "infrastructure/metadata/infrastructure/browsers/firefox/prefs.html.ini": [ + [ + {} + ] + ], "infrastructure/metadata/infrastructure/expected-fail/failing-test.html.ini": [ [ {} @@ -161852,6 +161896,11 @@ {} ] ], + "service-workers/service-worker/update-result.https-expected.txt": [ + [ + {} + ] + ], "service-workers/service-worker/worker-in-sandboxed-iframe-by-csp-fetch-event.https-expected.txt": [ [ {} @@ -185535,6 +185584,12 @@ {} ] ], + "css/css-syntax/declarations-trim-whitespace.html": [ + [ + "/css/css-syntax/declarations-trim-whitespace.html", + {} + ] + ], "css/css-syntax/ident-three-code-points.html": [ [ "/css/css-syntax/ident-three-code-points.html", @@ -195879,9 +195934,9 @@ {} ] ], - "feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.sub.html": [ + "feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.html": [ [ - "/feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.sub.html", + "/feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.html", {} ] ], @@ -209653,6 +209708,12 @@ {} ] ], + "infrastructure/browsers/firefox/prefs.html": [ + [ + "/infrastructure/browsers/firefox/prefs.html", + {} + ] + ], "infrastructure/expected-fail/failing-test.html": [ [ "/infrastructure/expected-fail/failing-test.html", @@ -230921,6 +230982,18 @@ {} ] ], + "server-timing/navigation_timing_idl.html": [ + [ + "/server-timing/navigation_timing_idl.html", + {} + ] + ], + "server-timing/resource_timing_idl.html": [ + [ + "/server-timing/resource_timing_idl.html", + {} + ] + ], "server-timing/server_timing_header-parsing.html": [ [ "/server-timing/server_timing_header-parsing.html", @@ -232247,6 +232320,12 @@ {} ] ], + "service-workers/service-worker/update-result.https.html": [ + [ + "/service-workers/service-worker/update-result.https.html", + {} + ] + ], "service-workers/service-worker/update.https.html": [ [ "/service-workers/service-worker/update.https.html", @@ -264402,6 +264481,14 @@ "7287e2ce42cab8fda1f63e97c98b664f0b49e9fb", "reftest" ], + "css/CSS2/floats/new-fc-beside-adjoining-float.html": [ + "f378062671d9de538e54c7dba552c2deab57baa4", + "reftest" + ], + "css/CSS2/floats/new-fc-separates-from-float.html": [ + "357427f1d71d7137c1ba4c386ae25acc7712928e", + "reftest" + ], "css/CSS2/floats/zero-space-between-floats-001.html": [ "59cd6c4ac06a611570a3ec21bac7289345b184f7", "testharness" @@ -298866,6 +298953,14 @@ "abadfe4da5dc6adc4e40700e84674ec84fc6d744", "testharness" ], + "css/css-syntax/declarations-trim-whitespace-expected.txt": [ + "78fbcb79d8c436fc24eaca8e5e699e9c471cffa9", + "support" + ], + "css/css-syntax/declarations-trim-whitespace.html": [ + "4e95ed2655816b40c437af2846bf4b513e527f0b", + "testharness" + ], "css/css-syntax/ident-three-code-points.html": [ "7ce37259edc09da4e36f40c026ac76f33d829720", "testharness" @@ -322407,7 +322502,7 @@ "support" ], "css/cssom-view/scroll-behavior-smooth.html": [ - "966ebff69f91c0ea92f4bc2f943df9ef9dc3bcf9", + "92b15db94769eccd94ee5b43b233b49ca66f2b9c", "testharness" ], "css/cssom-view/scroll-no-layout-box.html": [ @@ -333602,7 +333697,7 @@ "2ae1da8e026e63625a6168b842303cc156963ced", "support" ], - "feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.sub.html": [ + "feature-policy/experimental-features/vertical-scroll-scrollintoview.tentative.html": [ "fe6000c242c73c81b5fc3c227f7703299fea455c", "testharness" ], @@ -355970,6 +356065,14 @@ "e7549e915a809b48cac816dacdd7a9bbf476b596", "support" ], + "infrastructure/browsers/firefox/prefs-expected.txt": [ + "60b3082e7b4b85acfbd6239f69fe5c70db274450", + "support" + ], + "infrastructure/browsers/firefox/prefs.html": [ + "32cd95068c1f207719e75f27144ebe74eb7a9c75", + "testharness" + ], "infrastructure/expected-fail/failing-test-expected.txt": [ "936079eb1760f752fca0b0af39eecaf59d233c90", "support" @@ -355982,6 +356085,14 @@ "0f536ac59a959769966d56c5a546f9f2c2557e97", "support" ], + "infrastructure/metadata/infrastructure/browsers/firefox/__dir__.ini": [ + "29d2053e55e60d4e8a15def3a96a3501db03ec54", + "support" + ], + "infrastructure/metadata/infrastructure/browsers/firefox/prefs.html.ini": [ + "073cc56d2a4655779b55cf543a27ce1daded5936", + "support" + ], "infrastructure/metadata/infrastructure/expected-fail/failing-test.html.ini": [ "7eecbfc4845e6befe54b0f007d587a1a003993dc", "support" @@ -356183,7 +356294,7 @@ "support" ], "interfaces/geometry.idl": [ - "9aae8525ee6b27797783495e8d918892ee857a78", + "c757c625c0f5df3d677b5646bef04ac7075dbb64", "support" ], "interfaces/gyroscope.idl": [ @@ -375250,6 +375361,14 @@ "661cf7f329590a89aa2644a102a10d1ba34feb75", "testharness" ], + "server-timing/navigation_timing_idl.html": [ + "191f42a92f0ac135de816275920e54fa50065b15", + "testharness" + ], + "server-timing/resource_timing_idl.html": [ + "eba493537f5d156b4fb074e24787e522ea3c7971", + "testharness" + ], "server-timing/resources/blue.png": [ "7de5cdb5ad04ac365430b3b5f5ba01d2ba57ea23", "support" @@ -375939,7 +376058,7 @@ "support" ], "server-timing/server_timing_header-parsing.html": [ - "bde9c39ce610bd7178800f92f3181bef3cd55918", + "10f756bbf749b7ad8f7c6eb4efe752ee79c44b4a", "testharness" ], "server-timing/test_server_timing.html": [ @@ -378226,6 +378345,14 @@ "aac5705d6844e4a33200418504adb57053a45be2", "testharness" ], + "service-workers/service-worker/update-result.https-expected.txt": [ + "a9b3d1e5f40895cc1be2204bfeb7784792a15bbb", + "support" + ], + "service-workers/service-worker/update-result.https.html": [ + "06741e887be9746d7354394f74c054dd920d1b60", + "testharness" + ], "service-workers/service-worker/update.https.html": [ "d55da98b05b5885084474ebdbabdf6c0998f8bca", "testharness" @@ -382571,11 +382698,11 @@ "testharness" ], "web-animations/interfaces/KeyframeEffect/setKeyframes-expected.txt": [ - "27778063ab43a669b79aba5f792b4ba5ff22e071", + "179f66bdf827e9ea781c7cb6b96699c684d4f965", "support" ], "web-animations/interfaces/KeyframeEffect/setKeyframes.html": [ - "a346e0e004010a6f51e06ffd30d0b6eddd45421d", + "c5c631ef4e728ea5f40f14ad5590e4836068f361", "testharness" ], "web-animations/interfaces/KeyframeEffect/target-expected.txt": [
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace-expected.txt new file mode 100644 index 0000000..57d37ec --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace-expected.txt
@@ -0,0 +1,12 @@ +This is a testharness.js-based test. +PASS --foo-1:bar; +FAIL --foo-2: bar; assert_equals: expected "bar" but got " bar" +FAIL --foo-3:bar ; assert_equals: expected "bar" but got "bar " +FAIL --foo-4: bar ; assert_equals: expected "bar" but got " bar " +FAIL --foo-5: bar !important; assert_equals: expected "bar" but got " bar " +FAIL --foo-6: bar !important ; assert_equals: expected "bar" but got " bar " +PASS --foo-7:bar!important; +PASS --foo-8:bar!important ; +FAIL --foo-9:bar (then ws until end of rule) assert_equals: expected "bar" but got "bar " +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace.html new file mode 100644 index 0000000..a7d69d1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-syntax/declarations-trim-whitespace.html
@@ -0,0 +1,54 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Declarations trim whitespace from their beginning/ending</title> +<meta name="author" title="Tab Atkins-Bittner"> +<link rel=help href="https://drafts.csswg.org/css-syntax/#consume-declaration"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> + <div id="log"></div> + <style id="style-el"> + #foo { + --foo-1:bar; + --foo-2: bar; + --foo-3:bar ; + --foo-4: bar ; + --foo-5: bar !important; + --foo-6: bar !important ; + --foo-7:bar!important; + --foo-8:bar!important ; + --foo-9:bar + } + </style> + <p id=foo>foo</p> + <script> + let stylesheet = getComputedStyle(document.querySelector("#foo")); + let canonical = "bar"; + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-1"), canonical); + }, "--foo-1:bar;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-2"), canonical); + }, "--foo-2: bar;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-3"), canonical); + }, "--foo-3:bar ;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-4"), canonical); + }, "--foo-4: bar ;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-5"), canonical); + }, "--foo-5: bar !important;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-6"), canonical); + }, "--foo-6: bar !important ;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-7"), canonical); + }, "--foo-7:bar!important;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-8"), canonical); + }, "--foo-8:bar!important ;"); + test(function() { + assert_equals(stylesheet.getPropertyValue("--foo-9"), canonical); + }, "--foo-9:bar (then ws until end of rule)"); + </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html index f144a5f..e1a7a6a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html
@@ -56,5 +56,85 @@ window.scrollTo(0, 0); }, "BODY element scroll-behavior should not propagate to viewport"); + var instantHistoryNavigationTest = + async_test("Instant scrolling while doing history navigation."); + var smoothHistoryNavigationTest = + async_test("Smooth scrolling while doing history navigation."); + + function instant() { + document.documentElement.className = ""; + document.body.className = ""; + window.scrollTo(0, 0); + var p = document.createElement("pre"); + p.textContent = new Array(1000).join("newline\n"); + var a = document.createElement("a"); + a.href = "#"; + a.name = "foo"; + a.textContent = "foo"; + p.appendChild(a); + document.body.appendChild(p); + window.onhashchange = function() { + window.onhashchange = function() { + instantHistoryNavigationTest.step(function() { + assert_equals(location.hash, "", "Shouldn't be scrolled to a fragment."); + assert_equals(window.scrollY, 0, "Shouldn't be scrolled back to top yet."); + }); + p.remove(); + instantHistoryNavigationTest.done(); + smooth(); + } + + instantHistoryNavigationTest.step(function() { + assert_equals(location.hash, "#foo", "Should be scrolled to a fragment."); + assert_not_equals(window.scrollY, 0, "Shouldn't be scrolled to top anymore."); + }); + history.back(); + } + + instantHistoryNavigationTest.step(function() { + assert_equals(window.scrollY, 0, "Should be scrolled to top."); + assert_equals(location.hash, "", "Shouldn't be scrolled to a fragment."); + }); + location.hash = "foo"; + }; + instant(); + + function smooth() { + document.documentElement.className = ""; + document.body.className = ""; + window.scrollTo(0, 0); + var p = document.createElement("pre"); + p.textContent = new Array(1000).join("newline\n"); + var a = document.createElement("a"); + a.href = "#"; + a.name = "bar"; + a.textContent = "bar"; + p.appendChild(a); + document.body.appendChild(p); + window.onhashchange = function() { + window.onhashchange = function() { + smoothHistoryNavigationTest.step(function() { + assert_equals(location.hash, "", "Shouldn't be scrolled to a fragment."); + assert_not_equals(window.scrollY, 0, "Shouldn't be scrolled back to top yet."); + }); + p.remove(); + smoothHistoryNavigationTest.done(); + } + + smoothHistoryNavigationTest.step(function() { + assert_equals(location.hash, "#bar", "Should be scrolled to a fragment."); + assert_not_equals(window.scrollY, 0, "Shouldn't be scrolled to top anymore."); + }); + history.back(); + } + + smoothHistoryNavigationTest.step(function() { + assert_equals(window.scrollY, 0, "Should be scrolled to top."); + assert_equals(location.hash, "", "Shouldn't be scrolled to a fragment."); + }); + location.hash = "bar"; + document.documentElement.className = "smooth"; + }; + testContainer.style.display = "none"; </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-init-003.sub-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-init-003.sub-expected.txt deleted file mode 100644 index 24aa75d..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-init-003.sub-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -This is a testharness.js-based test. -PASS Check request values when initialized from Request -PASS Check request values when initialized from Request and init values -FAIL Check request values when initialized from url string assert_equals: Check credentials attribute expected "same-origin" but got "omit" -PASS Check request values when initialized from url and init values -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-structure-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-structure-expected.txt deleted file mode 100644 index 6d98b9ab..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/request/request-structure-expected.txt +++ /dev/null
@@ -1,21 +0,0 @@ -This is a testharness.js-based test. -PASS Request has clone method -PASS Request has arrayBuffer method -PASS Request has blob method -PASS Request has formData method -PASS Request has json method -PASS Request has text method -PASS Check method attribute -PASS Check url attribute -PASS Check headers attribute -PASS Check destination attribute -PASS Check referrer attribute -PASS Check referrerPolicy attribute -PASS Check mode attribute -FAIL Check credentials attribute assert_equals: Attribute credentials is read only. Default value is same-origin expected "same-origin" but got "omit" -PASS Check cache attribute -PASS Check redirect attribute -PASS Check integrity attribute -PASS Check bodyUsed attribute -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs-expected.txt new file mode 100644 index 0000000..89be16e --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Ensure that setting gecko prefs works Uncaught Error: assert_equals: expected "rgb(0, 255, 0)" but got "rgb(0, 0, 0)" +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs.html b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs.html new file mode 100644 index 0000000..64a985a --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/browsers/firefox/prefs.html
@@ -0,0 +1,7 @@ +<title>Ensure that setting gecko prefs works</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +assert_equals(getComputedStyle(document.documentElement).color, "rgb(0, 255, 0)") +</script> +<p>This should be green</p>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/__dir__.ini b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/__dir__.ini new file mode 100644 index 0000000..3e0ed18 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/__dir__.ini
@@ -0,0 +1,2 @@ +disabled: + if product != "firefox": true \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/prefs.html.ini b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/prefs.html.ini new file mode 100644 index 0000000..7b78d216 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/infrastructure/metadata/infrastructure/browsers/firefox/prefs.html.ini
@@ -0,0 +1,2 @@ +[prefs.html] + prefs: ["browser.display.foreground_color:#00FF00"]
diff --git a/third_party/WebKit/LayoutTests/external/wpt/interfaces/geometry.idl b/third_party/WebKit/LayoutTests/external/wpt/interfaces/geometry.idl index 7ee2a5a..be1d56b2 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/interfaces/geometry.idl +++ b/third_party/WebKit/LayoutTests/external/wpt/interfaces/geometry.idl
@@ -80,7 +80,6 @@ unrestricted double height = 0; }; -[LegacyArrayClass] interface DOMRectList { readonly attribute unsigned long length; getter DOMRect? item(unsigned long index);
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resources/idlharness.js b/third_party/WebKit/LayoutTests/external/wpt/resources/idlharness.js index fe72395..4664465 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/resources/idlharness.js +++ b/third_party/WebKit/LayoutTests/external/wpt/resources/idlharness.js
@@ -1513,8 +1513,6 @@ // object. // "Otherwise, if A is declared to inherit from another interface, then // return the interface prototype object for the inherited interface. - // "Otherwise, if A is declared with the [LegacyArrayClass] extended - // attribute, then return %ArrayPrototype%. // "Otherwise, return %ObjectPrototype%. // // "In the ECMAScript binding, the DOMException type has some additional @@ -1537,9 +1535,6 @@ !this.array .members[inherit_interface] .has_extended_attribute("NoInterfaceObject"); - } else if (this.has_extended_attribute('LegacyArrayClass')) { - inherit_interface = 'Array'; - inherit_interface_has_interface_object = true; } else if (this.name === "DOMException") { inherit_interface = 'Error'; inherit_interface_has_interface_object = true;
diff --git a/third_party/WebKit/LayoutTests/external/wpt/server-timing/navigation_timing_idl.html b/third_party/WebKit/LayoutTests/external/wpt/server-timing/navigation_timing_idl.html new file mode 100644 index 0000000..290bb88 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/server-timing/navigation_timing_idl.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<head> + <meta charset='utf-8' /> + <script src="/resources/testharness.js"></script> + <script src='/resources/testharnessreport.js'></script> + <script> + setup({explicit_done: true}) + window.addEventListener('load', function(){ + assert_not_equals(typeof performance.getEntriesByType('navigation')[0].serverTiming, 'undefined', + 'An instance of `PerformanceNavigationTiming` should have a `serverTiming` attribute.') + done() + }) + </script> +</head>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/server-timing/resource_timing_idl.html b/third_party/WebKit/LayoutTests/external/wpt/server-timing/resource_timing_idl.html new file mode 100644 index 0000000..d2c3c92 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/server-timing/resource_timing_idl.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<head> + <meta charset='utf-8' /> + <script src="/resources/testharness.js"></script> + <script src='/resources/testharnessreport.js'></script> + <script> + setup({explicit_done: true}) + window.addEventListener('load', function(){ + assert_not_equals(typeof performance.getEntriesByType('resource')[0].serverTiming, 'undefined', + 'An instance of `PerformanceResourceTiming` should have a `serverTiming` attribute.') + done() + }) + </script> +</head>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/server-timing/server_timing_header-parsing.html b/third_party/WebKit/LayoutTests/external/wpt/server-timing/server_timing_header-parsing.html index 4049c3dd..50396ed 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/server-timing/server_timing_header-parsing.html +++ b/third_party/WebKit/LayoutTests/external/wpt/server-timing/server_timing_header-parsing.html
@@ -19,7 +19,6 @@ } function runTests() { tests.forEach(function({url, expectedResults}) { - debugger; const {serverTiming} = performance.getEntriesByName(url)[0] const fileName = url.substring(url.lastIndexOf('/') + 1)
diff --git a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https-expected.txt new file mode 100644 index 0000000..74708f1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL ServiceWorkerRegistration.update() should resolve a registration object assert_true: update() should resolve a ServiceWorkerRegistration expected true got false +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https.html b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https.html new file mode 100644 index 0000000..d8ed94f --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/update-result.https.html
@@ -0,0 +1,23 @@ +<!DOCTYPE html> +<title>Service Worker: update() should resolve a ServiceWorkerRegistration</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/test-helpers.sub.js"></script> +<body> +<script> + +promise_test(async function(t) { + const script = './resources/empty.js'; + const scope = './resources/empty.html?update-result'; + + let reg = await navigator.serviceWorker.register(script, { scope }); + t.add_cleanup(async _ => await reg.unregister()); + await wait_for_state(t, reg.installing, 'activated'); + + let result = await reg.update(); + assert_true(result instanceof ServiceWorkerRegistration, + 'update() should resolve a ServiceWorkerRegistration'); +}, 'ServiceWorkerRegistration.update() should resolve a registration object'); + +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-and-gced-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-and-gced-expected.txt index 26239bf..bcd79ea 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-and-gced-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-and-gced-expected.txt
@@ -144,30 +144,7 @@ PASS childWindow.outerWidth is 0 PASS childWindow.pageXOffset is 0 PASS childWindow.pageYOffset is 0 -PASS childWindow.performance.navigation.redirectCount is 0 -PASS childWindow.performance.navigation.type is 0 PASS childWindow.performance.onresourcetimingbufferfull is null -PASS childWindow.performance.timing.connectEnd is 0 -PASS childWindow.performance.timing.connectStart is 0 -PASS childWindow.performance.timing.domComplete is 0 -PASS childWindow.performance.timing.domContentLoadedEventEnd is 0 -PASS childWindow.performance.timing.domContentLoadedEventStart is 0 -PASS childWindow.performance.timing.domInteractive is 0 -PASS childWindow.performance.timing.domLoading is 0 -PASS childWindow.performance.timing.domainLookupEnd is 0 -PASS childWindow.performance.timing.domainLookupStart is 0 -PASS childWindow.performance.timing.fetchStart is 0 -PASS childWindow.performance.timing.loadEventEnd is 0 -PASS childWindow.performance.timing.loadEventStart is 0 -PASS childWindow.performance.timing.navigationStart is 0 -PASS childWindow.performance.timing.redirectEnd is 0 -PASS childWindow.performance.timing.redirectStart is 0 -PASS childWindow.performance.timing.requestStart is 0 -PASS childWindow.performance.timing.responseEnd is 0 -PASS childWindow.performance.timing.responseStart is 0 -PASS childWindow.performance.timing.secureConnectionStart is 0 -PASS childWindow.performance.timing.unloadEventEnd is 0 -PASS childWindow.performance.timing.unloadEventStart is 0 PASS childWindow.personalbar.visible is false PASS childWindow.screen.availHeight is 0 PASS childWindow.screen.availLeft is 0
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-expected.txt index d8badf9f..72ed51ba 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/Window/property-access-on-cached-window-after-frame-removed-expected.txt
@@ -144,30 +144,7 @@ PASS childWindow.outerWidth is 0 PASS childWindow.pageXOffset is 0 PASS childWindow.pageYOffset is 0 -PASS childWindow.performance.navigation.redirectCount is 0 -PASS childWindow.performance.navigation.type is 0 PASS childWindow.performance.onresourcetimingbufferfull is null -PASS childWindow.performance.timing.connectEnd is 0 -PASS childWindow.performance.timing.connectStart is 0 -PASS childWindow.performance.timing.domComplete is 0 -PASS childWindow.performance.timing.domContentLoadedEventEnd is 0 -PASS childWindow.performance.timing.domContentLoadedEventStart is 0 -PASS childWindow.performance.timing.domInteractive is 0 -PASS childWindow.performance.timing.domLoading is 0 -PASS childWindow.performance.timing.domainLookupEnd is 0 -PASS childWindow.performance.timing.domainLookupStart is 0 -PASS childWindow.performance.timing.fetchStart is 0 -PASS childWindow.performance.timing.loadEventEnd is 0 -PASS childWindow.performance.timing.loadEventStart is 0 -PASS childWindow.performance.timing.navigationStart is 0 -PASS childWindow.performance.timing.redirectEnd is 0 -PASS childWindow.performance.timing.redirectStart is 0 -PASS childWindow.performance.timing.requestStart is 0 -PASS childWindow.performance.timing.responseEnd is 0 -PASS childWindow.performance.timing.responseStart is 0 -PASS childWindow.performance.timing.secureConnectionStart is 0 -PASS childWindow.performance.timing.unloadEventEnd is 0 -PASS childWindow.performance.timing.unloadEventStart is 0 PASS childWindow.personalbar.visible is false PASS childWindow.screen.availHeight is 0 PASS childWindow.screen.availLeft is 0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/delete-into-nested-block-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/delete-into-nested-block-expected.txt index 9489ade..3ed37ac 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/delete-into-nested-block-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/delete-into-nested-block-expected.txt
@@ -24,12 +24,12 @@ }, { "object": "NGPaintFragment", - "rect": [8, 69, 369, 20], + "rect": [8, 69, 370, 20], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [8, 69, 369, 20], + "rect": [8, 69, 370, 20], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-1-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-1-expected.txt index 744f0f61..0b18df3 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-1-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-1-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -324,12 +324,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-10-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-10-expected.txt index 55bd15e..bf6d12d 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-10-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-10-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -314,12 +314,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-2-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-2-expected.txt index 9b5a31b..0206397 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-2-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-2-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 541, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 521, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 581, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 541, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 521, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 341, 406, 19], "reason": "appeared" }, @@ -319,12 +319,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 361, 49, 19], + "rect": [371, 361, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-3-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-3-expected.txt index a1edcbf..735d513 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-3-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-3-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -329,12 +329,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-4-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-4-expected.txt index cdc5209..5d3648f 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-4-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-4-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 480, 406, 19], "reason": "appeared" }, @@ -319,12 +319,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-5-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-5-expected.txt index 38eba30..bec14450 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-5-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-5-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -324,12 +324,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, { @@ -354,7 +354,7 @@ }, { "object": "NGPaintFragment", - "rect": [350, 400, 19, 19], + "rect": [350, 400, 20, 19], "reason": "appeared" } ]
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-6-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-6-expected.txt index eebc523..3eeee63 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-6-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-6-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -319,12 +319,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-7-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-7-expected.txt index 7b9aa98..56c192a 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-7-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-7-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -319,12 +319,12 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-8-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-8-expected.txt index f321493..c69953c 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-8-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-8-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 340, 406, 19], "reason": "appeared" }, @@ -139,6 +139,11 @@ }, { "object": "NGPaintFragment", + "rect": [14, 460, 356, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 480, 355, 19], "reason": "appeared" }, @@ -150,11 +155,6 @@ { "object": "NGPaintFragment", "rect": [14, 460, 355, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 460, 355, 19], "reason": "disappeared" }, { @@ -324,7 +324,7 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-9-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-9-expected.txt index 0c27a1aa..c4e484c6 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-9-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/line-flow-with-floats-9-expected.txt
@@ -29,6 +29,26 @@ }, { "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 540, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "appeared" + }, + { + "object": "NGPaintFragment", + "rect": [14, 520, 407, 19], + "reason": "disappeared" + }, + { + "object": "NGPaintFragment", "rect": [14, 580, 406, 19], "reason": "appeared" }, @@ -49,26 +69,6 @@ }, { "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 540, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "appeared" - }, - { - "object": "NGPaintFragment", - "rect": [14, 520, 406, 19], - "reason": "disappeared" - }, - { - "object": "NGPaintFragment", "rect": [14, 360, 406, 19], "reason": "appeared" }, @@ -314,7 +314,7 @@ }, { "object": "NGPaintFragment", - "rect": [371, 360, 49, 19], + "rect": [371, 360, 50, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-div-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-div-expected.txt index 91f691d..246bd9ac 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-div-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-div-expected.txt
@@ -19,12 +19,12 @@ "paintInvalidations": [ { "object": "NGPaintFragment", - "rect": [8, 8, 742, 19], + "rect": [8, 8, 743, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [8, 8, 742, 19], + "rect": [8, 8, 743, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-iframe-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-iframe-expected.txt index c4efae7..eadd3f8 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-iframe-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/scroll/resize-scrollable-iframe-expected.txt
@@ -19,12 +19,12 @@ "paintInvalidations": [ { "object": "NGPaintFragment", - "rect": [8, 8, 762, 19], + "rect": [8, 8, 763, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [8, 8, 762, 19], + "rect": [8, 8, 763, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/selection/selection-partial-invalidation-between-blocks-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/selection/selection-partial-invalidation-between-blocks-expected.txt new file mode 100644 index 0000000..6ce5deb --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/selection/selection-partial-invalidation-between-blocks-expected.txt
@@ -0,0 +1,44 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "NGPaintFragment", + "rect": [11, 35, 74, 19], + "reason": "selection" + }, + { + "object": "NGPaintFragment", + "rect": [11, 11, 55, 19], + "reason": "selection" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "NGPaintFragment", + "reason": "selection" + }, + { + "object": "NGPaintFragment", + "reason": "selection" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/svg/relative-sized-content-with-resources-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/svg/relative-sized-content-with-resources-expected.txt index b68863a..1be7b6b0 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/svg/relative-sized-content-with-resources-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/svg/relative-sized-content-with-resources-expected.txt
@@ -19,12 +19,12 @@ "paintInvalidations": [ { "object": "NGPaintFragment", - "rect": [8, 16, 749, 19], + "rect": [8, 16, 750, 19], "reason": "appeared" }, { "object": "NGPaintFragment", - "rect": [8, 16, 749, 19], + "rect": [8, 16, 750, 19], "reason": "disappeared" }, {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success-expected.txt index 07cf3e3..74fa663 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success-expected.txt
@@ -1,12 +1,19 @@ Test device orientation -Running: setUp +Running: setUpDeviceOrientation -Running: setOverride +Running: firstOrientationOverride + +Running: setUpOrientationSensor + +Running: secondOrientationOverride Running: clearOverride device-orientation-success.js:22 alpha: 1.1 beta: 2.2 gamma: 3.3 device-orientation-success.js:22 alpha: 20 beta: 30 gamma: 40 +inspected-page.html:1 A reload is required so that the existing AbsoluteOrientationSensor and RelativeOrientationSensor objects on this page use the overridden values that have been provided. Close the inspector and reload again to return to the normal behavior. +device-orientation-success.js:22 alpha: 90 beta: 0 gamma: 0 +device-orientation-success.js:29 quaternion: 0,0,0.7071067811865475,0.7071067811865476 device-orientation-success.js:22 alpha: 1.1 beta: 2.2 gamma: 3.3
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success.js b/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success.js index a183eba2..8ffcc98 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/device-orientation-success.js
@@ -11,7 +11,7 @@ var mockGamma = 3.3; var absolute = true; - function setup() + function setUpDeviceOrientation() { testRunner.setMockDeviceOrientation(true, mockAlpha, true, mockBeta, true, mockGamma, absolute); window.addEventListener("deviceorientation", handler, false); @@ -21,18 +21,35 @@ { console.log("alpha: " + evt.alpha + " beta: " + evt.beta + " gamma: " + evt.gamma); } + + function setUpOrientationSensor() + { + let orientationSensor = new RelativeOrientationSensor(); + orientationSensor.onreading = () => + console.log("quaternion: " + orientationSensor.quaternion); + orientationSensor.start(); + } `); TestRunner.runTestSuite([ - function setUp(next) { - TestRunner.evaluateInPage('setup()', next); + function setUpDeviceOrientation(next) { + TestRunner.evaluateInPage('setUpDeviceOrientation()', next); }, - function setOverride(next) { + function firstOrientationOverride(next) { ConsoleTestRunner.addConsoleSniffer(next); TestRunner.DeviceOrientationAgent.setDeviceOrientationOverride(20, 30, 40); }, + function setUpOrientationSensor(next) { + TestRunner.evaluateInPage('setUpOrientationSensor()', next); + }, + + function secondOrientationOverride(next) { + ConsoleTestRunner.addConsoleSniffer(next); + TestRunner.DeviceOrientationAgent.setDeviceOrientationOverride(90, 0, 0); + }, + async function clearOverride(next) { await TestRunner.DeviceOrientationAgent.clearDeviceOrientationOverride(); ConsoleTestRunner.dumpConsoleMessages();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout-expected.txt index 8b19f49..5b0210ad 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout-expected.txt
@@ -3,11 +3,45 @@ Testing expression 1 + 1 with timeout: 0 error: Execution was terminated -Error occurred. +{ + error : "Execution was terminated" +} Testing expression while (1){} with timeout: 0 error: Execution was terminated -Error occurred. +{ + error : "Execution was terminated" +} -Does the runtime support side effect checks? true +Testing expression 1 + 1 with timeout: 0 +error: Execution was terminated +{ + error : "Execution was terminated" +} + +Does the runtime also support side effect checks? true + +Clearing cached side effect support +Set timer for test function. +Script execution paused. + +Testing expression 1 + 1 with timeout: 0 +error: Execution was terminated +{ + error : "Execution was terminated" +} + +Testing expression while (1){} with timeout: 0 +error: Execution was terminated +{ + error : "Execution was terminated" +} + +Testing expression 1 + 1 with timeout: 0 +error: Execution was terminated +{ + error : "Execution was terminated" +} +Does the runtime also support side effect checks? true +Script execution resumed.
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout.js b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout.js index 60bd3b0..5911675 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/evaluate-timeout.js
@@ -3,35 +3,58 @@ // found in the LICENSE file. (async function() { - await TestRunner.loadModule('sources_test_runner'); - TestRunner.addResult("Test frontend's timeout support.\n"); + await TestRunner.loadModule('sources_test_runner'); + TestRunner.addResult("Test frontend's timeout support.\n"); - const executionContext = UI.context.flavor(SDK.ExecutionContext); - const regularExpression = '1 + 1'; - const infiniteExpression = 'while (1){}'; + const executionContext = UI.context.flavor(SDK.ExecutionContext); + const regularExpression = '1 + 1'; + const infiniteExpression = 'while (1){}'; - await runtimeTestCase(regularExpression); - await runtimeTestCase(infiniteExpression); + await runtimeTestCase(regularExpression); + await runtimeTestCase(infiniteExpression); + await runtimeTestCase(regularExpression); - let supports = executionContext.runtimeModel.hasSideEffectSupport(); - TestRunner.addResult(`\nDoes the runtime support side effect checks? ${supports}`); - TestRunner.completeTest(); + let supports = executionContext.runtimeModel.hasSideEffectSupport(); + TestRunner.addResult(`\nDoes the runtime also support side effect checks? ${supports}`); + TestRunner.addResult(`\nClearing cached side effect support`); + executionContext.runtimeModel._hasSideEffectSupport = null; - async function runtimeTestCase(expression) { - TestRunner.addResult(`\nTesting expression ${expression} with timeout: 0`); - const result = await executionContext.evaluate({expression, timeout: 0}); - printDetails(result); + // Debugger evaluateOnCallFrame test. + await TestRunner.evaluateInPagePromise(` + function testFunction() + { + debugger; } + `); - function printDetails(result) { - if (result.error) { - TestRunner.addResult(`Error occurred.`); - } else if (result.exceptionDetails) { - let exceptionDescription = result.exceptionDetails.exception.description; - TestRunner.addResult(`Exception: ${exceptionDescription.split("\n")[0]}`); - } else if (result.object) { - let objectDescription = result.object.description; - TestRunner.addResult(`Result: ${objectDescription}`); - } - } - })(); + await SourcesTestRunner.startDebuggerTestPromise(); + await SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise(); + + await debuggerTestCase(regularExpression); + await debuggerTestCase(infiniteExpression); + await debuggerTestCase(regularExpression); + + supports = executionContext.runtimeModel.hasSideEffectSupport(); + TestRunner.addResult(`Does the runtime also support side effect checks? ${supports}`); + + SourcesTestRunner.completeDebuggerTest(); + + async function runtimeTestCase(expression) { + TestRunner.addResult(`\nTesting expression ${expression} with timeout: 0`); + const result = await executionContext.evaluate({expression, timeout: 0}); + printDetails(result); + } + + async function debuggerTestCase(expression) { + TestRunner.addResult(`\nTesting expression ${expression} with timeout: 0`); + const result = await executionContext.debuggerModel.selectedCallFrame().evaluate({expression, timeout: 0}); + printDetails(result); + } + + function printDetails(result) { + const customFormatters = {}; + for (let name of ['_runtimeModel', '_runtimeAgent']) + customFormatters[name] = 'formatAsTypeNameOrNull'; + TestRunner.dump(result, customFormatters); + } +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/fetch/script-tests/request.js b/third_party/WebKit/LayoutTests/http/tests/fetch/script-tests/request.js index b212aa2..25904ab 100644 --- a/third_party/WebKit/LayoutTests/http/tests/fetch/script-tests/request.js +++ b/third_party/WebKit/LayoutTests/http/tests/fetch/script-tests/request.js
@@ -53,8 +53,8 @@ 'Default Request.method should be GET'); assert_equals(request.mode, 'cors', 'Default Request.mode should be cors'); - assert_equals(request.credentials, 'omit', - 'Default Request.credentials should be omit'); + assert_equals(request.credentials, 'same-origin', + 'Default Request.credentials should be same-origin'); }); }, "Request default value test"); @@ -171,7 +171,7 @@ assert_equals(request2.url, URL, 'Request.url should match'); assert_equals(request2.method, 'GET', 'Request.method should match'); assert_equals(request2.mode, 'cors', 'Request.mode should match'); - assert_equals(request2.credentials, 'omit', + assert_equals(request2.credentials, 'same-origin', 'Request.credentials should match'); assert_equals(request2.headers.get('X-Fetch-Foo').split(', ')[0], 'foo1', 'Request.headers should match'); @@ -294,10 +294,10 @@ var init1 = {}; if (credentials1 != undefined) { init1['credentials'] = credentials1; } request1 = new Request(URL, init1); - assert_equals(request1.credentials, credentials1 || 'omit', + assert_equals(request1.credentials, credentials1 || 'same-origin', 'Request.credentials should match'); request1 = new Request(request1); - assert_equals(request1.credentials, credentials1 || 'omit', + assert_equals(request1.credentials, credentials1 || 'same-origin', 'Request.credentials should match'); CREDENTIALS.forEach(function(credentials2) { request1 = new Request(URL, init1);
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index b6e591a..9c835ea 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -979,6 +979,23 @@ method constructor method openWindow method respondWith +interface Performance : EventTarget + attribute @@toStringTag + getter onresourcetimingbufferfull + getter timeOrigin + method clearMarks + method clearMeasures + method clearResourceTimings + method constructor + method getEntries + method getEntriesByName + method getEntriesByType + method mark + method measure + method now + method setResourceTimingBufferSize + method toJSON + setter onresourcetimingbufferfull interface PerformanceEntry attribute @@toStringTag getter duration
diff --git a/third_party/WebKit/LayoutTests/virtual/android/frame-size/README.txt b/third_party/WebKit/LayoutTests/virtual/android/frame-size/README.txt new file mode 100644 index 0000000..571634ce --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/android/frame-size/README.txt
@@ -0,0 +1,2 @@ +Tests related to Android Chrome's "resize after layout" of the main viewport +done to allow zooming out to fit content width.
diff --git a/third_party/WebKit/LayoutTests/virtual/android/frame-size/intersection-observer-root-uses-frame-size.html b/third_party/WebKit/LayoutTests/virtual/android/frame-size/intersection-observer-root-uses-frame-size.html new file mode 100644 index 0000000..7b9ca25 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/android/frame-size/intersection-observer-root-uses-frame-size.html
@@ -0,0 +1,110 @@ +<!DOCTYPE html> +<script> + if (window.internals) + window.internals.settings.setViewportMetaEnabled(true); +</script> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> + +<meta name="viewport" content="width=980"> + +<style> + html { + width: 100%; + height: 100%; + background-color: white; + } + body { + width: 100%; + height: 100%; + background-color: lightgrey; + margin: 0; + } + #widediv { + border: 5px solid black; + box-sizing: border-box; + width: 200%; + } + #target { + width: 300px; + height: 300px; + position: absolute; + top: 600%; + background-color: red; + margin-bottom: 600%; + } + p { + margin-top: 0; + } +</style> +<p> + This test verifies that intersection observer on the root is correct in the + presence of Android's quirky viewport mode when an element wider than the + initial contianing block is present. The light grey box represents the + initial contianing block. The wide black box ensures the page is zoomed out + further than the ICB. +</p> + +<p> + To test manually: Scroll down until you see the box. This test passes if, as + soon as the box intersects the viewport, it turns green. +</p> +<div id="widediv"></div> +<div id="target"></div> + +<script> + const box = document.getElementById("target"); + const targetTop = box.getBoundingClientRect().top; + const targetBottom = box.getBoundingClientRect().bottom; + + const viewportHeight = window.innerHeight; + const startIntersectingScrollTop = targetTop - viewportHeight; + const endIntersectingScrollTop = targetBottom; + + function isVisible() { + return window.scrollY >= startIntersectingScrollTop && + window.scrollY < targetBottom; + } + + function scrollToAndWaitFrame(y) { + return () => { + return new Promise((resolve) => { + window.scrollTo(0, y); + requestAnimationFrame(() => { + resolve(); + }); + }); + }; + } + + addEventListener("load", () => { + if (window.internals) + window.internals.setPageScaleFactor(0.5); + + promise_test( t => { + return new Promise((resolve, reject) => { + if (window.testRunner) + assert_equals(visualViewport.scale, 0.5, "Page must start zoomed out"); + + const callback = function(entries) { + if (window.testRunner) { + t.step(() => { + assert_equals(entries.length, 1, "Observing only one element"); + assert_equals(entries[0].isIntersecting, isVisible(), + "Report intersection only if element is on-screen"); + }); + } + box.style.backgroundColor = + entries[0].isIntersecting ? "green" : "red"; + }; + const observer = new IntersectionObserver(callback, {}); + observer.observe(box); + resolve(); + }) + .then(scrollToAndWaitFrame(startIntersectingScrollTop - 1)) + .then(scrollToAndWaitFrame(startIntersectingScrollTop + 1)) + .then(scrollToAndWaitFrame(endIntersectingScrollTop - 1)) + .then(scrollToAndWaitFrame(endIntersectingScrollTop + 1)); + }, "IntersectionObserver uses correct root box"); + }); +</script>
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 093a9d20..9e62dca2 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -645,6 +645,23 @@ getter action getter notification method constructor +interface Performance : EventTarget + attribute @@toStringTag + getter onresourcetimingbufferfull + getter timeOrigin + method clearMarks + method clearMeasures + method clearResourceTimings + method constructor + method getEntries + method getEntriesByName + method getEntriesByType + method mark + method measure + method now + method setResourceTimingBufferSize + method toJSON + setter onresourcetimingbufferfull interface PerformanceEntry attribute @@toStringTag getter duration
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt index 0f155b1..787cdf3 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -620,6 +620,23 @@ [Worker] setter onclose [Worker] setter onerror [Worker] setter onshow +[Worker] interface Performance : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter onresourcetimingbufferfull +[Worker] getter timeOrigin +[Worker] method clearMarks +[Worker] method clearMeasures +[Worker] method clearResourceTimings +[Worker] method constructor +[Worker] method getEntries +[Worker] method getEntriesByName +[Worker] method getEntriesByType +[Worker] method mark +[Worker] method measure +[Worker] method now +[Worker] method setResourceTimingBufferSize +[Worker] method toJSON +[Worker] setter onresourcetimingbufferfull [Worker] interface PerformanceEntry [Worker] attribute @@toStringTag [Worker] getter duration
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt index 86ca4db..653b881 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -615,6 +615,23 @@ [Worker] setter onclose [Worker] setter onerror [Worker] setter onshow +[Worker] interface Performance : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter onresourcetimingbufferfull +[Worker] getter timeOrigin +[Worker] method clearMarks +[Worker] method clearMeasures +[Worker] method clearResourceTimings +[Worker] method constructor +[Worker] method getEntries +[Worker] method getEntriesByName +[Worker] method getEntriesByType +[Worker] method mark +[Worker] method measure +[Worker] method now +[Worker] method setResourceTimingBufferSize +[Worker] method toJSON +[Worker] setter onresourcetimingbufferfull [Worker] interface PerformanceEntry [Worker] attribute @@toStringTag [Worker] getter duration
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 5c02722..2aa5667 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -880,6 +880,23 @@ [Worker] method has [Worker] method keys [Worker] method set +[Worker] interface Performance : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter onresourcetimingbufferfull +[Worker] getter timeOrigin +[Worker] method clearMarks +[Worker] method clearMeasures +[Worker] method clearResourceTimings +[Worker] method constructor +[Worker] method getEntries +[Worker] method getEntriesByName +[Worker] method getEntriesByType +[Worker] method mark +[Worker] method measure +[Worker] method now +[Worker] method setResourceTimingBufferSize +[Worker] method toJSON +[Worker] setter onresourcetimingbufferfull [Worker] interface PerformanceEntry [Worker] attribute @@toStringTag [Worker] getter duration
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt index 19fbff96..0ec198f 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -875,6 +875,23 @@ [Worker] method has [Worker] method keys [Worker] method set +[Worker] interface Performance : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter onresourcetimingbufferfull +[Worker] getter timeOrigin +[Worker] method clearMarks +[Worker] method clearMeasures +[Worker] method clearResourceTimings +[Worker] method constructor +[Worker] method getEntries +[Worker] method getEntriesByName +[Worker] method getEntriesByType +[Worker] method mark +[Worker] method measure +[Worker] method now +[Worker] method setResourceTimingBufferSize +[Worker] method toJSON +[Worker] setter onresourcetimingbufferfull [Worker] interface PerformanceEntry [Worker] attribute @@toStringTag [Worker] getter duration
diff --git a/third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h b/third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h index 3e866b68..0f08739 100644 --- a/third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h +++ b/third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h
@@ -37,7 +37,6 @@ InputEventState event_state) override; void DidHandleInputEventOnMainThread(const WebInputEvent& web_input_event, WebInputEventResult result) override; - base::TimeDelta MostRecentExpectedQueueingTime() override; void DidAnimateForInputOnCompositorThread() override; void SetRendererHidden(bool hidden) override; void SetRendererBackgrounded(bool backgrounded) override; @@ -60,8 +59,6 @@ void SetTopLevelBlameContext( base::trace_event::BlameContext* blame_context) override; void SetRAILModeObserver(RAILModeObserver* observer) override; - bool MainThreadSeemsUnresponsive( - base::TimeDelta main_thread_responsiveness_threshold) override; void SetRendererProcessType(RendererProcessType type) override; WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser( const char* name,
diff --git a/third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h b/third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h index 4c2da30..07b9daf 100644 --- a/third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h +++ b/third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h
@@ -43,7 +43,6 @@ void(const WebInputEvent&, InputEventState)); MOCK_METHOD2(DidHandleInputEventOnMainThread, void(const WebInputEvent&, WebInputEventResult)); - MOCK_METHOD0(MostRecentExpectedQueueingTime, base::TimeDelta()); MOCK_METHOD0(DidAnimateForInputOnCompositorThread, void()); MOCK_METHOD1(SetRendererHidden, void(bool)); MOCK_METHOD1(SetRendererBackgrounded, void(bool)); @@ -67,7 +66,6 @@ MOCK_METHOD1(SetFreezingWhenBackgroundedEnabled, void(bool)); MOCK_METHOD1(SetTopLevelBlameContext, void(base::trace_event::BlameContext*)); MOCK_METHOD1(SetRAILModeObserver, void(RAILModeObserver*)); - MOCK_METHOD1(MainThreadSeemsUnresponsive, bool(base::TimeDelta)); MOCK_METHOD1(SetRendererProcessType, void(RendererProcessType)); MOCK_METHOD2(CreateWebScopedVirtualTimePauser, WebScopedVirtualTimePauser(
diff --git a/third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h b/third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h index 8baa0db..e4593568 100644 --- a/third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h +++ b/third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h
@@ -114,10 +114,6 @@ const WebInputEvent& web_input_event, WebInputEventResult result) = 0; - // Returns the most recently reported expected queueing time, computed over - // the past 1 second window. - virtual base::TimeDelta MostRecentExpectedQueueingTime() = 0; - // Tells the scheduler that the system is displaying an input animation (e.g. // a fling). Called by the compositor (impl) thread. virtual void DidAnimateForInputOnCompositorThread() = 0; @@ -206,12 +202,6 @@ // https://developers.google.com/web/tools/chrome-devtools/profile/evaluate-performance/rail virtual void SetRAILModeObserver(RAILModeObserver* observer) = 0; - // Returns whether or not the main thread appears unresponsive, based on the - // length and frequency of recent main thread tasks. To be called from the - // compositor thread. - virtual bool MainThreadSeemsUnresponsive( - base::TimeDelta main_thread_responsiveness_threshold) = 0; - // Sets the kind of renderer process. Should be called on the main thread // once. virtual void SetRendererProcessType(RendererProcessType type) = 0;
diff --git a/third_party/blink/public/platform/web_feature.mojom b/third_party/blink/public/platform/web_feature.mojom index d5269ec..761a511b 100644 --- a/third_party/blink/public/platform/web_feature.mojom +++ b/third_party/blink/public/platform/web_feature.mojom
@@ -59,8 +59,6 @@ kDeprecatedFlexboxWebContent = 61, kDeprecatedFlexboxChrome = 62, kDeprecatedFlexboxChromeExtension = 63, - kUnprefixedPerformanceTimeline = 65, - kUnprefixedUserTiming = 67, kWindowEvent = 69, kContentSecurityPolicyWithBaseElement = 70, kDocumentClear = 74, @@ -1317,8 +1315,6 @@ kV8DeprecatedStorageQuota_QueryUsageAndQuota_Method = 1810, kV8DeprecatedStorageQuota_RequestQuota_Method = 1811, kV8FileReaderSync_Constructor = 1812, - kUncancelableTouchEventPreventDefaulted = 1813, - kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted = 1814, kV8HTMLVideoElement_Poster_AttributeGetter = 1815, kV8HTMLVideoElement_Poster_AttributeSetter = 1816, kNotificationPermissionRequestedIframe = 1817, @@ -1908,6 +1904,12 @@ kCredentialManagerGetPublicKeyCredential = 2422, kCredentialManagerMakePublicKeyCredentialSuccess = 2423, kCredentialManagerGetPublicKeyCredentialSuccess = 2424, + kShapeOutsideContentBox = 2425, + kShapeOutsidePaddingBox = 2426, + kShapeOutsideBorderBox = 2427, + kShapeOutsideMarginBox = 2428, + kPerformanceTimeline = 2429, + kUserTiming = 2430, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/platform/web_input_event.h b/third_party/blink/public/platform/web_input_event.h index ab201a5..c34d26dc 100644 --- a/third_party/blink/public/platform/web_input_event.h +++ b/third_party/blink/public/platform/web_input_event.h
@@ -280,12 +280,7 @@ // This value represents a state which would have normally blocking // but was forced to be non-blocking during fling; not cancelable. kListenersForcedNonBlockingDueToFling, - // This value represents a state which would have normally blocking but - // was forced to be non-blocking due to the main thread being - // unresponsive. - kListenersForcedNonBlockingDueToMainThreadResponsiveness, - kLastDispatchType = - kListenersForcedNonBlockingDueToMainThreadResponsiveness, + kLastDispatchType = kListenersForcedNonBlockingDueToFling, }; // The rail mode for a wheel event specifies the axis on which scrolling is
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h index 08b6373..cbbfe11 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h
@@ -152,6 +152,8 @@ // resolve. // See: http://crbug.com/663476 if (ScriptForbiddenScope::IsScriptForbidden()) { + // Retain this object until it is actually resolved or rejected. + KeepAliveWhilePending(); timer_.StartOneShot(TimeDelta(), FROM_HERE); return; }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver_test.cc b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver_test.cc index f10fae38..eba306e 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver_test.cc
@@ -13,6 +13,7 @@ #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" +#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "v8/include/v8.h" namespace blink { @@ -259,6 +260,32 @@ EXPECT_FALSE(ScriptPromiseResolverKeepAlive::IsAlive()); } +TEST_F(ScriptPromiseResolverTest, keepAliveWhileScriptForbidden) { + ScriptPromiseResolverKeepAlive::Reset(); + ScriptPromiseResolver* resolver = nullptr; + { + ScriptState::Scope scope(GetScriptState()); + resolver = ScriptPromiseResolverKeepAlive::Create(GetScriptState()); + } + + { + ScriptForbiddenScope forbidden; + resolver->Resolve("hello"); + + ThreadState::Current()->CollectGarbage( + BlinkGC::kNoHeapPointersOnStack, BlinkGC::kAtomicMarking, + BlinkGC::kEagerSweeping, BlinkGC::kForcedGC); + EXPECT_TRUE(ScriptPromiseResolverKeepAlive::IsAlive()); + } + + base::RunLoop().RunUntilIdle(); + + ThreadState::Current()->CollectGarbage( + BlinkGC::kNoHeapPointersOnStack, BlinkGC::kAtomicMarking, + BlinkGC::kEagerSweeping, BlinkGC::kForcedGC); + EXPECT_FALSE(ScriptPromiseResolverKeepAlive::IsAlive()); +} + TEST_F(ScriptPromiseResolverTest, keepAliveUntilStopped) { ScriptPromiseResolverKeepAlive::Reset(); ScriptPromiseResolver* resolver = nullptr;
diff --git a/third_party/blink/renderer/core/core_idl_files.gni b/third_party/blink/renderer/core/core_idl_files.gni index fff8389..b2d84a3 100644 --- a/third_party/blink/renderer/core/core_idl_files.gni +++ b/third_party/blink/renderer/core/core_idl_files.gni
@@ -421,7 +421,6 @@ "timing/performance_server_timing.idl", "timing/performance_timing.idl", "timing/task_attribution_timing.idl", - "timing/worker_performance.idl", "typed_arrays/array_buffer.idl", "typed_arrays/array_buffer_view.idl", "typed_arrays/big_int_64_array.idl",
diff --git a/third_party/blink/renderer/core/events/touch_event.cc b/third_party/blink/renderer/core/events/touch_event.cc index d32dfe4..c4202fa9 100644 --- a/third_party/blink/renderer/core/events/touch_event.cc +++ b/third_party/blink/renderer/core/events/touch_event.cc
@@ -268,35 +268,10 @@ case PassiveMode::kNotPassive: case PassiveMode::kNotPassiveDefault: if (!cancelable()) { - if (view() && view()->IsLocalDOMWindow() && view()->GetFrame()) { - UseCounter::Count( - ToLocalFrame(view()->GetFrame()), - WebFeature::kUncancelableTouchEventPreventDefaulted); - } - - if (native_event_ && - GetWebTouchEvent(*native_event_)->dispatch_type == - WebInputEvent:: - kListenersForcedNonBlockingDueToMainThreadResponsiveness) { - // Non blocking due to main thread responsiveness. - if (view() && view()->IsLocalDOMWindow() && view()->GetFrame()) { - UseCounter::Count( - ToLocalFrame(view()->GetFrame()), - WebFeature:: - kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted); - } - message = - "Ignored attempt to cancel a " + type() + - " event with cancelable=false. This event was forced to be " - "non-cancellable because the page was too busy to handle the " - "event promptly."; - } else { - // Non blocking for any other reason. - message = "Ignored attempt to cancel a " + type() + - " event with cancelable=false, for example " - "because scrolling is in progress and " - "cannot be interrupted."; - } + message = "Ignored attempt to cancel a " + type() + + " event with cancelable=false, for example " + "because scrolling is in progress and " + "cannot be interrupted."; } break; case PassiveMode::kPassiveForcedDocumentLevel:
diff --git a/third_party/blink/renderer/core/events/touch_event_test.cc b/third_party/blink/renderer/core/events/touch_event_test.cc index b040115..e4aec9f8 100644 --- a/third_party/blink/renderer/core/events/touch_event_test.cc +++ b/third_party/blink/renderer/core/events/touch_event_test.cc
@@ -74,49 +74,6 @@ std::unique_ptr<DummyPageHolder> page_holder_; }; -TEST_F(TouchEventTest, PreventDefaultUncancelable) { - TouchEvent* event = EventWithDispatchType(WebInputEvent::kEventNonBlocking); - event->SetHandlingPassive(Event::PassiveMode::kNotPassiveDefault); - - EXPECT_THAT(Messages(), ElementsAre()); - event->preventDefault(); - EXPECT_THAT(Messages(), - ElementsAre("Ignored attempt to cancel a touchstart event with " - "cancelable=false, for example because scrolling is " - "in progress and cannot be interrupted.")); - EXPECT_THAT(MessageSources(), ElementsAre(kInterventionMessageSource)); - - EXPECT_TRUE(UseCounter::IsCounted( - GetDocument(), WebFeature::kUncancelableTouchEventPreventDefaulted)); - EXPECT_FALSE(UseCounter::IsCounted( - GetDocument(), - WebFeature:: - kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted)); -} - -TEST_F(TouchEventTest, - PreventDefaultUncancelableDueToMainThreadResponsiveness) { - TouchEvent* event = EventWithDispatchType( - WebInputEvent::kListenersForcedNonBlockingDueToMainThreadResponsiveness); - event->SetHandlingPassive(Event::PassiveMode::kNotPassiveDefault); - - EXPECT_THAT(Messages(), ElementsAre()); - event->preventDefault(); - EXPECT_THAT(Messages(), - ElementsAre("Ignored attempt to cancel a touchstart event with " - "cancelable=false. This event was forced to be " - "non-cancellable because the page was too busy to " - "handle the event promptly.")); - EXPECT_THAT(MessageSources(), ElementsAre(kInterventionMessageSource)); - - EXPECT_TRUE(UseCounter::IsCounted( - GetDocument(), WebFeature::kUncancelableTouchEventPreventDefaulted)); - EXPECT_TRUE(UseCounter::IsCounted( - GetDocument(), - WebFeature:: - kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted)); -} - TEST_F(TouchEventTest, PreventDefaultPassiveDueToDocumentLevelScrollerIntervention) { TouchEvent* event =
diff --git a/third_party/blink/renderer/core/fetch/request.cc b/third_party/blink/renderer/core/fetch/request.cc index bcfaf67a..a966276 100644 --- a/third_party/blink/renderer/core/fetch/request.cc +++ b/third_party/blink/renderer/core/fetch/request.cc
@@ -273,7 +273,7 @@ if (ParseCredentialsMode(init.Credentials(), &credentials_mode)) { request->SetCredentials(credentials_mode); } else if (!input_request) { - request->SetCredentials(network::mojom::FetchCredentialsMode::kOmit); + request->SetCredentials(network::mojom::FetchCredentialsMode::kSameOrigin); } // "If |init|'s cache member is present, set |request|'s cache mode to it."
diff --git a/third_party/blink/renderer/core/layout/intersection_geometry.cc b/third_party/blink/renderer/core/layout/intersection_geometry.cc index bd16a2f0..6953707 100644 --- a/third_party/blink/renderer/core/layout/intersection_geometry.cc +++ b/third_party/blink/renderer/core/layout/intersection_geometry.cc
@@ -117,17 +117,17 @@ !RuntimeEnabledFeatures::RootLayerScrollingEnabled()) { root_rect_ = LayoutRect(root_->GetFrameView()->VisibleContentRect()); root_->MapToVisualRectInAncestorSpace(nullptr, root_rect_); - } else if (root_->IsLayoutView() && root_->GetDocument().IsInMainFrame() && - root_->GetDocument() - .GetPage() - ->GetSettings() - .GetForceZeroLayoutHeight()) { - // The ForceZeroLayoutHeight quirk setting is used in Android WebView for + } else if (root_->IsLayoutView() && root_->GetDocument().IsInMainFrame()) { + // The main frame is a bit special (even after RLS) as the scrolling + // viewport can differ in size from the LayoutView itself. There's two + // situations this occurs in: + // 1) The ForceZeroLayoutHeight quirk setting is used in Android WebView for // compatibility and sets the initial-containing-block's (a.k.a. // LayoutView) height to 0. Thus, we can't use its size for intersection // testing. Use the FrameView geometry instead. - root_rect_ = LayoutRect( - LayoutPoint(), LayoutSize(root_->GetFrameView()->VisibleContentSize())); + // 2) An element wider than the ICB can cause us to resize the FrameView so + // we can zoom out to fit the entire element width. + root_rect_ = ToLayoutView(root_)->OverflowClipRect(LayoutPoint()); } else if (root_->IsBox() && root_->HasOverflowClip()) { root_rect_ = LayoutRect(ToLayoutBox(root_)->ContentBoxRect()); } else {
diff --git a/third_party/blink/renderer/core/layout/layout_text_control.cc b/third_party/blink/renderer/core/layout/layout_text_control.cc index c56a607..986814a 100644 --- a/third_party/blink/renderer/core/layout/layout_text_control.cc +++ b/third_party/blink/renderer/core/layout/layout_text_control.cc
@@ -70,13 +70,6 @@ GetTextControlElement()->UpdatePlaceholderVisibility(); } -static inline void UpdateUserModifyProperty(TextControlElement& node, - ComputedStyle& style) { - style.SetUserModify(node.IsDisabledOrReadOnly() - ? EUserModify::kReadOnly - : EUserModify::kReadWritePlaintextOnly); -} - int LayoutTextControl::TextBlockLogicalHeight() const { return (LogicalHeight() - BorderAndPaddingLogicalHeight()).ToInt(); } @@ -93,14 +86,6 @@ return unit_width.ToInt(); } -void LayoutTextControl::UpdateFromElement() { - Element* inner_editor = InnerEditorElement(); - if (inner_editor && inner_editor->GetLayoutObject()) - UpdateUserModifyProperty( - *GetTextControlElement(), - inner_editor->GetLayoutObject()->MutableStyleRef()); -} - int LayoutTextControl::ScrollbarThickness() const { // FIXME: We should get the size of the scrollbar from the LayoutTheme // instead.
diff --git a/third_party/blink/renderer/core/layout/layout_text_control.h b/third_party/blink/renderer/core/layout/layout_text_control.h index 0f54985..8f42483 100644 --- a/third_party/blink/renderer/core/layout/layout_text_control.h +++ b/third_party/blink/renderer/core/layout/layout_text_control.h
@@ -67,7 +67,6 @@ LayoutUnit line_height, LayoutUnit non_content_height) const = 0; - void UpdateFromElement() override; void ComputeLogicalHeight(LayoutUnit logical_height, LayoutUnit logical_top, LogicalExtentComputedValues&) const override;
diff --git a/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc b/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc index d7737d02..1997812 100644 --- a/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc +++ b/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/core/layout/shapes/shape_outside_info.h" #include <memory> +#include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.h" #include "third_party/blink/renderer/core/layout/floating_objects.h" @@ -49,10 +50,12 @@ void ShapeOutsideInfo::SetReferenceBoxLogicalSize( LayoutSize new_reference_box_logical_size) { + const Document& document = layout_box_.GetDocument(); bool is_horizontal_writing_mode = layout_box_.ContainingBlock()->Style()->IsHorizontalWritingMode(); switch (ReferenceBox(*layout_box_.Style()->ShapeOutside())) { case CSSBoxType::kMargin: + UseCounter::Count(document, WebFeature::kShapeOutsideMarginBox); if (is_horizontal_writing_mode) new_reference_box_logical_size.Expand(layout_box_.MarginWidth(), layout_box_.MarginHeight()); @@ -61,8 +64,10 @@ layout_box_.MarginWidth()); break; case CSSBoxType::kBorder: + UseCounter::Count(document, WebFeature::kShapeOutsideBorderBox); break; case CSSBoxType::kPadding: + UseCounter::Count(document, WebFeature::kShapeOutsidePaddingBox); if (is_horizontal_writing_mode) new_reference_box_logical_size.Shrink(layout_box_.BorderWidth(), layout_box_.BorderHeight()); @@ -71,6 +76,7 @@ layout_box_.BorderWidth()); break; case CSSBoxType::kContent: + UseCounter::Count(document, WebFeature::kShapeOutsideContentBox); if (is_horizontal_writing_mode) new_reference_box_logical_size.Shrink( layout_box_.BorderAndPaddingWidth(),
diff --git a/third_party/blink/renderer/core/timing/dom_window_performance.cc b/third_party/blink/renderer/core/timing/dom_window_performance.cc index 629e4689e..4f48d19 100644 --- a/third_party/blink/renderer/core/timing/dom_window_performance.cc +++ b/third_party/blink/renderer/core/timing/dom_window_performance.cc
@@ -6,7 +6,6 @@ #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" -#include "third_party/blink/renderer/core/timing/window_performance.h" namespace blink {
diff --git a/third_party/blink/renderer/core/timing/dom_window_performance.h b/third_party/blink/renderer/core/timing/dom_window_performance.h index 8bee7c47..18648dd1 100644 --- a/third_party/blink/renderer/core/timing/dom_window_performance.h +++ b/third_party/blink/renderer/core/timing/dom_window_performance.h
@@ -7,13 +7,13 @@ #include "base/macros.h" #include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/supplementable.h" namespace blink { class LocalDOMWindow; -class WindowPerformance; class CORE_EXPORT DOMWindowPerformance final : public GarbageCollected<DOMWindowPerformance>,
diff --git a/third_party/blink/renderer/core/timing/performance.cc b/third_party/blink/renderer/core/timing/performance.cc index 8131003d..10be6ccd 100644 --- a/third_party/blink/renderer/core/timing/performance.cc +++ b/third_party/blink/renderer/core/timing/performance.cc
@@ -111,6 +111,14 @@ return nullptr; } +PerformanceNavigation* Performance::navigation() const { + return nullptr; +} + +MemoryInfo* Performance::memory() const { + return nullptr; +} + DOMHighResTimeStamp Performance::timeOrigin() const { DCHECK(!time_origin_.is_null()); return GetUnixAtZeroMonotonic() +
diff --git a/third_party/blink/renderer/core/timing/performance.h b/third_party/blink/renderer/core/timing/performance.h index 3166b04..52a5316 100644 --- a/third_party/blink/renderer/core/timing/performance.h +++ b/third_party/blink/renderer/core/timing/performance.h
@@ -52,6 +52,8 @@ class DoubleOrPerformanceMarkOptions; class ExceptionState; +class MemoryInfo; +class PerformanceNavigation; class PerformanceObserver; class PerformanceTiming; class ResourceResponse; @@ -66,12 +68,17 @@ using PerformanceEntryVector = HeapVector<Member<PerformanceEntry>>; class CORE_EXPORT Performance : public EventTargetWithInlineData { + DEFINE_WRAPPERTYPEINFO(); + public: ~Performance() override; const AtomicString& InterfaceName() const override; + // Overriden by WindowPerformance but not by WorkerPerformance. virtual PerformanceTiming* timing() const; + virtual PerformanceNavigation* navigation() const; + virtual MemoryInfo* memory() const; virtual void UpdateLongTaskInstrumentation() {} @@ -228,7 +235,7 @@ Performance(TimeTicks time_origin, scoped_refptr<base::SingleThreadTaskRunner>); - // Expect Performance to override this method, + // Expect WindowPerformance to override this method, // WorkerPerformance doesn't have to override this. virtual PerformanceNavigationTiming* CreateNavigationTimingInstance() { return nullptr;
diff --git a/third_party/blink/renderer/core/timing/performance.idl b/third_party/blink/renderer/core/timing/performance.idl index 321813f..9198fbc 100644 --- a/third_party/blink/renderer/core/timing/performance.idl +++ b/third_party/blink/renderer/core/timing/performance.idl
@@ -31,11 +31,9 @@ // https://w3c.github.io/hr-time/#the-performance-interface -// TODO(foolip): This interface should be [Exposed=(Window,Worker)]. Doing that -// would allow the WorkerPerformance interface to be merged into this. // TODO(foolip): None of the optional DOMString arguments in this interface // should have a default value. -[ImplementedAs=WindowPerformance] +[Exposed=(Window,Worker)] interface Performance : EventTarget { [Affects=Nothing] DOMHighResTimeStamp now(); readonly attribute DOMHighResTimeStamp timeOrigin; @@ -43,9 +41,9 @@ // Performance Timeline // https://w3c.github.io/performance-timeline/#the-performance-interface // TODO(foolip): getEntries() should take an optional FilterOptions argument. - [MeasureAs=UnprefixedPerformanceTimeline] PerformanceEntryList getEntries(); - [MeasureAs=UnprefixedPerformanceTimeline] PerformanceEntryList getEntriesByType(DOMString entryType); - [MeasureAs=UnprefixedPerformanceTimeline] PerformanceEntryList getEntriesByName(DOMString name, optional DOMString entryType = null); + [MeasureAs=PerformanceTimeline] PerformanceEntryList getEntries(); + [MeasureAs=PerformanceTimeline] PerformanceEntryList getEntriesByType(DOMString entryType); + [MeasureAs=PerformanceTimeline] PerformanceEntryList getEntriesByName(DOMString name, optional DOMString entryType = null); // Resource Timing // https://w3c.github.io/resource-timing/#extensions-performance-interface @@ -55,21 +53,21 @@ // Navigation Timing // https://w3c.github.io/navigation-timing/#extensions-to-the-performance-interface - [SameObject, Measure] readonly attribute PerformanceTiming timing; - [SameObject, Measure] readonly attribute PerformanceNavigation navigation; + [Exposed=Window, SameObject, Measure] readonly attribute PerformanceTiming timing; + [Exposed=Window, SameObject, Measure] readonly attribute PerformanceNavigation navigation; // User Timing // https://w3c.github.io/user-timing/#extensions-performance-interface - [MeasureAs=UnprefixedUserTiming, CallWith=ScriptState, RaisesException] void mark(DOMString markName); - [MeasureAs=UnprefixedUserTiming, CallWith=ScriptState, RuntimeEnabled=CustomUserTiming, RaisesException] void mark(DOMString markName, (DOMHighResTimeStamp or PerformanceMarkOptions) startTimeOrPerformanceMarkOptions); - [MeasureAs=UnprefixedUserTiming] void clearMarks(optional DOMString markName = null); + [MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] void mark(DOMString markName); + [MeasureAs=UserTiming, CallWith=ScriptState, RuntimeEnabled=CustomUserTiming, RaisesException] void mark(DOMString markName, (DOMHighResTimeStamp or PerformanceMarkOptions) startTimeOrPerformanceMarkOptions); + [MeasureAs=UserTiming] void clearMarks(optional DOMString markName = null); - [MeasureAs=UnprefixedUserTiming, RaisesException] void measure(DOMString measureName, optional DOMString startMark = null, optional DOMString endMark = null); - [MeasureAs=UnprefixedUserTiming] void clearMeasures(optional DOMString measureName = null); + [MeasureAs=UserTiming, RaisesException] void measure(DOMString measureName, optional DOMString startMark = null, optional DOMString endMark = null); + [MeasureAs=UserTiming] void clearMeasures(optional DOMString measureName = null); // TODO(foolip): There is no spec for the Memory Info API, see blink-dev: // https://groups.google.com/a/chromium.org/d/msg/blink-dev/g5YRCGpC9vs/b4OJz71NmPwJ - [Measure] readonly attribute MemoryInfo memory; + [Exposed=Window, Measure] readonly attribute MemoryInfo memory; serializer = {attribute}; };
diff --git a/third_party/blink/renderer/core/timing/window_performance.cc b/third_party/blink/renderer/core/timing/window_performance.cc index 6e9b9fa..c2ba528 100644 --- a/third_party/blink/renderer/core/timing/window_performance.cc +++ b/third_party/blink/renderer/core/timing/window_performance.cc
@@ -120,8 +120,11 @@ return GetFrame()->GetDocument(); } -MemoryInfo* WindowPerformance::memory() { - return MemoryInfo::Create(); +PerformanceTiming* WindowPerformance::timing() const { + if (!timing_) + timing_ = PerformanceTiming::Create(GetFrame()); + + return timing_.Get(); } PerformanceNavigation* WindowPerformance::navigation() const { @@ -131,11 +134,8 @@ return navigation_.Get(); } -PerformanceTiming* WindowPerformance::timing() const { - if (!timing_) - timing_ = PerformanceTiming::Create(GetFrame()); - - return timing_.Get(); +MemoryInfo* WindowPerformance::memory() const { + return MemoryInfo::Create(); } PerformanceNavigationTiming*
diff --git a/third_party/blink/renderer/core/timing/window_performance.h b/third_party/blink/renderer/core/timing/window_performance.h index 21c8d9d..b7f926a 100644 --- a/third_party/blink/renderer/core/timing/window_performance.h +++ b/third_party/blink/renderer/core/timing/window_performance.h
@@ -45,7 +45,6 @@ class CORE_EXPORT WindowPerformance final : public Performance, public PerformanceMonitor::Client, public DOMWindowClient { - DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(WindowPerformance); friend class WindowPerformanceTest; @@ -57,9 +56,10 @@ ExecutionContext* GetExecutionContext() const override; - MemoryInfo* memory(); - PerformanceNavigation* navigation() const; PerformanceTiming* timing() const override; + PerformanceNavigation* navigation() const override; + + MemoryInfo* memory() const override; void UpdateLongTaskInstrumentation() override;
diff --git a/third_party/blink/renderer/core/timing/worker_performance.h b/third_party/blink/renderer/core/timing/worker_performance.h index 6916747..04d1e1ab 100644 --- a/third_party/blink/renderer/core/timing/worker_performance.h +++ b/third_party/blink/renderer/core/timing/worker_performance.h
@@ -42,8 +42,6 @@ class WorkerGlobalScope; class WorkerPerformance final : public Performance { - DEFINE_WRAPPERTYPEINFO(); - public: static WorkerPerformance* Create(WorkerGlobalScope* context) { return new WorkerPerformance(context);
diff --git a/third_party/blink/renderer/core/timing/worker_performance.idl b/third_party/blink/renderer/core/timing/worker_performance.idl deleted file mode 100644 index 4d9ffdab..0000000 --- a/third_party/blink/renderer/core/timing/worker_performance.idl +++ /dev/null
@@ -1,65 +0,0 @@ -/* - * Copyright (C) 2013 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// https://w3c.github.io/hr-time/#the-performance-interface - -// TODO(foolip): This interface should be merged into Performance. -// TODO(foolip): None of the optional DOMString arguments in this interface -// should have a default value. -[ - NoInterfaceObject -] interface WorkerPerformance : EventTarget { - DOMHighResTimeStamp now(); - readonly attribute DOMHighResTimeStamp timeOrigin; - - // Performance Timeline - // https://w3c.github.io/performance-timeline/#the-performance-interface - // TODO(foolip): getEntries() should take an optional FilterOptions argument. - PerformanceEntryList getEntries(); - PerformanceEntryList getEntriesByType(DOMString entryType); - PerformanceEntryList getEntriesByName(DOMString name, optional DOMString entryType = null); - - // Resource Timing - // https://w3c.github.io/resource-timing/#extensions-performance-interface - void clearResourceTimings(); - void setResourceTimingBufferSize(unsigned long maxSize); - attribute EventHandler onresourcetimingbufferfull; - - // User Timing - // https://w3c.github.io/user-timing/#extensions-performance-interface - [CallWith=ScriptState, RaisesException] void mark(DOMString markName); - [CallWith=ScriptState, RuntimeEnabled=CustomUserTiming, RaisesException] void mark(DOMString markName, (DOMHighResTimeStamp or PerformanceMarkOptions) startTimeOrPerformanceMarkOptions); - void clearMarks(optional DOMString markName = null); - - [RaisesException] void measure(DOMString measureName, optional DOMString startMark = null, optional DOMString endMark = null); - void clearMeasures(optional DOMString measureName = null); - - serializer = {attribute}; -};
diff --git a/third_party/blink/renderer/devtools/front_end/browser_debugger/module.json b/third_party/blink/renderer/devtools/front_end/browser_debugger/module.json index 10f1b3d..5593cb1d 100644 --- a/third_party/blink/renderer/devtools/front_end/browser_debugger/module.json +++ b/third_party/blink/renderer/devtools/front_end/browser_debugger/module.json
@@ -83,6 +83,34 @@ "order": 2, "persistence": "permanent", "className": "Sources.NetworkNavigatorView" + }, + { + "type": "view", + "location": "navigator-view", + "id": "navigator-overrides", + "title": "Overrides", + "order": 4, + "persistence": "permanent", + "className": "Sources.OverridesNavigatorView" + }, + { + "type": "view", + "location": "navigator-view", + "id": "navigator-contentScripts", + "title": "Content scripts", + "order": 5, + "persistence": "permanent", + "className": "Sources.ContentScriptsNavigatorView" + }, + { + "type": "@Sources.NavigatorView", + "viewId": "navigator-overrides", + "className": "Sources.OverridesNavigatorView" + }, + { + "type": "@Sources.NavigatorView", + "viewId": "navigator-contentScripts", + "className": "Sources.ContentScriptsNavigatorView" } ], "dependencies": [
diff --git a/third_party/blink/renderer/devtools/front_end/main/Main.js b/third_party/blink/renderer/devtools/front_end/main/Main.js index 7b87441..c25eb1d 100644 --- a/third_party/blink/renderer/devtools/front_end/main/Main.js +++ b/third_party/blink/renderer/devtools/front_end/main/Main.js
@@ -118,6 +118,7 @@ Runtime.experiments.register('sourceDiff', 'Source diff'); Runtime.experiments.register( 'stepIntoAsync', 'Introduce separate step action, stepInto becomes powerful enough to go inside async call'); + Runtime.experiments.register('splitInDrawer', 'Split in drawer', true); Runtime.experiments.register('terminalInDrawer', 'Terminal in drawer', true); // Timeline
diff --git a/third_party/blink/renderer/devtools/front_end/main/module.json b/third_party/blink/renderer/devtools/front_end/main/module.json index 7d58386fa..3c439d8 100644 --- a/third_party/blink/renderer/devtools/front_end/main/module.json +++ b/third_party/blink/renderer/devtools/front_end/main/module.json
@@ -285,6 +285,12 @@ }, { "type": "@UI.ViewLocationResolver", + "name": "drawer-sidebar", + "category": "Drawer sidebar", + "className": "UI.InspectorView" + }, + { + "type": "@UI.ViewLocationResolver", "name": "panel", "category": "Panel", "className": "UI.InspectorView"
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js b/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js index dc3d22d..1a76663 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js
@@ -1293,13 +1293,12 @@ */ async evaluate(options) { const runtimeModel = this.debuggerModel.runtimeModel(); - if (options.throwOnSideEffect && + // Assume backends either support both throwOnSideEffect and timeout options or neither. + const needsTerminationOptions = !!options.throwOnSideEffect || options.timeout !== undefined; + if (needsTerminationOptions && (runtimeModel.hasSideEffectSupport() === false || (runtimeModel.hasSideEffectSupport() === null && !await runtimeModel.checkSideEffectSupport()))) return {error: 'Side-effect checks not supported by backend.'}; - // TODO(luoe): remove this check when evaluateOnCallFrame supports timeout. - if (typeof options.timeout !== 'undefined') - return {error: 'Evaluation with timeout on pause not supported by backend.'}; const response = await this.debuggerModel._agent.invoke_evaluateOnCallFrame({ callFrameId: this.id, @@ -1309,7 +1308,8 @@ silent: options.silent, returnByValue: options.returnByValue, generatePreview: options.generatePreview, - throwOnSideEffect: options.throwOnSideEffect + throwOnSideEffect: options.throwOnSideEffect, + timeout: options.timeout }); const error = response[Protocol.Error]; if (error) {
diff --git a/third_party/blink/renderer/devtools/front_end/sources/module.json b/third_party/blink/renderer/devtools/front_end/sources/module.json index b8cc255..aed8aea 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/module.json +++ b/third_party/blink/renderer/devtools/front_end/sources/module.json
@@ -291,24 +291,6 @@ { "type": "view", "location": "navigator-view", - "id": "navigator-overrides", - "title": "Overrides", - "order": 4, - "persistence": "permanent", - "className": "Sources.OverridesNavigatorView" - }, - { - "type": "view", - "location": "navigator-view", - "id": "navigator-contentScripts", - "title": "Content scripts", - "order": 5, - "persistence": "permanent", - "className": "Sources.ContentScriptsNavigatorView" - }, - { - "type": "view", - "location": "navigator-view", "id": "navigator-snippets", "title": "Snippets", "order": 6, @@ -336,16 +318,6 @@ }, { "type": "@Sources.NavigatorView", - "viewId": "navigator-overrides", - "className": "Sources.OverridesNavigatorView" - }, - { - "type": "@Sources.NavigatorView", - "viewId": "navigator-contentScripts", - "className": "Sources.ContentScriptsNavigatorView" - }, - { - "type": "@Sources.NavigatorView", "viewId": "navigator-snippets", "className": "Sources.SnippetsNavigatorView" },
diff --git a/third_party/blink/renderer/devtools/front_end/terminal/module.json b/third_party/blink/renderer/devtools/front_end/terminal/module.json index c00e963..6802e2b4 100644 --- a/third_party/blink/renderer/devtools/front_end/terminal/module.json +++ b/third_party/blink/renderer/devtools/front_end/terminal/module.json
@@ -2,11 +2,10 @@ "extensions": [ { "type": "view", - "location": "drawer-view", + "location": "drawer-sidebar", "id": "drawer.xterm", "title": "Terminal", "order": 10, - "persistence": "closeable", "factoryName": "Terminal.TerminalWidget" } ],
diff --git a/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js b/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js index 9a9202ea..ac09596 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js +++ b/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js
@@ -44,6 +44,16 @@ this._drawerSplitWidget.enableShowModeSaving(); this._drawerSplitWidget.show(this.element); + if (Runtime.experiments.isEnabled('splitInDrawer')) { + this._innerDrawerSplitWidget = new UI.SplitWidget(true, true, 'Inspector.drawerSidebarSplitViewState', 200, 200); + this._drawerSplitWidget.setSidebarWidget(this._innerDrawerSplitWidget); + this._drawerSidebarTabbedLocation = + UI.viewManager.createTabbedLocation(this._showDrawer.bind(this, false), 'drawer-sidebar', true, true); + this._drawerSidebarTabbedPane = this._drawerSidebarTabbedLocation.tabbedPane(); + this._drawerSidebarTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this._drawerTabSelected, this); + this._innerDrawerSplitWidget.setSidebarWidget(this._drawerSidebarTabbedPane); + } + // Create drawer tabbed pane. this._drawerTabbedLocation = UI.viewManager.createTabbedLocation(this._showDrawer.bind(this, false), 'drawer-view', true, true); @@ -52,11 +62,18 @@ this._drawerTabbedPane.setMinimumSize(0, 27); const closeDrawerButton = new UI.ToolbarButton(Common.UIString('Close drawer'), 'largeicon-delete'); closeDrawerButton.addEventListener(UI.ToolbarButton.Events.Click, this._closeDrawer, this); - this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton); this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement()); - this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane); this._drawerTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this._drawerTabSelected, this); + if (this._drawerSidebarTabbedPane) { + this._innerDrawerSplitWidget.setMainWidget(this._drawerTabbedPane); + this._drawerSidebarTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton); + this._drawerSplitWidget.installResizer(this._drawerSidebarTabbedPane.headerElement()); + } else { + this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane); + this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton); + } + // Create main area tabbed pane. this._tabbedLocation = UI.viewManager.createTabbedLocation( InspectorFrontendHost.bringToFront.bind(InspectorFrontendHost), 'panel', true, true, @@ -115,6 +132,8 @@ return this._drawerTabbedLocation; if (locationName === 'panel') return this._tabbedLocation; + if (locationName === 'drawer-sidebar') + return this._drawerSidebarTabbedLocation; return null; }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js b/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js index 2765082..f0b55ed6 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js
@@ -747,7 +747,7 @@ */ hideDefaultResizer(noSplitter) { this.uninstallResizer(this._resizerElement); - this._sidebarElement.classList.toggle('no-default-splitter', noSplitter); + this._sidebarElement.classList.toggle('no-default-splitter', !!noSplitter); } /**
diff --git a/third_party/blink/renderer/modules/device_orientation/DEPS b/third_party/blink/renderer/modules/device_orientation/DEPS index 2862509..cc8db4f8 100644 --- a/third_party/blink/renderer/modules/device_orientation/DEPS +++ b/third_party/blink/renderer/modules/device_orientation/DEPS
@@ -9,4 +9,5 @@ "+third_party/blink/renderer/modules/event_modules.h", "+third_party/blink/renderer/modules/event_target_modules.h", "+third_party/blink/renderer/modules/modules_export.h", + "+third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h", ]
diff --git a/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc b/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc index bd25608..c9144c4 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc +++ b/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc
@@ -8,6 +8,7 @@ #include "third_party/blink/renderer/core/inspector/inspected_frames.h" #include "third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h" #include "third_party/blink/renderer/modules/device_orientation/device_orientation_data.h" +#include "third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" namespace blink { @@ -25,10 +26,12 @@ DeviceOrientationInspectorAgent::DeviceOrientationInspectorAgent( InspectedFrames* inspected_frames) - : inspected_frames_(inspected_frames) {} + : inspected_frames_(inspected_frames), + sensor_agent_(new SensorInspectorAgent(inspected_frames->Root())) {} void DeviceOrientationInspectorAgent::Trace(blink::Visitor* visitor) { visitor->Trace(inspected_frames_); + visitor->Trace(sensor_agent_); InspectorBaseAgent::Trace(visitor); } @@ -50,6 +53,7 @@ Controller()->SetOverride( DeviceOrientationData::Create(alpha, beta, gamma, false)); } + sensor_agent_->SetOrientationSensorOverride(alpha, beta, gamma); return Response::OK(); } @@ -58,6 +62,7 @@ false); if (Controller()) Controller()->ClearOverride(); + sensor_agent_->Disable(); return Response::OK(); } @@ -66,6 +71,7 @@ false); if (Controller()) Controller()->ClearOverride(); + sensor_agent_->Disable(); return Response::OK(); } @@ -82,6 +88,7 @@ state_->getDouble(DeviceOrientationInspectorAgentState::kGamma, &gamma); Controller()->SetOverride( DeviceOrientationData::Create(alpha, beta, gamma, false)); + sensor_agent_->SetOrientationSensorOverride(alpha, beta, gamma); } }
diff --git a/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.h b/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.h index 0f62d3e..67cdd984 100644 --- a/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.h +++ b/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.h
@@ -14,6 +14,7 @@ class DeviceOrientationController; class InspectedFrames; +class SensorInspectorAgent; class MODULES_EXPORT DeviceOrientationInspectorAgent final : public InspectorBaseAgent<protocol::DeviceOrientation::Metainfo> { @@ -36,6 +37,7 @@ DeviceOrientationController* Controller(); Member<InspectedFrames> inspected_frames_; + Member<SensorInspectorAgent> sensor_agent_; DISALLOW_COPY_AND_ASSIGN(DeviceOrientationInspectorAgent); };
diff --git a/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.idl b/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.idl index 1c6bc5b..c8e54ea9 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.idl
@@ -4,7 +4,7 @@ [ ImplementedAs=HTMLMediaElementEncryptedMedia ] partial interface HTMLMediaElement { - readonly attribute MediaKeys mediaKeys; + [SecureContext] readonly attribute MediaKeys mediaKeys; [SecureContext, CallWith=ScriptState] Promise setMediaKeys(MediaKeys? mediaKeys); attribute EventHandler onencrypted; attribute EventHandler onwaitingforkey;
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.idl b/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.idl index 1db2035e5..91bb823 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.idl
@@ -33,7 +33,8 @@ }; [ - Constructor(DOMString type, MediaKeyMessageEventInit eventInitDict) + Constructor(DOMString type, MediaKeyMessageEventInit eventInitDict), + SecureContext ] interface MediaKeyMessageEvent : Event { readonly attribute MediaKeyMessageType messageType; readonly attribute ArrayBuffer message;
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_key_session.idl b/third_party/blink/renderer/modules/encryptedmedia/media_key_session.idl index 6885c79..b9a672b 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_key_session.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/media_key_session.idl
@@ -24,7 +24,8 @@ */ [ - ActiveScriptWrappable + ActiveScriptWrappable, + SecureContext ] interface MediaKeySession : EventTarget { // session properties readonly attribute DOMString sessionId;
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.idl b/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.idl index f6f363f..a62d37a 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.idl
@@ -14,7 +14,9 @@ "internal-error" }; -interface MediaKeyStatusMap { +[ + SecureContext +] interface MediaKeyStatusMap { iterable <BufferSource, MediaKeyStatus>; readonly attribute unsigned long size; boolean has(BufferSource keyId);
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.idl b/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.idl index 44292eb..cf65a08d 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.idl
@@ -4,7 +4,9 @@ // https://w3c.github.io/encrypted-media/#mediakeysystemaccess-interface -interface MediaKeySystemAccess { +[ + SecureContext +] interface MediaKeySystemAccess { readonly attribute DOMString keySystem; MediaKeySystemConfiguration getConfiguration(); [CallWith=ScriptState] Promise<MediaKeys> createMediaKeys();
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.idl b/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.idl index e419aa4..09e21a7d 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.idl +++ b/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.idl
@@ -6,7 +6,8 @@ [ ImplementedAs=MediaKeysGetStatusForPolicy, - RuntimeEnabled=EncryptedMediaHdcpPolicyCheck + RuntimeEnabled=EncryptedMediaHdcpPolicyCheck, + SecureContext ] partial interface MediaKeys { [Measure, CallWith=ScriptState] Promise<MediaKeyStatus> getStatusForPolicy(MediaKeysPolicy policy); };
diff --git a/third_party/blink/renderer/modules/sensor/BUILD.gn b/third_party/blink/renderer/modules/sensor/BUILD.gn index f6fa59e..c9991956 100644 --- a/third_party/blink/renderer/modules/sensor/BUILD.gn +++ b/third_party/blink/renderer/modules/sensor/BUILD.gn
@@ -26,10 +26,16 @@ "sensor.h", "sensor_error_event.cc", "sensor_error_event.h", + "sensor_inspector_agent.cc", + "sensor_inspector_agent.h", "sensor_provider_proxy.cc", "sensor_provider_proxy.h", "sensor_proxy.cc", "sensor_proxy.h", + "sensor_proxy_impl.cc", + "sensor_proxy_impl.h", + "sensor_proxy_inspector_impl.cc", + "sensor_proxy_inspector_impl.h", "sensor_reading_remapper.cc", "sensor_reading_remapper.h", ]
diff --git a/third_party/blink/renderer/modules/sensor/sensor.cc b/third_party/blink/renderer/modules/sensor/sensor.cc index 5b8f224e..6d481fd 100644 --- a/third_party/blink/renderer/modules/sensor/sensor.cc +++ b/third_party/blink/renderer/modules/sensor/sensor.cc
@@ -154,9 +154,9 @@ auto Sensor::CreateSensorConfig() -> SensorConfigurationPtr { auto result = SensorConfiguration::New(); - double default_frequency = sensor_proxy_->DefaultConfig()->frequency; - double minimum_frequency = sensor_proxy_->FrequencyLimits().first; - double maximum_frequency = sensor_proxy_->FrequencyLimits().second; + double default_frequency = sensor_proxy_->GetDefaultFrequency(); + double minimum_frequency = sensor_proxy_->GetFrequencyLimits().first; + double maximum_frequency = sensor_proxy_->GetFrequencyLimits().second; if (frequency_ == 0.0) // i.e. was never set. frequency_ = default_frequency; @@ -187,6 +187,9 @@ void Sensor::ContextDestroyed(ExecutionContext*) { if (!IsIdleOrErrored()) Deactivate(); + + if (sensor_proxy_) + sensor_proxy_->Detach(); } void Sensor::OnSensorInitialized() { @@ -204,7 +207,6 @@ // reading is up-to-date. if (pending_reading_notification_.IsActive()) return; - double elapsedTime = sensor_proxy_->GetReading().timestamp() - last_reported_timestamp_; DCHECK_GT(elapsedTime, 0.0); @@ -299,9 +301,9 @@ configuration_ = CreateSensorConfig(); DCHECK(configuration_); DCHECK_GE(configuration_->frequency, - sensor_proxy_->FrequencyLimits().first); + sensor_proxy_->GetFrequencyLimits().first); DCHECK_LE(configuration_->frequency, - sensor_proxy_->FrequencyLimits().second); + sensor_proxy_->GetFrequencyLimits().second); } DCHECK(sensor_proxy_);
diff --git a/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.cc b/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.cc new file mode 100644 index 0000000..1aff8de0 --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.cc
@@ -0,0 +1,95 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h" + +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/inspector/console_message.h" +#include "third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h" +#include "third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h" + +namespace blink { + +SensorInspectorAgent::SensorInspectorAgent(LocalFrame* frame) + : provider_(SensorProviderProxy::From(frame)) {} + +void SensorInspectorAgent::Trace(blink::Visitor* visitor) { + visitor->Trace(provider_); +} + +namespace { + +void FillQuaternion(double alpha, + double beta, + double gamma, + device::SensorReadingQuat* reading) { + double half_x_angle = deg2rad(beta) * 0.5; + double half_y_angle = deg2rad(gamma) * 0.5; + double half_z_angle = deg2rad(alpha) * 0.5; + + double cos_z = cos(half_z_angle); + double sin_z = sin(half_z_angle); + double cos_y = cos(half_y_angle); + double sin_y = sin(half_y_angle); + double cos_x = cos(half_x_angle); + double sin_x = sin(half_x_angle); + + reading->x = sin_x * cos_y * cos_z - cos_x * sin_y * sin_z; + reading->y = cos_x * sin_y * cos_z + sin_x * cos_y * sin_z; + reading->z = cos_x * cos_y * sin_z + sin_x * sin_y * cos_z; + reading->w = cos_x * cos_y * cos_z - sin_x * sin_y * sin_z; +} + +void PopulateOrientationReading(double alpha, + double beta, + double gamma, + device::SensorReading* reading) { + FillQuaternion(alpha, beta, gamma, &reading->orientation_quat); + reading->orientation_quat.timestamp = WTF::CurrentTimeTicksInSeconds(); +} + +const char kInspectorConsoleMessage[] = + "A reload is required so that the existing AbsoluteOrientationSensor and " + "RelativeOrientationSensor objects on this page use the overridden " + "values that have been provided. Close the inspector and reload again " + "to return to the normal behavior."; + +} // namespace + +void SensorInspectorAgent::SetOrientationSensorOverride(double alpha, + double beta, + double gamma) { + if (!provider_->inspector_mode()) { + Document* document = provider_->GetSupplementable()->GetDocument(); + if (document) { + ConsoleMessage* console_message = ConsoleMessage::Create( + kJSMessageSource, kInfoMessageLevel, kInspectorConsoleMessage); + document->AddConsoleMessage(console_message); + } + provider_->set_inspector_mode(true); + } + + using device::mojom::blink::SensorType; + SensorProxy* absolute = + provider_->GetSensorProxy(SensorType::ABSOLUTE_ORIENTATION_QUATERNION); + SensorProxy* relative = + provider_->GetSensorProxy(SensorType::RELATIVE_ORIENTATION_QUATERNION); + + if (!absolute && !relative) + return; + + device::SensorReading reading; + PopulateOrientationReading(alpha, beta, gamma, &reading); + + if (absolute) + absolute->SetReadingForInspector(reading); + if (relative) + relative->SetReadingForInspector(reading); +} + +void SensorInspectorAgent::Disable() { + provider_->set_inspector_mode(false); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h b/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h new file mode 100644 index 0000000..42e3bead --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_inspector_agent.h
@@ -0,0 +1,32 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_INSPECTOR_AGENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_INSPECTOR_AGENT_H_ + +#include "third_party/blink/renderer/platform/heap/handle.h" + +namespace blink { + +class LocalFrame; +class SensorProviderProxy; + +class SensorInspectorAgent : public GarbageCollected<SensorInspectorAgent> { + public: + explicit SensorInspectorAgent(LocalFrame* frame); + virtual void Trace(blink::Visitor*); + + void SetOrientationSensorOverride(double alpha, double beta, double gamma); + + void Disable(); + + private: + Member<SensorProviderProxy> provider_; + + DISALLOW_COPY_AND_ASSIGN(SensorInspectorAgent); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_INSPECTOR_AGENT_H_
diff --git a/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc b/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc index f89482e8..fab070a9 100644 --- a/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc +++ b/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc
@@ -6,14 +6,15 @@ #include "services/device/public/mojom/constants.mojom-blink.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "third_party/blink/renderer/modules/sensor/sensor_proxy.h" +#include "third_party/blink/renderer/modules/sensor/sensor_proxy_impl.h" +#include "third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h" #include "third_party/blink/renderer/platform/mojo/mojo_helper.h" namespace blink { // SensorProviderProxy SensorProviderProxy::SensorProviderProxy(LocalFrame& frame) - : Supplement<LocalFrame>(frame) {} + : Supplement<LocalFrame>(frame), inspector_mode_(false) {} void SensorProviderProxy::InitializeIfNeeded() { if (IsInitialized()) @@ -54,7 +55,11 @@ Page* page) { DCHECK(!GetSensorProxy(type)); - SensorProxy* sensor = new SensorProxy(type, this, page); + SensorProxy* sensor = + inspector_mode_ + ? static_cast<SensorProxy*>( + new SensorProxyInspectorImpl(type, this, page)) + : static_cast<SensorProxy*>(new SensorProxyImpl(type, this, page)); sensor_proxies_.insert(sensor); return sensor; @@ -73,8 +78,15 @@ void SensorProviderProxy::OnSensorProviderConnectionError() { sensor_provider_.reset(); - for (SensorProxy* sensor : sensor_proxies_) - sensor->HandleSensorError(); + for (SensorProxy* sensor : sensor_proxies_) { + sensor->ReportError(kNotReadableError, + SensorProxy::kDefaultErrorDescription); + } +} + +void SensorProviderProxy::RemoveSensorProxy(SensorProxy* proxy) { + DCHECK(sensor_proxies_.Contains(proxy)); + sensor_proxies_.erase(proxy); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h b/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h index a489c6a..bad04f7d 100644 --- a/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h +++ b/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h
@@ -31,28 +31,33 @@ ~SensorProviderProxy(); SensorProxy* CreateSensorProxy(device::mojom::blink::SensorType, Page*); - SensorProxy* GetSensorProxy(device::mojom::blink::SensorType); + void set_inspector_mode(bool flag) { inspector_mode_ = flag; } + bool inspector_mode() const { return inspector_mode_; } + void Trace(blink::Visitor*) override; private: - friend class SensorProxy; // To call getSensorProvider(). + friend class SensorProxy; + // For SensorProviderProxy friends' use. + device::mojom::blink::SensorProvider* sensor_provider() const { + return sensor_provider_.get(); + } + void RemoveSensorProxy(SensorProxy* proxy); + using SensorsSet = HeapHashSet<WeakMember<SensorProxy>>; + const SensorsSet& sensor_proxies() const { return sensor_proxies_; } + + // For SensorProviderProxy personal use. explicit SensorProviderProxy(LocalFrame&); void InitializeIfNeeded(); bool IsInitialized() const { return sensor_provider_.is_bound(); } - - device::mojom::blink::SensorProvider* GetSensorProvider() const { - return sensor_provider_.get(); - } - void OnSensorProviderConnectionError(); - - using SensorsSet = HeapHashSet<WeakMember<SensorProxy>>; SensorsSet sensor_proxies_; device::mojom::blink::SensorProviderPtr sensor_provider_; + bool inspector_mode_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy.cc b/third_party/blink/renderer/modules/sensor/sensor_proxy.cc index 7d15357..12f2564 100644 --- a/third_party/blink/renderer/modules/sensor/sensor_proxy.cc +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy.cc
@@ -4,7 +4,6 @@ #include "third_party/blink/renderer/modules/sensor/sensor_proxy.h" -#include "services/device/public/cpp/generic_sensor/sensor_traits.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" @@ -15,38 +14,30 @@ #include "third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h" #include "third_party/blink/renderer/modules/sensor/sensor_reading_remapper.h" #include "third_party/blink/renderer/platform/layout_test_support.h" -#include "third_party/blink/renderer/platform/mojo/mojo_helper.h" namespace blink { using namespace device::mojom::blink; +const char SensorProxy::kDefaultErrorDescription[] = + "Could not connect to a sensor"; + SensorProxy::SensorProxy(SensorType sensor_type, SensorProviderProxy* provider, Page* page) : PageVisibilityObserver(page), FocusChangedObserver(page), type_(sensor_type), - mode_(ReportingMode::CONTINUOUS), - provider_(provider), - client_binding_(this), state_(SensorProxy::kUninitialized), - suspended_(false), - polling_timer_( - provider->GetSupplementable()->GetTaskRunner(TaskType::kSensor), - this, - &SensorProxy::OnPollingTimer) {} + provider_(provider) {} -SensorProxy::~SensorProxy() = default; - -void SensorProxy::Dispose() { - client_binding_.Close(); -} +SensorProxy::~SensorProxy() {} void SensorProxy::Trace(blink::Visitor* visitor) { visitor->Trace(observers_); visitor->Trace(provider_); PageVisibilityObserver::Trace(visitor); + FocusChangedObserver::Trace(visitor); } void SensorProxy::AddObserver(Observer* observer) { @@ -58,104 +49,48 @@ observers_.erase(observer); } -void SensorProxy::Initialize() { - if (state_ != kUninitialized) - return; - - if (!provider_->GetSensorProvider()) { - HandleSensorError(); - return; +void SensorProxy::Detach() { + if (!detached_) { + provider_->RemoveSensorProxy(this); + detached_ = true; } - - state_ = kInitializing; - auto callback = - WTF::Bind(&SensorProxy::OnSensorCreated, WrapWeakPersistent(this)); - provider_->GetSensorProvider()->GetSensor(type_, std::move(callback)); } -void SensorProxy::AddConfiguration(SensorConfigurationPtr configuration, - base::OnceCallback<void(bool)> callback) { - DCHECK(IsInitialized()); - AddActiveFrequency(configuration->frequency); - sensor_->AddConfiguration(std::move(configuration), std::move(callback)); +void SensorProxy::ReportError(ExceptionCode code, const String& message) { + auto copy = observers_; + for (Observer* observer : copy) { + observer->OnSensorError(code, message, String()); + } } -void SensorProxy::RemoveConfiguration(SensorConfigurationPtr configuration) { - DCHECK(IsInitialized()); - RemoveActiveFrequency(configuration->frequency); - sensor_->RemoveConfiguration(std::move(configuration)); +namespace { + +uint16_t GetScreenOrientationAngleForPage(Page* page) { + if (LayoutTestSupport::IsRunningLayoutTest()) { + // Simulate that the device is turned 90 degrees on the right. + // 'orientation_angle' must be 270 as per + // https://w3c.github.io/screen-orientation/#dfn-update-the-orientation-information. + return 270; + } + return page->GetChromeClient().GetScreenInfo().orientation_angle; } -void SensorProxy::Suspend() { - DCHECK(IsInitialized()); - if (suspended_) - return; - - sensor_->Suspend(); - suspended_ = true; - UpdatePollingStatus(); -} - -void SensorProxy::Resume() { - DCHECK(IsInitialized()); - if (!suspended_) - return; - - sensor_->Resume(); - suspended_ = false; - UpdatePollingStatus(); -} +} // namespace const device::SensorReading& SensorProxy::GetReading(bool remapped) const { + DCHECK(IsInitialized()); if (remapped) { if (remapped_reading_.timestamp() != reading_.timestamp()) { remapped_reading_ = reading_; SensorReadingRemapper::RemapToScreenCoords( - type_, GetScreenOrientationAngle(), &remapped_reading_); + type_, GetScreenOrientationAngleForPage(GetPage()), + &remapped_reading_); } return remapped_reading_; } return reading_; } -const SensorConfiguration* SensorProxy::DefaultConfig() const { - DCHECK(IsInitialized()); - return default_config_.get(); -} - -void SensorProxy::UpdateSensorReading() { - DCHECK(ShouldProcessReadings()); - device::SensorReading reading_data; - if (!shared_buffer_handle_->is_valid() || - !shared_buffer_reader_->GetReading(&reading_data)) { - HandleSensorError(); - return; - } - - double latest_timestamp = reading_data.timestamp(); - if (reading_.timestamp() != latest_timestamp && - latest_timestamp != 0.0) // The shared buffer is zeroed when - // sensor is stopped, we skip this - // reading. - { - DCHECK_GT(latest_timestamp, reading_.timestamp()) - << "Timestamps must increase monotonically"; - reading_ = reading_data; - for (Observer* observer : observers_) - observer->OnSensorReadingChanged(); - } -} - -void SensorProxy::RaiseError() { - HandleSensorError(); -} - -void SensorProxy::SensorReadingChanged() { - DCHECK_EQ(ReportingMode::ON_CHANGE, mode_); - if (ShouldProcessReadings()) - UpdateSensorReading(); -} - void SensorProxy::PageVisibilityChanged() { UpdateSuspendedStatus(); } @@ -164,125 +99,6 @@ UpdateSuspendedStatus(); } -void SensorProxy::HandleSensorError(SensorCreationResult error) { - state_ = kUninitialized; - active_frequencies_.clear(); - reading_ = device::SensorReading(); - UpdatePollingStatus(); - - // The m_sensor.reset() will release all callbacks and its bound parameters, - // therefore, handleSensorError accepts messages by value. - sensor_.reset(); - shared_buffer_.reset(); - shared_buffer_handle_.reset(); - default_config_.reset(); - client_binding_.Close(); - - ExceptionCode code = kNotReadableError; - String description = "Could not connect to a sensor"; - if (error == SensorCreationResult::ERROR_NOT_ALLOWED) { - code = kNotAllowedError; - description = "Permissions to access sensor are not granted"; - } - auto copy = observers_; - for (Observer* observer : copy) { - observer->OnSensorError(code, description, String()); - } -} - -void SensorProxy::OnSensorCreated(SensorCreationResult result, - SensorInitParamsPtr params) { - DCHECK_EQ(kInitializing, state_); - if (!params) { - DCHECK_NE(SensorCreationResult::SUCCESS, result); - HandleSensorError(result); - return; - } - - DCHECK_EQ(SensorCreationResult::SUCCESS, result); - const size_t kReadBufferSize = sizeof(ReadingBuffer); - - DCHECK_EQ(0u, params->buffer_offset % kReadBufferSize); - - mode_ = params->mode; - default_config_ = std::move(params->default_configuration); - if (!default_config_) { - HandleSensorError(); - return; - } - - sensor_.Bind(std::move(params->sensor)); - client_binding_.Bind(std::move(params->client_request)); - - shared_buffer_handle_ = std::move(params->memory); - DCHECK(!shared_buffer_); - shared_buffer_ = shared_buffer_handle_->MapAtOffset(kReadBufferSize, - params->buffer_offset); - - if (!shared_buffer_) { - HandleSensorError(); - return; - } - - const auto* buffer = static_cast<const device::SensorReadingSharedBuffer*>( - shared_buffer_.get()); - shared_buffer_reader_.reset( - new device::SensorReadingSharedBufferReader(buffer)); - frequency_limits_.first = params->minimum_frequency; - frequency_limits_.second = params->maximum_frequency; - - DCHECK_GT(frequency_limits_.first, 0.0); - DCHECK_GE(frequency_limits_.second, frequency_limits_.first); - DCHECK_GE(device::GetSensorMaxAllowedFrequency(type_), - frequency_limits_.second); - - auto error_callback = - WTF::Bind(&SensorProxy::HandleSensorError, WrapWeakPersistent(this), - SensorCreationResult::ERROR_NOT_AVAILABLE); - sensor_.set_connection_error_handler(std::move(error_callback)); - - state_ = kInitialized; - - UpdateSuspendedStatus(); - - for (Observer* observer : observers_) - observer->OnSensorInitialized(); -} - -void SensorProxy::OnPollingTimer(TimerBase*) { - UpdateSensorReading(); -} - -bool SensorProxy::ShouldProcessReadings() const { - return IsInitialized() && !suspended_ && !active_frequencies_.IsEmpty(); -} - -uint16_t SensorProxy::GetScreenOrientationAngle() const { - DCHECK(IsInitialized()); - if (LayoutTestSupport::IsRunningLayoutTest()) { - // Simulate that the device is turned 90 degrees on the right. - // 'orientation_angle' must be 270 as per - // https://w3c.github.io/screen-orientation/#dfn-update-the-orientation-information. - return 270; - } - return GetPage()->GetChromeClient().GetScreenInfo().orientation_angle; -} - -void SensorProxy::UpdatePollingStatus() { - if (mode_ != ReportingMode::CONTINUOUS) - return; - - if (ShouldProcessReadings()) { - // TODO(crbug/721297) : We need to find out an algorithm for resulting - // polling frequency. - polling_timer_.StartRepeating( - WTF::TimeDelta::FromSecondsD(1 / active_frequencies_.back()), - FROM_HERE); - } else { - polling_timer_.Stop(); - } -} - void SensorProxy::UpdateSuspendedStatus() { if (!IsInitialized()) return; @@ -300,27 +116,8 @@ Suspend(); } -void SensorProxy::RemoveActiveFrequency(double frequency) { - // Can use binary search as active_frequencies_ is sorted. - auto* it = std::lower_bound(active_frequencies_.begin(), - active_frequencies_.end(), frequency); - if (it == active_frequencies_.end()) { - NOTREACHED() << "Attempted to remove active frequency which is not present " - "in the list"; - return; - } - - active_frequencies_.erase(it); - UpdatePollingStatus(); - - if (active_frequencies_.IsEmpty()) - reading_ = device::SensorReading(); -} - -void SensorProxy::AddActiveFrequency(double frequency) { - active_frequencies_.push_back(frequency); - std::sort(active_frequencies_.begin(), active_frequencies_.end()); - UpdatePollingStatus(); +SensorProvider* SensorProxy::sensor_provider() const { + return provider_->sensor_provider(); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy.h b/third_party/blink/renderer/modules/sensor/sensor_proxy.h index 663580e..e85f93d 100644 --- a/third_party/blink/renderer/modules/sensor/sensor_proxy.h +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy.h
@@ -5,7 +5,6 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_H_ -#include "mojo/public/cpp/bindings/binding.h" #include "services/device/public/cpp/generic_sensor/sensor_reading.h" #include "services/device/public/cpp/generic_sensor/sensor_reading_shared_buffer_reader.h" #include "services/device/public/mojom/sensor.mojom-blink.h" @@ -14,9 +13,6 @@ #include "third_party/blink/renderer/core/page/focus_changed_observer.h" #include "third_party/blink/renderer/core/page/page_visibility_observer.h" #include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/supplementable.h" -#include "third_party/blink/renderer/platform/timer.h" -#include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { @@ -24,13 +20,11 @@ // This class wraps 'Sensor' mojo interface and used by multiple // JS sensor instances of the same type (within a single frame). -class SensorProxy final : public GarbageCollectedFinalized<SensorProxy>, - public device::mojom::blink::SensorClient, - public PageVisibilityObserver, - public FocusChangedObserver { - USING_GARBAGE_COLLECTED_MIXIN(SensorProxy); - USING_PRE_FINALIZER(SensorProxy, Dispose); +class SensorProxy : public GarbageCollectedFinalized<SensorProxy>, + public PageVisibilityObserver, + public FocusChangedObserver { WTF_MAKE_NONCOPYABLE(SensorProxy); + USING_GARBAGE_COLLECTED_MIXIN(SensorProxy); public: class Observer : public GarbageCollectedMixin { @@ -54,101 +48,64 @@ void AddObserver(Observer*); void RemoveObserver(Observer*); - void Initialize(); + // Public methods to be implemented by descendants. + virtual void Initialize() = 0; + virtual void AddConfiguration(device::mojom::blink::SensorConfigurationPtr, + base::OnceCallback<void(bool)>) = 0; + virtual void RemoveConfiguration( + device::mojom::blink::SensorConfigurationPtr) = 0; + virtual double GetDefaultFrequency() const = 0; + virtual std::pair<double, double> GetFrequencyLimits() const = 0; + virtual void SetReadingForInspector(const device::SensorReading&) {} + virtual void ReportError(ExceptionCode code, const String& description); + // Getters. bool IsInitializing() const { return state_ == kInitializing; } bool IsInitialized() const { return state_ == kInitialized; } - - void AddConfiguration(device::mojom::blink::SensorConfigurationPtr, - base::OnceCallback<void(bool)>); - - void RemoveConfiguration(device::mojom::blink::SensorConfigurationPtr); - - void Suspend(); - void Resume(); - device::mojom::blink::SensorType type() const { return type_; } - // Note: do not use the stored references to the returned value // outside the current call chain. const device::SensorReading& GetReading(bool remapped = false) const; - const device::mojom::blink::SensorConfiguration* DefaultConfig() const; - const std::pair<double, double>& FrequencyLimits() const { - return frequency_limits_; - } + // Detach from the local frame's SensorProviderProxy. + void Detach(); void Trace(blink::Visitor*) override; - private: - friend class SensorProviderProxy; + static const char kDefaultErrorDescription[]; + + protected: SensorProxy(device::mojom::blink::SensorType, SensorProviderProxy*, Page*); + void UpdateSuspendedStatus(); - // Updates sensor reading from shared buffer. - void UpdateSensorReading(); - void NotifySensorChanged(double timestamp); + // Protected methods to be implemented by descendants. + virtual void Suspend() {} + virtual void Resume() {} - // device::mojom::blink::SensorClient overrides. - void RaiseError() override; - void SensorReadingChanged() override; + device::mojom::blink::SensorProvider* sensor_provider() const; + device::mojom::blink::SensorType type_; + using ObserversSet = HeapHashSet<WeakMember<Observer>>; + ObserversSet observers_; + + enum State { kUninitialized, kInitializing, kInitialized }; + State state_ = kUninitialized; + + device::SensorReading reading_; + mutable device::SensorReading remapped_reading_; + + using ReadingBuffer = device::SensorReadingSharedBuffer; + + private: // PageVisibilityObserver overrides. void PageVisibilityChanged() override; // FocusChangedObserver overrides. void FocusedFrameChanged() override; - // Generic handler for a fatal error. - void HandleSensorError( - device::mojom::blink::SensorCreationResult = - device::mojom::blink::SensorCreationResult::ERROR_NOT_AVAILABLE); - - // mojo call callbacks. - void OnSensorCreated(device::mojom::blink::SensorCreationResult, - device::mojom::blink::SensorInitParamsPtr); - - void OnPollingTimer(TimerBase*); - - // Returns 'true' if readings should be propagated to Observers - // (i.e. proxy is initialized, not suspended and has active configurations); - // returns 'false' otherwise. - bool ShouldProcessReadings() const; - - // Starts or stops polling timer. - void UpdatePollingStatus(); - - // Suspends or resumes the wrapped sensor. - void UpdateSuspendedStatus(); - - void RemoveActiveFrequency(double frequency); - void AddActiveFrequency(double frequency); - uint16_t GetScreenOrientationAngle() const; - - device::mojom::blink::SensorType type_; - device::mojom::blink::ReportingMode mode_; Member<SensorProviderProxy> provider_; - using ObserversSet = HeapHashSet<WeakMember<Observer>>; - ObserversSet observers_; + bool detached_ = false; - device::mojom::blink::SensorPtr sensor_; - device::mojom::blink::SensorConfigurationPtr default_config_; - mojo::Binding<device::mojom::blink::SensorClient> client_binding_; - - enum State { kUninitialized, kInitializing, kInitialized }; - State state_; - mojo::ScopedSharedBufferHandle shared_buffer_handle_; - mojo::ScopedSharedBufferMapping shared_buffer_; - std::unique_ptr<device::SensorReadingSharedBufferReader> - shared_buffer_reader_; - bool suspended_; - device::SensorReading reading_; - mutable device::SensorReading remapped_reading_; - std::pair<double, double> frequency_limits_; - - WTF::Vector<double> active_frequencies_; - TaskRunnerTimer<SensorProxy> polling_timer_; - - using ReadingBuffer = device::SensorReadingSharedBuffer; static_assert( sizeof(ReadingBuffer) == device::mojom::blink::SensorInitParams::kReadBufferSizeForTests,
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc b/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc new file mode 100644 index 0000000..aaaa603 --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc
@@ -0,0 +1,269 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/sensor/sensor_proxy_impl.h" + +#include "services/device/public/cpp/generic_sensor/sensor_traits.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h" +#include "third_party/blink/renderer/modules/sensor/sensor_reading_remapper.h" +#include "third_party/blink/renderer/platform/mojo/mojo_helper.h" + +namespace blink { + +using namespace device::mojom::blink; + +SensorProxyImpl::SensorProxyImpl(SensorType sensor_type, + SensorProviderProxy* provider, + Page* page) + : SensorProxy(sensor_type, provider, page), + client_binding_(this), + polling_timer_( + provider->GetSupplementable()->GetTaskRunner(TaskType::kSensor), + this, + &SensorProxyImpl::OnPollingTimer) {} + +SensorProxyImpl::~SensorProxyImpl() {} + +void SensorProxyImpl::Dispose() { + client_binding_.Close(); +} + +void SensorProxyImpl::Trace(blink::Visitor* visitor) { + SensorProxy::Trace(visitor); +} + +void SensorProxyImpl::Initialize() { + if (state_ != kUninitialized) + return; + + if (!sensor_provider()) { + HandleSensorError(); + return; + } + + state_ = kInitializing; + auto callback = + WTF::Bind(&SensorProxyImpl::OnSensorCreated, WrapWeakPersistent(this)); + sensor_provider()->GetSensor(type_, std::move(callback)); +} + +void SensorProxyImpl::AddConfiguration( + SensorConfigurationPtr configuration, + base::OnceCallback<void(bool)> callback) { + DCHECK(IsInitialized()); + AddActiveFrequency(configuration->frequency); + sensor_->AddConfiguration(std::move(configuration), std::move(callback)); +} + +void SensorProxyImpl::RemoveConfiguration( + SensorConfigurationPtr configuration) { + DCHECK(IsInitialized()); + RemoveActiveFrequency(configuration->frequency); + sensor_->RemoveConfiguration(std::move(configuration)); +} + +double SensorProxyImpl::GetDefaultFrequency() const { + DCHECK(IsInitialized()); + return default_frequency_; +} + +std::pair<double, double> SensorProxyImpl::GetFrequencyLimits() const { + DCHECK(IsInitialized()); + return frequency_limits_; +} + +void SensorProxyImpl::Suspend() { + if (suspended_) + return; + + sensor_->Suspend(); + suspended_ = true; + UpdatePollingStatus(); +} + +void SensorProxyImpl::Resume() { + if (!suspended_) + return; + + sensor_->Resume(); + suspended_ = false; + UpdatePollingStatus(); +} + +void SensorProxyImpl::UpdateSensorReading() { + DCHECK(ShouldProcessReadings()); + device::SensorReading reading_data; + if (!shared_buffer_handle_->is_valid() || + !shared_buffer_reader_->GetReading(&reading_data)) { + HandleSensorError(); + return; + } + + double latest_timestamp = reading_data.timestamp(); + if (reading_.timestamp() != latest_timestamp && + latest_timestamp != 0.0) // The shared buffer is zeroed when + // sensor is stopped, we skip this + // reading. + { + DCHECK_GT(latest_timestamp, reading_.timestamp()) + << "Timestamps must increase monotonically"; + reading_ = reading_data; + for (Observer* observer : observers_) + observer->OnSensorReadingChanged(); + } +} + +void SensorProxyImpl::RaiseError() { + HandleSensorError(); +} + +void SensorProxyImpl::SensorReadingChanged() { + DCHECK_EQ(ReportingMode::ON_CHANGE, mode_); + if (ShouldProcessReadings()) + UpdateSensorReading(); +} + +void SensorProxyImpl::ReportError(ExceptionCode code, const String& message) { + state_ = kUninitialized; + active_frequencies_.clear(); + reading_ = device::SensorReading(); + UpdatePollingStatus(); + + // The m_sensor.reset() will release all callbacks and its bound parameters, + // therefore, handleSensorError accepts messages by value. + sensor_.reset(); + shared_buffer_.reset(); + shared_buffer_handle_.reset(); + default_frequency_ = 0.0; + frequency_limits_ = {0.0, 0.0}; + client_binding_.Close(); + + SensorProxy::ReportError(code, message); +} + +void SensorProxyImpl::HandleSensorError(SensorCreationResult error) { + if (error == SensorCreationResult::ERROR_NOT_ALLOWED) { + String description = "Permissions to access sensor are not granted"; + ReportError(kNotAllowedError, std::move(description)); + } else { + ReportError(kNotReadableError, kDefaultErrorDescription); + } +} + +void SensorProxyImpl::OnSensorCreated(SensorCreationResult result, + SensorInitParamsPtr params) { + DCHECK_EQ(kInitializing, state_); + if (!params) { + DCHECK_NE(SensorCreationResult::SUCCESS, result); + HandleSensorError(result); + return; + } + + DCHECK_EQ(SensorCreationResult::SUCCESS, result); + const size_t kReadBufferSize = sizeof(ReadingBuffer); + + DCHECK_EQ(0u, params->buffer_offset % kReadBufferSize); + + mode_ = params->mode; + if (!params->default_configuration) { + HandleSensorError(); + return; + } + + default_frequency_ = params->default_configuration->frequency; + DCHECK_GT(default_frequency_, 0.0); + + sensor_.Bind(std::move(params->sensor)); + client_binding_.Bind(std::move(params->client_request)); + + shared_buffer_handle_ = std::move(params->memory); + DCHECK(!shared_buffer_); + shared_buffer_ = shared_buffer_handle_->MapAtOffset(kReadBufferSize, + params->buffer_offset); + + if (!shared_buffer_) { + HandleSensorError(); + return; + } + + const auto* buffer = static_cast<const device::SensorReadingSharedBuffer*>( + shared_buffer_.get()); + shared_buffer_reader_.reset( + new device::SensorReadingSharedBufferReader(buffer)); + frequency_limits_.first = params->minimum_frequency; + frequency_limits_.second = params->maximum_frequency; + + DCHECK_GT(frequency_limits_.first, 0.0); + DCHECK_GE(frequency_limits_.second, frequency_limits_.first); + DCHECK_GE(device::GetSensorMaxAllowedFrequency(type_), + frequency_limits_.second); + + auto error_callback = + WTF::Bind(&SensorProxyImpl::HandleSensorError, WrapWeakPersistent(this), + SensorCreationResult::ERROR_NOT_AVAILABLE); + sensor_.set_connection_error_handler(std::move(error_callback)); + + state_ = kInitialized; + + UpdateSuspendedStatus(); + + for (Observer* observer : observers_) + observer->OnSensorInitialized(); +} + +void SensorProxyImpl::OnPollingTimer(TimerBase*) { + UpdateSensorReading(); +} + +bool SensorProxyImpl::ShouldProcessReadings() const { + return IsInitialized() && !suspended_ && !active_frequencies_.IsEmpty(); +} + +void SensorProxyImpl::UpdatePollingStatus() { + if (mode_ != ReportingMode::CONTINUOUS) + return; + + if (ShouldProcessReadings()) { + // TODO(crbug/721297) : We need to find out an algorithm for resulting + // polling frequency. + polling_timer_.StartRepeating( + WTF::TimeDelta::FromSecondsD(1 / active_frequencies_.back()), + FROM_HERE); + } else { + polling_timer_.Stop(); + } +} + +void SensorProxyImpl::RemoveActiveFrequency(double frequency) { + // Can use binary search as active_frequencies_ is sorted. + Vector<double>::iterator it = std::lower_bound( + active_frequencies_.begin(), active_frequencies_.end(), frequency); + if (it == active_frequencies_.end() || *it != frequency) { + NOTREACHED() << "Attempted to remove active frequency which is not present " + "in the list"; + return; + } + + active_frequencies_.erase(it); + UpdatePollingStatus(); + + if (active_frequencies_.IsEmpty()) + reading_ = device::SensorReading(); +} + +void SensorProxyImpl::AddActiveFrequency(double frequency) { + Vector<double>::iterator it = std::lower_bound( + active_frequencies_.begin(), active_frequencies_.end(), frequency); + if (it == active_frequencies_.end()) { + active_frequencies_.push_back(frequency); + } else { + active_frequencies_.insert(std::distance(active_frequencies_.begin(), it), + frequency); + } + UpdatePollingStatus(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.h b/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.h new file mode 100644 index 0000000..8c55c27 --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.h
@@ -0,0 +1,97 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_IMPL_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_IMPL_H_ + +#include "third_party/blink/renderer/modules/sensor/sensor_proxy.h" + +#include "mojo/public/cpp/bindings/binding.h" +#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" + +namespace blink { + +class SensorProviderProxy; + +// This class wraps 'Sensor' mojo interface and used by multiple +// JS sensor instances of the same type (within a single frame). +class SensorProxyImpl final : public SensorProxy, + public device::mojom::blink::SensorClient { + USING_PRE_FINALIZER(SensorProxyImpl, Dispose); + WTF_MAKE_NONCOPYABLE(SensorProxyImpl); + + public: + SensorProxyImpl(device::mojom::blink::SensorType, + SensorProviderProxy*, + Page*); + ~SensorProxyImpl() override; + + void Trace(blink::Visitor*) override; + + void Dispose(); + + private: + // SensorProxy overrides. + void Initialize() override; + void AddConfiguration(device::mojom::blink::SensorConfigurationPtr, + base::OnceCallback<void(bool)>) override; + void RemoveConfiguration( + device::mojom::blink::SensorConfigurationPtr) override; + double GetDefaultFrequency() const override; + std::pair<double, double> GetFrequencyLimits() const override; + void ReportError(ExceptionCode code, const String& message) override; + void Suspend() override; + void Resume() override; + + // Updates sensor reading from shared buffer. + void UpdateSensorReading(); + void NotifySensorChanged(double timestamp); + + // device::mojom::blink::SensorClient overrides. + void RaiseError() override; + void SensorReadingChanged() override; + + // Generic handler for a fatal error. + void HandleSensorError( + device::mojom::blink::SensorCreationResult = + device::mojom::blink::SensorCreationResult::ERROR_NOT_AVAILABLE); + + // mojo call callbacks. + void OnSensorCreated(device::mojom::blink::SensorCreationResult, + device::mojom::blink::SensorInitParamsPtr); + + void OnPollingTimer(TimerBase*); + + // Returns 'true' if readings should be propagated to Observers + // (i.e. proxy is initialized, not suspended and has active configurations); + // returns 'false' otherwise. + bool ShouldProcessReadings() const; + + // Starts or stops polling timer. + void UpdatePollingStatus(); + + void RemoveActiveFrequency(double frequency); + void AddActiveFrequency(double frequency); + + device::mojom::blink::ReportingMode mode_ = + device::mojom::blink::ReportingMode::CONTINUOUS; + device::mojom::blink::SensorPtr sensor_; + mojo::Binding<device::mojom::blink::SensorClient> client_binding_; + + mojo::ScopedSharedBufferHandle shared_buffer_handle_; + mojo::ScopedSharedBufferMapping shared_buffer_; + std::unique_ptr<device::SensorReadingSharedBufferReader> + shared_buffer_reader_; + double default_frequency_ = 0.0; + std::pair<double, double> frequency_limits_; + bool suspended_ = false; + + WTF::Vector<double> active_frequencies_; + TaskRunnerTimer<SensorProxyImpl> polling_timer_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_IMPL_H_
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc b/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc new file mode 100644 index 0000000..5016e51d --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc
@@ -0,0 +1,105 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h" + +#include "services/device/public/cpp/generic_sensor/sensor_traits.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/modules/sensor/sensor_reading_remapper.h" +#include "third_party/blink/renderer/platform/wtf/math_extras.h" + +namespace blink { + +using namespace device::mojom::blink; + +SensorProxyInspectorImpl::SensorProxyInspectorImpl( + SensorType sensor_type, + SensorProviderProxy* provider, + Page* page) + : SensorProxy(sensor_type, provider, page) {} + +SensorProxyInspectorImpl::~SensorProxyInspectorImpl() {} + +void SensorProxyInspectorImpl::Trace(blink::Visitor* visitor) { + SensorProxy::Trace(visitor); +} + +void SensorProxyInspectorImpl::Initialize() { + if (state_ != kUninitialized) + return; + + state_ = kInitializing; + + auto callback = WTF::Bind(&SensorProxyInspectorImpl::OnSensorCreated, + WrapWeakPersistent(this)); + + Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask( + FROM_HERE, std::move(callback)); +} + +void SensorProxyInspectorImpl::AddConfiguration( + SensorConfigurationPtr configuration, + base::OnceCallback<void(bool)> callback) { + DCHECK(IsInitialized()); + std::move(callback).Run(true); +} + +void SensorProxyInspectorImpl::RemoveConfiguration( + SensorConfigurationPtr configuration) { + DCHECK(IsInitialized()); +} + +double SensorProxyInspectorImpl::GetDefaultFrequency() const { + DCHECK(IsInitialized()); + return device::GetSensorDefaultFrequency(type_); +} + +std::pair<double, double> SensorProxyInspectorImpl::GetFrequencyLimits() const { + DCHECK(IsInitialized()); + return {1.0, device::GetSensorMaxAllowedFrequency(type_)}; +} + +void SensorProxyInspectorImpl::Suspend() { + suspended_ = true; +} + +void SensorProxyInspectorImpl::Resume() { + suspended_ = false; +} + +void SensorProxyInspectorImpl::SetReadingForInspector( + const device::SensorReading& reading) { + if (!ShouldProcessReadings()) + return; + + reading_ = reading; + for (Observer* observer : observers_) + observer->OnSensorReadingChanged(); +} + +void SensorProxyInspectorImpl::ReportError(ExceptionCode code, + const String& message) { + state_ = kUninitialized; + reading_ = device::SensorReading(); + SensorProxy::ReportError(code, message); +} + +void SensorProxyInspectorImpl::OnSensorCreated() { + DCHECK_EQ(kInitializing, state_); + + state_ = kInitialized; + + UpdateSuspendedStatus(); + + for (Observer* observer : observers_) + observer->OnSensorInitialized(); +} + +bool SensorProxyInspectorImpl::ShouldProcessReadings() const { + return IsInitialized() && !suspended_; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h b/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h new file mode 100644 index 0000000..06b758c8 --- /dev/null +++ b/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.h
@@ -0,0 +1,52 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_INSPECTOR_IMPL_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_INSPECTOR_IMPL_H_ + +#include "third_party/blink/renderer/modules/sensor/sensor_proxy.h" + +namespace blink { + +class SensorProxyInspectorImpl final : public SensorProxy { + WTF_MAKE_NONCOPYABLE(SensorProxyInspectorImpl); + + public: + SensorProxyInspectorImpl(device::mojom::blink::SensorType sensor_type, + SensorProviderProxy* provider, + Page* page); + ~SensorProxyInspectorImpl() override; + + void Trace(blink::Visitor*) override; + + private: + // SensorProxy overrides. + void Initialize() override; + void AddConfiguration(device::mojom::blink::SensorConfigurationPtr, + base::OnceCallback<void(bool)>) override; + void RemoveConfiguration( + device::mojom::blink::SensorConfigurationPtr) override; + double GetDefaultFrequency() const override; + std::pair<double, double> GetFrequencyLimits() const override; + void SetReadingForInspector(const device::SensorReading&) override; + + void ReportError(ExceptionCode, const String&) override; + + private: + void OnSensorCreated(); + + // Returns 'true' if readings should be propagated to Observers + // (i.e. proxy is initialized, not suspended); + // returns 'false' otherwise. + bool ShouldProcessReadings() const; + + void Suspend() override; + void Resume() override; + + bool suspended_ = false; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROXY_INSPECTOR_IMPL_H_
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 92551f71..d6a1d87 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1546,7 +1546,6 @@ ":platform_export", "//base/allocator:buildflags", "//components/viz/service", - "//device/base/synchronization", "//device/vr/public/mojom:mojom_blink", "//gin", "//mojo/public/cpp/base", @@ -1955,7 +1954,6 @@ "//cc", "//cc:test_support", "//cc/blink", - "//device/base/synchronization", "//mojo/edk", "//mojo/public/cpp/bindings/tests:for_blink_tests", "//mojo/public/cpp/test_support:test_utils",
diff --git a/third_party/blink/renderer/platform/fonts/shaping/harf_buzz_shaper_test.cc b/third_party/blink/renderer/platform/fonts/shaping/harf_buzz_shaper_test.cc index 0ed7ad6d..da08101 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/harf_buzz_shaper_test.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/harf_buzz_shaper_test.cc
@@ -907,7 +907,8 @@ EXPECT_EQ(result->NumCharacters(), composite_result->NumCharacters()); EXPECT_EQ(result->SnappedWidth(), composite_result->SnappedWidth()); - EXPECT_EQ(result->Bounds(), composite_result->Bounds()); + EXPECT_TRUE(composite_result->Bounds().Contains(result->Bounds())) + << composite_result->Bounds() << "/" << result->Bounds(); EXPECT_EQ(result->SnappedStartPositionForOffset(0), composite_result->SnappedStartPositionForOffset(0)); EXPECT_EQ(result->SnappedStartPositionForOffset(1), @@ -968,6 +969,30 @@ EXPECT_NEAR(result->Width(), result->Bounds().Width(), result->Width() * .1); } +TEST_F(HarfBuzzShaperTest, ShapeResultCopyRangeBoundsLtr) { + String string(u". "); + TextDirection direction = TextDirection::kLtr; + HarfBuzzShaper shaper(string.Characters16(), string.length()); + scoped_refptr<ShapeResult> result = shaper.Shape(&font, direction); + + // Because a space character does not have ink, the bounds of "." should be + // the same as the bounds of ". ". + scoped_refptr<ShapeResult> sub_range = result->SubRange(0, 1); + EXPECT_EQ(sub_range->Bounds().Width(), result->Bounds().Width()); +} + +TEST_F(HarfBuzzShaperTest, ShapeResultCopyRangeBoundsRtl) { + String string(u". "); + TextDirection direction = TextDirection::kRtl; + HarfBuzzShaper shaper(string.Characters16(), string.length()); + scoped_refptr<ShapeResult> result = shaper.Shape(&font, direction); + + // Because a space character does not have ink, the bounds of "." should be + // the same as the bounds of ". ". + scoped_refptr<ShapeResult> sub_range = result->SubRange(0, 1); + EXPECT_EQ(sub_range->Bounds().Width(), result->Bounds().Width()); +} + TEST_F(HarfBuzzShaperTest, SubRange) { String string(u"Hello world"); TextDirection direction = TextDirection::kRtl;
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc index a12e545a..da83c78 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -166,15 +166,14 @@ NOTREACHED(); } -void ShapeResult::RunInfo::SetGlyphAndPositions(unsigned index, - uint16_t glyph_id, +void HarfBuzzRunGlyphData::SetGlyphAndPositions(uint16_t glyph_id, + uint16_t character_index, float advance, - float offset_x, - float offset_y) { - HarfBuzzRunGlyphData& data = glyph_data_[index]; - data.glyph = glyph_id; - data.advance = advance; - data.offset = FloatSize(offset_x, offset_y); + const FloatSize& offset) { + glyph = glyph_id; + this->character_index = character_index; + this->advance = advance; + this->offset = offset; } ShapeResult::ShapeResult(const SimpleFontData* font_data, @@ -569,6 +568,66 @@ return static_cast<float>(value) / (1 << 16); } +// This is a helper class to accumulate glyph bounding box. +// +// Glyph positions and bounding boxes from HarfBuzz and fonts are in physical +// coordinate, while ShapeResult::glyph_bounding_box_ is in logical coordinate. +// To minimize the number of conversions, this class accumulates the bounding +// boxes in physical coordinate, and convert the accumulated box to logical. +struct GlyphBoundsAccumulator { + // Construct an accumulator with the logical glyph origin. + explicit GlyphBoundsAccumulator(float origin) : origin(origin) {} + + // The accumulated glyph bounding box in physical coordinate, until + // ConvertVerticalRunToLogical(). + FloatRect bounds; + // The current origin, in logical coordinate. + float origin; + + // Unite a glyph bounding box to |bounds|. + template <bool is_horizontal_run> + void Unite(const HarfBuzzRunGlyphData& glyph_data, + FloatRect bounds_for_glyph) { + if (UNLIKELY(bounds_for_glyph.IsEmpty())) + return; + + // Glyphs are drawn at |origin + offset|. Move glyph_bounds to that point. + // All positions in hb_glyph_position_t are relative to the current point. + // https://behdad.github.io/harfbuzz/harfbuzz-Buffers.html#hb-glyph-position-t-struct + if (is_horizontal_run) + bounds_for_glyph.SetX(bounds_for_glyph.X() + origin); + else + bounds_for_glyph.SetY(bounds_for_glyph.Y() + origin); + bounds_for_glyph.Move(glyph_data.offset); + + bounds.Unite(bounds_for_glyph); + } + + // Non-template version of |Unite()|, see above. + void Unite(bool is_horizontal_run, + const HarfBuzzRunGlyphData& glyph, + FloatRect bounds_for_glyph) { + is_horizontal_run ? Unite<true>(glyph, bounds_for_glyph) + : Unite<false>(glyph, bounds_for_glyph); + } + + // Convert vertical run glyph bounding box to logical. Horizontal runs do not + // need conversions because physical and logical are the same. + void ConvertVerticalRunToLogical(const FontMetrics& font_metrics) { + // Convert physical glyph_bounding_box to logical. + bounds = bounds.TransposedRect(); + + // The glyph bounding box of a vertical run uses ideographic baseline. + // Adjust the box Y position because the bounding box of a ShapeResult uses + // alphabetic baseline. + // See diagrams of base lines at + // https://drafts.csswg.org/css-writing-modes-3/#intro-baselines + int baseline_adjust = font_metrics.Ascent(kIdeographicBaseline) - + font_metrics.Ascent(kAlphabeticBaseline); + bounds.SetY(bounds.Y() + baseline_adjust); + } +}; + // Checks whether it's safe to break without reshaping before the given glyph. bool IsSafeToBreakBefore(const hb_glyph_info_t* glyph_infos, unsigned num_glyphs, @@ -597,10 +656,9 @@ void ShapeResult::ComputeGlyphPositions(ShapeResult::RunInfo* run, unsigned start_glyph, unsigned num_glyphs, - hb_buffer_t* harf_buzz_buffer, - FloatRect* glyph_bounding_box) { + hb_buffer_t* harf_buzz_buffer) { DCHECK_EQ(is_horizontal_run, run->IsHorizontal()); - const SimpleFontData* current_font_data = run->font_data_.get(); + const SimpleFontData& current_font_data = *run->font_data_; const hb_glyph_info_t* glyph_infos = hb_buffer_get_glyph_infos(harf_buzz_buffer, nullptr); const hb_glyph_position_t* glyph_positions = @@ -614,66 +672,52 @@ // and boudning box of glyphs are in physical. It's the caller's // responsibility to convert the united physical bounds to logical. float total_advance = 0.0f; - FloatPoint glyph_origin; - if (is_horizontal_run) - glyph_origin.SetX(width_); - else - glyph_origin.SetY(width_); + GlyphBoundsAccumulator bounds(width_); bool has_vertical_offsets = !is_horizontal_run; + // Because we reverse this later, it must be empty at this point. + DCHECK(run->safe_break_offsets_.IsEmpty()); + // HarfBuzz returns result in visual order, no need to flip for RTL. for (unsigned i = 0; i < num_glyphs; ++i) { uint16_t glyph = glyph_infos[start_glyph + i].codepoint; - hb_glyph_position_t pos = glyph_positions[start_glyph + i]; + const hb_glyph_position_t& pos = glyph_positions[start_glyph + i]; // Offset is primarily used when painting glyphs. Keep it in physical. - float offset_x = HarfBuzzPositionToFloat(pos.x_offset); - float offset_y = -HarfBuzzPositionToFloat(pos.y_offset); + FloatSize offset(HarfBuzzPositionToFloat(pos.x_offset), + -HarfBuzzPositionToFloat(pos.y_offset)); // One out of x_advance and y_advance is zero, depending on // whether the buffer direction is horizontal or vertical. // Convert to float and negate to avoid integer-overflow for ULONG_MAX. - float advance; - if (is_horizontal_run) - advance = HarfBuzzPositionToFloat(pos.x_advance); - else - advance = -HarfBuzzPositionToFloat(pos.y_advance); + float advance = is_horizontal_run ? HarfBuzzPositionToFloat(pos.x_advance) + : -HarfBuzzPositionToFloat(pos.y_advance); uint16_t character_index = glyph_infos[start_glyph + i].cluster - start_cluster; - run->glyph_data_[i].character_index = character_index; - - run->SetGlyphAndPositions(i, glyph, advance, offset_x, offset_y); + HarfBuzzRunGlyphData& glyph_data = run->glyph_data_[i]; + glyph_data.SetGlyphAndPositions(glyph, character_index, advance, offset); total_advance += advance; - has_vertical_offsets |= (offset_y != 0); + has_vertical_offsets |= (offset.Height() != 0); - // SetGlyphAndPositions() above sets to draw glyphs at |glyph_origin + - // offset_{x,y}|. Move glyph_bounds to that point. - // Then move the current point by |advance| from |glyph_origin|. - // All positions in hb_glyph_position_t are relative to the current point. - // https://behdad.github.io/harfbuzz/harfbuzz-Buffers.html#hb-glyph-position-t-struct - FloatRect glyph_bounds = current_font_data->BoundsForGlyph(glyph); - if (!glyph_bounds.IsEmpty()) { - glyph_bounds.Move(glyph_origin.X() + offset_x, - glyph_origin.Y() + offset_y); - glyph_bounding_box->Unite(glyph_bounds); - } - if (is_horizontal_run) - glyph_origin.SetX(glyph_origin.X() + advance); - else - glyph_origin.SetY(glyph_origin.Y() + advance); + bounds.Unite<is_horizontal_run>( + glyph_data, current_font_data.BoundsForGlyph(glyph_data.glyph)); + bounds.origin += advance; // Check if it is safe to break without reshaping before the cluster. - if (IsSafeToBreakBefore(glyph_infos + start_glyph, num_glyphs, i)) { - if (run->Rtl()) - run->safe_break_offsets_.push_front(character_index); - else - run->safe_break_offsets_.push_back(character_index); - } + if (IsSafeToBreakBefore(glyph_infos + start_glyph, num_glyphs, i)) + run->safe_break_offsets_.push_back(character_index); } run->width_ = std::max(0.0f, total_advance); has_vertical_offsets_ |= has_vertical_offsets; + + if (!is_horizontal_run) + bounds.ConvertVerticalRunToLogical(current_font_data.GetFontMetrics()); + glyph_bounding_box_.Unite(bounds.bounds); + + if (UNLIKELY(run->Rtl())) + run->safe_break_offsets_.Reverse(); } void ShapeResult::InsertRun(std::unique_ptr<ShapeResult::RunInfo> run_to_insert, @@ -684,30 +728,17 @@ std::unique_ptr<ShapeResult::RunInfo> run(std::move(run_to_insert)); DCHECK_EQ(num_glyphs, run->glyph_data_.size()); - FloatRect glyph_bounding_box; if (run->IsHorizontal()) { // Inserting a horizontal run into a horizontal or vertical result. In both // cases, no adjustments are needed because |glyph_bounding_box_| is in // logical coordinates and uses alphabetic baseline. ComputeGlyphPositions<true>(run.get(), start_glyph, num_glyphs, - harf_buzz_buffer, &glyph_bounding_box); + harf_buzz_buffer); } else { // Inserting a vertical run to a vertical result. ComputeGlyphPositions<false>(run.get(), start_glyph, num_glyphs, - harf_buzz_buffer, &glyph_bounding_box); - // Convert physical glyph_bounding_box to logical. - glyph_bounding_box = glyph_bounding_box.TransposedRect(); - // The glyph bounding box of a vertical run uses ideographic baseline. - // Adjust the box Y position because the bounding box of a ShapeResult uses - // alphabetic baseline. - // See diagrams of base lines at - // https://drafts.csswg.org/css-writing-modes-3/#intro-baselines - const FontMetrics& font_metrics = run->font_data_->GetFontMetrics(); - int baseline_adjust = font_metrics.Ascent(kIdeographicBaseline) - - font_metrics.Ascent(kAlphabeticBaseline); - glyph_bounding_box.SetY(glyph_bounding_box.Y() + baseline_adjust); + harf_buzz_buffer); } - glyph_bounding_box_.Unite(glyph_bounding_box); width_ += run->width_; num_glyphs_ += num_glyphs; DCHECK_GE(num_glyphs_, num_glyphs); @@ -795,6 +826,54 @@ runs_.swap(new_runs); } +// Returns the left of the glyph bounding box of the left most character. +float ShapeResult::LineLeftBounds() const { + DCHECK(!runs_.IsEmpty()); + const RunInfo& run = *runs_.front(); + const bool is_horizontal_run = run.IsHorizontal(); + const SimpleFontData& font_data = *run.font_data_; + DCHECK(!run.glyph_data_.IsEmpty()) << ToString(); + const unsigned character_index = run.glyph_data_.front().character_index; + GlyphBoundsAccumulator bounds(0.f); + for (const auto& glyph : run.glyph_data_) { + if (character_index != glyph.character_index) + break; + bounds.Unite(is_horizontal_run, glyph, + font_data.BoundsForGlyph(glyph.glyph)); + bounds.origin += glyph.advance; + } + if (UNLIKELY(!is_horizontal_run)) + bounds.ConvertVerticalRunToLogical(font_data.GetFontMetrics()); + return bounds.bounds.X(); +} + +// Returns the right of the glyph bounding box of the right most character. +float ShapeResult::LineRightBounds() const { + DCHECK(!runs_.IsEmpty()); + const RunInfo& run = *runs_.back(); + const bool is_horizontal_run = run.IsHorizontal(); + const SimpleFontData& font_data = *run.font_data_; + DCHECK(!run.glyph_data_.IsEmpty()) << ToString(); + const unsigned character_index = run.glyph_data_.back().character_index; + GlyphBoundsAccumulator bounds(width_); + for (auto glyph_it = run.glyph_data_.rbegin(); + glyph_it != run.glyph_data_.rend(); ++glyph_it) { + const auto& glyph = *glyph_it; + if (character_index != glyph.character_index) + break; + bounds.origin -= glyph.advance; + bounds.Unite(is_horizontal_run, glyph, + font_data.BoundsForGlyph(glyph.glyph)); + } + // If the last character has no ink (e.g., space character), assume the + // character before will not overflow more than the width of the space. + if (UNLIKELY(bounds.bounds.IsEmpty())) + return width_; + if (UNLIKELY(!is_horizontal_run)) + bounds.ConvertVerticalRunToLogical(font_data.GetFontMetrics()); + return bounds.bounds.MaxX(); +} + void ShapeResult::CopyRange(unsigned start_offset, unsigned end_offset, ShapeResult* target) const { @@ -831,27 +910,31 @@ } } - if (target->runs_.size() == target_run_size_before) + if (!target->num_glyphs_) return; // Runs in RTL result are in visual order, and that new runs should be // prepended. Reorder appended runs. DCHECK_EQ(Rtl(), target->Rtl()); - if (target->Rtl()) + if (UNLIKELY(Rtl() && target->runs_.size() != target_run_size_before)) target->ReorderRtlRuns(target_run_size_before); // Compute new glyph bounding box. - // If |start_offset| or |end_offset| are the start/end of |this|, use - // |glyph_bounding_box_| from |this| for the side. Otherwise, we cannot - // compute accurate glyph bounding box; approximate by assuming there are no - // glyph overflow nor underflow. - float left = target->width_; + // + // Computing glyph bounding box from Font is one of the most expensive + // operations. If |start_offset| or |end_offset| are the start/end of |this|, + // use the current |glyph_bounding_box_| for the side. + DCHECK(primary_font_.get() == target->primary_font_.get()); + bool know_left_edge = start_offset <= StartIndexForResult(); + bool know_right_edge = end_offset >= EndIndexForResult(); + if (UNLIKELY(Rtl())) + std::swap(know_left_edge, know_right_edge); + float left = know_left_edge ? target->width_ + glyph_bounding_box_.X() + : target->LineLeftBounds(); target->width_ += total_width; - float right = target->width_; - if (start_offset <= StartIndexForResult()) - left += glyph_bounding_box_.X(); - if (end_offset >= EndIndexForResult()) - right += glyph_bounding_box_.MaxX() - width_; + float right = know_right_edge + ? glyph_bounding_box_.MaxX() - width_ + target->width_ + : target->LineRightBounds(); FloatRect adjusted_box(left, glyph_bounding_box_.Y(), std::max(right - left, 0.0f), glyph_bounding_box_.Height()); @@ -922,11 +1005,12 @@ float start_position = position; for (unsigned i = 0; i < count; i++) { float advance = font->TabWidth(font_data, text_run.GetTabSize(), position); - run->glyph_data_[i].character_index = i; - run->SetGlyphAndPositions(i, font_data->SpaceGlyph(), advance, 0, 0); + HarfBuzzRunGlyphData& glyph_data = run->glyph_data_[i]; + glyph_data.SetGlyphAndPositions(font_data->SpaceGlyph(), i, advance, + FloatSize()); // Assume it's safe to break after a tab character. - run->safe_break_offsets_.push_back(run->glyph_data_[i].character_index); + run->safe_break_offsets_.push_back(glyph_data.character_index); position += advance; } run->width_ = position - start_position;
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.h b/third_party/blink/renderer/platform/fonts/shaping/shape_result.h index c8a5c59..a48ac4bd 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.h +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.h
@@ -216,8 +216,7 @@ void ComputeGlyphPositions(ShapeResult::RunInfo*, unsigned start_glyph, unsigned num_glyphs, - hb_buffer_t*, - FloatRect* glyph_bounding_box); + hb_buffer_t*); void InsertRun(std::unique_ptr<ShapeResult::RunInfo>, unsigned start_glyph, unsigned num_glyphs, @@ -226,6 +225,9 @@ void InsertRunForIndex(unsigned start_character_index); void ReorderRtlRuns(unsigned run_size_before); + float LineLeftBounds() const; + float LineRightBounds() const; + float width_; FloatRect glyph_bounding_box_; Vector<std::unique_ptr<RunInfo>> runs_;
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h b/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h index c06fd1e..38a9178c 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h
@@ -48,6 +48,11 @@ uint16_t character_index; float advance; FloatSize offset; + + void SetGlyphAndPositions(uint16_t glyph_id, + uint16_t character_index, + float advance, + const FloatSize& offset); }; struct ShapeResult::RunInfo { @@ -88,11 +93,6 @@ float XPositionForVisualOffset(unsigned, AdjustMidCluster) const; float XPositionForOffset(unsigned, AdjustMidCluster) const; void CharacterIndexForXPosition(float, GlyphIndexResult*) const; - void SetGlyphAndPositions(unsigned index, - uint16_t glyph_id, - float advance, - float offset_x, - float offset_y); size_t GlyphToCharacterIndex(size_t i) const { return start_index_ + glyph_data_[i].character_index;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc index a4e33638..a3a8cae 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
@@ -247,8 +247,7 @@ base::BindRepeating(&MainThreadSchedulerImpl::UpdatePolicy, base::Unretained(this)), helper_.ControlMainThreadTaskQueue()), - seqlock_queueing_time_estimator_( - QueueingTimeEstimator(this, kQueueingTimeWindowDuration, 20)), + queueing_time_estimator_(this, kQueueingTimeWindowDuration, 20), main_thread_only_(this, compositor_task_queue_, helper_.GetClock(), @@ -595,8 +594,7 @@ MainThreadSchedulerImpl::AnyThread::~AnyThread() = default; MainThreadSchedulerImpl::CompositorThreadOnly::CompositorThreadOnly() - : last_input_type(blink::WebInputEvent::kUndefined), - main_thread_seems_unresponsive(false) {} + : last_input_type(blink::WebInputEvent::kUndefined) {} MainThreadSchedulerImpl::CompositorThreadOnly::~CompositorThreadOnly() = default; @@ -949,10 +947,8 @@ internal::ProcessState::Get()->is_process_backgrounded = backgrounded; main_thread_only().background_status_changed_at = tick_clock()->NowTicks(); - seqlock_queueing_time_estimator_.seqlock.WriteBegin(); - seqlock_queueing_time_estimator_.data.OnRendererStateChanged( + queueing_time_estimator_.OnRendererStateChanged( backgrounded, main_thread_only().background_status_changed_at); - seqlock_queueing_time_estimator_.seqlock.WriteEnd(); UpdatePolicy(); @@ -1229,10 +1225,6 @@ } } -base::TimeDelta MainThreadSchedulerImpl::MostRecentExpectedQueueingTime() { - return main_thread_only().most_recent_expected_queueing_time; -} - bool MainThreadSchedulerImpl::IsHighPriorityWorkAnticipated() { helper_.CheckOnValidThread(); if (helper_.IsShutdown()) @@ -2409,42 +2401,6 @@ main_thread_only().rail_mode_observer = observer; } -bool MainThreadSchedulerImpl::MainThreadSeemsUnresponsive( - base::TimeDelta main_thread_responsiveness_threshold) { - base::TimeTicks now = tick_clock()->NowTicks(); - base::TimeDelta estimated_queueing_time; - - bool can_read = false; - - base::subtle::Atomic32 version; - seqlock_queueing_time_estimator_.seqlock.TryRead(&can_read, &version); - - // If we fail to determine if the main thread is busy, assume whether or not - // it's busy hasn't change since the last time we asked. - if (!can_read) - return GetCompositorThreadOnly().main_thread_seems_unresponsive; - - QueueingTimeEstimator::State queueing_time_estimator_state = - seqlock_queueing_time_estimator_.data.GetState(); - - // If we fail to determine if the main thread is busy, assume whether or not - // it's busy hasn't change since the last time we asked. - if (seqlock_queueing_time_estimator_.seqlock.ReadRetry(version)) - return GetCompositorThreadOnly().main_thread_seems_unresponsive; - - QueueingTimeEstimator queueing_time_estimator(queueing_time_estimator_state); - - estimated_queueing_time = - queueing_time_estimator.EstimateQueueingTimeIncludingCurrentTask(now); - - bool main_thread_seems_unresponsive = - estimated_queueing_time > main_thread_responsiveness_threshold; - GetCompositorThreadOnly().main_thread_seems_unresponsive = - main_thread_seems_unresponsive; - - return main_thread_seems_unresponsive; -} - void MainThreadSchedulerImpl::SetRendererProcessType(RendererProcessType type) { main_thread_only().process_type = type; } @@ -2492,9 +2448,7 @@ const TaskQueue::Task& task, base::TimeTicks start) { main_thread_only().current_task_start_time = start; - seqlock_queueing_time_estimator_.seqlock.WriteBegin(); - seqlock_queueing_time_estimator_.data.OnTopLevelTaskStarted(start, queue); - seqlock_queueing_time_estimator_.seqlock.WriteEnd(); + queueing_time_estimator_.OnTopLevelTaskStarted(start, queue); main_thread_only().task_description_for_tracing = TaskDescriptionForTracing{ static_cast<TaskType>(task.task_type()), queue @@ -2509,9 +2463,7 @@ base::TimeTicks end, base::Optional<base::TimeDelta> thread_time) { DCHECK_LE(start, end); - seqlock_queueing_time_estimator_.seqlock.WriteBegin(); - seqlock_queueing_time_estimator_.data.OnTopLevelTaskCompleted(end); - seqlock_queueing_time_estimator_.seqlock.WriteEnd(); + queueing_time_estimator_.OnTopLevelTaskCompleted(end); if (queue) task_queue_throttler()->OnTaskRunTimeReported(queue, start, end); @@ -2588,9 +2540,7 @@ } void MainThreadSchedulerImpl::OnBeginNestedRunLoop() { - seqlock_queueing_time_estimator_.seqlock.WriteBegin(); - seqlock_queueing_time_estimator_.data.OnBeginNestedRunLoop(); - seqlock_queueing_time_estimator_.seqlock.WriteEnd(); + queueing_time_estimator_.OnBeginNestedRunLoop(); main_thread_only().nested_runloop = true; ApplyVirtualTimePolicy(); @@ -2622,8 +2572,6 @@ void MainThreadSchedulerImpl::OnQueueingTimeForWindowEstimated( base::TimeDelta queueing_time, bool is_disjoint_window) { - main_thread_only().most_recent_expected_queueing_time = queueing_time; - if (main_thread_only().has_navigated) { if (main_thread_only().max_queueing_time < queueing_time) { if (!main_thread_only().max_queueing_time_metric) {
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h index 5f077115..6cf5102 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
@@ -17,7 +17,6 @@ #include "base/synchronization/lock.h" #include "base/trace_event/trace_log.h" #include "build/build_config.h" -#include "device/base/synchronization/shared_memory_seqlock_buffer.h" #include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/scheduler/base/task_time_observer.h" @@ -110,7 +109,6 @@ InputEventState event_state) override; void DidHandleInputEventOnMainThread(const WebInputEvent& web_input_event, WebInputEventResult result) override; - base::TimeDelta MostRecentExpectedQueueingTime() override; void DidAnimateForInputOnCompositorThread() override; void SetRendererHidden(bool hidden) override; void SetRendererBackgrounded(bool backgrounded) override; @@ -135,8 +133,6 @@ void SetTopLevelBlameContext( base::trace_event::BlameContext* blame_context) override; void SetRAILModeObserver(RAILModeObserver* observer) override; - bool MainThreadSeemsUnresponsive( - base::TimeDelta main_thread_responsiveness_threshold) override; void SetRendererProcessType(RendererProcessType type) override; WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser( const char* name, @@ -641,10 +637,7 @@ DeadlineTaskRunner delayed_update_policy_runner_; CancelableClosureHolder end_renderer_hidden_idle_period_closure_; - using SeqLockQueueingTimeEstimator = - device::SharedMemorySeqLockBuffer<QueueingTimeEstimator>; - - SeqLockQueueingTimeEstimator seqlock_queueing_time_estimator_; + QueueingTimeEstimator queueing_time_estimator_; base::TimeDelta delay_for_background_tab_freezing_; @@ -667,7 +660,6 @@ base::TimeTicks current_policy_expiration_time; base::TimeTicks estimated_next_frame_begin; base::TimeTicks current_task_start_time; - base::TimeDelta most_recent_expected_queueing_time; base::TimeDelta compositor_frame_interval; TraceableCounter<base::TimeDelta, kTracingCategoryNameDebug> longest_jank_free_task_duration; @@ -775,7 +767,6 @@ ~CompositorThreadOnly(); WebInputEvent::Type last_input_type; - bool main_thread_seems_unresponsive; std::unique_ptr<base::ThreadChecker> compositor_thread_checker; void CheckOnValidThread() {
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc index 06d7656..c7bfb7e 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
@@ -596,14 +596,6 @@ base::nullopt); } - void GetQueueingTimeEstimatorLock() { - scheduler_->seqlock_queueing_time_estimator_.seqlock.WriteBegin(); - } - - void DropQueueingTimeEstimatorLock() { - scheduler_->seqlock_queueing_time_estimator_.seqlock.WriteEnd(); - } - void RunSlowCompositorTask() { // Run a long compositor task so that compositor tasks appear to be running // slow and thus compositor tasks will not be prioritized. @@ -710,10 +702,6 @@ MainThreadSchedulerImpl::kRailsResponseTimeMillis); } - static base::TimeDelta responsiveness_threshold() { - return base::TimeDelta::FromMilliseconds(200); - } - template <typename E> static void CallForEachEnumValue(E first, E last, @@ -3845,80 +3833,6 @@ base::TimeDelta::FromMilliseconds(1300))); } -TEST_F(MainThreadSchedulerImplTest, UnresponsiveMainThread) { - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - - // Add one second long task. - AdvanceTimeWithTask(1); - EXPECT_TRUE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - - // Wait a second. - clock_.Advance(base::TimeDelta::FromSecondsD(2)); - - AdvanceTimeWithTask(0.5); - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); -} - -// As |responsiveness_threshold| == expected queueing time threshold == 0.2s, -// for a task shorter than the length of the window (1s), the critical value of -// the length of task x can be calculated by (x/2) * (x/1) = 0.2, in which x = -// 0.6324. -TEST_F(MainThreadSchedulerImplTest, UnresponsiveMainThreadAboveThreshold) { - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - - AdvanceTimeWithTask(0.64); - EXPECT_TRUE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); -} - -// As |responsiveness_threshold| == expected queueing time threshold == 0.2s, -// for a task shorter than the length of the window (1s), the critical value of -// the length of task x can be calculated by (x/2) * (x/1) = 0.2, in which x = -// 0.6324. -TEST_F(MainThreadSchedulerImplTest, ResponsiveMainThreadBelowThreshold) { - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - - AdvanceTimeWithTask(0.63); - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); -} - -TEST_F(MainThreadSchedulerImplTest, ResponsiveMainThreadDuringTask) { - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - clock_.Advance(base::TimeDelta::FromSecondsD(2)); - scheduler_->OnTaskStarted(fake_queue_.get(), fake_task_, clock_.NowTicks()); - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); -} - -TEST_F(MainThreadSchedulerImplTest, UnresponsiveMainThreadWithContention) { - // Process a long task, lock the queueing time estimator, and check that we - // still report the main thread is unresponsive. - AdvanceTimeWithTask(1); - EXPECT_TRUE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - GetQueueingTimeEstimatorLock(); - EXPECT_TRUE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - - // Advance the clock, so that in the last second, we were responsive. - clock_.Advance(base::TimeDelta::FromSecondsD(2)); - // While the queueing time estimator is locked, we believe the thread to still - // be unresponsive. - EXPECT_TRUE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); - // Once we've dropped the lock, we realize the main thread is responsive. - DropQueueingTimeEstimatorLock(); - EXPECT_FALSE( - scheduler_->MainThreadSeemsUnresponsive(responsiveness_threshold())); -} - // Nav Start Nav Start assert // | | | // v v v
diff --git a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.cc b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.cc index 75a6ed7..7c7ae21 100644 --- a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.cc +++ b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.cc
@@ -367,45 +367,5 @@ DISALLOW_COPY_AND_ASSIGN(RecordQueueingTimeClient); }; -base::TimeDelta QueueingTimeEstimator::EstimateQueueingTimeIncludingCurrentTask( - base::TimeTicks now) const { - RecordQueueingTimeClient record_queueing_time_client; - - // Make a copy of this QueueingTimeEstimator. We'll use it to evaluate the - // estimated input latency, assuming that any active task ends now. - QueueingTimeEstimator::State temporary_queueing_time_estimator_state(state_); - - // If there's a task in progress, pretend it ends now, and include it in the - // computation. If there's no task in progress, add an empty task to flush any - // stale windows. - if (temporary_queueing_time_estimator_state.current_task_start_time - .is_null()) { - temporary_queueing_time_estimator_state.OnTopLevelTaskStarted( - &record_queueing_time_client, now, nullptr); - } - temporary_queueing_time_estimator_state.OnTopLevelTaskCompleted( - &record_queueing_time_client, now); - - // Report the max of the queueing time for the last window, or the on-going - // window (tmp window in chart) which includes the current task. - // - // Estimate - // | - // v - // Actual Task |-------------------------... - // Assumed Task |----------------| - // Time |---o---o---o---o---o---o--------> - // 0 1 2 3 4 5 6 - // | s | s | s | s | s | s | - // |----last window----| - // |----tmp window-----| - base::TimeDelta last_window_queueing_time = - record_queueing_time_client.queueing_time(); - temporary_queueing_time_estimator_state.calculator_.EndStep( - &record_queueing_time_client); - return std::max(last_window_queueing_time, - record_queueing_time_client.queueing_time()); -} - } // namespace scheduler } // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.h b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.h index b313126..c841c09 100644 --- a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.h +++ b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator.h
@@ -151,9 +151,6 @@ // Returns all state except for the current |client_|. const State& GetState() const { return state_; } - base::TimeDelta EstimateQueueingTimeIncludingCurrentTask( - base::TimeTicks now) const; - private: Client* client_; // NOT OWNED. State state_;
diff --git a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator_unittest.cc b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator_unittest.cc index 2bc28c73..f8a7c06 100644 --- a/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/renderer/queueing_time_estimator_unittest.cc
@@ -209,138 +209,6 @@ fine_grained); } -// The main thread is considered unresponsive during a single long task. In this -// case, the single long task is 3 seconds long. -// Probability of being with the task = 3/5. Expected delay within task: -// avg(0, 3). Total expected queueing time = 3/5 * 3/2 = 0.9s. -// In this example, the queueing time comes from the current, incomplete window. -TEST_F(QueueingTimeEstimatorTest, - EstimateQueueingTimeDuringSingleLongTaskIncompleteWindow) { - QueueingTimeEstimatorForTest estimator( - &client, base::TimeDelta::FromSeconds(5), 1, time); - time += base::TimeDelta::FromMilliseconds(5000); - estimator.OnTopLevelTaskStarted(time, nullptr); - estimator.OnTopLevelTaskCompleted(time); - - base::TimeTicks start_time = time; - estimator.OnTopLevelTaskStarted(start_time, nullptr); - - time += base::TimeDelta::FromMilliseconds(3000); - - base::TimeDelta estimated_queueing_time = - estimator.EstimateQueueingTimeIncludingCurrentTask(time); - - EXPECT_EQ(base::TimeDelta::FromMilliseconds(900), estimated_queueing_time); - // Window time was not completed, so no UMA should be recorded. - histogram_tester.ExpectTotalCount( - "RendererScheduler.ExpectedTaskQueueingDuration", 0); - histogram_tester.ExpectTotalCount("ExpectedTaskQueueingDuration2", 0); -} - -// The main thread is considered unresponsive during a single long task, which -// exceeds the size of one window. We report the queueing time of the most -// recent window. Probability of being within the task = 100%, as the task -// fills the whole window. Expected delay within this task = avg(8, 3) = 5.5. -TEST_F(QueueingTimeEstimatorTest, - EstimateQueueingTimeDuringSingleLongTaskExceedingWindow) { - QueueingTimeEstimatorForTest estimator( - &client, base::TimeDelta::FromSeconds(5), 1, time); - time += base::TimeDelta::FromMilliseconds(5000); - estimator.OnTopLevelTaskStarted(time, nullptr); - estimator.OnTopLevelTaskCompleted(time); - - base::TimeTicks start_time = time; - estimator.OnTopLevelTaskStarted(start_time, nullptr); - - time += base::TimeDelta::FromMilliseconds(13000); - - base::TimeDelta estimated_queueing_time = - estimator.EstimateQueueingTimeIncludingCurrentTask(time); - - EXPECT_EQ(base::TimeDelta::FromMilliseconds(5500), estimated_queueing_time); -} - -// Estimate -// | -// v -// Task|------------------------------... -// Time|---o---o---o---o---o---o--------> -// 0 1 2 3 4 5 6 -// | s | s | s | s | s | -// |--------win1-------| -// |--------win2-------| -// -// s: step window -// win1: The last full window. -// win2: The partial window. -// -// EQT(win1) = (0.5 + 5.5) / 2 * (5 / 5) = 3 -// EQT(win2) = (4.5 + 0) / 2 * (4.5 / 5) = 2.025 -// So EQT = max(EQT(win1), EQT(win2)) = 3 -TEST_F(QueueingTimeEstimatorTest, - SlidingWindowEstimateQueueingTimeFullWindowLargerThanPartial) { - QueueingTimeEstimatorForTest estimator( - &client, base::TimeDelta::FromSeconds(5), 5, time); - time += base::TimeDelta::FromMilliseconds(5000); - estimator.OnTopLevelTaskStarted(time, nullptr); - estimator.OnTopLevelTaskCompleted(time); - - base::TimeTicks start_time = time; - estimator.OnTopLevelTaskStarted(start_time, nullptr); - - time += base::TimeDelta::FromMilliseconds(5500); - - base::TimeDelta estimated_queueing_time = - estimator.EstimateQueueingTimeIncludingCurrentTask(time); - - EXPECT_EQ(base::TimeDelta::FromMilliseconds(3000), estimated_queueing_time); - // Only EstimateQueueingTimeIncludingCurrentTask has been called after window - // completion, so UMA should not have been reported yet. - histogram_tester.ExpectTotalCount( - "RendererScheduler.ExpectedTaskQueueingDuration", 0); - histogram_tester.ExpectTotalCount( - "RendererScheduler.ExpectedTaskQueueingDuration3", 0); -} - -// Estimate -// | -// v -// Task |----------... -// Time|---o---o---o---o---o---o--------> -// 0 1 2 3 4 5 6 -// | s | s | s | s | s | -// |--------win1-------| -// |--------win2-------| -// -// s: step window -// win1: The last full window. -// win2: The partial window. -// -// EQT(win1) = 0 -// EQT(win2) = (0 + 0.5) / 2 * (0.5 / 2) = 0.025 -// So EQT = max(EQT(win1), EQT(win2)) = 0.025 -TEST_F(QueueingTimeEstimatorTest, - SlidingWindowEstimateQueueingTimePartialWindowLargerThanFull) { - QueueingTimeEstimatorForTest estimator( - &client, base::TimeDelta::FromSeconds(5), 5, time); - time += base::TimeDelta::FromMilliseconds(5000); - estimator.OnTopLevelTaskStarted(time, nullptr); - estimator.OnTopLevelTaskCompleted(time); - - time += base::TimeDelta::FromMilliseconds(5000); - base::TimeTicks start_time = time; - estimator.OnTopLevelTaskStarted(start_time, nullptr); - time += base::TimeDelta::FromMilliseconds(500); - - base::TimeDelta estimated_queueing_time = - estimator.EstimateQueueingTimeIncludingCurrentTask(time); - - EXPECT_EQ(base::TimeDelta::FromMilliseconds(25), estimated_queueing_time); - std::vector<BucketExpectation> expected = {{0, 1}}; - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 1, expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 1, expected); -} - // Tasks containing nested run loops may be extremely long without // negatively impacting user experience. Ignore such tasks. TEST_F(QueueingTimeEstimatorTest, IgnoresTasksWithNestedMessageLoops) {
diff --git a/third_party/blink/renderer/platform/scheduler/test/fake_renderer_scheduler.cc b/third_party/blink/renderer/platform/scheduler/test/fake_renderer_scheduler.cc index 1a23557..efc592d01 100644 --- a/third_party/blink/renderer/platform/scheduler/test/fake_renderer_scheduler.cc +++ b/third_party/blink/renderer/platform/scheduler/test/fake_renderer_scheduler.cc
@@ -68,10 +68,6 @@ const blink::WebInputEvent& web_input_event, WebInputEventResult result) {} -base::TimeDelta FakeRendererScheduler::MostRecentExpectedQueueingTime() { - return base::TimeDelta(); -} - void FakeRendererScheduler::DidAnimateForInputOnCompositorThread() {} bool FakeRendererScheduler::IsHighPriorityWorkAnticipated() { @@ -122,11 +118,6 @@ void FakeRendererScheduler::SetRAILModeObserver(RAILModeObserver* observer) {} -bool FakeRendererScheduler::MainThreadSeemsUnresponsive( - base::TimeDelta main_thread_responsiveness_threshold) { - return false; -} - void FakeRendererScheduler::SetRendererProcessType(RendererProcessType type) {} WebScopedVirtualTimePauser
diff --git a/third_party/closure_compiler/compiled_resources2.gyp b/third_party/closure_compiler/compiled_resources2.gyp index 2a90cc2..c85f24e 100644 --- a/third_party/closure_compiler/compiled_resources2.gyp +++ b/third_party/closure_compiler/compiled_resources2.gyp
@@ -14,7 +14,6 @@ 'target_name': 'compiled_resources2', 'type': 'none', 'dependencies': [ - '<(DEPTH)/chrome/browser/resources/bookmark_manager/js/compiled_resources2.gyp:*', '<(DEPTH)/chrome/browser/resources/chromeos/braille_ime/compiled_resources2.gyp:*', '<(DEPTH)/chrome/browser/resources/chromeos/compiled_resources2.gyp:*', '<(DEPTH)/chrome/browser/resources/chromeos/login/compiled_resources2.gyp:*',
diff --git a/third_party/mesa/BUILD.gn b/third_party/mesa/BUILD.gn index 148b7ec8..875e67c 100644 --- a/third_party/mesa/BUILD.gn +++ b/third_party/mesa/BUILD.gn
@@ -137,9 +137,6 @@ # mesa's STATIC_ASSERT() macro expands to an ununused typedef. "-Wno-unused-local-typedef", - - # mesa's flex scanner code uses "register" a lot. - "-Wno-deprecated-register", ] } if (is_win) {
diff --git a/third_party/mesa/README.chromium b/third_party/mesa/README.chromium index 1d714ea..7bd148f 100644 --- a/third_party/mesa/README.chromium +++ b/third_party/mesa/README.chromium
@@ -23,6 +23,7 @@ - Checked in sources normally autogenerated during Mesa's build process under src/chromium_gensrc. + These files are generated with flex 2.6.1 and bison 3.0.4. - Checked in public headers normally autogenerated during Mesa's build process under include. @@ -68,7 +69,6 @@ - Statically link libstdc++ in chromecast build - Merge http://cgit.freedesktop.org/mesa/mesa/commit/?id=5a6ec26 - Regenerated glsl_lexer.cc using Linux 3.13.0-63 (Ubuntu 14.04), Flex 2.5.39. - update GLDEBUGPROCARB and GLDEBUGPROC typedef to latest spec version to avoid type mismatch between headers (making userParam a const GLvoid*).
diff --git a/tools/fuchsia/local-sdk.py b/tools/fuchsia/local-sdk.py index 1023a58..9d9cd6d 100755 --- a/tools/fuchsia/local-sdk.py +++ b/tools/fuchsia/local-sdk.py
@@ -38,14 +38,6 @@ '--args=is_debug=false', build_dir) Run('scripts/fx', 'full-build') - # Also build the deprecated bootfs-based image. - # TODO(crbug.com/805057): Remove this once bootfs is turned down. - build_dir_bootfs = 'out/release-' + arch + '-bootfs' - Run('scripts/fx', 'set', arch, - '--packages=garnet/packages/sdk/bootfs', '--args=is_debug=false', - '--args=bootfs_packages=true', build_dir_bootfs) - Run('scripts/fx', 'full-build') - def main(args): if len(args) != 1 or not os.path.isdir(args[0]):
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 274da73..f832032 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -8072,10 +8072,19 @@ </enum> <enum name="CrossOriginAd"> + <obsolete> + Removed April 2018. New metric uses CrossOriginAdStatus. + </obsolete> <int value="0" label="Main Frame Origin same as Ad"/> <int value="1" label="Main Frame Origin differs from Ad"/> </enum> +<enum name="CrossOriginAdStatus"> + <int value="0" label="Ad Origin indeterminable"/> + <int value="1" label="Main Frame Origin same as Ad"/> + <int value="2" label="Main Frame Origin differs from Ad"/> +</enum> + <enum name="CrossOriginAutoplayResult"> <int value="0" label="Allowed"/> <int value="1" label="Blocked"/> @@ -13439,7 +13448,8 @@ <int value="3" label="Cancelable and not canceled"/> <int value="4" label="Cancelable and canceled"/> <int value="5" label="Forced Non-Blocking Due to Fling"/> - <int value="6" label="Forced Non-Blocking Due to Unresponsive Main Thread"/> + <int value="6" + label="Forced Non-Blocking Due to Unresponsive Main Thread (deprecated)"/> </enum> <enum name="EventTimestampValidity"> @@ -17837,9 +17847,6 @@ <int value="1810" label="V8DeprecatedStorageQuota_QueryUsageAndQuota_Method"/> <int value="1811" label="V8DeprecatedStorageQuota_RequestQuota_Method"/> <int value="1812" label="V8FileReaderSync_Constructor"/> - <int value="1813" label="UncancelableTouchEventPreventDefaulted"/> - <int value="1814" - label="UncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted"/> <int value="1815" label="V8HTMLVideoElement_Poster_AttributeGetter"/> <int value="1816" label="V8HTMLVideoElement_Poster_AttributeSetter"/> <int value="1817" label="NotificationPermissionRequestedIframe"/> @@ -18476,6 +18483,12 @@ <int value="2422" label="CredentialManagerGetPublicKeyCredential"/> <int value="2423" label="CredentialManagerMakePublicKeyCredentialSuccess"/> <int value="2424" label="CredentialManagerGetPublicKeyCredentialSuccess"/> + <int value="2425" label="ShapeOutsideContentBox"/> + <int value="2426" label="ShapeOutsidePaddingBox"/> + <int value="2427" label="ShapeOutsideBorderBox"/> + <int value="2428" label="ShapeOutsideMarginBox"/> + <int value="2429" label="PerformanceTimeline"/> + <int value="2430" label="UserTiming"/> </enum> <enum name="FeedbackSource"> @@ -19726,6 +19739,17 @@ <int value="8" label="Overflow"/> </enum> +<enum name="GaiaTokenRevocationStatus"> + <int value="0" label="Success"/> + <int value="1" label="Connection Canceled"/> + <int value="2" label="Connection Failed"/> + <int value="3" label="Connection Time Out"/> + <int value="4" label="Invalid Token"/> + <int value="5" label="Invalid Request"/> + <int value="6" label="Server Error"/> + <int value="7" label="Unknown Error"/> +</enum> + <enum name="Gamma"> <int value="0" label="GammaLinear"/> <int value="1" label="GammaSRGB"/> @@ -41283,6 +41307,13 @@ <int value="1" label="Reauth Shown"/> </enum> +<enum name="SigninRefreshTokenRevocationRequestProgress"> + <int value="0" label="Request Created"/> + <int value="1" label="Request Started"/> + <int value="2" label="Request Succeeded"/> + <int value="3" label="Request Failed"/> +</enum> + <enum name="SigninSignoutProfile"> <int value="0" label="Preference changed"> The preference or policy controlling if signin is valid has changed. @@ -47716,6 +47747,18 @@ <int value="3" label="Not connected (Wake On WiFi disabled)"/> </enum> +<enum name="WiFiPCIStatus"> + <int value="0" label="(Bad status) NIC not detected in lspci"/> + <int value="1" + label="(Bad status) NIC shows in lspci but wlan0 doesnt exist"/> + <int value="2" + label="(Bad status) NIC shows in lspci, wlan0 present, shill doesn't + know"/> + <int value="3" + label="(Good status) NIC present, wlan0 present, shill knows about + wlan0"/> +</enum> + <enum name="WiFiReasonCode"> <int value="0" label="kReasonReserved0"/> <int value="1" label="kReasonCodeUnspecified"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 21d96e4..a1e41f3 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -13708,6 +13708,15 @@ </summary> </histogram> +<histogram name="Cryptohome.FreeDiskSpaceTotalTime" units="ms"> + <owner>loyso@chromium.org</owner> + <summary> + In low disk space scenarios, Cryptohome performs a lot of disk space + operations to erase data. This is a number of milliseconds taken to perform + a cleanup. Reported only if longer than 5 ms. + </summary> +</histogram> + <histogram name="Cryptohome.HomedirEncryptionType" enum="HomedirEncryptionType"> <owner>dspaid@chromium.org</owner> <summary> @@ -23222,6 +23231,9 @@ <histogram name="Event.PassiveListeners.ForcedNonBlockingLatencyDueToUnresponsiveMainThread" units="microseconds"> + <obsolete> + Deprecated 04/2018 due to cancellation of experiment. + </obsolete> <owner>tdresser@chromium.org</owner> <summary> Time between when a touchstart or first touchmove event per scroll was @@ -62516,6 +62528,9 @@ <histogram name="PageLoad.FrameCounts.AdFrames.PerFrame.CrossOrigin" enum="CrossOriginAd"> + <obsolete> + Removed April 2018, replaced by OriginStatus. + </obsolete> <owner>ericrobinson@chromium.org</owner> <summary> For each identified ad frame, whether the origin of the ad matches the @@ -62528,6 +62543,21 @@ </summary> </histogram> +<histogram name="PageLoad.FrameCounts.AdFrames.PerFrame.OriginStatus" + enum="CrossOriginAdStatus"> + <owner>ericrobinson@chromium.org</owner> + <summary> + For each identified ad frame, whether the origin of the ad matches the + origin of the main frame, differs from the origin of the main frame, or is + indeterminable. + + An ad frame consists of the identified ad frame and all of its children + (which may also be ads, but are counted as part of the ancestor ad frame). + Frames of zero bytes (e.g., never had a document or their document was + doc.written and no sub-resources were loaded) are not counted. + </summary> +</histogram> + <histogram name="PageLoad.FrameCounts.AnyParentFrame.AdFrames" units="Ad frames"> <owner>jkarlin@chromium.org</owner> @@ -67969,6 +67999,16 @@ </summary> </histogram> +<histogram name="Platform.WiFiStatusAfterForcedPCIRescan" enum="WiFiPCIStatus"> + <owner>rajatja@chromium.org</owner> + <owner>kirtika@chromium.org</owner> + <summary> + Shows the wifi status after the pci bus is rescanned to recover wifi. The UI + depends on shill noticing that wlan0 is back up, so the only happy case is + one where shill recognizes wlan0 after the rescan completes. + </summary> +</histogram> + <histogram name="Platform.WriteSectorsLong"> <owner>gwendal@google.com</owner> <summary> @@ -75215,6 +75255,9 @@ <histogram name="RendererScheduler.ExpectedQueueingTimeWhenQueueingTime" units="ms"> + <obsolete> + Deprecated 04/2018. + </obsolete> <owner>tdresser@chromium.org</owner> <summary> Expected queueing time for events which were queued on the main thread @@ -86641,6 +86684,25 @@ </summary> </histogram> +<histogram name="Signin.RefreshTokenRevocationRequestProgress" + enum="SigninRefreshTokenRevocationRequestProgress"> + <owner>droger@chromium.org</owner> + <summary> + Tracks the progress of revocation requests for refresh tokens, and can be + used to check how many requests do not complete and why. Recorded for each + refresh token revocation request from the token service. + </summary> +</histogram> + +<histogram name="Signin.RefreshTokenRevocationStatus" + enum="GaiaTokenRevocationStatus"> + <owner>droger@chromium.org</owner> + <summary> + Reports the status (including error details) of token revocation requests + after they complete. + </summary> +</histogram> + <histogram name="Signin.SignedInDurationBeforeSignout" units="minutes"> <owner>mlerman@chromium.org</owner> <summary> @@ -99098,6 +99160,14 @@ </summary> </histogram> +<histogram name="URLBlacklistManager.ConstructorBuildTime" units="ms"> + <owner>grt@chromium.org</owner> + <summary> + The time it took to build and set the URL blacklist on the main thread + within URLBlacklistManager's constructor. + </summary> +</histogram> + <histogram name="UrlFetcher.StringResponseSize" units="KB"> <obsolete> Removed 10/2017. @@ -107377,6 +107447,8 @@ <affected-histogram name="PageLoad.Bytes.NonAdFrames.Aggregate.Total"/> <affected-histogram name="PageLoad.FrameCounts.AdFrames.PerFrame.CrossOrigin"/> + <affected-histogram + name="PageLoad.FrameCounts.AdFrames.PerFrame.OriginStatus"/> <affected-histogram name="PageLoad.FrameCounts.AnyParentFrame.AdFrames"/> </histogram_suffixes> @@ -116087,6 +116159,9 @@ </histogram_suffixes> <histogram_suffixes name="QueueingTimeThreshold" separator="_"> + <obsolete> + Deprecated 04/2018. + </obsolete> <suffix name="GreaterThan.10ms" label="Queueing Time greater than 10ms."/> <suffix name="GreaterThan.150ms" label="Queueing Time greater than 150ms."/> <suffix name="GreaterThan.300ms" label="Queueing Time greater than 300ms."/>
diff --git a/ui/gfx/paint_vector_icon.cc b/ui/gfx/paint_vector_icon.cc index b60aab1..95992eb 100644 --- a/ui/gfx/paint_vector_icon.cc +++ b/ui/gfx/paint_vector_icon.cc
@@ -28,10 +28,16 @@ namespace { +// The default size of a single side of the square canvas to which path +// coordinates are relative, in device independent pixels. +constexpr int kReferenceSizeDip = 48; + +constexpr int kEmptyIconSize = -1; + // Retrieves the specified CANVAS_DIMENSIONS size from a PathElement. int GetCanvasDimensions(const PathElement* path) { if (!path) - return kReferenceSizeDip; + return kEmptyIconSize; return path[0].command == CANVAS_DIMENSIONS ? path[1].arg : kReferenceSizeDip; } @@ -621,7 +627,12 @@ int GetDefaultSizeOfVectorIcon(const VectorIcon& icon) { if (icon.is_empty()) - return -1; + return kEmptyIconSize; + DCHECK_EQ(icon.reps[icon.reps_size - 1].path[0].command, CANVAS_DIMENSIONS) + << " " << icon.name + << " has no size in its icon definition, and it seems unlikely you want " + "to display at the default of 48dip. Please specify a size in " + "CreateVectorIcon()."; const PathElement* default_icon_path = icon.reps[icon.reps_size - 1].path; return GetCanvasDimensions(default_icon_path); }
diff --git a/ui/gfx/vector_icon_types.h b/ui/gfx/vector_icon_types.h index 195de85a..58e8bf9a 100644 --- a/ui/gfx/vector_icon_types.h +++ b/ui/gfx/vector_icon_types.h
@@ -11,10 +11,6 @@ namespace gfx { -// The size of a single side of the square canvas to which path coordinates -// are relative, in device independent pixels. -const int kReferenceSizeDip = 48; - // A command to Skia. enum CommandType { // A new <path> element. For the first path, this is assumed. @@ -47,7 +43,7 @@ CIRCLE, ROUND_RECT, CLOSE, - // Sets the dimensions of the canvas in dip. (Default is kReferenceSizeDip.) + // Sets the dimensions of the canvas in dip. CANVAS_DIMENSIONS, // Sets a bounding rect for the path. This allows fine adjustment because it // can tweak edge anti-aliasing. Args are x, y, w, h.
diff --git a/ui/latency/ipc/latency_info_param_traits.cc b/ui/latency/ipc/latency_info_param_traits.cc index 0023028..efe35b7b 100644 --- a/ui/latency/ipc/latency_info_param_traits.cc +++ b/ui/latency/ipc/latency_info_param_traits.cc
@@ -40,7 +40,6 @@ WriteParam(m, p.began_); WriteParam(m, p.terminated_); WriteParam(m, p.source_event_type_); - WriteParam(m, p.expected_queueing_time_on_dispatch_); } bool ParamTraits<ui::LatencyInfo>::Read(const base::Pickle* m, @@ -63,8 +62,6 @@ return false; if (!ReadParam(m, iter, &p->source_event_type_)) return false; - if (!ReadParam(m, iter, &p->expected_queueing_time_on_dispatch_)) - return false; return true; } @@ -85,8 +82,6 @@ LogParam(p.terminated_, l); l->append(" "); LogParam(p.source_event_type_, l); - l->append(" "); - LogParam(p.expected_queueing_time_on_dispatch_, l); } } // namespace IPC
diff --git a/ui/latency/latency_info.cc b/ui/latency/latency_info.cc index 52f2c1d..7a11d46b 100644 --- a/ui/latency/latency_info.cc +++ b/ui/latency/latency_info.cc
@@ -206,9 +206,6 @@ } } - expected_queueing_time_on_dispatch_ = - other.expected_queueing_time_on_dispatch_; - coalesced_ = other.coalesced(); // TODO(tdresser): Ideally we'd copy |began_| here as well, but |began_| // isn't very intuitive, and we can actually begin multiple times across @@ -236,9 +233,6 @@ } } - expected_queueing_time_on_dispatch_ = - other.expected_queueing_time_on_dispatch_; - coalesced_ = other.coalesced(); // TODO(tdresser): Ideally we'd copy |began_| here as well, but |began_| isn't // very intuitive, and we can actually begin multiple times across copied
diff --git a/ui/latency/latency_info.h b/ui/latency/latency_info.h index d9d3908..1269fbe 100644 --- a/ui/latency/latency_info.h +++ b/ui/latency/latency_info.h
@@ -223,15 +223,6 @@ source_event_type_ = type; } - void set_expected_queueing_time_on_dispatch( - base::TimeDelta expected_queueing_time) { - expected_queueing_time_on_dispatch_ = expected_queueing_time; - } - - base::TimeDelta expected_queueing_time_on_dispatch() const { - return expected_queueing_time_on_dispatch_; - } - bool began() const { return began_; } bool terminated() const { return terminated_; } void set_coalesced() { coalesced_ = true; } @@ -273,9 +264,6 @@ bool terminated_; // Stores the type of the first source event. SourceEventType source_event_type_; - // The expected queueing time on the main thread when this event was - // dispatched. - base::TimeDelta expected_queueing_time_on_dispatch_; #if !defined(OS_IOS) friend struct IPC::ParamTraits<ui::LatencyInfo>;
diff --git a/ui/latency/mojo/latency_info.mojom b/ui/latency/mojo/latency_info.mojom index 1b0e5e8..339bd73 100644 --- a/ui/latency/mojo/latency_info.mojom +++ b/ui/latency/mojo/latency_info.mojom
@@ -128,5 +128,4 @@ bool began; bool terminated; SourceEventType source_event_type; - mojo_base.mojom.TimeDelta expected_queueing_time_on_dispatch; };
diff --git a/ui/latency/mojo/latency_info_struct_traits.cc b/ui/latency/mojo/latency_info_struct_traits.cc index 2e44de6..74fe873 100644 --- a/ui/latency/mojo/latency_info_struct_traits.cc +++ b/ui/latency/mojo/latency_info_struct_traits.cc
@@ -360,12 +360,6 @@ } // static -base::TimeDelta StructTraits<ui::mojom::LatencyInfoDataView, ui::LatencyInfo>:: - expected_queueing_time_on_dispatch(const ui::LatencyInfo& info) { - return info.expected_queueing_time_on_dispatch(); -} - -// static bool StructTraits<ui::mojom::LatencyInfoDataView, ui::LatencyInfo>::Read( ui::mojom::LatencyInfoDataView data, ui::LatencyInfo* out) { @@ -392,8 +386,7 @@ out->terminated_ = data.terminated(); out->source_event_type_ = MojoSourceEventTypeToUI(data.source_event_type()); - return data.ReadExpectedQueueingTimeOnDispatch( - &out->expected_queueing_time_on_dispatch_); + return true; } } // namespace mojo
diff --git a/ui/latency/mojo/latency_info_struct_traits.h b/ui/latency/mojo/latency_info_struct_traits.h index 4fc347e..31c6de4 100644 --- a/ui/latency/mojo/latency_info_struct_traits.h +++ b/ui/latency/mojo/latency_info_struct_traits.h
@@ -101,8 +101,6 @@ static bool terminated(const ui::LatencyInfo& info); static ui::mojom::SourceEventType source_event_type( const ui::LatencyInfo& info); - static base::TimeDelta expected_queueing_time_on_dispatch( - const ui::LatencyInfo& info); static bool Read(ui::mojom::LatencyInfoDataView data, ui::LatencyInfo* out); };
diff --git a/ui/views/controls/webview/webview.cc b/ui/views/controls/webview/webview.cc index 74a13e1c..161185a 100644 --- a/ui/views/controls/webview/webview.cc +++ b/ui/views/controls/webview/webview.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/no_destructor.h" #include "build/build_config.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_context.h" @@ -23,6 +24,27 @@ namespace views { +namespace { + +// A testing stub that creates web contents. +WebView::WebContentsCreator* GetCreatorForTesting() { + static base::NoDestructor<WebView::WebContentsCreator> creator; + return creator.get(); +} + +} // namespace + +WebView::ScopedWebContentsCreatorForTesting::ScopedWebContentsCreatorForTesting( + WebContentsCreator creator) { + DCHECK(!*GetCreatorForTesting()); + *GetCreatorForTesting() = creator; +} + +WebView::ScopedWebContentsCreatorForTesting:: + ~ScopedWebContentsCreatorForTesting() { + *GetCreatorForTesting() = WebView::WebContentsCreator(); +} + // static const char WebView::kViewClassName[] = "WebView"; @@ -44,7 +66,7 @@ content::WebContents* WebView::GetWebContents() { if (!web_contents()) { - wc_owner_.reset(CreateWebContents(browser_context_)); + wc_owner_ = CreateWebContents(browser_context_); wc_owner_->SetDelegate(this); SetWebContents(wc_owner_.get()); } @@ -380,12 +402,11 @@ NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, false); } -content::WebContents* WebView::CreateWebContents( - content::BrowserContext* browser_context) { - content::WebContents* contents = NULL; - if (ViewsDelegate::GetInstance()) { - contents = - ViewsDelegate::GetInstance()->CreateWebContents(browser_context, NULL); +std::unique_ptr<content::WebContents> WebView::CreateWebContents( + content::BrowserContext* browser_context) { + std::unique_ptr<content::WebContents> contents; + if (*GetCreatorForTesting()) { + contents = GetCreatorForTesting()->Run(browser_context); } if (!contents) {
diff --git a/ui/views/controls/webview/webview.h b/ui/views/controls/webview/webview.h index 99affc1..87d9a1e7 100644 --- a/ui/views/controls/webview/webview.h +++ b/ui/views/controls/webview/webview.h
@@ -9,6 +9,7 @@ #include <memory> +#include "base/callback.h" #include "base/macros.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" @@ -94,6 +95,20 @@ const char* GetClassName() const override; NativeViewHost* holder() { return holder_; } + using WebContentsCreator = + base::RepeatingCallback<std::unique_ptr<content::WebContents>( + content::BrowserContext*)>; + + // An instance of this class registers a WebContentsCreator on construction + // and deregisters the WebContentsCreator on destruction. + class WEBVIEW_EXPORT ScopedWebContentsCreatorForTesting { + public: + explicit ScopedWebContentsCreatorForTesting(WebContentsCreator creator); + ~ScopedWebContentsCreatorForTesting(); + + private: + DISALLOW_COPY_AND_ASSIGN(ScopedWebContentsCreatorForTesting); + }; protected: // Swaps the owned WebContents |wc_owner_| with |new_web_contents|. Returns @@ -154,7 +169,7 @@ // Create a regular or test web contents (based on whether we're running // in a unit test or not). - content::WebContents* CreateWebContents( + std::unique_ptr<content::WebContents> CreateWebContents( content::BrowserContext* browser_context); NativeViewHost* const holder_;
diff --git a/ui/views/controls/webview/webview_unittest.cc b/ui/views/controls/webview/webview_unittest.cc index c2b5a70..3e82c4f5 100644 --- a/ui/views/controls/webview/webview_unittest.cc +++ b/ui/views/controls/webview/webview_unittest.cc
@@ -33,24 +33,6 @@ namespace { -// Provides functionality to create a test WebContents. -class WebViewTestViewsDelegate : public views::TestViewsDelegate { - public: - WebViewTestViewsDelegate() {} - ~WebViewTestViewsDelegate() override {} - - // Overriden from TestViewsDelegate. - content::WebContents* CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance) override { - return content::WebContentsTester::CreateTestWebContents(browser_context, - site_instance); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WebViewTestViewsDelegate); -}; - // Provides functionality to observe events on a WebContents like // OnVisibilityChanged/WebContentsDestroyed. class WebViewTestWebContentsObserver : public content::WebContentsObserver { @@ -146,8 +128,19 @@ ~WebViewUnitTest() override {} + std::unique_ptr<content::WebContents> CreateWebContentsForWebView( + content::BrowserContext* browser_context) { + return base::WrapUnique(content::WebContentsTester::CreateTestWebContents( + browser_context, nullptr)); + } + void SetUp() override { - set_views_delegate(base::WrapUnique(new WebViewTestViewsDelegate)); + views::WebView::WebContentsCreator creator = base::BindRepeating( + &WebViewUnitTest::CreateWebContentsForWebView, base::Unretained(this)); + scoped_web_contents_creator_ = + std::make_unique<views::WebView::ScopedWebContentsCreatorForTesting>( + creator); + set_views_delegate(base::WrapUnique(new views::TestViewsDelegate)); browser_context_.reset(new content::TestBrowserContext); WidgetTest::SetUp(); // Set the test content browser client to avoid pulling in needless @@ -171,6 +164,7 @@ } void TearDown() override { + scoped_web_contents_creator_.reset(); top_level_widget_->Close(); // Deletes all children and itself. RunPendingMessages(); @@ -187,14 +181,16 @@ NativeViewHost* holder() const { return web_view_->holder_; } std::unique_ptr<content::WebContents> CreateWebContents() const { - return base::WrapUnique(content::WebContents::Create( - content::WebContents::CreateParams(browser_context_.get()))); + return content::WebContents::Create( + content::WebContents::CreateParams(browser_context_.get())); } private: content::TestBrowserThreadBundle test_browser_thread_bundle_; std::unique_ptr<content::TestBrowserContext> browser_context_; content::TestContentBrowserClient test_browser_client_; + std::unique_ptr<views::WebView::ScopedWebContentsCreatorForTesting> + scoped_web_contents_creator_; Widget* top_level_widget_ = nullptr; WebView* web_view_ = nullptr;
diff --git a/ui/views/views_delegate.cc b/ui/views/views_delegate.cc index a64b2cb2..7b303dac 100644 --- a/ui/views/views_delegate.cc +++ b/ui/views/views_delegate.cc
@@ -100,12 +100,6 @@ void ViewsDelegate::ReleaseRef() { } -content::WebContents* ViewsDelegate::CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance) { - return nullptr; -} - base::TimeDelta ViewsDelegate::GetTextfieldPasswordRevealDuration() { return base::TimeDelta(); }
diff --git a/ui/views/views_delegate.h b/ui/views/views_delegate.h index cfaf7b0..8f70348 100644 --- a/ui/views/views_delegate.h +++ b/ui/views/views_delegate.h
@@ -27,12 +27,6 @@ class TimeDelta; } -namespace content { -class WebContents; -class BrowserContext; -class SiteInstance; -} - namespace gfx { class ImageSkia; class Rect; @@ -175,11 +169,6 @@ virtual void AddRef(); virtual void ReleaseRef(); - // Creates a web contents. This will return NULL unless overriden. - virtual content::WebContents* CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance); - // Gives the platform a chance to modify the properties of a Widget. virtual void OnBeforeWidgetInit(Widget::InitParams* params, internal::NativeWidgetDelegate* delegate) = 0;