diff --git a/DEPS b/DEPS index aade831..e19f5a7a 100644 --- a/DEPS +++ b/DEPS
@@ -199,11 +199,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': '011a77357ec4a6b583417a875a337dc3ae34a416', + 'skia_revision': '554e7574e960d48605156948ab658fd19b16697f', # 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': '1c9380eba0e26de8661d3b1c69778082b4771b2b', + 'v8_revision': '53a11922d89285a3f15744d59e0cfcff2dd33f91', # 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. @@ -211,11 +211,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'dea86294537c612e1f0d72d9b29b7ecb1a76dbd3', + 'angle_revision': 'a13f6847238e7e74fcb9a81caeb810800c8a8fef', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '7bcd79eccf28007fe7a60ed50251d91ea4e65674', + 'swiftshader_revision': '84b9bb6621c7eae8da034d31aceab780d8b1abdc', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -274,7 +274,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '57c86890de5feb413493f8f0b3b2a5f73d4967d0', + 'devtools_frontend_revision': '53fee9259fa3f1eeb1cfefbc00fbfdc8018eb2c7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -326,7 +326,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '042184128efea90552495d5054c3ae17b84cb3c3', + 'dawn_revision': '8a73e1876dbd2d862701fde91bc21630c4bd0e5b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -562,7 +562,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '1d2349b616ed4d24b5a66aadbfeb11d52849d9a1', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '0807c24b05bb588acede2152f2fca7d591ed0a1c', 'condition': 'checkout_ios', }, @@ -918,7 +918,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '3b055d329e60963cb8a7de7b4baec2202fe3eb60', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1742f98791c9ae6535f149cf3f0dc89ed0be3241', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1368,7 +1368,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/aemu/linux-amd64', - 'version': '_Al4vzs8u2wU-GYPWCG5soPJ7bitM8J9Yf85PjKhnAwC' + 'version': 'FZmiNfUmb6lJR28DxZkS03xoY4oJh4177LjCbVwbpCMC' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1612,7 +1612,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@fa2c56d16d1c61f699599a036154595f30966ff9', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@9f9233f23f55ac96d58c06a7176791e3d56b9e97', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index bda70a6..5bab2b53 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -2952,6 +2952,11 @@ '*.fidl', ] + # Don't check for owners files for changes in these directories. + exclude_paths = [ + 'third_party/crashpad/*', + ] + def AddPatternToCheck(input_file, pattern): owners_file = input_api.os_path.join( input_api.os_path.dirname(input_file.LocalPath()), 'OWNERS') @@ -2971,6 +2976,13 @@ # for. We should only nag patch authors about per-file rules if a file in that # directory would match that pattern. for f in input_api.AffectedFiles(include_deletes=False): + skip = False + for exclude in exclude_paths: + if input_api.fnmatch.fnmatch(f.LocalPath(), exclude): + skip = True + if skip: + continue + for pattern in file_patterns: if input_api.fnmatch.fnmatch( input_api.os_path.basename(f.LocalPath()), pattern):
diff --git a/PRESUBMIT_test.py b/PRESUBMIT_test.py index 3dbbb77b..85c5eb2 100755 --- a/PRESUBMIT_test.py +++ b/PRESUBMIT_test.py
@@ -2157,6 +2157,18 @@ 'Found OWNERS files that need to be updated for IPC security review ' + 'coverage.\nPlease update the OWNERS files below:', errors[0].message) + def testThirdPartyTestsDoNotRequireSecurityOwner(self): + mock_input_api = MockInputApi() + mock_input_api.files = [ + MockAffectedFile('third_party/crashpad/test/tests.cmx', + [ + 'const char kNoEnforcement[] = "Security?!? Pah!";', + ])] + mock_output_api = MockOutputApi() + errors = PRESUBMIT.CheckSecurityOwners( + mock_input_api, mock_output_api) + self.assertEqual([], errors) + def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self): mock_input_api = MockInputApi() mock_input_api.files = [
diff --git a/android_webview/java/src/org/chromium/android_webview/AwWebContentsObserver.java b/android_webview/java/src/org/chromium/android_webview/AwWebContentsObserver.java index 8fb71f2..226a6e121 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwWebContentsObserver.java +++ b/android_webview/java/src/org/chromium/android_webview/AwWebContentsObserver.java
@@ -13,6 +13,7 @@ import org.chromium.content_public.common.ContentUrlConstants; import org.chromium.net.NetError; import org.chromium.ui.base.PageTransition; +import org.chromium.url.GURL; import java.lang.ref.WeakReference; @@ -52,18 +53,20 @@ } @Override - public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) { + public void didFinishLoad(long frameId, GURL url, boolean isKnownValid, boolean isMainFrame) { + String validatedUrl = isKnownValid ? url.getSpec() : url.getPossiblyInvalidSpec(); if (isMainFrame && getClientIfNeedToFireCallback(validatedUrl) != null) { mLastDidFinishLoadUrl = validatedUrl; } } @Override - public void didStopLoading(String validatedUrl) { - if (validatedUrl.length() == 0) validatedUrl = ContentUrlConstants.ABOUT_BLANK_DISPLAY_URL; - AwContentsClient client = getClientIfNeedToFireCallback(validatedUrl); - if (client != null && validatedUrl.equals(mLastDidFinishLoadUrl)) { - client.getCallbackHelper().postOnPageFinished(validatedUrl); + public void didStopLoading(GURL gurl, boolean isKnownValid) { + String url = isKnownValid ? gurl.getSpec() : gurl.getPossiblyInvalidSpec(); + if (url.length() == 0) url = ContentUrlConstants.ABOUT_BLANK_DISPLAY_URL; + AwContentsClient client = getClientIfNeedToFireCallback(url); + if (client != null && url.equals(mLastDidFinishLoadUrl)) { + client.getCallbackHelper().postOnPageFinished(url); mLastDidFinishLoadUrl = null; } } @@ -76,7 +79,8 @@ } @Override - public void didFailLoad(boolean isMainFrame, @NetError int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, @NetError int errorCode, GURL failingGurl) { + String failingUrl = failingGurl.getPossiblyInvalidSpec(); AwContentsClient client = mAwContentsClient.get(); if (client == null) return; String unreachableWebDataUrl = AwContentsStatics.getUnreachableWebDataUrl(); @@ -109,7 +113,7 @@ public void didFinishNavigation(NavigationHandle navigation) { String url = navigation.getUrlString(); if (navigation.errorCode() != NetError.OK && !navigation.isDownload()) { - didFailLoad(navigation.isInMainFrame(), navigation.errorCode(), url); + didFailLoad(navigation.isInMainFrame(), navigation.errorCode(), navigation.getUrl()); } if (!navigation.hasCommitted()) return;
diff --git a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java index 13178f2e..07f5fa2 100644 --- a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java +++ b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java
@@ -104,7 +104,8 @@ Flag.baseFeature(AwFeatures.WEBVIEW_MIXED_CONTENT_AUTOUPGRADES, "Enables autoupgrades for audio/video/image mixed content when mixed content " + "mode is set to MIXED_CONTENT_COMPATIBILITY_MODE"), - Flag.baseFeature( - UiFeatures.SWIPE_TO_MOVE_CURSOR, "Enables swipe to move cursor feature."), + Flag.baseFeature(UiFeatures.SWIPE_TO_MOVE_CURSOR, + "Enables swipe to move cursor feature." + + "This flag will only take effect on Android 11 and above."), }; }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwContentCaptureTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwContentCaptureTest.java index 410598b..6fa88e5 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwContentCaptureTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwContentCaptureTest.java
@@ -21,6 +21,7 @@ import org.chromium.android_webview.AwContents; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.FlakyTest; import org.chromium.components.content_capture.ContentCaptureConsumer; @@ -593,6 +594,7 @@ @Test @SmallTest @Feature({"AndroidWebView"}) + @DisabledTest(message = "https://crbug.com/1156418") public void testChangeContent() throws Throwable { final String response = "<html><head></head><body>" + "<div id='editable_id'>Hello</div>"
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwWebContentsObserverTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwWebContentsObserverTest.java index ad71fada..7531161 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwWebContentsObserverTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwWebContentsObserverTest.java
@@ -34,16 +34,19 @@ private AwTestContainerView mTestContainerView; private AwWebContentsObserver mWebContentsObserver; - private static final String EXAMPLE_URL = "http://www.example.com/"; - private static final String EXAMPLE_URL_WITH_FRAGMENT = "http://www.example.com/#anchor"; - private static final String SYNC_URL = "http://example.org/"; - private String mUnreachableWebDataUrl; + private GURL mExampleURL; + private GURL mExampleURLWithFragment; + private GURL mSyncURL; + private GURL mUnreachableWebDataUrl; @Before public void setUp() { mContentsClient = new TestAwContentsClient(); mTestContainerView = mActivityTestRule.createAwTestContainerViewOnMainSync(mContentsClient); - mUnreachableWebDataUrl = AwContentsStatics.getUnreachableWebDataUrl(); + mUnreachableWebDataUrl = new GURL(AwContentsStatics.getUnreachableWebDataUrl()); + mExampleURL = new GURL("http://www.example.com/"); + mExampleURLWithFragment = new GURL("http://www.example.com/#anchor"); + mSyncURL = new GURL("http://example.org/"); // AwWebContentsObserver constructor must be run on the UI thread. InstrumentationRegistry.getInstrumentation().runOnMainSync( () -> mWebContentsObserver = @@ -62,37 +65,37 @@ mContentsClient.getOnPageFinishedHelper(); int callCount = onPageFinishedHelper.getCallCount(); - mWebContentsObserver.didFinishLoad(frameId, EXAMPLE_URL, mainFrame); - mWebContentsObserver.didStopLoading(EXAMPLE_URL); + mWebContentsObserver.didFinishLoad(frameId, mExampleURL, true, mainFrame); + mWebContentsObserver.didStopLoading(mExampleURL, true); onPageFinishedHelper.waitForCallback(callCount); Assert.assertEquals("onPageFinished should be called for main frame navigations.", callCount + 1, onPageFinishedHelper.getCallCount()); Assert.assertEquals("onPageFinished should be called for main frame navigations.", - EXAMPLE_URL, onPageFinishedHelper.getUrl()); + mExampleURL.getSpec(), onPageFinishedHelper.getUrl()); // In order to check that callbacks are *not* firing, first we execute code // that shoudn't emit callbacks, then code that emits a callback, and check that we // have got only one callback, and that its URL is from the last call. Since // callbacks are serialized, that means we didn't have a callback for the first call. callCount = onPageFinishedHelper.getCallCount(); - mWebContentsObserver.didFinishLoad(frameId, EXAMPLE_URL, subFrame); - mWebContentsObserver.didFinishLoad(frameId, SYNC_URL, mainFrame); - mWebContentsObserver.didStopLoading(SYNC_URL); + mWebContentsObserver.didFinishLoad(frameId, mExampleURL, true, subFrame); + mWebContentsObserver.didFinishLoad(frameId, mSyncURL, true, mainFrame); + mWebContentsObserver.didStopLoading(mSyncURL, true); onPageFinishedHelper.waitForCallback(callCount); Assert.assertEquals("onPageFinished should only be called for the main frame.", callCount + 1, onPageFinishedHelper.getCallCount()); - Assert.assertEquals("onPageFinished should only be called for the main frame.", SYNC_URL, - onPageFinishedHelper.getUrl()); + Assert.assertEquals("onPageFinished should only be called for the main frame.", + mSyncURL.getSpec(), onPageFinishedHelper.getUrl()); callCount = onPageFinishedHelper.getCallCount(); - mWebContentsObserver.didFinishLoad(frameId, mUnreachableWebDataUrl, mainFrame); - mWebContentsObserver.didFinishLoad(frameId, SYNC_URL, mainFrame); - mWebContentsObserver.didStopLoading(SYNC_URL); + mWebContentsObserver.didFinishLoad(frameId, mUnreachableWebDataUrl, false, mainFrame); + mWebContentsObserver.didFinishLoad(frameId, mSyncURL, true, mainFrame); + mWebContentsObserver.didStopLoading(mSyncURL, true); onPageFinishedHelper.waitForCallback(callCount); Assert.assertEquals("onPageFinished should not be called for the error url.", callCount + 1, onPageFinishedHelper.getCallCount()); - Assert.assertEquals("onPageFinished should not be called for the error url.", SYNC_URL, - onPageFinishedHelper.getUrl()); + Assert.assertEquals("onPageFinished should not be called for the error url.", + mSyncURL.getSpec(), onPageFinishedHelper.getUrl()); String baseUrl = null; boolean isInMainFrame = true; @@ -103,21 +106,21 @@ int errorCode = 0; int httpStatusCode = 200; callCount = onPageFinishedHelper.getCallCount(); - simulateNavigation(EXAMPLE_URL, isInMainFrame, isErrorPage, !isSameDocument, + simulateNavigation(mExampleURL, isInMainFrame, isErrorPage, !isSameDocument, !fragmentNavigation, !isRendererInitiated, PageTransition.TYPED); - simulateNavigation(EXAMPLE_URL_WITH_FRAGMENT, isInMainFrame, isErrorPage, isSameDocument, + simulateNavigation(mExampleURLWithFragment, isInMainFrame, isErrorPage, isSameDocument, fragmentNavigation, isRendererInitiated, PageTransition.TYPED); onPageFinishedHelper.waitForCallback(callCount); Assert.assertEquals("onPageFinished should be called for main frame fragment navigations.", callCount + 1, onPageFinishedHelper.getCallCount()); Assert.assertEquals("onPageFinished should be called for main frame fragment navigations.", - EXAMPLE_URL_WITH_FRAGMENT, onPageFinishedHelper.getUrl()); + mExampleURLWithFragment.getSpec(), onPageFinishedHelper.getUrl()); callCount = onPageFinishedHelper.getCallCount(); - simulateNavigation(EXAMPLE_URL, isInMainFrame, isErrorPage, !isSameDocument, + simulateNavigation(mExampleURL, isInMainFrame, isErrorPage, !isSameDocument, !fragmentNavigation, !isRendererInitiated, PageTransition.TYPED); - mWebContentsObserver.didFinishLoad(frameId, SYNC_URL, mainFrame); - mWebContentsObserver.didStopLoading(SYNC_URL); + mWebContentsObserver.didFinishLoad(frameId, mSyncURL, true, mainFrame); + mWebContentsObserver.didStopLoading(mSyncURL, true); onPageFinishedHelper.waitForCallback(callCount); onPageFinishedHelper.waitForCallback(callCount); Assert.assertEquals( @@ -125,15 +128,14 @@ callCount + 1, onPageFinishedHelper.getCallCount()); Assert.assertEquals( "onPageFinished should be called only for main frame fragment navigations.", - SYNC_URL, onPageFinishedHelper.getUrl()); + mSyncURL.getSpec(), onPageFinishedHelper.getUrl()); } @Test @SmallTest @Feature({"AndroidWebView"}) public void testDidFinishNavigation() throws Throwable { - String emptyUrl = ""; - String baseUrl = null; + GURL emptyUrl = GURL.emptyGURL(); boolean isInMainFrame = true; boolean isErrorPage = false; boolean isSameDocument = true; @@ -148,47 +150,46 @@ doUpdateVisitedHistoryHelper.waitForCallback(callCount); Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", callCount + 1, doUpdateVisitedHistoryHelper.getCallCount()); - Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", emptyUrl, - doUpdateVisitedHistoryHelper.getUrl()); + Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", + emptyUrl.getSpec(), doUpdateVisitedHistoryHelper.getUrl()); Assert.assertEquals(false, doUpdateVisitedHistoryHelper.getIsReload()); callCount = doUpdateVisitedHistoryHelper.getCallCount(); - simulateNavigation(EXAMPLE_URL, isInMainFrame, isErrorPage, !isSameDocument, + simulateNavigation(mExampleURL, isInMainFrame, isErrorPage, !isSameDocument, fragmentNavigation, isRendererInitiated, PageTransition.TYPED); doUpdateVisitedHistoryHelper.waitForCallback(callCount); Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", callCount + 1, doUpdateVisitedHistoryHelper.getCallCount()); - Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", EXAMPLE_URL, - doUpdateVisitedHistoryHelper.getUrl()); + Assert.assertEquals("doUpdateVisitedHistory should be called for any url.", + mExampleURL.getSpec(), doUpdateVisitedHistoryHelper.getUrl()); Assert.assertEquals(false, doUpdateVisitedHistoryHelper.getIsReload()); callCount = doUpdateVisitedHistoryHelper.getCallCount(); simulateNavigation(emptyUrl, isInMainFrame, isErrorPage, !isSameDocument, fragmentNavigation, isRendererInitiated, PageTransition.TYPED); - simulateNavigation(EXAMPLE_URL, !isInMainFrame, isErrorPage, !isSameDocument, + simulateNavigation(mExampleURL, !isInMainFrame, isErrorPage, !isSameDocument, fragmentNavigation, isRendererInitiated, PageTransition.TYPED); doUpdateVisitedHistoryHelper.waitForCallback(callCount); Assert.assertEquals("doUpdateVisitedHistory should only be called for the main frame.", callCount + 1, doUpdateVisitedHistoryHelper.getCallCount()); Assert.assertEquals("doUpdateVisitedHistory should only be called for the main frame.", - emptyUrl, doUpdateVisitedHistoryHelper.getUrl()); + emptyUrl.getSpec(), doUpdateVisitedHistoryHelper.getUrl()); Assert.assertEquals(false, doUpdateVisitedHistoryHelper.getIsReload()); callCount = doUpdateVisitedHistoryHelper.getCallCount(); - simulateNavigation(EXAMPLE_URL, isInMainFrame, isErrorPage, isSameDocument, + simulateNavigation(mExampleURL, isInMainFrame, isErrorPage, isSameDocument, !fragmentNavigation, !isRendererInitiated, PageTransition.RELOAD); doUpdateVisitedHistoryHelper.waitForCallback(callCount); Assert.assertEquals("doUpdateVisitedHistory should be called for reloads.", callCount + 1, doUpdateVisitedHistoryHelper.getCallCount()); - Assert.assertEquals("doUpdateVisitedHistory should be called for reloads.", EXAMPLE_URL, - doUpdateVisitedHistoryHelper.getUrl()); + Assert.assertEquals("doUpdateVisitedHistory should be called for reloads.", + mExampleURL.getSpec(), doUpdateVisitedHistoryHelper.getUrl()); Assert.assertEquals(true, doUpdateVisitedHistoryHelper.getIsReload()); } - private void simulateNavigation(String url, boolean isInMainFrame, boolean isErrorPage, + private void simulateNavigation(GURL gurl, boolean isInMainFrame, boolean isErrorPage, boolean isSameDocument, boolean isFragmentNavigation, boolean isRendererInitiated, int transition) { - GURL gurl = new GURL(url); NavigationHandle navigation = new NavigationHandle(0 /* navigationHandleProxy */, gurl, isInMainFrame, isSameDocument, isRendererInitiated); mWebContentsObserver.didStartNavigation(navigation);
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/TestAwContentsClient.java b/android_webview/javatests/src/org/chromium/android_webview/test/TestAwContentsClient.java index 3b9af645..03ef7cae 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/TestAwContentsClient.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/TestAwContentsClient.java
@@ -9,7 +9,6 @@ import android.net.http.SslError; import org.chromium.android_webview.AwConsoleMessage; -import org.chromium.android_webview.AwContentsClient.AwWebResourceRequest; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.ThreadUtils;
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 458559a1..d803cbc 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -978,6 +978,8 @@ "system/enterprise/enterprise_domain_observer.h", "system/gesture_education/gesture_education_notification_controller.cc", "system/gesture_education/gesture_education_notification_controller.h", + "system/holding_space/downloads_section.cc", + "system/holding_space/downloads_section.h", "system/holding_space/holding_space_color_provider_impl.cc", "system/holding_space/holding_space_color_provider_impl.h", "system/holding_space/holding_space_drag_util.cc", @@ -1006,6 +1008,8 @@ "system/holding_space/pinned_files_container.h", "system/holding_space/recent_files_container.cc", "system/holding_space/recent_files_container.h", + "system/holding_space/screen_captures_section.cc", + "system/holding_space/screen_captures_section.h", "system/ime/ime_feature_pod_controller.cc", "system/ime/ime_feature_pod_controller.h", "system/ime/ime_observer.h",
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 366e9031..2f06234 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -1066,6 +1066,9 @@ <message name="IDS_ASH_PHONE_HUB_BATTERY_STATUS_CHARGING_USB" desc="The tooltip text indicating the phone is currently charging via a USB connection."> Charging via USB </message> + <message name="IDS_ASH_PHONE_HUB_BATTERY_PERCENTAGE_ACCESSIBLE_TEXT" desc="The accessible text of the phone battery percentage displayed in the Phone Hub tray."> + Phone battery <ph name="BATTERY_PERCENTAGE">$1<ex>100</ex></ph>% + </message> <message name="IDS_ASH_PHONE_HUB_BATTERY_SAVER_ON" desc="The tooltip text indicating the phone is currently in battery saver mode."> Battery saver mode is on </message> @@ -1204,7 +1207,7 @@ <message name="IDS_ASH_PHONE_HUB_CONNECTED_DEVICE_SETTINGS_LABEL" desc="Label for the settings button in the Phone Hub UI that lets users know that the button routes to the Chrome OS Settings app page for connected devices (e.g. to disable Phone Hub features, enable/disable Smartlock, etc)"> Connected devices settings </message> - <message name="IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP" translateable="false" desc="Tooltip message that indicates to the user that the Silence Phone feature is disabled because their phone is on a work profile."> + <message name="IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP" desc="Tooltip message that indicates to the user that the Silence Phone feature is disabled because their phone is on a work profile."> Silence phone is not available on work profile </message> @@ -1348,16 +1351,16 @@ <message name="IDS_ASH_DESKS_DESK_4_MINI_VIEW_TITLE" desc="The label of the fourth virtual desk thumbnail."> Desk 4 </message> - <message name="IDS_ASH_DESKS_DESK_5_MINI_VIEW_TITLE" desc="The label of the fourth virtual desk thumbnail."> + <message name="IDS_ASH_DESKS_DESK_5_MINI_VIEW_TITLE" desc="The label of the fifth virtual desk thumbnail."> Desk 5 </message> - <message name="IDS_ASH_DESKS_DESK_6_MINI_VIEW_TITLE" desc="The label of the fourth virtual desk thumbnail."> + <message name="IDS_ASH_DESKS_DESK_6_MINI_VIEW_TITLE" desc="The label of the sixth virtual desk thumbnail."> Desk 6 </message> - <message name="IDS_ASH_DESKS_DESK_7_MINI_VIEW_TITLE" desc="The label of the fourth virtual desk thumbnail."> + <message name="IDS_ASH_DESKS_DESK_7_MINI_VIEW_TITLE" desc="The label of the seventh virtual desk thumbnail."> Desk 7 </message> - <message name="IDS_ASH_DESKS_DESK_8_MINI_VIEW_TITLE" desc="The label of the fourth virtual desk thumbnail."> + <message name="IDS_ASH_DESKS_DESK_8_MINI_VIEW_TITLE" desc="The label of the eighth virtual desk thumbnail."> Desk 8 </message> <message name="IDS_ASH_DESKS_MAX_NUM_REACHED" desc="Message shown to users when they attempt to add a new virtual desk when the maximum number of desks has been reached.">
diff --git a/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_BATTERY_PERCENTAGE_ACCESSIBLE_TEXT.png.sha1 b/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_BATTERY_PERCENTAGE_ACCESSIBLE_TEXT.png.sha1 new file mode 100644 index 0000000..ef007448 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_BATTERY_PERCENTAGE_ACCESSIBLE_TEXT.png.sha1
@@ -0,0 +1 @@ +72b4b1039e35fdd7f6d42bc25d509c1227e94d16 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP.png.sha1 b/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP.png.sha1 index 9ed7b92..35662b45 100644 --- a/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP.png.sha1 +++ b/ash/ash_strings_grd/IDS_ASH_PHONE_HUB_SILENCE_BUTTON_NOT_AVAILABLE_TOOLTIP.png.sha1
@@ -1 +1 @@ -97d2fdaa8a77f2ca60b7059fbd5997de0ba3cbe9 \ No newline at end of file +3b0209e5da0b1bbab21133d870925e9a7cfba337 \ No newline at end of file
diff --git a/ash/capture_mode/capture_mode_controller.cc b/ash/capture_mode/capture_mode_controller.cc index d862052..8c8303f 100644 --- a/ash/capture_mode/capture_mode_controller.cc +++ b/ash/capture_mode/capture_mode_controller.cc
@@ -4,8 +4,6 @@ #include "ash/capture_mode/capture_mode_controller.h" -#include <memory> -#include <string> #include <utility> #include "ash/capture_mode/capture_mode_metrics.h"
diff --git a/ash/capture_mode/capture_mode_session.cc b/ash/capture_mode/capture_mode_session.cc index d6697466..6c71245 100644 --- a/ash/capture_mode/capture_mode_session.cc +++ b/ash/capture_mode/capture_mode_session.cc
@@ -390,6 +390,10 @@ parent->layer()->Add(layer()); layer()->SetBounds(parent->bounds()); + // The last region selected could have been on a larger display. Ensure that + // the region is not larger than the current display. + ClampCaptureRegionToRootWindowSize(); + capture_mode_bar_widget_->Init( CreateWidgetParams(parent, CaptureModeBarView::GetBounds(current_root_), "CaptureModeBarWidget")); @@ -584,10 +588,31 @@ void CaptureModeSession::OnDisplayMetricsChanged( const display::Display& display, uint32_t metrics) { - if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION) { - UpdateCursor(display::Screen::GetScreen()->GetCursorScreenPoint(), - /*is_touch=*/false); + if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION | + DISPLAY_METRIC_DEVICE_SCALE_FACTOR))) { + return; } + + EndSelection(/*is_event_on_capture_bar=*/false, + /*region_intersects_capture_bar=*/false); + + UpdateCursor(display::Screen::GetScreen()->GetCursorScreenPoint(), + /*is_touch=*/false); + + // Ensure the region still fits the root window after display changes. + ClampCaptureRegionToRootWindowSize(); + + // Update the bounds of all created widgets and repaint the entire layer. + auto* parent = GetParentContainer(current_root_); + DCHECK_EQ(parent->layer(), layer()->parent()); + layer()->SetBounds(parent->bounds()); + + DCHECK(capture_mode_bar_widget_); + capture_mode_bar_widget_->SetBounds( + CaptureModeBarView::GetBounds(current_root_)); + if (capture_label_widget_) + UpdateCaptureLabelWidget(); + layer()->SchedulePaint(layer()->bounds()); } gfx::Rect CaptureModeSession::GetSelectedWindowBounds() const { @@ -776,7 +801,7 @@ SetMouseWarpEnabled(*old_mouse_warp_status_); old_mouse_warp_status_.reset(); - OnLocatedEventReleased(location, is_event_on_capture_bar, + OnLocatedEventReleased(is_event_on_capture_bar, region_intersects_capture_bar); break; case ui::ET_MOUSE_MOVED: @@ -928,30 +953,15 @@ } void CaptureModeSession::OnLocatedEventReleased( - const gfx::Point& location_in_root, bool is_event_on_capture_bar, bool region_intersects_capture_bar) { - fine_tune_position_ = FineTunePosition::kNone; - anchor_points_.clear(); - - is_drag_in_progress_ = false; - Shell::Get()->UpdateCursorCompositingEnabled(); - - // TODO(richui): update this for tablet mode. - UpdateCaptureBarWidgetOpacity( - region_intersects_capture_bar && !is_event_on_capture_bar - ? kCaptureBarOverlapOpacity - : 1.f, - /*on_release=*/true); + EndSelection(is_event_on_capture_bar, region_intersects_capture_bar); // Do a repaint to show the affordance circles. gfx::Rect damage_region = controller_->user_capture_region(); damage_region.Inset(gfx::Insets(-kDamageInsetDp)); layer()->SchedulePaint(damage_region); - UpdateDimensionsLabelWidget(/*is_resizing=*/false); - CloseMagnifierGlass(); - if (!is_selecting_region_) return; @@ -1395,4 +1405,29 @@ capture_bar_layer->SetOpacity(opacity); } +void CaptureModeSession::ClampCaptureRegionToRootWindowSize() { + gfx::Rect new_capture_region = controller_->user_capture_region(); + new_capture_region.AdjustToFit(current_root_->bounds()); + controller_->set_user_capture_region(new_capture_region); +} + +void CaptureModeSession::EndSelection(bool is_event_on_capture_bar, + bool region_intersects_capture_bar) { + fine_tune_position_ = FineTunePosition::kNone; + anchor_points_.clear(); + + is_drag_in_progress_ = false; + Shell::Get()->UpdateCursorCompositingEnabled(); + + // TODO(richui): Update this for tablet mode. + UpdateCaptureBarWidgetOpacity( + region_intersects_capture_bar && !is_event_on_capture_bar + ? kCaptureBarOverlapOpacity + : 1.f, + /*on_release=*/true); + + UpdateDimensionsLabelWidget(/*is_resizing=*/false); + CloseMagnifierGlass(); +} + } // namespace ash
diff --git a/ash/capture_mode/capture_mode_session.h b/ash/capture_mode/capture_mode_session.h index 2b3497c..4c8790c0 100644 --- a/ash/capture_mode/capture_mode_session.h +++ b/ash/capture_mode/capture_mode_session.h
@@ -133,8 +133,7 @@ bool is_touch, bool is_event_on_capture_bar); void OnLocatedEventDragged(const gfx::Point& location_in_root); - void OnLocatedEventReleased(const gfx::Point& location_in_root, - bool is_event_on_capture_bar, + void OnLocatedEventReleased(bool is_event_on_capture_bar, bool region_intersects_capture_bar); // Updates the capture region and the capture region widgets depending on the @@ -208,6 +207,16 @@ // animation duration and tween type for mouse/touch release. void UpdateCaptureBarWidgetOpacity(float opacity, bool on_release); + // Ensure the user region in |controller_| is within the bounds of the root + // window. This is called when creating |this| or when the display bounds have + // changed. + void ClampCaptureRegionToRootWindowSize(); + + // Ends a region selection. Cleans up internal state and updates the cursor, + // capture bar opacity and magnifier glass. + void EndSelection(bool is_event_on_capture_bar, + bool region_intersects_capture_bar); + CaptureModeController* const controller_; // The current root window on which the capture session is active, which may
diff --git a/ash/capture_mode/capture_mode_unittests.cc b/ash/capture_mode/capture_mode_unittests.cc index 137cfb76..64d8c66 100644 --- a/ash/capture_mode/capture_mode_unittests.cc +++ b/ash/capture_mode/capture_mode_unittests.cc
@@ -1885,6 +1885,66 @@ EXPECT_FALSE(controller->IsActive()); } +// Tests that after rotating a display, the capture session widgets are updated +// and the capture region is reset. +TEST_F(CaptureModeTest, DisplayRotation) { + UpdateDisplay("1200x600"); + + auto* controller = StartImageRegionCapture(); + SelectRegion(gfx::Rect(1200, 400)); + + // Rotate the primary display by 90 degrees. Test that the region and capture + // bar fit within the rotated bounds, and the capture label widget is still + // centered in the region. + Shell::Get()->display_manager()->SetDisplayRotation( + WindowTreeHostManager::GetPrimaryDisplayId(), display::Display::ROTATE_90, + display::Display::RotationSource::USER); + const gfx::Rect rotated_root_bounds(600, 1200); + EXPECT_TRUE(rotated_root_bounds.Contains(controller->user_capture_region())); + EXPECT_TRUE(rotated_root_bounds.Contains( + GetCaptureModeBarView()->GetBoundsInScreen())); + views::Widget* capture_label_widget = + CaptureModeSessionTestApi(controller->capture_mode_session()) + .capture_label_widget(); + ASSERT_TRUE(capture_label_widget); + EXPECT_EQ(controller->user_capture_region().CenterPoint(), + capture_label_widget->GetWindowBoundsInScreen().CenterPoint()); +} + +TEST_F(CaptureModeTest, DisplayBoundsChange) { + UpdateDisplay("1200x600"); + + auto* controller = StartImageRegionCapture(); + SelectRegion(gfx::Rect(1200, 400)); + + // Shrink the display. The capture region should shrink, and the capture bar + // should be adjusted to be centered. + UpdateDisplay("600x600"); + EXPECT_EQ(gfx::Rect(600, 400), controller->user_capture_region()); + EXPECT_EQ(300, + GetCaptureModeBarView()->GetBoundsInScreen().CenterPoint().x()); +} + +TEST_F(CaptureModeTest, ReenterOnSmallerDisplay) { + UpdateDisplay("1200x600,1201+0-600x600"); + + // Start off with the primary display as the targeted display. Create a region + // that fits the primary display but would be too big for the secondary + // display. + auto* event_generator = GetEventGenerator(); + MoveMouseToAndUpdateCursorDisplay(gfx::Point(600, 300), event_generator); + auto* controller = StartImageRegionCapture(); + SelectRegion(gfx::Rect(1200, 400)); + EXPECT_EQ(gfx::Rect(1200, 400), controller->user_capture_region()); + controller->Stop(); + + // Make the secondary display the targeted display. Test that the region has + // shrunk to fit the display. + MoveMouseToAndUpdateCursorDisplay(gfx::Point(1500, 300), event_generator); + StartImageRegionCapture(); + EXPECT_EQ(gfx::Rect(600, 400), controller->user_capture_region()); +} + // A test class that uses a mock time task environment. class CaptureModeMockTimeTest : public CaptureModeTest { public:
diff --git a/ash/clipboard/views/clipboard_history_delete_button.cc b/ash/clipboard/views/clipboard_history_delete_button.cc index b307dd8..33fa4aeb 100644 --- a/ash/clipboard/views/clipboard_history_delete_button.cc +++ b/ash/clipboard/views/clipboard_history_delete_button.cc
@@ -9,6 +9,8 @@ #include "ash/resources/vector_icons/vector_icons.h" #include "ash/style/ash_color_provider.h" #include "ash/style/scoped_light_mode_as_default.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/strings/grit/ui_strings.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/controls/highlight_path_generator.h" @@ -21,7 +23,8 @@ }, base::Unretained(listener))) { SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); - SetAccessibleName(base::ASCIIToUTF16(std::string(GetClassName()))); + SetAccessibleName( + l10n_util::GetStringUTF16(IDS_CLIPBOARD_HISTORY_DELETE_BUTTON)); SetImageHorizontalAlignment(views::ImageButton::ALIGN_CENTER); SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); SetPreferredSize(gfx::Size(ClipboardHistoryViews::kDeleteButtonSizeDip,
diff --git a/ash/keyboard/DIR_METADATA b/ash/keyboard/DIR_METADATA index 09b159b1..0891a9ac 100644 --- a/ash/keyboard/DIR_METADATA +++ b/ash/keyboard/DIR_METADATA
@@ -7,5 +7,5 @@ # https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/proto/dir_metadata.proto monorail { - component: "UI>Input>VirtualKeyboard" -} \ No newline at end of file + component: "OS>Inputs" +}
diff --git a/ash/public/cpp/holding_space/holding_space_constants.h b/ash/public/cpp/holding_space/holding_space_constants.h index 3165d07..eeb5be7 100644 --- a/ash/public/cpp/holding_space/holding_space_constants.h +++ b/ash/public/cpp/holding_space/holding_space_constants.h
@@ -55,7 +55,8 @@ // View IDs. constexpr int kHoldingSpacePinnedFilesContainerId = 1; constexpr int kHoldingSpaceRecentFilesContainerId = 2; -constexpr int kHoldingSpaceTrayIconId = 3; +constexpr int kHoldingSpaceScreenCapturePlayIconId = 3; +constexpr int kHoldingSpaceTrayIconId = 4; // The maximum allowed age for files restored into the holding space model. // Note that this is not enforced for pinned items.
diff --git a/ash/system/holding_space/downloads_section.cc b/ash/system/holding_space/downloads_section.cc new file mode 100644 index 0000000..fe03726 --- /dev/null +++ b/ash/system/holding_space/downloads_section.cc
@@ -0,0 +1,192 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/system/holding_space/downloads_section.h" + +#include <memory> + +#include "ash/public/cpp/holding_space/holding_space_client.h" +#include "ash/public/cpp/holding_space/holding_space_constants.h" +#include "ash/public/cpp/holding_space/holding_space_controller.h" +#include "ash/public/cpp/holding_space/holding_space_item.h" +#include "ash/public/cpp/holding_space/holding_space_metrics.h" +#include "ash/resources/vector_icons/vector_icons.h" +#include "ash/strings/grit/ash_strings.h" +#include "ash/style/ash_color_provider.h" +#include "ash/system/holding_space/holding_space_item_chip_view.h" +#include "ash/system/holding_space/holding_space_item_chips_container.h" +#include "ash/system/tray/tray_constants.h" +#include "ash/system/tray/tray_popup_utils.h" +#include "base/bind.h" +#include "base/containers/adapters.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/controls/button/button.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/box_layout.h" + +namespace ash { + +namespace { + +// Helpers --------------------------------------------------------------------- + +// Returns if an item of the specified `type` belongs in this section. +bool BelongsToSection(HoldingSpaceItem::Type type) { + return type == HoldingSpaceItem::Type::kDownload || + type == HoldingSpaceItem::Type::kNearbyShare; +} + +// Header----------------------------------------------------------------------- + +class Header : public views::Button { + public: + Header() { + SetAccessibleName( + l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_DOWNLOADS_TITLE)); + SetCallback( + base::BindRepeating(&Header::OnPressed, base::Unretained(this))); + + auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), + kHoldingSpaceDownloadsHeaderSpacing)); + + // Label. + auto* label = AddChildView(std::make_unique<views::Label>( + l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_DOWNLOADS_TITLE))); + label->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kTextColorPrimary)); + label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); + layout->SetFlexForView(label, 1); + + TrayPopupUtils::SetLabelFontList(label, + TrayPopupUtils::FontStyle::kSubHeader); + + // Chevron. + auto* chevron = AddChildView(std::make_unique<views::ImageView>()); + chevron->SetFlipCanvasOnPaintForRTLUI(true); + chevron->SetImage(gfx::CreateVectorIcon( + kChevronRightIcon, kHoldingSpaceDownloadsChevronIconSize, + AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kIconColorPrimary))); + } + + private: + void OnPressed() { + holding_space_metrics::RecordDownloadsAction( + holding_space_metrics::DownloadsAction::kClick); + + HoldingSpaceController::Get()->client()->OpenDownloads(base::DoNothing()); + } +}; + +} // namespace + +// DownloadsSection ------------------------------------------------------------ + +DownloadsSection::DownloadsSection(HoldingSpaceItemViewDelegate* delegate) + : HoldingSpaceItemViewsContainer(delegate) { + SetVisible(false); + + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical, gfx::Insets(), + kHoldingSpaceContainerChildSpacing)); + + // Header. + header_ = AddChildView(std::make_unique<Header>()); + header_->SetPaintToLayer(); + header_->layer()->SetFillsBoundsOpaquely(false); + header_->SetVisible(false); + + // Container. + container_ = AddChildView(std::make_unique<HoldingSpaceItemChipsContainer>()); + container_->SetVisible(false); +} + +DownloadsSection::~DownloadsSection() = default; + +void DownloadsSection::ChildVisibilityChanged(views::View* child) { + // This section should be visible iff it has visible children. + bool visible = false; + for (const views::View* c : children()) { + if (c->GetVisible()) { + visible = true; + break; + } + } + + if (visible != GetVisible()) + SetVisible(visible); + + HoldingSpaceItemViewsContainer::ChildVisibilityChanged(child); +} + +void DownloadsSection::ViewHierarchyChanged( + const views::ViewHierarchyChangedDetails& details) { + if (details.parent != container_) + return; + + // Update visibility when becoming empty or non-empty. Note that in the case + // of a view being added, `ViewHierarchyChanged()` is called *after* the view + // has been parented but in the case of a view being removed, it is called + // *before* the view is unparented. + if (container_->children().size() == 1u) { + header_->SetVisible(details.is_add); + container_->SetVisible(details.is_add); + } +} + +bool DownloadsSection::ContainsHoldingSpaceItemView( + const HoldingSpaceItem* item) { + return base::Contains(views_by_item_id_, item->id()); +} + +bool DownloadsSection::ContainsHoldingSpaceItemViews() { + return !views_by_item_id_.empty(); +} + +bool DownloadsSection::WillAddHoldingSpaceItemView( + const HoldingSpaceItem* item) { + return BelongsToSection(item->type()); +} + +void DownloadsSection::AddHoldingSpaceItemView(const HoldingSpaceItem* item) { + DCHECK(item->IsFinalized()); + DCHECK(BelongsToSection(item->type())); + DCHECK(!base::Contains(views_by_item_id_, item->id())); + + // Remove the last download view if we are already at max capacity. + if (container_->children().size() == kMaxDownloads) { + std::unique_ptr<views::View> view = + container_->RemoveChildViewT(container_->children().back()); + views_by_item_id_.erase( + HoldingSpaceItemView::Cast(view.get())->item()->id()); + } + + // Add the download view to the front in order to sort by recency. + views_by_item_id_[item->id()] = container_->AddChildViewAt( + std::make_unique<HoldingSpaceItemChipView>(delegate(), item), 0); +} + +void DownloadsSection::RemoveAllHoldingSpaceItemViews() { + views_by_item_id_.clear(); + container_->RemoveAllChildViews(true); +} + +// TODO(dmblack): Handle grow/shrink of container. +void DownloadsSection::AnimateIn(ui::LayerAnimationObserver* observer) { + for (auto& view_by_item_id : views_by_item_id_) + view_by_item_id.second->AnimateIn(observer); +} + +// TODO(dmblack): Handle animate out of `header_` if this section is going away +// permanently. +void DownloadsSection::AnimateOut(ui::LayerAnimationObserver* observer) { + for (auto& view_by_item_id : views_by_item_id_) + view_by_item_id.second->AnimateOut(observer); +} + +} // namespace ash
diff --git a/ash/system/holding_space/downloads_section.h b/ash/system/holding_space/downloads_section.h new file mode 100644 index 0000000..86ddb25 --- /dev/null +++ b/ash/system/holding_space/downloads_section.h
@@ -0,0 +1,46 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_SYSTEM_HOLDING_SPACE_DOWNLOADS_SECTION_H_ +#define ASH_SYSTEM_HOLDING_SPACE_DOWNLOADS_SECTION_H_ + +#include <map> + +#include "ash/system/holding_space/holding_space_item_views_container.h" + +namespace ash { + +class HoldingSpaceItemChipsContainer; +class HoldingSpaceItemView; + +// Section for downloads in the `RecentFilesContainer`. +class DownloadsSection : public HoldingSpaceItemViewsContainer { + public: + explicit DownloadsSection(HoldingSpaceItemViewDelegate* delegate); + DownloadsSection(const DownloadsSection& other) = delete; + DownloadsSection& operator=(const DownloadsSection& other) = delete; + ~DownloadsSection() override; + + // HoldingSpaceItemViewsContainer: + void ChildVisibilityChanged(views::View* child) override; + void ViewHierarchyChanged(const views::ViewHierarchyChangedDetails&) override; + bool ContainsHoldingSpaceItemView(const HoldingSpaceItem* item) override; + bool ContainsHoldingSpaceItemViews() override; + bool WillAddHoldingSpaceItemView(const HoldingSpaceItem* item) override; + void AddHoldingSpaceItemView(const HoldingSpaceItem* item) override; + void RemoveAllHoldingSpaceItemViews() override; + void AnimateIn(ui::LayerAnimationObserver* observer) override; + void AnimateOut(ui::LayerAnimationObserver* observer) override; + + private: + // Owned by view hierarchy. + HoldingSpaceItemChipsContainer* container_ = nullptr; + views::View* header_ = nullptr; + + std::map<std::string, HoldingSpaceItemView*> views_by_item_id_; +}; + +} // namespace ash + +#endif // ASH_SYSTEM_HOLDING_SPACE_DOWNLOADS_SECTION_H_
diff --git a/ash/system/holding_space/holding_space_item_screen_capture_view.cc b/ash/system/holding_space/holding_space_item_screen_capture_view.cc index 7513fc74..96630d1 100644 --- a/ash/system/holding_space/holding_space_item_screen_capture_view.cc +++ b/ash/system/holding_space/holding_space_item_screen_capture_view.cc
@@ -9,10 +9,14 @@ #include "ash/public/cpp/holding_space/holding_space_image.h" #include "ash/public/cpp/holding_space/holding_space_item.h" #include "ash/public/cpp/rounded_image_view.h" +#include "ash/style/ash_color_provider.h" #include "ash/system/tray/tray_constants.h" +#include "components/vector_icons/vector_icons.h" +#include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/background.h" #include "ui/views/controls/button/image_button.h" +#include "ui/views/controls/image_view.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/metadata/metadata_impl_macros.h" @@ -69,24 +73,29 @@ } void HoldingSpaceItemScreenCaptureView::AddPlayIcon() { - views::View* play_icon_container = - AddChildView(std::make_unique<views::View>()); + auto* play_icon_container = AddChildView(std::make_unique<views::View>()); + play_icon_container->SetFocusBehavior(views::View::FocusBehavior::NEVER); auto* layout = play_icon_container->SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kHorizontal, - kHoldingSpaceScreenCapturePadding)); + views::BoxLayout::Orientation::kHorizontal)); layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kCenter); layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kCenter); - views::View* play_icon = CreatePlayIcon(play_icon_container); + auto* play_icon = + play_icon_container->AddChildView(std::make_unique<views::ImageView>()); + play_icon->SetID(kHoldingSpaceScreenCapturePlayIconId); + play_icon->SetImage(gfx::CreateVectorIcon( + vector_icons::kPlayArrowIcon, kHoldingSpaceIconSize, + AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kButtonIconColor))); + play_icon->SetPreferredSize(kHoldingSpaceScreenCapturePlayIconSize); // Create contrasting background for the play icon. play_icon->SetBackground(views::CreateRoundedRectBackground( HoldingSpaceColorProvider::Get()->GetBackgroundColor(), kHoldingSpaceScreenCapturePlayIconSize.width() / 2)); - play_icon->SetPreferredSize(kHoldingSpaceScreenCapturePlayIconSize); } BEGIN_METADATA(HoldingSpaceItemScreenCaptureView, HoldingSpaceItemView)
diff --git a/ash/system/holding_space/holding_space_item_screen_capture_view.h b/ash/system/holding_space/holding_space_item_screen_capture_view.h index e21b2fb..87ddf45d 100644 --- a/ash/system/holding_space/holding_space_item_screen_capture_view.h +++ b/ash/system/holding_space/holding_space_item_screen_capture_view.h
@@ -32,7 +32,7 @@ private: void UpdateImage(); - // Overlays a play icon over the Screen Capture preview. + // Overlays a play icon over `image_`. void AddPlayIcon(); RoundedImageView* image_ = nullptr;
diff --git a/ash/system/holding_space/holding_space_item_view.cc b/ash/system/holding_space/holding_space_item_view.cc index 2380ca3b..6ea2b2f 100644 --- a/ash/system/holding_space/holding_space_item_view.cc +++ b/ash/system/holding_space/holding_space_item_view.cc
@@ -13,7 +13,6 @@ #include "ash/style/ash_color_provider.h" #include "ash/system/holding_space/holding_space_item_view_delegate.h" #include "base/bind.h" -#include "components/vector_icons/vector_icons.h" #include "ui/base/class_property.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/compositor/layer_animation_element.h" @@ -308,23 +307,6 @@ return pin_; } -views::View* HoldingSpaceItemView::CreatePlayIcon(views::View* parent) { - DCHECK(!play_icon_); - play_icon_ = parent->AddChildView(std::make_unique<views::ImageView>()); - play_icon_->SetFocusBehavior(views::View::FocusBehavior::NEVER); - play_icon_->SetVisible(true); - - const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( - AshColorProvider::ContentLayerType::kButtonIconColor); - - const gfx::ImageSkia play_icon_image = gfx::CreateVectorIcon( - vector_icons::kPlayArrowIcon, kHoldingSpaceIconSize, icon_color); - - play_icon_->SetImage(&play_icon_image); - - return play_icon_; -} - void HoldingSpaceItemView::OnPaintFocus(gfx::Canvas* canvas, gfx::Size size) { if (!HasFocus()) return;
diff --git a/ash/system/holding_space/holding_space_item_view.h b/ash/system/holding_space/holding_space_item_view.h index 055e9435..1cac307 100644 --- a/ash/system/holding_space/holding_space_item_view.h +++ b/ash/system/holding_space/holding_space_item_view.h
@@ -9,7 +9,6 @@ #include "ash/ash_export.h" #include "ui/views/animation/ink_drop_host_view.h" -#include "ui/views/controls/image_view.h" #include "ui/views/metadata/metadata_header_macros.h" namespace ui { @@ -74,13 +73,8 @@ void SetSelected(bool selected); bool selected() const { return selected_; } - views::View* play_icon() { return play_icon_; } - protected: views::ToggleImageButton* AddPin(views::View* parent); - // Creates a View consisting of a play icon. - views::View* CreatePlayIcon(views::View* parent); - virtual void OnPinVisiblityChanged(bool pin_visible) {} private: @@ -105,7 +99,6 @@ const std::string item_id_; views::ToggleImageButton* pin_ = nullptr; // Owned by view hierarchy. - views::ImageView* play_icon_ = nullptr; // Owned by view hierarchy. // Owners for the layers used to paint focused and selected states. std::unique_ptr<ui::LayerOwner> selected_layer_owner_;
diff --git a/ash/system/holding_space/holding_space_tray_bubble.cc b/ash/system/holding_space/holding_space_tray_bubble.cc index a8d27b4..d333f62 100644 --- a/ash/system/holding_space/holding_space_tray_bubble.cc +++ b/ash/system/holding_space/holding_space_tray_bubble.cc
@@ -128,18 +128,13 @@ std::make_unique<PinnedFilesContainer>(&delegate_)); bubble_container->SetFlexForChild(pinned_files_container_, 1); SetupViewLayer(pinned_files_container_); + pinned_files_container_->Init(); // Add recent files container. recent_files_container_ = bubble_container->AddChildView( std::make_unique<RecentFilesContainer>(&delegate_)); SetupViewLayer(recent_files_container_); - - // Populate both containers if holding space model has already been attached. - HoldingSpaceModel* model = HoldingSpaceController::Get()->model(); - if (model) { - pinned_files_container_->OnHoldingSpaceModelAttached(model); - recent_files_container_->OnHoldingSpaceModelAttached(model); - } + recent_files_container_->Init(); // Show the bubble. bubble_wrapper_ = std::make_unique<TrayBubbleWrapper>(
diff --git a/ash/system/holding_space/holding_space_tray_unittest.cc b/ash/system/holding_space/holding_space_tray_unittest.cc index cb16699d..2c70ef1 100644 --- a/ash/system/holding_space/holding_space_tray_unittest.cc +++ b/ash/system/holding_space/holding_space_tray_unittest.cc
@@ -1335,10 +1335,12 @@ EXPECT_EQ(screenshot_item->id(), HoldingSpaceItemView::Cast(screen_capture_chips[1])->item()->id()); - EXPECT_FALSE(HoldingSpaceItemView::Cast(screen_capture_chips[1])->play_icon()); + EXPECT_FALSE(screen_capture_chips[1]->GetViewByID( + kHoldingSpaceScreenCapturePlayIconId)); EXPECT_EQ(screen_recording_item->id(), HoldingSpaceItemView::Cast(screen_capture_chips[0])->item()->id()); - EXPECT_TRUE(HoldingSpaceItemView::Cast(screen_capture_chips[0])->play_icon()); + EXPECT_TRUE(screen_capture_chips[0]->GetViewByID( + kHoldingSpaceScreenCapturePlayIconId)); } INSTANTIATE_TEST_SUITE_P(All, HoldingSpaceTrayTest, testing::Bool());
diff --git a/ash/system/holding_space/pinned_files_container.cc b/ash/system/holding_space/pinned_files_container.cc index 32c4702..77604dbd 100644 --- a/ash/system/holding_space/pinned_files_container.cc +++ b/ash/system/holding_space/pinned_files_container.cc
@@ -133,6 +133,12 @@ PinnedFilesContainer::~PinnedFilesContainer() = default; +void PinnedFilesContainer::Init() { + HoldingSpaceModel* model = HoldingSpaceController::Get()->model(); + if (model) + OnHoldingSpaceModelAttached(model); +} + void PinnedFilesContainer::ViewHierarchyChanged( const views::ViewHierarchyChangedDetails& details) { // We only care about `item_chips_container_` becoming empty and non-empty.
diff --git a/ash/system/holding_space/pinned_files_container.h b/ash/system/holding_space/pinned_files_container.h index f92255c..cb459fc 100644 --- a/ash/system/holding_space/pinned_files_container.h +++ b/ash/system/holding_space/pinned_files_container.h
@@ -26,6 +26,9 @@ PinnedFilesContainer& operator=(const PinnedFilesContainer& other) = delete; ~PinnedFilesContainer() override; + // Initializes the container. + void Init(); + // HoldingSpaceItemViewsContainer: void ViewHierarchyChanged(const views::ViewHierarchyChangedDetails&) override; bool ContainsHoldingSpaceItemView(const HoldingSpaceItem* item) override;
diff --git a/ash/system/holding_space/recent_files_container.cc b/ash/system/holding_space/recent_files_container.cc index 85eb6472..d76c5e6 100644 --- a/ash/system/holding_space/recent_files_container.cc +++ b/ash/system/holding_space/recent_files_container.cc
@@ -6,106 +6,17 @@ #include <memory> -#include "ash/public/cpp/holding_space/holding_space_client.h" #include "ash/public/cpp/holding_space/holding_space_constants.h" #include "ash/public/cpp/holding_space/holding_space_controller.h" -#include "ash/public/cpp/holding_space/holding_space_item.h" -#include "ash/public/cpp/holding_space/holding_space_metrics.h" #include "ash/public/cpp/holding_space/holding_space_model.h" -#include "ash/resources/vector_icons/vector_icons.h" -#include "ash/strings/grit/ash_strings.h" -#include "ash/style/ash_color_provider.h" -#include "ash/system/holding_space/holding_space_item_chip_view.h" -#include "ash/system/holding_space/holding_space_item_chips_container.h" -#include "ash/system/holding_space/holding_space_item_screen_capture_view.h" -#include "ash/system/tray/tray_constants.h" -#include "ash/system/tray/tray_popup_utils.h" -#include "base/bind.h" -#include "base/containers/adapters.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/paint_vector_icon.h" -#include "ui/views/accessibility/view_accessibility.h" -#include "ui/views/border.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/image_view.h" -#include "ui/views/controls/label.h" +#include "ash/system/holding_space/downloads_section.h" +#include "ash/system/holding_space/screen_captures_section.h" #include "ui/views/layout/box_layout.h" -#include "ui/views/layout/flex_layout.h" -#include "ui/views/view_class_properties.h" namespace ash { -namespace { - -// Helpers --------------------------------------------------------------------- - -// Sets up the specified `label`. -void SetupLabel(views::Label* label) { - label->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( - AshColorProvider::ContentLayerType::kTextColorPrimary)); - TrayPopupUtils::SetLabelFontList(label, - TrayPopupUtils::FontStyle::kSubHeader); - label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); -} - -// Returns if an item of the specified `type` belongs in the downloads section. -bool BelongsToDownloadsSection(HoldingSpaceItem::Type type) { - return type == HoldingSpaceItem::Type::kDownload || - type == HoldingSpaceItem::Type::kNearbyShare; -} - -// Returns if an item of the specified `type` belongs in the screen captures -// section. -bool BelongsToScreenCaptureSection(HoldingSpaceItem::Type type) { - return type == HoldingSpaceItem::Type::kScreenshot || - type == HoldingSpaceItem::Type::kScreenRecording; -} - -// DownloadsHeader-------------------------------------------------------------- - -class DownloadsHeader : public views::Button { - public: - explicit DownloadsHeader() { - SetAccessibleName( - l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_DOWNLOADS_TITLE)); - - auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), - kHoldingSpaceDownloadsHeaderSpacing)); - - auto* label = AddChildView(std::make_unique<views::Label>( - l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_DOWNLOADS_TITLE))); - layout->SetFlexForView(label, 1); - SetupLabel(label); - - auto* chevron = AddChildView(std::make_unique<views::ImageView>()); - chevron->SetFlipCanvasOnPaintForRTLUI(true); - - const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( - AshColorProvider::ContentLayerType::kIconColorPrimary); - chevron->SetImage(CreateVectorIcon( - kChevronRightIcon, kHoldingSpaceDownloadsChevronIconSize, icon_color)); - - SetCallback(base::BindRepeating(&DownloadsHeader::OnPressed, - base::Unretained(this))); - } - - private: - void OnPressed() { - holding_space_metrics::RecordDownloadsAction( - holding_space_metrics::DownloadsAction::kClick); - - HoldingSpaceController::Get()->client()->OpenDownloads(base::DoNothing()); - } -}; - -} // namespace - -// RecentFilesContainer -------------------------------------------------------- - RecentFilesContainer::RecentFilesContainer( - HoldingSpaceItemViewDelegate* delegate) - : HoldingSpaceItemViewsContainer(delegate) { + HoldingSpaceItemViewDelegate* delegate) { SetID(kHoldingSpaceRecentFilesContainerId); SetVisible(false); @@ -113,34 +24,33 @@ views::BoxLayout::Orientation::kVertical, kHoldingSpaceContainerPadding, kHoldingSpaceContainerChildSpacing)); - screen_captures_label_ = AddChildView(std::make_unique<views::Label>( - l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_SCREEN_CAPTURES_TITLE))); - screen_captures_label_->SetPaintToLayer(); - screen_captures_label_->layer()->SetFillsBoundsOpaquely(false); - screen_captures_label_->SetVisible(false); - SetupLabel(screen_captures_label_); - - screen_captures_container_ = AddChildView(std::make_unique<views::View>()); - screen_captures_container_->SetVisible(false); - screen_captures_container_ - ->SetLayoutManager(std::make_unique<views::FlexLayout>()) - ->SetOrientation(views::LayoutOrientation::kHorizontal) - .SetDefault(views::kMarginsKey, - gfx::Insets(/*top=*/0, /*left=*/0, /*bottom=*/0, - /*right=*/kHoldingSpaceScreenCaptureSpacing)); - - downloads_header_ = AddChildView(std::make_unique<DownloadsHeader>()); - downloads_header_->SetPaintToLayer(); - downloads_header_->layer()->SetFillsBoundsOpaquely(false); - downloads_header_->SetVisible(false); - - downloads_container_ = - AddChildView(std::make_unique<HoldingSpaceItemChipsContainer>()); - downloads_container_->SetVisible(false); + // Sections. + sections_.push_back( + AddChildView(std::make_unique<ScreenCapturesSection>(delegate))); + sections_.push_back( + AddChildView(std::make_unique<DownloadsSection>(delegate))); } RecentFilesContainer::~RecentFilesContainer() = default; +void RecentFilesContainer::Init() { + HoldingSpaceModel* model = HoldingSpaceController::Get()->model(); + if (!model) + return; + + for (HoldingSpaceItemViewsContainer* section : sections_) + section->OnHoldingSpaceModelAttached(model); +} + +void RecentFilesContainer::Reset() { + for (HoldingSpaceItemViewsContainer* section : sections_) + section->Reset(); +} + +void RecentFilesContainer::ChildPreferredSizeChanged(views::View* child) { + PreferredSizeChanged(); +} + void RecentFilesContainer::ChildVisibilityChanged(views::View* child) { // The recent files container should be visible iff it has visible children. bool visible = false; @@ -150,122 +60,7 @@ if (visible != GetVisible()) SetVisible(visible); - HoldingSpaceItemViewsContainer::ChildVisibilityChanged(child); -} - -void RecentFilesContainer::ViewHierarchyChanged( - const views::ViewHierarchyChangedDetails& details) { - if (details.parent == screen_captures_container_) - OnScreenCapturesContainerViewHierarchyChanged(details); - else if (details.parent == downloads_container_) - OnDownloadsContainerViewHierarchyChanged(details); -} - -bool RecentFilesContainer::ContainsHoldingSpaceItemView( - const HoldingSpaceItem* item) { - return base::Contains(views_by_item_id_, item->id()); -} - -bool RecentFilesContainer::ContainsHoldingSpaceItemViews() { - return !views_by_item_id_.empty(); -} - -bool RecentFilesContainer::WillAddHoldingSpaceItemView( - const HoldingSpaceItem* item) { - return BelongsToDownloadsSection(item->type()) || - BelongsToScreenCaptureSection(item->type()); -} - -void RecentFilesContainer::AddHoldingSpaceItemView( - const HoldingSpaceItem* item) { - DCHECK(item->IsFinalized()); - - if (BelongsToScreenCaptureSection(item->type())) - AddHoldingSpaceScreenCaptureView(item); - else if (BelongsToDownloadsSection(item->type())) - AddHoldingSpaceDownloadView(item); - else - NOTREACHED(); -} - -void RecentFilesContainer::RemoveAllHoldingSpaceItemViews() { - views_by_item_id_.clear(); - screen_captures_container_->RemoveAllChildViews(true); - downloads_container_->RemoveAllChildViews(true); -} - -// TODO(dmblack): Handle grow/shrink of container. -// TODO(dmblack): Animate the screen captures section separately from the -// downloads section so that adding/removing an item from one section does not -// impact the other. -void RecentFilesContainer::AnimateIn(ui::LayerAnimationObserver* observer) { - for (auto& view_by_item_id : views_by_item_id_) - view_by_item_id.second->AnimateIn(observer); -} - -// TODO(dmblack): Handle animate out of screen captures and downloads labels if -// those sections are going away permanently. -// TODO(dmblack): Animate the screen captures section separately from the -// downloads section so that adding/removing an item from one section does not -// impact the other. -void RecentFilesContainer::AnimateOut(ui::LayerAnimationObserver* observer) { - for (auto& view_by_item_id : views_by_item_id_) - view_by_item_id.second->AnimateOut(observer); -} - -void RecentFilesContainer::AddHoldingSpaceScreenCaptureView( - const HoldingSpaceItem* item) { - DCHECK(BelongsToScreenCaptureSection(item->type())); - DCHECK(!base::Contains(views_by_item_id_, item->id())); - - // Remove the last screen capture view if we are already at max capacity. - if (screen_captures_container_->children().size() == kMaxScreenCaptures) { - std::unique_ptr<views::View> view = - screen_captures_container_->RemoveChildViewT( - screen_captures_container_->children().back()); - views_by_item_id_.erase( - HoldingSpaceItemView::Cast(view.get())->item()->id()); - } - - // Add the screen capture view to the front in order to sort by recency. - views_by_item_id_[item->id()] = screen_captures_container_->AddChildViewAt( - std::make_unique<HoldingSpaceItemScreenCaptureView>(delegate(), item), 0); -} - -void RecentFilesContainer::AddHoldingSpaceDownloadView( - const HoldingSpaceItem* item) { - DCHECK(BelongsToDownloadsSection(item->type())); - DCHECK(!base::Contains(views_by_item_id_, item->id())); - - // Remove the last download view if we are already at max capacity. - if (downloads_container_->children().size() == kMaxDownloads) { - std::unique_ptr<views::View> view = downloads_container_->RemoveChildViewT( - downloads_container_->children().back()); - views_by_item_id_.erase( - HoldingSpaceItemView::Cast(view.get())->item()->id()); - } - - // Add the download view to the front in order to sort by recency. - views_by_item_id_[item->id()] = downloads_container_->AddChildViewAt( - std::make_unique<HoldingSpaceItemChipView>(delegate(), item), 0); -} - -void RecentFilesContainer::OnScreenCapturesContainerViewHierarchyChanged( - const views::ViewHierarchyChangedDetails& details) { - // Update screen capture visibility when becoming empty or non-empty. - if (screen_captures_container_->children().size() == 1u) { - screen_captures_label_->SetVisible(details.is_add); - screen_captures_container_->SetVisible(details.is_add); - } -} - -void RecentFilesContainer::OnDownloadsContainerViewHierarchyChanged( - const views::ViewHierarchyChangedDetails& details) { - // Update downloads visibility when becoming empty or non-empty. - if (downloads_container_->children().size() == 1u) { - downloads_header_->SetVisible(details.is_add); - downloads_container_->SetVisible(details.is_add); - } + views::View::ChildVisibilityChanged(child); } } // namespace ash
diff --git a/ash/system/holding_space/recent_files_container.h b/ash/system/holding_space/recent_files_container.h index 473575d59..5e92a61 100644 --- a/ash/system/holding_space/recent_files_container.h +++ b/ash/system/holding_space/recent_files_container.h
@@ -5,53 +5,38 @@ #ifndef ASH_SYSTEM_HOLDING_SPACE_RECENT_FILES_CONTAINER_H_ #define ASH_SYSTEM_HOLDING_SPACE_RECENT_FILES_CONTAINER_H_ -#include <map> +#include <vector> -#include "ash/system/holding_space/holding_space_item_views_container.h" - -namespace views { -class Label; -} // namespace views +#include "ui/views/view.h" namespace ash { -class HoldingSpaceItemChipsContainer; -class HoldingSpaceItemView; +class HoldingSpaceItemViewDelegate; +class HoldingSpaceItemViewsContainer; -// Container for the recent files (e.g. screen captures, downloads, etc). -class RecentFilesContainer : public HoldingSpaceItemViewsContainer { +// Container for the recent files downloads and screen captures sections. +class RecentFilesContainer : public views::View { public: explicit RecentFilesContainer(HoldingSpaceItemViewDelegate* delegate); RecentFilesContainer(const RecentFilesContainer& other) = delete; RecentFilesContainer& operator=(const RecentFilesContainer& other) = delete; ~RecentFilesContainer() override; - // HoldingSpaceItemViewsContainer: - void ChildVisibilityChanged(views::View* child) override; - void ViewHierarchyChanged(const views::ViewHierarchyChangedDetails&) override; - bool ContainsHoldingSpaceItemView(const HoldingSpaceItem* item) override; - bool ContainsHoldingSpaceItemViews() override; - bool WillAddHoldingSpaceItemView(const HoldingSpaceItem* item) override; - void AddHoldingSpaceItemView(const HoldingSpaceItem* item) override; - void RemoveAllHoldingSpaceItemViews() override; - void AnimateIn(ui::LayerAnimationObserver* observer) override; - void AnimateOut(ui::LayerAnimationObserver* observer) override; + // Initializes the container. + void Init(); + + // Resets the container. Called when the tray bubble starts closing to + // stop observing the holding space controller/model to ensure that no new + // items are created while the bubble widget is being asynchronously closed. + void Reset(); private: - void AddHoldingSpaceScreenCaptureView(const HoldingSpaceItem* item); - void AddHoldingSpaceDownloadView(const HoldingSpaceItem* item); - void OnScreenCapturesContainerViewHierarchyChanged( - const views::ViewHierarchyChangedDetails& details); - void OnDownloadsContainerViewHierarchyChanged( - const views::ViewHierarchyChangedDetails& details); + // HoldingSpaceItemViewsContainer: + void ChildPreferredSizeChanged(views::View* child) override; + void ChildVisibilityChanged(views::View* child) override; - // Owned by view hierarchy. - views::View* screen_captures_container_ = nullptr; - views::Label* screen_captures_label_ = nullptr; - HoldingSpaceItemChipsContainer* downloads_container_ = nullptr; - views::View* downloads_header_ = nullptr; - - std::map<std::string, HoldingSpaceItemView*> views_by_item_id_; + // Views owned by view hierarchy. + std::vector<HoldingSpaceItemViewsContainer*> sections_; }; } // namespace ash
diff --git a/ash/system/holding_space/screen_captures_section.cc b/ash/system/holding_space/screen_captures_section.cc new file mode 100644 index 0000000..61a2fe5 --- /dev/null +++ b/ash/system/holding_space/screen_captures_section.cc
@@ -0,0 +1,158 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/system/holding_space/screen_captures_section.h" + +#include <memory> + +#include "ash/public/cpp/holding_space/holding_space_constants.h" +#include "ash/public/cpp/holding_space/holding_space_item.h" +#include "ash/strings/grit/ash_strings.h" +#include "ash/style/ash_color_provider.h" +#include "ash/system/holding_space/holding_space_item_screen_capture_view.h" +#include "ash/system/tray/tray_constants.h" +#include "ash/system/tray/tray_popup_utils.h" +#include "base/bind.h" +#include "base/containers/adapters.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/layout/flex_layout.h" +#include "ui/views/view_class_properties.h" + +namespace ash { + +namespace { + +// Helpers --------------------------------------------------------------------- + +// Returns if an item of the specified `type` belongs in this section. +bool BelongsToSection(HoldingSpaceItem::Type type) { + return type == HoldingSpaceItem::Type::kScreenshot || + type == HoldingSpaceItem::Type::kScreenRecording; +} + +} // namespace + +// ScreenCapturesSection ------------------------------------------------------- + +ScreenCapturesSection::ScreenCapturesSection( + HoldingSpaceItemViewDelegate* delegate) + : HoldingSpaceItemViewsContainer(delegate) { + SetVisible(false); + + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical, gfx::Insets(), + kHoldingSpaceContainerChildSpacing)); + + // Label. + label_ = AddChildView(std::make_unique<views::Label>( + l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_SCREEN_CAPTURES_TITLE))); + label_->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kTextColorPrimary)); + label_->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); + label_->SetPaintToLayer(); + label_->layer()->SetFillsBoundsOpaquely(false); + label_->SetVisible(false); + + TrayPopupUtils::SetLabelFontList(label_, + TrayPopupUtils::FontStyle::kSubHeader); + + // Container. + container_ = AddChildView(std::make_unique<views::View>()); + container_->SetVisible(false); + container_->SetLayoutManager(std::make_unique<views::FlexLayout>()) + ->SetOrientation(views::LayoutOrientation::kHorizontal) + .SetDefault(views::kMarginsKey, + gfx::Insets(/*top=*/0, /*left=*/0, /*bottom=*/0, + /*right=*/kHoldingSpaceScreenCaptureSpacing)); +} + +ScreenCapturesSection::~ScreenCapturesSection() = default; + +void ScreenCapturesSection::ChildVisibilityChanged(views::View* child) { + // This section should be visible iff it has visible children. + bool visible = false; + for (const views::View* c : children()) { + if (c->GetVisible()) { + visible = true; + break; + } + } + + if (visible != GetVisible()) + SetVisible(visible); + + HoldingSpaceItemViewsContainer::ChildVisibilityChanged(child); +} + +void ScreenCapturesSection::ViewHierarchyChanged( + const views::ViewHierarchyChangedDetails& details) { + if (details.parent != container_) + return; + + // Update visibility when becoming empty or non-empty. Note that in the case + // of a view being added, `ViewHierarchyChanged()` is called *after* the view + // has been parented but in the case of a view being removed, it is called + // *before* the view is unparented. + if (container_->children().size() == 1u) { + label_->SetVisible(details.is_add); + container_->SetVisible(details.is_add); + } +} + +bool ScreenCapturesSection::ContainsHoldingSpaceItemView( + const HoldingSpaceItem* item) { + return base::Contains(views_by_item_id_, item->id()); +} + +bool ScreenCapturesSection::ContainsHoldingSpaceItemViews() { + return !views_by_item_id_.empty(); +} + +bool ScreenCapturesSection::WillAddHoldingSpaceItemView( + const HoldingSpaceItem* item) { + return BelongsToSection(item->type()); +} + +void ScreenCapturesSection::AddHoldingSpaceItemView( + const HoldingSpaceItem* item) { + DCHECK(item->IsFinalized()); + DCHECK(BelongsToSection(item->type())); + DCHECK(!base::Contains(views_by_item_id_, item->id())); + + // Remove the last screen capture view if we are already at max capacity. + if (container_->children().size() == kMaxScreenCaptures) { + std::unique_ptr<views::View> view = + container_->RemoveChildViewT(container_->children().back()); + views_by_item_id_.erase( + HoldingSpaceItemView::Cast(view.get())->item()->id()); + } + + // Add the screen capture view to the front in order to sort by recency. + views_by_item_id_[item->id()] = container_->AddChildViewAt( + std::make_unique<HoldingSpaceItemScreenCaptureView>(delegate(), item), 0); +} + +void ScreenCapturesSection::RemoveAllHoldingSpaceItemViews() { + views_by_item_id_.clear(); + container_->RemoveAllChildViews(true); +} + +// TODO(dmblack): Handle grow/shrink of container. +void ScreenCapturesSection::AnimateIn(ui::LayerAnimationObserver* observer) { + for (auto& view_by_item_id : views_by_item_id_) + view_by_item_id.second->AnimateIn(observer); +} + +// TODO(dmblack): Handle animate out of `label_` if this section is going away +// permanently. +void ScreenCapturesSection::AnimateOut(ui::LayerAnimationObserver* observer) { + for (auto& view_by_item_id : views_by_item_id_) + view_by_item_id.second->AnimateOut(observer); +} + +} // namespace ash
diff --git a/ash/system/holding_space/screen_captures_section.h b/ash/system/holding_space/screen_captures_section.h new file mode 100644 index 0000000..525ce25 --- /dev/null +++ b/ash/system/holding_space/screen_captures_section.h
@@ -0,0 +1,56 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_SYSTEM_HOLDING_SPACE_SCREEN_CAPTURES_SECTION_H_ +#define ASH_SYSTEM_HOLDING_SPACE_SCREEN_CAPTURES_SECTION_H_ + +#include <map> + +#include "ash/system/holding_space/holding_space_item_views_container.h" + +namespace views { +class Label; +} // namespace views + +namespace ash { + +class HoldingSpaceItemView; + +// Section for screen captures in the `RecentFilesContainer`. +class ScreenCapturesSection : public HoldingSpaceItemViewsContainer { + public: + explicit ScreenCapturesSection(HoldingSpaceItemViewDelegate* delegate); + ScreenCapturesSection(const ScreenCapturesSection& other) = delete; + ScreenCapturesSection& operator=(const ScreenCapturesSection& other) = delete; + ~ScreenCapturesSection() override; + + // HoldingSpaceItemViewsContainer: + void ChildVisibilityChanged(views::View* child) override; + void ViewHierarchyChanged(const views::ViewHierarchyChangedDetails&) override; + bool ContainsHoldingSpaceItemView(const HoldingSpaceItem* item) override; + bool ContainsHoldingSpaceItemViews() override; + bool WillAddHoldingSpaceItemView(const HoldingSpaceItem* item) override; + void AddHoldingSpaceItemView(const HoldingSpaceItem* item) override; + void RemoveAllHoldingSpaceItemViews() override; + void AnimateIn(ui::LayerAnimationObserver* observer) override; + void AnimateOut(ui::LayerAnimationObserver* observer) override; + + private: + void AddHoldingSpaceScreenCaptureView(const HoldingSpaceItem* item); + void AddHoldingSpaceDownloadView(const HoldingSpaceItem* item); + void OnScreenCapturesContainerViewHierarchyChanged( + const views::ViewHierarchyChangedDetails& details); + void OnDownloadsContainerViewHierarchyChanged( + const views::ViewHierarchyChangedDetails& details); + + // Owned by view hierarchy. + views::View* container_ = nullptr; + views::Label* label_ = nullptr; + + std::map<std::string, HoldingSpaceItemView*> views_by_item_id_; +}; + +} // namespace ash + +#endif // ASH_SYSTEM_HOLDING_SPACE_SCREEN_CAPTURES_SECTION_H_
diff --git a/ash/system/phonehub/phone_status_view.cc b/ash/system/phonehub/phone_status_view.cc index e44fd36..d1477837 100644 --- a/ash/system/phonehub/phone_status_view.cc +++ b/ash/system/phonehub/phone_status_view.cc
@@ -265,6 +265,9 @@ SetBatteryTooltipText(); battery_label_->SetText( base::FormatPercent(phone_status.battery_percentage())); + battery_label_->SetAccessibleName(l10n_util::GetStringFUTF16( + IDS_ASH_PHONE_HUB_BATTERY_PERCENTAGE_ACCESSIBLE_TEXT, + base::NumberToString16(phone_status.battery_percentage()))); } PowerStatus::BatteryImageInfo PhoneStatusView::CalculateBatteryInfo() {
diff --git a/ash/system/virtual_keyboard/DIR_METADATA b/ash/system/virtual_keyboard/DIR_METADATA index 09b159b1..0891a9ac 100644 --- a/ash/system/virtual_keyboard/DIR_METADATA +++ b/ash/system/virtual_keyboard/DIR_METADATA
@@ -7,5 +7,5 @@ # https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/proto/dir_metadata.proto monorail { - component: "UI>Input>VirtualKeyboard" -} \ No newline at end of file + component: "OS>Inputs" +}
diff --git a/ash/wm/desks/autotest_desks_api.cc b/ash/wm/desks/autotest_desks_api.cc index 091f195..ef0cc64 100644 --- a/ash/wm/desks/autotest_desks_api.cc +++ b/ash/wm/desks/autotest_desks_api.cc
@@ -112,7 +112,7 @@ auto* animation = DesksController::Get()->animation(); DCHECK(animation); - animation_layer_ = animation->GetFirstDeskSwitchAnimatorForTesting() + animation_layer_ = animation->GetDeskSwitchAnimatorAtIndexForTesting(0) ->GetAnimationLayerForTesting(); animation_layer_->GetAnimator()->AddObserver(this); }
diff --git a/ash/wm/desks/desk_animation_base.cc b/ash/wm/desks/desk_animation_base.cc index f99eb826..479e4d2 100644 --- a/ash/wm/desks/desk_animation_base.cc +++ b/ash/wm/desks/desk_animation_base.cc
@@ -143,9 +143,9 @@ } RootWindowDeskSwitchAnimator* -DeskAnimationBase::GetFirstDeskSwitchAnimatorForTesting() const { - DCHECK(!desk_switch_animators_.empty()); - return desk_switch_animators_.front().get(); +DeskAnimationBase::GetDeskSwitchAnimatorAtIndexForTesting(size_t index) const { + DCHECK_LT(index, desk_switch_animators_.size()); + return desk_switch_animators_[index].get(); } } // namespace ash
diff --git a/ash/wm/desks/desk_animation_base.h b/ash/wm/desks/desk_animation_base.h index 684d193..2017549 100644 --- a/ash/wm/desks/desk_animation_base.h +++ b/ash/wm/desks/desk_animation_base.h
@@ -62,7 +62,8 @@ skip_notify_controller_on_animation_finished_for_testing_ = val; } - RootWindowDeskSwitchAnimator* GetFirstDeskSwitchAnimatorForTesting() const; + RootWindowDeskSwitchAnimator* GetDeskSwitchAnimatorAtIndexForTesting( + size_t index) const; protected: // Abstract functions that can be overridden by child classes to do different
diff --git a/ash/wm/desks/desk_animation_impl.cc b/ash/wm/desks/desk_animation_impl.cc index 75d82655a..ca00c9e 100644 --- a/ash/wm/desks/desk_animation_impl.cc +++ b/ash/wm/desks/desk_animation_impl.cc
@@ -129,7 +129,8 @@ } // Activate the target desk and take a screenshot. - DCHECK_EQ(pending_animators.size(), desk_switch_animators_.size()); + // TODO(crbug.com/1134390): Convert back to DCHECK when the issue is fixed. + CHECK_EQ(pending_animators.size(), desk_switch_animators_.size()); PrepareDeskForScreenshot(new_ending_desk_index); for (auto* animator : pending_animators) animator->TakeEndingDeskScreenshot(); @@ -142,28 +143,27 @@ presentation_time_recorder_->RequestNext(); - // List of animators that need a screenshot. It should be either empty or - // match the size of |desk_switch_animators_| as all the animations should be - // in sync. - std::vector<RootWindowDeskSwitchAnimator*> pending_animators; + // If any of the displays need a new screenshot while scrolling, take the + // ending desk screenshot for all of them to keep them in sync. + base::Optional<int> ending_desk_index; for (const auto& animator : desk_switch_animators_) { - if (animator->UpdateSwipeAnimation(scroll_delta_x)) - pending_animators.push_back(animator.get()); + if (!ending_desk_index) + ending_desk_index = animator->UpdateSwipeAnimation(scroll_delta_x); + else + animator->UpdateSwipeAnimation(scroll_delta_x); } // No screenshot needed. - if (pending_animators.empty()) { - OnEndingDeskScreenshotTaken(); + if (!ending_desk_index) return true; - } // Activate the target desk and take a screenshot. - // TODO(crbug.com/1134390): Convert back to DCHECK when the issue is fixed. - CHECK_EQ(pending_animators.size(), desk_switch_animators_.size()); - ending_desk_index_ = desk_switch_animators_[0]->ending_desk_index(); + ending_desk_index_ = *ending_desk_index; PrepareDeskForScreenshot(ending_desk_index_); - for (auto* animator : pending_animators) + for (const auto& animator : desk_switch_animators_) { + animator->PrepareForEndingDeskScreenshot(ending_desk_index_); animator->TakeEndingDeskScreenshot(); + } return true; }
diff --git a/ash/wm/desks/desk_animation_impl_unittest.cc b/ash/wm/desks/desk_animation_impl_unittest.cc index e8f9206..b9267a3 100644 --- a/ash/wm/desks/desk_animation_impl_unittest.cc +++ b/ash/wm/desks/desk_animation_impl_unittest.cc
@@ -8,6 +8,8 @@ #include "ash/test/ash_test_base.h" #include "ash/wm/desks/desks_controller.h" #include "ash/wm/desks/desks_histogram_enums.h" +#include "ash/wm/desks/root_window_desk_switch_animator_test_api.h" +#include "base/barrier_closure.h" #include "base/test/scoped_feature_list.h" namespace ash { @@ -33,4 +35,45 @@ animation.EndSwipeAnimation(); } +// Tests that there is no crash when swiping with external displays. Regression +// test for https://crbug.com/1154868. +TEST_F(DeskActivationAnimationTest, UpdateSwipeNewScreenshotCrash) { + // Crash is only reproducible on different resolution widths and easier to + // repro when the widths differ by a lot. + UpdateDisplay("600x600,601+0-2000x600"); + + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(features::kEnhancedDeskAnimations); + + // Crash repro requires three desks. + auto* desks_controller = DesksController::Get(); + desks_controller->NewDesk(DesksCreationRemovalSource::kButton); + desks_controller->NewDesk(DesksCreationRemovalSource::kButton); + + DeskActivationAnimation animation(desks_controller, 1, 2, + DesksSwitchSource::kDeskSwitchTouchpad, + /*update_window_activation=*/false); + animation.set_skip_notify_controller_on_animation_finished_for_testing(true); + animation.Launch(); + + // Wait until all ending screenshots have been taken before swiping. + size_t num_animators = 2u; + base::RunLoop run_loop; + base::RepeatingClosure end_screenshot_callback = + base::BarrierClosure(num_animators, run_loop.QuitClosure()); + for (size_t i = 0; i < num_animators; ++i) { + auto* desk_switch_animator = + animation.GetDeskSwitchAnimatorAtIndexForTesting(i); + RootWindowDeskSwitchAnimatorTestApi(desk_switch_animator) + .SetOnEndingScreenshotTakenCallback(end_screenshot_callback); + } + run_loop.Run(); + + // Swipe in a way which would have caused a crash using the old algorithm. See + // bug for more details. + animation.UpdateSwipeAnimation(-20); + animation.UpdateSwipeAnimation(10); + animation.EndSwipeAnimation(); +} + } // namespace ash
diff --git a/ash/wm/desks/root_window_desk_switch_animator.cc b/ash/wm/desks/root_window_desk_switch_animator.cc index 79f9db8b..c213c135 100644 --- a/ash/wm/desks/root_window_desk_switch_animator.cc +++ b/ash/wm/desks/root_window_desk_switch_animator.cc
@@ -248,9 +248,10 @@ return true; } -bool RootWindowDeskSwitchAnimator::UpdateSwipeAnimation(float scroll_delta_x) { +base::Optional<int> RootWindowDeskSwitchAnimator::UpdateSwipeAnimation( + float scroll_delta_x) { if (!starting_desk_screenshot_taken_ || !ending_desk_screenshot_taken_) - return false; + return base::nullopt; const float translation_delta_x = TouchpadToXTranslation(scroll_delta_x, x_translation_offset_); @@ -304,13 +305,16 @@ : transformed_animation_layer_bounds.x() > -kMinDistanceBeforeScreenshotDp; + // TODO(sammiequon): Make GetIndexOfMostVisibleDeskScreenshot() public and + // have DeskActivationAnimation keep track of |visible_desk_index_|. Right now + // OnVisibleDeskChanged will get called once for each display. const int old_visible_desk_index = visible_desk_index_; visible_desk_index_ = GetIndexOfMostVisibleDeskScreenshot(); if (old_visible_desk_index != visible_desk_index_) delegate_->OnVisibleDeskChanged(); if (!going_out_of_bounds) - return false; + return base::nullopt; // The upcoming desk we need to show will be an adjacent desk to the desk at // |visible_desk_index_| based on |moving_left|. @@ -318,13 +322,17 @@ if (new_desk_index < 0 || new_desk_index >= int{DesksController::Get()->desks().size()}) { - return false; + return base::nullopt; } - ending_desk_index_ = new_desk_index; + return new_desk_index; +} + +void RootWindowDeskSwitchAnimator::PrepareForEndingDeskScreenshot( + int new_ending_desk_index) { + ending_desk_index_ = new_ending_desk_index; ending_desk_screenshot_retries_ = 0; ending_desk_screenshot_taken_ = false; - return true; } int RootWindowDeskSwitchAnimator::EndSwipeAnimation() { @@ -346,9 +354,13 @@ if (!ending_desk_screenshot_taken_) weak_ptr_factory_.InvalidateWeakPtrs(); - ending_desk_index_ = visible_desk_index_; + // In tests, StartAnimation() may trigger OnDeskSwitchAnimationFinished() + // right away which may delete |this|. Store the target index in a + // local so we do not try to access a member of a deleted object. + const int ending_desk_index = visible_desk_index_; + ending_desk_index_ = ending_desk_index; StartAnimation(); - return ending_desk_index_; + return ending_desk_index; } void RootWindowDeskSwitchAnimator::OnImplicitAnimationsCompleted() {
diff --git a/ash/wm/desks/root_window_desk_switch_animator.h b/ash/wm/desks/root_window_desk_switch_animator.h index 9bb431ba..50dd8d3 100644 --- a/ash/wm/desks/root_window_desk_switch_animator.h +++ b/ash/wm/desks/root_window_desk_switch_animator.h
@@ -263,8 +263,17 @@ // Called as a user is performing a touchpad swipe. Requests a new screenshot // if necessary based on the last direction as specified in |scroll_delta_x|. // |scroll_delta_x| is in touchpad units, it will be converted to display - // units and then used to shift the animation layer. - bool UpdateSwipeAnimation(float scroll_delta_x); + // units and then used to shift the animation layer. If the animation layer is + // near its boundaries, this will return an index for the desk we should take + // a screenshot for. If we are not near the boundaries, or if there is no next + // adjacent desk in the direction we are heading, return base::nullopt. The + // delegate is responsible for requesting the screenshot. + base::Optional<int> UpdateSwipeAnimation(float scroll_delta_x); + + // Maybe called after UpdateSwipeAnimation() if we need a new screenshot. + // Updates |ending_desk_index_| and resets some other internal state related + // to the ending desk screenshot. + void PrepareForEndingDeskScreenshot(int new_ending_desk_index); // Called when a user ends a touchpad swipe. This will animate to the most // visible desk, whose index is also returned.
diff --git a/ash/wm/desks/root_window_desk_switch_animator_unittest.cc b/ash/wm/desks/root_window_desk_switch_animator_unittest.cc index 7ad2418..921b8bf 100644 --- a/ash/wm/desks/root_window_desk_switch_animator_unittest.cc +++ b/ash/wm/desks/root_window_desk_switch_animator_unittest.cc
@@ -486,12 +486,18 @@ // Swipe enough so that our third and fourth desk screenshots are taken, and // then swipe so that the fourth desk is fully shown. There should be 3 // visible desk changes in total. - ASSERT_TRUE( - animator()->UpdateSwipeAnimation(-touchpad_swipe_length_for_desk_change)); + base::Optional<int> new_index = + animator()->UpdateSwipeAnimation(-touchpad_swipe_length_for_desk_change); + ASSERT_TRUE(new_index.has_value()); + animator()->PrepareForEndingDeskScreenshot(*new_index); TakeEndingDeskScreenshotAndWait(); - ASSERT_TRUE( - animator()->UpdateSwipeAnimation(-touchpad_swipe_length_for_desk_change)); + + new_index = + animator()->UpdateSwipeAnimation(-touchpad_swipe_length_for_desk_change); + ASSERT_TRUE(new_index.has_value()); + animator()->PrepareForEndingDeskScreenshot(*new_index); TakeEndingDeskScreenshotAndWait(); + animator()->UpdateSwipeAnimation(-3 * touchpad_swipe_length_for_desk_change); EXPECT_EQ(3, visible_desk_changed_count());
diff --git a/ash/wm/gestures/wm_gesture_handler_unittest.cc b/ash/wm/gestures/wm_gesture_handler_unittest.cc index 4bf8c91..3141538e 100644 --- a/ash/wm/gestures/wm_gesture_handler_unittest.cc +++ b/ash/wm/gestures/wm_gesture_handler_unittest.cc
@@ -129,7 +129,7 @@ auto* animation = DesksController::Get()->animation(); DCHECK(animation); auto* desk_switch_animator = - animation->GetFirstDeskSwitchAnimatorForTesting(); + animation->GetDeskSwitchAnimatorAtIndexForTesting(0); base::RunLoop run_loop; RootWindowDeskSwitchAnimatorTestApi(desk_switch_animator) .SetOnEndingScreenshotTakenCallback(run_loop.QuitClosure());
diff --git a/ash/wm/window_resizer.cc b/ash/wm/window_resizer.cc index 5323b18..87f812a 100644 --- a/ash/wm/window_resizer.cc +++ b/ash/wm/window_resizer.cc
@@ -469,7 +469,6 @@ DCHECK(!min_size.IsEmpty()); DCHECK(!max_size.IsEmpty()); - gfx::SizeMinMaxToAspectRatio(aspect_ratio, &min_size, &max_size); gfx::SizeRectToAspectRatio(GetWindowResizeEdge(details().window_component), aspect_ratio, min_size, max_size, new_bounds); }
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc index 1081ef361..5650893c5 100644 --- a/base/allocator/partition_allocator/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -1222,8 +1222,7 @@ (slot_span->bucket->num_system_pages_per_slot_span * SystemPageSize()) / (very_small_size + kExtraAllocSize); first_slot_span_slots = - (SystemPageSize() + very_small_size + kExtraAllocSize - 1) / - (very_small_size + kExtraAllocSize); + SystemPageSize() / (very_small_size + kExtraAllocSize); EXPECT_EQ(total_slots - first_slot_span_slots, slot_span->num_unprovisioned_slots);
diff --git a/base/ranges/algorithm.h b/base/ranges/algorithm.h index aa9c66d9..9560558 100644 --- a/base/ranges/algorithm.h +++ b/base/ranges/algorithm.h
@@ -4299,7 +4299,7 @@ // // Returns: `last`. // -// Complexity: At most `3 log(last - first)` comparisons and twice as many +// Complexity: At most `3 * (last - first)` comparisons and twice as many // projections. // // Reference: https://wg21.link/make.heap#:~:text=ranges::make_heap(I @@ -4323,7 +4323,7 @@ // // Returns: `end(range)`. // -// Complexity: At most `3 log(size(range))` comparisons and twice as many +// Complexity: At most `3 * size(range)` comparisons and twice as many // projections. // // Reference: https://wg21.link/make.heap#:~:text=ranges::make_heap(R
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 5440699..9bbfd832 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20201207.1.1 +0.20201208.0.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 5440699..1662aa2a 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20201207.1.1 +0.20201207.3.1
diff --git a/chrome/VERSION b/chrome/VERSION index d191b27c..646113a 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=89 MINOR=0 -BUILD=4349 +BUILD=4350 PATCH=0
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 598ddef..547c01d 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -346,8 +346,6 @@ "java/src/org/chromium/chrome/browser/contacts_picker/ChromePickerAdapter.java", "java/src/org/chromium/chrome/browser/content/ContentUtils.java", "java/src/org/chromium/chrome/browser/content_capture/ContentCaptureHistoryDeletionObserver.java", - "java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java", - "java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java", "java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java", "java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java", "java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorFactory.java", @@ -1248,7 +1246,6 @@ "java/src/org/chromium/chrome/browser/signin/ConfirmManagedSyncDataDialog.java", "java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachine.java", "java/src/org/chromium/chrome/browser/signin/ConfirmSyncDataStateMachineDelegate.java", - "java/src/org/chromium/chrome/browser/signin/GoogleActivityController.java", "java/src/org/chromium/chrome/browser/signin/PersonalizedSigninPromoView.java", "java/src/org/chromium/chrome/browser/signin/ProfileDataCache.java", "java/src/org/chromium/chrome/browser/signin/SignOutDialogFragment.java",
diff --git a/chrome/android/features/tab_ui/BUILD.gn b/chrome/android/features/tab_ui/BUILD.gn index 9fd24cf..f8899853 100644 --- a/chrome/android/features/tab_ui/BUILD.gn +++ b/chrome/android/features/tab_ui/BUILD.gn
@@ -64,6 +64,7 @@ "java/res/layout/iph_drag_and_drop_dialog_layout.xml", "java/res/layout/new_tab_tile_card_item.xml", "java/res/layout/price_card.xml", + "java/res/layout/price_welcome_message_card_item.xml", "java/res/layout/selectable_tab_grid_card_item.xml", "java/res/layout/selectable_tab_list_card_item.xml", "java/res/layout/single_tab_view_layout.xml", @@ -123,6 +124,10 @@ "java/src/org/chromium/chrome/browser/tasks/tab_management/NewTabTileViewBinder.java", "java/src/org/chromium/chrome/browser/tasks/tab_management/NewTabTileViewProperties.java", "java/src/org/chromium/chrome/browser/tasks/tab_management/PriceCardView.java", + "java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardView.java", + "java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewBinder.java", + "java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewModel.java", + "java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageService.java", "java/src/org/chromium/chrome/browser/tasks/tab_management/SelectableTabGridView.java", "java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogCoordinator.java", "java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogMediator.java",
diff --git a/chrome/android/features/tab_ui/java/res/layout/price_welcome_message_card_item.xml b/chrome/android/features/tab_ui/java/res/layout/price_welcome_message_card_item.xml new file mode 100644 index 0000000..5c3f7d0b --- /dev/null +++ b/chrome/android/features/tab_ui/java/res/layout/price_welcome_message_card_item.xml
@@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2020 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> +<org.chromium.chrome.browser.tasks.tab_management.PriceWelcomeMessageCardView + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/tab_grid_price_welcome_message_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@drawable/message_card_background_with_inset"> + <LinearLayout + android:id="@+id/card_view" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_gravity="center" + android:orientation="vertical"> + <org.chromium.chrome.browser.tasks.tab_management.PriceCardView + android:id="@+id/price_info_box" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:gravity="center_horizontal" + android:layout_gravity="center" + android:layout_marginTop="16dp" + android:layout_marginBottom="16dp"/> + <TextView + android:id="@+id/title" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="4dp" + android:layout_gravity="center_horizontal" + android:textAppearance="@style/TextAppearance.TextLarge.Primary" + android:gravity="center_horizontal" /> + <TextView + android:id="@+id/content" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_gravity="center_horizontal" + android:gravity="center_horizontal" + android:textAppearance="@style/TextAppearance.TextMedium.Secondary" + android:layout_marginStart ="24dp" + android:layout_marginEnd="24dp" /> + <org.chromium.ui.widget.ButtonCompat + android:id="@+id/action_button" + android:layout_width="match_parent" + android:layout_height="wrap_content" + style="@style/FilledButton.Flat" + android:layout_gravity="center" + android:layout_marginTop="16dp" + android:layout_marginBottom="16dp" + android:layout_marginStart ="24dp" + android:layout_marginEnd="24dp" + android:paddingTop="8dp" + android:paddingBottom="8dp" /> + </LinearLayout> + <org.chromium.ui.widget.ChromeImageView + android:id="@+id/close_button" + android:layout_width="24dp" + android:layout_height="24dp" + android:contentDescription="@string/close" + android:layout_gravity="end" + android:layout_marginTop="16dp" + android:layout_marginEnd="16dp" + android:tint="@color/default_icon_color"/> +</org.chromium.chrome.browser.tasks.tab_management.PriceWelcomeMessageCardView>
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardProviderMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardProviderMediator.java index f2a92e4..b440a78 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardProviderMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardProviderMediator.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.tasks.tab_management; import static org.chromium.chrome.browser.tasks.tab_management.MessageService.MessageType.IPH; +import static org.chromium.chrome.browser.tasks.tab_management.MessageService.MessageType.PRICE_WELCOME; import static org.chromium.chrome.browser.tasks.tab_management.MessageService.MessageType.TAB_SUGGESTION; import android.content.Context; @@ -103,6 +104,11 @@ assert data instanceof IphMessageService.IphMessageData; return IphMessageCardViewModel.create(mContext, this::invalidateShownMessage, (IphMessageService.IphMessageData) data); + case PRICE_WELCOME: + assert data instanceof PriceWelcomeMessageService.PriceWelcomeMessageData; + return PriceWelcomeMessageCardViewModel.create(mContext, + this::invalidateShownMessage, + (PriceWelcomeMessageService.PriceWelcomeMessageData) data); default: return new PropertyModel.Builder(MessageCardViewProperties.ALL_KEYS) .with(MessageCardViewProperties.IS_INCOGNITO, false)
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardViewProperties.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardViewProperties.java index 39a1ef1..f4e6ab05 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardViewProperties.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageCardViewProperties.java
@@ -7,6 +7,7 @@ import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_ALPHA; import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_TYPE; +import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -46,10 +47,16 @@ new PropertyModel.WritableBooleanPropertyKey(); public static final PropertyModel.WritableBooleanPropertyKey IS_INCOGNITO = new PropertyModel.WritableBooleanPropertyKey(); + public static final PropertyModel.WritableObjectPropertyKey<String> TITLE_TEXT = + new PropertyModel.WritableObjectPropertyKey<>(); + public static final PropertyModel + .WritableObjectPropertyKey<ShoppingPersistedTabData.PriceDrop> PRICE_DROP = + new PropertyModel.WritableObjectPropertyKey<>(); - public static final PropertyKey[] ALL_KEYS = new PropertyKey[] {ACTION_TEXT, DESCRIPTION_TEXT, - DESCRIPTION_TEXT_TEMPLATE, MESSAGE_TYPE, ICON_PROVIDER, UI_ACTION_PROVIDER, - UI_DISMISS_ACTION_PROVIDER, MESSAGE_SERVICE_ACTION_PROVIDER, - MESSAGE_SERVICE_DISMISS_ACTION_PROVIDER, DISMISS_BUTTON_CONTENT_DESCRIPTION, - SHOULD_KEEP_AFTER_REVIEW, IS_ICON_VISIBLE, CARD_TYPE, CARD_ALPHA, IS_INCOGNITO}; + public static final PropertyKey[] ALL_KEYS = + new PropertyKey[] {ACTION_TEXT, DESCRIPTION_TEXT, DESCRIPTION_TEXT_TEMPLATE, + MESSAGE_TYPE, ICON_PROVIDER, UI_ACTION_PROVIDER, UI_DISMISS_ACTION_PROVIDER, + MESSAGE_SERVICE_ACTION_PROVIDER, MESSAGE_SERVICE_DISMISS_ACTION_PROVIDER, + DISMISS_BUTTON_CONTENT_DESCRIPTION, SHOULD_KEEP_AFTER_REVIEW, IS_ICON_VISIBLE, + CARD_TYPE, CARD_ALPHA, IS_INCOGNITO, TITLE_TEXT, PRICE_DROP}; }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageService.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageService.java index b01d6a3..ffb37bb 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageService.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/MessageService.java
@@ -18,13 +18,15 @@ * understands. */ public class MessageService { - @IntDef({MessageType.TAB_SUGGESTION, MessageType.IPH, MessageType.ALL}) + @IntDef({MessageType.TAB_SUGGESTION, MessageType.IPH, MessageType.PRICE_WELCOME, + MessageType.ALL}) @Retention(RetentionPolicy.SOURCE) public @interface MessageType { int FOR_TESTING = 0; int TAB_SUGGESTION = 1; int IPH = 2; - int ALL = 3; + int PRICE_WELCOME = 3; + int ALL = 4; } /**
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilities.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilities.java index 171143f..b8b31a7 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilities.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilities.java
@@ -19,6 +19,8 @@ @VisibleForTesting public static final String TRACK_PRICES_ON_TABS = ChromePreferenceKeys.PRICE_TRACKING_TRACK_PRICES_ON_TABS; + private static final String PRICE_WELCOME_MESSAGE_CARD = + ChromePreferenceKeys.PRICE_TRACKING_PRICE_WELCOME_MESSAGE_CARD; @VisibleForTesting public static final SharedPreferencesManager SHARED_PREFERENCES_MANAGER = @@ -40,4 +42,18 @@ return SHARED_PREFERENCES_MANAGER.readBoolean( TRACK_PRICES_ON_TABS, TabUiFeatureUtilities.isPriceTrackingEnabled()); } + + /** + * Forbid showing the PriceWelcomeMessageCard any more. + */ + public static void disablePriceWelcomeMessageCard() { + SHARED_PREFERENCES_MANAGER.writeBoolean(PRICE_WELCOME_MESSAGE_CARD, false); + } + + /** + * @return Whether the PriceWelcomeMessageCard is disabled by users. + */ + public static boolean isPriceWelcomeMessageCardDisabled() { + return !SHARED_PREFERENCES_MANAGER.readBoolean(PRICE_WELCOME_MESSAGE_CARD, true); + } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardView.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardView.java new file mode 100644 index 0000000..f16e419 --- /dev/null +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardView.java
@@ -0,0 +1,108 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_management; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.util.AttributeSet; +import android.widget.FrameLayout; +import android.widget.TextView; + +import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData; +import org.chromium.chrome.tab_ui.R; +import org.chromium.ui.widget.ButtonCompat; +import org.chromium.ui.widget.ChromeImageView; + +import java.lang.ref.WeakReference; + +class PriceWelcomeMessageCardView extends FrameLayout { + private static WeakReference<Bitmap> sCloseButtonBitmapWeakRef; + + private PriceCardView mPriceInfoBox; + private TextView mTitle; + private TextView mContent; + private ButtonCompat mActionButton; + private ChromeImageView mCloseButton; + + public PriceWelcomeMessageCardView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + + mPriceInfoBox = findViewById(R.id.price_info_box); + mTitle = findViewById(R.id.title); + mContent = findViewById(R.id.content); + mActionButton = findViewById(R.id.action_button); + mCloseButton = findViewById(R.id.close_button); + + if (sCloseButtonBitmapWeakRef == null || sCloseButtonBitmapWeakRef.get() == null) { + int closeButtonSize = + (int) getResources().getDimension(R.dimen.tab_grid_close_button_size); + Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.btn_close); + sCloseButtonBitmapWeakRef = new WeakReference<>( + Bitmap.createScaledBitmap(bitmap, closeButtonSize, closeButtonSize, true)); + } + mCloseButton.setImageBitmap(sCloseButtonBitmapWeakRef.get()); + } + + /** + * Set title text. + * @param titleText Text to be displayed. + */ + void setTitleText(String titleText) { + mTitle.setText(titleText); + } + + /** + * Set content text. + * @param contentText Text to be displayed. + */ + void setContentText(String contentText) { + mContent.setText(contentText); + } + + /** + * Set action text for the action button. + * @param actionText Text to be displayed. + */ + void setActionText(String actionText) { + mActionButton.setText(actionText); + } + + /** + * Set click listener for the action button. + * @param listener {@link android.view.View.OnClickListener} for the action button. + */ + void setActionButtonOnClickListener(OnClickListener listener) { + mActionButton.setOnClickListener(listener); + } + + /** + * Set content description for dismiss button. + * @param description The content description. + */ + void setDismissButtonContentDescription(String description) { + mCloseButton.setContentDescription(description); + } + + /** + * Set {@link android.view.View.OnClickListener} for dismiss button. + * @param listener {@link android.view.View.OnClickListener} to set. + */ + void setDismissButtonOnClickListener(OnClickListener listener) { + mCloseButton.setOnClickListener(listener); + } + + /** + * Set price strings for the price info box. + */ + void setPriceInfoBoxStrings(ShoppingPersistedTabData.PriceDrop priceDrop) { + mPriceInfoBox.setPriceStrings(priceDrop.price, priceDrop.previousPrice); + } +}
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewBinder.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewBinder.java new file mode 100644 index 0000000..55939d1 --- /dev/null +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewBinder.java
@@ -0,0 +1,66 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_management; + +import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_ALPHA; + +import android.view.ViewGroup; + +import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData; +import org.chromium.ui.modelutil.PropertyKey; +import org.chromium.ui.modelutil.PropertyModel; + +/** + * ViewBinder for PriceWelcomeMessageCardItem. + */ +class PriceWelcomeMessageCardViewBinder { + public static void bind(PropertyModel model, ViewGroup view, PropertyKey propertyKey) { + assert view instanceof PriceWelcomeMessageCardView; + + PriceWelcomeMessageCardView itemView = (PriceWelcomeMessageCardView) view; + if (MessageCardViewProperties.ACTION_TEXT == propertyKey) { + itemView.setActionText(model.get(MessageCardViewProperties.ACTION_TEXT)); + itemView.setActionButtonOnClickListener(v -> { + MessageCardView.ReviewActionProvider uiProvider = + model.get(MessageCardViewProperties.UI_ACTION_PROVIDER); + if (uiProvider != null) uiProvider.review(); + + MessageCardView.ReviewActionProvider serviceProvider = + model.get(MessageCardViewProperties.MESSAGE_SERVICE_ACTION_PROVIDER); + if (serviceProvider != null) serviceProvider.review(); + + MessageCardView.DismissActionProvider uiDismissProvider = + model.get(MessageCardViewProperties.UI_DISMISS_ACTION_PROVIDER); + if (uiDismissProvider != null + && !model.get(MessageCardViewProperties.SHOULD_KEEP_AFTER_REVIEW)) { + uiDismissProvider.dismiss(model.get(MessageCardViewProperties.MESSAGE_TYPE)); + } + }); + } else if (MessageCardViewProperties.TITLE_TEXT == propertyKey) { + itemView.setTitleText(model.get(MessageCardViewProperties.TITLE_TEXT)); + } else if (MessageCardViewProperties.DESCRIPTION_TEXT == propertyKey) { + itemView.setContentText(model.get(MessageCardViewProperties.DESCRIPTION_TEXT)); + } else if (MessageCardViewProperties.DISMISS_BUTTON_CONTENT_DESCRIPTION == propertyKey) { + itemView.setDismissButtonContentDescription( + model.get(MessageCardViewProperties.DISMISS_BUTTON_CONTENT_DESCRIPTION)); + itemView.setDismissButtonOnClickListener(v -> { + int type = model.get(MessageCardViewProperties.MESSAGE_TYPE); + MessageCardView.DismissActionProvider uiProvider = + model.get(MessageCardViewProperties.UI_DISMISS_ACTION_PROVIDER); + if (uiProvider != null) uiProvider.dismiss(type); + + MessageCardView.DismissActionProvider serviceProvider = model.get( + MessageCardViewProperties.MESSAGE_SERVICE_DISMISS_ACTION_PROVIDER); + if (serviceProvider != null) serviceProvider.dismiss(type); + }); + } else if (MessageCardViewProperties.PRICE_DROP == propertyKey) { + ShoppingPersistedTabData.PriceDrop priceDrop = + model.get(MessageCardViewProperties.PRICE_DROP); + if (priceDrop != null) itemView.setPriceInfoBoxStrings(priceDrop); + } else if (CARD_ALPHA == propertyKey) { + itemView.setAlpha(model.get(CARD_ALPHA)); + } + } +}
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewModel.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewModel.java new file mode 100644 index 0000000..5463bfb --- /dev/null +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageCardViewModel.java
@@ -0,0 +1,58 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_management; + +import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_ALPHA; +import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_TYPE; +import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.ModelType.MESSAGE; + +import android.content.Context; + +import org.chromium.chrome.tab_ui.R; +import org.chromium.ui.modelutil.PropertyModel; + +/** + * This is a util class for creating the property model of the {@link PriceWelcomeMessageCardView}. + */ +public class PriceWelcomeMessageCardViewModel { + /** + * Create a {@link PropertyModel} for {@link PriceWelcomeMessageCardView}. + * @param context The {@link Context} to use. + * @param uiDismissActionProvider The {@link MessageCardView.DismissActionProvider} to set. + * @param data The {@link PriceWelcomeMessageService.PriceWelcomeMessageData} to use. + * @return A {@link PropertyModel} for the given {@code data}. + */ + public static PropertyModel create(Context context, + MessageCardView.DismissActionProvider uiDismissActionProvider, + PriceWelcomeMessageService.PriceWelcomeMessageData data) { + String titleText = context.getString(R.string.price_drop_spotted_title); + String contentText = context.getString(R.string.price_drop_spotted_content); + String actionText = context.getString(R.string.price_drop_spotted_show_me); + String dismissButtonContextDescription = + context.getString(R.string.accessibility_tab_suggestion_dismiss_button); + + return new PropertyModel.Builder(MessageCardViewProperties.ALL_KEYS) + .with(MessageCardViewProperties.MESSAGE_TYPE, + MessageService.MessageType.PRICE_WELCOME) + .with(MessageCardViewProperties.UI_DISMISS_ACTION_PROVIDER, uiDismissActionProvider) + .with(MessageCardViewProperties.MESSAGE_SERVICE_DISMISS_ACTION_PROVIDER, + data.getDismissActionProvider()) + .with(MessageCardViewProperties.MESSAGE_SERVICE_ACTION_PROVIDER, + data.getReviewActionProvider()) + .with(MessageCardViewProperties.DESCRIPTION_TEXT, contentText) + .with(MessageCardViewProperties.DESCRIPTION_TEXT_TEMPLATE, null) + .with(MessageCardViewProperties.ACTION_TEXT, actionText) + .with(MessageCardViewProperties.DISMISS_BUTTON_CONTENT_DESCRIPTION, + dismissButtonContextDescription) + .with(MessageCardViewProperties.SHOULD_KEEP_AFTER_REVIEW, false) + .with(MessageCardViewProperties.IS_ICON_VISIBLE, false) + .with(MessageCardViewProperties.IS_INCOGNITO, false) + .with(MessageCardViewProperties.TITLE_TEXT, titleText) + .with(MessageCardViewProperties.PRICE_DROP, data.getPriceDrop()) + .with(CARD_TYPE, MESSAGE) + .with(CARD_ALPHA, 1f) + .build(); + } +} \ No newline at end of file
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageService.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageService.java new file mode 100644 index 0000000..637f3d0 --- /dev/null +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceWelcomeMessageService.java
@@ -0,0 +1,153 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.tasks.tab_management; + +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData; + +/** + * One of the concrete {@link MessageService} that only serves {@link MessageType#PRICE_WELCOME}. + */ +public class PriceWelcomeMessageService extends MessageService { + /** + * Provides the binding tab ID and the price drop of the binding tab. + */ + static class PriceTabData { + public final int bindingTabId; + public final ShoppingPersistedTabData.PriceDrop priceDrop; + + PriceTabData(int bindingTabId, ShoppingPersistedTabData.PriceDrop priceDrop) { + this.bindingTabId = bindingTabId; + this.priceDrop = priceDrop; + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof PriceTabData)) return false; + PriceTabData priceTabData = (PriceTabData) object; + return this.bindingTabId == priceTabData.bindingTabId + && this.priceDrop.equals(priceTabData.priceDrop); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + bindingTabId; + result = 31 * result + (priceDrop == null ? 0 : priceDrop.hashCode()); + return result; + } + } + + /** + * An interface to help build the PriceWelcomeMessage. + */ + public interface PriceWelcomeMessageProvider { + /** + * This method gets the information of the first tab showing price card. + * + * @return The PriceTabData including the tab ID and the price drop. + */ + PriceTabData getFirstTabShowingPriceCard(); + + /** + * This method gets the tab index from tab ID. + * + * @param tabId The tab ID to search for. + * @return the index within the {@link TabListModel}. + */ + int getTabIndexFromTabId(int tabId); + } + + /** + * An interface to handle the review action of PriceWelcomeMessage. + */ + public interface PriceWelcomeMessageReviewActionProvider { + /** + * This method scrolls to the binding tab of the PriceWelcomeMessage. + * + * @param tabIndex The index of the {@link Tab} that is binding to PriceWelcomeMessage. + */ + void scrollToBindingTab(int tabIndex); + } + + /** + * This is the data type that this MessageService is serving to its Observer. + */ + class PriceWelcomeMessageData implements MessageData { + private final ShoppingPersistedTabData.PriceDrop mPriceDrop; + private final MessageCardView.ReviewActionProvider mReviewActionProvider; + private final MessageCardView.DismissActionProvider mDismissActionProvider; + + PriceWelcomeMessageData(ShoppingPersistedTabData.PriceDrop priceDrop, + MessageCardView.ReviewActionProvider reviewActionProvider, + MessageCardView.DismissActionProvider dismissActionProvider) { + mPriceDrop = priceDrop; + mReviewActionProvider = reviewActionProvider; + mDismissActionProvider = dismissActionProvider; + } + + /** + * @return The {@link MessageCardViewProperties#PRICE_DROP} for the associated + * PRICE_WELCOME. + */ + ShoppingPersistedTabData.PriceDrop getPriceDrop() { + return mPriceDrop; + } + + /** + * @return The {@link MessageCardView.ReviewActionProvider} for the associated + * PRICE_WELCOME. + */ + MessageCardView.ReviewActionProvider getReviewActionProvider() { + return mReviewActionProvider; + } + + /** + * @return The {@link MessageCardView.DismissActionProvider} for the associated + * PRICE_WELCOME. + */ + MessageCardView.DismissActionProvider getDismissActionProvider() { + return mDismissActionProvider; + } + } + + private final PriceWelcomeMessageProvider mPriceWelcomeMessageProvider; + private final PriceWelcomeMessageReviewActionProvider mPriceWelcomeMessageReviewActionProvider; + + private PriceTabData mPriceTabData; + + PriceWelcomeMessageService(PriceWelcomeMessageProvider priceWelcomeMessageProvider, + PriceWelcomeMessageReviewActionProvider priceWelcomeMessageReviewActionProvider) { + super(MessageType.PRICE_WELCOME); + mPriceTabData = null; + mPriceWelcomeMessageProvider = priceWelcomeMessageProvider; + mPriceWelcomeMessageReviewActionProvider = priceWelcomeMessageReviewActionProvider; + } + + void preparePriceMessage() { + if (PriceTrackingUtilities.isPriceWelcomeMessageCardDisabled()) return; + PriceTabData priceTabData = mPriceWelcomeMessageProvider.getFirstTabShowingPriceCard(); + if (priceTabData == null) { + mPriceTabData = null; + sendInvalidNotification(); + } else if (!priceTabData.equals(mPriceTabData)) { + mPriceTabData = priceTabData; + sendInvalidNotification(); + sendAvailabilityNotification(new PriceWelcomeMessageData( + mPriceTabData.priceDrop, this::review, (int messageType) -> dismiss())); + } + } + + private void review() { + assert mPriceTabData != null; + mPriceWelcomeMessageReviewActionProvider.scrollToBindingTab( + mPriceWelcomeMessageProvider.getTabIndexFromTabId(mPriceTabData.bindingTabId)); + PriceTrackingUtilities.disablePriceWelcomeMessageCard(); + } + + private void dismiss() { + PriceTrackingUtilities.disablePriceWelcomeMessageCard(); + } +}
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java index cb81c3c..22e467d 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java
@@ -101,6 +101,7 @@ public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { final int dragFlags = viewHolder.getItemViewType() == TabProperties.UiType.MESSAGE || viewHolder.getItemViewType() == TabProperties.UiType.NEW_TAB_TILE + || viewHolder.getItemViewType() == TabProperties.UiType.PRICE_WELCOME ? 0 : mDragFlags; final int swipeFlags = viewHolder.getItemViewType() == TabProperties.UiType.NEW_TAB_TILE @@ -114,7 +115,8 @@ public boolean canDropOver(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder current, @NonNull RecyclerView.ViewHolder target) { if (target.getItemViewType() == TabProperties.UiType.MESSAGE - || target.getItemViewType() == TabProperties.UiType.NEW_TAB_TILE) { + || target.getItemViewType() == TabProperties.UiType.NEW_TAB_TILE + || target.getItemViewType() == TabProperties.UiType.PRICE_WELCOME) { return false; } return super.canDropOver(recyclerView, current, target);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java index 513924692..693eee73 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java
@@ -225,15 +225,19 @@ .fetch((shoppingPersistedTabData) -> { if (shoppingPersistedTabData.getPriceDrop() == null) { priceCardView.setVisibility(View.GONE); + model.set(TabProperties.PRICE_DROP, null); } else { priceCardView.setPriceStrings( shoppingPersistedTabData.getPriceDrop().price, shoppingPersistedTabData.getPriceDrop().previousPrice); priceCardView.setVisibility(View.VISIBLE); + model.set(TabProperties.PRICE_DROP, + shoppingPersistedTabData.getPriceDrop()); } }); } else { priceCardView.setVisibility(View.GONE); + model.set(TabProperties.PRICE_DROP, null); } } else if (TabProperties.PAGE_INFO_LISTENER == propertyKey) { TabListMediator.TabActionListener listener =
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java index 50c91bf..298d3e2d 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java
@@ -30,6 +30,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tasks.pseudotab.PseudoTab; +import org.chromium.chrome.browser.tasks.tab_management.PriceWelcomeMessageService.PriceTabData; import org.chromium.chrome.browser.tasks.tab_management.TabProperties.UiType; import org.chromium.chrome.features.start_surface.StartSurfaceConfiguration; import org.chromium.chrome.tab_ui.R; @@ -48,7 +49,8 @@ /** * Coordinator for showing UI for a list of tabs. Can be used in GRID or STRIP modes. */ -public class TabListCoordinator implements Destroyable { +public class TabListCoordinator + implements PriceWelcomeMessageService.PriceWelcomeMessageProvider, Destroyable { /** * Modes of showing the list of tabs. * @@ -339,6 +341,13 @@ } /** + * @return The index of the model list where the PriceWelcomeMessage should be inserted. + */ + int getPriceWelcomeMessageIndex() { + return mModel.size(); + } + + /** * @return The container {@link androidx.recyclerview.widget.RecyclerView} that is showing the * tab list UI. */ @@ -444,4 +453,15 @@ void removeSpecialListItem(@UiType int uiType, int itemIdentifier) { mMediator.removeSpecialItemFromModel(uiType, itemIdentifier); } + + // PriceWelcomeMessageService.PriceWelcomeMessageProvider implementation. + @Override + public PriceTabData getFirstTabShowingPriceCard() { + return mModel.getFirstTabShowingPriceCard(); + } + + @Override + public int getTabIndexFromTabId(int tabId) { + return mModel.indexFromId(tabId); + } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java index 095b03b..9a580d1d 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java
@@ -1138,7 +1138,10 @@ public int getSpanSize(int position) { int itemType = mModel.get(position).type; - if (itemType == TabProperties.UiType.MESSAGE) return manager.getSpanCount(); + if (itemType == TabProperties.UiType.MESSAGE + || itemType == TabProperties.UiType.PRICE_WELCOME) { + return manager.getSpanCount(); + } return 1; } }); @@ -1286,6 +1289,7 @@ .with(TabProperties.TABSTRIP_FAVICON_BACKGROUND_COLOR_ID, tabstripFaviconBackgroundDrawableId) .with(TabProperties.ACCESSIBILITY_DELEGATE, mAccessibilityDelegate) + .with(TabProperties.PRICE_DROP, null) .with(CARD_TYPE, TAB) .build(); @@ -1562,7 +1566,7 @@ */ void removeSpecialItemFromModel(@UiType int uiType, int itemIdentifier) { int index = TabModel.INVALID_TAB_INDEX; - if (uiType == UiType.MESSAGE) { + if (uiType == UiType.MESSAGE || uiType == UiType.PRICE_WELCOME) { if (itemIdentifier == MessageService.MessageType.ALL) { while (mModel.lastIndexForMessageItem() != TabModel.INVALID_TAB_INDEX) { index = mModel.lastIndexForMessageItem(); @@ -1582,7 +1586,7 @@ } private boolean validateItemAt(int index, @UiType int uiType, int itemIdentifier) { - if (uiType == UiType.MESSAGE) { + if (uiType == UiType.MESSAGE || uiType == UiType.PRICE_WELCOME) { return mModel.get(index).type == uiType && mModel.get(index).model.get(MESSAGE_TYPE) == itemIdentifier; } else if (uiType == UiType.NEW_TAB_TILE) {
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListModel.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListModel.java index df0d5c49..bd0ed3fa 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListModel.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListModel.java
@@ -19,6 +19,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.browser.tasks.tab_management.PriceWelcomeMessageService.PriceTabData; import org.chromium.ui.modelutil.MVCListAdapter; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyListModel; @@ -203,4 +204,18 @@ get(index).model.set(TabProperties.CARD_ANIMATION_STATUS, status); } + + /** + * Get the first tab showing price card. + */ + public PriceTabData getFirstTabShowingPriceCard() { + for (int i = 0; i < size(); i++) { + PropertyModel model = get(i).model; + if ((model.get(CARD_TYPE) == TAB) && (model.get(TabProperties.PRICE_DROP) != null)) { + return new PriceTabData( + model.get(TabProperties.TAB_ID), model.get(TabProperties.PRICE_DROP)); + } + } + return null; + } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabProperties.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabProperties.java index 09f4ada..2a00bd5 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabProperties.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabProperties.java
@@ -13,6 +13,7 @@ import androidx.annotation.IntDef; +import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData; import org.chromium.components.browser_ui.widget.selectable_list.SelectionDelegate; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -28,7 +29,7 @@ public class TabProperties { /** IDs for possible types of UI in the tab list. */ @IntDef({UiType.SELECTABLE, UiType.CLOSABLE, UiType.STRIP, UiType.MESSAGE, UiType.DIVIDER, - UiType.NEW_TAB_TILE}) + UiType.NEW_TAB_TILE, UiType.PRICE_WELCOME}) @Retention(RetentionPolicy.SOURCE) public @interface UiType { int SELECTABLE = 0; @@ -37,6 +38,7 @@ int MESSAGE = 3; int DIVIDER = 4; int NEW_TAB_TILE = 5; + int PRICE_WELCOME = 6; } public static final PropertyModel.WritableIntPropertyKey TAB_ID = @@ -118,6 +120,9 @@ public static final WritableObjectPropertyKey<String> CLOSE_BUTTON_DESCRIPTION_STRING = new WritableObjectPropertyKey<>(); + public static final WritableObjectPropertyKey<ShoppingPersistedTabData.PriceDrop> PRICE_DROP = + new WritableObjectPropertyKey<>(); + public static final PropertyKey[] ALL_KEYS_TAB_GRID = new PropertyKey[] {TAB_ID, TAB_SELECTED_LISTENER, TAB_CLOSED_LISTENER, FAVICON, THUMBNAIL_FETCHER, IPH_PROVIDER, TITLE, IS_SELECTED, CHECKED_DRAWABLE_STATE_LIST, CREATE_GROUP_LISTENER, CARD_ALPHA, @@ -127,7 +132,7 @@ SELECTABLE_TAB_ACTION_BUTTON_SELECTED_BACKGROUND, URL_DOMAIN, ACCESSIBILITY_DELEGATE, SEARCH_QUERY, PAGE_INFO_LISTENER, PAGE_INFO_ICON_DRAWABLE_ID, CARD_TYPE, CONTENT_DESCRIPTION_STRING, CLOSE_BUTTON_DESCRIPTION_STRING, - SHOPPING_PERSISTED_TAB_DATA_FETCHER}; + SHOPPING_PERSISTED_TAB_DATA_FETCHER, PRICE_DROP}; public static final PropertyKey[] ALL_KEYS_TAB_STRIP = new PropertyKey[] {TAB_ID, TAB_SELECTED_LISTENER, TAB_CLOSED_LISTENER, FAVICON,
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java index 4ebc7fb..a0c7b6a11 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java
@@ -109,6 +109,7 @@ private ViewGroup mContainer; private TabCreatorManager mTabCreatorManager; private boolean mIsInitialized; + private PriceWelcomeMessageService mPriceWelcomeMessageService; private final ViewGroup mRootView; private final MenuOrKeyboardActionController @@ -211,9 +212,14 @@ mMessageCardProviderCoordinator = new MessageCardProviderCoordinator( context, tabModelSelector::isIncognitoSelected, (identifier) -> { - mTabListCoordinator.removeSpecialListItem( - TabProperties.UiType.MESSAGE, identifier); - appendNextMessage(identifier); + if (identifier == MessageService.MessageType.PRICE_WELCOME) { + mTabListCoordinator.removeSpecialListItem( + TabProperties.UiType.PRICE_WELCOME, identifier); + } else { + mTabListCoordinator.removeSpecialListItem( + TabProperties.UiType.MESSAGE, identifier); + appendNextMessage(identifier); + } }); if (TabUiFeatureUtilities.isTabGroupsAndroidEnabled()) { @@ -238,6 +244,12 @@ new LayoutViewBuilder(R.layout.new_tab_tile_card_item), NewTabTileViewBinder::bind); } + + if (TabUiFeatureUtilities.isPriceTrackingEnabled()) { + mTabListCoordinator.registerItemType(TabProperties.UiType.PRICE_WELCOME, + new LayoutViewBuilder(R.layout.price_welcome_message_card_item), + PriceWelcomeMessageCardViewBinder::bind); + } } if (CachedFeatureFlags.isEnabled(ChromeFeatureList.INSTANT_START) @@ -308,6 +320,13 @@ new IphMessageService(mTabGridIphDialogCoordinator); mMessageCardProviderCoordinator.subscribeMessageService(iphMessageService); } + + if (TabUiFeatureUtilities.isPriceTrackingEnabled()) { + mPriceWelcomeMessageService = + new PriceWelcomeMessageService(mTabListCoordinator, mMediator); + mMessageCardProviderCoordinator.subscribeMessageService( + mPriceWelcomeMessageService); + } } mIsInitialized = true; } @@ -435,10 +454,12 @@ public boolean resetWithTabs( @Nullable List<PseudoTab> tabs, boolean quickMode, boolean mruMode) { mMediator.registerFirstMeaningfulPaintRecorder(); + // Make sure that before resetWithListOfTabs, there are no messages in the middle of tabs in + // our TabListModel. + removeAllAppendedMessage(); boolean showQuickly = mTabListCoordinator.resetWithListOfTabs(tabs, quickMode, mruMode); if (showQuickly) { mTabListCoordinator.removeSpecialListItem(TabProperties.UiType.NEW_TAB_TILE, 0); - removeAllAppendedMessage(); } int cardsCount = tabs == null ? 0 : tabs.size(); @@ -447,7 +468,13 @@ mNewTabTileCoordinator.getModel()); cardsCount += 1; } - if (tabs != null && tabs.size() > 0) appendMessagesTo(cardsCount); + + if (tabs != null && tabs.size() > 0) { + if (mPriceWelcomeMessageService != null) { + mPriceWelcomeMessageService.preparePriceMessage(); + } + appendMessagesTo(cardsCount); + } return showQuickly; } @@ -466,8 +493,14 @@ List<MessageCardProviderMediator.Message> messages = mMessageCardProviderCoordinator.getMessageItems(); for (int i = 0; i < messages.size(); i++) { - mTabListCoordinator.addSpecialListItemToEnd( - TabProperties.UiType.MESSAGE, messages.get(i).model); + if (messages.get(i).type == MessageService.MessageType.PRICE_WELCOME) { + mTabListCoordinator.addSpecialListItem( + mTabListCoordinator.getPriceWelcomeMessageIndex(), + TabProperties.UiType.PRICE_WELCOME, messages.get(i).model); + } else { + mTabListCoordinator.addSpecialListItemToEnd( + TabProperties.UiType.MESSAGE, messages.get(i).model); + } } sAppendedMessagesForTesting = messages.size() > 0; } @@ -478,8 +511,14 @@ List<MessageCardProviderMediator.Message> messages = mMessageCardProviderCoordinator.getMessageItems(); for (int i = 0; i < messages.size(); i++) { - mTabListCoordinator.addSpecialListItem( - index + i, TabProperties.UiType.MESSAGE, messages.get(i).model); + if (messages.get(i).type == MessageService.MessageType.PRICE_WELCOME) { + mTabListCoordinator.addSpecialListItem( + mTabListCoordinator.getPriceWelcomeMessageIndex(), + TabProperties.UiType.PRICE_WELCOME, messages.get(i).model); + } else { + mTabListCoordinator.addSpecialListItem( + index + i, TabProperties.UiType.MESSAGE, messages.get(i).model); + } } if (messages.size() > 0) sAppendedMessagesForTesting = true; }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherMediator.java index 93c658f..098f133 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherMediator.java
@@ -65,8 +65,10 @@ * The Mediator that is responsible for resetting the tab grid or carousel based on visibility and * model changes. */ -class TabSwitcherMediator implements TabSwitcher.Controller, TabListRecyclerView.VisibilityListener, - TabListMediator.GridCardOnClickListenerProvider { +class TabSwitcherMediator + implements TabSwitcher.Controller, TabListRecyclerView.VisibilityListener, + TabListMediator.GridCardOnClickListenerProvider, + PriceWelcomeMessageService.PriceWelcomeMessageReviewActionProvider { private static final String TAG = "TabSwitcherMediator"; // This should be the same as TabListCoordinator.GRID_LAYOUT_SPAN_COUNT for the selected tab @@ -778,6 +780,11 @@ } } + @Override + public void scrollToBindingTab(int tabIndex) { + mContainerViewModel.set(TabListContainerProperties.INITIAL_SCROLL_INDEX, tabIndex); + } + private boolean ableToOpenDialog(Tab tab) { return TabUiFeatureUtilities.isTabGroupsAndroidEnabled() && mTabModelSelector.isIncognitoSelected() == tab.isIncognito()
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java index 4364a656..57898d8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java
@@ -214,6 +214,7 @@ return mOrigin; } + @CalledByNative("AutofillProfile") public String getHonorificPrefix() { return mHonorificPrefix; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java index b0fa32b..b5a5f83 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java
@@ -155,13 +155,13 @@ private void fetchFaviconForTab(final Tab tab) { if (mFaviconHelper == null) mFaviconHelper = new FaviconHelper(); - // Since tab#getProfile() is not available by this time, we will use whatever last used - // profile. - // TODO (https://crbug.com/1048632): Use the current profile (i.e., regular profile or - // incognito profile) instead of always using regular profile. It works correctly now, but - // it is not safe. - mFaviconHelper.getLocalFaviconImageForURL(Profile.getLastUsedRegularProfile(), - tab.getUrlString(), mFaviconSize, new FaviconImageCallback() { + // Since tab#getProfile() is not available by this time, we will use tab#isIncognito boolean + // to get the correct profile. + Profile profile = !tab.isIncognito() + ? Profile.getLastUsedRegularProfile() + : Profile.getLastUsedRegularProfile().getPrimaryOTRProfile(); + mFaviconHelper.getLocalFaviconImageForURL( + profile, tab.getUrlString(), mFaviconSize, new FaviconImageCallback() { @Override public void onFaviconAvailable(Bitmap favicon, String iconUrl) { updateFaviconFromHistory(tab, favicon);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayContentDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayContentDelegate.java index be745f5..bd3156c5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayContentDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayContentDelegate.java
@@ -43,9 +43,8 @@ /** * Called when content started loading in the panel. - * @param url The URL that is loading. */ - public void onContentLoadStarted(String url) {} + public void onContentLoadStarted() {} /** * Called when the navigation entry has been committed.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java index ca518b6f..7ac9b6f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java
@@ -35,6 +35,7 @@ import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.content_public.common.ResourceRequestBody; import org.chromium.ui.base.ViewAndroidDelegate; +import org.chromium.url.GURL; /** * Content container for an OverlayPanel. This class is responsible for the management of the @@ -349,8 +350,8 @@ mWebContentsObserver = new WebContentsObserver(mWebContents) { @Override - public void didStartLoading(String url) { - mContentDelegate.onContentLoadStarted(url); + public void didStartLoading(GURL url) { + mContentDelegate.onContentLoadStarted(); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java index fb1caf7..8fc1b4d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java
@@ -137,7 +137,8 @@ Action.SHARE_LINK, Action.OPEN_IN_EPHEMERAL_TAB, Action.OPEN_IMAGE_IN_EPHEMERAL_TAB, Action.DIRECT_SHARE_LINK, Action.DIRECT_SHARE_IMAGE, Action.SEARCH_WITH_GOOGLE_LENS, Action.COPY_IMAGE, Action.SHOP_SIMILAR_PRODUCTS, Action.SHOP_IMAGE_WITH_GOOGLE_LENS, - Action.SEARCH_SIMILAR_PRODUCTS, Action.READ_LATER}) + Action.SEARCH_SIMILAR_PRODUCTS, Action.READ_LATER, + Action.SHOP_WITH_GOOGLE_LENS_CHIP}) @Retention(RetentionPolicy.SOURCE) public @interface Action { int OPEN_IN_NEW_TAB = 0; @@ -178,7 +179,8 @@ int SHOP_IMAGE_WITH_GOOGLE_LENS = 31; int SEARCH_SIMILAR_PRODUCTS = 32; int READ_LATER = 33; - int NUM_ENTRIES = 34; + int SHOP_WITH_GOOGLE_LENS_CHIP = 34; + int NUM_ENTRIES = 35; } // Note: these values must match the ContextMenuSaveLinkType enum in enums.xml. @@ -845,6 +847,30 @@ }); } + @Override + public @Nullable ChipDelegate getChipDelegate() { + if (LensUtils.enableImageChip(isIncognito())) { + return new LensChipDelegate(mParams.getPageUrl(), mParams.getTitleText(), + mParams.getSrcUrl(), getPageTitle(), isIncognito(), + mItemDelegate.getWebContents(), mNativeDelegate, getOnChipClickedCallback(), + getOnChipShownCallback()); + } + + return null; + } + + private Runnable getOnChipClickedCallback() { + return () -> { + recordContextMenuSelection(ContextMenuUma.Action.SHOP_WITH_GOOGLE_LENS_CHIP); + }; + } + + private Runnable getOnChipShownCallback() { + return () -> { + maybeRecordBooleanUkm("ContextMenuAndroid.Shown", "ShopWithGoogleLensChip"); + }; + } + /** * Checks whether a url is empty or blank. * @param url The url need to be checked.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java index 213afa588..0fd33aa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java
@@ -207,10 +207,8 @@ final RevampedContextMenuCoordinator menuCoordinator = new RevampedContextMenuCoordinator(topContentOffsetPx, mCurrentNativeDelegate); mCurrentContextMenu = menuCoordinator; - if (LensUtils.enableImageChip(mIsIncognito)) { - mChipDelegate = new LensChipDelegate(mCurrentContextMenuParams.getPageUrl(), - mCurrentContextMenuParams.getTitleText(), mCurrentContextMenuParams.getSrcUrl(), - mPageTitle, mIsIncognito, mWebContents, mCurrentNativeDelegate); + mChipDelegate = mCurrentPopulator.getChipDelegate(); + if (mChipDelegate != null) { menuCoordinator.displayMenuWithChip(mWindow, mWebContents, mCurrentContextMenuParams, items, mCallback, mOnMenuShown, mOnMenuClosed, mChipDelegate); } else {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/LensChipDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/LensChipDelegate.java index f54de7f4..4d99502 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/LensChipDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/LensChipDelegate.java
@@ -18,10 +18,12 @@ private LensQueryParams mLensQueryParams; private LensController mLensController; private ContextMenuNativeDelegate mNativeDelegate; + private Runnable mOnChipClickedCallback; + private Runnable mOnChipShownCallback; public LensChipDelegate(String pageUrl, String titleOrAltText, String srcUrl, String pageTitle, - boolean isIncognito, WebContents webContents, - ContextMenuNativeDelegate nativeDelegate) { + boolean isIncognito, WebContents webContents, ContextMenuNativeDelegate nativeDelegate, + Runnable onChipClickedCallback, Runnable onChipShownCallback) { mLensController = LensController.getInstance(); if (!mLensController.isQueryEnabled()) { return; @@ -35,6 +37,8 @@ .withWebContents(webContents) .build(); mNativeDelegate = nativeDelegate; + mOnChipClickedCallback = onChipClickedCallback; + mOnChipShownCallback = onChipShownCallback; } @Override @@ -46,8 +50,19 @@ Callback<Uri> callback = (uri) -> { mLensQueryParams.setImageUri(uri); - mLensController.getChipRenderParams( - mLensQueryParams, (chipParams) -> { chipParamsCallback.onResult(chipParams); }); + mLensController.getChipRenderParams(mLensQueryParams, (chipParams) -> { + if (isValidChipRenderParams(chipParams)) { + Runnable mergedOnClickCallback = () -> { + // The onClickCallback defined in LensController. + chipParams.onClickCallback.run(); + // The onClickCallback defined when initialize the LensChipDelegate. + mOnChipClickedCallback.run(); + }; + chipParams.onClickCallback = mergedOnClickCallback; + chipParams.onShowCallback = mOnChipShownCallback; + } + chipParamsCallback.onResult(chipParams); + }); }; // Must occur on UI thread.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuChipController.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuChipController.java index f0f8186..031e2ad6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuChipController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuChipController.java
@@ -169,6 +169,9 @@ mPopupWindow.show(); recordChipEvent(ChipEvent.SHOWN); + if (mChipRenderParams.onShowCallback != null) { + mChipRenderParams.onShowCallback.run(); + } } // This method should only be used in test files. It is not marked
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java index 446a839f..363371a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java
@@ -105,8 +105,8 @@ private static final String INTENT_URL_PREFIX = "intent:"; - // We blacklist this URL because malformed URLs may bring up this page. - private static final String BLACKLISTED_URL = ContentUrlConstants.ABOUT_BLANK_DISPLAY_URL; + // We denylist this URL because malformed URLs may bring up this page. + private static final String DENYLISTED_URL = ContentUrlConstants.ABOUT_BLANK_DISPLAY_URL; // How long to wait for a tap near a previous tap before hiding the UI or showing a re-Tap. // This setting is not critical: in practice it determines how long to wait after an invalid @@ -830,7 +830,7 @@ mLoadedSearchUrlTimeMs = System.currentTimeMillis(); mLastSearchRequestLoaded = mSearchRequest; String searchUrl = mSearchRequest.getSearchUrl(); - ContextualSearchManagerJni.get().whitelistContextualSearchJsApiUrl( + ContextualSearchManagerJni.get().allowlistContextualSearchJsApiUrl( mNativeContextualSearchManagerPtr, this, searchUrl); mSearchPanel.loadUrlInPanel(searchUrl); mDidStartLoadingResolvedSearchRequest = true; @@ -1039,7 +1039,7 @@ } @Override - public void onContentLoadStarted(String url) { + public void onContentLoadStarted() { mDidPromoteSearchNavigation = false; } @@ -1191,7 +1191,7 @@ * @param url The URL we are navigating to. */ public void onExternalNavigation(String url) { - if (!mDidPromoteSearchNavigation && mSearchPanel != null && !BLACKLISTED_URL.equals(url) + if (!mDidPromoteSearchNavigation && mSearchPanel != null && !DENYLISTED_URL.equals(url) && !url.startsWith(INTENT_URL_PREFIX) && shouldPromoteSearchNavigation()) { // Do not promote to a regular tab if we're loading our Resolved Search // URL, otherwise we'll promote it when prefetching the Serp. @@ -1936,7 +1936,7 @@ void gatherSurroundingText(long nativeContextualSearchManager, ContextualSearchManager caller, ContextualSearchContext contextualSearchContext, WebContents baseWebContents); - void whitelistContextualSearchJsApiUrl( + void allowlistContextualSearchJsApiUrl( long nativeContextualSearchManager, ContextualSearchManager caller, String url); void enableContextualSearchJsApiForWebContents(long nativeContextualSearchManager, ContextualSearchManager caller, WebContents overlayWebContents);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarCoordinator.java index 65ab38f2..034a0bcd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarCoordinator.java
@@ -21,6 +21,7 @@ import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; import org.chromium.chrome.browser.lifecycle.Destroyable; import org.chromium.chrome.browser.lifecycle.NativeInitObserver; +import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.ntp.FakeboxDelegate; import org.chromium.chrome.browser.omnibox.status.StatusCoordinator; import org.chromium.chrome.browser.omnibox.status.StatusView; @@ -118,10 +119,12 @@ mUrlBar = mLocationBarLayout.findViewById(R.id.url_bar); OneshotSupplierImpl<AssistantVoiceSearchService> assistantVoiceSearchSupplier = new OneshotSupplierImpl(); - + // TODO(crbug.com/1151513): Inject LocaleManager instance to LocationBarCoordinator instead + // of using the singleton. mLocationBarMediator = new LocationBarMediator(mLocationBarLayout, locationBarDataProvider, assistantVoiceSearchSupplier, profileObservableSupplier, - PrivacyPreferencesManagerImpl.getInstance()); + PrivacyPreferencesManagerImpl.getInstance(), overrideUrlLoadingDelegate, + LocaleManager.getInstance()); mUrlCoordinator = new UrlBarCoordinator((UrlBar) mUrlBar, windowDelegate, actionModeCallback, mCallbackController.makeCancelable(mLocationBarMediator::onUrlFocusChange), @@ -149,7 +152,7 @@ mLocationBarLayout.addUrlFocusChangeListener(mAutocompleteCoordinator); mLocationBarLayout.initialize(mAutocompleteCoordinator, mUrlCoordinator, mStatusCoordinator, - locationBarDataProvider, windowDelegate, windowAndroid, overrideUrlLoadingDelegate, + locationBarDataProvider, windowDelegate, windowAndroid, mLocationBarMediator.getVoiceRecognitionHandler(), assistantVoiceSearchSupplier); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java index f33a682..1c4b8e0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java
@@ -36,8 +36,6 @@ import org.chromium.base.supplier.OneshotSupplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.WindowDelegate; -import org.chromium.chrome.browser.locale.LocaleManager; -import org.chromium.chrome.browser.ntp.NewTabPageUma; import org.chromium.chrome.browser.omnibox.UrlBar.ScrollType; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; @@ -55,15 +53,11 @@ import org.chromium.components.search_engines.TemplateUrl; import org.chromium.components.search_engines.TemplateUrlService; import org.chromium.components.search_engines.TemplateUrlService.TemplateUrlServiceObserver; -import org.chromium.content_public.browser.LoadUrlParams; -import org.chromium.content_public.common.ResourceRequestBody; import org.chromium.ui.KeyboardVisibilityDelegate; -import org.chromium.ui.base.PageTransition; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.util.ColorUtils; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; /** @@ -114,7 +108,6 @@ private Runnable mKeyboardResizeModeTask; private Runnable mKeyboardHideTask; private TemplateUrlServiceObserver mTemplateUrlObserver; - private OverrideUrlLoadingDelegate mOverrideUrlLoadingDelegate; public LocationBarLayout(Context context, AttributeSet attrs) { this(context, attrs, R.layout.location_bar); @@ -209,7 +202,6 @@ @NonNull UrlBarCoordinator urlCoordinator, @NonNull StatusCoordinator statusCoordinator, @NonNull LocationBarDataProvider locationBarDataProvider, @NonNull WindowDelegate windowDelegate, @NonNull WindowAndroid windowAndroid, - @NonNull OverrideUrlLoadingDelegate overrideUrlLoadingDelegate, @NonNull VoiceRecognitionHandler voiceRecognitionHandler, @NonNull OneshotSupplier<AssistantVoiceSearchService> assistantVoiceSearchSupplier) { mAutocompleteCoordinator = autocompleteCoordinator; @@ -218,7 +210,6 @@ mWindowDelegate = windowDelegate; mWindowAndroid = windowAndroid; mLocationBarDataProvider = locationBarDataProvider; - mOverrideUrlLoadingDelegate = overrideUrlLoadingDelegate; mVoiceRecognitionHandler = voiceRecognitionHandler; mAssistantVoiceSearchServiceSupplier = assistantVoiceSearchSupplier; @@ -330,18 +321,6 @@ // When we restore tabs, we focus the selected tab so the URL of the page shows. } - public void performSearchQuery(String query, List<String> searchParams) { - if (TextUtils.isEmpty(query)) return; - - String queryUrl = TemplateUrlServiceFactory.get().getUrlForSearchQuery(query, searchParams); - - if (!TextUtils.isEmpty(queryUrl)) { - loadUrl(queryUrl, PageTransition.GENERATED, 0); - } else { - setSearchQuery(query); - } - } - /** * Sets the query string in the omnibox (ensuring the URL bar has focus and triggering * autocomplete for the specified query) as if the user typed it. @@ -394,7 +373,6 @@ setUrlBarFocus(false, null, OmniboxFocusReason.UNFOCUS); // Revert the URL to match the current page. setUrl(mLocationBarDataProvider.getCurrentUrl()); - focusCurrentTab(); } public void gestureDetected(boolean isLongPress) { @@ -601,78 +579,6 @@ updateButtonVisibility(); } - /* package */ void loadUrlFromVoice(String url) { - loadUrl(url, PageTransition.TYPED, 0); - } - - /** - * Load the url given with the given transition. Exposed for child classes to overwrite as - * necessary. - */ - /* package */ void loadUrl(String url, @PageTransition int transition, long inputStart) { - loadUrlWithPostData(url, transition, inputStart, null, null); - } - - protected void loadUrlWithPostData(String url, @PageTransition int transition, long inputStart, - @Nullable String postDataType, @Nullable byte[] postData) { - Tab currentTab = getCurrentTab(); - - // The code of the rest of this class ensures that this can't be called until the native - // side is initialized - assert mNativeInitialized : "Loading URL before native side initialized"; - - // TODO(crbug.com/1085812): Should be taking a full loaded LoadUrlParams. - if (mOverrideUrlLoadingDelegate.willHandleLoadUrlWithPostData(url, transition, postDataType, - postData, mLocationBarDataProvider.isIncognito())) { - return; - } - - if (currentTab != null - && (currentTab.isNativePage() - || UrlUtilities.isNTPUrl(currentTab.getUrlString()))) { - NewTabPageUma.recordOmniboxNavigation(url, transition); - // Passing in an empty string should not do anything unless the user is at the NTP. - // Since the NTP has no url, pressing enter while clicking on the URL bar should refresh - // the page as it does when you click and press enter on any other site. - if (url.isEmpty()) url = currentTab.getUrlString(); - } - - // Loads the |url| in a new tab or the current ContentView and gives focus to the - // ContentView. - if (currentTab != null && !url.isEmpty()) { - LoadUrlParams loadUrlParams = new LoadUrlParams(url); - loadUrlParams.setVerbatimHeaders(GeolocationHeader.getGeoHeader(url, currentTab)); - loadUrlParams.setTransitionType(transition | PageTransition.FROM_ADDRESS_BAR); - if (inputStart != 0) { - loadUrlParams.setInputStartTimestamp(inputStart); - } - - if (!TextUtils.isEmpty(postDataType)) { - StringBuilder headers = new StringBuilder(); - String prevHeader = loadUrlParams.getVerbatimHeaders(); - if (prevHeader != null && !prevHeader.isEmpty()) { - headers.append(prevHeader); - headers.append("\r\n"); - } - loadUrlParams.setExtraHeaders(new HashMap<String, String>() { - { put("Content-Type", postDataType); } - }); - headers.append(loadUrlParams.getExtraHttpRequestHeadersString()); - loadUrlParams.setVerbatimHeaders(headers.toString()); - } - - if (postData != null && postData.length != 0) { - loadUrlParams.setPostData(ResourceRequestBody.createFromBytes(postData)); - } - - currentTab.loadUrl(loadUrlParams); - RecordUserAction.record("MobileOmniboxUse"); - } - LocaleManager.getInstance().recordLocaleBasedSearchMetrics(false, url, transition); - - focusCurrentTab(); - } - /** * @param focusable Whether the url bar should be focusable. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarMediator.java index f48b921..0734e56 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarMediator.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.omnibox; import android.content.Context; +import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; @@ -15,15 +16,19 @@ import org.chromium.base.CallbackController; import org.chromium.base.CommandLine; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.OneshotSupplierImpl; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.gsa.GSAState; +import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.native_page.NativePageFactory; import org.chromium.chrome.browser.ntp.FakeboxDelegate; +import org.chromium.chrome.browser.ntp.NewTabPageUma; import org.chromium.chrome.browser.omnibox.UrlBar.UrlBarDelegate; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; +import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; import org.chromium.chrome.browser.omnibox.status.StatusCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteDelegate; @@ -33,9 +38,15 @@ import org.chromium.chrome.browser.privacy.settings.PrivacyPreferencesManagerImpl; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.search_engines.TemplateUrlServiceFactory; +import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.util.KeyNavigationUtil; +import org.chromium.components.embedder_support.util.UrlUtilities; +import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.common.ResourceRequestBody; +import org.chromium.ui.base.PageTransition; import org.chromium.ui.base.WindowAndroid; +import java.util.HashMap; import java.util.List; /** @@ -58,6 +69,8 @@ private ObservableSupplier<Profile> mProfileSupplier; private PrivacyPreferencesManagerImpl mPrivacyPreferencesManager; private CallbackController mCallbackController = new CallbackController(); + private final OverrideUrlLoadingDelegate mOverrideUrlLoadingDelegate; + private final LocaleManager mLocaleManager; private boolean mNativeInitialized; @@ -65,7 +78,9 @@ @NonNull LocationBarDataProvider locationBarDataProvider, @NonNull OneshotSupplierImpl<AssistantVoiceSearchService> assistantVoiceSearchSupplier, @NonNull ObservableSupplier<Profile> profileSupplier, - @NonNull PrivacyPreferencesManagerImpl privacyPreferencesManager) { + @NonNull PrivacyPreferencesManagerImpl privacyPreferencesManager, + @NonNull OverrideUrlLoadingDelegate overrideUrlLoadingDelegate, + @NonNull LocaleManager localeManager) { mLocationBarLayout = locationBarLayout; mLocationBarDataProvider = locationBarDataProvider; mLocationBarDataProvider.addObserver(this); @@ -74,6 +89,8 @@ mProfileSupplier = profileSupplier; mProfileSupplier.addObserver(mCallbackController.makeCancelable(this::setProfile)); mPrivacyPreferencesManager = privacyPreferencesManager; + mOverrideUrlLoadingDelegate = overrideUrlLoadingDelegate; + mLocaleManager = localeManager; } /** @@ -143,6 +160,14 @@ SearchEngineLogoUtils.shouldShowSearchEngineLogo(profile.isOffTheRecord())); } + private void focusCurrentTab() { + assert mLocationBarDataProvider != null; + if (mLocationBarDataProvider.hasTab()) { + View view = mLocationBarDataProvider.getTab().getView(); + if (view != null) view.requestFocus(); + } + } + /*package */ void updateVisualsForState() { mLocationBarLayout.onPrimaryColorChanged(); } @@ -216,7 +241,15 @@ @Override public void performSearchQuery(String query, List<String> searchParams) { - mLocationBarLayout.performSearchQuery(query, searchParams); + if (TextUtils.isEmpty(query)) return; + + String queryUrl = TemplateUrlServiceFactory.get().getUrlForSearchQuery(query, searchParams); + + if (!TextUtils.isEmpty(queryUrl)) { + loadUrl(queryUrl, PageTransition.GENERATED, 0); + } else { + mLocationBarLayout.setSearchQuery(query); + } } @Override @@ -281,14 +314,70 @@ } @Override - public void loadUrl(String url, int transition, long inputStart) { - mLocationBarLayout.loadUrl(url, transition, inputStart); + public void loadUrl(String url, @PageTransition int transition, long inputStart) { + loadUrlWithPostData(url, transition, inputStart, null, null); } @Override public void loadUrlWithPostData( String url, int transition, long inputStart, String postDataType, byte[] postData) { - mLocationBarLayout.loadUrlWithPostData(url, transition, inputStart, postDataType, postData); + assert mLocationBarDataProvider != null; + Tab currentTab = mLocationBarDataProvider.getTab(); + + // The code of the rest of this class ensures that this can't be called until the native + // side is initialized + assert mNativeInitialized : "Loading URL before native side initialized"; + + // TODO(crbug.com/1085812): Should be taking a full loaded LoadUrlParams. + if (mOverrideUrlLoadingDelegate.willHandleLoadUrlWithPostData(url, transition, postDataType, + postData, mLocationBarDataProvider.isIncognito())) { + return; + } + + if (currentTab != null + && (currentTab.isNativePage() + || UrlUtilities.isNTPUrl(currentTab.getUrlString()))) { + NewTabPageUma.recordOmniboxNavigation(url, transition); + // Passing in an empty string should not do anything unless the user is at the NTP. + // Since the NTP has no url, pressing enter while clicking on the URL bar should refresh + // the page as it does when you click and press enter on any other site. + if (url.isEmpty()) url = currentTab.getUrlString(); + } + + // Loads the |url| in a new tab or the current ContentView and gives focus to the + // ContentView. + if (currentTab != null && !url.isEmpty()) { + LoadUrlParams loadUrlParams = new LoadUrlParams(url); + loadUrlParams.setVerbatimHeaders(GeolocationHeader.getGeoHeader(url, currentTab)); + loadUrlParams.setTransitionType(transition | PageTransition.FROM_ADDRESS_BAR); + if (inputStart != 0) { + loadUrlParams.setInputStartTimestamp(inputStart); + } + + if (!TextUtils.isEmpty(postDataType)) { + StringBuilder headers = new StringBuilder(); + String prevHeader = loadUrlParams.getVerbatimHeaders(); + if (prevHeader != null && !prevHeader.isEmpty()) { + headers.append(prevHeader); + headers.append("\r\n"); + } + loadUrlParams.setExtraHeaders(new HashMap<String, String>() { + { put("Content-Type", postDataType); } + }); + headers.append(loadUrlParams.getExtraHttpRequestHeadersString()); + loadUrlParams.setVerbatimHeaders(headers.toString()); + } + + if (postData != null && postData.length != 0) { + loadUrlParams.setPostData(ResourceRequestBody.createFromBytes(postData)); + } + + currentTab.loadUrl(loadUrlParams); + RecordUserAction.record("MobileOmniboxUse"); + } + mLocaleManager.recordLocaleBasedSearchMetrics(false, url, transition); + + focusCurrentTab(); } @Override @@ -327,7 +416,7 @@ @Override public void loadUrlFromVoice(String url) { - mLocationBarLayout.loadUrlFromVoice(url); + loadUrl(url, PageTransition.TYPED, 0); } @Override @@ -371,6 +460,7 @@ @Override public void backKeyPressed() { mLocationBarLayout.backKeyPressed(); + focusCurrentTab(); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java index ff74044..044d964 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java
@@ -119,12 +119,11 @@ @NonNull UrlBarCoordinator urlCoordinator, @NonNull StatusCoordinator statusCoordinator, @NonNull LocationBarDataProvider locationBarDataProvider, @NonNull WindowDelegate windowDelegate, @NonNull WindowAndroid windowAndroid, - @NonNull OverrideUrlLoadingDelegate overrideUrlLoadingDelegate, @NonNull VoiceRecognitionHandler voiceRecognitionHandler, @NonNull OneshotSupplier<AssistantVoiceSearchService> assistantVoiceSearchSupplier) { super.initialize(autocompleteCoordinator, urlCoordinator, statusCoordinator, - locationBarDataProvider, windowDelegate, windowAndroid, overrideUrlLoadingDelegate, - voiceRecognitionHandler, assistantVoiceSearchSupplier); + locationBarDataProvider, windowDelegate, windowAndroid, voiceRecognitionHandler, + assistantVoiceSearchSupplier); mStatusCoordinator.setShowIconsWhenUrlFocused(true); if (SearchEngineLogoUtils.shouldShowSearchEngineLogo( mLocationBarDataProvider.isIncognito())) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java index 1c9bd58c..05b5e8e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java
@@ -25,6 +25,7 @@ import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge; import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge.AddressField; import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge.AddressUiComponent; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.payments.mojom.AddressErrors; import java.lang.annotation.Retention; @@ -63,6 +64,8 @@ @Nullable private EditorFieldModel mCountryField; @Nullable + private EditorFieldModel mHonorificField; + @Nullable private EditorFieldModel mPhoneField; @Nullable private EditorFieldModel mEmailField; @@ -112,6 +115,11 @@ mAddressErrors = errors; } + private boolean isUIForHonorificPrefixesEnabled() { + return ChromeFeatureList.isEnabled( + ChromeFeatureList.AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS); + } + private String getAddressError(int field) { if (mAddressErrors == null) return null; @@ -152,6 +160,7 @@ * Builds and shows an editor model with the following fields. * * [ country dropdown ] <----- country dropdown is always present. + * [ honorific field ] <----- above name, present if purpose is Purpose.AUTOFILL_SETTINGS. * [ an address field ] \ * [ an address field ] \ * ... <-- field order, presence, required, and labels depend on country. @@ -226,6 +235,17 @@ mPhoneValidator.setCountryCode(mCountryField.getValue().toString()); mPhoneFormatter.setCountryCode(mCountryField.getValue().toString()); + // Honorific prefix is present only for autofill settings. + if (mPurpose == Purpose.AUTOFILL_SETTINGS && isUIForHonorificPrefixesEnabled()) { + if (mHonorificField == null) { + mHonorificField = EditorFieldModel.createTextInput(); + mHonorificField.setLabel( + mContext.getString(R.string.autofill_profile_editor_honorific_prefix)); + } + // Retrieve and set the honorific prefix value. + mHonorificField.setValue(mProfile.getHonorificPrefix()); + } + // There's a finite number of fields for address editing. Changing the country will re-order // and relabel the fields. The meaning of each field remains the same. if (mAddressFields.isEmpty()) { @@ -333,6 +353,9 @@ profile.setCountryCode(mCountryField.getValue().toString()); profile.setPhoneNumber(mPhoneField.getValue().toString()); if (mEmailField != null) profile.setEmailAddress(mEmailField.getValue().toString()); + if (mHonorificField != null) { + profile.setHonorificPrefix(mHonorificField.getValue().toString()); + } // Autofill profile bridge normalizes the language code for the autofill profile. profile.setLanguageCode(mAutofillProfileBridge.getCurrentBestLanguageCode()); @@ -507,6 +530,11 @@ for (int i = 0; i < mAddressUiComponents.size(); i++) { AddressUiComponent component = mAddressUiComponents.get(i); + // Honorific prefix should go before name. + if (component.id == AddressField.RECIPIENT && mHonorificField != null) { + mEditor.addField(mHonorificField); + } + EditorFieldModel field = mAddressFields.get(component.id); // Labels depend on country, e.g., state is called province in some countries. These are
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java index 8f9cf5e6..16b89e9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.payments; +import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.graphics.drawable.Drawable; @@ -17,7 +18,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.task.PostTask; import org.chromium.chrome.R; -import org.chromium.chrome.browser.app.ChromeActivity; import org.chromium.components.payments.ErrorStrings; import org.chromium.components.payments.PayerData; import org.chromium.components.payments.PaymentApp; @@ -122,17 +122,22 @@ mWebContents = webContents; } + @Nullable + private Context getActivityContext() { + WindowAndroid window = mWebContents.getTopLevelNativeWindow(); + return window == null ? null : window.getActivity().get(); + } + // Launcher implementation. @Override public void showLeavingIncognitoWarning( Callback<String> denyCallback, Runnable approveCallback) { - ChromeActivity activity = ChromeActivity.fromWebContents(mWebContents); - if (activity == null) { + Context context = getActivityContext(); + if (context == null) { denyCallback.onResult(ErrorStrings.ACTIVITY_NOT_FOUND); return; } - - new UiUtils.CompatibleAlertDialogBuilder(activity, R.style.Theme_Chromium_AlertDialog) + new UiUtils.CompatibleAlertDialogBuilder(context, R.style.Theme_Chromium_AlertDialog) .setTitle(R.string.external_app_leave_incognito_warning_title) .setMessage(R.string.external_payment_app_leave_incognito_warning) .setPositiveButton(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/PaymentHandlerMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/PaymentHandlerMediator.java index 26b2d4f..efce2a9f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/PaymentHandlerMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/PaymentHandlerMediator.java
@@ -30,6 +30,7 @@ import org.chromium.payments.mojom.PaymentEventResponseType; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.util.TokenHolder; +import org.chromium.url.GURL; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -274,7 +275,7 @@ // Implement WebContentsObserver: @Override - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingUrl) { if (!isMainFrame) return; mHandler.post(() -> { mCloseReason = CloseReason.FAIL_LOAD;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/toolbar/PaymentHandlerToolbarMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/toolbar/PaymentHandlerToolbarMediator.java index 2355092..5e2f9dd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/toolbar/PaymentHandlerToolbarMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/handler/toolbar/PaymentHandlerToolbarMediator.java
@@ -13,6 +13,7 @@ import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.ui.modelutil.PropertyModel; +import org.chromium.url.GURL; /** * PaymentHandlerToolbar mediator, which is responsible for receiving events from the view and @@ -70,7 +71,7 @@ // WebContentsObserver: @Override - public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) { + public void didFinishLoad(long frameId, GURL url, boolean isKnownValid, boolean isMainFrame) { // Hides the Progress Bar after a delay to make sure it is rendered for at least // a few frames, otherwise its completion won't be visually noticeable. mHideProgressBarHandler = new Handler(); @@ -81,7 +82,7 @@ } @Override - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingUrl) { mModel.set(PaymentHandlerToolbarProperties.PROGRESS_VISIBLE, false); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java index b309f1d7..1f38b8a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java
@@ -107,6 +107,7 @@ /** Input submitted before before the native library was loaded. */ private String mQueuedUrl; + private @PageTransition int mQueuedTransition; private String mQueuedPostDataType; private byte[] mQueuedPostData; @@ -176,7 +177,10 @@ /*shareDelegateSupplier=*/null, /*incognitoStateProvider=*/null, getLifecycleDispatcher(), /*overrideUrlLoadingDelegate=*/ (String url, @PageTransition int transition, String postDataType, byte[] postData, - boolean incognito) -> false); + boolean incognito) -> { + loadUrl(url, transition, postDataType, postData); + return true; + }); // Kick off everything needed for the user to type into the box. beginQuery(); @@ -292,7 +296,9 @@ assert !mIsActivityUsable : "finishDeferredInitialization() incorrectly called multiple times"; mIsActivityUsable = true; - if (mQueuedUrl != null) loadUrl(mQueuedUrl, mQueuedPostDataType, mQueuedPostData); + if (mQueuedUrl != null) { + loadUrl(mQueuedUrl, mQueuedTransition, mQueuedPostDataType, mQueuedPostData); + } // TODO(tedchoc): Warmup triggers the CustomTab layout to be inflated, but this widget // will navigate to Tabbed mode. Investigate whether this can inflate @@ -345,11 +351,12 @@ return true; } - @Override - public void loadUrl(String url, @Nullable String postDataType, @Nullable byte[] postData) { + /* package */ void loadUrl(String url, @PageTransition int transition, + @Nullable String postDataType, @Nullable byte[] postData) { // Wait until native has loaded. if (!mIsActivityUsable) { mQueuedUrl = url; + mQueuedTransition = transition; mQueuedPostDataType = postDataType; mQueuedPostData = postData; return; @@ -363,6 +370,7 @@ .makeCustomAnimation(this, android.R.anim.fade_in, android.R.anim.fade_out) .toBundle()); RecordUserAction.record("SearchWidget.SearchMade"); + LocaleManager.getInstance().recordLocaleBasedSearchMetrics(true, url, transition); finish(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivityLocationBarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivityLocationBarLayout.java index 70d7d1f..e62d9c5c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivityLocationBarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivityLocationBarLayout.java
@@ -18,7 +18,6 @@ import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.omnibox.LocationBarDataProvider; import org.chromium.chrome.browser.omnibox.LocationBarLayout; -import org.chromium.chrome.browser.omnibox.OverrideUrlLoadingDelegate; import org.chromium.chrome.browser.omnibox.UrlBar; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; @@ -34,9 +33,6 @@ public class SearchActivityLocationBarLayout extends LocationBarLayout { /** Delegates calls out to the containing Activity. */ public static interface Delegate { - /** Load a URL in the associated tab. */ - void loadUrl(String url, @Nullable String postDataType, @Nullable byte[] postData); - /** The user hit the back button. */ void backKeyPressed(); } @@ -64,13 +60,12 @@ @NonNull UrlBarCoordinator urlCoordinator, @NonNull StatusCoordinator statusCoordinator, @NonNull LocationBarDataProvider locationBarDataProvider, @NonNull WindowDelegate windowDelegate, @NonNull WindowAndroid windowAndroid, - @NonNull OverrideUrlLoadingDelegate overrideUrlLoadingDelegate, @NonNull VoiceRecognitionHandler voiceRecognitionHandler, @NonNull OneshotSupplier<AssistantVoiceSearchService> assistantVoiceSearchServiceSupplier) { super.initialize(autocompleteCoordinator, urlCoordinator, statusCoordinator, - locationBarDataProvider, windowDelegate, windowAndroid, overrideUrlLoadingDelegate, - voiceRecognitionHandler, assistantVoiceSearchServiceSupplier); + locationBarDataProvider, windowDelegate, windowAndroid, voiceRecognitionHandler, + assistantVoiceSearchServiceSupplier); setUrlBarFocusable(true); mPendingSearchPromoDecision = LocaleManager.getInstance().needToCheckForSearchEnginePromo(); getAutocompleteCoordinator().setShouldPreventOmniboxAutocomplete( @@ -78,13 +73,6 @@ } @Override - protected void loadUrlWithPostData(String url, int transition, long inputStart, - @Nullable String postDataType, @Nullable byte[] postData) { - mDelegate.loadUrl(url, postDataType, postData); - LocaleManager.getInstance().recordLocaleBasedSearchMetrics(true, url, transition); - } - - @Override public void backKeyPressed() { mDelegate.backKeyPressed(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/LensUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/share/LensUtils.java index 15cca56..b70a25d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/LensUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/LensUtils.java
@@ -508,10 +508,16 @@ */ public static boolean shouldLogUkm(boolean isIncognito) { // Lens shopping feature takes the priority over the "Search image with Google Lens". + if (enableImageChip(isIncognito)) { + return ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( + ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP, LOG_UKM_PARAM_NAME, true); + } + if (isGoogleLensShoppingFeatureEnabled(isIncognito)) { return ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( ChromeFeatureList.CONTEXT_MENU_SHOP_WITH_GOOGLE_LENS, LOG_UKM_PARAM_NAME, true); } + if (isGoogleLensFeatureEnabled(isIncognito)) { return ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS, LOG_UKM_PARAM_NAME,
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/GoogleActivityController.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/GoogleActivityController.java deleted file mode 100644 index a8da3fb4..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/GoogleActivityController.java +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.signin; - -/** - * Controls how Google uses Chrome data to personalize Search and other Google services. - * TODO(crbug.com/1153038): Remove this class after migrating the callers in //clank. - */ -@Deprecated -public class GoogleActivityController - extends org.chromium.chrome.browser.signin.ui.GoogleActivityController {}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS index 657e4f5..9844c97e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS
@@ -17,6 +17,7 @@ "+chrome/android/java/src/org/chromium/chrome/browser/ssl/SecurityStateModel.java", "+chrome/android/java/src/org/chromium/chrome/browser/tab", "+chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/Tab.java", + "+chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java", "+chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuNativeDelegate.java", "+chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java", "+chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulatorFactory.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuPopulator.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuPopulator.java index 6d6fed284..0020545 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuPopulator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuPopulator.java
@@ -9,6 +9,7 @@ import androidx.annotation.Nullable; import org.chromium.base.ObserverList.RewindableIterator; +import org.chromium.chrome.browser.contextmenu.ChipDelegate; import org.chromium.chrome.browser.contextmenu.ContextMenuPopulator; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; @@ -62,4 +63,9 @@ public String getPageTitle() { return mPopulator.getPageTitle(); } + + @Override + public @Nullable ChipDelegate getChipDelegate() { + return mPopulator.getChipDelegate(); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java index a096e5e..30a792f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java
@@ -224,18 +224,22 @@ } @Override - public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) { + public void didFinishLoad( + long frameId, GURL url, boolean isKnownValid, boolean isMainFrame) { + assert isKnownValid; if (mTab.getNativePage() != null) { mTab.pushNativePageStateToNavigationEntry(); } - if (isMainFrame) mTab.didFinishPageLoad(validatedUrl); + if (isMainFrame) mTab.didFinishPageLoad(url.getSpec()); PolicyAuditor auditor = AppHooks.get().getPolicyAuditor(); auditor.notifyAuditEvent(ContextUtils.getApplicationContext(), - AuditEvent.OPEN_URL_SUCCESS, validatedUrl, ""); + AuditEvent.OPEN_URL_SUCCESS, url.getSpec(), ""); } @Override - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingGurl) { + String failingUrl = failingGurl.getSpec(); + RewindableIterator<TabObserver> observers = mTab.getTabObservers(); while (observers.hasNext()) { observers.next().onDidFailLoad(mTab, isMainFrame, errorCode, failingUrl);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/settings/AutofillProfilesFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/settings/AutofillProfilesFragmentTest.java index 7416467b..cdda805 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/settings/AutofillProfilesFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/settings/AutofillProfilesFragmentTest.java
@@ -15,17 +15,20 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; -import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.settings.SettingsActivity; import org.chromium.chrome.browser.settings.SettingsActivityTestRule; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.util.browser.Features; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.KeyboardVisibilityDelegate; @@ -36,13 +39,15 @@ * Unit test suite for AutofillProfilesFragment. */ -@RunWith(BaseJUnit4ClassRunner.class) +@RunWith(ChromeJUnit4ClassRunner.class) public class AutofillProfilesFragmentTest { @Rule public final AutofillTestRule rule = new AutofillTestRule(); @Rule public final SettingsActivityTestRule<AutofillProfilesFragment> mSettingsActivityTestRule = new SettingsActivityTestRule<>(AutofillProfilesFragment.class); + @Rule + public final TestRule mFeaturesProcessorRule = new Features.JUnitProcessor(); @Before public void setUp() throws TimeoutException { @@ -66,6 +71,8 @@ @Test @MediumTest @Feature({"Preferences"}) + @Features. + EnableFeatures({ChromeFeatureList.AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS}) public void testAddProfile() throws Exception { SettingsActivity activity = mSettingsActivityTestRule.startSettingsActivity(); AutofillProfilesFragment autofillProfileFragment = @@ -82,8 +89,8 @@ // Add a profile. updatePreferencesAndWait(autofillProfileFragment, addProfile, - new String[] {"Alice Doe", "Google", "111 Added St", "Los Angeles", "CA", "90291", - "650-253-0000", "add@profile.com"}, + new String[] {"Ms.", "Alice Doe", "Google", "111 Added St", "Los Angeles", "CA", + "90291", "650-253-0000", "add@profile.com"}, R.id.editor_dialog_done_button, false); Assert.assertEquals(7 /* One toggle + one add button + five profiles. */, @@ -98,6 +105,8 @@ @Test @MediumTest @Feature({"Preferences"}) + @Features. + EnableFeatures({ChromeFeatureList.AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS}) public void testAddIncompletedProfile() throws Exception { SettingsActivity activity = mSettingsActivityTestRule.startSettingsActivity(); AutofillProfilesFragment autofillProfileFragment = @@ -113,7 +122,7 @@ Assert.assertNotNull(addProfile); // Add an incomplete profile. - updatePreferencesAndWait(autofillProfileFragment, addProfile, new String[] {"Mike Doe"}, + updatePreferencesAndWait(autofillProfileFragment, addProfile, new String[] {"", "Mike Doe"}, R.id.editor_dialog_done_button, false); // Incomplete profile should still be added. @@ -128,6 +137,8 @@ @Test @MediumTest @Feature({"Preferences"}) + @Features. + EnableFeatures({ChromeFeatureList.AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS}) public void testAddProfileWithInvalidPhone() throws Exception { SettingsActivity activity = mSettingsActivityTestRule.startSettingsActivity(); AutofillProfilesFragment autofillProfileFragment = @@ -144,7 +155,8 @@ // Try to add a profile with invalid phone. updatePreferencesAndWait(autofillProfileFragment, addProfile, - new String[] {"", "", "", "", "", "", "123"}, R.id.editor_dialog_done_button, true); + new String[] {"", "", "", "", "", "", "", "123"}, R.id.editor_dialog_done_button, + true); activity.finish(); } @@ -183,6 +195,8 @@ @Test @MediumTest @Feature({"Preferences"}) + @Features. + EnableFeatures({ChromeFeatureList.AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS}) public void testEditProfile() throws Exception { SettingsActivity activity = mSettingsActivityTestRule.startSettingsActivity(); AutofillProfilesFragment autofillProfileFragment = @@ -199,8 +213,8 @@ // Edit a profile. updatePreferencesAndWait(autofillProfileFragment, johnProfile, - new String[] {"Emily Doe", "Google", "111 Edited St", "Los Angeles", "CA", "90291", - "650-253-0000", "edit@profile.com"}, + new String[] {"Dr.", "Emily Doe", "Google", "111 Edited St", "Los Angeles", "CA", + "90291", "650-253-0000", "edit@profile.com"}, R.id.editor_dialog_done_button, false); // Check if the preferences are updated correctly. Assert.assertEquals(6 /* One toggle + one add button + four profiles. */,
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java index d4f6d697..634acb25 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java
@@ -383,6 +383,7 @@ @MediumTest @Feature({"RenderTest"}) @Features.EnableFeatures(PageInfoFeatureList.PAGE_INFO_V2) + @FlakyTest(message = "https://crbug.com/1156285") public void testShowCookiesSubpage() throws IOException { mActivityTestRule.startMainActivityOnBlankPage(); setThirdPartyCookieBlocking(CookieControlsMode.BLOCK_THIRD_PARTY);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java index 5bda1695..dee3203 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.share; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; @@ -865,6 +866,38 @@ } /** + * Test {@link LensUtils#shouldLogUkm(isIncognito)} method for enable UKM logging for Lens chip + * integration. + */ + @CommandLineFlags. + Add({"enable-features=" + ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP + "<FakeStudyName", + "force-fieldtrials=FakeStudyName/Enabled", + "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" + + "logUkm/true"}) + @Test + @SmallTest + public void + shouldLogUkm_shoppingChipUkmLoggingEnabled() { + assertTrue(shouldLogUkmOnUiThread(/* isIncognito=*/false)); + } + + /** + * Test {@link LensUtils#shouldLogUkm(isIncognito)} method for enable UKM logging for Lens chip + * integration. + */ + @CommandLineFlags. + Add({"enable-features=" + ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP + "<FakeStudyName", + "force-fieldtrials=FakeStudyName/Enabled", + "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" + + "logUkm/false"}) + @Test + @SmallTest + public void + shouldLogUkm_shoppingChipUkmLoggingDisabled() { + assertFalse(shouldLogUkmOnUiThread(/* isIncognito=*/false)); + } + + /** * Test {@link LensUtils#isInShoppingAllowlist(url)} method for url with default shopping url * patterns. */ @@ -897,4 +930,9 @@ return TestThreadUtils.runOnUiThreadBlockingNoException( () -> LensUtils.enableImageChip(isIncognito)); } + + private boolean shouldLogUkmOnUiThread(boolean isIncognito) { + return TestThreadUtils.runOnUiThreadBlockingNoException( + () -> LensUtils.shouldLogUkm(isIncognito)); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/LocationBarMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/LocationBarMediatorTest.java index 6342a6756..00a974ec 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/LocationBarMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/LocationBarMediatorTest.java
@@ -11,26 +11,31 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.content.Context; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.annotation.Config; +import org.chromium.base.BuildConfig; import org.chromium.base.supplier.ObservableSupplierImpl; import org.chromium.base.supplier.OneshotSupplierImpl; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; import org.chromium.chrome.browser.omnibox.status.StatusCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator; @@ -43,12 +48,16 @@ import org.chromium.chrome.test.util.browser.Features; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.components.search_engines.TemplateUrlService; +import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.ui.base.PageTransition; /** Unit tests for LocationBarMediator. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) @Features.EnableFeatures(ChromeFeatureList.OMNIBOX_ASSISTANT_VOICE_SEARCH) public class LocationBarMediatorTest { + private static final String TEST_URL = "http://testurl.com"; + @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); @Rule @@ -82,6 +91,13 @@ private OmniboxPrerender.Natives mPrerenderJni; @Mock private SearchEngineLogoUtils.Delegate mSearchEngineDelegate; + @Mock + private OverrideUrlLoadingDelegate mOverrideUrlLoadingDelegate; + @Mock + private LocaleManager mLocaleManager; + + @Captor + private ArgumentCaptor<LoadUrlParams> mLoadUrlParamsCaptor; private ObservableSupplierImpl<Profile> mProfileSupplier = new ObservableSupplierImpl<>(); private LocationBarMediator mMediator; @@ -93,7 +109,8 @@ mJniMocker.mock(ProfileJni.TEST_HOOKS, mProfileNativesJniMock); mJniMocker.mock(OmniboxPrerenderJni.TEST_HOOKS, mPrerenderJni); mMediator = new LocationBarMediator(mLocationBarLayout, mLocationBarDataProvider, - mAssistantVoiceSearchSupplier, mProfileSupplier, mPrivacyPreferencesManager); + mAssistantVoiceSearchSupplier, mProfileSupplier, mPrivacyPreferencesManager, + mOverrideUrlLoadingDelegate, mLocaleManager); mMediator.setCoordinators(mUrlCoordinator, mAutocompleteCoordinator, mStatusCoordintor); SearchEngineLogoUtils.setDelegateForTesting(mSearchEngineDelegate); } @@ -180,4 +197,44 @@ 456L, profile, mTab); verify(mUrlCoordinator).setAutocompleteText("text", "textWithAutocomplete"); } + + @Test + public void testLoadUrl() { + mMediator.onFinishNativeInitialization(); + + doReturn(mTab).when(mLocationBarDataProvider).getTab(); + mMediator.loadUrl(TEST_URL, PageTransition.TYPED, 0); + + verify(mTab).loadUrl(mLoadUrlParamsCaptor.capture()); + Assert.assertEquals(TEST_URL, mLoadUrlParamsCaptor.getValue().getUrl()); + Assert.assertEquals(PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR, + mLoadUrlParamsCaptor.getValue().getTransitionType()); + } + + @Test + public void testLoadUrl_NativeNotInitialized() { + if (BuildConfig.DCHECK_IS_ON) { + // clang-format off + try { + mMediator.loadUrl(TEST_URL, PageTransition.TYPED, 0); + throw new Error("Expected an assert to be triggered."); + } catch (AssertionError e) {} + // clang-format on + } + } + + @Test + public void testLoadUrl_OverrideLoadingDelegate() { + mMediator.onFinishNativeInitialization(); + + doReturn(mTab).when(mLocationBarDataProvider).getTab(); + doReturn(true) + .when(mOverrideUrlLoadingDelegate) + .willHandleLoadUrlWithPostData(TEST_URL, PageTransition.TYPED, null, null, false); + mMediator.loadUrl(TEST_URL, PageTransition.TYPED, 0); + + verify(mOverrideUrlLoadingDelegate) + .willHandleLoadUrlWithPostData(TEST_URL, PageTransition.TYPED, null, null, false); + verify(mTab, times(0)).loadUrl(any()); + } }
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index c2bfb19a..432e656 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -5487,6 +5487,9 @@ <message name="IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_TITLE" desc="Title for the Welcome screen in Chrome OS 'Add account' dialog."> Add a secondary Google Account for <ph name="USER_NAME">$1<ex>John</ex></ph> </message> + <message name="IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_CHECKBOX" desc="Checkbox text for the Welcome screen in Chrome OS 'Add account' dialog. If user checks this checkbox, this screen will not be shown the next time they open the dialog."> + Don't remind me next time + </message> <message name="IDS_ACCOUNT_MANAGER_ERROR_NO_INTERNET_TITLE" desc="Title for the network error screen."> No Internet </message>
diff --git a/chrome/app/chromeos_strings_grdp/IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_CHECKBOX.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_CHECKBOX.png.sha1 new file mode 100644 index 0000000..54b96e7 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_CHECKBOX.png.sha1
@@ -0,0 +1 @@ +3cd2c3d820354c5f7e641c8eb7f1b6d2608f1535 \ No newline at end of file
diff --git a/chrome/app/nearby_share_strings.grdp b/chrome/app/nearby_share_strings.grdp index 58cd661..db582cf 100644 --- a/chrome/app/nearby_share_strings.grdp +++ b/chrome/app/nearby_share_strings.grdp
@@ -69,7 +69,7 @@ <!-- Discovery page --> <message name="IDS_NEARBY_DISCOVERY_PAGE_INFO" desc="Help text on how to use the Nearby Share feature. Explains how to enable it on a nearby Chromebook to share with it."> - Make sure both devices are unlocked, close together, and have Bluetooth turned on. If you’re sharing with a Chromebook, make sure it has Nearby Sharing turned on (open the status area by selecting the time, then select Nearby Share). <ph name="LINK_BEGIN"><a></ph>Learn more<ph name="LINK_END"></a></ph> + Make sure both devices are unlocked, close together, and have Bluetooth turned on. If you’re sharing with a Chromebook not in your contacts, make sure it has Nearby visibility turned on (open the status area by selecting the time, then select Nearby visibility). <ph name="LINK_BEGIN"><a></ph>Learn more<ph name="LINK_END"></a></ph> </message> <message name="IDS_NEARBY_DISCOVERY_PAGE_SUBTITLE" desc="Subtitle of the Nearby Share device discovery page. This is where users select a device to share files with."> Select the device you’d like to share files with @@ -113,6 +113,9 @@ <message name="IDS_NEARBY_ACTIONS_CANCEL" desc="Action button text to cancel the current step in the Nearby Share UI."> Cancel </message> + <message name="IDS_NEARBY_ACTIONS_CLOSE" desc="Action button text to close the dialog. Shown when the process is complete or failed due to error."> + Close + </message> <message name="IDS_NEARBY_ACTIONS_CONFIRM" desc="Action button text to confirm a transfer in the Nearby Share UI."> Confirm </message> @@ -128,8 +131,8 @@ <message name="IDS_NEARBY_ERROR_CANT_SHARE" desc="Notify user that the file wasn't able to be shared. Generic title text for displaying errors to the user. To be shown next to more specific error text."> Can't share </message> - <message name="IDS_NEARBY_ERROR_NO_RESPONSE" desc="Notify user that the file share failed because the receiver neither accepted nor declined the share."> - The device you're sharing with didn't respond + <message name="IDS_NEARBY_ERROR_NO_RESPONSE" desc="Notify user that the file share failed because the receiver neither accepted nor declined the share. Suggest trying again."> + The device you're sharing with didn't respond. Please try again. </message> <message name="IDS_NEARBY_ERROR_NOT_ENOUGH_SPACE" desc="Notify user that the file can't be shared because there isn't enough disk space to store it. Displayed as a subtitle under a more generic file-couldn't-be-shared message."> Not enough disk space @@ -137,8 +140,8 @@ <message name="IDS_NEARBY_ERROR_REJECTED" desc="Notify sender that receiver declined the file share."> The device you’re trying to share with did not accept </message> - <message name="IDS_NEARBY_ERROR_SOMETHING_WRONG" desc="Generic error text shown when the reason for the failure is unknown or too technical to explain."> - Something went wrong + <message name="IDS_NEARBY_ERROR_SOMETHING_WRONG" desc="Generic error text shown when the reason for the failure is unknown or too technical to explain. Suggest trying again."> + Something went wrong. Please try again. </message> <message name="IDS_NEARBY_ERROR_TIME_OUT" desc="Notify user that the file share failed because something didn't happen in time, e.g. the receiver neither accepted nor declined the share. Generic title text to be shown next to more specific error text describing the situation."> Time out
diff --git a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ACTIONS_CLOSE.png.sha1 b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ACTIONS_CLOSE.png.sha1 new file mode 100644 index 0000000..778ea99b --- /dev/null +++ b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ACTIONS_CLOSE.png.sha1
@@ -0,0 +1 @@ +93c31f041c0e3998f62f5498c463efcac003d13c \ No newline at end of file
diff --git a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_DISCOVERY_PAGE_INFO.png.sha1 b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_DISCOVERY_PAGE_INFO.png.sha1 index 828b14c5..4cc453e 100644 --- a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_DISCOVERY_PAGE_INFO.png.sha1 +++ b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_DISCOVERY_PAGE_INFO.png.sha1
@@ -1 +1 @@ -2ee345a76fb36c02485d4dd7afe01e4a44b2fe44 \ No newline at end of file +ca62ef5bb132403e22abbe5e03f1f4966fb4d01e \ No newline at end of file
diff --git a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_NO_RESPONSE.png.sha1 b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_NO_RESPONSE.png.sha1 index f5d1c7d..778ea99b 100644 --- a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_NO_RESPONSE.png.sha1 +++ b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_NO_RESPONSE.png.sha1
@@ -1 +1 @@ -f38db7627a182411870be8280cf02595d1fd04e5 \ No newline at end of file +93c31f041c0e3998f62f5498c463efcac003d13c \ No newline at end of file
diff --git a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_SOMETHING_WRONG.png.sha1 b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_SOMETHING_WRONG.png.sha1 index c549766d..fc0c6e9 100644 --- a/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_SOMETHING_WRONG.png.sha1 +++ b/chrome/app/nearby_share_strings_grdp/IDS_NEARBY_ERROR_SOMETHING_WRONG.png.sha1
@@ -1 +1 @@ -8c1def7ee1cc0e81f4c65b1bfc75404030354276 \ No newline at end of file +830d82dfe712b7a3b761710c0948bf25543cd76d \ No newline at end of file
diff --git a/chrome/app/os_settings_strings.grdp b/chrome/app/os_settings_strings.grdp index f5960d3..66515df6 100644 --- a/chrome/app/os_settings_strings.grdp +++ b/chrome/app/os_settings_strings.grdp
@@ -993,7 +993,7 @@ <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_TITLE" desc="A title for a dialog to assign a switch key to an action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> Assign switch <ph name="action">$1<ex>Select</ex></ph> </message> - <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_WAIT_FOR_KEY_PROMPT" desc="A message shown to ask a suer to press a switch key to be assigned to an action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_WAIT_FOR_KEY_PROMPT" desc="A message shown to ask a user to press a switch key to be assigned to an action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> Please press a switch key to assign. </message> <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_WAIT_FOR_CONFIRMATION_PROMPT" desc="A message shown to ask a user to confirm by pressing a switch key to be assigned to an action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> @@ -1005,8 +1005,23 @@ <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_WARN_NOT_CONFIRMED_PROMPT" desc="A message warning the user that the switch key pressed during confirmation did not match the initial switch key pressed. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> Keys do not match. '<ph name="unexpectedKey">$1<ex>enter</ex></ph>' was pressed. '<ph name="currentKey">$2<ex>backspace</ex></ph>' was pressed before. Press any key to exit. </message> - <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> - Open a dialog to assign a switch key + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_0_SWITCHES" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Mentions no switches assigned. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + 0 switches assigned + </message> + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_1_SWITCH" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Includes currently assigned switch. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <ph name="SWITCH">$1<ex>backspace</ex></ph> + </message> + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_2_SWITCHES" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Includes listing of two currently assigned switches. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <ph name="FIRST_SWITCH">$1<ex>backspace</ex></ph>, <ph name="SECOND_SWITCH">$2<ex>enter</ex></ph> + </message> + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_3_SWITCHES" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Includes listing of three currently assigned switches. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <ph name="FIRST_SWITCH">$1<ex>backspace</ex></ph>, <ph name="SECOND_SWITCH">$2<ex>enter</ex></ph>, <ph name="THIRD_SWITCH">$3<ex>escape</ex></ph> + </message> + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_4_SWITCHES" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Includes listing of three currently assigned switches, and mentions one other switch is assigned. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <ph name="FIRST_SWITCH">$1<ex>backspace</ex></ph>, <ph name="SECOND_SWITCH">$2<ex>enter</ex></ph>, <ph name="THIRD_SWITCH">$3<ex>escape</ex></ph>, and 1 more switch + </message> + <message name="IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_5_OR_MORE_SWITCHES" desc="A sub-label for the link that brings up a dialog to assign a switch key to an action. Includes listing of three currently assigned switches, and mentions number of other switches assigned. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> + <ph name="FIRST_SWITCH">$1<ex>backspace</ex></ph>, <ph name="SECOND_SWITCH">$2<ex>enter</ex></ph>, <ph name="THIRD_SWITCH">$3<ex>escape</ex></ph>, and <ph name="NUMBER_OF_OTHER_SWITCHES">$4<ex>2</ex></ph> more switches </message> <message name="IDS_SETTINGS_SWITCH_ACCESS_ACTION_ASSIGNMENT_DIALOG_WARN_ALREADY_ASSIGNED_ACTION_PROMPT" desc="A message warning the user that the switch key pressed is assigned to another action. Switch Access is an alternative input method designed for users with limited mobility, where the user has as little as one switch (for example, a button) to control the computer."> '<ph name="currentKey">$1<ex>enter</ex></ph>' is already assigned to the '<ph name="action">$2<ex>Select</ex></ph>' action. Press any key to exit. @@ -2445,10 +2460,10 @@ <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_ACK_SUMMARY" desc="The summary of the dialog containing the Phone Hub notification opt-in flow shown when the Phone Hub 'Notifications' toggle is switched on."> Receive notifications from your phone on your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> </message> - <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_TITLE" translateable="false" desc="The title of the dialog containing the Phone Hub notification opt-in flow shown when the user needs to follow the setup flow instructions on their phone in order to start mirroring notifications from their phone to their Chromebook."> + <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_TITLE" desc="The title of the dialog containing the Phone Hub notification opt-in flow shown when the user needs to follow the setup flow instructions on their phone in order to start mirroring notifications from their phone to their Chromebook."> Complete setup on your phone </message> - <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_SUMMARY" translateable="false" desc="The body text of the dialog containing the Phone Hub notification opt-in flow shown when the user needs to follow the setup flow instructions on their phone in order to start mirroring notifications from their phone to their Chromebook."> + <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_SUMMARY" desc="The body text of the dialog containing the Phone Hub notification opt-in flow shown when the user needs to follow the setup flow instructions on their phone in order to start mirroring notifications from their phone to their Chromebook."> Make sure your phone is nearby, unlocked, and has Bluetooth and Wi-Fi turned on. Follow steps on your phone to complete setup. </message> <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_CONNECTING_TITLE" desc="The title of the dialog containing the Phone Hub notification opt-in flow shown when the user has confirmed to enable the feature that will mirror phone notifications to their Chromebook."> @@ -2460,7 +2475,7 @@ <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_TITLE" desc="The title of the dialog containing the Phone Hub notification opt-in flow when the feature is successfully turned on and notifications on their phone will now be mirrored to their Chromebook."> Notifications turned on </message> - <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_SUMMARY" translateable="false" desc="The body text of the dialog containing the Phone Hub notification opt-in flow when the feature is successfully turned on and notifications on their phone will now be mirrored to their Chromebook."> + <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_SUMMARY" desc="The body text of the dialog containing the Phone Hub notification opt-in flow when the feature is successfully turned on and notifications on their phone will now be mirrored to their Chromebook."> You can now receive notifications from your phone on your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph>. Dismissing notifications on your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> will also dismiss them on your phone. Make sure your phone is nearby and has Bluetooth and Wi-Fi turned on. </message> <message name="IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COULD_NOT_ESTABLISH_CONNECTION_TITLE" desc="The title of the dialog containing the Phone Hub notification opt-in flow when the device is unable to establish a connection to the phone.">
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_ASSIGNMENTS_SUB_LABEL.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_ASSIGNMENTS_SUB_LABEL.png.sha1 new file mode 100644 index 0000000..58e297d7 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_ASSIGNMENTS_SUB_LABEL.png.sha1
@@ -0,0 +1 @@ +28d499afb456baa9c75df032f35b51c60f3bdffd \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL.png.sha1 deleted file mode 100644 index 7e951f3..0000000 --- a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -a512bf0c633d820bfb91e9f0aff89da5551a7787 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_0_SWITCHES.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_0_SWITCHES.png.sha1 new file mode 100644 index 0000000..73ed5d4 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_0_SWITCHES.png.sha1
@@ -0,0 +1 @@ +28c8250e5935e5419fbf77d1dc978825b80eec88 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_1_SWITCH.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_1_SWITCH.png.sha1 new file mode 100644 index 0000000..ced9449 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_1_SWITCH.png.sha1
@@ -0,0 +1 @@ +8c3699b58e6386bc64688243dcc6c352214ea9e4 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_2_SWITCHES.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_2_SWITCHES.png.sha1 new file mode 100644 index 0000000..4618aad --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_2_SWITCHES.png.sha1
@@ -0,0 +1 @@ +c44cd066ef558866202a7a8f76d1667ee9bd93e9 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_3_SWITCHES.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_3_SWITCHES.png.sha1 new file mode 100644 index 0000000..a5d53a2 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_3_SWITCHES.png.sha1
@@ -0,0 +1 @@ +cbef9143e99a2b8b12e7266e1b85219e257e14d3 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_4_SWITCHES.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_4_SWITCHES.png.sha1 new file mode 100644 index 0000000..e44b7a7 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_4_SWITCHES.png.sha1
@@ -0,0 +1 @@ +51e5503c21928f09f4321d3deae9180a342c3264 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_5_OR_MORE_SWITCHES.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_5_OR_MORE_SWITCHES.png.sha1 new file mode 100644 index 0000000..754bee80 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_5_OR_MORE_SWITCHES.png.sha1
@@ -0,0 +1 @@ +8773321941498ed0b035628357477b6594f4ad73 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_SUMMARY.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_SUMMARY.png.sha1 new file mode 100644 index 0000000..620662b2 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_SUMMARY.png.sha1
@@ -0,0 +1 @@ +f0ce57678f6abed15a581f84788f303a82d5d665 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_TITLE.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_TITLE.png.sha1 new file mode 100644 index 0000000..620662b2 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_AWAITING_RESPONSE_TITLE.png.sha1
@@ -0,0 +1 @@ +f0ce57678f6abed15a581f84788f303a82d5d665 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_SUMMARY.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_SUMMARY.png.sha1 new file mode 100644 index 0000000..06fbc16d --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_MULTIDEVICE_NOTIFICATION_ACCESS_SETUP_DIALOG_COMPLETED_SUMMARY.png.sha1
@@ -0,0 +1 @@ +3e088c9a51be79f8da1cb7c31d83d403768b155b \ No newline at end of file
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 81b9dfe..7ea49b7 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -358,11 +358,11 @@ =1 {{COUNT} compromised password} other {{COUNT} compromised passwords}} </message> - <message name="IDS_SETTINGS_INSECURE_PASSWORDS_COUNT" desc="Number of insecure passwords present in the database"> - {COUNT, plural, - =0 {No security issues found} - =1 {Found {COUNT} security issue} - other {Found {COUNT} security issues}} + <message name="IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT" desc="This short text shows the amount of compromised passwords that the Chrome password check found."> + {NUM_COMPROMISED, plural, + =0 {No compromised passwords} + =1 {1 compromised password} + other {{NUM_COMPROMISED} compromised passwords}} </message> <message name="IDS_SETTINGS_WEAK_PASSWORDS_COUNT" desc="Number of weak passwords present in the database. Displayed when the user is signed out and no compromised passwords exist"> {COUNT, plural, @@ -370,6 +370,18 @@ =1 {Found {COUNT} weak password} other {Found {COUNT} weak passwords}} </message> + <message name="IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT" desc="This short text shows the amount of weak passwords that the Chrome password check found."> + {NUM_WEAK, plural, + =0 {No weak passwords} + =1 {1 weak password} + other {{NUM_WEAK} weak passwords}} + </message> + <message name="IDS_SETTINGS_INSECURE_PASSWORDS_COUNT" desc="Number of insecure passwords present in the database"> + {COUNT, plural, + =0 {No security issues found} + =1 {Found {COUNT} security issue} + other {Found {COUNT} security issues}} + </message> <message name="IDS_SETTINGS_CHECK_PASSWORDS_AGAIN" desc="Button to start bulk password check manually in passwords check section."> Check again </message> @@ -1244,15 +1256,6 @@ <message name="IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_FEATURE_UNAVAILABLE" desc="Explains that the password check feature is not available in this version of the browser."> Password check is not available in Chromium </message> - <message name="IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE" desc="This text explains that the Chrome password check did not find any insecure passwords."> - No security issues found - </message> - <message name="IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS" desc="This shows the amount of compromised passwords that the Chrome password check found."> - {NUM_COMPROMISED, plural, =0 {} =1 {1 compromised password} other {{NUM_COMPROMISED} compromised passwords}} - </message> - <message name="IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS" desc="This shows the amount of weak passwords that the Chrome password check found."> - {NUM_WEAK, plural, =0 {} =1 {1 weak password} other {{NUM_WEAK} weak passwords}} - </message> <message name="IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_BUTTON_ARIA_LABEL" desc="Accessibility text for the button that allows users to review their passwords."> Review passwords </message> @@ -1514,6 +1517,12 @@ <message name="IDS_SETTINGS_CLEAR_DATA" desc="Text for clear browsing data button in Privacy options in the tabbed UI"> Clear data </message> + <message name="IDS_SETTINGS_CLEARING_DATA" desc="Accessibility text for after the clear browsing data button is clicked and while the data is being cleared"> + Clearing data... + </message> + <message name="IDS_SETTINGS_CLEARED_DATA" desc="Accessibility text for after the data has been cleared"> + Data cleared. + </message> <message name="IDS_SETTINGS_CLEAR_BROWSING_DATA" desc="Text for clear browsing data button in Privacy options"> Clear browsing data </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARED_DATA.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARED_DATA.png.sha1 new file mode 100644 index 0000000..5436f48ef --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARED_DATA.png.sha1
@@ -0,0 +1 @@ +773c91219cad9d9630b8e09b06ecfaad26394504 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARING_DATA.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARING_DATA.png.sha1 new file mode 100644 index 0000000..cdad2b84 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CLEARING_DATA.png.sha1
@@ -0,0 +1 @@ +74bbd2055e63e512ed986c83e2c7fac0c42f66e4 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT.png.sha1 new file mode 100644 index 0000000..f4047135 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT.png.sha1
@@ -0,0 +1 @@ +57beb450355e12e0a3ca2c8c9a4ce2b41a892535 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS.png.sha1 deleted file mode 100644 index 03ed930..0000000 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -48000c9b3b776cd72ef4b37861123533cef88cb7 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE.png.sha1 deleted file mode 100644 index 9051e4c..0000000 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -9337b5cfa3bcef4342156a73d83cf37043f783e9 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS.png.sha1 deleted file mode 100644 index 17a7c6cb..0000000 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -8d987688c08641fee35f117eddeaa63f9769a515 \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT.png.sha1 new file mode 100644 index 0000000..0ce6202 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT.png.sha1
@@ -0,0 +1 @@ +3530dd0582d65de57d6d71d472576ce8c41fd292 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 1ebb6408..40b4701 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -105,6 +105,7 @@ ] deps = [ "//base", + "//build:chromeos_buildflags", "//chrome/common:buildflags", "//media:media_buildflags", ] @@ -1234,6 +1235,8 @@ "policy/messaging_layer/upload/dm_server_upload_service.h", "policy/messaging_layer/upload/record_handler_impl.cc", "policy/messaging_layer/upload/record_handler_impl.h", + "policy/messaging_layer/upload/record_upload_request_builder.cc", + "policy/messaging_layer/upload/record_upload_request_builder.h", "policy/messaging_layer/upload/upload_client.cc", "policy/messaging_layer/upload/upload_client.h", "policy/messaging_layer/util/backoff_settings.cc", @@ -2359,7 +2362,7 @@ "//ui/webui", "//ui/webui/resources/cr_components/customize_themes:mojom", ] - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "apps/digital_goods/digital_goods_factory_impl.cc", "apps/digital_goods/digital_goods_factory_impl.h", @@ -2449,7 +2452,7 @@ # Platforms that have a network diagnostics dialog. All others fall through # to the stub which is not implemented. - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "net/net_error_diagnostics_dialog_chromeos.cc" ] } else if (is_win) { sources += [ "net/net_error_diagnostics_dialog_win.cc" ] @@ -4157,7 +4160,7 @@ "//courgette:courgette_lib", "//third_party/sqlite", ] - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "sharing/webrtc/ice_config_fetcher.cc", "sharing/webrtc/ice_config_fetcher.h", @@ -4193,14 +4196,13 @@ "task_manager/sampling/shared_sampler_posix.cc", ] - # TODO(crbug.com / 1052397): Rename chromeos_is_browser_only to is_lacros. - if (!chromeos_is_browser_only) { + if (!is_chromeos_lacros) { sources += [ "first_run/first_run_internal_posix.cc" ] } } } - if (is_chromeos) { + if (is_chromeos_ash) { assert(enable_native_notifications) sources += [ "apps/app_service/arc_activity_adaptive_icon_impl.cc", @@ -4545,21 +4547,21 @@ ] } - if (is_chromeos || enable_extensions || is_android) { + if (is_chromeos_ash || enable_extensions || is_android) { sources += [ "metrics/cached_metrics_profile.cc", "metrics/cached_metrics_profile.h", ] } - if (is_chromeos || chromeos_is_browser_only) { + if (is_chromeos_ash || is_chromeos_lacros) { sources += [ "feedback/system_logs/log_sources/user_log_files_log_source.cc", "feedback/system_logs/log_sources/user_log_files_log_source.h", ] } - if (is_lacros) { + if (is_chromeos_lacros) { assert(enable_native_notifications) sources += [ "chrome_browser_main_parts_lacros.cc", @@ -4581,6 +4583,8 @@ "lacros/immersive_context_lacros.h", "lacros/lacros_chrome_service_delegate_impl.cc", "lacros/lacros_chrome_service_delegate_impl.h", + "lacros/metrics_reporting_observer.cc", + "lacros/metrics_reporting_observer.h", "lacros/snap_controller_lacros.cc", "lacros/snap_controller_lacros.h", "lacros/system_logs/lacros_system_log_fetcher.cc", @@ -5009,7 +5013,7 @@ } } - if (is_chromeos) { + if (is_chromeos_ash) { if (use_allocator == "tcmalloc") { deps += [ "//chrome/common/performance_manager/mojom" ] @@ -5020,7 +5024,7 @@ } } - if (is_linux) { + if (is_linux || is_chromeos_lacros) { # Desktop linux, doesn't count ChromeOS. sources += [ "download/download_status_updater_linux.cc", @@ -5041,7 +5045,7 @@ deps += [ "//components/dbus/thread_linux" ] } - if (!is_lacros) { + if (!is_chromeos_lacros) { sources += [ "platform_util_linux.cc" ] if (enable_native_notifications) { @@ -5102,14 +5106,14 @@ ] } - if (is_win || is_chromeos) { + if (is_win || is_chromeos_ash) { sources += [ "webshare/share_service_impl.cc", "webshare/share_service_impl.h", ] } - if (is_win || is_mac || is_linux) { + if (is_win || is_mac || (is_linux || is_chromeos_lacros)) { sources += [ "browser_switcher/alternative_browser_driver.h", "browser_switcher/browser_switcher_navigation_throttle.cc", @@ -5128,12 +5132,12 @@ if (is_win) { sources += [ "browser_switcher/alternative_browser_driver_win.cc" ] } - if (is_mac || is_linux) { + if (is_mac || (is_linux || is_chromeos_lacros)) { sources += [ "browser_switcher/alternative_browser_driver_posix.cc" ] } } - if (is_chromeos && use_cras) { + if (is_chromeos_ash && use_cras) { defines += [ "USE_CRAS" ] } @@ -5154,7 +5158,7 @@ ] } - if (!is_android && !is_chromeos) { + if (!is_android && !is_chromeos_ash) { sources += [ "device_identity/device_oauth2_token_store_desktop.cc", "device_identity/device_oauth2_token_store_desktop.h", @@ -5221,7 +5225,7 @@ "upgrade_detector/upgrade_detector_impl.cc", "upgrade_detector/upgrade_detector_impl.h", ] - } else { # is_android || is_chromeos + } else { # is_android || is_chromeos_ash sources += [ "installable/digital_asset_links/digital_asset_links_handler.cc", "installable/digital_asset_links/digital_asset_links_handler.h", @@ -5274,7 +5278,7 @@ ] } - if (is_win || is_mac || (is_chromeos && use_dbus)) { + if (is_win || is_mac || (is_chromeos_ash && use_dbus)) { sources += [ "media_galleries/fileapi/device_media_async_file_util.cc", "media_galleries/fileapi/device_media_async_file_util.h", @@ -5285,7 +5289,7 @@ "media_galleries/fileapi/mtp_file_stream_reader.cc", "media_galleries/fileapi/mtp_file_stream_reader.h", ] - if (is_chromeos && use_dbus) { + if (is_chromeos_ash && use_dbus) { # TODO(donna.wu@intel.com): push this into chrome / browser / chromeos # and chrome / browser / media_galleries / chromeos deps += [ "//services/device/public/mojom" ] @@ -5340,10 +5344,10 @@ if (is_mac) { sources += [ "background/background_mode_manager_mac.mm" ] } - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "background/background_mode_manager_chromeos.cc" ] } - if (use_aura && !is_win && !is_chromeos) { + if (use_aura && !is_win && !is_chromeos_ash) { sources += [ "background/background_mode_manager_aura.cc" ] } } @@ -5444,7 +5448,7 @@ ] } - if (!is_chromeos) { + if (!is_chromeos_ash) { sources += [ "printing/cloud_print/cloud_print_proxy_service.cc", "printing/cloud_print/cloud_print_proxy_service.h", @@ -5738,7 +5742,7 @@ "//google_apis/drive", "//services/device/public/mojom", ] - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "speech/extension_api/tts_engine_extension_observer_chromeos.cc", "speech/extension_api/tts_engine_extension_observer_chromeos.h", @@ -6020,7 +6024,7 @@ "//services/device/public/mojom", "//third_party/adobe/flash:flapper_version_h", ] - if (is_chromeos) { + if (is_chromeos_ash) { deps += [ "//chromeos/cryptohome" ] } } @@ -6291,7 +6295,7 @@ if (use_cups) { configs += [ "//printing:cups" ] - if (is_chromeos) { + if (is_chromeos_ash) { deps += [ "//chrome/services/cups_proxy", "//chrome/services/cups_proxy/public/mojom", @@ -6306,10 +6310,10 @@ "net/nss_context.cc", "net/nss_context.h", ] - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "net/nss_context_chromeos.cc" ] } - if (is_linux) { + if (is_linux || is_chromeos_lacros) { sources += [ "net/nss_context_linux.cc" ] } } @@ -6446,10 +6450,10 @@ if (enable_plugins) { #.json is not in the default sources_assignment_filter. - if (is_chromeos) { + if (is_chromeos_ash) { inputs = [ "resources/plugin_metadata/plugins_chromeos.json" ] } - if (is_linux && !is_chromeos) { + if (is_linux || is_chromeos_lacros) { inputs = [ "resources/plugin_metadata/plugins_linux.json" ] } if (is_mac) { @@ -6476,7 +6480,7 @@ deps += [ "//chrome/browser/ui/webui/explore_sites_internals:mojo_bindings_js" ] } - if (is_chromeos) { + if (is_chromeos_ash) { deps += [ "//chrome/browser/resources/chromeos/account_manager:web_components", "//chrome/browser/resources/chromeos/account_manager/components:web_components", @@ -6500,7 +6504,7 @@ ] } - if (is_chromeos && optimize_webui) { + if (is_chromeos_ash && optimize_webui) { deps += [ "//chrome/browser/resources/chromeos/internet_config_dialog:build", "//chrome/browser/resources/chromeos/internet_detail_dialog:build", @@ -6744,7 +6748,7 @@ ] } - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "chromeos/app_mode/fake_cws.cc", "chromeos/app_mode/fake_cws.h", @@ -6850,7 +6854,7 @@ "//google_apis:test_support", "//services/data_decoder/public/cpp:test_support", ] - if (is_chromeos) { + if (is_chromeos_ash) { deps += [ "//chrome/browser/chromeos" ] } }
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index e20dcbf..116dfa90 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -204,7 +204,7 @@ #include "chrome/browser/web_applications/components/external_app_install_features.h" #endif // OS_ANDROID -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/ash_switches.h" #include "chrome/browser/chromeos/crosapi/browser_util.h" #include "chrome/browser/nearby_sharing/common/nearby_share_features.h" @@ -215,7 +215,7 @@ #include "media/capture/video/chromeos/video_capture_features_chromeos.h" #include "third_party/cros_system_api/switches/chrome_switches.h" #include "ui/events/ozone/features.h" -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) #include "chrome/browser/ui/browser_dialogs.h" @@ -470,7 +470,7 @@ nullptr}}; #endif // OS_ANDROID -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::FeatureParam kForceDark_SimpleHsl[] = { {"inversion_method", "hsl_based"}, {"image_behavior", "none"}, @@ -685,7 +685,7 @@ {flags_ui::kGenericExperimentChoiceEnabled, switches::kTopChromeTouchUi, switches::kTopChromeTouchUiEnabled}}; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const char kLacrosSupportInternalName[] = "lacros-support"; const char kLacrosStabilityInternalName[] = "lacros-stability"; @@ -713,9 +713,9 @@ {flag_descriptions::kUiShowCompositedLayerBordersAll, cc::switches::kUIShowCompositedLayerBorders, ""}}; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::Choice kCrosRegionsModeChoices[] = { {flag_descriptions::kCrosRegionsModeDefault, "", ""}, {flag_descriptions::kCrosRegionsModeOverride, @@ -725,7 +725,7 @@ chromeos::switches::kCrosRegionsMode, chromeos::switches::kCrosRegionsModeHide}, }; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::Choice kForceUIDirectionChoices[] = { {flags_ui::kGenericExperimentChoiceDefault, "", ""}, @@ -743,7 +743,7 @@ switches::kForceDirectionRTL}, }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::Choice kSchedulerConfigurationChoices[] = { {flags_ui::kGenericExperimentChoiceDefault, "", ""}, {flag_descriptions::kSchedulerConfigurationConservative, @@ -753,7 +753,7 @@ switches::kSchedulerConfiguration, switches::kSchedulerConfigurationPerformance}, }; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) const FeatureEntry::FeatureParam kCompactSuggestions_SemicompactVariant[] = { @@ -2267,7 +2267,7 @@ base::size(kAlignFontDisplayAutoTimeoutWithLCPGoalSwap1000), nullptr}, }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::Choice kEnableCrOSActionRecorderChoices[] = { {flags_ui::kGenericExperimentChoiceDefault, "", ""}, {ash::switches::kCrOSActionRecorderWithHash, @@ -2286,7 +2286,7 @@ ash::switches::kEnableCrOSActionRecorder, ash::switches::kCrOSActionRecorderStructuredDisabled}, }; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) const FeatureEntry::Choice kWebOtpBackendChoices[] = { @@ -2325,7 +2325,7 @@ switches::kEnableExperimentalCookieFeatures, ""}, }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::Choice kFrameThrottleFpsChoices[] = { {flag_descriptions::kFrameThrottleFpsDefault, "", ""}, {flag_descriptions::kFrameThrottleFps5, ash::switches::kFrameThrottleFps, @@ -2340,7 +2340,7 @@ "25"}, {flag_descriptions::kFrameThrottleFps30, ash::switches::kFrameThrottleFps, "30"}}; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) // The variations of --password-change-in-settings. @@ -2373,11 +2373,11 @@ nullptr}}; #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) constexpr char kAssistantBetterOnboardingInternalName[] = "enable-assistant-better-onboarding"; constexpr char kAssistantTimersV2InternalName[] = "enable-assistant-timers-v2"; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if !defined(OS_WIN) && !defined(OS_FUCHSIA) const FeatureEntry::FeatureParam @@ -2468,12 +2468,12 @@ kSubresourceRedirectLoginRobotsBasedCompression, base::size(kSubresourceRedirectLoginRobotsBasedCompression), nullptr}}; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const FeatureEntry::FeatureVariation kOmniboxRichEntitiesInLauncherVariations[] = { {"with linked Suggest experiment", {}, 0, "t4461027"}, }; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // RECORDING USER METRICS FOR FLAGS: // ----------------------------------------------------------------------------- @@ -2501,6 +2501,7 @@ const FeatureEntry kFeatureEntries[] = { // Include generated flags for flag unexpiry; see //docs/flag_expiry.md and // //tools/flags/generate_unexpire_flags.py. +#include "build/chromeos_buildflags.h" #include "chrome/browser/unexpire_flags_gen.inc" {"ignore-gpu-blocklist", flag_descriptions::kIgnoreGpuBlocklistName, flag_descriptions::kIgnoreGpuBlocklistDescription, kOsAll, @@ -2756,7 +2757,7 @@ flag_descriptions::kWebUITabStripDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kWebUITabStrip)}, #endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) -#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) { "webui-tab-strip-tab-drag-integration", flag_descriptions::kWebUITabStripTabDragIntegrationName, @@ -2764,11 +2765,11 @@ kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kWebUITabStripTabDragIntegration), }, -#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) {"focus-mode", flag_descriptions::kFocusMode, flag_descriptions::kFocusModeDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kFocusMode)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"disable-explicit-dma-fences", flag_descriptions::kDisableExplicitDmaFencesName, flag_descriptions::kDisableExplicitDmaFencesDescription, kOsCrOS, @@ -2779,8 +2780,8 @@ flag_descriptions::kUseHDRTransferFunctionName, flag_descriptions::kUseHDRTransferFunctionDescription, kOsCrOS, FEATURE_VALUE_TYPE(display::features::kUseHDRTransferFunction)}, -#endif // OS_CHROMEOS -#if defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"account-management-flows-v2", flag_descriptions::kAccountManagementFlowsV2Name, flag_descriptions::kAccountManagementFlowsV2Description, kOsCrOS, @@ -2926,9 +2927,9 @@ {"system-tray-mic-gain", flag_descriptions::kSystemTrayMicGainName, flag_descriptions::kSystemTrayMicGainDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kSystemTrayMicGainSetting)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#if (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && !defined(OS_ANDROID) { "enable-accelerated-video-decode", flag_descriptions::kAcceleratedVideoDecodeName, @@ -2944,7 +2945,8 @@ kOsMac | kOsWin | kOsCrOS | kOsAndroid, SINGLE_DISABLE_VALUE_TYPE(switches::kDisableAcceleratedVideoDecode), }, -#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#endif // (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && + // !defined(OS_ANDROID) { "disable-accelerated-video-encode", flag_descriptions::kAcceleratedVideoEncodeName, @@ -2959,7 +2961,7 @@ kOsAll, FEATURE_VALUE_TYPE(media::kEnableMediaInternals), }, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) { "zero-copy-video-capture", flag_descriptions::kZeroCopyVideoCaptureName, @@ -2985,7 +2987,7 @@ flag_descriptions::kUiShowCompositedLayerBordersName, flag_descriptions::kUiShowCompositedLayerBordersDescription, kOsCrOS, MULTI_VALUE_TYPE(kUiShowCompositedLayerBordersChoices)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"debug-packed-apps", flag_descriptions::kDebugPackedAppName, flag_descriptions::kDebugPackedAppDescription, kOsDesktop, SINGLE_VALUE_TYPE(switches::kDebugPackedApps)}, @@ -3042,7 +3044,7 @@ flag_descriptions::kSuggestionsWithSubStringMatchName, flag_descriptions::kSuggestionsWithSubStringMatchDescription, kOsAll, FEATURE_VALUE_TYPE(autofill::features::kAutofillTokenPrefixMatching)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-virtual-keyboard", flag_descriptions::kVirtualKeyboardName, flag_descriptions::kVirtualKeyboardDescription, kOsCrOS, SINGLE_VALUE_TYPE(keyboard::switches::kEnableVirtualKeyboard)}, @@ -3050,7 +3052,7 @@ flag_descriptions::kVirtualKeyboardDisabledName, flag_descriptions::kVirtualKeyboardDisabledDescription, kOsCrOS, SINGLE_VALUE_TYPE(keyboard::switches::kDisableVirtualKeyboard)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_SERVICE_DISCOVERY) {"device-discovery-notifications", flag_descriptions::kDeviceDiscoveryNotificationsName, @@ -3113,7 +3115,7 @@ kOverrideSitePrefsForHrefTranslateVariations, "OverrideSitePrefsForHrefTranslate")}, -#if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS) && !defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS) && !BUILDFLAG(IS_CHROMEOS_ASH) {"enable-native-notifications", flag_descriptions::kNotificationsNativeFlagName, flag_descriptions::kNotificationsNativeFlagDescription, @@ -3180,13 +3182,13 @@ flag_descriptions::kExtensionContentVerificationName, flag_descriptions::kExtensionContentVerificationDescription, kOsDesktop, MULTI_VALUE_TYPE(kExtensionContentVerificationChoices)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-lock-screen-notification", flag_descriptions::kLockScreenNotificationName, flag_descriptions::kLockScreenNotificationDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kLockScreenNotifications)}, -#endif // OS_CHROMEOS -#if defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"crostini-use-dlc", flag_descriptions::kCrostiniUseDlcName, flag_descriptions::kCrostiniUseDlcDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCrostiniUseDlc)}, @@ -3220,7 +3222,7 @@ flag_descriptions::kDynamicTcmallocDescription, kOsCrOS, FEATURE_VALUE_TYPE(performance_manager::features::kDynamicTcmallocTuning)}, #endif // BUILDFLAG(USE_TCMALLOC) -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"enable-site-isolation-for-password-sites", flag_descriptions::kSiteIsolationForPasswordSitesName, @@ -3290,7 +3292,7 @@ flag_descriptions::kEnableNavigationPredictorRendererWarmupName, flag_descriptions::kEnableNavigationPredictorRendererWarmupDescription, kOsAll, FEATURE_VALUE_TYPE(features::kNavigationPredictorRendererWarmup)}, -#endif // OS_CHROMEOS || OS_LINUX +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || OS_LINUX {"enable-preconnect-to-search", flag_descriptions::kEnablePreconnectToSearchName, flag_descriptions::kEnablePreconnectToSearchDescription, kOsAll, @@ -3421,11 +3423,11 @@ flag_descriptions::kMacV2GPUSandboxDescription, kOsMac, FEATURE_VALUE_TYPE(features::kMacV2GPUSandbox)}, #endif // OS_MAC -#if defined(OS_CHROMEOS) || defined(OS_WIN) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_WIN) {"web-share", flag_descriptions::kWebShareName, flag_descriptions::kWebShareDescription, kOsWin | kOsCrOS, FEATURE_VALUE_TYPE(features::kWebShare)}, -#endif // OS_CHROMEOS || OS_WIN +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || OS_WIN #if BUILDFLAG(ENABLE_VR) {"webxr-incubations", flag_descriptions::kWebXrIncubationsName, flag_descriptions::kWebXrIncubationsDescription, kOsAll, @@ -3437,12 +3439,12 @@ flag_descriptions::kWebXrForceRuntimeDescription, kOsDesktop, MULTI_VALUE_TYPE(kWebXrForceRuntimeChoices)}, #endif // ENABLE_VR -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"disable-accelerated-mjpeg-decode", flag_descriptions::kAcceleratedMjpegDecodeName, flag_descriptions::kAcceleratedMjpegDecodeDescription, kOsCrOS, SINGLE_DISABLE_VALUE_TYPE(switches::kDisableAcceleratedMjpegDecode)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"system-keyboard-lock", flag_descriptions::kSystemKeyboardLockName, flag_descriptions::kSystemKeyboardLockDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kSystemKeyboardLock)}, @@ -3575,11 +3577,11 @@ flag_descriptions::kUseWinrtMidiApiDescription, kOsWin, FEATURE_VALUE_TYPE(midi::features::kMidiManagerWinrt)}, #endif // OS_WIN -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"cros-regions-mode", flag_descriptions::kCrosRegionsModeName, flag_descriptions::kCrosRegionsModeDescription, kOsCrOS, MULTI_VALUE_TYPE(kCrosRegionsModeChoices)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID) {"enable-autofill-credit-card-upload", flag_descriptions::kAutofillCreditCardUploadName, @@ -3668,7 +3670,7 @@ FEATURE_VALUE_TYPE(password_manager::features::kPasswordImport)}, {"enable-force-dark", flag_descriptions::kForceWebContentsDarkModeName, flag_descriptions::kForceWebContentsDarkModeDescription, kOsAll, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // TODO(https://crbug.com/1011696): Investigate crash reports and // re-enable variations for ChromeOS. FEATURE_VALUE_TYPE(blink::features::kForceWebContentsDarkMode)}, @@ -3676,7 +3678,7 @@ FEATURE_WITH_PARAMS_VALUE_TYPE(blink::features::kForceWebContentsDarkMode, kForceDarkVariations, "ForceDarkVariations")}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"enable-android-dark-search", flag_descriptions::kAndroidDarkSearchName, flag_descriptions::kAndroidDarkSearchDescription, kOsAndroid, @@ -3710,7 +3712,7 @@ flag_descriptions::kAriaElementReflectionName, flag_descriptions::kAriaElementReflectionDescription, kOsAll, FEATURE_VALUE_TYPE(features::kEnableAriaElementReflection)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-encryption-migration", flag_descriptions::kEnableEncryptionMigrationName, flag_descriptions::kEnableEncryptionMigrationDescription, kOsCrOS, @@ -3793,7 +3795,7 @@ flag_descriptions::kMagnifierNewFocusFollowingName, flag_descriptions::kMagnifierNewFocusFollowingDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kMagnifierNewFocusFollowing)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) {"enable-immersive-fullscreen-toolbar", flag_descriptions::kImmersiveFullscreenName, @@ -3831,7 +3833,7 @@ {"fill-on-account-select", flag_descriptions::kFillOnAccountSelectName, flag_descriptions::kFillOnAccountSelectDescription, kOsAll, FEATURE_VALUE_TYPE(password_manager::features::kFillOnAccountSelect)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"arc-custom-tabs-experiment", flag_descriptions::kArcCustomTabsExperimentName, flag_descriptions::kArcCustomTabsExperimentDescription, kOsCrOS, @@ -3858,7 +3860,7 @@ {"arc-usb-host", flag_descriptions::kArcUsbHostName, flag_descriptions::kArcUsbHostDescription, kOsCrOS, FEATURE_VALUE_TYPE(arc::kUsbHostFeature)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) {"enable-winrt-sensor-implementation", flag_descriptions::kWinrtSensorsImplementationName, @@ -3874,12 +3876,12 @@ flag_descriptions::kExpensiveBackgroundTimerThrottlingDescription, kOsAll, FEATURE_VALUE_TYPE(features::kExpensiveBackgroundTimerThrottling)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {ui_devtools::switches::kEnableUiDevTools, flag_descriptions::kUiDevToolsName, flag_descriptions::kUiDevToolsDescription, kOsCrOS, SINGLE_VALUE_TYPE(ui_devtools::switches::kEnableUiDevTools)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-autofill-credit-card-ablation-experiment", flag_descriptions::kEnableAutofillCreditCardAblationExperimentDisplayName, @@ -3900,13 +3902,13 @@ FEATURE_VALUE_TYPE(autofill::features::kAutofillRefreshStyleAndroid)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-touchscreen-calibration", flag_descriptions::kTouchscreenCalibrationName, flag_descriptions::kTouchscreenCalibrationDescription, kOsCrOS, SINGLE_VALUE_TYPE(chromeos::switches::kEnableTouchCalibrationSetting)}, -#endif // defined(OS_CHROMEOS) -#if defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"camera-system-web-app", flag_descriptions::kCameraSystemWebAppName, flag_descriptions::kCameraSystemWebAppDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCameraSystemWebApp)}, @@ -3980,7 +3982,7 @@ {"spectre-v2-mitigation", flag_descriptions::kSpectreVariant2MitigationName, flag_descriptions::kSpectreVariant2MitigationDescription, kOsCrOS, FEATURE_VALUE_TYPE(sandbox::policy::features::kSpectreVariant2Mitigation)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) {"gdi-text-printing", flag_descriptions::kGdiTextPrinting, @@ -4172,11 +4174,11 @@ kOsAll, FEATURE_VALUE_TYPE(omnibox::kSpeculativeServiceWorkerStartOnQueryInput)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"scheduler-configuration", flag_descriptions::kSchedulerConfigurationName, flag_descriptions::kSchedulerConfigurationDescription, kOsCrOS, MULTI_VALUE_TYPE(kSchedulerConfigurationChoices)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"enable-command-line-on-non-rooted-devices", @@ -4316,7 +4318,7 @@ flag_descriptions::kEnableSearchPrefetchDescription, kOsAll, SINGLE_VALUE_TYPE(kSearchPrefetchServiceCommandLineFlag)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"handwriting-gesture", flag_descriptions::kHandwritingGestureName, flag_descriptions::kHandwritingGestureDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kHandwritingGesture)}, @@ -4325,7 +4327,7 @@ flag_descriptions::kHandwritingGestureEditingName, flag_descriptions::kHandwritingGestureEditingDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kHandwritingGestureEditing)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"block-insecure-private-network-requests", flag_descriptions::kBlockInsecurePrivateNetworkRequestsName, @@ -4393,12 +4395,12 @@ FEATURE_VALUE_TYPE(chrome::android::kOmniboxSpareRenderer)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"double-tap-to-zoom-in-tablet-mode", flag_descriptions::kDoubleTapToZoomInTabletModeName, flag_descriptions::kDoubleTapToZoomInTabletModeDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kDoubleTapToZoomInTabletMode)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {flag_descriptions::kReadLaterFlagId, flag_descriptions::kReadLaterName, flag_descriptions::kReadLaterDescription, kOsDesktop | kOsAndroid, @@ -4629,7 +4631,7 @@ flag_descriptions::kEnableWebAuthenticationCableV2SupportDescription, kOsDesktop | kOsAndroid, FEATURE_VALUE_TYPE(device::kWebAuthPhoneSupport)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-web-authentication-chromeos-authenticator", flag_descriptions::kEnableWebAuthenticationChromeOSAuthenticatorName, flag_descriptions:: @@ -4860,7 +4862,7 @@ FEATURE_VALUE_TYPE( lookalikes::features::kDetectTargetEmbeddingLookalikes)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-app-data-search", flag_descriptions::kEnableAppDataSearchName, flag_descriptions::kEnableAppDataSearchDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kEnableAppDataSearch)}, @@ -4868,7 +4870,7 @@ {"enable-app-grid-ghost", flag_descriptions::kEnableAppGridGhostName, flag_descriptions::kEnableAppGridGhostDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kEnableAppGridGhost)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if !defined(OS_ANDROID) {"enable-accessibility-live-caption", @@ -4927,12 +4929,12 @@ FEATURE_VALUE_TYPE( autofill::features::kAutofillEnableAccountWalletStorage)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-zero-state-app-reinstall-suggestions", flag_descriptions::kEnableAppReinstallZeroStateName, flag_descriptions::kEnableAppReinstallZeroStateDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kEnableAppReinstallZeroState)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-resampling-input-events", flag_descriptions::kEnableResamplingInputEventsName, @@ -4966,7 +4968,7 @@ kOsAll, FEATURE_VALUE_TYPE(features::kCompositorThreadedScrollbarScrolling)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-vaapi-jpeg-image-decode-acceleration", flag_descriptions::kVaapiJpegImageDecodeAccelerationName, flag_descriptions::kVaapiJpegImageDecodeAccelerationDescription, kOsCrOS, @@ -5052,7 +5054,7 @@ kOsMac | kOsWin | kOsLinux, FEATURE_VALUE_TYPE(features::kDestroyProfileOnBrowserClose)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-usbguard", flag_descriptions::kUsbguardName, flag_descriptions::kUsbguardDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kUsbguard)}, @@ -5067,7 +5069,7 @@ flag_descriptions::kKerberosSettingsSectionName, flag_descriptions::kKerberosSettingsSectionDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kKerberosSettingsSection)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) {"use-angle", flag_descriptions::kUseAngleName, @@ -5084,7 +5086,7 @@ "EphemeralTabOpenMode")}, #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-assistant-dsp", flag_descriptions::kEnableGoogleAssistantDspName, flag_descriptions::kEnableGoogleAssistantDspDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::assistant::features::kEnableDspHotword)}, @@ -5146,7 +5148,7 @@ flag_descriptions::kEnableAssistantTimersV2Name, flag_descriptions::kEnableAssistantTimersV2Description, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::assistant::features::kAssistantTimersV2)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_CLICK_TO_CALL) {"click-to-call-ui", flag_descriptions::kClickToCallUIName, @@ -5202,7 +5204,7 @@ kSharingDeviceExpirationVariations, "SharingDeviceExpiration")}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"ash-enable-pip-rounded-corners", flag_descriptions::kAshEnablePipRoundedCornersName, flag_descriptions::kAshEnablePipRoundedCornersDescription, kOsCrOS, @@ -5213,7 +5215,7 @@ flag_descriptions::kAshSwapSideVolumeButtonsForOrientationDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kSwapSideVolumeButtonsForOrientation)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-implicit-root-scroller", flag_descriptions::kEnableImplicitRootScrollerName, flag_descriptions::kEnableImplicitRootScrollerDescription, kOsAll, @@ -5224,13 +5226,13 @@ flag_descriptions::kEnableTextFragmentAnchorDescription, kOsAll, FEATURE_VALUE_TYPE(blink::features::kTextFragmentAnchor)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-assistant-stereo-input", flag_descriptions::kEnableGoogleAssistantStereoInputName, flag_descriptions::kEnableGoogleAssistantStereoInputDescription, kOsCrOS, FEATURE_VALUE_TYPE( chromeos::assistant::features::kEnableStereoAudioInput)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-audio-focus-enforcement", flag_descriptions::kEnableAudioFocusEnforcementName, @@ -5252,7 +5254,7 @@ FEATURE_VALUE_TYPE(media::kHardwareMediaKeyHandling)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"app-service-adaptive-icon", flag_descriptions::kAppServiceAdaptiveIconName, flag_descriptions::kAppServiceAdaptiveIconDescription, kOsCrOS, @@ -5285,7 +5287,7 @@ {"intent-handling-sharing", flag_descriptions::kIntentHandlingSharingName, flag_descriptions::kIntentHandlingSharingDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kIntentHandlingSharing)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) {"d3d11-video-decoder", flag_descriptions::kD3D11VideoDecoderName, @@ -5293,7 +5295,7 @@ FEATURE_VALUE_TYPE(media::kD3D11VideoDecoder)}, #endif -#if defined(OS_CHROMEOS) && BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION) +#if BUILDFLAG(IS_CHROMEOS_ASH) && BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION) {"chromeos-direct-video-decoder", flag_descriptions::kChromeOSDirectVideoDecoderName, flag_descriptions::kChromeOSDirectVideoDecoderDescription, kOsCrOS, @@ -5320,12 +5322,12 @@ autofill_assistant::features::kAutofillAssistantProactiveHelp)}, #endif // defined(OS_ANDROID) -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) {"web-contents-occlusion", flag_descriptions::kWebContentsOcclusionName, flag_descriptions::kWebContentsOcclusionDescription, kOsWin | kOsMac | kOsCrOS, FEATURE_VALUE_TYPE(features::kWebContentsOcclusion)}, -#endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"mobile-identity-consistency", @@ -5357,12 +5359,12 @@ FEATURE_VALUE_TYPE(views::kInstallableInkDropFeature)}, #endif // defined(TOOLKIT_VIEWS) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-assistant-launcher-integration", flag_descriptions::kEnableAssistantLauncherIntegrationName, flag_descriptions::kEnableAssistantLauncherIntegrationDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kEnableAssistantSearch)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(TOOLKIT_VIEWS) {"enable-md-rounded-corners-on-dialogs", @@ -5392,7 +5394,7 @@ kOsLinux | kOsWin | kOsAndroid | kOsMac, FEATURE_VALUE_TYPE(features::kUseSkiaRenderer)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"allow-disable-mouse-acceleration", flag_descriptions::kAllowDisableMouseAccelerationName, flag_descriptions::kAllowDisableMouseAccelerationDescription, kOsCrOS, @@ -5508,7 +5510,7 @@ {"print-server-scaling", flag_descriptions::kPrintServerScalingName, flag_descriptions::kPrintServerScalingDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kPrintServerScaling)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"autofill-off-no-server-data", flag_descriptions::kAutofillOffNoServerDataName, @@ -5564,12 +5566,12 @@ FEATURE_VALUE_TYPE(features::kEnterpriseReportingApiKeychainRecreation)}, #endif // defined(OS_MAC) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enterprise-reporting-in-chromeos", flag_descriptions::kEnterpriseReportingInChromeOSName, flag_descriptions::kEnterpriseReportingInChromeOSDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kEnterpriseReportingInChromeOS)}, -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) #if !defined(OS_ANDROID) {"enterprise-realtime-extension-request", @@ -5603,12 +5605,12 @@ flag_descriptions::kAutofillPruneSuggestionsDescription, kOsAll, FEATURE_VALUE_TYPE(autofill::features::kAutofillPruneSuggestions)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-advanced-ppd-attributes", flag_descriptions::kEnableAdvancedPpdAttributesName, flag_descriptions::kEnableAdvancedPpdAttributesDescription, kOsCrOS, FEATURE_VALUE_TYPE(printing::features::kAdvancedPpdAttributes)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"allow-sync-xhr-in-page-dismissal", flag_descriptions::kAllowSyncXHRInPageDismissalName, @@ -5636,25 +5638,25 @@ flag_descriptions::kColorPickerEyeDropperDescription, kOsWin | kOsMac, FEATURE_VALUE_TYPE(features::kEyeDropper)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"auto-screen-brightness", flag_descriptions::kAutoScreenBrightnessName, flag_descriptions::kAutoScreenBrightnessDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kAutoScreenBrightness)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"audio-worklet-realtime-thread", flag_descriptions::kAudioWorkletRealtimeThreadName, flag_descriptions::kAudioWorkletRealtimeThreadDescription, kOsAll, FEATURE_VALUE_TYPE(blink::features::kAudioWorkletRealtimeThread)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"smart-dim-model-v3", flag_descriptions::kSmartDimModelV3Name, flag_descriptions::kSmartDimModelV3Description, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kSmartDimModelV3)}, {"smart-dim-new-ml-agent", flag_descriptions::kSmartDimNewMlAgentName, flag_descriptions::kSmartDimNewMlAgentDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kSmartDimNewMlAgent)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"privacy-reordered-android", @@ -5718,12 +5720,12 @@ FEATURE_VALUE_TYPE( safe_browsing::kEnhancedProtectionMessageInInterstitials)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"gesture-properties-dbus-service", flag_descriptions::kEnableGesturePropertiesDBusServiceName, flag_descriptions::kEnableGesturePropertiesDBusServiceDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kGesturePropertiesDBusService)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"cookie-deprecation-messages", flag_descriptions::kCookieDeprecationMessagesName, @@ -5808,11 +5810,11 @@ flag_descriptions::kSafetyTipDescription, kOsAll, FEATURE_VALUE_TYPE(security_state::features::kSafetyTipUI)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"crostini-webui-upgrader", flag_descriptions::kCrostiniWebUIUpgraderName, flag_descriptions::kCrostiniWebUIUpgraderDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCrostiniWebUIUpgrader)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"turn-off-streaming-media-caching-on-battery", flag_descriptions::kTurnOffStreamingMediaCachingOnBatteryName, @@ -5841,12 +5843,12 @@ SINGLE_VALUE_TYPE( previews::switches::kEnableDeferAllScriptWithoutOptimizationHints)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-assistant-routines", flag_descriptions::kEnableAssistantRoutinesName, flag_descriptions::kEnableAssistantRoutinesDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::assistant::features::kAssistantRoutines)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"notification-scheduler-debug-options", flag_descriptions::kNotificationSchedulerDebugOptionName, @@ -5861,18 +5863,18 @@ #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"lock-screen-media-controls", flag_descriptions::kLockScreenMediaControlsName, flag_descriptions::kLockScreenMediaControlsDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kLockScreenMediaControls)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"contextual-nudges", flag_descriptions::kContextualNudgesName, flag_descriptions::kContextualNudgesDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kContextualNudges)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"decode-jpeg-images-to-yuv", flag_descriptions::kDecodeJpeg420ImagesToYUVName, @@ -5954,7 +5956,7 @@ chrome::android::kContextMenuSearchAndShopWithGoogleLens)}, #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"launcher-settings-search", flag_descriptions::kLauncherSettingsSearchName, flag_descriptions::kLauncherSettingsSearchDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kLauncherSettingsSearch)}, @@ -5962,7 +5964,7 @@ {"enable-suggested-files", flag_descriptions::kEnableSuggestedFilesName, flag_descriptions::kEnableSuggestedFilesDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kEnableSuggestedFiles)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"passwords-account-storage", flag_descriptions::kEnablePasswordsAccountStorageName, @@ -6020,7 +6022,7 @@ FEATURE_VALUE_TYPE(security_state::features::kLegacyTLSWarnings)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-assistant-aec", flag_descriptions::kEnableGoogleAssistantAecName, flag_descriptions::kEnableGoogleAssistantAecDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::assistant::features::kAssistantAudioEraser)}, @@ -6054,7 +6056,7 @@ FEATURE_VALUE_TYPE(features::kNewMacNotificationAPI)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"exo-gamepad-vibration", flag_descriptions::kExoGamepadVibrationName, flag_descriptions::kExoGamepadVibrationDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kGamepadVibration)}, @@ -6064,7 +6066,7 @@ {"exo-pointer-lock", flag_descriptions::kExoPointerLockName, flag_descriptions::kExoPointerLockDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kExoPointerLock)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) {"metal", flag_descriptions::kMetalName, @@ -6076,12 +6078,12 @@ flag_descriptions::kEnableDeJellyDescription, kOsAll, SINGLE_VALUE_TYPE(switches::kEnableDeJelly)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-cros-action-recorder", flag_descriptions::kEnableCrOSActionRecorderName, flag_descriptions::kEnableCrOSActionRecorderDescription, kOsCrOS, MULTI_VALUE_TYPE(kEnableCrOSActionRecorderChoices)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"enable-games-hub", flag_descriptions::kGamesHubName, @@ -6105,7 +6107,7 @@ FEATURE_VALUE_TYPE(blink::features::kFtpProtocol)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"crostini-use-buster-image", flag_descriptions::kCrostiniUseBusterImageName, flag_descriptions::kCrostiniUseBusterImageDescription, kOsCrOS, @@ -6113,7 +6115,7 @@ {"crostini-disk-resizing", flag_descriptions::kCrostiniDiskResizingName, flag_descriptions::kCrostiniDiskResizingDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCrostiniDiskResizing)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"homepage-promo-card", flag_descriptions::kHomepagePromoCardName, @@ -6123,7 +6125,7 @@ "HomepagePromoAndroid")}, #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"split-settings-sync", flag_descriptions::kSplitSettingsSyncName, flag_descriptions::kSplitSettingsSyncDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kSplitSettingsSync)}, @@ -6160,18 +6162,18 @@ flag_descriptions::kUseWallpaperStagingUrlName, flag_descriptions::kUseWallpaperStagingUrlDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kUseWallpaperStagingUrl)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"autofill-enable-virtual-card", flag_descriptions::kAutofillEnableVirtualCardName, flag_descriptions::kAutofillEnableVirtualCardDescription, kOsDesktop, FEATURE_VALUE_TYPE(autofill::features::kAutofillEnableVirtualCard)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"account-id-migration", flag_descriptions::kAccountIdMigrationName, flag_descriptions::kAccountIdMigrationDescription, kOsCrOS, FEATURE_VALUE_TYPE(switches::kAccountIdMigration)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // TODO(https://crbug.com/1032161): Implement and enable for ChromeOS. {"raw-clipboard", flag_descriptions::kRawClipboardName, @@ -6209,7 +6211,7 @@ flag_descriptions::kFreezeUserAgentDescription, kOsDesktop | kOsAndroid, FEATURE_VALUE_TYPE(blink::features::kFreezeUserAgent)}, -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) {"enable-user-data-snapshot", flag_descriptions::kUserDataSnapshotName, flag_descriptions::kUserDataSnapshotDescription, kOsMac | kOsWin | kOsLinux, @@ -6280,7 +6282,7 @@ FEATURE_VALUE_TYPE(page_info::kPageInfoV2)}, #endif // !defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"drag-to-snap-in-clamshell-mode", flag_descriptions::kDragToSnapInClamshellModeName, flag_descriptions::kDragToSnapInClamshellModeDescription, kOsCrOS, @@ -6301,7 +6303,7 @@ flag_descriptions::kEnhancedClipboardSimpleRenderName, flag_descriptions::kEnhancedClipboardSimpleRenderDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kClipboardHistorySimpleRender)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) {"enable-media-foundation-video-capture", @@ -6310,14 +6312,14 @@ FEATURE_VALUE_TYPE(media::kMediaFoundationVideoCapture)}, #endif // defined(OS_WIN) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"scanning-ui", flag_descriptions::kScanningUIName, flag_descriptions::kScanningUIDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kScanningUI)}, {"avatar-toolbar-button", flag_descriptions::kAvatarToolbarButtonName, flag_descriptions::kAvatarToolbarButtonDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kAvatarToolbarButton)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"color-provider-redirection", flag_descriptions::kColorProviderRedirectionName, @@ -6347,7 +6349,7 @@ FEATURE_VALUE_TYPE(features::kCopyLinkToText)}, #endif // !defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"nearby-sharing", flag_descriptions::kNearbySharingName, flag_descriptions::kNearbySharingDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kNearbySharing)}, @@ -6358,7 +6360,7 @@ {"nearby-sharing-webrtc", flag_descriptions::kNearbySharingWebRtcName, flag_descriptions::kNearbySharingWebRtcDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kNearbySharingWebRtc)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"android-default-browser-promo", @@ -6400,7 +6402,7 @@ kAlignFontDisplayAutoTimeoutWithLCPGoalVariations, "AlignFontDisplayAutoTimeoutWithLCPGoal")}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-palm-suppression", flag_descriptions::kEnablePalmSuppressionName, flag_descriptions::kEnablePalmSuppressionDescription, kOsCrOS, FEATURE_VALUE_TYPE(ui::kEnablePalmSuppression)}, @@ -6409,7 +6411,7 @@ flag_descriptions::kMovablePartialScreenshotName, flag_descriptions::kMovablePartialScreenshotDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kMovablePartialScreenshot)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-experimental-cookie-features", flag_descriptions::kEnableExperimentalCookieFeaturesName, @@ -6447,11 +6449,11 @@ flag_descriptions::kEnableTranslateSubFramesDescription, kOsAll, FEATURE_VALUE_TYPE(translate::kTranslateSubFrames)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"suggested-content-toggle", flag_descriptions::kSuggestedContentToggleName, flag_descriptions::kSuggestedContentToggleDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kSuggestedContentToggle)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if !defined(OS_ANDROID) {"enable-media-feeds", flag_descriptions::kEnableMediaFeedsName, @@ -6507,7 +6509,7 @@ FEATURE_VALUE_TYPE(features::kChromeCleanupScanCompletedNotification)}, #endif // !defined(OS_WIN) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-launcher-app-paging", flag_descriptions::kNewDragSpecInLauncherName, flag_descriptions::kNewDragSpecInLauncherDescription, kOsCrOS, @@ -6515,18 +6517,18 @@ {"cdm-factory-daemon", flag_descriptions::kCdmFactoryDaemonName, flag_descriptions::kCdmFactoryDaemonDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCdmFactoryDaemon)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"autofill-enable-offers-in-downstream", flag_descriptions::kAutofillEnableOffersInDownstreamName, flag_descriptions::kAutofillEnableOffersInDownstreamDescription, kOsAll, FEATURE_VALUE_TYPE(autofill::features::kAutofillEnableOffersInDownstream)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-sharesheet", flag_descriptions::kSharesheetName, flag_descriptions::kSharesheetDescription, kOsAll, FEATURE_VALUE_TYPE(features::kSharesheet)}, -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"schemeful-same-site", flag_descriptions::kSchemefulSameSiteName, flag_descriptions::kSchemefulSameSiteDescription, kOsAll, @@ -6567,11 +6569,11 @@ FEATURE_VALUE_TYPE( security_interstitials::kInsecureFormSubmissionInterstitial)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"frame-throttle-fps", flag_descriptions::kFrameThrottleFpsName, flag_descriptions::kFrameThrottleFpsDescription, kOsCrOS, MULTI_VALUE_TYPE(kFrameThrottleFpsChoices)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"filling-passwords-from-any-origin", @@ -6628,11 +6630,11 @@ autofill::features::kAutofillDownstreamCvcPromptUseGooglePayLogo)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-auto-select", flag_descriptions::kEnableAutoSelectName, flag_descriptions::kEnableAutoSelectDescription, kOsCrOS, FEATURE_VALUE_TYPE(blink::features::kCrOSAutoSelect)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"smart-suggestion-for-large-downloads", @@ -6689,7 +6691,7 @@ flag_descriptions::kSyncAutofillWalletOfferDataDescription, kOsAll, FEATURE_VALUE_TYPE(switches::kSyncAutofillWalletOfferData)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"enable-holding-space", flag_descriptions::kHoldingSpaceName, flag_descriptions::kHoldingSpaceDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kTemporaryHoldingSpace)}, @@ -6718,7 +6720,7 @@ FEATURE_VALUE_TYPE(features::kUseSerialBusEnumerator)}, #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"omnibox-rich-entities-in-launcher", flag_descriptions::kOmniboxRichEntitiesInLauncherName, flag_descriptions::kOmniboxRichEntitiesInLauncherDescription, kOsCrOS, @@ -6741,15 +6743,17 @@ FEATURE_VALUE_TYPE(features::kMuteNotificationsDuringScreenShare)}, #endif // !defined(OS_ANDROID) -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || \ +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || \ defined(OS_MAC) {"enable-ephemeral-guest-profiles-on-desktop", flag_descriptions::kEnableEphemeralGuestProfilesOnDesktopName, flag_descriptions::kEnableEphemeralGuestProfilesOnDesktopDescription, kOsWin | kOsLinux | kOsMac, FEATURE_VALUE_TYPE(features::kEnableEphemeralGuestProfilesOnDesktop)}, -#endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || - // defined(OS_MAC) +#endif // defined(OS_WIN) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS)) || defined(OS_MAC) #if defined(OS_ANDROID) {"decouple-sync-from-android-auto-sync", @@ -6802,12 +6806,12 @@ kOsWin | kOsLinux | kOsCrOS, FEATURE_VALUE_TYPE(blink::features::kInsertKeyToggleMode)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"connectivity-diagnostics-webui", flag_descriptions::kConnectivityDiagnosticsWebUiName, flag_descriptions::kConnectivityDiagnosticsWebUiDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kConnectivityDiagnosticsWebUi)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) {"enable-autofill-password-account-indicator-footer", @@ -6888,12 +6892,12 @@ flag_descriptions::kShowPerformanceMetricsHudDescription, kOsAll, FEATURE_VALUE_TYPE(features::kHudDisplayForPerformanceMetrics)}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"disable-buffer-bw-compression", flag_descriptions::kDisableBufferBWCompressionName, flag_descriptions::kDisableBufferBWCompressionDescription, kOsCrOS, SINGLE_VALUE_TYPE(switches::kDisableBufferBWCompression)}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) {"enable-prerender2", flag_descriptions::kPrerender2Name, flag_descriptions::kPrerender2Description, kOsAll, @@ -6930,6 +6934,11 @@ FEATURE_VALUE_TYPE(continuous_search::features::kContinuousSearch)}, #endif // defined(OS_ANDROID) + // TODO(crbug.com/1155358): Enable Chrome Labs for ChromeOS + {"chrome-labs", flag_descriptions::kChromeLabsName, + flag_descriptions::kChromeLabsDescription, kOsLinux | kOsMac | kOsWin, + FEATURE_VALUE_TYPE(features::kChromeLabs)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the @@ -6974,7 +6983,7 @@ bool SkipConditionalFeatureEntry(const flags_ui::FlagsStorage* storage, const FeatureEntry& entry) { version_info::Channel channel = chrome::GetChannel(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // enable-ui-devtools is only available on for non Stable channels. if (!strcmp(ui_devtools::switches::kEnableUiDevTools, entry.internal_name) && channel == version_info::Channel::STABLE) { @@ -7003,7 +7012,7 @@ channel != version_info::Channel::UNKNOWN) { return true; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // data-reduction-proxy-lo-fi and enable-data-reduction-proxy-lite-page // are only available for Chromium builds and the Canary/Dev/Beta channels. @@ -7078,13 +7087,13 @@ std::set<base::CommandLine::StringType>* out_difference) { const char* extra_flag_sentinel_begin_flag_name = nullptr; const char* extra_flag_sentinel_end_flag_name = nullptr; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Put the flags between --policy-switches--begin and --policy-switches-end on // ChromeOS. extra_flag_sentinel_begin_flag_name = chromeos::switches::kPolicySwitchesBegin; extra_flag_sentinel_end_flag_name = chromeos::switches::kPolicySwitchesEnd; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return flags_ui::FlagsState::AreSwitchesIdenticalToCurrentCommandLine( new_cmdline, active_cmdline, out_difference, extra_flag_sentinel_begin_flag_name, extra_flag_sentinel_end_flag_name);
diff --git a/chrome/browser/about_flags_browsertest.cc b/chrome/browser/about_flags_browsertest.cc index 206e813..806e3bd0 100644 --- a/chrome/browser/about_flags_browsertest.cc +++ b/chrome/browser/about_flags_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -261,7 +262,7 @@ // non-ChromeOS. ToggleEnableDropdown(contents, kFlagName, true); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // On non-ChromeOS, the command line is not modified until restart. EXPECT_EQ(kInitialSwitches, base::CommandLine::ForCurrentProcess()->GetSwitches()); @@ -282,7 +283,7 @@ // Flaky. http://crbug.com/1010678 IN_PROC_BROWSER_TEST_P(AboutFlagsBrowserTest, DISABLED_OriginFlagEnabled) { -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // On non-ChromeOS, the command line is modified after restart. EXPECT_EQ( GetSanitizedInputAndCommandLine(), @@ -301,7 +302,7 @@ EXPECT_EQ(GetSanitizedInputAndCommandLine(), GetOriginListText(contents, kFlagName)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS doesn't read chrome://flags values on startup so we explicitly // need to disable and re-enable the flag here. ToggleEnableDropdown(contents, kFlagName, true); @@ -347,7 +348,7 @@ EXPECT_TRUE(IsFlagPresent(contents, kExpiredFlagName)); } -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_P(AboutFlagsBrowserTest, PRE_ExpiredFlagDoesntApply) { NavigateToFlagsPage(); content::WebContents* contents =
diff --git a/chrome/browser/accessibility/accessibility_extension_api.cc b/chrome/browser/accessibility/accessibility_extension_api.cc index e007e7de..26104d0f 100644 --- a/chrome/browser/accessibility/accessibility_extension_api.cc +++ b/chrome/browser/accessibility/accessibility_extension_api.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chromeos/accessibility/magnification_manager.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" @@ -38,7 +39,7 @@ #include "ui/events/base_event_utils.h" #include "ui/events/keycodes/keyboard_codes.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/accessibility_controller.h" #include "ash/public/cpp/accessibility_controller_enums.h" #include "ash/public/cpp/accessibility_focus_ring_info.h" @@ -82,7 +83,7 @@ const std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // TODO(chrome-a11y-core): we can't open a settings page when you're on the // signin profile, but maybe we should notify the user and explain why? Profile* profile = chromeos::AccessibilityManager::Get()->profile(); @@ -94,13 +95,13 @@ #else // This function should only be available on ChromeOS. EXTENSION_FUNCTION_VALIDATE(false); -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return RespondNow(NoArguments()); } ExtensionFunction::ResponseAction AccessibilityPrivateSetFocusRingsFunction::Run() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<accessibility_private::SetFocusRings::Params> params( accessibility_private::SetFocusRings::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -171,12 +172,12 @@ return RespondNow(NoArguments()); #else return RespondNow(Error(kErrorNotSupported)); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } ExtensionFunction::ResponseAction AccessibilityPrivateSetHighlightsFunction::Run() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<accessibility_private::SetHighlights::Params> params( accessibility_private::SetHighlights::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -194,7 +195,7 @@ chromeos::AccessibilityManager::Get()->SetHighlights(rects, color); return RespondNow(NoArguments()); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return RespondNow(Error(kErrorNotSupported)); } @@ -204,7 +205,7 @@ ChromeExtensionFunctionDetails details(this); CHECK(extension()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool enabled; bool capture; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &enabled)); @@ -223,14 +224,14 @@ ash::EventRewriterController::Get()->CaptureAllKeysForSpokenFeedback( enabled && capture); return RespondNow(NoArguments()); -#endif // defined OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return RespondNow(Error(kErrorNotSupported)); } ExtensionFunction::ResponseAction AccessibilityPrivateDarkenScreenFunction::Run() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool darken = false; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &darken)); chromeos::AccessibilityManager::Get()->SetDarkenScreen(darken); @@ -240,7 +241,7 @@ #endif } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ExtensionFunction::ResponseAction AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction::Run() { std::unique_ptr<
diff --git a/chrome/browser/accessibility/accessibility_extension_api.h b/chrome/browser/accessibility/accessibility_extension_api.h index d535299f..ded97e2 100644 --- a/chrome/browser/accessibility/accessibility_extension_api.h +++ b/chrome/browser/accessibility/accessibility_extension_api.h
@@ -7,6 +7,7 @@ #include <string> +#include "build/chromeos_buildflags.h" #include "extensions/browser/extension_function.h" // API function that enables or disables web content accessibility support. @@ -61,7 +62,7 @@ ACCESSIBILITY_PRIVATE_OPENSETTINGSSUBPAGE) }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // API function that sets native ChromeVox ARC support. class AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction : public ExtensionFunction {
diff --git a/chrome/browser/accessibility/accessibility_labels_service_browsertest.cc b/chrome/browser/accessibility/accessibility_labels_service_browsertest.cc index 427af46..ab070aa 100644 --- a/chrome/browser/accessibility/accessibility_labels_service_browsertest.cc +++ b/chrome/browser/accessibility/accessibility_labels_service_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/command_line.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -14,11 +15,11 @@ #include "content/public/browser/browser_accessibility_state.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_test.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #else #include "content/public/browser/browser_accessibility_state.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) class AccessibilityLabelsBrowserTest : public InProcessBrowserTest { public: @@ -34,7 +35,7 @@ void TearDownOnMainThread() override { EnableScreenReader(false); } void EnableScreenReader(bool enabled) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Enable Chromevox. chromeos::AccessibilityManager::Get()->EnableSpokenFeedback(enabled); #else @@ -46,7 +47,7 @@ content::BrowserAccessibilityState::GetInstance() ->RemoveAccessibilityModeFlags(ui::AXMode::kScreenReader); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } private:
diff --git a/chrome/browser/accessibility/accessibility_state_utils.cc b/chrome/browser/accessibility/accessibility_state_utils.cc index 12e43e0..e0e8970 100644 --- a/chrome/browser/accessibility/accessibility_state_utils.cc +++ b/chrome/browser/accessibility/accessibility_state_utils.cc
@@ -4,17 +4,19 @@ #include "chrome/browser/accessibility/accessibility_state_utils.h" -#if defined(OS_CHROMEOS) +#include "build/chromeos_buildflags.h" + +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #else #include <stdint.h> #include "content/public/browser/browser_accessibility_state.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace accessibility_state_utils { bool IsScreenReaderEnabled() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) return chromeos::AccessibilityManager::Get() && chromeos::AccessibilityManager::Get()->IsSpokenFeedbackEnabled(); #else @@ -23,7 +25,7 @@ ui::AXMode mode = content::BrowserAccessibilityState::GetInstance()->GetAccessibilityMode(); return mode.has_mode(ui::AXMode::kScreenReader); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } } // namespace accessibility_state_utils
diff --git a/chrome/browser/accessibility/browser_accessibility_state_browsertest.cc b/chrome/browser/accessibility/browser_accessibility_state_browsertest.cc index 88276db..3189fd9 100644 --- a/chrome/browser/accessibility/browser_accessibility_state_browsertest.cc +++ b/chrome/browser/accessibility/browser_accessibility_state_browsertest.cc
@@ -4,6 +4,7 @@ #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/test/browser_test.h" @@ -22,7 +23,7 @@ BrowserAccessibilityState::GetInstance()->UpdateHistogramsForTesting(); #if defined(OS_WIN) histograms.ExpectTotalCount("Accessibility.WinScreenReader", 1); -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) histograms.ExpectTotalCount("Accessibility.CrosSpokenFeedback", 1); #endif }
diff --git a/chrome/browser/accessibility/caption_controller_browsertest.cc b/chrome/browser/accessibility/caption_controller_browsertest.cc index fe72dc1..c97a964 100644 --- a/chrome/browser/accessibility/caption_controller_browsertest.cc +++ b/chrome/browser/accessibility/caption_controller_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/files/file_path.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/accessibility/caption_controller_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/lifetime/application_lifetime.h" @@ -473,7 +474,7 @@ #endif } -#if !defined(OS_CHROMEOS) // No multi-profile on ChromeOS. +#if !BUILDFLAG(IS_CHROMEOS_ASH) // No multi-profile on ChromeOS. IN_PROC_BROWSER_TEST_F(CaptionControllerTest, LiveCaptionEnabledChanged_MultipleProfiles) {
diff --git a/chrome/browser/after_startup_task_utils.cc b/chrome/browser/after_startup_task_utils.cc index dcea2ca0..8816c2dc 100644 --- a/chrome/browser/after_startup_task_utils.cc +++ b/chrome/browser/after_startup_task_utils.cc
@@ -18,6 +18,7 @@ #include "base/sequenced_task_runner.h" #include "base/synchronization/atomic_flag.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" @@ -32,7 +33,9 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #endif -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "ui/views/linux_ui/linux_ui.h" #endif @@ -138,7 +141,9 @@ g_after_startup_tasks.Get().clear(); g_after_startup_tasks.Get().shrink_to_fit(); -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // Make sure we complete the startup notification sequence, or launchers will // get confused by not receiving the expected message from the main process. views::LinuxUI* linux_ui = views::LinuxUI::instance();
diff --git a/chrome/browser/android/contextualsearch/contextual_search_manager.cc b/chrome/browser/android/contextualsearch/contextual_search_manager.cc index 61a85d0..7d1f4429 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_manager.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_manager.cc
@@ -168,7 +168,7 @@ overlay_web_contents, this); } -void ContextualSearchManager::WhitelistContextualSearchJsApiUrl( +void ContextualSearchManager::AllowlistContextualSearchJsApiUrl( JNIEnv* env, jobject obj, const base::android::JavaParamRef<jstring>& j_url) {
diff --git a/chrome/browser/android/contextualsearch/contextual_search_manager.h b/chrome/browser/android/contextualsearch/contextual_search_manager.h index c941d5b..f247823 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_manager.h +++ b/chrome/browser/android/contextualsearch/contextual_search_manager.h
@@ -48,14 +48,14 @@ const base::android::JavaParamRef<jobject>& j_contextual_search_context, const base::android::JavaParamRef<jobject>& j_base_web_contents); - // Whitelists the given |j_url| for injection of the Contextual Search + // Allowlists the given |j_url| for injection of the Contextual Search // JavaScript API. EnableContextualSearchJsApiForWebContents must also be // called with the WebContents that will host the page in the Overlay. // This method should be called when the URL navigation starts so the // JavaScript API can be established before the page executes. // The given URL is stored for future reference when ShouldEnableJsApi is // called by a Renderer through mojo. - void WhitelistContextualSearchJsApiUrl( + void AllowlistContextualSearchJsApiUrl( JNIEnv* env, jobject obj, const base::android::JavaParamRef<jstring>& j_url); @@ -64,7 +64,7 @@ // This method should be called at least once for this Overlay Panel, and // before any page loads in the Overlay so that the Contextual Search // JavaScript API can be injected into the Overlay Panel. - // WhitelistContextualSearchJsApiUrl must also be called for every URL + // AllowlistContextualSearchJsApiUrl must also be called for every URL // that will be loaded, in order for the JavaScript API to be enabled for that // URL. void EnableContextualSearchJsApiForWebContents(
diff --git a/chrome/browser/apps/app_service/crostini_apps.cc b/chrome/browser/apps/app_service/crostini_apps.cc index 8438573..cf417ec8 100644 --- a/chrome/browser/apps/app_service/crostini_apps.cc +++ b/chrome/browser/apps/app_service/crostini_apps.cc
@@ -241,13 +241,13 @@ : apps::mojom::OptionalBool::kFalse; // The Crostini Terminal app is a hard-coded special case. It is the entry - // point to installing other Crostini apps. + // point to installing other Crostini apps, and is always in search. apps::mojom::AppPtr app = apps::mojom::App::New(); app->app_type = apps::mojom::AppType::kCrostini; app->app_id = crostini::kCrostiniTerminalSystemAppId; app->show_in_launcher = show; app->show_in_shelf = show; - app->show_in_search = show; + app->show_in_search = apps::mojom::OptionalBool::kTrue; Publish(std::move(app), subscribers_); }
diff --git a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc index b351c34e..299460c 100644 --- a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc +++ b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc
@@ -8,6 +8,7 @@ #include <utility> #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/apps/intent_helper/intent_picker_auto_display_service.h" #include "chrome/browser/apps/intent_helper/intent_picker_internal.h" #include "chrome/browser/ui/intent_picker_tab_helper.h" @@ -15,7 +16,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/apps/intent_helper/chromeos_intent_picker_helpers.h" #elif defined(OS_MAC) #include "chrome/browser/apps/intent_helper/mac_intent_picker_helpers.h" @@ -85,7 +86,7 @@ // TODO(crbug.com/824598): Store the apps that is found in // intent_picker_tab_helper and update the icon visibility and apps if there is // app installed or uninstalled. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) MaybeShowIntentPickerChromeOs(navigation_handle); #else const GURL& url = navigation_handle->GetURL(); @@ -96,7 +97,7 @@ void ShowIntentPickerBubble(content::WebContents* web_contents, const GURL& url) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ShowIntentPickerBubbleChromeOs(web_contents, url); #else std::vector<IntentPickerAppInfo> apps = FindAppsForUrl(web_contents, url, {});
diff --git a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc index 6616189..2cb6cb8 100644 --- a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc +++ b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc
@@ -13,6 +13,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/media_galleries/media_file_system_registry.h" @@ -221,7 +222,9 @@ } // Test is flaky on windows and linux: crbug.com/1150017. -#if defined(OS_WIN) || defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #define MAYBE_RemoveListenerAndModifyGallery \ DISABLED_RemoveListenerAndModifyGallery #else
diff --git a/chrome/browser/apps/platform_apps/app_browsertest.cc b/chrome/browser/apps/platform_apps/app_browsertest.cc index 3269931..fc8134a 100644 --- a/chrome/browser/apps/platform_apps/app_browsertest.cc +++ b/chrome/browser/apps/platform_apps/app_browsertest.cc
@@ -830,7 +830,7 @@ // This appears to be unreliable. // TODO(stevenjb): Investigate and enable -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) || defined(OS_WIN) || \ +#if (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || defined(OS_WIN) || \ defined(OS_MAC) #define MAYBE_AppWindowRestoreState DISABLED_AppWindowRestoreState #else
diff --git a/chrome/browser/autocomplete/autocomplete_browsertest.cc b/chrome/browser/autocomplete/autocomplete_browsertest.cc index 0018af8..bb8550a56 100644 --- a/chrome/browser/autocomplete/autocomplete_browsertest.cc +++ b/chrome/browser/autocomplete/autocomplete_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/memory_dump_manager.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h" #include "chrome/browser/autocomplete/in_memory_url_index_factory.h" #include "chrome/browser/extensions/extension_browsertest.h" @@ -127,7 +128,7 @@ // Autocomplete test is flaky on ChromeOS. // http://crbug.com/52928 -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_Autocomplete DISABLED_Autocomplete #else #define MAYBE_Autocomplete Autocomplete
diff --git a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc index b141ec3..a81ac31 100644 --- a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc +++ b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc
@@ -13,6 +13,7 @@ #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" #include "chrome/browser/autocomplete/document_suggestions_service_factory.h" #include "chrome/browser/autocomplete/in_memory_url_index_factory.h" @@ -123,7 +124,7 @@ chrome::kLanguageOptionsSubPage, chrome::kPasswordManagerSubPage, chrome::kPaymentsSubPage, chrome::kResetProfileSettingsSubPage, chrome::kSearchEnginesSubPage, chrome::kSyncSetupSubPage, -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) chrome::kCreateProfileSubPage, chrome::kImportDataSubPage, chrome::kManageProfileSubPage, chrome::kPeopleSubPage, #endif
diff --git a/chrome/browser/autofill/android/personal_data_manager_android.cc b/chrome/browser/autofill/android/personal_data_manager_android.cc index 9d1b0c8..87f2af7 100644 --- a/chrome/browser/autofill/android/personal_data_manager_android.cc +++ b/chrome/browser/autofill/android/personal_data_manager_android.cc
@@ -323,6 +323,8 @@ AutofillType(NAME_FULL), ConvertJavaStringToUTF16(Java_AutofillProfile_getFullName(env, jprofile)), g_browser_process->GetApplicationLocale()); + MaybeSetRawInfo(profile, autofill::NAME_HONORIFIC_PREFIX, + Java_AutofillProfile_getHonorificPrefix(env, jprofile)); MaybeSetRawInfo(profile, autofill::COMPANY_NAME, Java_AutofillProfile_getCompanyName(env, jprofile)); MaybeSetRawInfo(profile, autofill::ADDRESS_HOME_STREET_ADDRESS,
diff --git a/chrome/browser/background/background_mode_manager.cc b/chrome/browser/background/background_mode_manager.cc index eb07f1a..948f8be 100644 --- a/chrome/browser/background/background_mode_manager.cc +++ b/chrome/browser/background/background_mode_manager.cc
@@ -870,7 +870,8 @@ // Since there are multiple profiles which share the status tray, we now // use the browser process to keep track of it. -#if !defined(OS_MAC) && !defined(OS_CHROMEOS) && !BUILDFLAG(IS_LACROS) +#if !defined(OS_MAC) && !BUILDFLAG(IS_CHROMEOS_ASH) && \ + !BUILDFLAG(IS_CHROMEOS_LACROS) if (!status_tray_) status_tray_ = g_browser_process->status_tray(); #endif
diff --git a/chrome/browser/background/background_mode_manager_unittest.cc b/chrome/browser/background/background_mode_manager_unittest.cc index 350d5ee..6b2cf08 100644 --- a/chrome/browser/background/background_mode_manager_unittest.cc +++ b/chrome/browser/background/background_mode_manager_unittest.cc
@@ -17,6 +17,7 @@ #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" @@ -45,7 +46,7 @@ #include "ui/gfx/image/image.h" #include "ui/message_center/public/cpp/notifier_id.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #endif @@ -308,7 +309,7 @@ // We aren't interested in if the keep alive works correctly in this test. std::unique_ptr<ScopedKeepAlive> test_keep_alive_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS needs extra services to run in the following order. chromeos::ScopedCrosSettingsTestHelper cros_settings_test_helper_; chromeos::ScopedTestUserManager test_user_manager_;
diff --git a/chrome/browser/banners/app_banner_manager_desktop.cc b/chrome/browser/banners/app_banner_manager_desktop.cc index f5f8f35..fdfa0cc 100644 --- a/chrome/browser/banners/app_banner_manager_desktop.cc +++ b/chrome/browser/banners/app_banner_manager_desktop.cc
@@ -12,6 +12,7 @@ #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/banners/app_banner_metrics.h" #include "chrome/browser/banners/app_banner_settings_helper.h" #include "chrome/browser/profiles/profile.h" @@ -24,10 +25,10 @@ #include "extensions/common/constants.h" #include "third_party/blink/public/mojom/manifest/display_mode.mojom.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { @@ -35,9 +36,9 @@ // https://github.com/w3c/manifest/wiki/Platforms const char kPlatformChromeWebStore[] = "chrome_web_store"; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const char kPlatformPlay[] = "play"; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) bool gDisableTriggeringForTesting = false; @@ -108,13 +109,13 @@ if (base::EqualsASCII(platform, kPlatformChromeWebStore)) return true; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::EqualsASCII(platform, kPlatformPlay) && arc::IsArcAllowedForProfile( Profile::FromBrowserContext(web_contents()->GetBrowserContext()))) { return true; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return false; } @@ -134,13 +135,13 @@ id, extensions::ExtensionRegistry::ENABLED) != nullptr; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::EqualsASCII(platform, kPlatformPlay)) { ArcAppListPrefs* arc_app_list_prefs = ArcAppListPrefs::Get(web_contents()->GetBrowserContext()); return arc_app_list_prefs && arc_app_list_prefs->GetPackage(id) != nullptr; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return false; }
diff --git a/chrome/browser/browser_features.cc b/chrome/browser/browser_features.cc index 8689377..b5b36ed 100644 --- a/chrome/browser/browser_features.cc +++ b/chrome/browser/browser_features.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/browser_features.h" +#include "build/chromeos_buildflags.h" + namespace features { // Enables using the ClosedTabCache to instantly restore recently closed tabs @@ -27,7 +29,7 @@ // chrome/browser/promo_browser_command/promo_browser_command.mojom const char kPromoBrowserCommandIdParam[] = "PromoBrowserCommandIdParam"; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Enables being able to zoom a web page by double tapping in Chrome OS tablet // mode. const base::Feature kDoubleTapToZoomInTabletMode{ @@ -57,11 +59,11 @@ base::FEATURE_DISABLED_BY_DEFAULT}; #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Enables taking snapshots of the user data directory after a major // milestone update and restoring them after a version rollback. const base::Feature kUserDataSnapshot{"UserDataSnapshot", base::FEATURE_ENABLED_BY_DEFAULT}; -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) } // namespace features
diff --git a/chrome/browser/browser_features.h b/chrome/browser/browser_features.h index 939e87f7..8b0118d 100644 --- a/chrome/browser/browser_features.h +++ b/chrome/browser/browser_features.h
@@ -10,6 +10,7 @@ #include "base/feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" namespace features { @@ -23,7 +24,7 @@ extern const base::Feature kPromoBrowserCommands; extern const char kPromoBrowserCommandIdParam[]; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) extern const base::Feature kDoubleTapToZoomInTabletMode; #endif @@ -37,7 +38,7 @@ extern const base::Feature kNewMacNotificationAPI; #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) extern const base::Feature kUserDataSnapshot; #endif
diff --git a/chrome/browser/browser_process.h b/chrome/browser/browser_process.h index 4adbeee..f04600e 100644 --- a/chrome/browser/browser_process.h +++ b/chrome/browser/browser_process.h
@@ -19,6 +19,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/buildflags.h" #include "media/media_buildflags.h" @@ -237,7 +238,9 @@ // before the full browser starts. virtual StartupData* startup_data() = 0; -#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) // This will start a timer that, if Chrome is in persistent mode, will check // whether an update is available, and if that's the case, restart the // browser. Note that restart code will strip some of the command line keys
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 2e76ca4..ba85a2d 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -34,6 +34,7 @@ #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/battery/battery_metrics.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chrome_browser_main.h" @@ -148,7 +149,7 @@ #include "chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.h" #endif -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/message_center/message_center.h" #endif @@ -190,7 +191,7 @@ #include "content/public/browser/plugin_service.h" #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/first_run/upgrade_util.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/ui/user_manager.h" @@ -201,7 +202,7 @@ #include "chrome/browser/error_reporting/chrome_js_error_report_processor.h" // nogncheck #endif -#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) // How often to check if the persistent instance of Chrome needs to restart // to install an update. static const int kUpdateCheckIntervalHours = 6; @@ -246,7 +247,7 @@ net::NetLog::Get()->InitializeSourceIdPartition(); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Forces creation of |metrics_services_manager_client_| if necessary // (typically this call is a no-op as MetricsServicesManager has already been // created). @@ -286,7 +287,7 @@ extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); #endif -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) message_center::MessageCenter::Initialize(); // Set the system notification source display name ("Google Chrome" or // "Chromium"). @@ -384,7 +385,7 @@ plugins_resource_service_.reset(); #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Initial cleanup for ChromeBrowserCloudManagement, shutdown components that // depend on profile and notification system. For example, ProfileManager // observer and KeyServices observer need to be removed before profiles. @@ -397,7 +398,7 @@ system_notification_helper_.reset(); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Need to clear the desktop notification balloons before the IO thread and // before the profiles, since if there are any still showing we will access // those things during teardown. @@ -414,11 +415,11 @@ { TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown:ProfileManager"); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // The desktop User Manager needs to be closed before the guest profile // can be destroyed. UserManager::Hide(); -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) // `profile_manager_` must be destroyed before `background_mode_manager_`, // because the background mode manager does not stop observing profile // changes at destruction (notifying the observers would cause a use-after- @@ -435,7 +436,7 @@ storage_monitor::StorageMonitor::Destroy(); #endif -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) if (message_center::MessageCenter::Get()) message_center::MessageCenter::Shutdown(); #endif @@ -598,7 +599,7 @@ metrics::MetricsService* metrics = g_browser_process->metrics_service(); if (metrics && local_state_) { metrics->RecordStartOfSessionEnd(); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // MetricsService lazily writes to prefs, force it to write now. // On ChromeOS, chrome gets killed when hangs, so no need to // commit metrics::prefs::kStabilitySessionEndCompleted change immediately. @@ -725,7 +726,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO(miguelg) return NULL for MAC as well once native notifications // are enabled by default. -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) return nullptr; #else if (!created_notification_ui_manager_) @@ -839,7 +840,7 @@ #endif const std::string& BrowserProcessImpl::GetApplicationLocale() { -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // TODO(crbug.com/1033644): Remove #if. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); #endif @@ -928,9 +929,9 @@ registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false); -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) registry->RegisterBooleanPref(prefs::kEulaAccepted, false); -#endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) // TODO(brettw,*): this comment about ResourceBundle was here since // initial commit. This comment seems unrelated, bit-rotten and @@ -940,11 +941,11 @@ // are registered. registry->RegisterStringPref(language::prefs::kApplicationLocale, std::string()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) registry->RegisterStringPref(prefs::kOwnerLocale, std::string()); registry->RegisterStringPref(prefs::kHardwareKeyboardLayout, std::string()); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) registry->RegisterBooleanPref(metrics::prefs::kMetricsReportingEnabled, GoogleUpdateSettings::GetCollectStatsConsent()); @@ -1020,7 +1021,9 @@ return startup_data_; } -#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) void BrowserProcessImpl::StartAutoupdateTimer() { autoupdate_timer_.Start(FROM_HERE, base::TimeDelta::FromHours(kUpdateCheckIntervalHours), @@ -1195,7 +1198,7 @@ void BrowserProcessImpl::CreateNotificationUIManager() { // Android and Chrome OS do not use the NotificationUIManager anymore. // All notification traffic is routed through NotificationPlatformBridge. -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) DCHECK(!notification_ui_manager_); notification_ui_manager_ = NotificationUIManager::Create(); created_notification_ui_manager_ = !!notification_ui_manager_; @@ -1385,7 +1388,9 @@ } // Mac is currently not supported. -#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) bool BrowserProcessImpl::IsRunningInBackground() const { // Check if browser is in the background. @@ -1454,5 +1459,5 @@ RestartBackgroundInstance(); } } - -#endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS))
diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index 7cfbdefc..a967b1e 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h
@@ -20,6 +20,7 @@ #include "base/sequence_checker.h" #include "base/timer/timer.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/common/buildflags.h" #include "components/keep_alive_registry/keep_alive_state_observer.h" @@ -179,7 +180,9 @@ StartupData* startup_data() override; -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) void StartAutoupdateTimer() override; #endif @@ -290,7 +293,7 @@ background_printing_manager_; #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Manager for desktop notification UI. bool created_notification_ui_manager_ = false; std::unique_ptr<NotificationUIManager> notification_ui_manager_; @@ -353,7 +356,9 @@ std::unique_ptr<BatteryMetrics> battery_metrics_; -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) base::RepeatingTimer autoupdate_timer_; // Gets called by autoupdate timer to see if browser needs restart and can be @@ -362,7 +367,8 @@ bool IsRunningInBackground() const; void OnPendingRestartResult(bool is_update_pending_restart); void RestartBackgroundInstance(); -#endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +#endif // defined(OS_WIN) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS)) // component updater is normally not used under ChromeOS due // to concerns over integrity of data shared between profiles,
diff --git a/chrome/browser/browser_process_platform_part.h b/chrome/browser/browser_process_platform_part.h index d6ff203..03738c9 100644 --- a/chrome/browser/browser_process_platform_part.h +++ b/chrome/browser/browser_process_platform_part.h
@@ -6,11 +6,12 @@ #define CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_H_ #include "build/build_config.h" +#include "build/chromeos_buildflags.h" // Include the appropriate BrowserProcessPlatformPart based on the platform. #if defined(OS_ANDROID) #include "chrome/browser/browser_process_platform_part_android.h" -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/browser_process_platform_part_chromeos.h" #elif defined(OS_MAC) #include "chrome/browser/browser_process_platform_part_mac.h"
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index b355156..4de4ad11 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -161,7 +161,7 @@ <!-- In-session login flow --> <include name="IDR_INLINE_LOGIN_HTML" file="resources\inline_login\inline_login.html" type="BINDATA" /> <include name="IDR_INLINE_LOGIN_APP_JS" file="${root_gen_dir}\chrome\browser\resources\inline_login\inline_login_app.js" use_base_dir="false" type ="BINDATA" preprocess="true" /> - <include name="IDR_INLINE_LOGIN_BROWSER_PROXY_JS" file="resources\inline_login\inline_login_browser_proxy.js" type ="BINDATA"/> + <include name="IDR_INLINE_LOGIN_BROWSER_PROXY_JS" file="resources\inline_login\inline_login_browser_proxy.js" type ="BINDATA" preprocess="true"/> </if> <if expr="chromeos">
diff --git a/chrome/browser/certificate_manager_model.cc b/chrome/browser/certificate_manager_model.cc index f2d7428..407b7ca 100644 --- a/chrome/browser/certificate_manager_model.cc +++ b/chrome/browser/certificate_manager_model.cc
@@ -15,6 +15,7 @@ #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/net/nss_context.h" #include "chrome/browser/ui/crypto_module_password_dialog_nss.h" #include "chrome/common/net/x509_certificate_model_nss.h" @@ -29,7 +30,7 @@ #include "net/cert/x509_util_nss.h" #include "ui/base/l10n/l10n_util.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" @@ -76,12 +77,12 @@ return org; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Log message for an operation that can not be performed on a certificate of a // given source. constexpr char kOperationNotPermitted[] = "Operation not permitted on a certificate. Source: "; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } // namespace @@ -268,7 +269,7 @@ DISALLOW_COPY_AND_ASSIGN(CertsSourcePlatformNSS); }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Provides certificates installed through enterprise policy. class CertsSourcePolicy : public CertificateManagerModel::CertsSource, chromeos::PolicyCertificateProvider::Observer { @@ -436,7 +437,7 @@ DISALLOW_COPY_AND_ASSIGN(CertsSourceExtensions); }; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } // namespace @@ -483,7 +484,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<Params> params = std::make_unique<Params>(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) policy::UserNetworkConfigurationUpdater* user_network_configuration_updater = policy::UserNetworkConfigurationUpdaterFactory::GetForBrowserContext( browser_context); @@ -521,7 +522,7 @@ base::RepeatingClosure certs_source_updated_callback = base::BindRepeating( &CertificateManagerModel::OnCertsSourceUpdated, base::Unretained(this)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Certificates installed and web trusted by enterprise policy is the highest // priority CertsSource. // UserNetworkConfigurationUpdater is only available for the primary user's @@ -537,7 +538,7 @@ certs_sources_.push_back(std::make_unique<CertsSourcePlatformNSS>( certs_source_updated_callback, nss_cert_database)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Certificates installed by enterprise policy without web trust are lower // priority than the main NSS DB based CertsSource. // Rationale: The user should be able to add trust to policy-provided @@ -695,7 +696,7 @@ bool is_user_db_available = !!cert_db->GetPublicSlot(); bool is_tpm_available = false; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) is_tpm_available = crypto::IsTPMTokenEnabledForNSS(); #endif content::GetUIThreadTaskRunner({})->PostTask(
diff --git a/chrome/browser/certificate_manager_model.h b/chrome/browser/certificate_manager_model.h index 66255aa..245af174 100644 --- a/chrome/browser/certificate_manager_model.h +++ b/chrome/browser/certificate_manager_model.h
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" +#include "build/chromeos_buildflags.h" #include "net/cert/nss_cert_database.h" #include "net/cert/scoped_nss_types.h" #include "net/ssl/client_cert_identity.h" @@ -22,7 +23,7 @@ class ResourceContext; } // namespace content -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) namespace chromeos { class CertificateProvider; class PolicyCertificateProvider; @@ -121,7 +122,7 @@ // Holds parameters during construction. struct Params { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // May be nullptr. chromeos::PolicyCertificateProvider* policy_certs_provider = nullptr; // May be nullptr.
diff --git a/chrome/browser/certificate_manager_model_unittest.cc b/chrome/browser/certificate_manager_model_unittest.cc index cfa0b351..7109760 100644 --- a/chrome/browser/certificate_manager_model_unittest.cc +++ b/chrome/browser/certificate_manager_model_unittest.cc
@@ -7,6 +7,7 @@ #include "base/observer_list.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "build/chromeos_buildflags.h" #include "content/public/test/browser_task_environment.h" #include "crypto/scoped_test_nss_db.h" #include "net/cert/nss_cert_database.h" @@ -18,7 +19,7 @@ #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h" #include "chromeos/network/onc/certificate_scope.h" #include "chromeos/network/policy_certificate_provider.h" @@ -196,7 +197,7 @@ EXPECT_FALSE(platform_cert_info->hardware_backed()); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) namespace { class FakePolicyCertificateProvider @@ -660,4 +661,4 @@ } } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/chrome_back_forward_cache_browsertest.cc b/chrome/browser/chrome_back_forward_cache_browsertest.cc index 0853c0b..e06327e 100644 --- a/chrome/browser/chrome_back_forward_cache_browsertest.cc +++ b/chrome/browser/chrome_back_forward_cache_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/mixed_content_settings_tab_helper.h" #include "chrome/browser/permissions/permission_manager_factory.h" @@ -47,7 +48,7 @@ adapter_ = base::MakeRefCounted<testing::NiceMock<device::MockBluetoothAdapter>>(); device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // In CHROMEOS build, even when |adapter_| object is released at TearDown() // it causes the test to fail on exit with an error indicating |adapter_| is // leaked.
diff --git a/chrome/browser/chrome_browser_field_trials.cc b/chrome/browser/chrome_browser_field_trials.cc index 2d6772e0..84f2551e 100644 --- a/chrome/browser/chrome_browser_field_trials.cc +++ b/chrome/browser/chrome_browser_field_trials.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_util.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/metrics/chrome_metrics_service_client.h" #include "chrome/browser/metrics/chrome_metrics_services_manager_client.h" @@ -35,7 +36,7 @@ #include "chrome/browser/chrome_browser_field_trials_desktop.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/first_run/help_app_first_run_field_trial.h" #include "chrome/browser/chromeos/sync/split_settings_sync_field_trial.h" #include "chromeos/services/multidevice_setup/public/cpp/first_run_field_trial.h" @@ -92,11 +93,11 @@ if (!has_seed) { CreateFallbackSamplingTrialIfNeeded(feature_list); CreateFallbackUkmSamplingTrialIfNeeded(feature_list); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) chromeos::multidevice_setup::CreateFirstRunFieldTrial(feature_list); #endif } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // These trials are fully client controlled and must be configured whether or // not a seed is available. split_settings_sync_field_trial::Create(feature_list, local_state_);
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index d1e267b..10c7ca6 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -8,6 +8,7 @@ #include "base/feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/accessibility/accessibility_labels_service.h" #include "chrome/browser/accessibility/accessibility_labels_service_factory.h" #include "chrome/browser/buildflags.h" @@ -143,13 +144,13 @@ #include "chrome/browser/ui/webui/discards/site_data.mojom.h" #endif -#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID) #include "chrome/browser/ui/webui/signin/profile_customization_ui.h" #include "chrome/browser/ui/webui/signin/profile_picker_ui.h" #include "ui/webui/resources/cr_components/customize_themes/customize_themes.mojom.h" -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/apps/digital_goods/digital_goods_factory_impl.h" #include "chrome/browser/nearby_sharing/common/nearby_share_features.h" #include "chrome/browser/ui/webui/app_management/app_management.mojom.h" @@ -201,14 +202,14 @@ #include "third_party/blink/public/mojom/digital_goods/digital_goods.mojom.h" #endif -#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_ANDROID) -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) +#if defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/webshare/share_service_impl.h" #endif #include "third_party/blink/public/mojom/webshare/webshare.mojom.h" #endif -#if defined(OS_CHROMEOS) && !defined(OFFICIAL_BUILD) +#if BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OFFICIAL_BUILD) #include "chromeos/components/file_manager/file_manager_ui.h" #include "chromeos/components/file_manager/mojom/file_manager.mojom.h" #include "chromeos/components/telemetry_extension_ui/mojom/diagnostics_service.mojom.h" // nogncheck crbug.com/1125897 @@ -563,12 +564,12 @@ base::BindRepeating(&payments::CreatePaymentCredential)); #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) map->Add<payments::mojom::DigitalGoodsFactory>(base::BindRepeating( &apps::DigitalGoodsFactoryImpl::BindDigitalGoodsFactory)); #endif -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) if (base::FeatureList::IsEnabled(features::kWebShare)) { map->Add<blink::mojom::ShareService>( base::BindRepeating(&ShareServiceImpl::Create)); @@ -643,10 +644,10 @@ RegisterWebUIControllerInterfaceBinder< customize_themes::mojom::CustomizeThemesHandlerFactory, NewTabPageUI -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) , ProfileCustomizationUI, ProfilePickerUI, settings::SettingsUI -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) >(map); #if !defined(OFFICIAL_BUILD) @@ -675,7 +676,7 @@ ::mojom::web_app_internals::WebAppInternalsPageHandler, InternalsUI>(map); #endif // defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) RegisterWebUIControllerInterfaceBinder< add_supervision::mojom::AddSupervisionHandler, chromeos::AddSupervisionUI>(map); @@ -766,9 +767,9 @@ RegisterWebUIControllerInterfaceBinder<chromeos::scanning::mojom::ScanService, chromeos::ScanningUI>(map); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_CHROMEOS) && !defined(OFFICIAL_BUILD) +#if BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OFFICIAL_BUILD) RegisterWebUIControllerInterfaceBinder< chromeos::file_manager::mojom::PageHandlerFactory, chromeos::file_manager::FileManagerUI>(map); @@ -816,7 +817,7 @@ map); #endif // !defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::FeatureList::IsEnabled(features::kNearbySharing)) { RegisterWebUIControllerInterfaceBinder< nearby_share::mojom::NearbyShareSettings, @@ -833,7 +834,7 @@ chromeos::settings::OSSettingsUI>( map); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } } // namespace internal
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index 8831c0f4..f9562eb 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -194,23 +194,25 @@ #include "ui/base/l10n/l10n_util.h" #endif // defined(OS_ANDROID) -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/first_run/upgrade_util.h" #include "components/enterprise/browser/controller/chrome_browser_cloud_management_controller.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/stats_reporting_controller.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/settings/cros_settings_names.h" #include "components/arc/metrics/stability_metrics_manager.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/first_run/upgrade_util_linux.h" -#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) +#endif // defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #if defined(OS_LINUX) || defined(OS_CHROMEOS) #include "components/crash/core/app/breakpad_linux.h" @@ -245,8 +247,10 @@ #include "ui/shell_dialogs/select_file_dialog.h" #endif // defined(OS_WIN) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. #if defined(OS_WIN) || defined(OS_MAC) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS)) + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h" #include "chrome/browser/metrics/desktop_session_duration/touch_mode_stats_tracker.h" #include "chrome/browser/profiles/profile_activity_metrics_recorder.h" @@ -285,7 +289,7 @@ #include "printing/backend/win_helper.h" #endif -#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h" #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h" #endif @@ -295,7 +299,7 @@ #include "components/rlz/rlz_tracker.h" // nogncheck crbug.com/1125897 #endif // BUILDFLAG(ENABLE_RLZ) -#if BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_LACROS) #include "ui/shell_dialogs/select_file_dialog_lacros.h" #endif @@ -326,7 +330,7 @@ } } -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator, const std::vector<GURL>& new_tabs) { for (auto it = new_tabs.begin(); it != new_tabs.end(); ++it) { @@ -334,7 +338,7 @@ browser_creator->AddFirstRunTab(*it); } } -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Initializes the primary profile, possibly doing some user prompting to pick // a fallback profile. Returns the newly created profile, or NULL if startup @@ -380,7 +384,7 @@ } Profile* profile = nullptr; -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) // On ChromeOS and Android the ProfileManager will use the same path as the // one we got passed. CreateInitialProfile will therefore use the correct path // automatically. @@ -410,7 +414,7 @@ "Error creating primary profile."); return nullptr; } -#endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) UMA_HISTOGRAM_LONG_TIMES( "Startup.CreateFirstProfile", base::Time::Now() - start); @@ -756,7 +760,7 @@ #if !defined(OS_ANDROID) DCHECK(browser_creator_.get()); #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) DCHECK(master_prefs_.get()); #endif @@ -814,7 +818,7 @@ int ChromeBrowserMainParts::ApplyFirstRunPrefs() { // Android does first run in Java instead of native. // Chrome OS has its own out-of-box-experience code. -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) master_prefs_ = std::make_unique<first_run::MasterPrefs>(); std::unique_ptr<installer::InitialPreferences> installer_initial_prefs = @@ -845,7 +849,7 @@ master_prefs_->suppress_default_browser_prompt_for_version); } -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) return content::RESULT_CODE_NORMAL_EXIT; } @@ -880,11 +884,11 @@ PrefService* local_state = browser_process_->local_state(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) chromeos::CrosSettings::Initialize(local_state); chromeos::StatsReportingController::Initialize(local_state); arc::StabilityMetricsManager::Initialize(local_state); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) { TRACE_EVENT0( @@ -921,7 +925,7 @@ // Android does first run in Java instead of native. // Chrome OS has its own out-of-box-experience code. -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) if (first_run::IsChromeFirstRun()) { if (!parsed_command_line().HasSwitch(switches::kApp) && !parsed_command_line().HasSwitch(switches::kAppId)) { @@ -939,7 +943,7 @@ base::CreateDirectory(user_native_messaging_dir); #endif // defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS) } -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_OPENBSD) // Set the product channel for crash reports. @@ -958,8 +962,10 @@ SecKeychainAddCallback(&KeychainCallback, 0, nullptr); #endif // defined(OS_MAC) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. #if defined(OS_WIN) || defined(OS_MAC) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS)) + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) metrics::DesktopSessionDurationTracker::Initialize(); ProfileActivityMetricsRecorder::Initialize(); TouchModeStatsTracker::Initialize( @@ -1187,7 +1193,7 @@ } ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory()); -#elif BUILDFLAG(IS_LACROS) +#elif BUILDFLAG(IS_CHROMEOS_LACROS) ui::SelectFileDialog::SetFactory(new ui::SelectFileDialogLacros::Factory()); #endif // defined(OS_WIN) @@ -1271,7 +1277,7 @@ downgrade_manager_.UpdateLastVersion(user_data_dir_); #endif -#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID) // Initialize the chrome browser cloud management controller controller after // the browser process singleton is acquired to remove race conditions where // multiple browser processes start simultaneously. The main @@ -1434,7 +1440,7 @@ // (requires supporting early exit). PostProfileInit(); -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Execute first run specific code after the PrefService has been initialized // and preferences have been registered since some of the import code depends // on preferences. @@ -1450,7 +1456,7 @@ if (browser_shutdown::IsTryingToQuit()) return content::RESULT_CODE_NORMAL_EXIT; } -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) // Sets things up so that if we crash from this point on, a dialog will @@ -1479,7 +1485,7 @@ } #endif // defined(OS_WIN) -#if BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_RLZ) && !BUILDFLAG(IS_CHROMEOS_ASH) // Init the RLZ library. This just binds the dll and schedules a task on the // file thread to be run sometime later. If this is the first run we record // the installation event. @@ -1495,7 +1501,7 @@ ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_), ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_), ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_)); -#endif // BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS) +#endif // BUILDFLAG(ENABLE_RLZ) && !BUILDFLAG(IS_CHROMEOS_ASH) // Configure modules that need access to resources. net::NetModule::SetResourceProvider(ChromeNetResourceProvider); @@ -1538,10 +1544,10 @@ language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage( browser_process_->GetApplicationLocale()); // On ChromeOS results in a crash. https://crbug.com/1151558 -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) language_usage_metrics::LanguageUsageMetrics::RecordPageLanguages( *UrlLanguageHistogramFactory::GetForBrowserContext(profile_)); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // On mobile, need for clean shutdown arises only when the application comes // to foreground (i.e. MetricsService::OnAppEnterForeground is called). @@ -1551,7 +1557,7 @@ browser_process_->metrics_service()->LogNeedForCleanShutdown(); #endif // !defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !BUILDFLAG(IS_CHROMEOS_ASH) // Create the instance of the cloud print proxy service so that it can launch // the service process if needed. This is needed because the service process // might have shutdown because an update was available. @@ -1612,7 +1618,7 @@ // We are in regular browser boot sequence. Open initial tabs and enter the // main message loop. std::vector<Profile*> last_opened_profiles; -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // On ChromeOS multiple profiles doesn't apply, and will break if we load // them this early as the cryptohome hasn't yet been mounted (which happens // only once we log in). And if we're launching a web app, we don't want to @@ -1621,7 +1627,7 @@ last_opened_profiles = g_browser_process->profile_manager()->GetLastOpenedProfiles(); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // This step is costly and is already measured in // Startup.StartupBrowserCreator_Start. @@ -1631,21 +1637,26 @@ browser_creator_->Start(parsed_command_line(), base::FilePath(), profile_, last_opened_profiles); if (started) { -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) // Initialize autoupdate timer. Timer callback costs basically nothing // when browser is not in persistent mode, so it's OK to let it ride on // the main thread. This needs to be done here because we don't want // to start the timer when Chrome is run inside a test harness. browser_process_->StartAutoupdateTimer(); -#endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +#endif // defined(OS_WIN) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS)) -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // On Linux, the running exe will be updated if an upgrade becomes // available while the browser is running. We need to save the last // modified time of the exe, so we can compare to determine if there is // an upgrade while the browser is kept alive by a persistent extension. upgrade_util::SaveLastModifiedTimeOfExe(); -#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) +#endif // defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // Record now as the last successful chrome start. if (ShouldRecordActiveUse(parsed_command_line())) @@ -1800,9 +1811,9 @@ browser_shutdown::ShutdownPostThreadsStop(restart_mode); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) master_prefs_.reset(); -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) process_singleton_.reset(); device_event_log::Shutdown(); @@ -1814,11 +1825,11 @@ // paths from content/browser/browser_main. CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) arc::StabilityMetricsManager::Shutdown(); chromeos::StatsReportingController::Shutdown(); chromeos::CrosSettings::Shutdown(); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #endif // defined(OS_ANDROID) }
diff --git a/chrome/browser/chrome_browser_main.h b/chrome/browser/chrome_browser_main.h index 294caf8..cc214ddc 100644 --- a/chrome/browser/chrome_browser_main.h +++ b/chrome/browser/chrome_browser_main.h
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_process_singleton.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/process_singleton.h" @@ -192,7 +193,7 @@ downgrade::DowngradeManager downgrade_manager_; #endif -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // Android's first run is done in Java instead of native. Chrome OS does not // use master preferences. std::unique_ptr<first_run::MasterPrefs> master_prefs_;
diff --git a/chrome/browser/chrome_browser_main_linux.cc b/chrome/browser/chrome_browser_main_linux.cc index f6ce26c7..441a46a 100644 --- a/chrome/browser/chrome_browser_main_linux.cc +++ b/chrome/browser/chrome_browser_main_linux.cc
@@ -13,6 +13,7 @@ #include "base/single_thread_task_runner.h" #include "base/task/thread_pool.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/grit/chromium_strings.h" #include "components/crash/core/app/breakpad_linux.h" @@ -24,7 +25,7 @@ #include "media/audio/audio_manager.h" #include "ui/base/l10n/l10n_util.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/installer/util/google_update_settings.h" #else #include "base/command_line.h" @@ -45,7 +46,7 @@ } void ChromeBrowserMainPartsLinux::PreProfileInit() { -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Needs to be called after we have chrome::DIR_USER_DATA and // g_browser_process. This happens in PreCreateThreads. // base::GetLinuxDistro() will initialize its value if needed. @@ -57,7 +58,7 @@ media::AudioManager::SetGlobalAppName( l10n_util::GetStringUTF8(IDS_SHORT_PRODUCT_NAME)); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Set up crypt config. This should be kept in sync with the OSCrypt parts of // SystemNetworkContextManager::OnNetworkServiceCreated. std::unique_ptr<os_crypt::Config> config(new os_crypt::Config()); @@ -88,7 +89,7 @@ // true all the time isn't useful, we overload the meaning of the breakpad // registration metric to mean "is crash reporting enabled", since that's // what breakpad registration effectively meant in the days before crashpad. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) breakpad_registered = GoogleUpdateSettings::GetCollectStatsConsent(); #else breakpad_registered = crash_reporter::GetUploadsEnabled(); @@ -101,7 +102,7 @@ } void ChromeBrowserMainPartsLinux::PostMainMessageLoopStart() { -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) bluez::BluezDBusManager::Initialize(nullptr /* system_bus */); #endif @@ -109,7 +110,7 @@ } void ChromeBrowserMainPartsLinux::PostDestroyThreads() { -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) bluez::BluezDBusManager::Shutdown(); bluez::BluezDBusThreadManager::Shutdown(); #endif
diff --git a/chrome/browser/chrome_browser_main_parts_lacros.cc b/chrome/browser/chrome_browser_main_parts_lacros.cc index 691bc72..529a709 100644 --- a/chrome/browser/chrome_browser_main_parts_lacros.cc +++ b/chrome/browser/chrome_browser_main_parts_lacros.cc
@@ -6,6 +6,7 @@ #include "base/check.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/lacros/metrics_reporting_observer.h" #include "content/public/common/result_codes.h" ChromeBrowserMainPartsLacros::ChromeBrowserMainPartsLacros( @@ -20,9 +21,12 @@ if (result != content::RESULT_CODE_NORMAL_EXIT) return result; + // The observer sets the initial metrics consent state, then observes ash + // for updates. Create it here because local state is required to check for + // policy overrides. DCHECK(g_browser_process->local_state()); - // TODO(https://crbug.com/1148604): Inherit metrics consent from ash. Do it - // here because local state is required to check for policy overrides. + metrics_reporting_observer_ = std::make_unique<MetricsReportingObserver>(); + metrics_reporting_observer_->Init(); return content::RESULT_CODE_NORMAL_EXIT; }
diff --git a/chrome/browser/chrome_browser_main_parts_lacros.h b/chrome/browser/chrome_browser_main_parts_lacros.h index 23958edc9..8e3f9135 100644 --- a/chrome/browser/chrome_browser_main_parts_lacros.h +++ b/chrome/browser/chrome_browser_main_parts_lacros.h
@@ -5,8 +5,12 @@ #ifndef CHROME_BROWSER_CHROME_BROWSER_MAIN_PARTS_LACROS_H_ #define CHROME_BROWSER_CHROME_BROWSER_MAIN_PARTS_LACROS_H_ +#include <memory> + #include "chrome/browser/chrome_browser_main_linux.h" +class MetricsReportingObserver; + // Startup and shutdown code for Lacros. See ChromeBrowserMainParts for details. class ChromeBrowserMainPartsLacros : public ChromeBrowserMainPartsLinux { public: @@ -19,6 +23,9 @@ // ChromeBrowserMainParts: int PreEarlyInitialization() override; + + private: + std::unique_ptr<MetricsReportingObserver> metrics_reporting_observer_; }; #endif // CHROME_BROWSER_CHROME_BROWSER_MAIN_PARTS_LACROS_H_
diff --git a/chrome/browser/chrome_browser_main_posix.cc b/chrome/browser/chrome_browser_main_posix.cc index 25741e2d..315d460 100644 --- a/chrome/browser/chrome_browser_main_posix.cc +++ b/chrome/browser/chrome_browser_main_posix.cc
@@ -18,6 +18,7 @@ #include "base/macros.h" #include "base/notreached.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/app/shutdown_signal_handlers_posix.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/sessions/session_restore.h" @@ -69,7 +70,9 @@ // ExitHandler takes care of deleting itself. new ExitHandler(); } else { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) switch (signal) { case SIGINT: case SIGHUP: @@ -120,7 +123,7 @@ // static void ExitHandler::Exit() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // On ChromeOS, exiting on signal should be always clean. chrome::ExitIgnoreUnloadHandlers(); #else @@ -162,7 +165,7 @@ } void ChromeBrowserMainPartsPosix::ShowMissingLocaleMessageBox() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) NOTREACHED(); // Should not ever happen on ChromeOS. #elif defined(OS_MAC) // Not called on Mac because we load the locale files differently.
diff --git a/chrome/browser/chrome_browser_main_win.cc b/chrome/browser/chrome_browser_main_win.cc index 3c3c539..8f82872 100644 --- a/chrome/browser/chrome_browser_main_win.cc +++ b/chrome/browser/chrome_browser_main_win.cc
@@ -60,6 +60,7 @@ #include "chrome/browser/web_applications/chrome_pwa_launcher/launcher_update.h" #include "chrome/browser/web_applications/components/web_app_handler_registration_utils_win.h" #include "chrome/browser/web_applications/components/web_app_shortcut.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/win/browser_util.h" #include "chrome/browser/win/chrome_elf_init.h" #include "chrome/browser/win/conflicts/enumerate_input_method_editors.h" @@ -96,7 +97,6 @@ #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" -#include "extensions/browser/extension_registry.h" #include "ui/base/cursor/cursor_loader_win.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_win.h" @@ -467,20 +467,20 @@ // The profile was unloaded. return; } + auto* provider = web_app::WebAppProvider::Get(profile); + if (!provider) + return; + web_app::AppRegistrar& registrar = provider->registrar(); // Create a vector of all PWA-launcher paths in |profile_dir|. std::vector<base::FilePath> pwa_launcher_paths; - for (const auto& extension : - extensions::ExtensionRegistry::Get(profile)->enabled_extensions()) { - if (extension->from_bookmark()) { - base::FilePath web_app_path = - web_app::GetOsIntegrationResourcesDirectoryForApp( - profile_dir, extension->id(), GURL()); - web_app_path = - web_app_path.Append(web_app::GetAppSpecificLauncherFilename( - base::UTF8ToUTF16(extension->name()))); - pwa_launcher_paths.push_back(std::move(web_app_path)); - } + for (const web_app::AppId& app_id : registrar.GetAppIds()) { + base::FilePath web_app_path = + web_app::GetOsIntegrationResourcesDirectoryForApp(profile_dir, app_id, + GURL()); + web_app_path = web_app_path.Append(web_app::GetAppSpecificLauncherFilename( + base::UTF8ToUTF16(registrar.GetAppShortName(app_id)))); + pwa_launcher_paths.push_back(std::move(web_app_path)); } base::ThreadPool::PostTask(
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 59e5175..3b0478f 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -397,7 +397,7 @@ #include "components/soda/constants.h" #include "sandbox/mac/seatbelt_exec.h" #include "sandbox/policy/mac/sandbox_mac.h" -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/tablet_mode.h" #include "chrome/app/chrome_crash_reporter_client.h" @@ -435,7 +435,7 @@ #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "services/service_manager/public/mojom/interface_provider_spec.mojom.h" -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/chrome_browser_main_linux.h" #elif defined(OS_ANDROID) #include "base/android/application_status_listener.h" @@ -468,9 +468,9 @@ #include "chrome/browser/chrome_browser_main_posix.h" #endif -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/accessibility/accessibility_features.h" -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) #if !defined(OS_ANDROID) #include "chrome/browser/badging/badge_manager.h" @@ -492,8 +492,10 @@ #include "chrome/grit/chrome_unscaled_resources.h" // nogncheck crbug.com/1125897 #endif // !defined(OS_ANDROID) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. #if defined(OS_WIN) || defined(OS_MAC) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS)) + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "chrome/browser/browser_switcher/browser_switcher_navigation_throttle.h" #endif @@ -513,7 +515,7 @@ // TODO(crbug.com/939205): Once the upcoming App Service is available, use a // single navigation throttle to display the intent picker on all platforms. #if !defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.h" #include "chrome/browser/chromeos/apps/intent_helper/common_apps_navigation_throttle.h" #else @@ -525,7 +527,9 @@ #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h" #endif -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.h" #endif @@ -593,11 +597,11 @@ #include "chrome/browser/supervised_user/supervised_user_google_auth_navigation_throttle.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/app_mode/kiosk_settings_navigation_throttle.h" #include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_navigation_throttle.h" #include "chrome/browser/speech/tts_controller_delegate_impl.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_MEDIA_REMOTING) #include "chrome/browser/media/cast_remoting_connector.h" @@ -650,7 +654,7 @@ #include "chrome/browser/vr/chrome_xr_integration_client.h" #endif -#if BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/chrome_browser_main_parts_lacros.h" #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_lacros.h" #include "chromeos/lacros/lacros_chrome_service_impl.h" @@ -1298,9 +1302,9 @@ extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart); #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) extra_parts_.push_back(new ChromeContentBrowserClientChromeOsPart); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) extra_parts_.push_back(new ChromeContentBrowserClientTabStripPart); @@ -1386,7 +1390,7 @@ #elif BUILDFLAG(IS_CHROMEOS_LACROS) main_parts = std::make_unique<ChromeBrowserMainPartsLacros>(parameters, &startup_data_); -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) main_parts = std::make_unique<ChromeBrowserMainPartsLinux>(parameters, &startup_data_); #elif defined(OS_ANDROID) @@ -1412,10 +1416,12 @@ // Construct additional browser parts. Stages are called in the order in // which they are added. #if defined(TOOLKIT_VIEWS) -#if BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_LACROS) main_parts->AddParts( std::make_unique<ChromeBrowserMainExtraPartsViewsLacros>()); -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) main_parts->AddParts( std::make_unique<ChromeBrowserMainExtraPartsViewsLinux>()); #else @@ -1423,7 +1429,7 @@ #endif #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // TODO(jamescook): Combine with ChromeBrowserMainPartsChromeos. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsAsh>()); #endif @@ -1642,7 +1648,7 @@ bool ChromeContentBrowserClient::ShouldUseMobileFlingCurve() { #if defined(OS_ANDROID) return true; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) return ash::TabletMode::Get() && ash::TabletMode::Get()->InTabletMode(); #else return false; @@ -2231,7 +2237,7 @@ kDinosaurEasterEggSwitches, base::size(kDinosaurEasterEggSwitches)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS need to pass primary user homedir (in multi-profiles session). base::FilePath homedir; base::PathService::Get(base::DIR_HOME, &homedir); @@ -2250,7 +2256,7 @@ process, profile); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const std::string& login_profile = browser_command_line.GetSwitchValueASCII( chromeos::switches::kLoginProfile); if (!login_profile.empty()) @@ -2373,7 +2379,7 @@ static const char* const kSwitchNames[] = { autofill::switches::kIgnoreAutocompleteOffForAutofill, autofill::switches::kShowAutofillSignatures, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) switches::kShortMergeSessionTimeoutForTest, // For tests only. #endif #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -2398,7 +2404,7 @@ switches::kEnableNaClNonSfiMode, #endif switches::kEnableNetBenchmarking, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) switches::kForceAppMode, #endif #if BUILDFLAG(ENABLE_NACL) @@ -2451,7 +2457,7 @@ command_line->AppendSwitch(switches::kDisableBreakpad); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (ChromeCrashReporterClient::ShouldPassCrashLoopBefore(process_type)) { static const char* const kSwitchNames[] = { crash_reporter::switches::kCrashLoopBefore, @@ -2769,7 +2775,7 @@ return !cookie_settings->ShouldBlockThirdPartyCookies(); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) void ChromeContentBrowserClient::OnTrustAnchorUsed( content::BrowserContext* browser_context) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); @@ -3036,7 +3042,7 @@ Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (chromeos::ProfileHelper::IsSigninProfile(profile)) { // On the sign-in profile, never show certificate selection to the user. A // client certificate is an identifier that can be stable for a long time, @@ -3064,7 +3070,7 @@ } VLOG(1) << "Client cert requested in sign-in profile."; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<net::ClientCertIdentity> auto_selected_identity = AutoSelectCertificate(profile, requesting_url, client_certs); @@ -3209,7 +3215,7 @@ return new speech::ChromeSpeechRecognitionManagerDelegate(); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) content::TtsControllerDelegate* ChromeContentBrowserClient::GetTtsControllerDelegate() { return TtsControllerDelegateImpl::GetInstance(); @@ -3221,7 +3227,7 @@ content::TtsController::GetInstance()->SetTtsEngineDelegate( TtsExtensionEngine::GetInstance()); #endif -#ifdef OS_CHROMEOS +#if BUILDFLAG(IS_CHROMEOS_ASH) return TtsPlatformImplChromeOs::GetInstance(); #else return nullptr; @@ -3303,7 +3309,7 @@ web_prefs->force_dark_mode_enabled = prefs->GetBoolean(prefs::kWebKitForceDarkModeEnabled); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) web_prefs->always_show_focus = prefs->GetBoolean(ash::prefs::kAccessibilityFocusHighlightEnabled); #else @@ -3710,7 +3716,7 @@ const base::FilePath& storage_partition_path, std::vector<std::unique_ptr<storage::FileSystemBackend>>* additional_backends) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) storage::ExternalMountPoints* external_mount_points = content::BrowserContext::GetMountPoints(browser_context); DCHECK(external_mount_points); @@ -3919,11 +3925,11 @@ page_load_metrics::MetricsNavigationThrottle::Create(handle)); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) MaybeAddThrottle( chromeos::WebTimeLimitNavigationThrottle::MaybeCreateThrottleFor(handle), &throttles); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_SUPERVISED_USERS) MaybeAddThrottle( @@ -3961,7 +3967,7 @@ } #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Check if we need to add merge session throttle. This throttle will postpone // loading of main frames. if (handle->IsInMainFrame()) { @@ -3978,7 +3984,7 @@ #if !defined(OS_ANDROID) auto url_to_apps_throttle = -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::FeatureList::IsEnabled(features::kAppServiceIntentHandling) ? apps::CommonAppsNavigationThrottle::MaybeCreate(handle) : chromeos::ChromeOsAppsNavigationThrottle::MaybeCreate(handle); @@ -4069,14 +4075,16 @@ handle)); } +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. #if defined(OS_WIN) || defined(OS_MAC) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS)) + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) MaybeAddThrottle(browser_switcher::BrowserSwitcherNavigationThrottle:: MaybeCreateThrottleFor(handle), &throttles); #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) MaybeAddThrottle( chromeos::KioskSettingsNavigationThrottle::MaybeCreateThrottleFor(handle), &throttles); @@ -4458,7 +4466,7 @@ int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { -#if BUILDFLAG(ENABLE_EXTENSIONS) || defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_EXTENSIONS) || BUILDFLAG(IS_CHROMEOS_ASH) content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -4468,14 +4476,14 @@ web_contents->GetBrowserContext(), ukm_source_id, !!extensions::WebViewGuest::FromWebContents(web_contents))); #endif // BUILDFLAG(ENABLE_EXTENSIONS) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); factories->emplace(content::kExternalFileScheme, chromeos::ExternalFileURLLoaderFactory::Create( profile, content::ChildProcessHost::kInvalidUniqueID)); -#endif // defined(OS_CHROMEOS) -#endif // BUILDFLAG(ENABLE_EXTENSIONS) || defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#endif // BUILDFLAG(ENABLE_EXTENSIONS) || BUILDFLAG(IS_CHROMEOS_ASH) } void ChromeContentBrowserClient:: @@ -4568,7 +4576,7 @@ DISALLOW_COPY_AND_ASSIGN(SpecialAccessFileURLLoaderFactory); }; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool IsSystemFeatureDisabled(policy::SystemFeature system_feature) { PrefService* const local_state = g_browser_process->local_state(); if (!local_state) // Sometimes it's not available in tests. @@ -4616,13 +4624,13 @@ int render_process_id, int render_frame_id, NonNetworkURLLoaderFactoryMap* factories) { -#if defined(OS_CHROMEOS) || BUILDFLAG(ENABLE_EXTENSIONS) +#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(ENABLE_EXTENSIONS) content::RenderFrameHost* frame_host = RenderFrameHost::FromID(render_process_id, render_frame_id); WebContents* web_contents = WebContents::FromRenderFrameHost(frame_host); -#endif // defined(OS_CHROMEOS) || BUILDFLAG(ENABLE_EXTENSIONS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(ENABLE_EXTENSIONS) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (web_contents) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); @@ -4630,7 +4638,7 @@ chromeos::ExternalFileURLLoaderFactory::Create( profile, render_process_id)); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_EXTENSIONS) factories->emplace(extensions::kExtensionScheme, @@ -5132,7 +5140,7 @@ return false; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Special case : in ChromeOS in Guest mode bookmarks and history are // disabled for security reasons. New tab page explains the reasons, so // we redirect user to new tab page. @@ -5834,7 +5842,7 @@ void ChromeContentBrowserClient::BindBrowserControlInterface( mojo::ScopedMessagePipeHandle pipe) { -#if BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_LACROS) chromeos::LacrosChromeServiceImpl::Get()->BindReceiver( mojo::PendingReceiver<crosapi::mojom::LacrosChromeService>( std::move(pipe)));
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index 59479aa..10a0497f 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -20,6 +20,7 @@ #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/startup_data.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/web_contents.h" @@ -288,7 +289,7 @@ std::string GetWebBluetoothBlocklist() override; bool AllowConversionMeasurement( content::BrowserContext* browser_context) override; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) void OnTrustAnchorUsed(content::BrowserContext* browser_context) override; #endif scoped_refptr<network::SharedURLLoaderFactory> @@ -339,7 +340,7 @@ bool* no_javascript_access) override; content::SpeechRecognitionManagerDelegate* CreateSpeechRecognitionManagerDelegate() override; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) content::TtsControllerDelegate* GetTtsControllerDelegate() override; #endif content::TtsPlatform* GetTtsPlatform() override;
diff --git a/chrome/browser/chrome_content_browser_client_browsertest.cc b/chrome/browser/chrome_content_browser_client_browsertest.cc index 0df6591..90a71a2b 100644 --- a/chrome/browser/chrome_content_browser_client_browsertest.cc +++ b/chrome/browser/chrome_content_browser_client_browsertest.cc
@@ -15,6 +15,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/profiles/profile.h" @@ -482,7 +483,7 @@ EXPECT_EQ(base::ASCIIToUTF16("about:blank"), tab_title); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Tests that if a protocol handler is registered for a scheme, an external // program (another Chrome tab in this case) is not launched to handle the // navigation. This is a regression test for crbug.com/963133.
diff --git a/chrome/browser/chrome_content_browser_client_receiver_bindings.cc b/chrome/browser/chrome_content_browser_client_receiver_bindings.cc index ab5fda63..272ab252 100644 --- a/chrome/browser/chrome_content_browser_client_receiver_bindings.cc +++ b/chrome/browser/chrome_content_browser_client_receiver_bindings.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/badging/badge_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/cache_stats_recorder.h" @@ -42,7 +43,7 @@ #elif defined(OS_WIN) #include "chrome/browser/win/conflicts/module_database.h" #include "chrome/browser/win/conflicts/module_event_sink_impl.h" -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h" #include "chromeos/components/cdm_factory_daemon/cdm_factory_daemon_proxy.h" #include "components/performance_manager/public/performance_manager.h" @@ -183,7 +184,7 @@ content::GetUIThreadTaskRunner({})); #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (performance_manager::mechanism::userspace_swap:: UserspaceSwapInitializationImpl::UserspaceSwapSupportedAndEnabled()) { registry->AddInterface( @@ -294,10 +295,10 @@ return; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (auto r = receiver.As<chromeos::cdm::mojom::CdmFactoryDaemon>()) chromeos::CdmFactoryDaemonProxy::Create(std::move(r)); -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } void ChromeContentBrowserClient::BindUtilityHostReceiver(
diff --git a/chrome/browser/chrome_content_browser_client_unittest.cc b/chrome/browser/chrome_content_browser_client_unittest.cc index 71603361..c8c19ab 100644 --- a/chrome/browser/chrome_content_browser_client_unittest.cc +++ b/chrome/browser/chrome_content_browser_client_unittest.cc
@@ -21,6 +21,7 @@ #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include "chrome/browser/captive_portal/captive_portal_service_factory.h" #include "chrome/browser/search_engines/template_url_service_factory.h" @@ -71,7 +72,7 @@ #include "components/captive_portal/content/captive_portal_tab_helper.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/test/scoped_feature_list.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/policy/policy_cert_service.h" @@ -83,7 +84,7 @@ #include "chromeos/constants/chromeos_features.h" #include "components/policy/core/common/policy_pref_names.h" #include "components/user_manager/scoped_user_manager.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) using content::BrowsingDataFilterBuilder; using testing::_; @@ -183,7 +184,7 @@ ASSERT_EQ("X11", pieces[0]); pieces = base::SplitStringUsingSubstr(pieces[1], " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // X11; CrOS armv7l 4537.56.0 // ^^ ASSERT_EQ(3u, pieces.size()); @@ -777,7 +778,7 @@ #endif } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) class ChromeContentSettingsRedirectTest : public ChromeContentBrowserClientTest { public: @@ -905,7 +906,7 @@ EXPECT_TRUE(policy::PolicyCertServiceFactory::UsedPolicyCertificates(kEmail)); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) class CaptivePortalCheckProcessHost : public content::MockRenderProcessHost { public:
diff --git a/chrome/browser/chrome_notification_types.h b/chrome/browser/chrome_notification_types.h index 75e5ec8c..207e753b 100644 --- a/chrome/browser/chrome_notification_types.h +++ b/chrome/browser/chrome_notification_types.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_CHROME_NOTIFICATION_TYPES_H_ #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "extensions/buildflags/buildflags.h" #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -137,7 +138,7 @@ // Misc -------------------------------------------------------------------- -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Sent immediately after the logged-in user's profile is ready. // The details are a Profile object. NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
diff --git a/chrome/browser/chrome_plugin_browsertest.cc b/chrome/browser/chrome_plugin_browsertest.cc index 62e241b..db24b06 100644 --- a/chrome/browser/chrome_plugin_browsertest.cc +++ b/chrome/browser/chrome_plugin_browsertest.cc
@@ -13,6 +13,7 @@ #include "base/strings/utf_string_conversions.h" #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" @@ -48,7 +49,7 @@ using ChromePluginTest = InProcessBrowserTest; // Verify that the official builds have the known set of plugins. -#if defined(OS_CHROMEOS) // http://crbug.com/1147726 +#if BUILDFLAG(IS_CHROMEOS_ASH) // http://crbug.com/1147726 #define MAYBE_InstalledPlugins DISABLED_InstalledPlugins #else #define MAYBE_InstalledPlugins InstalledPlugins
diff --git a/chrome/browser/chrome_resource_bundle_helper.cc b/chrome/browser/chrome_resource_bundle_helper.cc index 66fb4fea..494d1f7 100644 --- a/chrome/browser/chrome_resource_bundle_helper.cc +++ b/chrome/browser/chrome_resource_bundle_helper.cc
@@ -9,6 +9,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/metrics/chrome_feature_list_creator.h" #include "chrome/browser/prefs/chrome_command_line_pref_store.h" @@ -27,7 +28,7 @@ #include "ui/base/resource/resource_bundle_android.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/common/pref_names.h" #include "chromeos/constants/chromeos_switches.h" #endif @@ -38,7 +39,7 @@ ChromeFeatureListCreator* chrome_feature_list_creator) { TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState"); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(chromeos::switches::kLoginManager)) { PrefService* local_state = chrome_feature_list_creator->local_state(); @@ -54,7 +55,7 @@ local_state->SetString(language::prefs::kApplicationLocale, owner_locale); } } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } // Initializes the shared instance of ResourceBundle and returns the application
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 0240977..e9ae697 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1055,6 +1055,8 @@ "crosapi/keystore_service_ash.h", "crosapi/message_center_ash.cc", "crosapi/message_center_ash.h", + "crosapi/metrics_reporting_ash.cc", + "crosapi/metrics_reporting_ash.h", "crosapi/screen_manager_ash.cc", "crosapi/screen_manager_ash.h", "crosapi/select_file_ash.cc", @@ -3444,6 +3446,7 @@ "crosapi/account_manager_ash_unittest.cc", "crosapi/browser_util_unittest.cc", "crosapi/message_center_ash_unittest.cc", + "crosapi/metrics_reporting_ash_unittest.cc", "crosapi/test_mojo_connection_manager_unittest.cc", "crostini/ansible/ansible_management_service_unittest.cc", "crostini/crostini_disk_unittest.cc",
diff --git a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.cc b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.cc index 2ff34da..9d29ed1 100644 --- a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.cc +++ b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.cc
@@ -32,6 +32,9 @@ using AXStringListProperty = mojom::AccessibilityStringListProperty; using AXStringProperty = mojom::AccessibilityStringProperty; +constexpr mojom::AccessibilityStringProperty + AccessibilityNodeInfoDataWrapper::text_properties_[]; + AccessibilityNodeInfoDataWrapper::AccessibilityNodeInfoDataWrapper( AXTreeSourceArc* tree_source, AXNodeInfoData* node) @@ -638,10 +641,11 @@ } bool AccessibilityNodeInfoDataWrapper::HasText() const { - // The same properties are checked as ComputeNameFromContentsInternal. - return HasNonEmptyStringProperty(node_ptr_, - AXStringProperty::CONTENT_DESCRIPTION) || - HasNonEmptyStringProperty(node_ptr_, AXStringProperty::TEXT); + for (const auto it : text_properties_) { + if (HasNonEmptyStringProperty(node_ptr_, it)) + return true; + } + return false; } bool AccessibilityNodeInfoDataWrapper::HasAccessibilityFocusableText() const { @@ -678,18 +682,13 @@ if (IsVirtualNode() || IsAccessibilityFocusableContainer()) return; - // Take the name from either content description or text. It's not clear - // whether labeled by should be taken into account here. std::string name; - if (!GetProperty(AXStringProperty::CONTENT_DESCRIPTION, &name) || - name.empty()) { - GetProperty(AXStringProperty::TEXT, &name); - } - - // Stop when we get a name for this subtree. - if (!name.empty()) { - names->push_back(name); - return; + for (const auto it : text_properties_) { + if (GetProperty(it, &name) && !name.empty()) { + // Stop when we get a name for this subtree. + names->push_back(name); + return; + } } // Otherwise, continue looking for a name in this subtree.
diff --git a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.h b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.h index 5a205bc6..fd009e4 100644 --- a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.h +++ b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper.h
@@ -90,6 +90,13 @@ mojom::AccessibilityLiveRegionType container_live_status_ = mojom::AccessibilityLiveRegionType::NONE; + // Properties which should be checked for recursive text computation. + // It's not clear whether labeled by should be taken into account here. + static constexpr mojom::AccessibilityStringProperty text_properties_[3] = { + mojom::AccessibilityStringProperty::TEXT, + mojom::AccessibilityStringProperty::CONTENT_DESCRIPTION, + mojom::AccessibilityStringProperty::STATE_DESCRIPTION}; + // This property is a cached value so that we can avoid same computation. // mutable because once the value is computed it won't change. mutable base::Optional<bool> has_important_property_cache_;
diff --git a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper_unittest.cc b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper_unittest.cc index bf3f714..c946139 100644 --- a/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper_unittest.cc +++ b/chrome/browser/chromeos/arc/accessibility/accessibility_node_info_data_wrapper_unittest.cc
@@ -315,6 +315,55 @@ data.GetStringAttribute(ax::mojom::StringAttribute::kName, &name)); } +TEST_F(AccessibilityNodeInfoDataWrapperTest, NameFromTextProperties) { + AXNodeInfoData root; + root.id = 10; + AccessibilityNodeInfoDataWrapper root_wrapper(tree_source(), &root); + SetIdToWrapper(&root_wrapper); + SetProperty(&root, AXStringProperty::CLASS_NAME, ""); + SetProperty(&root, AXBooleanProperty::IMPORTANCE, true); + SetProperty(&root, AXBooleanProperty::CLICKABLE, true); + SetProperty(&root, AXBooleanProperty::FOCUSABLE, true); + SetProperty(&root, AXIntListProperty::CHILD_NODE_IDS, std::vector<int>({1})); + + AXNodeInfoData child1; + child1.id = 1; + AccessibilityNodeInfoDataWrapper child1_wrapper(tree_source(), &child1); + SetIdToWrapper(&child1_wrapper); + + // Set all properties that will be used in name computation. + SetProperty(&child1, AXStringProperty::TEXT, "text"); + SetProperty(&child1, AXStringProperty::CONTENT_DESCRIPTION, + "content_description"); + SetProperty(&child1, AXStringProperty::STATE_DESCRIPTION, + "state_description"); + + AccessibilityNodeInfoDataWrapper wrapper(tree_source(), &root); + + ui::AXNodeData data = CallSerialize(wrapper); + + std::string name; + + ASSERT_TRUE( + data.GetStringAttribute(ax::mojom::StringAttribute::kName, &name)); + ASSERT_EQ("text", name); + + // Unset TEXT property, and confirm that CONTENT_DESCRIPTION is used as name. + SetProperty(&child1, AXStringProperty::TEXT, ""); + data = CallSerialize(wrapper); + ASSERT_TRUE( + data.GetStringAttribute(ax::mojom::StringAttribute::kName, &name)); + ASSERT_EQ("content_description", name); + + // Unset CONTENT_DESCRIPTION property, and confirm that STATE_DESCRIPTION is + // used as name. + SetProperty(&child1, AXStringProperty::CONTENT_DESCRIPTION, ""); + data = CallSerialize(wrapper); + ASSERT_TRUE( + data.GetStringAttribute(ax::mojom::StringAttribute::kName, &name)); + ASSERT_EQ("state_description", name); +} + TEST_F(AccessibilityNodeInfoDataWrapperTest, TextFieldNameAndValue) { AXNodeInfoData node; SetProperty(&node, AXStringProperty::CLASS_NAME, "");
diff --git a/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.cc b/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.cc index 4e5accf..cde8cc9 100644 --- a/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.cc +++ b/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/chromeos/crosapi/file_manager_ash.h" #include "chrome/browser/chromeos/crosapi/keystore_service_ash.h" #include "chrome/browser/chromeos/crosapi/message_center_ash.h" +#include "chrome/browser/chromeos/crosapi/metrics_reporting_ash.h" #include "chrome/browser/chromeos/crosapi/screen_manager_ash.h" #include "chrome/browser/chromeos/crosapi/select_file_ash.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" @@ -40,6 +41,8 @@ AshChromeServiceImpl::AshChromeServiceImpl( mojo::PendingReceiver<mojom::AshChromeService> pending_receiver) : receiver_(this, std::move(pending_receiver)), + metrics_reporting_ash_(std::make_unique<MetricsReportingAsh>( + g_browser_process->local_state())), screen_manager_ash_(std::make_unique<ScreenManagerAsh>()), cert_database_ash_(std::make_unique<CertDatabaseAsh>()) { // TODO(hidehiko): Remove non-critical log from here. @@ -105,6 +108,11 @@ message_center_ash_ = std::make_unique<MessageCenterAsh>(std::move(receiver)); } +void AshChromeServiceImpl::BindMetricsReporting( + mojo::PendingReceiver<mojom::MetricsReporting> receiver) { + metrics_reporting_ash_->BindReceiver(std::move(receiver)); +} + void AshChromeServiceImpl::BindSelectFile( mojo::PendingReceiver<mojom::SelectFile> receiver) { // TODO(https://crbug.com/1148448): Convert this to allow multiple,
diff --git a/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.h b/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.h index 9fb6e4e..15bc50e 100644 --- a/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.h +++ b/chrome/browser/chromeos/crosapi/ash_chrome_service_impl.h
@@ -19,6 +19,7 @@ class FileManagerAsh; class KeystoreServiceAsh; class MessageCenterAsh; +class MetricsReportingAsh; class ScreenManagerAsh; class SelectFileAsh; @@ -39,6 +40,8 @@ mojo::PendingReceiver<mojom::KeystoreService> receiver) override; void BindMessageCenter( mojo::PendingReceiver<mojom::MessageCenter> receiver) override; + void BindMetricsReporting( + mojo::PendingReceiver<mojom::MetricsReporting> receiver) override; void BindScreenManager( mojo::PendingReceiver<mojom::ScreenManager> receiver) override; void BindSelectFile( @@ -66,6 +69,7 @@ std::unique_ptr<FileManagerAsh> file_manager_ash_; std::unique_ptr<KeystoreServiceAsh> keystore_service_ash_; std::unique_ptr<MessageCenterAsh> message_center_ash_; + std::unique_ptr<MetricsReportingAsh> metrics_reporting_ash_; std::unique_ptr<ScreenManagerAsh> screen_manager_ash_; std::unique_ptr<SelectFileAsh> select_file_ash_; std::unique_ptr<FeedbackAsh> feedback_ash_;
diff --git a/chrome/browser/chromeos/crosapi/browser_util.cc b/chrome/browser/chromeos/crosapi/browser_util.cc index 0198cca5..a8a8d4f 100644 --- a/chrome/browser/chromeos/crosapi/browser_util.cc +++ b/chrome/browser/chromeos/crosapi/browser_util.cc
@@ -161,7 +161,7 @@ base::flat_map<base::Token, uint32_t> GetInterfaceVersions() { static_assert( - crosapi::mojom::AshChromeService::Version_ == 7, + crosapi::mojom::AshChromeService::Version_ == 8, "if you add a new crosapi, please add it to the version map here"); InterfaceVersions versions; AddVersion<crosapi::mojom::AccountManager>(&versions); @@ -171,6 +171,7 @@ AddVersion<crosapi::mojom::FileManager>(&versions); AddVersion<crosapi::mojom::KeystoreService>(&versions); AddVersion<crosapi::mojom::MessageCenter>(&versions); + AddVersion<crosapi::mojom::MetricsReporting>(&versions); AddVersion<crosapi::mojom::ScreenManager>(&versions); AddVersion<crosapi::mojom::SnapshotCapturer>(&versions); AddVersion<device::mojom::HidConnection>(&versions);
diff --git a/chrome/browser/chromeos/crosapi/metrics_reporting_ash.cc b/chrome/browser/chromeos/crosapi/metrics_reporting_ash.cc new file mode 100644 index 0000000..7418084da --- /dev/null +++ b/chrome/browser/chromeos/crosapi/metrics_reporting_ash.cc
@@ -0,0 +1,64 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/crosapi/metrics_reporting_ash.h" + +#include <utility> + +#include "base/bind.h" +#include "base/check.h" +#include "chromeos/crosapi/mojom/metrics_reporting.mojom.h" +#include "components/metrics/metrics_pref_names.h" +#include "components/prefs/pref_service.h" + +namespace crosapi { + +MetricsReportingAsh::MetricsReportingAsh(PrefService* local_state) + : local_state_(local_state) { + DCHECK(local_state_); + pref_change_registrar_.Init(local_state_); + // base::Unretained() is safe because PrefChangeRegistrar removes all + // observers when it is destroyed. + pref_change_registrar_.Add(metrics::prefs::kMetricsReportingEnabled, + base::Bind(&MetricsReportingAsh::NotifyObservers, + base::Unretained(this))); +} + +MetricsReportingAsh::~MetricsReportingAsh() = default; + +void MetricsReportingAsh::BindReceiver( + mojo::PendingReceiver<mojom::MetricsReporting> receiver) { + receivers_.Add(this, std::move(receiver)); +} + +void MetricsReportingAsh::AddObserver( + mojo::PendingRemote<mojom::MetricsReportingObserver> observer) { + mojo::Remote<mojom::MetricsReportingObserver> remote(std::move(observer)); + // Fire the observer with the initial value. + bool enabled = IsMetricsReportingEnabled(); + remote->OnMetricsReportingChanged(enabled); + // Store the observer for future notifications. + observers_.Add(std::move(remote)); +} + +void MetricsReportingAsh::SetMetricsReportingEnabled( + bool enabled, + SetMetricsReportingEnabledCallback callback) { + // TODO(https://crbug.com/1148604): Implement this. + NOTIMPLEMENTED(); + std::move(callback).Run(); +} + +void MetricsReportingAsh::NotifyObservers() { + bool enabled = IsMetricsReportingEnabled(); + for (auto& observer : observers_) { + observer->OnMetricsReportingChanged(enabled); + } +} + +bool MetricsReportingAsh::IsMetricsReportingEnabled() const { + return local_state_->GetBoolean(metrics::prefs::kMetricsReportingEnabled); +} + +} // namespace crosapi
diff --git a/chrome/browser/chromeos/crosapi/metrics_reporting_ash.h b/chrome/browser/chromeos/crosapi/metrics_reporting_ash.h new file mode 100644 index 0000000..ecebd16 --- /dev/null +++ b/chrome/browser/chromeos/crosapi/metrics_reporting_ash.h
@@ -0,0 +1,60 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROSAPI_METRICS_REPORTING_ASH_H_ +#define CHROME_BROWSER_CHROMEOS_CROSAPI_METRICS_REPORTING_ASH_H_ + +#include "chromeos/crosapi/mojom/metrics_reporting.mojom.h" +#include "components/prefs/pref_change_registrar.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "mojo/public/cpp/bindings/remote_set.h" + +class PrefService; + +namespace crosapi { + +// The ash-chrome implementation of the MetricsReporting crosapi interface. +// This class must only be used from the main thread. +class MetricsReportingAsh : public mojom::MetricsReporting { + public: + // |local_state| is injected for testing. In production it is the global + // local state PrefService, owned by g_browser_process. + explicit MetricsReportingAsh(PrefService* local_state); + MetricsReportingAsh(const MetricsReportingAsh&) = delete; + MetricsReportingAsh& operator=(const MetricsReportingAsh&) = delete; + ~MetricsReportingAsh() override; + + void BindReceiver(mojo::PendingReceiver<mojom::MetricsReporting> receiver); + + // crosapi::mojom::MetricsReporting: + void AddObserver( + mojo::PendingRemote<mojom::MetricsReportingObserver> observer) override; + void SetMetricsReportingEnabled( + bool enabled, + SetMetricsReportingEnabledCallback callback) override; + + private: + // Notifies all observers of the current metrics state. + void NotifyObservers(); + + // Returns whether metrics reporting is enabled. + bool IsMetricsReportingEnabled() const; + + // In production, owned by g_browser_process, which outlives this object. + PrefService* const local_state_; + + // Observes the metrics enabled pref. + PrefChangeRegistrar pref_change_registrar_; + + // This class supports any number of connections. + mojo::ReceiverSet<mojom::MetricsReporting> receivers_; + + // This class supports any number of observers. + mojo::RemoteSet<mojom::MetricsReportingObserver> observers_; +}; + +} // namespace crosapi + +#endif // CHROME_BROWSER_CHROMEOS_CROSAPI_METRICS_REPORTING_ASH_H_
diff --git a/chrome/browser/chromeos/crosapi/metrics_reporting_ash_unittest.cc b/chrome/browser/chromeos/crosapi/metrics_reporting_ash_unittest.cc new file mode 100644 index 0000000..112e706 --- /dev/null +++ b/chrome/browser/chromeos/crosapi/metrics_reporting_ash_unittest.cc
@@ -0,0 +1,71 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/crosapi/metrics_reporting_ash.h" + +#include "base/test/task_environment.h" +#include "chrome/test/base/scoped_testing_local_state.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chromeos/crosapi/mojom/message_center.mojom.h" +#include "components/metrics/metrics_pref_names.h" +#include "components/prefs/pref_service.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace crosapi { +namespace { + +class TestObserver : public mojom::MetricsReportingObserver { + public: + TestObserver() = default; + TestObserver(const TestObserver&) = delete; + TestObserver& operator=(const TestObserver&) = delete; + ~TestObserver() override = default; + + // crosapi::mojom::MetricsReportingObserver: + void OnMetricsReportingChanged(bool enabled) override { + metrics_enabled_ = enabled; + } + + // Public because this is test code. + base::Optional<bool> metrics_enabled_; + mojo::Receiver<mojom::MetricsReportingObserver> receiver_{this}; +}; + +TEST(MetricsReportingAshTest, Basics) { + base::test::TaskEnvironment task_environment; + + // Simulate metrics reporting enabled. + ScopedTestingLocalState local_state(TestingBrowserProcess::GetGlobal()); + local_state.Get()->SetBoolean(metrics::prefs::kMetricsReportingEnabled, true); + + // Construct the object under test. + MetricsReportingAsh metrics_reporting_ash(local_state.Get()); + mojo::Remote<mojom::MetricsReporting> metrics_reporting_remote; + metrics_reporting_ash.BindReceiver( + metrics_reporting_remote.BindNewPipeAndPassReceiver()); + + // Adding an observer results in it being fired with the current state. + TestObserver observer; + metrics_reporting_remote->AddObserver( + observer.receiver_.BindNewPipeAndPassRemote()); + metrics_reporting_remote.FlushForTesting(); + ASSERT_TRUE(observer.metrics_enabled_.has_value()); + EXPECT_TRUE(observer.metrics_enabled_.value()); + + // Disabling metrics reporting in ash fires the observer with the new value. + observer.metrics_enabled_.reset(); + local_state.Get()->SetBoolean(metrics::prefs::kMetricsReportingEnabled, + false); + observer.receiver_.FlushForTesting(); + ASSERT_TRUE(observer.metrics_enabled_.has_value()); + EXPECT_FALSE(observer.metrics_enabled_.value()); + + // TODO(https://crbug.com/1148604): Test SetMetricsReportingConsent() once + // that function is implemented. +} + +} // namespace +} // namespace crosapi
diff --git a/chrome/browser/chromeos/crostini/crostini_terminal.cc b/chrome/browser/chromeos/crostini/crostini_terminal.cc index 344623d..8e5db7d 100644 --- a/chrome/browser/chromeos/crostini/crostini_terminal.cc +++ b/chrome/browser/chromeos/crostini/crostini_terminal.cc
@@ -13,7 +13,6 @@ #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/browser/chromeos/crostini/crostini_pref_names.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" -#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/window_properties.h" #include "chrome/browser/ui/browser.h"
diff --git a/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc b/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc index bc75dab4..b793c6f 100644 --- a/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc +++ b/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc
@@ -142,7 +142,7 @@ drivefs::mojom::QueryParameters::SortDirection::kAscending, base::BindLambdaForTesting( [=](FileError error, std::vector<base::FilePath> paths) { - EXPECT_EQ(2, paths.size()); + EXPECT_EQ(2u, paths.size()); EXPECT_EQ("baz", paths[0].BaseName().value()); EXPECT_EQ("bar", paths[1].BaseName().value()); quit_closure.Run();
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index f5161b9..fb25712f 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -106,11 +106,6 @@ return *this; } - TestCase& EnableTrash() { - options.trash = true; - return *this; - } - // Show the startup browser. Some tests invoke the file picker dialog during // the test. Requesting a file picker from a background page is forbidden by // the apps platform, and it's a bug that these tests do so. @@ -1034,9 +1029,9 @@ WRAPPED_INSTANTIATE_TEST_SUITE_P( Trash, /* trash.js */ FilesAppBrowserTest, - ::testing::Values(TestCase("trashMoveToTrash").EnableTrash(), - TestCase("trashRestoreFromToast").EnableTrash(), - TestCase("trashRestoreFromTrash").EnableTrash(), - TestCase("trashDeleteFromTrash").EnableTrash())); + ::testing::Values(TestCase("trashMoveToTrash"), + TestCase("trashRestoreFromToast"), + TestCase("trashRestoreFromTrash"), + TestCase("trashDeleteFromTrash"))); } // namespace file_manager
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 2230798f..0991f26 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc
@@ -737,7 +737,6 @@ PRINT_IF_NOT_DEFAULT(single_partition_format) PRINT_IF_NOT_DEFAULT(smbfs) PRINT_IF_NOT_DEFAULT(tablet_mode) - PRINT_IF_NOT_DEFAULT(trash) PRINT_IF_NOT_DEFAULT(zip) PRINT_IF_NOT_DEFAULT(zip_no_nacl) @@ -1649,6 +1648,12 @@ std::vector<base::Feature> enabled_features; std::vector<base::Feature> disabled_features; + // Make sure to run the ARC storage UI toast tests. + enabled_features.push_back(arc::kUsbStorageUIFeature); + + // Use Trash in tests. + enabled_features.push_back(chromeos::features::kFilesTrash); + if (options.files_swa) { enabled_features.push_back(chromeos::features::kFilesSWA); } else { @@ -1659,9 +1664,6 @@ arc::SetArcAvailableCommandLineForTesting(command_line); } - // Make sure to run the ARC storage UI toast tests. - enabled_features.push_back(arc::kUsbStorageUIFeature); - if (options.documents_provider) { enabled_features.push_back(arc::kEnableDocumentsProviderInFilesAppFeature); } else { @@ -1698,10 +1700,6 @@ enabled_features.push_back(chromeos::features::kFilesSinglePartitionFormat); } - if (options.trash) { - enabled_features.push_back(chromeos::features::kFilesTrash); - } - if (options.enable_holding_space) { enabled_features.push_back(ash::features::kTemporaryHoldingSpace); } else {
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 65dbe6b..cb0ed27 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h
@@ -91,9 +91,6 @@ // Whether test needs smbfs for native SMB integration. bool smbfs = false; - // Whether test needs trash. - bool trash = false; - // Whether test needs the unified media view feature. bool unified_media_view = false;
diff --git a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc index 00db0ddb..4d1b5e0 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc
@@ -99,15 +99,15 @@ } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesDisplayPanel) { - RunTestURL("foreground/elements/files_xf_elements_unittest_gen.html"); + RunTestURL("foreground/elements/files_xf_elements_unittest.m_gen.html"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesMessage) { - RunTestURL("foreground/elements/files_message_unittest_gen.html"); + RunTestURL("foreground/elements/files_message_unittest.m_gen.html"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesPasswordDialog) { - RunTestURL("foreground/elements/files_password_dialog_unittest_gen.html"); + RunTestURL("foreground/elements/files_password_dialog_unittest.m_gen.html"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesToast) {
diff --git a/chrome/browser/chromeos/input_method/input_method_manager_impl_unittest.cc b/chrome/browser/chromeos/input_method/input_method_manager_impl_unittest.cc index e2536bc..1c1ade0a 100644 --- a/chrome/browser/chromeos/input_method/input_method_manager_impl_unittest.cc +++ b/chrome/browser/chromeos/input_method/input_method_manager_impl_unittest.cc
@@ -808,7 +808,6 @@ EXPECT_TRUE(manager_->GetActiveIMEState()->ReplaceEnabledInputMethods(ids)); EXPECT_EQ(4U, manager_->GetActiveIMEState()->GetNumActiveInputMethods()); EXPECT_EQ(2, keyboard_->set_current_keyboard_layout_by_name_count_); - // See input_methods.txt for an expected XKB layout name. EXPECT_EQ("us(dvorak)", keyboard_->last_layout_); manager_->GetActiveIMEState()->SwitchToNextInputMethod(); EXPECT_EQ(3, keyboard_->set_current_keyboard_layout_by_name_count_);
diff --git a/chrome/browser/chromeos/input_method/ui/DIR_METADATA b/chrome/browser/chromeos/input_method/ui/DIR_METADATA index 1d28f0a..ca0e79f 100644 --- a/chrome/browser/chromeos/input_method/ui/DIR_METADATA +++ b/chrome/browser/chromeos/input_method/ui/DIR_METADATA
@@ -1,3 +1,3 @@ monorail: { - component: "UI>Input>Text>IME" + component: "OS>Inputs" }
diff --git a/chrome/browser/component_updater/registration.cc b/chrome/browser/component_updater/registration.cc index 8bec7e3..cf3b88c 100644 --- a/chrome/browser/component_updater/registration.cc +++ b/chrome/browser/component_updater/registration.cc
@@ -8,6 +8,7 @@ #include "base/path_service.h" #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/buildflags.h" #include "chrome/browser/component_updater/autofill_regex_component_installer.h" @@ -59,9 +60,9 @@ #include "media/base/media_switches.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/component_updater/smart_dim_component_installer.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(ENABLE_NACL) #include "chrome/browser/component_updater/pnacl_component_installer.h" @@ -100,12 +101,12 @@ #endif // BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT) #if BUILDFLAG(ENABLE_NACL) && !defined(OS_ANDROID) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // PNaCl on Chrome OS is on rootfs and there is no need to download it. But // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component // installer when running on Linux. See crbug.com/422121 for more details. if (!base::SysInfo::IsRunningOnChromeOS()) -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) RegisterPnaclComponent(cus); #endif // BUILDFLAG(ENABLE_NACL) && !defined(OS_ANDROID) @@ -124,7 +125,7 @@ // the old file. component_updater::DeleteLegacyCRLSet(path); -#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID) // Clean up previous STH sets that may have been installed. This is not // done for: // Android: Because STH sets were never used @@ -134,12 +135,12 @@ } RegisterSSLErrorAssistantComponent(cus); RegisterFileTypePoliciesComponent(cus); -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // CRLSetFetcher attempts to load a CRL set from either the local disk or // network. // For Chrome OS this registration is delayed until user login. component_updater::RegisterCRLSetComponent(cus); -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) RegisterOriginTrialsComponent(cus); RegisterMediaEngagementPreloadComponent(cus, base::OnceClosure()); @@ -179,9 +180,9 @@ cus, profile_prefs, g_browser_process->local_state()); #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) RegisterSmartDimComponent(cus); -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(USE_MINIKIN_HYPHENATION) && !defined(OS_ANDROID) RegisterHyphenationComponent(cus);
diff --git a/chrome/browser/component_updater/widevine_cdm_component_installer.cc b/chrome/browser/component_updater/widevine_cdm_component_installer.cc index 7eab4d1..08fb9ca 100644 --- a/chrome/browser/component_updater/widevine_cdm_component_installer.cc +++ b/chrome/browser/component_updater/widevine_cdm_component_installer.cc
@@ -27,6 +27,7 @@ #include "base/task/thread_pool.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/media/cdm_manifest.h" #include "components/component_updater/component_installer.h" #include "components/component_updater/component_updater_service.h" @@ -76,9 +77,9 @@ "mac"; #elif defined(OS_WIN) "win"; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) "cros"; -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) "linux"; #else #error This file should only be included for supported platforms.
diff --git a/chrome/browser/content_settings/content_settings_browsertest.cc b/chrome/browser/content_settings/content_settings_browsertest.cc index d896bf4..f1dd0a6c 100644 --- a/chrome/browser/content_settings/content_settings_browsertest.cc +++ b/chrome/browser/content_settings/content_settings_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" @@ -731,7 +732,7 @@ // This fails on ChromeOS because kRestoreOnStartup is ignored and the startup // preference is always "continue where I left off. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Verify that cookies can be allowed and set using exceptions for particular // website(s) only for a session when all others are blocked.
diff --git a/chrome/browser/contextmenu/BUILD.gn b/chrome/browser/contextmenu/BUILD.gn index 9556eaf..9ead1e1 100644 --- a/chrome/browser/contextmenu/BUILD.gn +++ b/chrome/browser/contextmenu/BUILD.gn
@@ -8,6 +8,8 @@ android_library("java") { sources = [ + "java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java", + "java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java", "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuItemDelegate.java", "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuNativeDelegate.java", "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuNativeDelegateImpl.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java b/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java rename to chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipDelegate.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java b/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java similarity index 75% rename from chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java rename to chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java index 105af521..45ebfe5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java +++ b/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ChipRenderParams.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.contextmenu; import androidx.annotation.DrawableRes; +import androidx.annotation.Nullable; import androidx.annotation.StringRes; /** @@ -18,6 +19,9 @@ public @DrawableRes int iconResourceId; // The callback to be called when the chip clicked. - // A non-null ChipRenderParams will always have a non-null callback. + // A non-null ChipRenderParams will always have a non-null onClickCallback. public Runnable onClickCallback; + + // A callback to be called when the chip shown. + public @Nullable Runnable onShowCallback; } \ No newline at end of file
diff --git a/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java b/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java index b5b92eb..0c27487 100644 --- a/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java +++ b/chrome/browser/contextmenu/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java
@@ -6,6 +6,8 @@ import android.util.Pair; +import androidx.annotation.Nullable; + import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import java.util.List; @@ -46,4 +48,10 @@ * @return The title of current web page. */ String getPageTitle(); + + /** + * @return A chip delegate responsible for populating chip data and action handling. + */ + @Nullable + ChipDelegate getChipDelegate(); }
diff --git a/chrome/browser/crash_recovery_browsertest.cc b/chrome/browser/crash_recovery_browsertest.cc index 8a21b15..2ccc4d1 100644 --- a/chrome/browser/crash_recovery_browsertest.cc +++ b/chrome/browser/crash_recovery_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -39,7 +40,7 @@ using content::WebContents; // TODO(jam): http://crbug.com/350550 -#if !(defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER)) +#if !(BUILDFLAG(IS_CHROMEOS_ASH) && defined(ADDRESS_SANITIZER)) namespace {
diff --git a/chrome/browser/crash_upload_list/crash_upload_list.cc b/chrome/browser/crash_upload_list/crash_upload_list.cc index 7988291b..d63e3508 100644 --- a/chrome/browser/crash_upload_list/crash_upload_list.cc +++ b/chrome/browser/crash_upload_list/crash_upload_list.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/crash_upload_list/crash_upload_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #if defined(OS_MAC) || defined(OS_WIN) #include "chrome/browser/crash_upload_list/crash_upload_list_crashpad.h" @@ -38,7 +39,7 @@ // ChromeOS uses crash_sender as its uploader even when Crashpad is enabled, // which isn't compatible with CrashUploadListCrashpad. crash_sender continues // to log uploads in CrashUploadList::kReporterLogFilename. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) if (crash_reporter::IsCrashpadEnabled()) { return new CrashUploadListCrashpad(); }
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry.cc b/chrome/browser/custom_handlers/protocol_handler_registry.cc index 5d5bd08..c33a340 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry.cc
@@ -16,6 +16,7 @@ #include "base/notreached.h" #include "base/stl_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/common/custom_handlers/protocol_handler.h" #include "chrome/common/pref_names.h" @@ -215,7 +216,7 @@ } void ProtocolHandlerRegistry::InstallDefaultsForChromeOS() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Only chromeos has default protocol handlers at this point. AddPredefinedHandler( ProtocolHandler::CreateProtocolHandler(
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry_factory.cc b/chrome/browser/custom_handlers/protocol_handler_registry_factory.cc index 76f55ebe..06a1b25 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry_factory.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry_factory.cc
@@ -8,6 +8,7 @@ #include "base/memory/singleton.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -59,7 +60,7 @@ ProtocolHandlerRegistry* registry = new ProtocolHandlerRegistry( context, std::make_unique<ProtocolHandlerRegistry::Delegate>()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // If installing defaults, they must be installed prior calling // InitProtocolSettings registry->InstallDefaultsForChromeOS();
diff --git a/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc b/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc index 48e1c21..1dde9a9 100644 --- a/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc +++ b/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc
@@ -17,6 +17,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/profiles/profile.h" @@ -128,7 +129,7 @@ } // namespace -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.cc b/chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.cc index 78def63..9c7a6db3 100644 --- a/chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.cc +++ b/chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.cc
@@ -17,6 +17,7 @@ #include "base/strings/string_util.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h" @@ -287,7 +288,7 @@ return data_reduction_proxy::Client::CHROME_ANDROID; #elif defined(OS_MAC) return data_reduction_proxy::Client::CHROME_MAC; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) return data_reduction_proxy::Client::CHROME_CHROMEOS; #elif defined(OS_LINUX) || defined(OS_CHROMEOS) return data_reduction_proxy::Client::CHROME_LINUX;
diff --git a/chrome/browser/data_saver/subresource_redirect_browsertest.cc b/chrome/browser/data_saver/subresource_redirect_browsertest.cc index 8259eb5f..1af8266 100644 --- a/chrome/browser/data_saver/subresource_redirect_browsertest.cc +++ b/chrome/browser/data_saver/subresource_redirect_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/task/thread_pool/thread_pool_instance.h" #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" @@ -454,7 +455,7 @@ } }; -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/defaults.cc b/chrome/browser/defaults.cc index 6bc7640..6c93743 100644 --- a/chrome/browser/defaults.cc +++ b/chrome/browser/defaults.cc
@@ -6,10 +6,11 @@ #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" namespace browser_defaults { -#if defined(OS_CHROMEOS) || defined(OS_MAC) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_MAC) const bool kBrowserAliveWithNoWindows = true; const bool kShowExitMenuItem = false; #else @@ -17,7 +18,7 @@ const bool kShowExitMenuItem = true; #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const bool kShowUpgradeMenuItem = false; const bool kShowImportOnBookmarkBar = false; const bool kAlwaysOpenIncognitoWindow = true; @@ -29,7 +30,7 @@ const bool kAlwaysCreateTabbedBrowserOnSessionRestore = true; #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const bool kShowHelpMenuItemIcon = true; #else const bool kShowHelpMenuItemIcon = false; @@ -37,13 +38,15 @@ const bool kDownloadPageHasShowInFolder = true; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const bool kSyncAutoStarts = true; #else const bool kSyncAutoStarts = false; #endif -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) const bool kScrollEventChangesTab = true; #else const bool kScrollEventChangesTab = false;
diff --git a/chrome/browser/dom_distiller/distillable_page_utils_browsertest.cc b/chrome/browser/dom_distiller/distillable_page_utils_browsertest.cc index 6cc93ab..0111def 100644 --- a/chrome/browser/dom_distiller/distillable_page_utils_browsertest.cc +++ b/chrome/browser/dom_distiller/distillable_page_utils_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" @@ -311,6 +312,6 @@ "IsPageDistillable"), Pointee(false)); } -#endif // OS_CHROMEOS || OS_LINUX || OS_MACOS || OS_WIN +#endif // BUILDFLAG(IS_CHROMEOS_ASH) || OS_LINUX || OS_MACOS || OS_WIN } // namespace dom_distiller
diff --git a/chrome/browser/downgrade/buildflags.gni b/chrome/browser/downgrade/buildflags.gni index ec184e7..dfee39d 100644 --- a/chrome/browser/downgrade/buildflags.gni +++ b/chrome/browser/downgrade/buildflags.gni
@@ -2,8 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromeos/ui_mode.gni") import("//build/config/features.gni") declare_args() { - enable_downgrade_processing = !is_android && !is_chromeos + enable_downgrade_processing = !is_android && !is_chromeos_ash }
diff --git a/chrome/browser/download/download_dir_util.cc b/chrome/browser/download/download_dir_util.cc index 6e5f3c54..9e0faad 100644 --- a/chrome/browser/download/download_dir_util.cc +++ b/chrome/browser/download/download_dir_util.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/download/download_dir_util.h" #include "base/files/file_path.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/policy/policy_path_parser.h" #include "components/policy/core/browser/configuration_policy_handler_parameters.h"
diff --git a/chrome/browser/error_reporting/BUILD.gn b/chrome/browser/error_reporting/BUILD.gn index 4115d4b..101eb5e2 100644 --- a/chrome/browser/error_reporting/BUILD.gn +++ b/chrome/browser/error_reporting/BUILD.gn
@@ -13,6 +13,7 @@ ] deps = [ "//base", + "//build:chromeos_buildflags", "//components/crash/content/browser/error_reporting", "//components/crash/core/app", "//components/feedback",
diff --git a/chrome/browser/error_reporting/chrome_js_error_report_processor.cc b/chrome/browser/error_reporting/chrome_js_error_report_processor.cc index 97696e6..9e2f876 100644 --- a/chrome/browser/error_reporting/chrome_js_error_report_processor.cc +++ b/chrome/browser/error_reporting/chrome_js_error_report_processor.cc
@@ -20,6 +20,7 @@ #include "base/task/thread_pool.h" #include "base/time/default_clock.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/crash/content/browser/error_reporting/javascript_error_report.h" #include "components/crash/core/app/client_upload_info.h" #include "components/feedback/redaction_tool.h" @@ -256,7 +257,7 @@ params["browser"] = "Chrome"; params["browser_version"] = platform.version; params["channel"] = platform.channel; -#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) // base::SysInfo::OperatingSystemName() returns "Linux" on ChromeOS devices. params["os"] = "ChromeOS"; #else
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 6dd14648..b45e51e 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -997,8 +997,6 @@ "api/tabs/tabs_util_chromeos.cc", "api/terminal/crostini_startup_status.cc", "api/terminal/crostini_startup_status.h", - "api/terminal/terminal_extension_helper.cc", - "api/terminal/terminal_extension_helper.h", "api/terminal/terminal_private_api.cc", "api/terminal/terminal_private_api.h", "api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc",
diff --git a/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc b/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc index 67e19a18..86cd394e 100644 --- a/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc +++ b/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
@@ -135,8 +135,9 @@ ExtensionPageCaptureApiTest, ::testing::Values(ContextType::kServiceWorker)); +// Flaky on all platforms: https://crbug.com/1156323 IN_PROC_BROWSER_TEST_P(ExtensionPageCaptureApiTest, - SaveAsMHTMLWithoutFileAccess) { + DISABLED_SaveAsMHTMLWithoutFileAccess) { ASSERT_TRUE(StartEmbeddedTestServer()); PageCaptureSaveAsMHTMLDelegate delegate; ASSERT_TRUE(RunTestWithFlagsAndArg("page_capture",
diff --git a/chrome/browser/extensions/api/tab_groups/tab_groups_api_apitest.cc b/chrome/browser/extensions/api/tab_groups/tab_groups_api_apitest.cc index 38115647..89a14c7 100644 --- a/chrome/browser/extensions/api/tab_groups/tab_groups_api_apitest.cc +++ b/chrome/browser/extensions/api/tab_groups/tab_groups_api_apitest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_apitest.h" #include "content/public/test/browser_test.h" @@ -13,7 +14,9 @@ using TabGroupsApiTest = ExtensionApiTest; IN_PROC_BROWSER_TEST_F(TabGroupsApiTest, TestTabGroupsWorks) { -#if defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) // TODO(crbug.com/1148195): Fix flakiness of this text on Linux. return; #endif
diff --git a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc index 2032794..7455a98 100644 --- a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc
@@ -6,6 +6,7 @@ #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_apitest.h"
diff --git a/chrome/browser/extensions/api/terminal/terminal_extension_helper.cc b/chrome/browser/extensions/api/terminal/terminal_extension_helper.cc deleted file mode 100644 index 9d6965bb..0000000 --- a/chrome/browser/extensions/api/terminal/terminal_extension_helper.cc +++ /dev/null
@@ -1,58 +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/extensions/api/terminal/terminal_extension_helper.h" - -#include <stddef.h> - -#include "base/stl_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/webui_url_constants.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/common/extension.h" - -namespace extensions { - -namespace { - -const char kCroshExtensionEntryPoint[] = "/html/crosh.html"; - -} // namespace - -const Extension* TerminalExtensionHelper::GetTerminalExtension( - Profile* profile) { - // Search order for terminal extensions: nassh-dev, then nassh. - static const char* const kPossibleAppIds[] = { - extension_misc::kHTermDevAppId, - extension_misc::kHTermAppId, - }; - - // The nassh-dev should be first in the list. - DCHECK_EQ(kPossibleAppIds[0], extension_misc::kHTermDevAppId); - - const ExtensionSet& extensions = - ExtensionRegistry::Get(profile)->enabled_extensions(); - for (size_t i = 0; i < base::size(kPossibleAppIds); ++i) { - const extensions::Extension* extension = - extensions.GetByID(kPossibleAppIds[i]); - if (extension) - return extension; - } - - return nullptr; -} - -GURL TerminalExtensionHelper::GetCroshURL(Profile* profile) { - // chrome-untrusted://crosh by default. - GURL url(chrome::kChromeUIUntrustedCroshURL); - const extensions::Extension* extension = GetTerminalExtension(profile); - // Allow nassh-dev or nassh to override. - if (extension) { - url = extension->GetResourceURL(kCroshExtensionEntryPoint); - } - return url; -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/terminal/terminal_extension_helper.h b/chrome/browser/extensions/api/terminal/terminal_extension_helper.h deleted file mode 100644 index 0824898..0000000 --- a/chrome/browser/extensions/api/terminal/terminal_extension_helper.h +++ /dev/null
@@ -1,32 +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_EXTENSIONS_API_TERMINAL_TERMINAL_EXTENSION_HELPER_H_ -#define CHROME_BROWSER_EXTENSIONS_API_TERMINAL_TERMINAL_EXTENSION_HELPER_H_ - -#include <string> - -#include "url/gurl.h" - -class Profile; - -namespace extensions { - -class Extension; - -class TerminalExtensionHelper { - public: - // Returns the crosh extension. It is the first found out of: - // 1. nassh-dev : okddffdblfhhnmhodogpojmfkjmhinfp - // 2. nassh : pnhechapfaindjhompbnflcldabbghjo - static const Extension* GetTerminalExtension(Profile* profile); - - // Returns crosh URL. chrome-untrusted://crosh is used by default, but it can - // be overridden by nassh-dev or nassh. - static GURL GetCroshURL(Profile* profile); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_TERMINAL_TERMINAL_EXTENSION_HELPER_H_
diff --git a/chrome/browser/extensions/api/terminal/terminal_private_api.cc b/chrome/browser/extensions/api/terminal/terminal_private_api.cc index f1b271a..0921ae86 100644 --- a/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chrome/browser/extensions/api/terminal/terminal_private_api.cc
@@ -28,7 +28,6 @@ #include "chrome/browser/chromeos/crostini/crostini_terminal.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/extensions/api/terminal/crostini_startup_status.h" -#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/common/chrome_switches.h"
diff --git a/chrome/browser/extensions/api/virtual_keyboard_private/DIR_METADATA b/chrome/browser/extensions/api/virtual_keyboard_private/DIR_METADATA index c209bae..1ae4c22 100644 --- a/chrome/browser/extensions/api/virtual_keyboard_private/DIR_METADATA +++ b/chrome/browser/extensions/api/virtual_keyboard_private/DIR_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Input>VirtualKeyboard" + component: "OS>Inputs" }
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 3af733b..acd7433 100644 --- a/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_apitest.cc
@@ -119,6 +119,7 @@ #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/test/test_url_loader_client.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "ui/base/ui_base_features.h" @@ -1297,6 +1298,7 @@ auto make_browser_request = [this](const GURL& url) { auto request = std::make_unique<network::ResourceRequest>(); request->url = url; + request->destination = network::mojom::RequestDestination::kEmpty; request->resource_type = static_cast<int>(blink::mojom::ResourceType::kSubResource); @@ -3033,7 +3035,9 @@ // Regression test for http://crbug.com/996940. Requests that redirected to an // appcache handled URL could have request ID collisions. // This test is flaky on Linux: https://crbug.com/1094834. -#if defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #define MAYBE_RedirectToAppCacheRequest DISABLED_RedirectToAppCacheRequest #else #define MAYBE_RedirectToAppCacheRequest RedirectToAppCacheRequest
diff --git a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc index 0847188..d752945a 100644 --- a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc +++ b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc
@@ -198,7 +198,7 @@ LazyInitData(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (extension_id == extension_misc::kFilesManagerAppId) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); // Disable $i18n{} template JS string replacement during JS code coverage.
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.cc b/chrome/browser/extensions/chrome_extensions_browser_client.cc index a232b61..da3b4b4 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.cc +++ b/chrome/browser/extensions/chrome_extensions_browser_client.cc
@@ -210,7 +210,7 @@ bool ChromeExtensionsBrowserClient::AllowCrossRendererResourceLoad( const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito, @@ -219,7 +219,7 @@ const ProcessMap& process_map) { bool allowed = false; if (chrome_url_request_util::AllowCrossRendererResourceLoad( - request, resource_type, page_transition, child_id, is_incognito, + request, destination, page_transition, child_id, is_incognito, extension, extensions, process_map, &allowed)) { return allowed; }
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.h b/chrome/browser/extensions/chrome_extensions_browser_client.h index 683afba..2d0e97c 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.h +++ b/chrome/browser/extensions/chrome_extensions_browser_client.h
@@ -21,6 +21,7 @@ #include "extensions/browser/kiosk/kiosk_delegate.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" namespace base { class CommandLine; @@ -82,14 +83,15 @@ const std::string& content_security_policy, mojo::PendingRemote<network::mojom::URLLoaderClient> client, bool send_cors_header) override; - bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map) override; + bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map) override; PrefService* GetPrefServiceForContext( content::BrowserContext* context) override; void GetEarlyExtensionPrefsObservers(
diff --git a/chrome/browser/extensions/chrome_url_request_util.cc b/chrome/browser/extensions/chrome_url_request_util.cc index beec2a1d..0a965952 100644 --- a/chrome/browser/extensions/chrome_url_request_util.cc +++ b/chrome/browser/extensions/chrome_url_request_util.cc
@@ -217,17 +217,18 @@ namespace extensions { namespace chrome_url_request_util { -bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map, - bool* allowed) { +bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map, + bool* allowed) { if (url_request_util::AllowCrossRendererResourceLoad( - request, resource_type, page_transition, child_id, is_incognito, + request, destination, page_transition, child_id, is_incognito, extension, extensions, process_map, allowed)) { return true; }
diff --git a/chrome/browser/extensions/chrome_url_request_util.h b/chrome/browser/extensions/chrome_url_request_util.h index 2138257..dd116bf6 100644 --- a/chrome/browser/extensions/chrome_url_request_util.h +++ b/chrome/browser/extensions/chrome_url_request_util.h
@@ -9,8 +9,8 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/public/mojom/url_loader.mojom-forward.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "ui/base/page_transition_types.h" namespace base { @@ -33,15 +33,16 @@ // Sets allowed=true to allow a chrome-extension:// resource request coming from // renderer A to access a resource in an extension running in renderer B. // Returns false when it couldn't determine if the resource is allowed or not -bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map, - bool* allowed); +bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map, + bool* allowed); // Return the |request|'s resource path relative to the Chromium resources path // (chrome::DIR_RESOURCES) *if* the request refers to a resource within the
diff --git a/chrome/browser/extensions/extension_protocols_unittest.cc b/chrome/browser/extensions/extension_protocols_unittest.cc index 419423f..1437721 100644 --- a/chrome/browser/extensions/extension_protocols_unittest.cc +++ b/chrome/browser/extensions/extension_protocols_unittest.cc
@@ -51,6 +51,7 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/metrics/public/cpp/ukm_source_id.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/test/test_url_loader_client.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -59,9 +60,7 @@ #include "third_party/blink/public/common/privacy_budget/identifiability_metrics.h" #include "third_party/blink/public/common/privacy_budget/identifiable_surface.h" #include "third_party/blink/public/common/privacy_budget/scoped_identifiability_test_sample_collector.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" -using blink::mojom::ResourceType; using extensions::ExtensionRegistry; using network::mojom::URLLoader; using testing::_; @@ -142,9 +141,10 @@ } // Helper function to create a |ResourceRequest| for testing purposes. -network::ResourceRequest CreateResourceRequest(const std::string& method, - ResourceType resource_type, - const GURL& url) { +network::ResourceRequest CreateResourceRequest( + const std::string& method, + network::mojom::RequestDestination destination, + const GURL& url) { network::ResourceRequest request; request.method = method; request.url = url; @@ -153,9 +153,9 @@ request.request_initiator = url::Origin::Create(url); // ensure initiator set. request.referrer_policy = blink::ReferrerUtils::GetDefaultNetReferrerPolicy(); - request.resource_type = static_cast<int>(resource_type); + request.destination = destination; request.is_main_frame = - resource_type == blink::mojom::ResourceType::kMainFrame; + destination == network::mojom::RequestDestination::kDocument; return request; } @@ -241,8 +241,9 @@ browser_context(), test_ukm_id_, false)); } - GetResult RequestOrLoad(const GURL& url, ResourceType resource_type) { - return LoadURL(url, resource_type); + GetResult RequestOrLoad(const GURL& url, + network::mojom::RequestDestination destination) { + return LoadURL(url, destination); } void AddExtension(const scoped_refptr<const Extension>& extension, @@ -274,7 +275,7 @@ /*notifications_disabled=*/false); } return RequestOrLoad(extension->GetResourceURL(relative_path), - blink::mojom::ResourceType::kMainFrame); + network::mojom::RequestDestination::kDocument); } ExtensionRegistry* extension_registry() { @@ -307,8 +308,9 @@ // Load the extension. { - auto get_result = RequestOrLoad(extension->GetResourceURL("test.dat"), - blink::mojom::ResourceType::kMainFrame); + auto get_result = + RequestOrLoad(extension->GetResourceURL("test.dat"), + network::mojom::RequestDestination::kDocument); EXPECT_EQ(net::OK, get_result.result()); } } @@ -334,7 +336,8 @@ StrictMock<MockMediaRouterExtensionAccessLogger> media_router_access_logger_; private: - GetResult LoadURL(const GURL& url, ResourceType resource_type) { + GetResult LoadURL(const GURL& url, + network::mojom::RequestDestination destination) { constexpr int32_t kRoutingId = 81; constexpr int32_t kRequestId = 28; @@ -343,7 +346,7 @@ loader_factory_->CreateLoaderAndStart( loader.InitWithNewPipeAndPassReceiver(), kRoutingId, kRequestId, network::mojom::kURLLoadOptionNone, - CreateResourceRequest("GET", resource_type, url), client.CreateRemote(), + CreateResourceRequest("GET", destination, url), client.CreateRemote(), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); if (power_monitor_source_) { @@ -428,8 +431,9 @@ // It doesn't matter that the resource doesn't exist. If the resource // is blocked, we should see BLOCKED_BY_CLIENT. Otherwise, the request // should just fail because the file doesn't exist. - auto get_result = RequestOrLoad(extension->GetResourceURL("404.html"), - blink::mojom::ResourceType::kMainFrame); + auto get_result = + RequestOrLoad(extension->GetResourceURL("404.html"), + network::mojom::RequestDestination::kDocument); if (cases[i].should_allow_main_frame_load) { EXPECT_EQ(net::ERR_FILE_NOT_FOUND, get_result.result()) @@ -476,7 +480,7 @@ auto get_result = RequestOrLoad(extension->GetResourceURL("webstore_icon_16.png"), - blink::mojom::ResourceType::kMedia); + network::mojom::RequestDestination::kVideo); EXPECT_EQ(net::OK, get_result.result()); CheckForContentLengthHeader(get_result); EXPECT_EQ("image/png", get_result.GetResponseHeaderByName( @@ -493,7 +497,7 @@ auto get_result = RequestOrLoad(extension->GetResourceURL("webstore_icon_16.png"), - blink::mojom::ResourceType::kMedia); + network::mojom::RequestDestination::kVideo); EXPECT_EQ(net::OK, get_result.result()); CheckForContentLengthHeader(get_result); EXPECT_EQ("image/png", get_result.GetResponseHeaderByName( @@ -516,7 +520,7 @@ { auto get_result = RequestOrLoad(extension->GetResourceURL("test.dat"), - blink::mojom::ResourceType::kMedia); + network::mojom::RequestDestination::kVideo); EXPECT_EQ(net::OK, get_result.result()); // Check that cache-related headers are set. @@ -550,8 +554,9 @@ { blink::test::ScopedIdentifiabilityTestSampleCollector metrics; - auto get_result = RequestOrLoad(extension->GetResourceURL("test.dat"), - blink::mojom::ResourceType::kMainFrame); + auto get_result = + RequestOrLoad(extension->GetResourceURL("test.dat"), + network::mojom::RequestDestination::kDocument); EXPECT_EQ(net::OK, get_result.result()); ExpectExtensionAccessResult(extension, metrics.entries(), @@ -567,7 +572,7 @@ blink::test::ScopedIdentifiabilityTestSampleCollector metrics; auto get_result = RequestOrLoad(extension->GetResourceURL("test.dat"), - blink::mojom::ResourceType::kMedia); + network::mojom::RequestDestination::kVideo); EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, get_result.result()); ExpectExtensionAccessResult(extension, metrics.entries(), @@ -817,7 +822,7 @@ for (const auto& test_case : test_cases) { SCOPED_TRACE(test_case.file_name); auto result = RequestOrLoad(extension->GetResourceURL(test_case.file_name), - blink::mojom::ResourceType::kSubResource); + network::mojom::RequestDestination::kEmpty); EXPECT_EQ( test_case.expected_mime_type, result.GetResponseHeaderByName(net::HttpRequestHeaders::kContentType));
diff --git a/chrome/browser/external_protocol/external_protocol_handler.cc b/chrome/browser/external_protocol/external_protocol_handler.cc index e1ba4292..98ca27c 100644 --- a/chrome/browser/external_protocol/external_protocol_handler.cc +++ b/chrome/browser/external_protocol/external_protocol_handler.cc
@@ -14,6 +14,7 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/external_protocol/auto_launch_protocols_policy_handler.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" @@ -150,7 +151,7 @@ platform_util::OpenExternal( Profile::FromBrowserContext(web_contents->GetBrowserContext()), url); -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) // If the protocol navigation occurs in a new tab, close it. // Avoid calling CloseContents if the tab is not in this browser's tab strip // model; this can happen if the protocol was initiated by something @@ -192,7 +193,7 @@ bool chrome_is_default_handler = state == shell_integration::IS_DEFAULT; // On ChromeOS, Click to Call is integrated into the external protocol dialog. -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) if (web_contents && ShouldOfferClickToCallForURL( web_contents->GetBrowserContext(), escaped_url)) { // Handle tel links by opening the Click to Call dialog. This will call back
diff --git a/chrome/browser/fast_shutdown_browsertest.cc b/chrome/browser/fast_shutdown_browsertest.cc index 93edb16..c6970c1 100644 --- a/chrome/browser/fast_shutdown_browsertest.cc +++ b/chrome/browser/fast_shutdown_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -40,7 +41,8 @@ // This tests for a previous error where uninstalling an onbeforeunload handler // would enable fast shutdown even if an onunload handler still existed. // Flaky on all platforms, http://crbug.com/89173 -#if !defined(OS_CHROMEOS) // ChromeOS opens tabs instead of windows for popups. +#if !BUILDFLAG( \ + IS_CHROMEOS_ASH) // ChromeOS opens tabs instead of windows for popups. IN_PROC_BROWSER_TEST_F(FastShutdown, DISABLED_SlowTermination) { // Need to run these tests on http:// since we only allow cookies on that (and // https obviously).
diff --git a/chrome/browser/file_select_helper.cc b/chrome/browser/file_select_helper.cc index d6fe06d..72982f2 100644 --- a/chrome/browser/file_select_helper.cc +++ b/chrome/browser/file_select_helper.cc
@@ -16,6 +16,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/enterprise/connectors/common.h" #include "chrome/browser/platform_util.h" @@ -43,7 +44,7 @@ #include "chrome/browser/file_select_helper_contacts_android.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "content/public/browser/site_instance.h" #endif @@ -294,7 +295,7 @@ if (AbortIfWebContentsDestroyed()) return; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (!files.empty()) { if (!IsValidProfile(profile_)) { RunFileChooserEnd(); @@ -313,7 +314,7 @@ this)); return; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) std::vector<FileChooserFileInfoPtr> chooser_files; for (const auto& file : files) {
diff --git a/chrome/browser/first_run/first_run_internal_lacros.cc b/chrome/browser/first_run/first_run_internal_lacros.cc index 2895f7d..fc4b99d 100644 --- a/chrome/browser/first_run/first_run_internal_lacros.cc +++ b/chrome/browser/first_run/first_run_internal_lacros.cc
@@ -12,13 +12,21 @@ namespace internal { void DoPostImportPlatformSpecificTasks(Profile* profile) { - const crosapi::mojom::LacrosInitParams* init_params = - chromeos::LacrosChromeServiceImpl::Get()->init_params(); + auto* lacros_service = chromeos::LacrosChromeServiceImpl::Get(); + + // The code below is only needed for legacy ash where the metrics reporting + // API is not available. + // TODO(https://crbug.com/1155751): Remove this check and the code below when + // all lacros clients are on OS 89 or later. + if (lacros_service->IsMetricsReportingAvailable()) + return; + // Lacros skips the first run dialog because Chrome is the default browser on // Chrome OS and metrics consent is chosen during the Chrome OS out of box // setup experience. Lacros inherits first-run metrics consent from ash over // mojo. After first-run lacros handles metrics consent via settings. - ChangeMetricsReportingState(init_params->ash_metrics_enabled); + ChangeMetricsReportingState( + lacros_service->init_params()->ash_metrics_enabled); } bool ShowPostInstallEULAIfNeeded(installer::InitialPreferences* install_prefs) {
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 1c51a3bc..cd61609 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -400,7 +400,7 @@ { "name": "back-forward-cache", "owners": [ "bfcache-dev@chromium.org" ], - "expiry_milestone": 88 + "expiry_milestone": 95 }, { "name": "background-task-component-update", @@ -489,6 +489,11 @@ "expiry_milestone": 92 }, { + "name": "chrome-labs", + "owners": ["elainechien", "robliao"], + "expiry_milestone": 96 + }, + { "name": "chrome-share-highlights-android", "owners": [ "gayane" ], "expiry_milestone": 90 @@ -4262,7 +4267,11 @@ { "name": "scheduler-configuration", "owners": [ "kerrnel", "mnissler" ], - "expiry_milestone": 88 + // This flag never expires because some users need to override CPU security + // settings for performance gains, at their own risk. Chrome OS users cannot + // modify the command line, so a flag is the publicly documented mechanism + // exposed to users. + "expiry_milestone": -1 }, {"name": "schemeful-same-site", "owners": [ "bingler", "chlily" ], @@ -4596,12 +4605,12 @@ { "name": "tab-hover-card-images", "owners": [ "dfried", "corising", "//chrome/browser/ui/views/tabs/OWNERS" ], - "expiry_milestone": 88 + "expiry_milestone": 90 }, { "name": "tab-hover-cards", "owners": [ "corising", "//chrome/browser/ui/views/tabs/OWNERS" ], - "expiry_milestone": 88 + "expiry_milestone": 90 }, { "name": "tab-outlines-in-low-contrast-themes",
diff --git a/chrome/browser/flag-never-expire-list.json b/chrome/browser/flag-never-expire-list.json index 45ce580..7794f6e 100644 --- a/chrome/browser/flag-never-expire-list.json +++ b/chrome/browser/flag-never-expire-list.json
@@ -83,6 +83,7 @@ "reader-mode-heuristics", "record-web-app-debug-info", "release-notes-notification-all-channels", + "scheduler-configuration", "set-market-url-for-testing", "show-autofill-type-predictions", "show-bluetooth-debug-log-toggle",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index caf00c0..723e824 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/flag_descriptions.h" +#include "build/chromeos_buildflags.h" + // Keep in identical order as the header file, see the comment at the top // for formatting rules. @@ -320,6 +322,11 @@ "Use advanced offline capability check to decide whether the browser " "displays install prompts for PWAs."; +const char kChromeLabsName[] = "Chrome Labs"; +const char kChromeLabsDescription[] = + "Access Chrome Labs through the toolbar menu to see featured user-facing " + "experimental features."; + const char kContextMenuGoogleLensChipName[] = "Google Lens powered image search for surfaced as a chip below the context " "menu."; @@ -3275,7 +3282,8 @@ const char kSwipeToMoveCursorName[] = "Swipe to move cursor"; const char kSwipeToMoveCursorDescription[] = - "Allows user to use touch gestures to move the text cursor around."; + "Allows user to use touch gestures to move the text cursor around. This " + "flag will only take effect on Android 11 and above."; const char kTabbedAppOverflowMenuIconsName[] = "Android tabbed app overflow menu icons"; @@ -3649,7 +3657,7 @@ // Chrome OS ------------------------------------------------------------------- -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const char kAccountManagementFlowsV2Name[] = "Enable redesign of account management flows"; @@ -4678,7 +4686,7 @@ // Prefer keeping this section sorted to adding new definitions down here. -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // All views-based platforms -------------------------------------------------- @@ -4772,14 +4780,14 @@ #endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || // defined(OS_CHROMEOS) -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) const char kWebContentsOcclusionName[] = "Enable occlusion of web contents"; const char kWebContentsOcclusionDescription[] = "If enabled, web contents will behave as hidden when it is occluded by " "other windows."; -#endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_CHROMEOS) || defined(OS_LINUX) #if BUILDFLAG(USE_TCMALLOC) @@ -4790,28 +4798,30 @@ #endif // BUILDFLAG(USE_TCMALLOC) #endif // #if defined(OS_CHROMEOS) || defined(OS_LINUX) -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) const char kUserDataSnapshotName[] = "Enable user data snapshots"; const char kUserDataSnapshotDescription[] = "Enables taking snapshots of the user data directory after a Chrome " "update and restoring them after a version rollback."; -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) const char kWebShareName[] = "Web Share"; const char kWebShareDescription[] = "Enables the Web Share (navigator.share) APIs on experimentally supported " "platforms."; -#endif // defined(OS_WIN) || defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || \ +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || \ defined(OS_MAC) const char kEnableEphemeralGuestProfilesOnDesktopName[] = "Enable ephemeral Guest profiles on Desktop"; const char kEnableEphemeralGuestProfilesOnDesktopDescription[] = "Enables ephemeral Guest profiles on Windows, Linux, and Mac."; -#endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || - // defined(OS_MAC) +#endif // defined(OS_WIN) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS)) || defined(OS_MAC) // Feature flags -------------------------------------------------------------- @@ -4880,13 +4890,13 @@ "When enabled makes use of a WebUI-based tab strip."; #endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) -#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) const char kWebUITabStripTabDragIntegrationName[] = "ChromeOS drag-drop extensions for WebUI tab strip"; const char kWebUITabStripTabDragIntegrationDescription[] = "Enables special handling in ash for WebUI tab strip tab drags. Allows " "dragging tabs out to new windows."; -#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID)
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 20d2e226..6cc5eb6 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -9,6 +9,7 @@ #include "base/check_op.h" #include "build/build_config.h" #include "build/buildflag.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/buildflags.h" #include "components/nacl/common/buildflags.h" #include "components/paint_preview/buildflags/buildflags.h" @@ -198,6 +199,9 @@ extern const char kCheckOfflineCapabilityName[]; extern const char kCheckOfflineCapabilityDescription[]; +extern const char kChromeLabsName[]; +extern const char kChromeLabsDescription[]; + extern const char kContextMenuGoogleLensChipName[]; extern const char kContextMenuGoogleLensChipDescription[]; @@ -2114,7 +2118,7 @@ // Chrome OS ------------------------------------------------------------------ -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) extern const char kAccountManagementFlowsV2Name[]; extern const char kAccountManagementFlowsV2Description[]; @@ -2735,7 +2739,7 @@ // Prefer keeping this section sorted to adding new declarations down here. -#endif // #if defined(OS_CHROMEOS) +#endif // #if BUILDFLAG(IS_CHROMEOS_ASH) // All views-based platforms -------------------------------------------------- @@ -2790,12 +2794,12 @@ #endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || // defined(OS_CHROMEOS) -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) extern const char kWebContentsOcclusionName[]; extern const char kWebContentsOcclusionDescription[]; -#endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_CHROMEOS) || defined(OS_LINUX) #if BUILDFLAG(USE_TCMALLOC) @@ -2804,17 +2808,19 @@ #endif // BUILDFLAG(USE_TCMALLOC) #endif // #if defined(OS_CHROMEOS) || defined(OS_LINUX) -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) extern const char kUserDataSnapshotName[]; extern const char kUserDataSnapshotDescription[]; -#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) extern const char kWebShareName[]; extern const char kWebShareDescription[]; -#endif // defined(OS_WIN) || defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || \ +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || \ defined(OS_MAC) extern const char kEnableEphemeralGuestProfilesOnDesktopName[]; extern const char kEnableEphemeralGuestProfilesOnDesktopDescription[]; @@ -2868,10 +2874,10 @@ extern const char kWebUITabStripDescription[]; #endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) -#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) extern const char kWebUITabStripTabDragIntegrationName[]; extern const char kWebUITabStripTabDragIntegrationDescription[]; -#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && defined(OS_CHROMEOS) +#endif // BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) && BUILDFLAG(IS_CHROMEOS_ASH) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID)
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index d51a5b0..23685a01 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -77,6 +77,7 @@ &autofill::features::kAutofillRefreshStyleAndroid, &autofill::features::kAutofillEnableCardNicknameManagement, &autofill::features::kAutofillEnableGoogleIssuedCard, + &autofill::features::kAutofillEnableUIForHonorificPrefixesInSettings, &autofill_assistant::features::kAutofillAssistant, &autofill_assistant::features::kAutofillAssistantChromeEntry, &autofill_assistant::features::kAutofillAssistantDirectActions,
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index ae2742f..ffa63605 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -205,6 +205,8 @@ "AutofillEnablePasswordInfoBarAccountIndicationFooter"; public static final String AUTOFILL_ENABLE_SAVE_CARD_INFO_BAR_ACCOUNT_INDICATION_FOOTER = "AutofillEnableSaveCardInfoBarAccountIndicationFooter"; + public static final String AUTOFILL_ENABLE_UI_FOR_HONORIFIC_PREFIXES_IN_SETTINGS = + "AutofillEnableUIForHonorificPrefixesInSettings"; public static final String ADJUST_WEBAPK_INSTALLATION_SPACE = "AdjustWebApkInstallationSpace"; public static final String ANDROID_DEFAULT_BROWSER_PROMO = "AndroidDefaultBrowserPromo"; public static final String ANDROID_LAYOUT_CHANGE_TAB_REPARENT =
diff --git a/chrome/browser/focus_ring_browsertest.cc b/chrome/browser/focus_ring_browsertest.cc index 7edd7e1b..c206dddb 100644 --- a/chrome/browser/focus_ring_browsertest.cc +++ b/chrome/browser/focus_ring_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/path_service.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "cc/test/pixel_comparator.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" @@ -85,7 +86,7 @@ platform_suffix = "_mac"; #elif defined(OS_WIN) platform_suffix = "_win"; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) platform_suffix = "_chromeos"; #endif
diff --git a/chrome/browser/gcm/gcm_profile_service_unittest.cc b/chrome/browser/gcm/gcm_profile_service_unittest.cc index 948fa73..fb52bb8 100644 --- a/chrome/browser/gcm/gcm_profile_service_unittest.cc +++ b/chrome/browser/gcm/gcm_profile_service_unittest.cc
@@ -20,9 +20,10 @@ #include "chrome/test/base/testing_profile.h" #include "components/gcm_driver/gcm_profile_service.h" #include "content/public/browser/browser_task_traits.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chromeos/dbus/dbus_thread_manager.h" #endif +#include "build/chromeos_buildflags.h" #include "components/gcm_driver/fake_gcm_app_handler.h" #include "components/gcm_driver/fake_gcm_client.h" #include "components/gcm_driver/fake_gcm_client_factory.h" @@ -157,7 +158,7 @@ } void GCMProfileServiceTest::SetUp() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Create a DBus thread manager setter for its side effect. // Ignore the return value. chromeos::DBusThreadManager::GetSetterForTesting();
diff --git a/chrome/browser/google/google_brand.cc b/chrome/browser/google/google_brand.cc index 55f5263..d02397f 100644 --- a/chrome/browser/google/google_brand.cc +++ b/chrome/browser/google/google_brand.cc
@@ -13,11 +13,12 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/installer/util/google_update_settings.h" #if defined(OS_MAC) #include "chrome/browser/mac/keystone_glue.h" -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/google/google_brand_chromeos.h" #endif @@ -77,7 +78,7 @@ #if defined(OS_MAC) brand->assign(keystone_glue::BrandCode()); -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) brand->assign(google_brand::chromeos::GetBrand()); #else brand->clear(); @@ -93,7 +94,7 @@ #endif bool GetRlzBrand(std::string* brand) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) brand->assign(google_brand::chromeos::GetRlzBrand()); return true; #else
diff --git a/chrome/browser/google/google_update_settings_posix.cc b/chrome/browser/google/google_update_settings_posix.cc index a9089e6..b8784e8 100644 --- a/chrome/browser/google/google_update_settings_posix.cc +++ b/chrome/browser/google/google_update_settings_posix.cc
@@ -12,6 +12,7 @@ #include "base/synchronization/lock.h" #include "base/task/lazy_thread_pool_task_runner.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/chrome_paths.h" #include "components/crash/core/app/crashpad.h" @@ -32,7 +33,7 @@ const char kConsentToSendStats[] = "Consent To Send Stats"; void SetConsentFilePermissionIfNeeded(const base::FilePath& consent_file) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // The consent file needs to be world readable. See http://crbug.com/383003 int permissions; if (base::GetPosixFilePermissions(consent_file, &permissions) && @@ -77,7 +78,9 @@ bool GoogleUpdateSettings::SetCollectStatsConsent(bool consented) { #if defined(OS_MAC) crash_reporter::SetUploadConsent(consented); -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) if (crash_reporter::IsCrashpadEnabled()) { crash_reporter::SetUploadConsent(consented); }
diff --git a/chrome/browser/google/google_update_settings_unittest.cc b/chrome/browser/google/google_update_settings_unittest.cc index 046aef6..f1c5766e 100644 --- a/chrome/browser/google/google_update_settings_unittest.cc +++ b/chrome/browser/google/google_update_settings_unittest.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/installer/util/google_update_settings.h" #include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/path_service.h" #include "base/test/scoped_path_override.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/google/google_brand.h" #include "chrome/common/chrome_paths.h" -#include "chrome/installer/util/google_update_settings.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -79,7 +80,7 @@ #endif } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Test for http://crbug.com/383003 TEST_F(GoogleUpdateTest, ConsentFileIsWorldReadable) { // Turn on stats reporting.
diff --git a/chrome/browser/guest_view/chrome_guest_view_manager_delegate.cc b/chrome/browser/guest_view/chrome_guest_view_manager_delegate.cc index c9ae4273..bbf4848 100644 --- a/chrome/browser/guest_view/chrome_guest_view_manager_delegate.cc +++ b/chrome/browser/guest_view/chrome_guest_view_manager_delegate.cc
@@ -5,9 +5,10 @@ #include "chrome/browser/guest_view/chrome_guest_view_manager_delegate.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/task_manager/web_contents_tags.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/app_mode/app_session.h" #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h" #endif @@ -31,7 +32,7 @@ // manager. task_manager::WebContentsTags::CreateForGuestContents(guest_web_contents); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Notifies kiosk session about the added guest. chromeos::AppSession* app_session = chromeos::KioskAppManager::Get()->app_session();
diff --git a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc index 6354ea1..2cf1f2c 100644 --- a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc +++ b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc
@@ -188,7 +188,7 @@ } // namespace // Flaky on ChromeOS and Lacros (https://crbug.com/1033009) -#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) #define MAYBE_GuestDevToolsReloadsEmbedder DISABLED_GuestDevToolsReloadsEmbedder #else #define MAYBE_GuestDevToolsReloadsEmbedder GuestDevToolsReloadsEmbedder
diff --git a/chrome/browser/image_decoder/BUILD.gn b/chrome/browser/image_decoder/BUILD.gn index 101a4786..6641692 100644 --- a/chrome/browser/image_decoder/BUILD.gn +++ b/chrome/browser/image_decoder/BUILD.gn
@@ -7,6 +7,7 @@ source_set("image_decoder") { deps = [ "//base", + "//build:chromeos_buildflags", "//content/public/browser", "//ipc", "//services/data_decoder/public/cpp", @@ -34,6 +35,7 @@ deps = [ ":image_decoder", "//base", + "//build:chromeos_buildflags", "//chrome/app:generated_resources", "//chrome/test:test_support", "//chrome/test:test_support_ui",
diff --git a/chrome/browser/image_decoder/DEPS b/chrome/browser/image_decoder/DEPS index da0e266..84a3b198 100644 --- a/chrome/browser/image_decoder/DEPS +++ b/chrome/browser/image_decoder/DEPS
@@ -3,6 +3,7 @@ include_rules = [ "+base", "+build/build_config.h", + "+build/chromeos_buildflags.h", "+chrome/grit/generated_resources.h", "+chrome/test", "+content/public/browser", @@ -13,4 +14,4 @@ "+third_party/skia/include/core", "+ui/base", "+ui/gfx/geometry", -] \ No newline at end of file +]
diff --git a/chrome/browser/image_decoder/image_decoder.cc b/chrome/browser/image_decoder/image_decoder.cc index c41639c..d247b94 100644 --- a/chrome/browser/image_decoder/image_decoder.cc +++ b/chrome/browser/image_decoder/image_decoder.cc
@@ -10,6 +10,7 @@ #include "base/callback.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "ipc/ipc_channel.h" @@ -154,10 +155,10 @@ data_decoder::mojom::ImageCodec codec = data_decoder::mojom::ImageCodec::DEFAULT; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (image_codec == ROBUST_PNG_CODEC) codec = data_decoder::mojom::ImageCodec::ROBUST_PNG; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) auto callback = base::BindOnce(&OnDecodeImageDone,
diff --git a/chrome/browser/image_decoder/image_decoder.h b/chrome/browser/image_decoder/image_decoder.h index 59988b3..0b21cb5f 100644 --- a/chrome/browser/image_decoder/image_decoder.h +++ b/chrome/browser/image_decoder/image_decoder.h
@@ -14,6 +14,7 @@ #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h" +#include "build/chromeos_buildflags.h" namespace data_decoder { class DataDecoder; @@ -80,9 +81,9 @@ enum ImageCodec { DEFAULT_CODEC = 0, // Uses WebKit image decoding (via WebImage). -#if defined(OS_CHROMEOS) - ROBUST_PNG_CODEC, // Restrict decoding to robust PNG codec. -#endif // defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) + ROBUST_PNG_CODEC, // Restrict decoding to robust PNG codec. +#endif // BUILDFLAG(IS_CHROMEOS_ASH) }; static ImageDecoder* GetInstance();
diff --git a/chrome/browser/image_decoder/image_decoder_browsertest.cc b/chrome/browser/image_decoder/image_decoder_browsertest.cc index 920ef2f7..0e42aa2 100644 --- a/chrome/browser/image_decoder/image_decoder_browsertest.cc +++ b/chrome/browser/image_decoder/image_decoder_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_child_process_observer.h" @@ -110,7 +111,7 @@ EXPECT_FALSE(test_request.decode_succeeded()); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, BasicDecodeWithOptionsString) { base::RunLoop run_loop; @@ -155,7 +156,7 @@ EXPECT_FALSE(test_request.decode_succeeded()); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, BasicDecode) { base::RunLoop run_loop;
diff --git a/chrome/browser/infobars/infobars_browsertest.cc b/chrome/browser/infobars/infobars_browsertest.cc index 0e96421..98351eb 100644 --- a/chrome/browser/infobars/infobars_browsertest.cc +++ b/chrome/browser/infobars/infobars_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "build/buildflag.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/devtools/devtools_infobar_delegate.h" #include "chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h" #include "chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h" @@ -59,7 +60,7 @@ #include "sandbox/policy/switches.h" #include "ui/base/l10n/l10n_util.h" -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ui/startup/default_browser_infobar_delegate.h" #endif @@ -332,7 +333,7 @@ break; case IBD::DEFAULT_BROWSER_INFOBAR_DELEGATE: -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ADD_FAILURE() << "This infobar is not supported on this OS."; #else chrome::DefaultBrowserInfoBarDelegate::Create(GetInfoBarService(), @@ -468,7 +469,7 @@ ShowAndVerifyUi(); } -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(InfoBarUiTest, InvokeUi_default_browser) { ShowAndVerifyUi(); }
diff --git a/chrome/browser/invalidation/profile_invalidation_provider_factory.cc b/chrome/browser/invalidation/profile_invalidation_provider_factory.cc index f5baecc..2f5c2d9 100644 --- a/chrome/browser/invalidation/profile_invalidation_provider_factory.cc +++ b/chrome/browser/invalidation/profile_invalidation_provider_factory.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/gcm/gcm_profile_service_factory.h" @@ -31,7 +32,7 @@ #include "content/public/browser/storage_partition.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/files/file_path.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" @@ -72,7 +73,7 @@ // static ProfileInvalidationProvider* ProfileInvalidationProviderFactory::GetForProfile( Profile* profile) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Using ProfileHelper::GetSigninProfile() here would lead to an infinite loop // when this method is called during the creation of the sign-in profile // itself. Using ProfileHelper::GetSigninProfileDir() is safe because it does @@ -118,7 +119,7 @@ std::unique_ptr<IdentityProvider> identity_provider; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); if (user_manager::UserManager::IsInitialized() && @@ -127,7 +128,7 @@ identity_provider = std::make_unique<DeviceIdentityProvider>( DeviceOAuth2TokenServiceFactory::Get()); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) Profile* profile = Profile::FromBrowserContext(context);
diff --git a/chrome/browser/lacros/metrics_reporting_lacros_browsertest.cc b/chrome/browser/lacros/metrics_reporting_lacros_browsertest.cc new file mode 100644 index 0000000..abe5cd2 --- /dev/null +++ b/chrome/browser/lacros/metrics_reporting_lacros_browsertest.cc
@@ -0,0 +1,77 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/optional.h" +#include "base/run_loop.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/crosapi/mojom/metrics_reporting.mojom.h" +#include "chromeos/lacros/lacros_chrome_service_impl.h" +#include "content/public/test/browser_test.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" + +namespace crosapi { +namespace { + +class TestObserver : public mojom::MetricsReportingObserver { + public: + TestObserver() = default; + TestObserver(const TestObserver&) = delete; + TestObserver& operator=(const TestObserver&) = delete; + ~TestObserver() override = default; + + // crosapi::mojom::MetricsReportingObserver: + void OnMetricsReportingChanged(bool enabled) override { + metrics_enabled_ = enabled; + if (on_changed_run_loop_) + on_changed_run_loop_->Quit(); + } + + // Public because this is test code. + base::Optional<bool> metrics_enabled_; + base::RunLoop* on_changed_run_loop_ = nullptr; + mojo::Receiver<mojom::MetricsReportingObserver> receiver_{this}; +}; + +using MetricsReportingLacrosBrowserTest = InProcessBrowserTest; + +IN_PROC_BROWSER_TEST_F(MetricsReportingLacrosBrowserTest, Basics) { + auto* lacros_service = chromeos::LacrosChromeServiceImpl::Get(); + ASSERT_TRUE(lacros_service); + + // We don't assert the initial metrics state because it might vary depending + // on the ash build type (official vs. not). + const bool ash_metrics_enabled = + lacros_service->init_params()->ash_metrics_enabled; + + mojo::Remote<mojom::MetricsReporting> metrics_reporting; + lacros_service->BindMetricsReporting( + metrics_reporting.BindNewPipeAndPassReceiver()); + + // Adding an observer fires it. + base::RunLoop run_loop1; + TestObserver observer1; + observer1.on_changed_run_loop_ = &run_loop1; + metrics_reporting->AddObserver( + observer1.receiver_.BindNewPipeAndPassRemote()); + run_loop1.Run(); + ASSERT_TRUE(observer1.metrics_enabled_.has_value()); + EXPECT_EQ(ash_metrics_enabled, observer1.metrics_enabled_.value()); + + // Adding another observer fires it as well. + base::RunLoop run_loop2; + TestObserver observer2; + observer2.on_changed_run_loop_ = &run_loop2; + metrics_reporting->AddObserver( + observer2.receiver_.BindNewPipeAndPassRemote()); + run_loop2.Run(); + ASSERT_TRUE(observer2.metrics_enabled_.has_value()); + EXPECT_EQ(ash_metrics_enabled, observer2.metrics_enabled_.value()); + + // TODO(https://crbug.com/1148604): Test SetMetricsReportingConsent() once + // that function is implemented. +} + +} // namespace +} // namespace crosapi
diff --git a/chrome/browser/lacros/metrics_reporting_observer.cc b/chrome/browser/lacros/metrics_reporting_observer.cc new file mode 100644 index 0000000..939a213 --- /dev/null +++ b/chrome/browser/lacros/metrics_reporting_observer.cc
@@ -0,0 +1,36 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/lacros/metrics_reporting_observer.h" + +#include "base/bind.h" +#include "chrome/browser/metrics/metrics_reporting_state.h" +#include "chromeos/lacros/lacros_chrome_service_impl.h" + +MetricsReportingObserver::MetricsReportingObserver() = default; + +MetricsReportingObserver::~MetricsReportingObserver() = default; + +void MetricsReportingObserver::Init() { + auto* lacros_service = chromeos::LacrosChromeServiceImpl::Get(); + if (!lacros_service->IsMetricsReportingAvailable()) { + LOG(WARNING) << "MetricsReporting API not available"; + return; + } + + // Set the initial state. + ChangeMetricsReportingState( + lacros_service->init_params()->ash_metrics_enabled); + + // Add this object as an observer. The observer will fire with the current + // state in ash, to avoid races where ash might change state between the + // initial state above from lacros startup and the observer being added. + lacros_service->BindMetricsReporting( + metrics_reporting_remote_.BindNewPipeAndPassReceiver()); + metrics_reporting_remote_->AddObserver(receiver_.BindNewPipeAndPassRemote()); +} + +void MetricsReportingObserver::OnMetricsReportingChanged(bool enabled) { + ChangeMetricsReportingState(enabled); +}
diff --git a/chrome/browser/lacros/metrics_reporting_observer.h b/chrome/browser/lacros/metrics_reporting_observer.h new file mode 100644 index 0000000..6389a76 --- /dev/null +++ b/chrome/browser/lacros/metrics_reporting_observer.h
@@ -0,0 +1,36 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_LACROS_METRICS_REPORTING_OBSERVER_H_ +#define CHROME_BROWSER_LACROS_METRICS_REPORTING_OBSERVER_H_ + +#include "chromeos/crosapi/mojom/metrics_reporting.mojom.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" + +// Observes ash-chrome for changes in metrics reporting consent state. The UX +// goal is to have a single "shared" metrics reporting state across the OS and +// browser. Ash owns the canonical state, so lacros observes it for changes. +class MetricsReportingObserver + : public crosapi::mojom::MetricsReportingObserver { + public: + MetricsReportingObserver(); + MetricsReportingObserver(const MetricsReportingObserver&) = delete; + MetricsReportingObserver& operator=(const MetricsReportingObserver&) = delete; + ~MetricsReportingObserver() override; + + void Init(); + + // crosapi::mojom::MetricsObserver: + void OnMetricsReportingChanged(bool enabled) override; + + private: + // Mojo connection to ash. + mojo::Remote<crosapi::mojom::MetricsReporting> metrics_reporting_remote_; + + // Receives mojo messages from ash. + mojo::Receiver<crosapi::mojom::MetricsReportingObserver> receiver_{this}; +}; + +#endif // CHROME_BROWSER_LACROS_METRICS_REPORTING_OBSERVER_H_
diff --git a/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc b/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc index 5a18f416..1b28068 100644 --- a/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc +++ b/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc
@@ -10,6 +10,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/lite_video/lite_video_features.h" #include "chrome/browser/lite_video/lite_video_hint.h" @@ -242,7 +243,7 @@ } // Fails occasionally on ChromeOS. http://crbug.com/1102563 -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_LiteVideoCanApplyLiteVideo_NoHintForHost \ DISABLED_LiteVideoCanApplyLiteVideo_NoHintForHost #else
diff --git a/chrome/browser/loader/signed_exchange_policy_browsertest.cc b/chrome/browser/loader/signed_exchange_policy_browsertest.cc index dc18c8a..dd48fb6c 100644 --- a/chrome/browser/loader/signed_exchange_policy_browsertest.cc +++ b/chrome/browser/loader/signed_exchange_policy_browsertest.cc
@@ -4,6 +4,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ssl/cert_verifier_browser_test.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/ui_test_utils.h" @@ -76,7 +77,7 @@ policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, blacklist.Clone(), nullptr); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) policy::SetEnterpriseUsersDefaults(&policies); #endif policy_provider_.UpdateChromePolicy(policies);
diff --git a/chrome/browser/logging_chrome_unittest.cc b/chrome/browser/logging_chrome_unittest.cc index f65e1415..d1b532e0 100644 --- a/chrome/browser/logging_chrome_unittest.cc +++ b/chrome/browser/logging_chrome_unittest.cc
@@ -9,6 +9,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/env_vars.h" #include "chrome/common/logging_chrome.h" #include "content/public/common/content_switches.h" @@ -90,7 +91,7 @@ RestoreEnvironmentVariable(); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(ChromeLoggingTest, TimestampedName) { base::FilePath path = base::FilePath(FILE_PATH_LITERAL("xy.zzy")); base::FilePath timestamped_path = @@ -155,4 +156,4 @@ ::testing::MatchesRegex("^.*chrome-test-log_\\d+-\\d+$")); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/media/kaleidoscope/constants.cc b/chrome/browser/media/kaleidoscope/constants.cc index 7f39a15..af02494 100644 --- a/chrome/browser/media/kaleidoscope/constants.cc +++ b/chrome/browser/media/kaleidoscope/constants.cc
@@ -6,8 +6,12 @@ const char kKaleidoscopeUIHost[] = "kaleidoscope"; +const char kKaleidoscopeUIWatchHost[] = "watch"; + const char kKaleidoscopeUIURL[] = "chrome://kaleidoscope"; +const char kKaleidoscopeWatchUIURL[] = "chrome://watch"; + const char kKaleidoscopeUntrustedContentUIURL[] = "chrome-untrusted://kaleidoscope/";
diff --git a/chrome/browser/media/kaleidoscope/constants.h b/chrome/browser/media/kaleidoscope/constants.h index 1d2d191..955d2816 100644 --- a/chrome/browser/media/kaleidoscope/constants.h +++ b/chrome/browser/media/kaleidoscope/constants.h
@@ -7,8 +7,12 @@ extern const char kKaleidoscopeUIHost[]; +extern const char kKaleidoscopeUIWatchHost[]; + extern const char kKaleidoscopeUIURL[]; +extern const char kKaleidoscopeWatchUIURL[]; + extern const char kKaleidoscopeUntrustedContentUIURL[]; extern const char kKaleidoscopeUntrustedPALChildURL[];
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc index a04d4ff3..8f1200cc 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc
@@ -207,7 +207,7 @@ } void KaleidoscopeDataProviderImpl::SendFeedback() { - chrome::ShowFeedbackPage(GURL(kKaleidoscopeUIURL), profile_, + chrome::ShowFeedbackPage(GURL(kKaleidoscopeWatchUIURL), profile_, chrome::kFeedbackSourceKaleidoscope, std::string() /* description_template */, std::string() /* description_placeholder_text */,
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper.cc index 52e6581..8f7ce19 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper.cc
@@ -21,6 +21,12 @@ return *origin; } +const url::Origin& WatchOrigin() { + static base::NoDestructor<url::Origin> origin( + url::Origin::Create(GURL(kKaleidoscopeWatchUIURL))); + return *origin; +} + const url::Origin& KaleidoscopeUntrustedOrigin() { static base::NoDestructor<url::Origin> origin( url::Origin::Create(GURL(kKaleidoscopeUntrustedContentUIURL))); @@ -44,7 +50,8 @@ // If the tab is Kaleidoscope then we should allow autoplay. auto parent_origin = url::Origin::Create(handle->GetWebContents()->GetLastCommittedURL()); - if (parent_origin.IsSameOriginWith(KaleidoscopeOrigin())) { + if (parent_origin.IsSameOriginWith(KaleidoscopeOrigin()) || + parent_origin.IsSameOriginWith(WatchOrigin())) { return true; } @@ -91,13 +98,18 @@ !new_origin.IsSameOriginWith(KaleidoscopeOrigin()) && handle->IsInMainFrame()) { OnKaleidoscopeSessionEnded(); + } else if (current_origin.IsSameOriginWith(WatchOrigin()) && + !new_origin.IsSameOriginWith(WatchOrigin()) && + handle->IsInMainFrame()) { + OnKaleidoscopeSessionEnded(); } } void KaleidoscopeTabHelper::WebContentsDestroyed() { auto current_origin = url::Origin::Create(web_contents()->GetLastCommittedURL()); - if (current_origin.IsSameOriginWith(KaleidoscopeOrigin())) { + if (current_origin.IsSameOriginWith(KaleidoscopeOrigin()) || + current_origin.IsSameOriginWith(WatchOrigin())) { OnKaleidoscopeSessionEnded(); } }
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper_browsertest.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper_browsertest.cc index 7333c84d..96382cf1 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper_browsertest.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_tab_helper_browsertest.cc
@@ -146,6 +146,32 @@ } IN_PROC_BROWSER_TEST_F(KaleidoscopeTabHelperBrowserTest, + SessionMetric_OpenedRecommendation_Watch) { + const GURL kTestPageUrl = embedded_test_server()->GetURL(kTestPagePath); + + { + // Navigate to Kaleidoscope. + NavigateParams params(browser(), GURL(kKaleidoscopeWatchUIURL), + ui::PAGE_TRANSITION_LINK); + ui_test_utils::NavigateToURL(¶ms); + } + + // Simulate a playback. + KaleidoscopeTabHelper::FromWebContents(GetWebContents())->MarkAsSuccessful(); + + { + // Navigate away from Kaleidoscope. + NavigateParams params(browser(), kTestPageUrl, ui::PAGE_TRANSITION_LINK); + ui_test_utils::NavigateToURL(¶ms); + } + + histogram_tester_.ExpectBucketCount( + KaleidoscopeTabHelper:: + kKaleidoscopeOpenedMediaRecommendationHistogramName, + true, 1); +} + +IN_PROC_BROWSER_TEST_F(KaleidoscopeTabHelperBrowserTest, SessionMetric_DidNotOpenRecommendation) { const GURL kTestPageUrl = embedded_test_server()->GetURL(kTestPagePath);
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_ui.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_ui.cc index 66909e08..58426ef 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_ui.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_ui.cc
@@ -204,58 +204,7 @@ std::move(callback).Run(ref_contents); } -content::WebUIDataSource* CreateUntrustedPALChildWebUIDataSource() { - content::WebUIDataSource* untrusted_source = - content::WebUIDataSource::Create(kKaleidoscopeUntrustedPALChildURL); - untrusted_source->DisableDenyXFrameOptions(); - - // Allow scripts from Google. - untrusted_source->OverrideContentSecurityPolicy( - network::mojom::CSPDirectiveName::ScriptSrc, - "script-src https://imasdk.googleapis.com 'unsafe-inline' 'self';"); - untrusted_source->DisableTrustedTypesCSP(); - -#if BUILDFLAG(ENABLE_KALEIDOSCOPE) - untrusted_source->AddResourcePath("pal-child.html", - IDR_KALEIDOSCOPE_PAL_CHILD_HTML); - untrusted_source->AddResourcePath("pal-child.js", - IDR_KALEIDOSCOPE_PAL_CHILD_JS); -#endif // BUILDFLAG(ENABLE_KALEIDOSCOPE) - - return untrusted_source; -} - -} // anonymous namespace - -// We set |enable_chrome_send| to true since we need it for browser tests. -KaleidoscopeUI::KaleidoscopeUI(content::WebUI* web_ui) - : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) { - web_ui->AddRequestableScheme(content::kChromeUIUntrustedScheme); - - auto* browser_context = web_ui->GetWebContents()->GetBrowserContext(); - content::WebUIDataSource::Add(browser_context, CreateWebUIDataSource()); - content::WebUIDataSource::Add(browser_context, - CreateUntrustedWebUIDataSource()); - content::WebUIDataSource::Add(browser_context, - CreateUntrustedPALChildWebUIDataSource()); -} - -KaleidoscopeUI::~KaleidoscopeUI() { - if (metrics_recorder_) - metrics_recorder_->OnExitPage(); - - // Ensure that the provider is deleted before the metrics recorder, since the - // provider has a pointer to the metrics recorder. - provider_.reset(); - metrics_recorder_.reset(); - identity_manager_.reset(); -} - -// static -content::WebUIDataSource* KaleidoscopeUI::CreateWebUIDataSource() { - content::WebUIDataSource* html_source = - content::WebUIDataSource::Create(kKaleidoscopeUIHost); - +void ConfigureMainFrameWebUIDataSource(content::WebUIDataSource* html_source) { // Allows us to put content in an IFrame. html_source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ChildSrc, @@ -307,7 +256,68 @@ #endif // BUILDFLAG(ENABLE_KALEIDOSCOPE) html_source->AddResourcePath("module.js", IDR_KALEIDOSCOPE_NTP_MODULE_JS); +} +content::WebUIDataSource* CreateUntrustedPALChildWebUIDataSource() { + content::WebUIDataSource* untrusted_source = + content::WebUIDataSource::Create(kKaleidoscopeUntrustedPALChildURL); + untrusted_source->DisableDenyXFrameOptions(); + + // Allow scripts from Google. + untrusted_source->OverrideContentSecurityPolicy( + network::mojom::CSPDirectiveName::ScriptSrc, + "script-src https://imasdk.googleapis.com 'unsafe-inline' 'self';"); + untrusted_source->DisableTrustedTypesCSP(); + +#if BUILDFLAG(ENABLE_KALEIDOSCOPE) + untrusted_source->AddResourcePath("pal-child.html", + IDR_KALEIDOSCOPE_PAL_CHILD_HTML); + untrusted_source->AddResourcePath("pal-child.js", + IDR_KALEIDOSCOPE_PAL_CHILD_JS); +#endif // BUILDFLAG(ENABLE_KALEIDOSCOPE) + + return untrusted_source; +} + +} // anonymous namespace + +// We set |enable_chrome_send| to true since we need it for browser tests. +KaleidoscopeUI::KaleidoscopeUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) { + web_ui->AddRequestableScheme(content::kChromeUIUntrustedScheme); + + auto* browser_context = web_ui->GetWebContents()->GetBrowserContext(); + content::WebUIDataSource::Add(browser_context, CreateWebUIDataSource()); + content::WebUIDataSource::Add(browser_context, CreateWatchDataSource()); + content::WebUIDataSource::Add(browser_context, + CreateUntrustedWebUIDataSource()); + content::WebUIDataSource::Add(browser_context, + CreateUntrustedPALChildWebUIDataSource()); +} + +KaleidoscopeUI::~KaleidoscopeUI() { + if (metrics_recorder_) + metrics_recorder_->OnExitPage(); + + // Ensure that the provider is deleted before the metrics recorder, since the + // provider has a pointer to the metrics recorder. + provider_.reset(); + metrics_recorder_.reset(); + identity_manager_.reset(); +} + +// static +content::WebUIDataSource* KaleidoscopeUI::CreateWebUIDataSource() { + auto* html_source = content::WebUIDataSource::Create(kKaleidoscopeUIHost); + ConfigureMainFrameWebUIDataSource(html_source); + return html_source; +} + +// static +content::WebUIDataSource* KaleidoscopeUI::CreateWatchDataSource() { + auto* html_source = + content::WebUIDataSource::Create(kKaleidoscopeUIWatchHost); + ConfigureMainFrameWebUIDataSource(html_source); return html_source; }
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_ui.h b/chrome/browser/media/kaleidoscope/kaleidoscope_ui.h index 413edd7..174b943 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_ui.h +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_ui.h
@@ -30,6 +30,8 @@ static content::WebUIDataSource* CreateWebUIDataSource(); + static content::WebUIDataSource* CreateWatchDataSource(); + static content::WebUIDataSource* CreateUntrustedWebUIDataSource(); private:
diff --git a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc index 20a9adb2..9988d55 100644 --- a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc +++ b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc
@@ -6,10 +6,11 @@ #include "base/memory/memory_pressure_monitor.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/memory/enterprise_memory_limit_pref_observer.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/logging.h" #include "base/system/sys_info.h" #include "chromeos/memory/pressure/system_memory_pressure_evaluator.h" @@ -29,7 +30,7 @@ g_browser_process->local_state()); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::SysInfo::IsRunningOnChromeOS()) { cros_evaluator_ = std::make_unique<chromeos::memory::SystemMemoryPressureEvaluator>( @@ -47,7 +48,7 @@ // pref_service. memory_limit_pref_observer_.reset(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) cros_evaluator_.reset(); #endif }
diff --git a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h index 57ffacf..1c8b902 100644 --- a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h +++ b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h
@@ -8,9 +8,10 @@ #include <memory> #include "base/macros.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) namespace chromeos { namespace memory { class SystemMemoryPressureEvaluator; @@ -42,7 +43,7 @@ std::unique_ptr<memory::EnterpriseMemoryLimitPrefObserver> memory_limit_pref_observer_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<chromeos::memory::SystemMemoryPressureEvaluator> cros_evaluator_; #endif
diff --git a/chrome/browser/memory/oom_memory_details.cc b/chrome/browser/memory/oom_memory_details.cc index 81e0af8..2919d43 100644 --- a/chrome/browser/memory/oom_memory_details.cc +++ b/chrome/browser/memory/oom_memory_details.cc
@@ -35,7 +35,7 @@ // These logs are collected by user feedback reports. We want them to help // diagnose user-reported problems with frequently discarded tabs. std::string log_string = ToLogString(/*include_tab_title=*/false); -#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS) +#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) base::GraphicsMemoryInfoKB gpu_meminfo; if (base::GetGraphicsMemoryInfo(&gpu_meminfo)) { log_string +=
diff --git a/chrome/browser/memory_details.h b/chrome/browser/memory_details.h index c2ae7f5f..38520cf2 100644 --- a/chrome/browser/memory_details.h +++ b/chrome/browser/memory_details.h
@@ -16,6 +16,7 @@ #include "base/strings/string16.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "content/public/common/process_type.h" namespace memory_instrumentation { @@ -141,7 +142,7 @@ // Returns a pointer to the ProcessData structure for Chrome. ProcessData* ChromeBrowser(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const base::SwapInfo& swap_info() const { return swap_info_; } #endif @@ -172,7 +173,7 @@ std::vector<ProcessData> process_data_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::SwapInfo swap_info_; #endif
diff --git a/chrome/browser/memory_details_linux.cc b/chrome/browser/memory_details_linux.cc index 090e05f7..a1360023 100644 --- a/chrome/browser/memory_details_linux.cc +++ b/chrome/browser/memory_details_linux.cc
@@ -21,6 +21,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/chrome_constants.h" #include "chrome/grit/chromium_strings.h" #include "content/public/browser/browser_task_traits.h" @@ -137,7 +138,7 @@ process_data_.push_back(current_browser); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::GetSwapInfo(&swap_info_); #endif
diff --git a/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc b/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc index c5b5dc9..5abe450 100644 --- a/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc +++ b/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ppapi/ppapi_test.h" #include "components/nacl/browser/nacl_browser.h" @@ -82,7 +83,8 @@ #if defined(ADDRESS_SANITIZER) # define MAYBE_Breakpoint DISABLED_Breakpoint -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY) +#elif (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && \ + defined(ARCH_CPU_ARM_FAMILY) // Timing out on ARM linux: http://crbug.com/238469 # define MAYBE_Breakpoint DISABLED_Breakpoint #else
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc b/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc index d864ea47..3620dda 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc +++ b/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/navigation_predictor/navigation_predictor.h" #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service.h" #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service_factory.h" @@ -263,7 +264,7 @@ // Disabled because it fails when SingleProcessMash feature is enabled. Since // Navigation Predictor is not going to be enabled on Chrome OS, disabling the // browser test on that platform is fine. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_CHROMEOS(x) x
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_features.cc b/chrome/browser/navigation_predictor/navigation_predictor_features.cc index 03e0d6d..37a1fe35 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor_features.cc +++ b/chrome/browser/navigation_predictor/navigation_predictor_features.cc
@@ -24,11 +24,6 @@ "NavigationPredictorEnablePreconnectOnSameDocumentNavigations", base::FEATURE_DISABLED_BY_DEFAULT}; -// Used for controlling the navigation predictor based preconnect experiments. -const base::Feature kNavigationPredictorPreconnectSocketCompletionTime{ - "NavigationPredictorPreconnectSocketCompletionTime", - base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kNavigationPredictorRendererWarmup{ "NavigationPredictorRendererWarmup", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_features.h b/chrome/browser/navigation_predictor/navigation_predictor_features.h index 6d277ea..97dcfcf3 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor_features.h +++ b/chrome/browser/navigation_predictor/navigation_predictor_features.h
@@ -14,7 +14,6 @@ extern const base::Feature kNavigationPredictorPreconnectHoldback; extern const base::Feature kNavigationPredictorEnablePreconnectOnSameDocumentNavigations; -extern const base::Feature kNavigationPredictorPreconnectSocketCompletionTime; extern const base::Feature kNavigationPredictorRendererWarmup; } // namespace features
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_preconnect_client.cc b/chrome/browser/navigation_predictor/navigation_predictor_preconnect_client.cc index fc996327..b542ccc 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor_preconnect_client.cc +++ b/chrome/browser/navigation_predictor/navigation_predictor_preconnect_client.cc
@@ -179,10 +179,7 @@ // The delay beyond the idle socket timeout that net uses when // re-preconnecting. If negative, no retries occur. - const base::TimeDelta retry_delay = - base::TimeDelta::FromMilliseconds(base::GetFieldTrialParamByFeatureAsInt( - features::kNavigationPredictorPreconnectSocketCompletionTime, - "preconnect_socket_completion_time_msec", 50)); + const base::TimeDelta retry_delay = base::TimeDelta::FromMilliseconds(50); // Set/Reset the timer to fire after the preconnect times out. Add an extra // delay to make sure the preconnect has expired if it wasn't used.
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_renderer_warmup_client_browsertest.cc b/chrome/browser/navigation_predictor/navigation_predictor_renderer_warmup_client_browsertest.cc index 5241b482..2a602984 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor_renderer_warmup_client_browsertest.cc +++ b/chrome/browser/navigation_predictor/navigation_predictor_renderer_warmup_client_browsertest.cc
@@ -4,6 +4,7 @@ #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service.h" #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -31,7 +32,7 @@ } // Occasional flakes on Windows (https://crbug.com/1045971). -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/navigation_predictor/search_engine_preconnector.cc b/chrome/browser/navigation_predictor/search_engine_preconnector.cc index a99cac69c..04c0c9d0 100644 --- a/chrome/browser/navigation_predictor/search_engine_preconnector.cc +++ b/chrome/browser/navigation_predictor/search_engine_preconnector.cc
@@ -106,10 +106,7 @@ // The delay beyond the idle socket timeout that net uses when // re-preconnecting. If negative, no retries occur. - const base::TimeDelta retry_delay = - base::TimeDelta::FromMilliseconds(base::GetFieldTrialParamByFeatureAsInt( - features::kNavigationPredictorPreconnectSocketCompletionTime, - "preconnect_socket_completion_time_msec", 50)); + const base::TimeDelta retry_delay = base::TimeDelta::FromMilliseconds(50); // Set/Reset the timer to fire after the preconnect times out. Add an extra // delay to make sure the preconnect has expired if it wasn't used.
diff --git a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc index 99a3c6b..b6e61b1d 100644 --- a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc
@@ -326,7 +326,11 @@ /*total_bytes=*/0, /*bytes_transferred=*/0), /*upgraded_medium=*/base::nullopt); - payload_status_listeners_.erase(it); + + // Erase using the payload ID key instead of the iterator. The + // OnStatusUpdate() call might result in iterator invalidation, for example, + // if the listener map entry is removed during a resulting payload clean-up. + payload_status_listeners_.erase(payload_id); } nearby_connections_->CancelPayload( kServiceId, payload_id, @@ -345,11 +349,7 @@ std::vector<PayloadPtr> payloads; for (auto& it : incoming_payloads_) { payloads.push_back(std::move(it.second)); - // Make sure to clean up the raw pointer to the payload listener. - auto listener_it = payload_status_listeners_.find(it.first); - if (listener_it != payload_status_listeners_.end()) { - payload_status_listeners_.erase(listener_it); - } + payload_status_listeners_.erase(it.first); } file_handler_.ReleaseFilePayloads(std::move(payloads));
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index da35f7e..27f0afe6 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -762,11 +762,10 @@ } void NearbySharingServiceImpl::DoCancel( - const ShareTarget& share_target, + ShareTarget share_target, StatusCodesCallback status_codes_callback, bool write_cancel_frame) { ShareTargetInfo* info = GetShareTargetInfo(share_target); - if (!info || !info->endpoint_id()) { NS_LOG(ERROR) << __func__ << ": Cancel invoked for unknown share target, returning " @@ -777,18 +776,13 @@ return; } - // We immediately inform the user that the transfer has been cancelled because - // subsequent disconnections might be interpreted as failure. The - // TransferUpdateDecorator will ignore subsequent statuses in favor of this - // cancelled status. - if (info->transfer_update_callback()) { - info->transfer_update_callback()->OnTransferUpdate( - share_target, TransferMetadataBuilder() - .set_status(TransferMetadata::Status::kCancelled) - .build()); - } - - // Before disconnecting, cancel all ongoing payloads. + // Cancel all ongoing payload transfers before invoking the transfer update + // callback. Invoking the transfer update callback first could result in + // payload cleanup before we have a chance to cancel the payload via Nearby + // Connections, and the payload tracker might not receive the expected + // cancellation signals. Also, note that there might not be any ongoing + // payload transfer, for example, if a connection has not been established + // yet. for (int64_t attachment_id : share_target.GetAttachmentIds()) { base::Optional<int64_t> payload_id = GetAttachmentPayloadId(attachment_id); if (payload_id) { @@ -796,15 +790,29 @@ } } - // If a connection exists, close the connection. Otherwise disconnect from + // Inform the user that the transfer has been cancelled before disconnecting + // because subsequent disconnections might be interpreted as failure. The + // TransferUpdateDecorator will ignore subsequent statuses in favor of this + // cancelled status. Note that the transfer update callback might have already + // been invoked as a result of the payload cancellations above, but again, + // superfluous status updates are handled gracefully by the + // TransferUpdateDecorator. + if (info->transfer_update_callback()) { + info->transfer_update_callback()->OnTransferUpdate( + share_target, TransferMetadataBuilder() + .set_status(TransferMetadata::Status::kCancelled) + .build()); + } + + // If a connection exists, close the connection after a short delay that + // allows for final processing by the other device. Otherwise, disconnect from // endpoint id directly. Note: A share attempt can be cancelled by the user - // before a connection is fully established, so info->connection() might be - // null. + // before a connection is fully established, in which case, info->connection() + // will be null. if (info->connection()) { info->connection()->SetDisconnectionListener( base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget, weak_ptr_factory_.GetWeakPtr(), share_target)); - base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&NearbySharingServiceImpl::CloseConnection, @@ -816,6 +824,7 @@ } } else { nearby_connections_manager_->Disconnect(*info->endpoint_id()); + UnregisterShareTarget(share_target); } std::move(status_codes_callback).Run(StatusCodes::kOk); @@ -3224,7 +3233,11 @@ if (info && info->transfer_update_callback()) info->transfer_update_callback()->OnTransferUpdate(share_target, metadata); - if (TransferMetadata::IsFinalStatus(metadata.status())) { + // Cancellation has its own disconnection strategy, possibly adding a delay + // before disconnection to provide the other party time to process the + // cancellation. + if (TransferMetadata::IsFinalStatus(metadata.status()) && + metadata.status() != TransferMetadata::Status::kCancelled) { Disconnect(share_target, metadata); } } @@ -3400,8 +3413,9 @@ info.set_endpoint_id(endpoint_id); return info; } else { - // We need to explicitly remove any previous share target for |endpoint_id| - // if one exists, notifying observers that a share target is lost. + // We need to explicitly remove any previous share target for + // |endpoint_id| if one exists, notifying observers that a share target is + // lost. const auto it = outgoing_share_target_map_.find(endpoint_id); if (it != outgoing_share_target_map_.end() && it->second.id != share_target.id) {
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h index 77c20b7..75d6879 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h
@@ -325,7 +325,10 @@ NearbyConnectionsManager::ConnectionsStatus status); void SetInHighVisibility(bool in_high_visibility); - void DoCancel(const ShareTarget& share_target, + // Note: |share_target| is intentionally passed by value. A share target + // reference could likely be invalidated by the owner during the multi-step + // cancellation process. + void DoCancel(ShareTarget share_target, StatusCodesCallback status_codes_callback, bool write_cancel_frame);
diff --git a/chrome/browser/nearby_sharing/payload_tracker.cc b/chrome/browser/nearby_sharing/payload_tracker.cc index 25972f7..217ee0e 100644 --- a/chrome/browser/nearby_sharing/payload_tracker.cc +++ b/chrome/browser/nearby_sharing/payload_tracker.cc
@@ -67,13 +67,20 @@ last_upgraded_medium_ = upgraded_medium; } - it->second.amount_transferred = update->bytes_transferred; if (it->second.status != update->status) { it->second.status = update->status; NS_LOG(VERBOSE) << __func__ << ": Payload id " << update->payload_id << " had status change: " << update->status; } + + // The number of bytes transferred should never go down. That said, some + // status updates like cancellation might send a value of 0. In that case, we + // retain the last known value for use in metrics. + if (update->bytes_transferred > it->second.amount_transferred) { + it->second.amount_transferred = update->bytes_transferred; + } + OnTransferUpdate(); }
diff --git a/chrome/browser/net/profile_network_context_service_browsertest.cc b/chrome/browser/net/profile_network_context_service_browsertest.cc index 4b55e9e69..d422868 100644 --- a/chrome/browser/net/profile_network_context_service_browsertest.cc +++ b/chrome/browser/net/profile_network_context_service_browsertest.cc
@@ -69,7 +69,7 @@ #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chromeos/constants/chromeos_features.h" #endif @@ -657,7 +657,7 @@ ::testing::Bool()); #endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) class ProfileNetworkContextServiceMemoryPressureFeatureBrowsertest : public ProfileNetworkContextServiceBrowsertest, public ::testing::WithParamInterface<base::Optional<bool>> { @@ -710,4 +710,4 @@ ProfileNetworkContextServiceMemoryPressureFeatureBrowsertest, /*disable_idle_sockets_close_on_memory_pressure=*/ ::testing::Values(base::nullopt, true, false)); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/optimization_guide/hints_fetcher_browsertest.cc b/chrome/browser/optimization_guide/hints_fetcher_browsertest.cc index 4d5b404..18688e5 100644 --- a/chrome/browser/optimization_guide/hints_fetcher_browsertest.cc +++ b/chrome/browser/optimization_guide/hints_fetcher_browsertest.cc
@@ -16,6 +16,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" @@ -551,7 +552,7 @@ // Issues with multiple profiles likely cause the site engagement service-based // tests to flake. -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/optimization_guide/optimization_guide_keyed_service_browsertest.cc b/chrome/browser/optimization_guide/optimization_guide_keyed_service_browsertest.cc index e482b31a..027267b 100644 --- a/chrome/browser/optimization_guide/optimization_guide_keyed_service_browsertest.cc +++ b/chrome/browser/optimization_guide/optimization_guide_keyed_service_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/optimization_guide/optimization_guide_hints_manager.h" @@ -313,7 +314,7 @@ // ChromeOS has multiple profiles and optimization guide currently does not // run on non-Android. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) histogram_tester()->ExpectUniqueSample( "OptimizationGuide.RemoteFetchingEnabled", false, 1); EXPECT_TRUE(IsInSyntheticTrialGroup( @@ -609,7 +610,7 @@ // ChromeOS has multiple profiles and optimization guide currently does not // run on non-Android. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) histogram_tester()->ExpectUniqueSample( "OptimizationGuide.RemoteFetchingEnabled", true, 1); EXPECT_TRUE(IsInSyntheticTrialGroup( @@ -643,7 +644,7 @@ // ChromeOS has multiple profiles and optimization guide currently does not // run on non-Android. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) histogram_tester()->ExpectUniqueSample( "OptimizationGuide.RemoteFetchingEnabled", true, 1); EXPECT_TRUE(IsInSyntheticTrialGroup(
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc index 25560f6..77e6841 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/download/download_service_factory.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" @@ -451,7 +452,7 @@ } }; -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc b/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc index 935e8ad1..5b03fba 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc
@@ -14,6 +14,7 @@ #include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/optimization_guide/optimization_guide_navigation_data.h" #include "chrome/browser/optimization_guide/optimization_guide_web_contents_observer.h" #include "chrome/browser/optimization_guide/prediction/prediction_model_download_manager.h" @@ -616,7 +617,7 @@ }; // No support for Mac, Windows or ChromeOS. -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_observer_unittest.cc index e7ddeee..5e6afc4 100644 --- a/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/signed_exchange_page_load_metrics_observer_unittest.cc
@@ -7,6 +7,7 @@ #include <memory> #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" #include "components/page_load_metrics/browser/page_load_tracker.h" #include "components/page_load_metrics/common/test/page_load_metrics_test_util.h" @@ -318,7 +319,10 @@ } // Test is flaky on linux_tsan: crbug.com:1082135. -#if defined(OS_LINUX) && defined(THREAD_SANITIZER) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && \ + defined(THREAD_SANITIZER) #define MAYBE_WithSignedExchangeBackground DISABLED_WithSignedExchangeBackground #else #define MAYBE_WithSignedExchangeBackground WithSignedExchangeBackground
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc index d154380..3aee84d 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc
@@ -24,6 +24,7 @@ #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer.h" #include "chrome/browser/page_load_metrics/observers/core/ukm_page_load_metrics_observer.h" #include "chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer.h" @@ -1931,7 +1932,7 @@ SessionStartupPref::SetStartupPref( profile, SessionStartupPref(SessionStartupPref::LAST)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) SessionServiceTestHelper helper( SessionServiceFactory::GetForProfile(profile)); helper.SetForceBrowserNotAliveWithNoWindows(true);
diff --git a/chrome/browser/payments/BUILD.gn b/chrome/browser/payments/BUILD.gn index e65c431..9bf49781 100644 --- a/chrome/browser/payments/BUILD.gn +++ b/chrome/browser/payments/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromeos/ui_mode.gni") + source_set("browser_tests") { testonly = true @@ -37,6 +39,7 @@ deps = [ "//base/test:test_support", + "//build:chromeos_buildflags", "//chrome/test:test_support", "//chrome/test/payments:test_support", "//components/payments/content", @@ -71,7 +74,7 @@ ] } - if (is_chromeos) { + if (is_chromeos_ash) { deps += [ "//ash/public/cpp/external_arc:external_arc" ] } }
diff --git a/chrome/browser/payments/android_payment_app_factory_browsertest.cc b/chrome/browser/payments/android_payment_app_factory_browsertest.cc index 876a63c..58efbcd 100644 --- a/chrome/browser/payments/android_payment_app_factory_browsertest.cc +++ b/chrome/browser/payments/android_payment_app_factory_browsertest.cc
@@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#if defined(OS_CHROMEOS) +#include "build/chromeos_buildflags.h" + +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/external_arc/overlay/arc_overlay_manager.h" #endif #include "base/test/scoped_feature_list.h" @@ -48,7 +50,7 @@ // goods purchase. IN_PROC_BROWSER_TEST_F(AndroidPaymentAppFactoryTest, IgnoreOtherPaymentAppsInTwaWhenHaveAppStoreBilling) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ash::ArcOverlayManager overlay_manager_; #endif @@ -71,11 +73,11 @@ test_controller()->SetTwaPaymentApp("https://play.google.com/billing", "{\"status\": \"" + response + "\"}"); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::string expected_response = response; #else std::string expected_response = "success"; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) NavigateTo("b.com", "/payment_handler_status.html"); ASSERT_EQ(expected_response,
diff --git a/chrome/browser/payments/chrome_payment_request_delegate.cc b/chrome/browser/payments/chrome_payment_request_delegate.cc index ec4904a..dbe37e4f 100644 --- a/chrome/browser/payments/chrome_payment_request_delegate.cc +++ b/chrome/browser/payments/chrome_payment_request_delegate.cc
@@ -9,6 +9,7 @@ #include "base/check_op.h" #include "base/memory/ref_counted.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/autofill/address_normalizer_factory.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/autofill/validation_rules_storage_factory.h" @@ -42,9 +43,9 @@ #include "third_party/libaddressinput/chromium/chrome_metadata_source.h" #include "third_party/libaddressinput/chromium/chrome_storage_impl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/apps/apk_web_app_service.h" -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace payments { @@ -261,7 +262,7 @@ } std::string ChromePaymentRequestDelegate::GetTwaPackageName() const { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) auto* rfh = content::RenderFrameHost::FromID(frame_routing_id_); if (!rfh || !rfh->IsCurrent()) return ""; @@ -279,7 +280,7 @@ return twa_package_name.has_value() ? twa_package_name.value() : ""; #else return ""; -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } PaymentRequestDialog* ChromePaymentRequestDelegate::GetDialogForTesting() {
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index fd0d78b..5e75a7c9 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -30,6 +30,7 @@ #include "base/threading/thread_restrictions.h" #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/extensions/component_loader.h" @@ -1038,7 +1039,7 @@ RunTestsInJsModule("redirects_fail_test.js", "test.pdf"); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_P(PDFExtensionJSTest, Printing) { RunTestsInJsModule("printing_icon_test.js", "test.pdf"); } @@ -1059,7 +1060,7 @@ // elements without loading a PDF is difficult. RunTestsInJsModule("annotations_toolbar_test.js", "test.pdf"); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) INSTANTIATE_TEST_SUITE_P(/* no prefix */, PDFExtensionJSTest, testing::Bool()); @@ -2156,7 +2157,9 @@ // Runs `action` and checks the Linux selection clipboard contains `expected`. void DoActionAndCheckSelectionClipboard(base::OnceClosure action, const std::string& expected) { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) DoActionAndCheckClipboard(std::move(action), ui::ClipboardBuffer::kSelection, expected); #else @@ -2286,7 +2289,9 @@ } // Flaky on ChromeOS (https://crbug.com/1121446) -#if defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #define MAYBE_CombinedShiftArrowPresses DISABLED_CombinedShiftArrowPresses #else #define MAYBE_CombinedShiftArrowPresses CombinedShiftArrowPresses @@ -2442,7 +2447,7 @@ } // Flaky on ChromeOS (https://crbug.com/922974) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_TouchscreenPinchInvokesCustomZoom \ DISABLED_TouchscreenPinchInvokesCustomZoom #else
diff --git a/chrome/browser/pdf/pdf_extension_util.cc b/chrome/browser/pdf/pdf_extension_util.cc index a6d491e7..398404c8 100644 --- a/chrome/browser/pdf/pdf_extension_util.cc +++ b/chrome/browser/pdf/pdf_extension_util.cc
@@ -6,6 +6,7 @@ #include "base/strings/string_util.h" #include "base/values.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_content_client.h" #include "chrome/grit/browser_resources.h" @@ -17,9 +18,9 @@ #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/login/ui/login_display_host.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace pdf_extension_util { @@ -72,7 +73,7 @@ {"tooltipRotateCW", IDS_PDF_TOOLTIP_ROTATE_CW}, {"tooltipThumbnails", IDS_PDF_TOOLTIP_THUMBNAILS}, {"zoomTextInputAriaLabel", IDS_PDF_ZOOM_TEXT_INPUT_ARIA_LABEL}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) {"tooltipAnnotate", IDS_PDF_ANNOTATION_ANNOTATE}, {"annotationDocumentTooLarge", IDS_PDF_ANNOTATION_DOCUMENT_TOO_LARGE}, {"annotationDocumentProtected", IDS_PDF_ANNOTATION_DOCUMENT_PROTECTED}, @@ -129,12 +130,12 @@ {"annotationFormWarningDetail", IDS_PDF_DISCARD_FORM_CHANGES_DETAIL}, {"annotationFormWarningKeepEditing", IDS_PDF_KEEP_EDITING}, {"annotationFormWarningDiscard", IDS_PDF_DISCARD}, -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) }; for (const auto& resource : kPdfResources) dict->SetStringKey(resource.name, l10n_util::GetStringUTF16(resource.id)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::string16 edit_string = l10n_util::GetStringUTF16(IDS_EDIT); base::Erase(edit_string, '&'); dict->SetStringKey("editButton", edit_string); @@ -185,11 +186,11 @@ bool enable_printing = true; bool enable_annotations = false; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // For Chrome OS, enable printing only if we are not at OOBE. enable_printing = !chromeos::LoginDisplayHost::default_host(); enable_annotations = true; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) dict->SetKey("printingEnabled", base::Value(enable_printing)); dict->SetKey("pdfAnnotationsEnabled", base::Value(enable_annotations)); }
diff --git a/chrome/browser/permissions/chrome_permission_request_manager_unittest.cc b/chrome/browser/permissions/chrome_permission_request_manager_unittest.cc index 1d68e5f..1da3082 100644 --- a/chrome/browser/permissions/chrome_permission_request_manager_unittest.cc +++ b/chrome/browser/permissions/chrome_permission_request_manager_unittest.cc
@@ -15,6 +15,7 @@ #include "base/test/simple_test_clock.h" #include "base/util/values/values_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/permissions/adaptive_quiet_notification_permission_ui_enabler.h" #include "chrome/browser/permissions/quiet_notification_permission_ui_config.h" @@ -40,7 +41,7 @@ #include "components/user_manager/scoped_user_manager.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/app_mode/web_app/web_kiosk_app_manager.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #endif @@ -113,7 +114,7 @@ manager_->NavigationEntryCommitted(details); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<permissions::MockPermissionRequest> MakeRequestInWebKioskMode( const GURL& url, const GURL& app_url) { @@ -638,7 +639,7 @@ recorded_time); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(ChromePermissionRequestManagerTest, TestWebKioskModeSameOrigin) { auto request = MakeRequestInWebKioskMode(/*url*/ GURL("https://google.com/page"), @@ -659,4 +660,4 @@ EXPECT_FALSE(request->granted()); EXPECT_TRUE(request->finished()); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/permissions/chrome_permissions_client.cc b/chrome/browser/permissions/chrome_permissions_client.cc index 38193575..3b123183 100644 --- a/chrome/browser/permissions/chrome_permissions_client.cc +++ b/chrome/browser/permissions/chrome_permissions_client.cc
@@ -8,6 +8,7 @@ #include "base/feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/bluetooth/bluetooth_chooser_context.h" #include "chrome/browser/bluetooth/bluetooth_chooser_context_factory.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" @@ -52,7 +53,7 @@ #include "chrome/browser/ui/permission_bubble/permission_prompt.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/app_mode/web_app/web_kiosk_app_data.h" #include "chrome/browser/chromeos/app_mode/web_app/web_kiosk_app_manager.h" #include "components/user_manager/user.h" @@ -156,7 +157,7 @@ } } -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) // Some Google-affiliated domains are not allowed to delete cookies for // supervised accounts. bool ChromePermissionsClient::IsCookieDeletionDisabled( @@ -191,7 +192,7 @@ permissions::PermissionRequest::IconId ChromePermissionsClient::GetOverrideIconId(ContentSettingsType type) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // TODO(xhwang): fix this icon, see crbug.com/446263. if (type == ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER) return kProductIcon; @@ -263,7 +264,7 @@ } base::Optional<url::Origin> ChromePermissionsClient::GetAutoApprovalOrigin() { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // In web kiosk mode, all permission requests are auto-approved for the origin // of the main app. if (user_manager::UserManager::IsInitialized() &&
diff --git a/chrome/browser/permissions/chrome_permissions_client.h b/chrome/browser/permissions/chrome_permissions_client.h index f386781..b39b21b 100644 --- a/chrome/browser/permissions/chrome_permissions_client.h +++ b/chrome/browser/permissions/chrome_permissions_client.h
@@ -7,6 +7,7 @@ #include "base/no_destructor.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/permissions/permissions_client.h" class ChromePermissionsClient : public permissions::PermissionsClient { @@ -32,7 +33,7 @@ void AreSitesImportant( content::BrowserContext* browser_context, std::vector<std::pair<url::Origin, bool>>* urls) override; -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) bool IsCookieDeletionDisabled(content::BrowserContext* browser_context, const GURL& origin) override; #endif
diff --git a/chrome/browser/permissions/permission_manager_factory.cc b/chrome/browser/permissions/permission_manager_factory.cc index 84074108..630ff22 100644 --- a/chrome/browser/permissions/permission_manager_factory.cc +++ b/chrome/browser/permissions/permission_manager_factory.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/permissions/permission_manager_factory.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/accessibility/accessibility_permission_context.h" #include "chrome/browser/background_fetch/background_fetch_permission_context.h" #include "chrome/browser/background_sync/periodic_background_sync_permission_context.h" @@ -37,8 +38,7 @@ #include "components/permissions/permission_manager.h" #include "ppapi/buildflags/buildflags.h" - -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/media/protected_media_identifier_permission_context.h" #endif @@ -74,7 +74,7 @@ std::make_unique<GeolocationPermissionContextDelegateAndroid>( profile)); #endif -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_ANDROID) permission_contexts[ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER] = std::make_unique<ProtectedMediaIdentifierPermissionContext>(profile); #endif
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc b/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc index 62c4e224..44d4d06 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc
@@ -10,6 +10,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/devtools/devtools_window_testing.h" #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" @@ -53,7 +54,7 @@ #include "ui/views/controls/button/image_button.h" #include "ui/views/widget/widget_observer.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/accelerators.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/hit_test.h" @@ -121,6 +122,11 @@ return mock_controller_; } + OverlayWindowViews* GetOverlayWindow() { + return static_cast<OverlayWindowViews*>( + window_controller()->GetWindowForTesting()); + } + void LoadTabAndEnterPictureInPicture(Browser* browser, const base::FilePath& file_path) { GURL test_page_url = ui_test_utils::GetTestUrl( @@ -223,10 +229,8 @@ EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); #if defined(TOOLKIT_VIEWS) - auto* overlay_window = window_controller()->GetWindowForTesting(); - gfx::NativeWindow native_window = - static_cast<OverlayWindowViews*>(overlay_window)->GetNativeWindow(); -#if defined(OS_CHROMEOS) || defined(OS_MAC) + gfx::NativeWindow native_window = GetOverlayWindow()->GetNativeWindow(); +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_MAC) EXPECT_FALSE(platform_util::IsWindowActive(native_window)); #else EXPECT_TRUE(platform_util::IsWindowActive(native_window)); @@ -234,7 +238,7 @@ #endif } -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) class PictureInPicturePixelComparisonBrowserTest : public PictureInPictureWindowControllerBrowserTest { public: @@ -351,15 +355,13 @@ ASSERT_NE(nullptr, window_controller()); EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window_views = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - overlay_window_views->SetSize(gfx::Size(402, 268)); + GetOverlayWindow()->SetSize(gfx::Size(402, 268)); base::string16 expected_title = base::ASCIIToUTF16("resized"); EXPECT_EQ(expected_title, content::TitleWatcher(active_web_contents, expected_title) .WaitAndGetTitle()); Wait(base::TimeDelta::FromSeconds(3)); - TakeOverlayWindowScreenshot(overlay_window_views); + TakeOverlayWindowScreenshot(GetOverlayWindow()); SkBitmap expected_image; base::FilePath expected_image_path = @@ -385,15 +387,12 @@ EXPECT_TRUE(in_picture_in_picture); EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window_views = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - bool result = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( active_web_contents, "changeVideoSrc();", &result)); const int resize_width = 402, resize_height = 268; - overlay_window_views->SetSize(gfx::Size(resize_width, resize_height)); + GetOverlayWindow()->SetSize(gfx::Size(resize_width, resize_height)); base::string16 expected_title = base::ASCIIToUTF16("resized"); EXPECT_EQ(expected_title, content::TitleWatcher(active_web_contents, expected_title) @@ -401,8 +400,8 @@ EXPECT_TRUE(content::ExecuteScript(active_web_contents, "video.play();")); Wait(base::TimeDelta::FromSeconds(3)); - MoveMouseOver(overlay_window_views); - TakeOverlayWindowScreenshot(overlay_window_views); + MoveMouseOver(GetOverlayWindow()); + TakeOverlayWindowScreenshot(GetOverlayWindow()); base::FilePath expected_pause_image_path = GetFilePath(FILE_PATH_LITERAL("pixel_expected_pause_control.png")); @@ -429,12 +428,12 @@ EXPECT_TRUE(content::ExecuteScript(active_web_contents, "video.pause();")); Wait(base::TimeDelta::FromSeconds(3)); - MoveMouseOver(overlay_window_views); - TakeOverlayWindowScreenshot(overlay_window_views); + MoveMouseOver(GetOverlayWindow()); + TakeOverlayWindowScreenshot(GetOverlayWindow()); ASSERT_TRUE(ReadImageFile(expected_play_image_path, &expected_image)); EXPECT_TRUE(CompareImages(GetResultBitmap(), expected_image)); } -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) // Tests that when an active WebContents accurately tracks whether a video // is in Picture-in-Picture. @@ -488,18 +487,15 @@ SetUpWindowController(active_web_contents); ASSERT_TRUE(window_controller()); - content::OverlayWindow* overlay_window = - window_controller()->GetWindowForTesting(); - ASSERT_TRUE(overlay_window); - ASSERT_FALSE(overlay_window->IsVisible()); + ASSERT_NE(GetOverlayWindow(), nullptr); + ASSERT_FALSE(GetOverlayWindow()->IsVisible()); bool result = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( active_web_contents, "enterPictureInPicture();", &result)); EXPECT_TRUE(result); - static_cast<OverlayWindowViews*>(overlay_window) - ->SetSize(gfx::Size(400, 400)); + GetOverlayWindow()->SetSize(gfx::Size(400, 400)); base::string16 expected_title = base::ASCIIToUTF16("resized"); EXPECT_EQ(expected_title, @@ -752,12 +748,9 @@ &is_paused)); EXPECT_FALSE(is_paused); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); + EXPECT_TRUE(GetOverlayWindow()->IsVisible()); - EXPECT_TRUE(overlay_window->IsVisible()); - - EXPECT_EQ(overlay_window->playback_state_for_testing(), + EXPECT_EQ(GetOverlayWindow()->playback_state_for_testing(), OverlayWindowViews::PlaybackState::kPaused); } @@ -770,10 +763,7 @@ EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -785,7 +775,7 @@ EXPECT_TRUE(in_picture_in_picture); EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); } // Tests that updating video src when video is in Picture-in-Picture session @@ -797,10 +787,7 @@ EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -815,7 +802,7 @@ EXPECT_TRUE(in_picture_in_picture); EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); } // Tests that changing video src to media stream when video is in @@ -828,10 +815,7 @@ EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -846,14 +830,17 @@ EXPECT_TRUE(in_picture_in_picture); EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); - EXPECT_FALSE(overlay_window->previous_track_controls_view_for_testing() + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); + EXPECT_FALSE(GetOverlayWindow() + ->previous_track_controls_view_for_testing() ->layer() ->visible()); - EXPECT_FALSE(overlay_window->play_pause_controls_view_for_testing() + EXPECT_FALSE(GetOverlayWindow() + ->play_pause_controls_view_for_testing() ->layer() ->visible()); - EXPECT_FALSE(overlay_window->next_track_controls_view_for_testing() + EXPECT_FALSE(GetOverlayWindow() + ->next_track_controls_view_for_testing() ->layer() ->visible()); } @@ -1288,7 +1275,9 @@ // Tests that when a new surface id is sent to the Picture-in-Picture window, it // doesn't move back to its default position. // TODO(crbug.com/1146047): Test is flaky on Linux. -#if defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #define MAYBE_SurfaceIdChangeDoesNotMoveWindow DISABLED_SurfaceIdChangeDoesNotMoveWindow #else #define MAYBE_SurfaceIdChangeDoesNotMoveWindow SurfaceIdChangeDoesNotMoveWindow @@ -1301,16 +1290,17 @@ content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); - ASSERT_TRUE(overlay_window->IsVisible()); + ASSERT_NE(GetOverlayWindow(), nullptr); + ASSERT_TRUE(GetOverlayWindow()->IsVisible()); + + const auto max_size = GetOverlayWindow()->GetMaximumSize(); + const int side_length = std::min(max_size.width(), max_size.height()); // Move and resize the window to the top left corner and wait for ack. { - WidgetBoundsChangeWaiter waiter(overlay_window); + WidgetBoundsChangeWaiter waiter(GetOverlayWindow()); - overlay_window->SetBounds(gfx::Rect(0, 0, 400, 400)); + GetOverlayWindow()->SetBounds(gfx::Rect(0, 0, side_length, side_length)); waiter.Wait(); } @@ -1324,12 +1314,13 @@ // Simulate a new surface layer and a change in aspect ratio then wait for // ack. { - WidgetBoundsChangeWaiter waiter(overlay_window); + WidgetBoundsChangeWaiter waiter(GetOverlayWindow()); - overlay_window->SetSurfaceId(viz::SurfaceId( + GetOverlayWindow()->SetSurfaceId(viz::SurfaceId( viz::FrameSinkId(1, 1), viz::LocalSurfaceId(9, base::UnguessableToken::Create()))); - overlay_window->UpdateVideoSize(gfx::Size(200, 100)); + GetOverlayWindow()->UpdateVideoSize( + gfx::Size(side_length / 2, side_length / 4)); waiter.Wait(); } @@ -1337,8 +1328,8 @@ // The position should be closer to the (0, 0) than the default one (bottom // right corner). This will be reflected by checking that the position is // below (100, 100). - EXPECT_LT(overlay_window->GetBounds().x(), 100); - EXPECT_LT(overlay_window->GetBounds().y(), 100); + EXPECT_LT(GetOverlayWindow()->GetBounds().x(), 100); + EXPECT_LT(GetOverlayWindow()->GetBounds().y(), 100); } // Tests that the Picture-in-Picture state is properly updated when the window @@ -1351,13 +1342,11 @@ content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); - ASSERT_TRUE(overlay_window->IsVisible()); + ASSERT_NE(GetOverlayWindow(), nullptr); + ASSERT_TRUE(GetOverlayWindow()->IsVisible()); // Simulate closing from the system. - overlay_window->OnNativeWidgetDestroyed(); + GetOverlayWindow()->OnNativeWidgetDestroyed(); ExpectLeavePictureInPicture(active_web_contents); } @@ -1380,13 +1369,10 @@ EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - - EXPECT_EQ(overlay_window->playback_state_for_testing(), + EXPECT_EQ(GetOverlayWindow()->playback_state_for_testing(), OverlayWindowViews::PlaybackState::kPlaying); - EXPECT_TRUE(overlay_window->video_layer_for_testing()->visible()); + EXPECT_TRUE(GetOverlayWindow()->video_layer_for_testing()->visible()); ASSERT_TRUE( content::ExecuteScript(active_web_contents, "exitPictureInPicture();")); @@ -1409,10 +1395,7 @@ &is_paused)); EXPECT_TRUE(is_paused); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - - EXPECT_EQ(overlay_window->playback_state_for_testing(), + EXPECT_EQ(GetOverlayWindow()->playback_state_for_testing(), OverlayWindowViews::PlaybackState::kPaused); } } @@ -1433,10 +1416,8 @@ LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_NE(nullptr, overlay_window); - EXPECT_TRUE(overlay_window->IsVisible()); + ASSERT_NE(nullptr, GetOverlayWindow()); + EXPECT_TRUE(GetOverlayWindow()->IsVisible()); auto* pip_window_manager = PictureInPictureWindowManager::GetInstance(); ASSERT_NE(nullptr, pip_window_manager); @@ -1467,10 +1448,8 @@ LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); - EXPECT_TRUE(overlay_window->IsVisible()); + ASSERT_TRUE(GetOverlayWindow()); + EXPECT_TRUE(GetOverlayWindow()->IsVisible()); } // This checks that a video in Picture-in-Picture with preload none, when @@ -1574,7 +1553,7 @@ DevToolsWindowTesting::CloseDevToolsWindowSync(window); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Tests that video in Picture-in-Picture is paused when user presses // VKEY_MEDIA_PLAY_PAUSE key even if there's another media playing in a // foreground tab. @@ -1637,28 +1616,23 @@ SetUpWindowController(active_web_contents); ASSERT_TRUE(window_controller()); - content::OverlayWindow* overlay_window = - window_controller()->GetWindowForTesting(); - ASSERT_TRUE(overlay_window); - ASSERT_FALSE(overlay_window->IsVisible()); + ASSERT_NE(GetOverlayWindow(), nullptr); + ASSERT_FALSE(GetOverlayWindow()->IsVisible()); bool result = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( active_web_contents, "enterPictureInPicture();", &result)); ASSERT_TRUE(result); - OverlayWindowViews* overlay_window_views = - static_cast<OverlayWindowViews*>(overlay_window); - // The PiP window starts in the bottom-right quadrant of the screen. - gfx::Rect bottom_right_bounds = overlay_window_views->GetBounds(); + gfx::Rect bottom_right_bounds = GetOverlayWindow()->GetBounds(); // The relative center point of the window. gfx::Point center(bottom_right_bounds.width() / 2, bottom_right_bounds.height() / 2); gfx::Point close_button_position = - overlay_window_views->close_image_position_for_testing(); + GetOverlayWindow()->close_image_position_for_testing(); gfx::Point resize_button_position = - overlay_window_views->resize_handle_position_for_testing(); + GetOverlayWindow()->resize_handle_position_for_testing(); // The close button should be in the top right corner. EXPECT_LT(center.x(), close_button_position.x()); @@ -1667,17 +1641,17 @@ EXPECT_GT(center.x(), resize_button_position.x()); EXPECT_GT(center.y(), resize_button_position.y()); // The resize button hit test should start a top left resizing drag. - EXPECT_EQ(HTTOPLEFT, overlay_window_views->GetResizeHTComponent()); + EXPECT_EQ(HTTOPLEFT, GetOverlayWindow()->GetResizeHTComponent()); // Move the window to the bottom left corner. gfx::Rect bottom_left_bounds(0, bottom_right_bounds.y(), bottom_right_bounds.width(), bottom_right_bounds.height()); - overlay_window_views->SetBounds(bottom_left_bounds); + GetOverlayWindow()->SetBounds(bottom_left_bounds); close_button_position = - overlay_window_views->close_image_position_for_testing(); + GetOverlayWindow()->close_image_position_for_testing(); resize_button_position = - overlay_window_views->resize_handle_position_for_testing(); + GetOverlayWindow()->resize_handle_position_for_testing(); // The close button should be in the top left corner. EXPECT_GT(center.x(), close_button_position.x()); @@ -1686,17 +1660,17 @@ EXPECT_LT(center.x(), resize_button_position.x()); EXPECT_GT(center.y(), resize_button_position.y()); // The resize button hit test should start a top right resizing drag. - EXPECT_EQ(HTTOPRIGHT, overlay_window_views->GetResizeHTComponent()); + EXPECT_EQ(HTTOPRIGHT, GetOverlayWindow()->GetResizeHTComponent()); // Move the window to the top right corner. gfx::Rect top_right_bounds(bottom_right_bounds.x(), 0, bottom_right_bounds.width(), bottom_right_bounds.height()); - overlay_window_views->SetBounds(top_right_bounds); + GetOverlayWindow()->SetBounds(top_right_bounds); close_button_position = - overlay_window_views->close_image_position_for_testing(); + GetOverlayWindow()->close_image_position_for_testing(); resize_button_position = - overlay_window_views->resize_handle_position_for_testing(); + GetOverlayWindow()->resize_handle_position_for_testing(); // The close button should be in the top right corner. EXPECT_LT(center.x(), close_button_position.x()); @@ -1705,16 +1679,16 @@ EXPECT_GT(center.x(), resize_button_position.x()); EXPECT_LT(center.y(), resize_button_position.y()); // The resize button hit test should start a bottom left resizing drag. - EXPECT_EQ(HTBOTTOMLEFT, overlay_window_views->GetResizeHTComponent()); + EXPECT_EQ(HTBOTTOMLEFT, GetOverlayWindow()->GetResizeHTComponent()); // Move the window to the top left corner. gfx::Rect top_left_bounds(0, 0, bottom_right_bounds.width(), bottom_right_bounds.height()); - overlay_window_views->SetBounds(top_left_bounds); + GetOverlayWindow()->SetBounds(top_left_bounds); close_button_position = - overlay_window_views->close_image_position_for_testing(); + GetOverlayWindow()->close_image_position_for_testing(); resize_button_position = - overlay_window_views->resize_handle_position_for_testing(); + GetOverlayWindow()->resize_handle_position_for_testing(); // The close button should be in the top right corner. EXPECT_LT(center.x(), close_button_position.x()); @@ -1723,10 +1697,10 @@ EXPECT_LT(center.x(), resize_button_position.x()); EXPECT_LT(center.y(), resize_button_position.y()); // The resize button hit test should start a bottom right resizing drag. - EXPECT_EQ(HTBOTTOMRIGHT, overlay_window_views->GetResizeHTComponent()); + EXPECT_EQ(HTBOTTOMRIGHT, GetOverlayWindow()->GetResizeHTComponent()); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // Tests that the Play/Pause button is displayed appropriately in the // Picture-in-Picture window. @@ -1739,31 +1713,29 @@ browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_NE(nullptr, active_web_contents); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(nullptr, GetOverlayWindow()); // Play/Pause button is displayed if video is not a mediastream. - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_TRUE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); // Play/Pause button is hidden if video is a mediastream. bool result = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( active_web_contents, "changeVideoSrcToMediaStream();", &result)); EXPECT_TRUE(result); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); // Play/Pause button is not hidden anymore when video is not a mediastream. ASSERT_TRUE(content::ExecuteScriptAndExtractBool( active_web_contents, "changeVideoSrc();", &result)); EXPECT_TRUE(result); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_TRUE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); } // Check that page visibility API events are fired when tab is hidden, shown, @@ -1894,15 +1866,15 @@ SkipAdButtonVisibility) { LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); // Skip Ad button is not displayed initially when mouse is hovering over the // window. - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->skip_ad_controls_view_for_testing()->layer()->visible()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->skip_ad_controls_view_for_testing() + ->layer() + ->visible()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1912,26 +1884,32 @@ ASSERT_TRUE(content::ExecuteScript( active_web_contents, "setMediaSessionActionHandler('skipad');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->skip_ad_controls_view_for_testing()->layer()->visible()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->skip_ad_controls_view_for_testing() + ->layer() + ->visible()); // Play video and check that Skip Ad button is now displayed when // video plays and mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript(active_web_contents, "video.play();")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_TRUE( - overlay_window->skip_ad_controls_view_for_testing()->layer()->visible()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_TRUE(GetOverlayWindow() + ->skip_ad_controls_view_for_testing() + ->layer() + ->visible()); // Unset action handler and check that Skip Ad button is not displayed when // video plays and mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript( active_web_contents, "unsetMediaSessionActionHandler('skipad');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->skip_ad_controls_view_for_testing()->layer()->visible()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->skip_ad_controls_view_for_testing() + ->layer() + ->visible()); } // Tests that the Play/Plause button is displayed in the Picture-in-Picture @@ -1942,9 +1920,7 @@ LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1956,9 +1932,9 @@ active_web_contents, "changeVideoSrcToMediaStream();", &result)); EXPECT_TRUE(result); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); // Play second video (non-muted) so that Media Session becomes active. ASSERT_TRUE( @@ -1969,27 +1945,27 @@ ASSERT_TRUE(content::ExecuteScript(active_web_contents, "setMediaSessionActionHandler('play');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); // Set Media Session action "pause" handler and check that Play/Pause button // is now displayed when mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript(active_web_contents, "setMediaSessionActionHandler('pause');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_TRUE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); // Unset Media Session action "pause" handler and check that Play/Pause button // is hidden when mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript( active_web_contents, "unsetMediaSessionActionHandler('pause');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); ASSERT_TRUE( content::ExecuteScript(active_web_contents, "exitPictureInPicture();")); @@ -2004,9 +1980,9 @@ active_web_contents, "enterPictureInPicture();", &result)); EXPECT_TRUE(result); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_TRUE( - overlay_window->play_pause_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->play_pause_controls_view_for_testing()->IsDrawn()); } // Tests that a Next Track button is displayed in the Picture-in-Picture window @@ -2015,15 +1991,13 @@ NextTrackButtonVisibility) { LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); // Next Track button is not displayed initially when mouse is hovering over // the window. - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->next_track_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->next_track_controls_view_for_testing()->IsDrawn()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2033,35 +2007,35 @@ ASSERT_TRUE(content::ExecuteScript( active_web_contents, "setMediaSessionActionHandler('nexttrack');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->next_track_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->next_track_controls_view_for_testing()->IsDrawn()); // Play video and check that Next Track button is now displayed when // video plays and mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript(active_web_contents, "video.play();")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_TRUE( - overlay_window->next_track_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->next_track_controls_view_for_testing()->IsDrawn()); - gfx::Rect next_track_bounds = - overlay_window->next_track_controls_view_for_testing() - ->GetBoundsInScreen(); + gfx::Rect next_track_bounds = GetOverlayWindow() + ->next_track_controls_view_for_testing() + ->GetBoundsInScreen(); // Unset action handler and check that Next Track button is not displayed when // video plays and mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript( active_web_contents, "unsetMediaSessionActionHandler('nexttrack');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); + MoveMouseOver(GetOverlayWindow()); EXPECT_FALSE( - overlay_window->next_track_controls_view_for_testing()->IsDrawn()); + GetOverlayWindow()->next_track_controls_view_for_testing()->IsDrawn()); // Next Track button is still at the same previous location. - EXPECT_EQ(next_track_bounds, - overlay_window->next_track_controls_view_for_testing() - ->GetBoundsInScreen()); + EXPECT_EQ(next_track_bounds, GetOverlayWindow() + ->next_track_controls_view_for_testing() + ->GetBoundsInScreen()); } // Tests that Next Track button bounds are updated right away when @@ -2070,31 +2044,31 @@ NextTrackButtonBounds) { LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - gfx::Rect next_track_bounds = - overlay_window->next_track_controls_view_for_testing() - ->GetBoundsInScreen(); + gfx::Rect next_track_bounds = GetOverlayWindow() + ->next_track_controls_view_for_testing() + ->GetBoundsInScreen(); ASSERT_TRUE(content::ExecuteScript( active_web_contents, "setMediaSessionActionHandler('nexttrack');")); ASSERT_TRUE(content::ExecuteScript(active_web_contents, "video.play();")); base::RunLoop().RunUntilIdle(); - EXPECT_NE(next_track_bounds, - overlay_window->next_track_controls_view_for_testing() - ->GetBoundsInScreen()); + EXPECT_NE(next_track_bounds, GetOverlayWindow() + ->next_track_controls_view_for_testing() + ->GetBoundsInScreen()); } // Tests that a Previous Track button is displayed in the Picture-in-Picture // window when Media Session Action "previoustrack" is handled by the website. // TODO(crbug.com/985303): Flaky on Linux. -#if defined(OS_LINUX) +// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is +// complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #define MAYBE_PreviousTrackButtonVisibility \ DISABLED_PreviousTrackButtonVisibility #else @@ -2104,15 +2078,14 @@ MAYBE_PreviousTrackButtonVisibility) { LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); // Previous Track button is not displayed initially when mouse is hovering // over the window. - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->previous_track_controls_view_for_testing()->IsDrawn()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->previous_track_controls_view_for_testing() + ->IsDrawn()); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2123,20 +2096,23 @@ ASSERT_TRUE(content::ExecuteScript( active_web_contents, "setMediaSessionActionHandler('previoustrack');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->previous_track_controls_view_for_testing()->IsDrawn()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->previous_track_controls_view_for_testing() + ->IsDrawn()); // Play video and check that Previous Track button is now displayed when // video plays and mouse is hovering over the window. ASSERT_TRUE(content::ExecuteScript(active_web_contents, "video.play();")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_TRUE( - overlay_window->previous_track_controls_view_for_testing()->IsDrawn()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_TRUE(GetOverlayWindow() + ->previous_track_controls_view_for_testing() + ->IsDrawn()); gfx::Rect previous_track_bounds = - overlay_window->previous_track_controls_view_for_testing() + GetOverlayWindow() + ->previous_track_controls_view_for_testing() ->GetBoundsInScreen(); // Unset action handler and check that Previous Track button is not displayed @@ -2144,12 +2120,14 @@ ASSERT_TRUE(content::ExecuteScript( active_web_contents, "unsetMediaSessionActionHandler('previoustrack');")); base::RunLoop().RunUntilIdle(); - MoveMouseOver(overlay_window); - EXPECT_FALSE( - overlay_window->previous_track_controls_view_for_testing()->IsDrawn()); + MoveMouseOver(GetOverlayWindow()); + EXPECT_FALSE(GetOverlayWindow() + ->previous_track_controls_view_for_testing() + ->IsDrawn()); // Previous Track button is still at the same previous location. EXPECT_EQ(previous_track_bounds, - overlay_window->previous_track_controls_view_for_testing() + GetOverlayWindow() + ->previous_track_controls_view_for_testing() ->GetBoundsInScreen()); } @@ -2159,15 +2137,14 @@ PreviousTrackButtonBounds) { LoadTabAndEnterPictureInPicture( browser(), base::FilePath(kPictureInPictureWindowSizePage)); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); + ASSERT_NE(GetOverlayWindow(), nullptr); content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); gfx::Rect previous_track_bounds = - overlay_window->previous_track_controls_view_for_testing() + GetOverlayWindow() + ->previous_track_controls_view_for_testing() ->GetBoundsInScreen(); ASSERT_TRUE(content::ExecuteScript( @@ -2176,7 +2153,8 @@ base::RunLoop().RunUntilIdle(); EXPECT_NE(previous_track_bounds, - overlay_window->previous_track_controls_view_for_testing() + GetOverlayWindow() + ->previous_track_controls_view_for_testing() ->GetBoundsInScreen()); } @@ -2872,14 +2850,12 @@ ASSERT_TRUE( content::ExecuteScript(active_web_contents, "addPauseEventListener();")); - OverlayWindowViews* overlay_window = static_cast<OverlayWindowViews*>( - window_controller()->GetWindowForTesting()); - ASSERT_TRUE(overlay_window); - ASSERT_FALSE(overlay_window->GetFocusManager()->GetFocusedView()); + ASSERT_NE(GetOverlayWindow(), nullptr); + ASSERT_FALSE(GetOverlayWindow()->GetFocusManager()->GetFocusedView()); ui::KeyEvent space_key_pressed(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::DomCode::SPACE, ui::EF_NONE); - overlay_window->OnKeyEvent(&space_key_pressed); + GetOverlayWindow()->OnKeyEvent(&space_key_pressed); base::string16 expected_title = base::ASCIIToUTF16("pause"); EXPECT_EQ(expected_title,
diff --git a/chrome/browser/platform_util_unittest.cc b/chrome/browser/platform_util_unittest.cc index ac683075..6b81370 100644 --- a/chrome/browser/platform_util_unittest.cc +++ b/chrome/browser/platform_util_unittest.cc
@@ -13,10 +13,11 @@ #include "base/run_loop.h" #include "base/stl_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/platform_util_internal.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/json/json_string_value_serializer.h" #include "base/values.h" #include "chrome/browser/chrome_content_browser_client.h" @@ -40,7 +41,7 @@ namespace { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // ChromeContentBrowserClient subclass that sets up a custom file system backend // that allows the test to grant file access to the file manager extension ID @@ -248,7 +249,7 @@ }; #endif // OS_POSIX -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS doesn't follow symbolic links in sandboxed filesystems. So all the // symbolic link tests should return PATH_NOT_FOUND. @@ -277,9 +278,9 @@ EXPECT_EQ(OPEN_FAILED_NO_HANLDER_FOR_FILE_TYPE, CallOpenItem(unhandled_file, OPEN_FILE)); } -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if defined(OS_POSIX) && !defined(OS_CHROMEOS) +#if defined(OS_POSIX) && !BUILDFLAG(IS_CHROMEOS_ASH) // On all other Posix platforms, the symbolic link tests should work as // expected.
diff --git a/chrome/browser/plugins/plugins_resource_service.cc b/chrome/browser/plugins/plugins_resource_service.cc index 8a123eb..dea3c4f 100644 --- a/chrome/browser/plugins/plugins_resource_service.cc +++ b/chrome/browser/plugins/plugins_resource_service.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/plugins/plugin_finder.h" @@ -59,9 +60,9 @@ std::string filename; #if defined(OS_WIN) filename = "plugins_win.json"; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) filename = "plugins_chromeos.json"; -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) filename = "plugins_linux.json"; #elif defined(OS_MAC) filename = "plugins_mac.json";
diff --git a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc new file mode 100644 index 0000000..3db631f1 --- /dev/null +++ b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc
@@ -0,0 +1,232 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h" + +#include <string> + +#include "base/base64.h" +#include "base/notreached.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" +#include "base/strings/string_util.h" +#include "base/values.h" +#include "components/policy/proto/record.pb.h" +#include "components/policy/proto/record_constants.pb.h" + +namespace reporting { + +namespace { + +// UploadEncryptedReportingRequestBuilder list key +constexpr char kEncryptedRecordListKey[] = "encryptedRecord"; + +// EncrypedRecordDictionaryBuilder strings +constexpr char kEncryptedWrappedRecord[] = "encryptedWrappedRecord"; +constexpr char kSequencingInformationKey[] = "sequencingInformation"; +constexpr char kEncryptionInfoKey[] = "encryptionInfo"; + +// SequencingInformationDictionaryBuilder strings +constexpr char kSequencingId[] = "sequencingId"; +constexpr char kGenerationId[] = "generationId"; +constexpr char kPriority[] = "priority"; + +// EncryptionInfoDictionaryBuilder strings +constexpr char kEncryptionKey[] = "encryptionKey"; +constexpr char kPublicKeyId[] = "publicKeyId"; + +} // namespace + +UploadEncryptedReportingRequestBuilder:: + UploadEncryptedReportingRequestBuilder() { + result_ = base::Value{base::Value::Type::DICTIONARY}; + result_.value().SetKey(GetEncryptedRecordListPath(), + base::Value{base::Value::Type::LIST}); +} + +UploadEncryptedReportingRequestBuilder:: + ~UploadEncryptedReportingRequestBuilder() = default; + +UploadEncryptedReportingRequestBuilder& +UploadEncryptedReportingRequestBuilder::AddRecord( + const EncryptedRecord& record) { + if (!result_.has_value()) { + // Some errors were already detected. + return *this; + } + base::Value* const records_list = + result_.value().FindListKey(GetEncryptedRecordListPath()); + if (!records_list || !records_list->is_list()) { + NOTREACHED(); // Should not happen. + return *this; + } + + auto record_result = EncryptedRecordDictionaryBuilder(record).Build(); + if (!record_result.has_value()) { + // Record has errors. Stop here. + result_ = base::nullopt; + return *this; + } + + records_list->Append(std::move(record_result.value())); + return *this; +} + +base::Optional<base::Value> UploadEncryptedReportingRequestBuilder::Build() { + return std::move(result_); +} + +// static +base::StringPiece +UploadEncryptedReportingRequestBuilder::GetEncryptedRecordListPath() { + return kEncryptedRecordListKey; +} + +EncryptedRecordDictionaryBuilder::EncryptedRecordDictionaryBuilder( + const EncryptedRecord& record) { + base::Value record_dictionary{base::Value::Type::DICTIONARY}; + + // A record without sequencing information cannot be uploaded - deny it. + if (!record.has_sequencing_information()) { + return; + } + auto sequencing_information_result = + SequencingInformationDictionaryBuilder(record.sequencing_information()) + .Build(); + if (!sequencing_information_result.has_value()) { + // Sequencing information was improperly configured. Record cannot be + // uploaded. Deny it. + return; + } + record_dictionary.SetKey(GetSequencingInformationKeyPath(), + std::move(sequencing_information_result.value())); + + // Encryption information can be missing until we set up encryption as + // mandatory. + if (record.has_encryption_info()) { + auto encryption_info_result = + EncryptionInfoDictionaryBuilder(record.encryption_info()).Build(); + if (!encryption_info_result.has_value()) { + // Encryption info has been corrupted or set improperly. Deny it. + return; + } + record_dictionary.SetKey(GetEncryptionInfoPath(), + std::move(encryption_info_result.value())); + } + + // Gap records won't fill in this field, so it can be missing. + if (record.has_encrypted_wrapped_record()) { + std::string base64_encode; + base::Base64Encode(record.encrypted_wrapped_record(), &base64_encode); + record_dictionary.SetStringKey(GetEncryptedWrappedRecordPath(), + base64_encode); + } + + // Result complete. + result_ = std::move(record_dictionary); +} + +EncryptedRecordDictionaryBuilder::~EncryptedRecordDictionaryBuilder() = default; + +base::Optional<base::Value> EncryptedRecordDictionaryBuilder::Build() { + return std::move(result_); +} + +// static +base::StringPiece +EncryptedRecordDictionaryBuilder::GetEncryptedWrappedRecordPath() { + return kEncryptedWrappedRecord; +} + +// static +base::StringPiece +EncryptedRecordDictionaryBuilder::GetSequencingInformationKeyPath() { + return kSequencingInformationKey; +} + +// static +base::StringPiece EncryptedRecordDictionaryBuilder::GetEncryptionInfoPath() { + return kEncryptionInfoKey; +} + +SequencingInformationDictionaryBuilder::SequencingInformationDictionaryBuilder( + const SequencingInformation& sequencing_information) { + // SequencingInformation requires all three fields be set. + if (!sequencing_information.has_sequencing_id() || + !sequencing_information.has_generation_id() || + !sequencing_information.has_priority()) { + return; + } + + base::Value sequencing_dictionary{base::Value::Type::DICTIONARY}; + sequencing_dictionary.SetStringKey( + GetSequencingIdPath(), + base::NumberToString(sequencing_information.sequencing_id())); + sequencing_dictionary.SetStringKey( + GetGenerationIdPath(), + base::NumberToString(sequencing_information.generation_id())); + sequencing_dictionary.SetIntKey(GetPriorityPath(), + sequencing_information.priority()); + result_ = std::move(sequencing_dictionary); +} + +SequencingInformationDictionaryBuilder:: + ~SequencingInformationDictionaryBuilder() = default; + +base::Optional<base::Value> SequencingInformationDictionaryBuilder::Build() { + return std::move(result_); +} + +// static +base::StringPiece +SequencingInformationDictionaryBuilder::GetSequencingIdPath() { + return kSequencingId; +} + +// static +base::StringPiece +SequencingInformationDictionaryBuilder::GetGenerationIdPath() { + return kGenerationId; +} + +// static +base::StringPiece SequencingInformationDictionaryBuilder::GetPriorityPath() { + return kPriority; +} + +EncryptionInfoDictionaryBuilder::EncryptionInfoDictionaryBuilder( + const EncryptionInfo& encryption_info) { + base::Value encryption_info_dictionary{base::Value::Type::DICTIONARY}; + + // EncryptionInfo requires both fields are set. + if (!encryption_info.has_encryption_key() || + !encryption_info.has_public_key_id()) { + return; + } + + encryption_info_dictionary.SetStringKey(GetEncryptionKeyPath(), + encryption_info.encryption_key()); + encryption_info_dictionary.SetStringKey( + GetPublicKeyIdPath(), + base::NumberToString(encryption_info.public_key_id())); + result_ = std::move(encryption_info_dictionary); +} + +EncryptionInfoDictionaryBuilder::~EncryptionInfoDictionaryBuilder() = default; + +base::Optional<base::Value> EncryptionInfoDictionaryBuilder::Build() { + return std::move(result_); +} + +// static +base::StringPiece EncryptionInfoDictionaryBuilder::GetEncryptionKeyPath() { + return kEncryptionKey; +} + +// static +base::StringPiece EncryptionInfoDictionaryBuilder::GetPublicKeyIdPath() { + return kPublicKeyId; +} + +} // namespace reporting
diff --git a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h new file mode 100644 index 0000000..d8955b8a3 --- /dev/null +++ b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h
@@ -0,0 +1,133 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_RECORD_UPLOAD_REQUEST_BUILDER_H_ +#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_RECORD_UPLOAD_REQUEST_BUILDER_H_ + +#include <string> + +#include "base/optional.h" +#include "base/strings/string_piece.h" +#include "base/values.h" +#include "components/policy/proto/record.pb.h" + +namespace reporting { + +// Builds an upload request payload specific for +// EncryptedReportingJobConfiguration A JSON version of the payload looks like +// this: +// { +// "encryptedRecord": [ +// { +// "encryptedWrappedRecord": "EncryptedMessage", +// "encryptionInfo" : { +// "encryptionKey": "EncryptedMessage", +// "publicKeyId": 1 +// }, +// "sequencingInformation": { +// "sequencingId": 1, +// "generationId": 123456789, +// "priority": 1 +// } +// }, +// { +// "encryptedWrappedRecord": "EncryptedMessage", +// "encryptionInfo" : { +// "encryptionKey": "EncryptedMessage", +// "publicKeyId": 2 +// }, +// "sequencingInformation": { +// "sequencingId": 2, +// "generationId": 123456789, +// "priority": 1 +// } +// } +// ] +// } +// TODO(b/170054326): Add 'need_encryption_key' field, if requested. +// TODO(b/159361496): Periodically add memory and disk space usage. +// +// This payload is added to the common payload of all reporting jobs, which +// includes "device" and "browser" sub-fields: +// +// EncryptedReportingRequestBuilder builder; +// builder.AddRecord(record1); +// builder.AddRecord(record2); +// ... +// builder.AddRecord(recordN); +// auto payload_result = builder.Build(); +// DCHECK(payload_result.has_value()); +// job_payload_.MergeDict(payload_result.value()); + +class UploadEncryptedReportingRequestBuilder { + public: + UploadEncryptedReportingRequestBuilder(); + ~UploadEncryptedReportingRequestBuilder(); + + UploadEncryptedReportingRequestBuilder& AddRecord( + const EncryptedRecord& record); + + base::Optional<base::Value> Build(); + + static base::StringPiece GetEncryptedRecordListPath(); + + static const char kEncryptedRecordListKey_[]; + + base::Optional<base::Value> result_; +}; + +// Builds a |base::Value| dictionary from a |EncryptedRecord| +// proto. +class EncryptedRecordDictionaryBuilder { + public: + explicit EncryptedRecordDictionaryBuilder(const EncryptedRecord& record); + ~EncryptedRecordDictionaryBuilder(); + + base::Optional<base::Value> Build(); + + static base::StringPiece GetEncryptedWrappedRecordPath(); + static base::StringPiece GetSequencingInformationKeyPath(); + static base::StringPiece GetEncryptionInfoPath(); + + private: + base::Optional<base::Value> result_; +}; + +// Builds a |base::Value| dictionary from a |SequencingInformation| +// proto. +class SequencingInformationDictionaryBuilder { + public: + explicit SequencingInformationDictionaryBuilder( + const SequencingInformation& sequencing_information); + ~SequencingInformationDictionaryBuilder(); + + base::Optional<base::Value> Build(); + + static base::StringPiece GetSequencingIdPath(); + static base::StringPiece GetGenerationIdPath(); + static base::StringPiece GetPriorityPath(); + + private: + base::Optional<base::Value> result_; +}; + +// Builds a |base::Value| dictionary from a |EncryptionInfo| proto. +class EncryptionInfoDictionaryBuilder { + public: + explicit EncryptionInfoDictionaryBuilder( + const EncryptionInfo& encryption_info); + ~EncryptionInfoDictionaryBuilder(); + + base::Optional<base::Value> Build(); + + static base::StringPiece GetEncryptionKeyPath(); + static base::StringPiece GetPublicKeyIdPath(); + + private: + base::Optional<base::Value> result_; +}; + +} // namespace reporting + +#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_RECORD_UPLOAD_REQUEST_BUILDER_H_
diff --git a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder_unittest.cc b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder_unittest.cc new file mode 100644 index 0000000..b671811b --- /dev/null +++ b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder_unittest.cc
@@ -0,0 +1,149 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h" + +#include <cstdint> +#include <string> + +#include "base/strings/strcat.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::Not; + +namespace reporting { +namespace { + +constexpr uint64_t kGenerationId = 4321; +constexpr Priority kPriority = Priority::IMMEDIATE; + +// Default values for EncryptionInfo +constexpr char kEncryptionKey[] = "abcdef"; +constexpr uint64_t kPublicKeyId = 9876; + +class RecordUploadRequestBuilderTest : public ::testing::Test { + public: + RecordUploadRequestBuilderTest() = default; + + protected: + static EncryptedRecord GenerateEncryptedRecord( + const base::StringPiece encrypted_wrapped_record) { + EncryptedRecord record; + record.set_encrypted_wrapped_record(std::string(encrypted_wrapped_record)); + + auto* const sequencing_information = + record.mutable_sequencing_information(); + sequencing_information->set_sequencing_id(GetNextSequenceId()); + sequencing_information->set_generation_id(kGenerationId); + sequencing_information->set_priority(kPriority); + + auto* const encryption_info = record.mutable_encryption_info(); + encryption_info->set_encryption_key(kEncryptionKey); + encryption_info->set_public_key_id(kPublicKeyId); + + return record; + } + + static uint64_t GetNextSequenceId() { + static uint64_t sequencing_id = 0; + return sequencing_id++; + } +}; + +TEST_F(RecordUploadRequestBuilderTest, AcceptEncryptedRecordsList) { + const std::vector<std::string> kEncryptedWrappedRecords{ + "T", "E", "S", "T", "_", "I", "N", "F", "O"}; + static constexpr size_t kNumRecords = 10; + + std::vector<EncryptedRecord> records; + records.reserve(kNumRecords); + for (size_t counter = 0; counter < kNumRecords; ++counter) { + records.push_back(GenerateEncryptedRecord( + base::StrCat({"TEST_INFO_", base::NumberToString(counter)}))); + } + + UploadEncryptedReportingRequestBuilder builder; + for (const auto& record : records) { + builder.AddRecord(record); + } + auto request_payload = builder.Build(); + ASSERT_TRUE(request_payload.has_value()); + ASSERT_TRUE(request_payload.value().is_dict()); + base::Value* const record_list = request_payload.value().FindListKey( + UploadEncryptedReportingRequestBuilder::GetEncryptedRecordListPath()); + ASSERT_TRUE(record_list); + ASSERT_TRUE(record_list->is_list()); + EXPECT_EQ(record_list->GetList().size(), records.size()); + + size_t counter = 0; + for (const auto& record : records) { + auto record_value_result = EncryptedRecordDictionaryBuilder(record).Build(); + ASSERT_TRUE(record_value_result.has_value()); + EXPECT_EQ(record_list->GetList()[counter++], record_value_result.value()); + } +} + +TEST_F(RecordUploadRequestBuilderTest, BreakListOnSingleBadRecord) { + const std::vector<std::string> kEncryptedWrappedRecords{ + "T", "E", "S", "T", "_", "I", "N", "F", "O"}; + static constexpr size_t kNumRecords = 10; + + std::vector<EncryptedRecord> records; + records.reserve(kNumRecords); + for (size_t counter = 0; counter < kNumRecords; ++counter) { + records.push_back(GenerateEncryptedRecord( + base::StrCat({"TEST_INFO_", base::NumberToString(counter)}))); + } + // Corrupt one record. + records[kNumRecords - 2] + .mutable_sequencing_information() + ->clear_generation_id(); + + UploadEncryptedReportingRequestBuilder builder; + for (const auto& record : records) { + builder.AddRecord(record); + } + auto request_payload = builder.Build(); + ASSERT_FALSE(request_payload.has_value()) << request_payload.value(); +} + +TEST_F(RecordUploadRequestBuilderTest, DenyPoorlyFormedEncryptedRecords) { + // Reject empty record. + EncryptedRecord record; + + EXPECT_FALSE(EncryptedRecordDictionaryBuilder(record).Build().has_value()); + + // Reject encrypted_wrapped_record without sequencing information. + record.set_encrypted_wrapped_record("Enterprise"); + + EXPECT_FALSE(EncryptedRecordDictionaryBuilder(record).Build().has_value()); + + // Reject incorrectly set sequencing information by only setting sequencing + // id. + auto* sequencing_information = record.mutable_sequencing_information(); + sequencing_information->set_sequencing_id(1701); + + EXPECT_FALSE(EncryptedRecordDictionaryBuilder(record).Build().has_value()); + + // Finish correctly setting sequencing information but incorrectly set + // encryption info. + sequencing_information->set_generation_id(12345678); + sequencing_information->set_priority(IMMEDIATE); + + auto* encryption_info = record.mutable_encryption_info(); + encryption_info->set_encryption_key("Key"); + + EXPECT_FALSE(EncryptedRecordDictionaryBuilder(record).Build().has_value()); + + // Finish correctly setting encryption info - expect complete call. + encryption_info->set_public_key_id(1234); + + EXPECT_TRUE(EncryptedRecordDictionaryBuilder(record).Build().has_value()); +} + +} // namespace +} // namespace reporting
diff --git a/chrome/browser/policy/policy_prefs_browsertest.cc b/chrome/browser/policy/policy_prefs_browsertest.cc index e106657..75bd165 100644 --- a/chrome/browser/policy/policy_prefs_browsertest.cc +++ b/chrome/browser/policy/policy_prefs_browsertest.cc
@@ -17,6 +17,7 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/run_loop.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -33,9 +34,9 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/profiles/profile_helper.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace policy { @@ -95,7 +96,7 @@ kCrosSettingsPrefix); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Class used to check policy to pref mappings for policies that are mapped into // the sign-in profile (usually via LoginProfilePolicyProvider). @@ -125,7 +126,7 @@ &provider_, kCrosSettingsPrefix); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // For WebUI integration tests, see cr_policy_indicator_tests.js and // cr_policy_pref_indicator_tests.js.
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java index 7a40229bb..942758f1 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java
@@ -532,6 +532,11 @@ public static final String PREFETCH_OFFLINE_COUNTER = "prefetch_notification_offline_counter"; /** + * Whether users disable the PriceWelcomeMessageCard. + */ + public static final String PRICE_TRACKING_PRICE_WELCOME_MESSAGE_CARD = + "Chrome.PriceTracking.PriceWelcome"; + /** * Whether users turn on the feature track prices on tabs. */ public static final String PRICE_TRACKING_TRACK_PRICES_ON_TABS = @@ -837,6 +842,7 @@ IMAGE_DESCRIPTIONS_JUST_ONCE_COUNT, IMAGE_DESCRIPTIONS_DONT_ASK_AGAIN, PERSISTENT_OFFLINE_CONTENT_AVAILABILITY_STATUS, + PRICE_TRACKING_PRICE_WELCOME_MESSAGE_CARD, PRICE_TRACKING_TRACK_PRICES_ON_TABS, PROMO_IS_DISMISSED.pattern(), PROMO_TIMES_SEEN.pattern(),
diff --git a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc index 70a692a..da263fb3 100644 --- a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc +++ b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc
@@ -19,6 +19,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -411,7 +412,7 @@ } // namespace // Occasional flakes on Windows (https://crbug.com/1045971). -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.cc b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.cc index e13e488..e39169b6 100644 --- a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.cc +++ b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "build/chromeos_buildflags.h" #include "mojo/public/cpp/bindings/remote.h" PrefetchProxyNetworkContextClient::PrefetchProxyNetworkContextClient() = @@ -94,7 +95,7 @@ } #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) void PrefetchProxyNetworkContextClient::OnTrustAnchorUsed() {} #endif
diff --git a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.h b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.h index e2175df7..0e1e30f 100644 --- a/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.h +++ b/chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_network_context_client.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_PREFETCH_PREFETCH_PROXY_PREFETCH_PROXY_NETWORK_CONTEXT_CLIENT_H_ #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/network/public/mojom/network_context.mojom.h" @@ -69,7 +70,7 @@ const std::string& spn, OnGenerateHttpNegotiateAuthTokenCallback callback) override; #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) void OnTrustAnchorUsed() override; #endif void OnTrustTokenIssuanceDivertedToSystem(
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index f74f5b50e..0c083f7 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -84,7 +84,7 @@ #include "chrome/browser/ui/tabs/pinned_tab_codec.h" #include "chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.h" #include "chrome/browser/ui/user_education/feature_promo_snooze_service.h" -#include "chrome/browser/ui/webui/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/ui/webui/print_preview/policy_settings.h" #include "chrome/browser/updates/announcement_notification/announcement_notification_service.h"
diff --git a/chrome/browser/previews/previews_test_util.h b/chrome/browser/previews/previews_test_util.h index fd272cf6..2ba8be5 100644 --- a/chrome/browser/previews/previews_test_util.h +++ b/chrome/browser/previews/previews_test_util.h
@@ -9,6 +9,7 @@ #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -36,7 +37,7 @@ // Previews InfoBar (which these tests trigger) does not work on Mac. // See https://crbug.com/782322 for details. Also occasional flakes on win7 // (https://crbug.com/789542). -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH) #define DISABLE_ON_WIN_MAC_CHROMEOS(x) DISABLED_##x #else #define DISABLE_ON_WIN_MAC_CHROMEOS(x) x
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow.cc b/chrome/browser/printing/cloud_print/gcd_api_flow.cc index 376a654..98b2012 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow.cc
@@ -39,8 +39,11 @@ return cloud_devices::kCloudPrintAuthScope; } -std::vector<std::string> CloudPrintApiFlowRequest::GetExtraRequestHeaders() { - return std::vector<std::string>(1, cloud_print::kChromeCloudPrintProxyHeader); +std::vector<std::pair<std::string, std::string>> +CloudPrintApiFlowRequest::GetExtraRequestHeaders() { + return std::vector<std::pair<std::string, std::string>>( + 1, std::make_pair(cloud_print::kChromeCloudPrintProxyHeaderName, + cloud_print::kChromeCloudPrintProxyHeaderValue)); } } // namespace cloud_print
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow.h b/chrome/browser/printing/cloud_print/gcd_api_flow.h index e8b6948..788e0afd 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow.h +++ b/chrome/browser/printing/cloud_print/gcd_api_flow.h
@@ -67,7 +67,9 @@ virtual std::string GetOAuthScope() = 0; // Returns extra headers, if any, to send with this request. - virtual std::vector<std::string> GetExtraRequestHeaders() = 0; + virtual std::vector< + std::pair<std::string /* name */, std::string /* value */>> + GetExtraRequestHeaders() = 0; // Returns the network traffic annotation tag for this request. virtual NetworkTrafficAnnotation GetNetworkTrafficAnnotationType() = 0; @@ -93,7 +95,8 @@ // GCDApiFlowRequest implementation std::string GetOAuthScope() override; - std::vector<std::string> GetExtraRequestHeaders() override; + std::vector<std::pair<std::string, std::string>> GetExtraRequestHeaders() + override; private: DISALLOW_COPY_AND_ASSIGN(CloudPrintApiFlowRequest);
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc index 4a8b984..6f41ac75 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
@@ -129,9 +129,10 @@ request->headers.SetHeader(kCloudPrintOAuthHeaderKey, GetOAuthHeaderValue(access_token_info.token)); - std::vector<std::string> extra_headers = request_->GetExtraRequestHeaders(); - for (const std::string& header : extra_headers) - request->headers.AddHeaderFromString(header); + auto extra_headers = request_->GetExtraRequestHeaders(); + for (const auto& header : extra_headers) { + request->headers.SetHeader(header.first, header.second); + } url_loader_ = network::SimpleURLLoader::Create( std::move(request),
diff --git a/chrome/browser/printing/print_backend_browsertest.cc b/chrome/browser/printing/print_backend_browsertest.cc index 65b3092a..4b34cf945 100644 --- a/chrome/browser/printing/print_backend_browsertest.cc +++ b/chrome/browser/printing/print_backend_browsertest.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <stdint.h> + #include <memory> #include <string> #include <utility> @@ -27,6 +29,9 @@ namespace { constexpr char kDefaultPrinterName[] = "default-test-printer"; +constexpr char kInvalidPrinterName[] = "invalid-test-printer"; + +constexpr int32_t kCopiesMax = 123; } // namespace @@ -82,8 +87,12 @@ /*printer_status=*/0, /*is_default=*/true, /*options=*/PrinterBasicInfoOptions{}); + // Only explicitly specify capabilities that we pay attention to in the + // tests. + auto default_caps = std::make_unique<PrinterSemanticCapsAndDefaults>(); + default_caps->copies_max = kCopiesMax; print_backend_service_->test_print_backend_->AddValidPrinter( - kDefaultPrinterName, nullptr, std::move(printer_info)); + kDefaultPrinterName, std::move(default_caps), std::move(printer_info)); } // Public callbacks used by tests. @@ -94,17 +103,26 @@ CheckForQuit(); } + void OnDidGetPrinterSemanticCapsAndDefaults( + base::Optional<PrinterSemanticCapsAndDefaults>* capture_printer_caps, + const base::Optional<PrinterSemanticCapsAndDefaults>& printer_caps) { + *capture_printer_caps = printer_caps; + CheckForQuit(); + } + // The following are helper functions for having a wait loop in the test and - // exit when expected messages are received. + // exit when expected messages are received. Expect to only have to wait for + // one message. void WaitUntilCallbackReceived() { - if (received_message_) { - // Callback happened before even needing to wait. - return; + // If callback happened before getting here, then no need to wait. + if (!received_message_) { + base::RunLoop run_loop; + quit_callback_ = run_loop.QuitClosure(); + run_loop.Run(); } - base::RunLoop run_loop; - quit_callback_ = run_loop.QuitClosure(); - run_loop.Run(); + // Reset for possible subsequent test. + received_message_ = false; } void CheckForQuit() { @@ -130,6 +148,7 @@ // without having performed initialization. IN_PROC_BROWSER_TEST_F(PrintBackendBrowserTest, FailWithoutInit) { base::Optional<std::string> default_printer_name; + base::Optional<PrinterSemanticCapsAndDefaults> printer_caps; // Safe to use base::Unretained(this) since waiting locally on the callback // forces a shorter lifetime than `this`. @@ -138,6 +157,14 @@ base::Unretained(this), &default_printer_name)); WaitUntilCallbackReceived(); EXPECT_FALSE(default_printer_name.has_value()); + + GetPrintBackendService()->GetPrinterSemanticCapsAndDefaults( + kDefaultPrinterName, + base::BindOnce( + &PrintBackendBrowserTest::OnDidGetPrinterSemanticCapsAndDefaults, + base::Unretained(this), &printer_caps)); + WaitUntilCallbackReceived(); + EXPECT_FALSE(printer_caps.has_value()); } IN_PROC_BROWSER_TEST_F(PrintBackendBrowserTest, GetDefaultPrinterName) { @@ -155,4 +182,31 @@ EXPECT_EQ(default_printer_name.value(), kDefaultPrinterName); } +IN_PROC_BROWSER_TEST_F(PrintBackendBrowserTest, + GetPrinterSemanticCapsAndDefaults) { + base::Optional<PrinterSemanticCapsAndDefaults> printer_caps; + + DoInitAndSetupTestData(); + + // Safe to use base::Unretained(this) since waiting locally on the callback + // forces a shorter lifetime than `this`. + GetPrintBackendService()->GetPrinterSemanticCapsAndDefaults( + kDefaultPrinterName, + base::BindOnce( + &PrintBackendBrowserTest::OnDidGetPrinterSemanticCapsAndDefaults, + base::Unretained(this), &printer_caps)); + WaitUntilCallbackReceived(); + EXPECT_TRUE(printer_caps.has_value()); + EXPECT_EQ(printer_caps->copies_max, kCopiesMax); + + // Requesting for an invalid printer should not return capabilities. + GetPrintBackendService()->GetPrinterSemanticCapsAndDefaults( + kInvalidPrinterName, + base::BindOnce( + &PrintBackendBrowserTest::OnDidGetPrinterSemanticCapsAndDefaults, + base::Unretained(this), &printer_caps)); + WaitUntilCallbackReceived(); + EXPECT_FALSE(printer_caps.has_value()); +} + } // namespace printing
diff --git a/chrome/browser/printing/print_view_manager.cc b/chrome/browser/printing/print_view_manager.cc index e7432a32..7adf1908 100644 --- a/chrome/browser/printing/print_view_manager.cc +++ b/chrome/browser/printing/print_view_manager.cc
@@ -295,13 +295,13 @@ } } -void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, - bool source_is_modifiable) { +void PrintViewManager::ShowScriptedPrintPreview(bool source_is_modifiable) { if (print_preview_state_ != SCRIPTED_PREVIEW) return; DCHECK(print_preview_rfh_); - if (rfh != print_preview_rfh_) + if (print_manager_host_receivers_.GetCurrentTargetFrame() != + print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = @@ -337,8 +337,6 @@ IPC_MESSAGE_FORWARD_DELAY_REPLY( PrintHostMsg_SetupScriptedPrintPreview, &helper, FrameDispatchHelper::OnSetupScriptedPrintPreview) - IPC_MESSAGE_HANDLER(PrintHostMsg_ShowScriptedPrintPreview, - OnShowScriptedPrintPreview) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP()
diff --git a/chrome/browser/printing/print_view_manager.h b/chrome/browser/printing/print_view_manager.h index 8770b7b..f463d9d 100644 --- a/chrome/browser/printing/print_view_manager.h +++ b/chrome/browser/printing/print_view_manager.h
@@ -64,6 +64,7 @@ // mojom::PrintManagerHost: void DidShowPrintDialog() override; + void ShowScriptedPrintPreview(bool source_is_modifiable) override; // content::WebContentsObserver implementation. void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; @@ -100,8 +101,6 @@ // IPC Message handlers. void OnSetupScriptedPrintPreview(content::RenderFrameHost* rfh, IPC::Message* reply_msg); - void OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, - bool source_is_modifiable); void OnScriptedPrintPreviewReply(IPC::Message* reply_msg); void MaybeUnblockScriptedPreviewRPH();
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index 94774af..c6df233 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -26,7 +26,6 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_manager.h" -#include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" @@ -64,6 +63,7 @@ #if BUILDFLAG(ENABLE_PRINT_PREVIEW) #include "chrome/browser/printing/print_error_dialog.h" +#include "chrome/browser/printing/print_view_manager.h" #endif namespace printing {
diff --git a/chrome/browser/printing/printing_message_filter.cc b/chrome/browser/printing/printing_message_filter.cc index ca5858b..184d285 100644 --- a/chrome/browser/printing/printing_message_filter.cc +++ b/chrome/browser/printing/printing_message_filter.cc
@@ -14,7 +14,6 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" -#include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h"
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_settings.cc b/chrome/browser/privacy_sandbox/privacy_sandbox_settings.cc index ea1e596..669642d2 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_settings.cc +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_settings.cc
@@ -61,25 +61,10 @@ bool PrivacySandboxSettings::IsFlocAllowed( const GURL& url, const base::Optional<url::Origin>& top_frame_origin) const { - if (!base::FeatureList::IsEnabled(features::kPrivacySandboxSettings)) { - // Simply respect cookie settings if the UI is not available. An empty site - // for cookies is provided so the context is always as a third party. - return cookie_settings_->IsCookieAccessAllowed(url, GURL(), - top_frame_origin); - } - - if (!pref_service_->GetBoolean(prefs::kPrivacySandboxApisEnabled)) - return false; - - // TODO (crbug.com/1155504): Bypassing CookieSettings to access content - // settings directly ignores allowlisted schemes and the storage access API. - // These should be taken into account here. ContentSettingsForOneType cookie_settings; cookie_settings_->GetCookieSettings(&cookie_settings); - return !HasNonDefaultBlockSetting( - cookie_settings, url, - top_frame_origin ? top_frame_origin->GetURL() : GURL()); + return IsPrivacySandboxAllowed(url, top_frame_origin, cookie_settings); } base::Time PrivacySandboxSettings::FlocDataAccessibleSince() const { @@ -91,16 +76,50 @@ bool PrivacySandboxSettings::IsConversionMeasurementAllowed( const url::Origin& top_frame_origin, const url::Origin& reporting_origin) const { - // Simply respect the 3P cookie setting. - // TODO(crbug.com/1152336): Respect privacy sandbox settings. - return !cookie_settings_->ShouldBlockThirdPartyCookies(); + ContentSettingsForOneType cookie_settings; + cookie_settings_->GetCookieSettings(&cookie_settings); + + return IsPrivacySandboxAllowed(reporting_origin.GetURL(), top_frame_origin, + cookie_settings); } bool PrivacySandboxSettings::ShouldSendConversionReport( const url::Origin& impression_origin, const url::Origin& conversion_origin, const url::Origin& reporting_origin) const { - // Simply respect the 3P cookie setting. - // TODO(crbug.com/1152336): Respect privacy sandbox settings. - return !cookie_settings_->ShouldBlockThirdPartyCookies(); + // Re-using the |cookie_settings| allows this function to be faster + // than simply calling IsConversionMeasurementAllowed() twice + ContentSettingsForOneType cookie_settings; + cookie_settings_->GetCookieSettings(&cookie_settings); + + // The |reporting_origin| needs to have been accessible in both impression + // and conversion contexts. These are both checked when they occur, but + // user settings may have changed between then and when the conversion report + // is sent. + return IsPrivacySandboxAllowed(reporting_origin.GetURL(), impression_origin, + cookie_settings) && + IsPrivacySandboxAllowed(reporting_origin.GetURL(), reporting_origin, + cookie_settings); +} + +bool PrivacySandboxSettings::IsPrivacySandboxAllowed( + const GURL& url, + const base::Optional<url::Origin>& top_frame_origin, + const ContentSettingsForOneType& cookie_settings) const { + if (!base::FeatureList::IsEnabled(features::kPrivacySandboxSettings)) { + // Simply respect cookie settings if the UI is not available. An empty site + // for cookies is provided so the context is always as a third party. + return cookie_settings_->IsCookieAccessAllowed(url, GURL(), + top_frame_origin); + } + + if (!pref_service_->GetBoolean(prefs::kPrivacySandboxApisEnabled)) + return false; + + // TODO (crbug.com/1155504): Bypassing the CookieSettings class to access + // content settings directly ignores allowlisted schemes and the storage + // access API. These should be taken into account here. + return !HasNonDefaultBlockSetting( + cookie_settings, url, + top_frame_origin ? top_frame_origin->GetURL() : GURL()); }
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_settings.h b/chrome/browser/privacy_sandbox/privacy_sandbox_settings.h index 2fea6908..a4ba4a3 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_settings.h +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_settings.h
@@ -60,6 +60,17 @@ const url::Origin& conversion_origin, const url::Origin& reporting_origin) const; + protected: + // Determines based on the current features, preferences and provided + // |cookie_settings| whether Privacy Sandbox APIs are generally allowable for + // |url| on |top_frame_origin|. Individual APIs may perform additional checks + // for allowability (such as incognito) ontop of this. |cookie_settings| is + // provided as a parameter to allow callers to cache it between calls. + bool IsPrivacySandboxAllowed( + const GURL& url, + const base::Optional<url::Origin>& top_frame_origin, + const ContentSettingsForOneType& cookie_settings) const; + private: content_settings::CookieSettings* cookie_settings_; PrefService* pref_service_;
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_unittest.cc b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_unittest.cc index 3b69924..10cbad4 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_unittest.cc +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/privacy_sandbox/privacy_sandbox_settings.h" +#include "base/test/gtest_util.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -111,10 +112,12 @@ } base::test::ScopedFeatureList* feature_list() { return &feature_list_; } + protected: + std::unique_ptr<PrivacySandboxSettings> privacy_sandbox_settings_; + private: content::BrowserTaskEnvironment browser_task_environment_; TestingProfile profile_; - std::unique_ptr<PrivacySandboxSettings> privacy_sandbox_settings_; base::test::ScopedFeatureList feature_list_; }; @@ -132,6 +135,14 @@ GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + SetupTestState( /*privacy_sandbox_available=*/false, /*privacy_sandbox_enabled=*/false, @@ -139,15 +150,24 @@ /*user_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", ContentSetting::CONTENT_SETTING_ALLOW}, - {"https://another-embedded.com", "*", + {"https://another-test.com", "*", ContentSetting::CONTENT_SETTING_BLOCK}}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_TRUE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( - GURL("https://another-embedded.com"), base::nullopt)); + GURL("https://another-test.com"), base::nullopt)); + + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); SetupTestState( /*privacy_sandbox_available=*/false, @@ -159,11 +179,20 @@ /*managed_cookie_setting=*/kNoSetting, {{"https://embedded.com", "https://test.com", ContentSetting::CONTENT_SETTING_BLOCK}}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); EXPECT_TRUE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), base::nullopt)); + + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); } TEST_F(PrivacySandboxSettingsTest, PreferenceOverridesDefaultContentSetting) { @@ -176,10 +205,19 @@ /*user_cookie_exceptions=*/{}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_TRUE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + // An allow exception should not override the preference value. SetupTestState( /*privacy_sandbox_available=*/true, @@ -187,12 +225,23 @@ /*default_cookie_setting=*/ContentSetting::CONTENT_SETTING_ALLOW, /*user_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", + ContentSetting::CONTENT_SETTING_ALLOW}, + {"https://embedded.com", "https://another-test.com", ContentSetting::CONTENT_SETTING_ALLOW}}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); } TEST_F(PrivacySandboxSettingsTest, CookieBlockExceptionsApply) { @@ -207,10 +256,19 @@ ContentSetting::CONTENT_SETTING_BLOCK}}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + // User created exceptions should not apply if a managed default coookie // setting exists. What the managed default setting actually is should *not* // affect whether APIs are enabled. The cookie managed state is reflected in @@ -221,12 +279,22 @@ /*default_cookie_setting=*/ContentSetting::CONTENT_SETTING_ALLOW, /*user_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", + ContentSetting::CONTENT_SETTING_BLOCK}, + {"https://embedded.com", "https://another-test.com", ContentSetting::CONTENT_SETTING_BLOCK}}, /*managed_cookie_setting=*/ContentSetting::CONTENT_SETTING_BLOCK, /*managed_cookie_exceptions=*/{}); + EXPECT_TRUE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); // Managed content setting exceptions should override both the privacy // sandbox pref and any user settings. @@ -236,10 +304,13 @@ /*default_cookie_setting=*/ContentSetting::CONTENT_SETTING_ALLOW, /*user_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", + ContentSetting::CONTENT_SETTING_ALLOW}, + {"https://embedded.com", "https://another-test.com", ContentSetting::CONTENT_SETTING_ALLOW}}, /*managed_cookie_setting=*/ContentSetting::CONTENT_SETTING_ALLOW, {{"https://embedded.com", "https://test.com", ContentSetting::CONTENT_SETTING_BLOCK}}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); @@ -247,6 +318,21 @@ GURL("https://unrelated.com"), url::Origin::Create(GURL("https://unrelated.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://unrelated-a.com")), + url::Origin::Create(GURL("https://unrelated-b.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://unrelated-c.com")), + url::Origin::Create(GURL("https://unrelated-d.com")), + url::Origin::Create(GURL("https://unrelated-e.com")))); + // A less specific block exception should not override a more specific allow // exception. The effective content setting in this scenario is still allow, // even though a block exception exists. @@ -257,7 +343,11 @@ /*user_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", ContentSetting::CONTENT_SETTING_ALLOW}, + {"https://embedded.com", "https://another-test.com", + ContentSetting::CONTENT_SETTING_ALLOW}, {"https://[*.]embedded.com", "https://[*.]test.com", + ContentSetting::CONTENT_SETTING_BLOCK}, + {"https://[*.]embedded.com", "https://[*.]another-test.com", ContentSetting::CONTENT_SETTING_BLOCK}}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); @@ -265,8 +355,8 @@ GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); - // Exceptions which specify a top frame origin should not match against an - // empty top frame. + // Exceptions which specify a top frame origin should not match against other + // top frame origins, or an empty origin. SetupTestState( /*privacy_sandbox_available=*/true, /*privacy_sandbox_enabled=*/true, @@ -278,9 +368,18 @@ /*managed_cookie_exceptions=*/ {{"https://embedded.com", "https://test.com", ContentSetting::CONTENT_SETTING_BLOCK}}); + EXPECT_TRUE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), base::nullopt)); + EXPECT_TRUE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_TRUE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://yet-another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + // Exceptions which specify a wildcard top frame origin should match both // empty top frames and non empty top frames. SetupTestState( @@ -291,15 +390,24 @@ {{"https://embedded.com", "*", ContentSetting::CONTENT_SETTING_BLOCK}}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), base::nullopt)); EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://test.com")))); + + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://test.com")), + url::Origin::Create(GURL("https://another-test.com")), + url::Origin::Create(GURL("https://embedded.com")))); } -TEST_F(PrivacySandboxSettingsTest, FlocAlwaysThirdParty) { - // Check that when the UI is not enabled, all FLoC requests are considered +TEST_F(PrivacySandboxSettingsTest, ThirdPartyByDefault) { + // Check that when the UI is not enabled, all requests are considered // as third party requests. profile()->GetTestingPrefService()->SetUserPref( prefs::kCookieControlsMode, @@ -312,9 +420,18 @@ /*user_cookie_exceptions=*/{}, /*managed_cookie_setting=*/kNoSetting, /*managed_cookie_exceptions=*/{}); + EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), url::Origin::Create(GURL("https://embedded.com")))); EXPECT_FALSE(privacy_sandbox_settings()->IsFlocAllowed( GURL("https://embedded.com"), base::nullopt)); + + EXPECT_FALSE(privacy_sandbox_settings()->IsConversionMeasurementAllowed( + url::Origin::Create(GURL("https://embedded.com")), + url::Origin::Create(GURL("https://embedded.com")))); + EXPECT_FALSE(privacy_sandbox_settings()->ShouldSendConversionReport( + url::Origin::Create(GURL("https://embedded.com")), + url::Origin::Create(GURL("https://embedded.com")), + url::Origin::Create(GURL("https://embedded.com")))); }
diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc index 2bdc8ea..137fa56 100644 --- a/chrome/browser/process_singleton_posix.cc +++ b/chrome/browser/process_singleton_posix.cc
@@ -98,7 +98,8 @@ #include "chrome/browser/ui/process_singleton_dialog_linux.h" #endif -#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS) +#if defined(TOOLKIT_VIEWS) && \ + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "ui/views/linux_ui/linux_ui.h" #endif @@ -871,7 +872,8 @@ SendRemoteProcessInteractionResultHistogram(REMOTE_PROCESS_SHUTTING_DOWN); return PROCESS_NONE; } else if (strncmp(buf, kACKToken, base::size(kACKToken) - 1) == 0) { -#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS) +#if defined(TOOLKIT_VIEWS) && \ + (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) // Likely NULL in unit tests. views::LinuxUI* linux_ui = views::LinuxUI::instance(); if (linux_ui)
diff --git a/chrome/browser/profiles/DEPS b/chrome/browser/profiles/DEPS index 0a1ba26..52d84ae 100644 --- a/chrome/browser/profiles/DEPS +++ b/chrome/browser/profiles/DEPS
@@ -4,4 +4,18 @@ # is created. "+chrome/browser/performance_manager/persistence/site_data/site_data_cache_facade_factory.h" ], + # TODO(crbug.com/1149277): Remove include rules for profile once it is in its + # own GN target. GN will prevent dependency cycles more reliably. + "profile\.(cc|h)": [ + # Profile is a dependency for most of //chrome/browser for keyed services. + # It should not depend on anything in the //chrome/browser target. + "-chrome/browser", + "+chrome/browser/profiles/profile.h", + # Files without dependencies on //chrome/browser: + "+chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h", + "+chrome/browser/profiles/android/jni_headers", + "+chrome/browser/profiles/profile_observer.h", + # TODO(crbug.com/1149277): Remove this: + "+chrome/browser/first_run/first_run.h", + ] }
diff --git a/chrome/browser/push_messaging/push_messaging_notification_manager.cc b/chrome/browser/push_messaging/push_messaging_notification_manager.cc index daaec7c..3133819 100644 --- a/chrome/browser/push_messaging/push_messaging_notification_manager.cc +++ b/chrome/browser/push_messaging/push_messaging_notification_manager.cc
@@ -16,6 +16,7 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/notifications/platform_notification_service_factory.h" #include "chrome/browser/notifications/platform_notification_service_impl.h" @@ -50,7 +51,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/android_sms/android_sms_service_factory.h" #include "chrome/browser/chromeos/android_sms/android_sms_urls.h" #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" @@ -109,7 +110,7 @@ EnforceRequirementsCallback message_handled_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (ShouldSkipUserVisibleOnlyRequirements(origin)) { std::move(message_handled_callback) .Run(/* did_show_generic_notification= */ false); @@ -285,7 +286,7 @@ .Run(/* did_show_generic_notification= */ true); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool PushMessagingNotificationManager::ShouldSkipUserVisibleOnlyRequirements( const GURL& origin) { // This is a short-term exception to user visible only enforcement added
diff --git a/chrome/browser/push_messaging/push_messaging_notification_manager.h b/chrome/browser/push_messaging/push_messaging_notification_manager.h index 425c7ec..7f7de31 100644 --- a/chrome/browser/push_messaging/push_messaging_notification_manager.h +++ b/chrome/browser/push_messaging/push_messaging_notification_manager.h
@@ -12,9 +12,10 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/push_messaging/budget_database.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/android_sms/android_sms_app_manager.h" #include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h" #endif @@ -85,7 +86,7 @@ bool success, const std::string& notification_id); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool ShouldSkipUserVisibleOnlyRequirements(const GURL& origin); void SetTestMultiDeviceSetupClient( @@ -101,7 +102,7 @@ BudgetDatabase budget_database_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) chromeos::multidevice_setup::MultiDeviceSetupClient* test_multidevice_setup_client_ = nullptr;
diff --git a/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc b/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc index 1dcbf41..56a1076 100644 --- a/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc +++ b/chrome/browser/push_messaging/push_messaging_notification_manager_unittest.cc
@@ -4,15 +4,16 @@ #include "chrome/browser/push_messaging/push_messaging_notification_manager.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "base/bind.h" +#include "build/chromeos_buildflags.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_contents.h" #include "content/public/test/test_renderer_host.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/android_sms/fake_android_sms_app_manager.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" #endif @@ -53,7 +54,7 @@ EXPECT_FALSE(manager.IsTabVisible(profile(), web_contents(), origin)); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(PushMessagingNotificationManagerTest, SkipEnforceUserVisibleOnlyRequirementsForAndroidMessages) { GURL app_url("https://example.com/test/");
diff --git a/chrome/browser/push_messaging/push_messaging_service_factory.cc b/chrome/browser/push_messaging/push_messaging_service_factory.cc index 8013e9a2..b77faa81 100644 --- a/chrome/browser/push_messaging/push_messaging_service_factory.cc +++ b/chrome/browser/push_messaging/push_messaging_service_factory.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/engagement/site_engagement_service_factory.h" #include "chrome/browser/gcm/gcm_profile_service_factory.h" @@ -19,7 +20,7 @@ #include "components/gcm_driver/instance_id/instance_id_profile_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/android_sms/android_sms_service_factory.h" #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" #endif @@ -50,7 +51,7 @@ DependsOn(HostContentSettingsMapFactory::GetInstance()); DependsOn(PermissionManagerFactory::GetInstance()); DependsOn(SiteEngagementServiceFactory::GetInstance()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) DependsOn(chromeos::android_sms::AndroidSmsServiceFactory::GetInstance()); DependsOn(chromeos::multidevice_setup::MultiDeviceSetupClientFactory:: GetInstance());
diff --git a/chrome/browser/renderer_preferences_util.cc b/chrome/browser/renderer_preferences_util.cc index ed40422a..399f3b9 100644 --- a/chrome/browser/renderer_preferences_util.cc +++ b/chrome/browser/renderer_preferences_util.cc
@@ -10,6 +10,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -34,7 +35,7 @@ #include "ui/base/cocoa/defaults_utils.h" #endif -#if defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) +#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "ui/views/linux_ui/linux_ui.h" @@ -134,7 +135,7 @@ pref_service->GetBoolean(prefs::kWebRTCAllowLegacyTLSProtocols); #if defined(USE_AURA) prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // This color is 0x544d90fe modulated with 0xffffff. prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA); prefs->active_selection_fg_color = SK_ColorBLACK; @@ -153,7 +154,7 @@ prefs->caret_blink_interval = interval; #endif -#if defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) +#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) views::LinuxUI* linux_ui = views::LinuxUI::instance(); if (linux_ui) { if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) {
diff --git a/chrome/browser/resources/BUILD.gn b/chrome/browser/resources/BUILD.gn index 508dbf5..95c2542 100644 --- a/chrome/browser/resources/BUILD.gn +++ b/chrome/browser/resources/BUILD.gn
@@ -42,8 +42,6 @@ "management:closure_compile", "media_router:closure_compile", "nearby_internals:closure_compile", - "nearby_share/shared:closure_compile", - "nearby_share/shared:closure_compile_module", "new_tab_page:closure_compile", "ntp4:closure_compile", "omnibox:closure_compile", @@ -72,6 +70,8 @@ deps += [ "chromeos:closure_compile", "nearby_share:closure_compile", + "nearby_share/shared:closure_compile", + "nearby_share/shared:closure_compile_module", ] } if (enable_extensions) {
diff --git a/chrome/browser/resources/inline_login/BUILD.gn b/chrome/browser/resources/inline_login/BUILD.gn index 3cd125f5..e9ca290e 100644 --- a/chrome/browser/resources/inline_login/BUILD.gn +++ b/chrome/browser/resources/inline_login/BUILD.gn
@@ -22,6 +22,7 @@ js_library("inline_login_app") { deps = [ ":inline_login_browser_proxy", + ":welcome_page_app", "//chrome/browser/resources/gaia_auth_host:authenticator.m", "//third_party/polymer/v3_0/components-chromium/paper-spinner:paper-spinner-lite", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
diff --git a/chrome/browser/resources/inline_login/inline_login_app.js b/chrome/browser/resources/inline_login/inline_login_app.js index cc96f0c..643e79e 100644 --- a/chrome/browser/resources/inline_login/inline_login_app.js +++ b/chrome/browser/resources/inline_login/inline_login_app.js
@@ -8,7 +8,6 @@ import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import 'chrome://resources/cr_elements/cr_view_manager/cr_view_manager.m.js'; - import {isChromeOS} from '//resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {isRTL} from 'chrome://resources/js/util.m.js'; @@ -88,6 +87,19 @@ type: String, value: '', }, + + /* + * True if welcome page should not be shown. + * @private + */ + shouldSkipWelcomePage_: { + type: Boolean, + value() { + // TODO(crbug.com/1144114): get value from pref. + return false; + }, + readOnly: true, + }, }, /** @private {?InlineLoginBrowserProxy} */ @@ -252,6 +264,9 @@ if (this.$.signinFrame.canGoBack()) { this.$.signinFrame.back(); this.$.signinFrame.focus(); + } else if (this.isWelcomePageEnabled_()) { + // Allow user go back to the welcome page, if it's enabled. + this.switchView_(View.welcome); } else { this.closeDialog_(); } @@ -312,13 +327,20 @@ * @private */ isWelcomePageEnabled_() { - return this.isAccountManagementFlowsV2Enabled_; + return this.isAccountManagementFlowsV2Enabled_ && + !this.shouldSkipWelcomePage_; }, + // <if expr="chromeos"> /** @private */ onOkButtonClick_() { this.switchView_(View.addAccount); + const skipChecked = + /** @type {WelcomePageAppElement} */ (this.$$('welcome-page-app')) + .isSkipCheckboxChecked(); + this.browserProxy_.skipWelcomePage(skipChecked); }, + // </if> /** @param {Object} authExtHost */ setAuthExtHostForTest(authExtHost) {
diff --git a/chrome/browser/resources/inline_login/inline_login_browser_proxy.js b/chrome/browser/resources/inline_login/inline_login_browser_proxy.js index 91bb37dd..0aa47c5 100644 --- a/chrome/browser/resources/inline_login/inline_login_browser_proxy.js +++ b/chrome/browser/resources/inline_login/inline_login_browser_proxy.js
@@ -55,6 +55,14 @@ /** Send 'dialogClose' message to close the login dialog. */ dialogClose() {} + + // <if expr="chromeos"> + /** + * Send 'skipWelcomePage' message to the handler. + * @param {boolean} skip Whether the welcome page should be skipped. + */ + skipWelcomePage(skip) {} + // </if> } /** @implements {InlineLoginBrowserProxy} */ @@ -103,6 +111,13 @@ dialogClose() { chrome.send('dialogClose'); } + + // <if expr="chromeos"> + /** @override */ + skipWelcomePage(skip) { + chrome.send('skipWelcomePage', [skip]); + } + // </if> } addSingletonGetter(InlineLoginBrowserProxyImpl);
diff --git a/chrome/browser/resources/inline_login/welcome_page_app.html b/chrome/browser/resources/inline_login/welcome_page_app.html index 0aa4f4e..f8cfd795 100644 --- a/chrome/browser/resources/inline_login/welcome_page_app.html +++ b/chrome/browser/resources/inline_login/welcome_page_app.html
@@ -6,11 +6,16 @@ width: 338px; } .google-full-logo { + /* The same size as in webview. */ width: 74px; } .secondary { color: var(--cr-secondary-text-color); } + .skip-checkbox { + margin: auto; + margin-top: 40px; + } </style> <div class="main-container"> @@ -20,11 +25,17 @@ </if> <h1>[[getWelcomeTitle_()]]</h1> <p class="secondary" inner-h-t-m-l="[[getWelcomeBody_()]]"></p> - <if expr="_google_chrome"> - <div class="image-container"> + <div class="image-container"> + <if expr="_google_chrome"> <img class="welcome-image" alt="" srcset="account_manager_welcome_1x.png 1x, account_manager_welcome_2x.png 2x"> - </div> - </if> + </if> + </div> + <div class="skip-checkbox"> + <cr-checkbox id="checkbox" + aria-label="$i18n{accountManagerDialogWelcomeCheckbox}"> + <span class="secondary">$i18n{accountManagerDialogWelcomeCheckbox}</span> + </cr-checkbox> + </div> </div>
diff --git a/chrome/browser/resources/inline_login/welcome_page_app.js b/chrome/browser/resources/inline_login/welcome_page_app.js index 0b14987..23ca6bc 100644 --- a/chrome/browser/resources/inline_login/welcome_page_app.js +++ b/chrome/browser/resources/inline_login/welcome_page_app.js
@@ -3,6 +3,7 @@ // found in the LICENSE file. import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; +import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; import './account_manager_shared_css.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; @@ -21,6 +22,11 @@ () => this.dispatchEvent(new CustomEvent('opened-new-window'))); }, + /** @return {boolean} */ + isSkipCheckboxChecked() { + return this.$.checkbox.checked; + }, + /** * @return {string} * @private
diff --git a/chrome/browser/resources/nearby_share/BUILD.gn b/chrome/browser/resources/nearby_share/BUILD.gn index aa610ad..7b7aa9d9 100644 --- a/chrome/browser/resources/nearby_share/BUILD.gn +++ b/chrome/browser/resources/nearby_share/BUILD.gn
@@ -56,7 +56,7 @@ resource_path_rewrites = [ "chrome/browser/ui/webui/nearby_share/nearby_share.mojom-lite.js|mojo/nearby_share.mojom-lite.js", "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom-lite.js|mojo/nearby_share_settings.mojom-lite.js", - "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom-lite.js|mojo/nearby_share_settings.mojom-lite.js", + "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom-lite.js|mojo/nearby_share_target_types.mojom-lite.js", ] } @@ -79,11 +79,8 @@ "app.js", "icons.js", "nearby_confirmation_page.js", - "nearby_device.js", - "nearby_device_icon.js", "nearby_discovery_page.js", "nearby_preview.js", - "nearby_progress.js", ] } @@ -127,11 +124,8 @@ ":app", ":discovery_manager", ":nearby_confirmation_page", - ":nearby_device", - ":nearby_device_icon", ":nearby_discovery_page", ":nearby_preview", - ":nearby_progress", ] } @@ -156,7 +150,7 @@ js_library("nearby_confirmation_page") { deps = [ ":nearby_preview", - ":nearby_progress", + "./shared:nearby_progress.m", "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_button:cr_button.m", @@ -165,28 +159,11 @@ ] } -js_library("nearby_device") { - deps = [ - ":nearby_device_icon", - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - "//third_party/polymer/v3_0/components-chromium/iron-icon", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - -js_library("nearby_device_icon") { - deps = [ - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - "//third_party/polymer/v3_0/components-chromium/iron-icon", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - js_library("nearby_discovery_page") { deps = [ ":discovery_manager", - ":nearby_device", ":nearby_preview", + "./shared:nearby_device.m", "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", "//third_party/polymer/v3_0/components-chromium/iron-list", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", @@ -202,23 +179,12 @@ ] } -js_library("nearby_progress") { - deps = [ - ":nearby_device_icon", - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - html_to_js("web_components") { js_files = [ "app.js", "icons.js", "nearby_confirmation_page.js", - "nearby_device.js", - "nearby_device_icon.js", "nearby_discovery_page.js", "nearby_preview.js", - "nearby_progress.js", ] }
diff --git a/chrome/browser/resources/nearby_share/nearby_confirmation_page.html b/chrome/browser/resources/nearby_share/nearby_confirmation_page.html index ca372ef..731a36f 100644 --- a/chrome/browser/resources/nearby_share/nearby_confirmation_page.html +++ b/chrome/browser/resources/nearby_share/nearby_confirmation_page.html
@@ -86,7 +86,8 @@ action-button-label="[[getActionButtonLabel_(needsConfirmation_)]]" action-button-event-name="accept" cancel-button-label="[[getCancelButtonLabel_(needsConfirmation_)]]" - cancel-button-event-name="[[getCancelEventName_(needsConfirmation_)]]"> + cancel-button-event-name="[[getCancelEventName_(needsConfirmation_)]]" + close-only="[[errorTitle_]]"> <div id="centerContent" slot="content"> <div id="processRow"> <div id="processRowContent">
diff --git a/chrome/browser/resources/nearby_share/nearby_confirmation_page.js b/chrome/browser/resources/nearby_share/nearby_confirmation_page.js index cdc1df5..e26e9073 100644 --- a/chrome/browser/resources/nearby_share/nearby_confirmation_page.js +++ b/chrome/browser/resources/nearby_share/nearby_confirmation_page.js
@@ -13,10 +13,10 @@ import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; import './nearby_preview.js'; -import './nearby_progress.js'; import './mojo/nearby_share_target_types.mojom-lite.js'; import './mojo/nearby_share.mojom-lite.js'; import './shared/nearby_page_template.m.js'; +import './shared/nearby_progress.m.js'; import './strings.m.js'; import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js';
diff --git a/chrome/browser/resources/nearby_share/nearby_device.html b/chrome/browser/resources/nearby_share/nearby_device.html deleted file mode 100644 index d1d76b3f..0000000 --- a/chrome/browser/resources/nearby_share/nearby_device.html +++ /dev/null
@@ -1,71 +0,0 @@ -<style> - #wrapper { - align-items: center; - background-color: rgb(255, 255, 255); - border: 1px solid rgba(216, 216, 216, 0.76); - border-radius: 8px; - box-sizing: border-box; - cursor: pointer; - display: flex; - height: 40px; - margin-block-end: 6px; - padding-block-end: 6px; - padding-block-start: 6px; - padding-inline-end: 9px; - padding-inline-start: 9px; - } - - :host(:focus) { - outline: none; - } - - :host(:focus) #wrapper { - border-color: var(--google-grey-refresh-700); - } - - :host([is-selected]) #wrapper { - border-color: var(--google-blue-refresh-500); - } - - :host([is-selected]) #done { - display: flex; - } - - :host([is-selected]) #name { - color: var(--google-blue-600); - } - - #done { - color: var(--google-blue-600); - display: none; - flex-shrink: 0; - height: 17px; - width: 17px; - } - - #icon { - --nearby-device-icon-size: 15px; - flex-shrink: 0; - height: 26px; - width: 26px; - } - - #name { - color: rgb(95, 99, 104); - flex-grow: 1; - font-size: 11px; - font-weight: 500; - letter-spacing: 0.3px; - margin-inline-start: 11px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } -</style> - -<div id="wrapper"> - <nearby-device-icon id="icon" share-target="[[shareTarget]]"> - </nearby-device-icon> - <div id="name">[[shareTarget.name]]</div> - <iron-icon id="done" icon="nearby-share:done"></iron-icon> -</div>
diff --git a/chrome/browser/resources/nearby_share/nearby_device.js b/chrome/browser/resources/nearby_share/nearby_device.js deleted file mode 100644 index 641739d74..0000000 --- a/chrome/browser/resources/nearby_share/nearby_device.js +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview The 'nearby-device' component shows details of a remote device. - */ - -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; -import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; -import './icons.js'; -import './nearby_device_icon.js'; -import './mojo/nearby_share_target_types.mojom-lite.js'; -import './mojo/nearby_share.mojom-lite.js'; - -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -Polymer({ - is: 'nearby-device', - - _template: html`{__html_template__}`, - - properties: { - /** - * Expected to start as null, then change to a valid object before this - * component is shown. - * @type {?nearbyShare.mojom.ShareTarget} - */ - shareTarget: { - type: Object, - value: null, - }, - - /** - * Whether this share target is selected. - * @type {boolean} - */ - isSelected: { - type: Boolean, - reflectToAttribute: true, - }, - }, -});
diff --git a/chrome/browser/resources/nearby_share/nearby_device_icon.html b/chrome/browser/resources/nearby_share/nearby_device_icon.html deleted file mode 100644 index bced8c7..0000000 --- a/chrome/browser/resources/nearby_share/nearby_device_icon.html +++ /dev/null
@@ -1,17 +0,0 @@ -<style> - :host { - background-color: var(--nearby-device-icon-background-color, - var(--google-blue-50)); - border-radius: 50%; - display: flex; - } - - #icon { - color: var(--nearby-device-icon-color, var(--google-blue-600)); - height: var(--nearby-device-icon-size, 24px); - margin: auto; - width: var(--nearby-device-icon-size, 24px); - } -</style> - -<iron-icon id="icon" icon="[[getShareTargetIcon_(shareTarget)]]"></iron-icon>
diff --git a/chrome/browser/resources/nearby_share/nearby_discovery_page.html b/chrome/browser/resources/nearby_share/nearby_discovery_page.html index e6cd64a..93220b7 100644 --- a/chrome/browser/resources/nearby_share/nearby_discovery_page.html +++ b/chrome/browser/resources/nearby_share/nearby_discovery_page.html
@@ -142,7 +142,8 @@ action-button-event-name="next" action-disabled="[[!selectedShareTarget]]" cancel-button-label="$i18n{nearbyShareActionsCancel}" - cancel-button-event-name="close"> + cancel-button-event-name="close" + close-only="[[errorTitle_]]"> <div id="centerContent" slot="content"> <cr-lottie animation-url="nearby_share_pulse_animation.json" autoplay="true">
diff --git a/chrome/browser/resources/nearby_share/nearby_discovery_page.js b/chrome/browser/resources/nearby_share/nearby_discovery_page.js index 429892f..fbd8ad5 100644 --- a/chrome/browser/resources/nearby_share/nearby_discovery_page.js +++ b/chrome/browser/resources/nearby_share/nearby_discovery_page.js
@@ -12,7 +12,7 @@ import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; -import './nearby_device.js'; +import './shared/nearby_device.m.js'; import './nearby_preview.js'; import './mojo/nearby_share_target_types.mojom-lite.js'; import './mojo/nearby_share.mojom-lite.js';
diff --git a/chrome/browser/resources/nearby_share/nearby_progress.html b/chrome/browser/resources/nearby_share/nearby_progress.html deleted file mode 100644 index 6119bd9f..0000000 --- a/chrome/browser/resources/nearby_share/nearby_progress.html +++ /dev/null
@@ -1,108 +0,0 @@ -<style> - #device-name { - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - color: rgba(0, 0, 0, 0.87); - display: -webkit-box; - letter-spacing: 0.25px; - line-height: 154%; - overflow: hidden; - text-align: center; - } - - #icon { - height: 68px; - margin: auto; - width: 68px; - } - - .has-error #icon { - --nearby-device-icon-color: var(--google-grey-600); - --nearby-device-icon-background-color: var(--google-grey-200); - } - - #progress-container { - display: flex; - height: 76px; - margin: 8px auto 20px auto; - position: relative; - width: 76px; - } - - #wheel { - fill: none; - stroke: var(--google-blue-600); - stroke-dasharray: 100; - stroke-dashoffset: calc(100 - var(--progress-percentage, 0)); - stroke-linecap: round; - stroke-width: 2px; - transform: rotate(-90deg); - transform-origin: 50% 50%; - transition: stroke-dashoffset 400ms ease; - } - - .unknown-progress #wheel { - animation: 1.4s ease-in-out infinite both unknown-progress-animation; - stroke-dasharray: 116; - } - - .has-error #wheel { - animation: none; - stroke: var(--google-red-600); - stroke-dashoffset: 0; - } - - #svg { - left: 0; - position: absolute; - top: 0; - } - - .unknown-progress #svg { - animation: 2s linear infinite svg-animation; - } - - .has-error #svg { - animation: none; - } - - @keyframes unknown-progress-animation { - 0%, - 25% { - stroke-dashoffset: 115; - transform: rotate(0); - } - 50%, - 75% { - stroke-dashoffset: 30; - transform: rotate(45deg); - } - 100% { - stroke-dashoffset: 115; - transform: rotate(360deg); - } - } - - @keyframes svg-animation { - 0% { transform: rotateZ(0deg); } - 100% { transform: rotateZ(360deg); } - } -</style> - -<div id="progress-container" role="progressbar" aria-valuemin="0" - aria-valuemax="100" aria-valuenow$="[[progress]]" - tabindex$="[[getProgressBarTabIndex_(progress)]]" - class$="[[getProgressWheelClass_(progress, hasError)]]"> - <!-- This svg is inlined so that it can be styled with css; otherwise, - it would be better to put it in an iron-icon. --> - <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"> - <circle id="wheel" - cx="40" cy="40" r="39" pathLength="100"> - </circle> - </svg> - <nearby-device-icon id="icon" share-target="[[shareTarget]]"> - </nearby-device-icon> -</div> -<div id="device-name" aria-label="$i18n{nearbyShareOnboardingPageDeviceName}"> - [[shareTarget.name]] -</div>
diff --git a/chrome/browser/resources/nearby_share/shared/BUILD.gn b/chrome/browser/resources/nearby_share/shared/BUILD.gn index 55b61e7a..66f5f9bb2 100644 --- a/chrome/browser/resources/nearby_share/shared/BUILD.gn +++ b/chrome/browser/resources/nearby_share/shared/BUILD.gn
@@ -9,6 +9,8 @@ import("//ui/webui/resources/tools/js_modulizer.gni") import("./nearby_shared.gni") +assert(is_chromeos, "Nearby Share is CrOS only") + os_settings_dir = "$root_gen_dir/chrome/browser/resources/settings/chromeos" preprocess_v2_manifest = "preprocessed_v2_manifest.json" preprocess_v3_manifest = "preprocessed_v3_manifest.json" @@ -38,10 +40,16 @@ "nearby_contact_manager.js", "nearby_contact_visibility.html", "nearby_contact_visibility.js", + "nearby_device_icon.html", + "nearby_device_icon.js", + "nearby_device.html", + "nearby_device.js", "nearby_onboarding_page.html", "nearby_onboarding_page.js", "nearby_page_template.html", "nearby_page_template.js", + "nearby_progress.html", + "nearby_progress.js", "nearby_share_settings.html", "nearby_share_settings.js", "nearby_share_settings_behavior.html", @@ -61,8 +69,11 @@ in_files = [ "nearby_contact_manager.m.js", "nearby_contact_visibility.m.js", + "nearby_device_icon.m.js", + "nearby_device.m.js", "nearby_onboarding_page.m.js", "nearby_page_template.m.js", + "nearby_progress.m.js", "nearby_share_settings.m.js", "nearby_share_settings_behavior.m.js", "nearby_shared_icons.m.js", @@ -75,8 +86,11 @@ deps = [ ":nearby_contact_manager", ":nearby_contact_visibility", + ":nearby_device_icon", + ":nearby_device", ":nearby_onboarding_page", ":nearby_page_template", + ":nearby_progress", ":nearby_share_settings", ":nearby_share_settings_behavior", ":nearby_visibility_page", @@ -109,9 +123,31 @@ ] } +js_library("nearby_device_icon") { + deps = [ + "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", + "//chromeos/services/nearby/public/mojom:nearby_share_target_types_js_library_for_compile", + "//third_party/polymer/v1_0/components-chromium/iron-icon:iron-icon-extracted", + ] +} + +js_library("nearby_device") { + deps = [ + ":nearby_device_icon", + "//third_party/polymer/v1_0/components-chromium/iron-icon:iron-icon-extracted", + ] +} + js_library("nearby_page_template") { } +js_library("nearby_progress") { + deps = [ + ":nearby_device_icon", + "//third_party/polymer/v1_0/components-chromium/iron-icon:iron-icon-extracted", + ] +} + js_library("nearby_onboarding_page") { deps = [ ":nearby_page_template", @@ -157,8 +193,11 @@ deps = [ ":nearby_contact_manager.m", ":nearby_contact_visibility.m", + ":nearby_device_icon.m", + ":nearby_device.m", ":nearby_onboarding_page.m", ":nearby_page_template.m", + ":nearby_progress.m", ":nearby_share_settings.m", ":nearby_share_settings_behavior.m", ":nearby_visibility_page.m", @@ -169,12 +208,17 @@ public_deps = [ ":modulize", ":nearby_contact_visibility_module", + ":nearby_device_icon_module", + ":nearby_device_module", ":nearby_onboarding_page_module", ":nearby_page_template_module", + ":nearby_progress_module", ":nearby_shared_icons_module", ":nearby_shared_share_type_icons_module", ":nearby_visibility_page_module", + "//chrome/browser/ui/webui/nearby_share:mojom_js", "//chrome/browser/ui/webui/nearby_share/public/mojom:mojom_js", + "//chromeos/services/nearby/public/mojom:nearby_share_target_types_js", ] } @@ -203,6 +247,25 @@ extra_deps = [ ":nearby_contact_visibility_module" ] } +js_library("nearby_device_icon.m") { + sources = [ "$root_gen_dir/chrome/browser/resources/nearby_share/shared/nearby_device_icon.m.js" ] + deps = [ + "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", + "//chromeos/services/nearby/public/mojom:nearby_share_target_types_js_library_for_compile", + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + ] + extra_deps = [ ":nearby_device_icon_module" ] +} + +js_library("nearby_device.m") { + sources = [ "$root_gen_dir/chrome/browser/resources/nearby_share/shared/nearby_device.m.js" ] + deps = [ + ":nearby_device_icon.m", + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + ] + extra_deps = [ ":nearby_device_module" ] +} + js_library("nearby_onboarding_page.m") { sources = [ "$root_gen_dir/chrome/browser/resources/nearby_share/shared/nearby_onboarding_page.m.js" ] deps = [ @@ -220,6 +283,15 @@ extra_deps = [ ":nearby_page_template_module" ] } +js_library("nearby_progress.m") { + sources = [ "$root_gen_dir/chrome/browser/resources/nearby_share/shared/nearby_progress.m.js" ] + deps = [ + ":nearby_device_icon.m", + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + ] + extra_deps = [ ":nearby_progress_module" ] +} + js_library("nearby_share_settings_behavior.m") { sources = [ "$root_gen_dir/chrome/browser/resources/nearby_share/shared/nearby_share_settings_behavior.m.js" ] deps = [ @@ -259,6 +331,22 @@ namespace_rewrites = nearby_shared_namespace_rewrites } +polymer_modulizer("nearby_device_icon") { + js_file = "nearby_device_icon.js" + html_file = "nearby_device_icon.html" + html_type = "dom-module" + auto_imports = nearby_shared_auto_imports + namespace_rewrites = nearby_shared_namespace_rewrites +} + +polymer_modulizer("nearby_device") { + js_file = "nearby_device.js" + html_file = "nearby_device.html" + html_type = "dom-module" + auto_imports = nearby_shared_auto_imports + namespace_rewrites = nearby_shared_namespace_rewrites +} + polymer_modulizer("nearby_onboarding_page") { js_file = "nearby_onboarding_page.js" html_file = "nearby_onboarding_page.html" @@ -275,6 +363,14 @@ namespace_rewrites = nearby_shared_namespace_rewrites } +polymer_modulizer("nearby_progress") { + js_file = "nearby_progress.js" + html_file = "nearby_progress.html" + html_type = "dom-module" + auto_imports = nearby_shared_auto_imports + namespace_rewrites = nearby_shared_namespace_rewrites +} + polymer_modulizer("nearby_shared_icons") { js_file = "nearby_shared_icons.m.js" html_file = "nearby_shared_icons.html"
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_device.html b/chrome/browser/resources/nearby_share/shared/nearby_device.html new file mode 100644 index 0000000..a6431c3 --- /dev/null +++ b/chrome/browser/resources/nearby_share/shared/nearby_device.html
@@ -0,0 +1,84 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="nearby_shared_icons.html"> +<link rel="import" href="nearby_device_icon.html"> + +<dom-module id="nearby-device"> + <template> + <style> + #wrapper { + align-items: center; + background-color: rgb(255, 255, 255); + border: 1px solid rgba(216, 216, 216, 0.76); + border-radius: 8px; + box-sizing: border-box; + cursor: pointer; + display: flex; + height: 40px; + margin-block-end: 6px; + padding-block-end: 6px; + padding-block-start: 6px; + padding-inline-end: 9px; + padding-inline-start: 9px; + } + + :host(:focus) { + outline: none; + } + + :host(:focus) #wrapper { + border-color: var(--google-grey-refresh-700); + } + + :host([is-selected]) #wrapper { + border-color: var(--google-blue-refresh-500); + } + + :host([is-selected]) #done { + display: flex; + } + + :host([is-selected]) #name { + color: var(--google-blue-600); + } + + #done { + color: var(--google-blue-600); + display: none; + flex-shrink: 0; + height: 17px; + width: 17px; + } + + #icon { + --nearby-device-icon-size: 15px; + flex-shrink: 0; + height: 26px; + width: 26px; + } + + #name { + color: rgb(95, 99, 104); + flex-grow: 1; + font-size: 11px; + font-weight: 500; + letter-spacing: 0.3px; + margin-inline-start: 11px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + </style> + + <div id="wrapper"> + <nearby-device-icon id="icon" share-target="[[shareTarget]]"> + </nearby-device-icon> + <div id="name">[[shareTarget.name]]</div> + <iron-icon id="done" icon="nearby-share:done"></iron-icon> + </div> + </template> + <script src="nearby_device.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_device.js b/chrome/browser/resources/nearby_share/shared/nearby_device.js new file mode 100644 index 0000000..76b76cd --- /dev/null +++ b/chrome/browser/resources/nearby_share/shared/nearby_device.js
@@ -0,0 +1,32 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview The 'nearby-device' component shows details of a remote device. + */ + +Polymer({ + is: 'nearby-device', + + properties: { + /** + * Expected to start as null, then change to a valid object before this + * component is shown. + * @type {?nearbyShare.mojom.ShareTarget} + */ + shareTarget: { + type: Object, + value: null, + }, + + /** + * Whether this share target is selected. + * @type {boolean} + */ + isSelected: { + type: Boolean, + reflectToAttribute: true, + }, + }, +});
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_device_icon.html b/chrome/browser/resources/nearby_share/shared/nearby_device_icon.html new file mode 100644 index 0000000..1af979d --- /dev/null +++ b/chrome/browser/resources/nearby_share/shared/nearby_device_icon.html
@@ -0,0 +1,35 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="nearby_shared_icons.html"> + +<script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script> +<script src="chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js"></script> +<script src="/mojo/nearby_share_target_types.mojom-lite.js"></script> +<script src="/mojo/nearby_share.mojom-lite.js"></script> + +<dom-module id="nearby-device-icon"> + <template> + <style> + :host { + background-color: var(--nearby-device-icon-background-color, + var(--google-blue-50)); + border-radius: 50%; + display: flex; + } + + #icon { + color: var(--nearby-device-icon-color, var(--google-blue-600)); + height: var(--nearby-device-icon-size, 24px); + margin: auto; + width: var(--nearby-device-icon-size, 24px); + } + </style> + + <iron-icon id="icon" icon="[[getShareTargetIcon_(shareTarget)]]"> + </iron-icon> + </template> + <script src="nearby_device_icon.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/nearby_share/nearby_device_icon.js b/chrome/browser/resources/nearby_share/shared/nearby_device_icon.js similarity index 71% rename from chrome/browser/resources/nearby_share/nearby_device_icon.js rename to chrome/browser/resources/nearby_share/shared/nearby_device_icon.js index cce84e0..8e6b50c5 100644 --- a/chrome/browser/resources/nearby_share/nearby_device_icon.js +++ b/chrome/browser/resources/nearby_share/shared/nearby_device_icon.js
@@ -8,20 +8,9 @@ * type. */ -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; -import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; -import './icons.js'; -import './mojo/nearby_share_target_types.mojom-lite.js'; -import './mojo/nearby_share.mojom-lite.js'; - -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - Polymer({ is: 'nearby-device-icon', - _template: html`{__html_template__}`, - properties: { /** * The share target to show the icon for. Expected to start as null, then
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_page_template.html b/chrome/browser/resources/nearby_share/shared/nearby_page_template.html index e2645f9..0320bb0 100644 --- a/chrome/browser/resources/nearby_share/shared/nearby_page_template.html +++ b/chrome/browser/resources/nearby_share/shared/nearby_page_template.html
@@ -70,23 +70,32 @@ </div> <div id="actions"> - <template is="dom-if" if="[[utilityButtonLabel]]"> - <cr-button id="utilityButton" class="cancel-button" - on-click="onUtilityClick_" aria-label="[[utilityButtonLabel]]"> - [[utilityButtonLabel]] - </cr-button> + <template is="dom-if" if="[[!closeOnly]]"> + <template is="dom-if" if="[[utilityButtonLabel]]"> + <cr-button id="utilityButton" class="cancel-button" + on-click="onUtilityClick_" aria-label="[[utilityButtonLabel]]"> + [[utilityButtonLabel]] + </cr-button> + </template> + <template is="dom-if" if="[[cancelButtonLabel]]"> + <cr-button id="cancelButton" class="cancel-button" + on-click="onCancelClick_" aria-label="[[cancelButtonLabel]]"> + [[cancelButtonLabel]] + </cr-button> + </template> + <template is="dom-if" if="[[actionButtonLabel]]"> + <cr-button id="actionButton" class="action-button" + on-click="onActionClick_" disabled="[[actionDisabled]]" + aria-label="[[actionButtonLabel]]"> + [[actionButtonLabel]] + </cr-button> + </template> </template> - <template is="dom-if" if="[[cancelButtonLabel]]"> - <cr-button id="cancelButton" class="cancel-button" - on-click="onCancelClick_" aria-label="[[cancelButtonLabel]]"> - [[cancelButtonLabel]] - </cr-button> - </template> - <template is="dom-if" if="[[actionButtonLabel]]"> - <cr-button id="actionButton" class="action-button" - on-click="onActionClick_" disabled="[[actionDisabled]]" - aria-label="[[actionButtonLabel]]"> - [[actionButtonLabel]] + <template is="dom-if" if="[[closeOnly]]"> + <cr-button id="closeButton" class="action-button" + on-click="onCloseClick_" + aria-label="$i18n{nearbyShareActionsClose}"> + $i18n{nearbyShareActionsClose} </cr-button> </template> </div>
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_page_template.js b/chrome/browser/resources/nearby_share/shared/nearby_page_template.js index b86501be..4aac7cf 100644 --- a/chrome/browser/resources/nearby_share/shared/nearby_page_template.js +++ b/chrome/browser/resources/nearby_share/shared/nearby_page_template.js
@@ -21,23 +21,28 @@ type: String, }, - /** @type {?string} */ + /** + * Text to show on the action button. If either this is falsey, or if + * |closeOnly| is true, then the action button is hidden. + * @type {?string} + * */ actionButtonLabel: { type: String, }, /** @type {string} */ - actionButtonEventName: { - type: String, - value: 'action' - }, + actionButtonEventName: {type: String, value: 'action'}, actionDisabled: { type: Boolean, value: false, }, - /** @type {?string} */ + /** + * Text to show on the cancel button. If either this is falsey, or if + * |closeOnly| is true, then the cancel button is hidden. + * @type {?string} + * */ cancelButtonLabel: { type: String, }, @@ -48,7 +53,11 @@ value: 'cancel', }, - /** @type {?string} */ + /** + * Text to show on the utility button. If either this is falsey, or if + * |closeOnly| is true, then the utility button is hidden. + * @type {?string} + * */ utilityButtonLabel: { type: String, }, @@ -57,7 +66,16 @@ utilityButtonEventName: { type: String, value: 'utility', - } + }, + + /** + * When true, hide all other buttons and show a close button. + * @type {boolean} + * */ + closeOnly: { + type: Boolean, + value: false, + }, }, /** @private */ @@ -74,4 +92,9 @@ onUtilityClick_() { this.fire(this.utilityButtonEventName); }, + + /** @private */ + onCloseClick_() { + this.fire('close'); + }, });
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_progress.html b/chrome/browser/resources/nearby_share/shared/nearby_progress.html new file mode 100644 index 0000000..2fb5c05 --- /dev/null +++ b/chrome/browser/resources/nearby_share/shared/nearby_progress.html
@@ -0,0 +1,121 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> +<link rel="import" href="nearby_shared_icons.html"> +<link rel="import" href="nearby_device_icon.html"> + +<dom-module id="nearby-progress"> + <template> + <style> + #device-name { + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + color: rgba(0, 0, 0, 0.87); + display: -webkit-box; + letter-spacing: 0.25px; + line-height: 154%; + overflow: hidden; + text-align: center; + } + + #icon { + height: 68px; + margin: auto; + width: 68px; + } + + .has-error #icon { + --nearby-device-icon-color: var(--google-grey-600); + --nearby-device-icon-background-color: var(--google-grey-200); + } + + #progress-container { + display: flex; + height: 76px; + margin: 8px auto 20px auto; + position: relative; + width: 76px; + } + + #wheel { + fill: none; + stroke: var(--google-blue-600); + stroke-dasharray: 100; + stroke-dashoffset: calc(100 - var(--progress-percentage, 0)); + stroke-linecap: round; + stroke-width: 2px; + transform: rotate(-90deg); + transform-origin: 50% 50%; + transition: stroke-dashoffset 400ms ease; + } + + .unknown-progress #wheel { + animation: 1.4s ease-in-out infinite both unknown-progress-animation; + stroke-dasharray: 116; + } + + .has-error #wheel { + animation: none; + stroke: var(--google-red-600); + stroke-dashoffset: 0; + } + + #svg { + left: 0; + position: absolute; + top: 0; + } + + .unknown-progress #svg { + animation: 2s linear infinite svg-animation; + } + + .has-error #svg { + animation: none; + } + + @keyframes unknown-progress-animation { + 0%, + 25% { + stroke-dashoffset: 115; + transform: rotate(0); + } + 50%, + 75% { + stroke-dashoffset: 30; + transform: rotate(45deg); + } + 100% { + stroke-dashoffset: 115; + transform: rotate(360deg); + } + } + + @keyframes svg-animation { + 0% { transform: rotateZ(0deg); } + 100% { transform: rotateZ(360deg); } + } + </style> + + <div id="progress-container" role="progressbar" aria-valuemin="0" + aria-valuemax="100" aria-valuenow$="[[progress]]" + tabindex$="[[getProgressBarTabIndex_(progress)]]" + class$="[[getProgressWheelClass_(progress, hasError)]]"> + <!-- This svg is inlined so that it can be styled with css; otherwise, + it would be better to put it in an iron-icon. --> + <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"> + <circle id="wheel" + cx="40" cy="40" r="39" pathLength="100"> + </circle> + </svg> + <nearby-device-icon id="icon" share-target="[[shareTarget]]"> + </nearby-device-icon> + </div> + <div id="device-name" + aria-label="$i18n{nearbyShareOnboardingPageDeviceName}"> + [[shareTarget.name]] + </div> + </template> + <script src="nearby_progress.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/nearby_share/nearby_progress.js b/chrome/browser/resources/nearby_share/shared/nearby_progress.js similarity index 83% rename from chrome/browser/resources/nearby_share/nearby_progress.js rename to chrome/browser/resources/nearby_share/shared/nearby_progress.js index 43481a8..ddfe226 100644 --- a/chrome/browser/resources/nearby_share/nearby_progress.js +++ b/chrome/browser/resources/nearby_share/shared/nearby_progress.js
@@ -9,19 +9,9 @@ * an animation if the percentage is unknown. */ -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; -import './nearby_device_icon.js'; -import './mojo/nearby_share_target_types.mojom-lite.js'; -import './mojo/nearby_share.mojom-lite.js'; - -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - Polymer({ is: 'nearby-progress', - _template: html`{__html_template__}`, - properties: { /** * The share target to show the progress for. Expected to start as null,
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_shared_icons.html b/chrome/browser/resources/nearby_share/shared/nearby_shared_icons.html index 936a299..e1f6fe74 100644 --- a/chrome/browser/resources/nearby_share/shared/nearby_shared_icons.html +++ b/chrome/browser/resources/nearby_share/shared/nearby_shared_icons.html
@@ -36,6 +36,23 @@ </svg> </iron-iconset-svg> +<iron-iconset-svg name="nearby-share" size="24"> + <svg> + <defs> + <!-- Nearby Share icons --> + <g id="done"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"></path></g> + + <!-- + These icons are copied from Polymer's iron-icons and kept in sorted order. + See http://goo.gl/Y1OdAq for instructions on adding additional icons. + --> + <g id="laptop"><path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"></path></g> + <g id="smartphone"><path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"></path></g> + <g id="tablet"><path d="M21 4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 1.99-.9 1.99-2L23 6c0-1.1-.9-2-2-2zm-2 14H5V6h14v12z"></path></g> + </defs> + </svg> +</iron-iconset-svg> + <iron-iconset-svg name="nearby-images" size="200"> <svg> <defs>
diff --git a/chrome/browser/resources/new_tab_page/app.html b/chrome/browser/resources/new_tab_page/app.html index 482e801b6..d13639a8 100644 --- a/chrome/browser/resources/new_tab_page/app.html +++ b/chrome/browser/resources/new_tab_page/app.html
@@ -349,7 +349,7 @@ <dom-if if="[[lazyRender_]]" restamp> <template> <cr-toast id="dismissModuleToast" duration="10000"> - <div id="dismissModuleToastMessage">[[dismissedModuleData_.message]]</div> + <div id="dismissModuleToastMessage">[[dismissModuleToastMessage_]]</div> <cr-button id="undoDismissModuleButton" aria-label="$i18n{undoDescription}" on-click="onUndoDismissModuleButtonClick_">
diff --git a/chrome/browser/resources/new_tab_page/app.js b/chrome/browser/resources/new_tab_page/app.js index a054f731..76645c82 100644 --- a/chrome/browser/resources/new_tab_page/app.js +++ b/chrome/browser/resources/new_tab_page/app.js
@@ -248,15 +248,21 @@ moduleDescriptors_: Object, /** - * Data about the most recently dismissed module. - * @type {?{id: string, element: !Element, message: string, - * restoreCallback: function()}} + * The <ntp-module-wrapper> element of the last dismissed module. + * @type {?Element} * @private */ - dismissedModuleData_: { + dismissedModuleWrapper_: { type: Object, value: null, }, + + /** + * The message shown in the toast when a module is dismissed. + * @type {string} + * @private + */ + dismissModuleToastMessage_: String, }; } @@ -879,25 +885,19 @@ } /** - * @param {!CustomEvent<{message: string, restoreCallback: function()}>} e - * Event notifying a module was dismissed. Contains the message to show in - * the toast. + * @param {!CustomEvent<string>} e Event notifying a module was dismissed. + * Contains the message to show in the toast. * @private */ onDismissModule_(e) { - this.dismissedModuleData_ = { - id: $$(this, '#modules').itemForElement(e.target).id, - element: /** @type {!Element} */ (e.target), - message: loadTimeData.getStringF( - 'dismissModuleToastMessage', e.detail.message), - restoreCallback: e.detail.restoreCallback, - }; - this.dismissedModuleData_.element.hidden = true; + this.dismissedModuleWrapper_ = /** @type {!Element} */ (e.target); // Notify the user. + this.dismissModuleToastMessage_ = e.detail; $$(this, '#dismissModuleToast').show(); // Notify the backend. - this.pageHandler_.onDismissModule(this.dismissedModuleData_.id); + this.pageHandler_.onDismissModule( + this.dismissedModuleWrapper_.descriptor.id); } /** @@ -905,15 +905,14 @@ */ onUndoDismissModuleButtonClick_() { // Restore the module. - this.dismissedModuleData_.restoreCallback(); - this.dismissedModuleData_.element.hidden = false; - + this.dismissedModuleWrapper_.restore(); // Notify the user. $$(this, '#dismissModuleToast').hide(); // Notify the backend. - this.pageHandler_.onRestoreModule(this.dismissedModuleData_.id); + this.pageHandler_.onRestoreModule( + this.dismissedModuleWrapper_.descriptor.id); - this.dismissedModuleData_ = null; + this.dismissedModuleWrapper_ = null; } /**
diff --git a/chrome/browser/resources/new_tab_page/modules/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/BUILD.gn index 8aad5ce..50f191d 100644 --- a/chrome/browser/resources/new_tab_page/modules/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/BUILD.gn
@@ -29,12 +29,6 @@ ] } -js_library("module_header") { - deps = [ - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - js_library("module_registry") { deps = [ ":module_descriptor", @@ -43,10 +37,7 @@ } html_to_js("web_components_local") { - js_files = [ - "module_header.js", - "module_wrapper.js", - ] + js_files = [ "module_wrapper.js" ] } group("web_components") { @@ -85,7 +76,6 @@ in_folder = target_gen_dir out_folder = "$target_gen_dir/$preprocess_folder" in_files = [ - "module_header.js", "module_wrapper.js", "dummy/module.js", "task_module/module.js",
diff --git a/chrome/browser/resources/new_tab_page/modules/dummy/module.html b/chrome/browser/resources/new_tab_page/modules/dummy/module.html index 7da21dc..1c21ec5 100644 --- a/chrome/browser/resources/new_tab_page/modules/dummy/module.html +++ b/chrome/browser/resources/new_tab_page/modules/dummy/module.html
@@ -1,19 +1,8 @@ <style> - :host { - width: 100%; - } - cr-grid { --cr-grid-gap: 8px; } - #moduleContent { - align-items: center; - display: flex; - height: 260px; - justify-content: center; - } - .tile-item { color: var(--cr-primary-text-color); height: 120px; @@ -24,14 +13,11 @@ border-radius: 8px; } </style> -<ntp-module-header module-id="[[id]]">[[title]]</ntp-module-header> -<div id="moduleContent"> - <cr-grid id="tiles" columns="3"> - <template id="tileList" is="dom-repeat" items="[[tiles]]"> - <div class="tile-item" title="[[item.label]]"> - <img is="ntp-img" auto-src="[[item.imageUrl]]"></img> - <span>[[item.value]]</span> - </div> - </template> - </cr-grid> -</div> +<cr-grid id="tiles" columns="3"> + <template id="tileList" is="dom-repeat" items="[[tiles]]"> + <div class="tile-item" title="[[item.label]]"> + <img is="ntp-img" auto-src="[[item.imageUrl]]"></img> + <span>[[item.value]]</span> + </div> + </template> +</cr-grid>
diff --git a/chrome/browser/resources/new_tab_page/modules/dummy/module.js b/chrome/browser/resources/new_tab_page/modules/dummy/module.js index 7ae904f..28c83d3e 100644 --- a/chrome/browser/resources/new_tab_page/modules/dummy/module.js +++ b/chrome/browser/resources/new_tab_page/modules/dummy/module.js
@@ -6,7 +6,6 @@ import '../../img.js'; import '../../strings.m.js'; -import '../module_header.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; @@ -30,14 +29,8 @@ static get properties() { return { - /** @type {!string} */ - id: String, - /** @type {!Array<!foo.mojom.FooDataItem>} */ tiles: Array, - - /** @type {!string} */ - title: String, }; } @@ -55,26 +48,18 @@ customElements.define(DummyModuleElement.is, DummyModuleElement); -/** - * @param {!string} id - * @param {!string} titleId - * @return {!DummyModuleElement} - */ -function createDummyElement(id, titleId) { - const element = new DummyModuleElement(); - element.id = id; - element.title = loadTimeData.getString(titleId); - return element; -} - /** @type {!ModuleDescriptor} */ export const dummyDescriptor = new ModuleDescriptor( /*id=*/ 'dummy', - /*heightPx=*/ 314, - () => Promise.resolve(createDummyElement('dummy', 'modulesDummyTitle'))); + /*heightPx=*/ 260, () => Promise.resolve({ + element: new DummyModuleElement(), + title: loadTimeData.getString('modulesDummyTitle'), + })); /** @type {!ModuleDescriptor} */ export const dummyDescriptor2 = new ModuleDescriptor( /*id=*/ 'dummy2', - /*heightPx=*/ 314, - () => Promise.resolve(createDummyElement('dummy2', 'modulesDummy2Title'))); + /*heightPx=*/ 260, () => Promise.resolve({ + element: new DummyModuleElement(), + title: loadTimeData.getString('modulesDummy2Title'), + }));
diff --git a/chrome/browser/resources/new_tab_page/modules/kaleidoscope/externs.js b/chrome/browser/resources/new_tab_page/modules/kaleidoscope/externs.js index 4c4232a..552315b 100644 --- a/chrome/browser/resources/new_tab_page/modules/kaleidoscope/externs.js +++ b/chrome/browser/resources/new_tab_page/modules/kaleidoscope/externs.js
@@ -3,6 +3,9 @@ // found in the LICENSE file. /** - * @returns {Promise<?HTMLElement>} + * @returns {Promise<?{ + * element: !HTMLElement, + * title: string, + * }>} */ window.loadKaleidoscopeModule = () => {};
diff --git a/chrome/browser/resources/new_tab_page/modules/kaleidoscope/module.js b/chrome/browser/resources/new_tab_page/modules/kaleidoscope/module.js index c12cb48..2cc426e 100644 --- a/chrome/browser/resources/new_tab_page/modules/kaleidoscope/module.js +++ b/chrome/browser/resources/new_tab_page/modules/kaleidoscope/module.js
@@ -13,7 +13,7 @@ /** @type {!ModuleDescriptor} */ export const kaleidoscopeDescriptor = new ModuleDescriptor( /*id=*/ 'kaleidoscope', - /*heightPx=*/ 384, + /*heightPx=*/ 330, async () => { return loadKaleidoscopeModule(); },
diff --git a/chrome/browser/resources/new_tab_page/modules/module_descriptor.js b/chrome/browser/resources/new_tab_page/modules/module_descriptor.js index 8032f597..a77ab16d 100644 --- a/chrome/browser/resources/new_tab_page/modules/module_descriptor.js +++ b/chrome/browser/resources/new_tab_page/modules/module_descriptor.js
@@ -10,7 +10,20 @@ */ /** - * @typedef {function(): !Promise<?HTMLElement>} + * @typedef {{ + * info: (function()|undefined), + * dismiss: (function():string|undefined), + * restore: (function()|undefined), + * }} + */ +let Actions; + +/** + * @typedef {function(): !Promise<?{ + * element: !HTMLElement, + * title: string, + * actions: (undefined|Actions), + * }>} */ let InitializeModuleCallback; @@ -25,10 +38,14 @@ this.id_ = id; /** @private {number} */ this.heightPx_ = heightPx; + /** @private {?string} */ + this.title_ = null; /** @private {HTMLElement} */ this.element_ = null; /** @private {!InitializeModuleCallback} */ this.initializeCallback_ = initializeCallback; + /** @private {?Actions} */ + this.actions_ = null; } /** @return {string} */ @@ -41,16 +58,29 @@ return this.heightPx_; } + /** @return {?string} */ + get title() { + return this.title_; + } + /** @return {?HTMLElement} */ get element() { return this.element_; } + /** @return {?Actions} */ + get actions() { + return this.actions_; + } + async initialize() { - this.element_ = await this.initializeCallback_(); - if (!this.element_) { + const info = await this.initializeCallback_(); + if (!info) { return; } + this.title_ = info.title; + this.element_ = info.element; + this.actions_ = info.actions || null; BrowserProxy.getInstance().handler.onModuleLoaded( this.id_, BrowserProxy.getInstance().now()); }
diff --git a/chrome/browser/resources/new_tab_page/modules/module_header.html b/chrome/browser/resources/new_tab_page/modules/module_header.html deleted file mode 100644 index 04f70e71..0000000 --- a/chrome/browser/resources/new_tab_page/modules/module_header.html +++ /dev/null
@@ -1,37 +0,0 @@ -<style include="cr-icons"> - :host { - align-items: center; - display: flex; - height: 22px; - margin: 16px; - } - - #title { - color: var(--cr-primary-text-color); - font-size: 15px; - } - - #headerSpacer { - flex-grow: 1; - } - - #infoButton { - --cr-icon-image: url(./icons/info.svg); - } - - #dismissButton { - --cr-icon-button-margin-start: 4px; - } -</style> -<span id="title"><slot></slot></span> -<div id="headerSpacer"></div> -<template is="dom-if" if="[[showInfoButton]]"> - <cr-icon-button id="infoButton" title="$i18n{moduleInfoButtonTitle}" - on-click="onInfoButtonClick_"> - </cr-icon-button> -</template> -<template is="dom-if" if="[[showDismissButton]]"> - <cr-icon-button id="dismissButton" title="$i18n{moduleDismissButtonTitle}" - class="icon-clear" on-click="onDismissButtonClick_"> - </cr-icon-button> -</template>
diff --git a/chrome/browser/resources/new_tab_page/modules/module_header.js b/chrome/browser/resources/new_tab_page/modules/module_header.js deleted file mode 100644 index 148e6e99..0000000 --- a/chrome/browser/resources/new_tab_page/modules/module_header.js +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {assert} from 'chrome://resources/js/assert.m.js'; -import {html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -import {BrowserProxy} from '../browser_proxy.js'; - -/** @fileoverview Element that displays a header inside a module. */ - -class ModuleHeaderElement extends PolymerElement { - static get is() { - return 'ntp-module-header'; - } - - static get template() { - return html`{__html_template__}`; - } - - static get properties() { - return { - /** - * The ID of the module. - * @type {!string} - */ - moduleId: String, - - /** - * The title to be displayed. - * @type {!string} - */ - title: String, - - /** - * True if the header should display an info button. - * @type {boolean} - */ - showInfoButton: { - type: Boolean, - value: false, - }, - - /** - * True if the header should display a dismiss button. - * @type {boolean} - */ - showDismissButton: { - type: Boolean, - value: false, - }, - }; - } - - ready() { - super.ready(); - const observer = new IntersectionObserver(([{intersectionRatio}]) => { - if (intersectionRatio >= .5) { - observer.disconnect(); - BrowserProxy.getInstance().handler.onModuleImpression( - this.moduleId, BrowserProxy.getInstance().now()); - } - }, {threshold: .5}); - // Calling observe will immediately invoke the callback. If the header is - // fully shown when the page loads, the first callback invocation will - // happen before the header has dimensions. For this reason, we start - // observing after the element has had a chance to be rendered. - microTask.run(() => { - observer.observe(this); - }); - } - - /** @private */ - onInfoButtonClick_() { - this.dispatchEvent(new CustomEvent('info-button-click', {bubbles: true})); - } - - /** @private */ - onDismissButtonClick_() { - this.dispatchEvent( - new CustomEvent('dismiss-button-click', {bubbles: true})); - } -} - -customElements.define(ModuleHeaderElement.is, ModuleHeaderElement);
diff --git a/chrome/browser/resources/new_tab_page/modules/module_wrapper.html b/chrome/browser/resources/new_tab_page/modules/module_wrapper.html index 6b0693d..11f4f72 100644 --- a/chrome/browser/resources/new_tab_page/modules/module_wrapper.html +++ b/chrome/browser/resources/new_tab_page/modules/module_wrapper.html
@@ -1,4 +1,4 @@ -<style> +<style include="cr-icons"> :host { background-color: var(--ntp-background-override-color); border: solid var(--ntp-border-color) 1px; @@ -8,10 +8,48 @@ overflow: hidden; } + #header { + align-items: center; + display: flex; + height: 22px; + margin: 16px; + } + + #title { + color: var(--cr-primary-text-color); + font-size: 15px; + } + + #headerSpacer { + flex-grow: 1; + } + + #infoButton { + --cr-icon-image: url(./icons/info.svg); + } + + #dismissButton { + --cr-icon-button-margin-start: 4px; + } + #moduleElement { align-items: center; display: flex; justify-content: center; } </style> +<div id="header"> + <span id="title">[[descriptor.title]]</span> + <div id="headerSpacer"></div> + <template is="dom-if" if="[[descriptor.actions.info]]"> + <cr-icon-button id="infoButton" title="$i18n{moduleInfoButtonTitle}" + on-click="onInfoButtonClick_"> + </cr-icon-button> + </template> + <template is="dom-if" if="[[descriptor.actions.dismiss]]"> + <cr-icon-button id="dismissButton" title="$i18n{moduleDismissButtonTitle}" + class="icon-clear" on-click="onDismissButtonClick_"> + </cr-icon-button> + </template> +</div> <div id="moduleElement"></div>
diff --git a/chrome/browser/resources/new_tab_page/modules/module_wrapper.js b/chrome/browser/resources/new_tab_page/modules/module_wrapper.js index fa20545..d73701ca 100644 --- a/chrome/browser/resources/new_tab_page/modules/module_wrapper.js +++ b/chrome/browser/resources/new_tab_page/modules/module_wrapper.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert} from 'chrome://resources/js/assert.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BrowserProxy} from '../browser_proxy.js'; import {ModuleDescriptor} from './module_descriptor.js'; @@ -38,13 +38,49 @@ assert(!oldValue); this.$.moduleElement.appendChild(this.descriptor.element); this.$.moduleElement.style.height = `${this.descriptor.heightPx}px`; - + const observer = new IntersectionObserver(([{intersectionRatio}]) => { + if (intersectionRatio >= .5) { + observer.disconnect(); + BrowserProxy.getInstance().handler.onModuleImpression( + this.descriptor.id, BrowserProxy.getInstance().now()); + } + }, {threshold: .5}); + // Calling observe will immediately invoke the callback. If the header is + // fully shown when the page loads, the first callback invocation will + // happen before the header has dimensions. For this reason, we start + // observing after the element has had a chance to be rendered. + microTask.run(() => { + observer.observe(this.$.header); + }); // Log at most one usage per module per NTP page load. This is possible, // if a user opens a link in a new tab. this.descriptor.element.addEventListener('usage', () => { BrowserProxy.getInstance().handler.onModuleUsage(this.descriptor.id); }, {once: true}); } + + /** @private */ + onInfoButtonClick_() { + this.descriptor.actions.info(); + } + + /** @private */ + onDismissButtonClick_() { + this.hidden = true; + const message = this.descriptor.actions.dismiss(); + this.dispatchEvent(new CustomEvent('dismiss-module', { + bubbles: true, + composed: true, + detail: message, + })); + } + + restore() { + this.hidden = false; + if (this.descriptor.actions.restore) { + this.descriptor.actions.restore(); + } + } } customElements.define(ModuleWrapperElement.is, ModuleWrapperElement);
diff --git a/chrome/browser/resources/new_tab_page/modules/task_module/module.html b/chrome/browser/resources/new_tab_page/modules/task_module/module.html index e107431..ac2c08b 100644 --- a/chrome/browser/resources/new_tab_page/modules/task_module/module.html +++ b/chrome/browser/resources/new_tab_page/modules/task_module/module.html
@@ -1,15 +1,8 @@ <style include="cr-hidden-style"> :host { - display: flex; - flex-direction: column; - height: 100%; - width: 100%; - } - - #moduleContent { box-sizing: border-box; display: block; - flex-grow: 1; + height: 100%; padding-inline-end: 15px; padding-inline-start: 15px; width: 100%; @@ -177,38 +170,31 @@ text-decoration: none; } </style> -<ntp-module-header module-id="[[id]]" - show-info-button on-info-button-click="onInfoButtonClick_" - show-dismiss-button on-dismiss-button-click="onDismissButtonClick_"> - [[task.title]] -</ntp-module-header> -<div id="moduleContent"> - <div id="taskItems"> - <template is="dom-repeat" id="taskItemsRepeat" items="[[task.taskItems]]" - on-dom-change="onDomChange_"> - <a class="task-item" href="[[item.targetUrl.url]]" - on-click="onTaskItemClick_" on-auxclick="onTaskItemClick_"> - <div class="image-background"> - <div class="image-container"> - <img is="ntp-img" auto-src="[[item.imageUrl.url]]"></img> - </div> +<div id="taskItems"> + <template is="dom-repeat" id="taskItemsRepeat" items="[[task.taskItems]]" + on-dom-change="onDomChange_"> + <a class="task-item" href="[[item.targetUrl.url]]" + on-click="onTaskItemClick_" on-auxclick="onTaskItemClick_"> + <div class="image-background"> + <div class="image-container"> + <img is="ntp-img" auto-src="[[item.imageUrl.url]]"></img> </div> - <div class="price" hidden$="[[!item.price]]">[[item.price]]</div> - <div class="name" title="[[item.name]]">[[item.name]]</div> - <div class="info">[[item.info]]</div> - </a> - </template> - </div> - <div id="relatedSearches"> - <template is="dom-repeat" id="relatedSearchesRepeat" - items="[[task.relatedSearches]]" on-dom-change="onDomChange_"> - <a class="pill" href="[[item.targetUrl.url]]" on-click="onPillClick_" - on-auxclick="onPillClick_"> - <div class="loupe"></div> - <div class="search-text">[[item.text]]</div> - </a> - </template> - </div> + </div> + <div class="price" hidden$="[[!item.price]]">[[item.price]]</div> + <div class="name" title="[[item.name]]">[[item.name]]</div> + <div class="info">[[item.info]]</div> + </a> + </template> +</div> +<div id="relatedSearches"> + <template is="dom-repeat" id="relatedSearchesRepeat" + items="[[task.relatedSearches]]" on-dom-change="onDomChange_"> + <a class="pill" href="[[item.targetUrl.url]]" on-click="onPillClick_" + on-auxclick="onPillClick_"> + <div class="loupe"></div> + <div class="search-text">[[item.text]]</div> + </a> + </template> </div> <template is="dom-if" if="[[showInfoDialog]]" restamp> <cr-dialog show-on-attach>
diff --git a/chrome/browser/resources/new_tab_page/modules/task_module/module.js b/chrome/browser/resources/new_tab_page/modules/task_module/module.js index 783bdfad..58217b3 100644 --- a/chrome/browser/resources/new_tab_page/modules/task_module/module.js +++ b/chrome/browser/resources/new_tab_page/modules/task_module/module.js
@@ -3,9 +3,9 @@ // found in the LICENSE file. import '../../img.js'; -import '../module_header.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ModuleDescriptor} from '../module_descriptor.js'; import {TaskModuleHandlerProxy} from './task_module_handler_proxy.js'; @@ -27,9 +27,6 @@ static get properties() { return { - /** @type {string} */ - id: String, - /** @type {!taskModule.mojom.TaskModuleType} */ taskModuleType: { type: Number, @@ -85,36 +82,11 @@ } /** @private */ - onInfoButtonClick_() { - this.showInfoDialog = true; - } - - /** @private */ onCloseClick_() { this.showInfoDialog = false; } /** @private */ - onDismissButtonClick_() { - TaskModuleHandlerProxy.getInstance().handler.dismissTask( - this.taskModuleType, this.task.name); - this.dispatchEvent(new CustomEvent('dismiss-module', { - bubbles: true, - composed: true, - detail: { - message: this.task.name, - restoreCallback: this.onRestore_.bind(this), - }, - })); - } - - /** @private */ - onRestore_() { - TaskModuleHandlerProxy.getInstance().handler.restoreTask( - this.taskModuleType, this.task.name); - } - - /** @private */ onDomChange_() { if (!this.intersectionObserver_) { this.intersectionObserver_ = new IntersectionObserver(entries => { @@ -134,8 +106,8 @@ customElements.define(TaskModuleElement.is, TaskModuleElement); -/** @return {!Promise<?HTMLElement>} */ -async function createModule(id, taskModuleType) { +/** @return {!Promise<?{element: !HTMLElement, title: string}>} */ +async function createModule(taskModuleType) { const {task} = await TaskModuleHandlerProxy.getInstance().handler.getPrimaryTask( taskModuleType); @@ -145,20 +117,34 @@ const element = new TaskModuleElement(); element.taskModuleType = taskModuleType; element.task = task; - element.id = id; - return element; + return { + element: element, + title: task.title, + actions: { + info: () => { + element.showInfoDialog = true; + }, + dismiss: () => { + TaskModuleHandlerProxy.getInstance().handler.dismissTask( + taskModuleType, task.name); + return loadTimeData.getStringF('dismissModuleToastMessage', task.name); + }, + restore: () => { + TaskModuleHandlerProxy.getInstance().handler.restoreTask( + taskModuleType, task.name); + }, + }, + }; } /** @type {!ModuleDescriptor} */ export const recipeTasksDescriptor = new ModuleDescriptor( /*id=*/ 'recipe_tasks', - /*heightPx=*/ 260, - createModule.bind( - null, 'recipe_tasks', taskModule.mojom.TaskModuleType.kRecipe)); + /*heightPx=*/ 206, + createModule.bind(null, taskModule.mojom.TaskModuleType.kRecipe)); /** @type {!ModuleDescriptor} */ export const shoppingTasksDescriptor = new ModuleDescriptor( /*id=*/ 'shopping_tasks', - /*heightPx=*/ 324, - createModule.bind( - null, 'shopping_tasks', taskModule.mojom.TaskModuleType.kShopping)); + /*heightPx=*/ 270, + createModule.bind(null, taskModule.mojom.TaskModuleType.kShopping));
diff --git a/chrome/browser/resources/settings/autofill_page/password_check_behavior.js b/chrome/browser/resources/settings/autofill_page/password_check_behavior.js index d9eb411..746ae27 100644 --- a/chrome/browser/resources/settings/autofill_page/password_check_behavior.js +++ b/chrome/browser/resources/settings/autofill_page/password_check_behavior.js
@@ -147,6 +147,16 @@ }, /** + * True if weak passwords are shown in SC, in which case the PW check UI + * adapts a bit to show the information in the same form as SC. + * @return {boolean} + * @private + */ + safetyCheckWeakPasswordsEnabled_() { + return loadTimeData.getBoolean('safetyCheckWeakPasswordsEnabled'); + }, + + /** * Helper that fetches pluralized strings corresponding to the number of * compromised, weak and insecure credentials. * @private @@ -162,8 +172,28 @@ proxy.getPluralString('weakPasswords', weak) .then(count => this.weakPasswordsCount = count); - proxy.getPluralString('insecurePasswords', compromised + weak) - .then(count => this.insecurePasswordsCount = count); + (() => { + if (!this.safetyCheckWeakPasswordsEnabled_()) { + // Old code path: adds up compromised and weak passwords. + return proxy.getPluralString('insecurePasswords', compromised + weak); + } + if (compromised > 0 && weak > 0) { + return proxy.getPluralStringTupleWithComma( + 'safetyCheckPasswordsCompromised', compromised, + 'safetyCheckPasswordsWeak', weak); + } + if (compromised > 0) { + // Only compromised and no weak passwords. + return proxy.getPluralString( + 'safetyCheckPasswordsCompromised', compromised); + } + if (weak > 0) { + // Only weak and no compromised passwords. + return proxy.getPluralString('safetyCheckPasswordsWeak', weak); + } + // No security issues. + return proxy.getPluralString('compromisedPasswords', 0); + })().then(count => this.insecurePasswordsCount = count); }, /**
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index a514bb55e5..ca9d259 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -53,6 +53,7 @@ "chrome://os-settings/app-management/file_path.mojom-lite.js", "chrome://os-settings/app-management/image.mojom-lite.js", "chrome://os-settings/app-management/types.mojom-lite.js", + "chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js", "chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom.html", "chrome://resources/mojo/mojo/public/mojom/base/string16.mojom.html", "chrome://resources/mojo/mojo/public/mojom/base/time.mojom.html",
diff --git a/chrome/browser/resources/settings/chromeos/nearby_share_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/nearby_share_page/BUILD.gn index 500ef8e..f720e03d 100644 --- a/chrome/browser/resources/settings/chromeos/nearby_share_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/nearby_share_page/BUILD.gn
@@ -24,8 +24,11 @@ } js_library("nearby_share_confirm_page") { - deps = - [ "//chrome/browser/resources/nearby_share/shared:nearby_page_template" ] + deps = [ + "//chrome/browser/resources/nearby_share/shared:nearby_device", + "//chrome/browser/resources/nearby_share/shared:nearby_page_template", + "//chrome/browser/resources/nearby_share/shared:nearby_progress", + ] } js_library("nearby_account_manager_browser_proxy") { @@ -160,7 +163,9 @@ js_library("nearby_share_confirm_page.m") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_confirm_page.m.js" ] deps = [ + "//chrome/browser/resources/nearby_share/shared:nearby_device.m", "//chrome/browser/resources/nearby_share/shared:nearby_page_template.m", + "//chrome/browser/resources/nearby_share/shared:nearby_progress.m", ] extra_deps = [ ":nearby_share_confirm_page_module" ] }
diff --git a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_confirm_page.html b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_confirm_page.html index 8ab1d9e..7f6edcc 100644 --- a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_confirm_page.html +++ b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_confirm_page.html
@@ -1,6 +1,8 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="../../shared/nearby_page_template.html"> +<link rel="import" href="../../shared/nearby_device.html"> +<link rel="import" href="../../shared/nearby_progress.html"> <dom-module id="nearby-share-confirm-page"> <template>
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.html b/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.html index efe0254..37fe6a0 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.html +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.html
@@ -31,36 +31,18 @@ <cr-link-row on-click="onSelectAssignClick_" id="selectLinkRow" label="$i18n{assignSelectSwitchLabel}" - sub-label="$i18n{assignSwitchSubLabel}" + sub-label="[[getAssignSwitchSubLabel_(selectAssignments_)]]" deep-link-focus-id$="[[Setting.kSwitchActionAssignment]]"> - <ul id="selectAssignmentList"> - <template is="dom-repeat" - items="[[selectAssignments_]]" as="assignment"> - <li>[[assignment]]</li> - </template> - </ul> </cr-link-row> <cr-link-row on-click="onNextAssignClick_" id="nextLinkRow" label="$i18n{assignNextSwitchLabel}" - sub-label="$i18n{assignSwitchSubLabel}"> - <ul id="nextAssignmentList"> - <template is="dom-repeat" - items="[[nextAssignments_]]" as="assignment"> - <li>[[assignment]]</li> - </template> - </ul> + sub-label="[[getAssignSwitchSubLabel_(nextAssignments_)]]"> </cr-link-row> <cr-link-row on-click="onPreviousAssignClick_" id="previousLinkRow" label="$i18n{assignPreviousSwitchLabel}" - sub-label="$i18n{assignSwitchSubLabel}"> - <ul id="previousAssignmentList"> - <template is="dom-repeat" - items="[[previousAssignments_]]" as="assignment"> - <li>[[assignment]]</li> - </template> - </ul> + sub-label="[[getAssignSwitchSubLabel_(previousAssignments_)]]"> </cr-link-row> </div> <template is="dom-if"
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.js b/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.js index c1c40b9..12a2067a 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.js +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/switch_access_subpage.js
@@ -240,6 +240,31 @@ }, /** + * @param {!Array<string>} switches List of switch names + * @return {string} (e.g. 'Alt, Backspace, Enter, and 4 more switches') + * @private + */ + getAssignSwitchSubLabel_(switches) { + switch (switches.length) { + case 0: + return this.i18n('assignSwitchSubLabel0Switches'); + case 1: + return this.i18n('assignSwitchSubLabel1Switch', switches[0]); + case 2: + return this.i18n('assignSwitchSubLabel2Switches', ...switches); + case 3: + return this.i18n('assignSwitchSubLabel3Switches', ...switches); + case 4: + return this.i18n( + 'assignSwitchSubLabel4Switches', ...switches.slice(0, 3)); + default: + return this.i18n( + 'assignSwitchSubLabel5OrMoreSwitches', ...switches.slice(0, 3), + switches.length - 3); + } + }, + + /** * @return {string} * @private */
diff --git a/chrome/browser/resources/settings/chromeos/os_page_visibility.js b/chrome/browser/resources/settings/chromeos/os_page_visibility.js index f49676b..af2be2c 100644 --- a/chrome/browser/resources/settings/chromeos/os_page_visibility.js +++ b/chrome/browser/resources/settings/chromeos/os_page_visibility.js
@@ -137,7 +137,8 @@ autofill: true, people: { lockScreen: true, - kerberosAccounts: isKerberosEnabled, + kerberosAccounts: + isKerberosEnabled && !isKerberosSettingsSectionEnabled, googleAccounts: isAccountManagerEnabled, manageUsers: true, },
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/BUILD.gn b/chrome/browser/resources/settings/clear_browsing_data_dialog/BUILD.gn index e073a1e..a7d9d965 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/BUILD.gn +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/BUILD.gn
@@ -30,6 +30,7 @@ "../controls:settings_checkbox", "../controls:settings_dropdown_menu.m", "../people_page:sync_browser_proxy.m", + "//third_party/polymer/v3_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer", "//ui/webui/resources/js:load_time_data.m", "//ui/webui/resources/js:web_ui_listener_behavior.m", ]
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html index 2eee770f..414ac8e1 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
@@ -95,6 +95,11 @@ color: var(--cr-secondary-text-color); padding: 16px; } + + #clearingDataAlert { + clip: rect(0, 0, 0, 0); + position: fixed; + } </style> <cr-dialog id="clearBrowsingDataDialog" @@ -235,6 +240,12 @@ clearButtonDisabled_)]]"> $i18n{clearData} </cr-button> + + <!-- The alert must be inside the dialog for it to be read while the + dialog is open. --> + <div id="clearingDataAlert" role="alert"> + [[clearingDataAlertString_]] + </div> </div> <template is="dom-if" if="[[shouldShowFooter_(syncStatus.signedIn)]]" restamp>
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js index 3c8f324..7bf4e97 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
@@ -22,6 +22,7 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {WebUIListenerBehavior} from 'chrome://resources/js/web_ui_listener_behavior.m.js'; +import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {DropdownMenuOptionList} from '../controls/settings_dropdown_menu.m.js'; @@ -123,6 +124,12 @@ }, /** @private */ + clearingDataAlertString_: { + type: String, + value: '', + }, + + /** @private */ clearButtonDisabled_: { type: Boolean, value: false, @@ -446,6 +453,7 @@ */ clearBrowsingData_: async function() { this.clearingInProgress_ = true; + this.clearingDataAlertString_ = loadTimeData.getString('clearingData'); const tab = this.$.tabs.selectedItem; const dataTypes = this.getSelectedDataTypes_(tab); const timePeriod = tab.querySelector('.time-range-select').pref.value; @@ -464,6 +472,8 @@ await this.browserProxy_.clearBrowsingData( dataTypes, timePeriod, this.installedApps_); this.clearingInProgress_ = false; + IronA11yAnnouncer.requestAvailability(); + this.fire('iron-announce', {text: loadTimeData.getString('clearedData')}); this.showHistoryDeletionDialog_ = showHistoryNotice; // If both the history notice and the passwords notice should be shown, show // the history notice first, and then show the passwords notice once the
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chrome/browser/resources/settings/privacy_page/privacy_page.js index acd4ee3..86446bb 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.js +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -306,7 +306,11 @@ /** @private */ onDialogClosed_() { Router.getInstance().navigateTo(assert(routes.CLEAR_BROWSER_DATA.parent)); - focusWithoutInk(assert(this.$$('#clearBrowsingData'))); + setTimeout(() => { + // Focus after a timeout to ensure any a11y messages get read before + // screen readers read out the newly focused element. + focusWithoutInk(assert(this.$$('#clearBrowsingData'))); + }); }, /** @private */
diff --git a/chrome/browser/resources/settings/privacy_page/security_page.html b/chrome/browser/resources/settings/privacy_page/security_page.html index d6404f47..3904e69 100644 --- a/chrome/browser/resources/settings/privacy_page/security_page.html +++ b/chrome/browser/resources/settings/privacy_page/security_page.html
@@ -43,6 +43,10 @@ padding-inline-start: 0; } + settings-toggle-button:not([disabled]) { + pointer-events: all; + } + #safeBrowsingEnhanced .bullet-line:last-of-type { padding-bottom: 12px; }
diff --git a/chrome/browser/resources_util.cc b/chrome/browser/resources_util.cc index a5701567..88e0b09 100644 --- a/chrome/browser/resources_util.cc +++ b/chrome/browser/resources_util.cc
@@ -11,11 +11,12 @@ #include "base/containers/flat_map.h" #include "base/no_destructor.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/grit/theme_resources_map.h" #include "components/grit/components_scaled_resources_map.h" #include "ui/resources/grit/ui_resources_map.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/chromeos/resources/grit/ui_chromeos_resources_map.h" #endif @@ -31,7 +32,7 @@ ThemeMap() { size_t storage_size = kComponentsScaledResourcesSize + kThemeResourcesSize + kUiResourcesSize; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) storage_size += kUiChromeosResourcesSize; #endif @@ -49,7 +50,7 @@ for (size_t i = 0; i < kUiResourcesSize; ++i) { storage.emplace_back(kUiResources[i].name, kUiResources[i].value); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) for (size_t i = 0; i < kUiChromeosResourcesSize; ++i) { storage.emplace_back(kUiChromeosResources[i].name, kUiChromeosResources[i].value);
diff --git a/chrome/browser/resources_util_unittest.cc b/chrome/browser/resources_util_unittest.cc index 0f7059b3..73fc01e 100644 --- a/chrome/browser/resources_util_unittest.cc +++ b/chrome/browser/resources_util_unittest.cc
@@ -8,11 +8,12 @@ #include "base/stl_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/grit/components_scaled_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/resources/grit/ui_resources.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" #endif @@ -25,7 +26,7 @@ {"IDR_ERROR_NETWORK_GENERIC", IDR_ERROR_NETWORK_GENERIC}, // IDRs from ui/resources/ui_resources.grd should be valid. {"IDR_DEFAULT_FAVICON", IDR_DEFAULT_FAVICON}, -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Check IDRs from ui/chromeos/resources/ui_chromeos_resources.grd. {"IDR_LOGIN_DEFAULT_USER", IDR_LOGIN_DEFAULT_USER}, #endif
diff --git a/chrome/browser/rlz/chrome_rlz_tracker_delegate.cc b/chrome/browser/rlz/chrome_rlz_tracker_delegate.cc index 4eb38c5..0497e2d9 100644 --- a/chrome/browser/rlz/chrome_rlz_tracker_delegate.cc +++ b/chrome/browser/rlz/chrome_rlz_tracker_delegate.cc
@@ -9,6 +9,7 @@ #include "base/command_line.h" #include "base/notreached.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/google/google_brand.h" @@ -39,7 +40,7 @@ #include "chrome/installer/util/google_update_settings.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/command_line.h" #include "chromeos/constants/chromeos_switches.h" #endif @@ -53,7 +54,7 @@ user_prefs::PrefRegistrySyncable* registry) { #if BUILDFLAG(ENABLE_RLZ) int rlz_ping_delay_seconds = 90; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kRlzPingDelay)) { // Use a switch for overwriting the default delay because it doesn't seem
diff --git a/chrome/browser/safe_browsing/BUILD.gn b/chrome/browser/safe_browsing/BUILD.gn index b19f77f..a9b0594c 100644 --- a/chrome/browser/safe_browsing/BUILD.gn +++ b/chrome/browser/safe_browsing/BUILD.gn
@@ -223,8 +223,6 @@ "incident_reporting/platform_state_store.h", "incident_reporting/preference_validation_delegate.cc", "incident_reporting/preference_validation_delegate.h", - "incident_reporting/resource_request_detector.cc", - "incident_reporting/resource_request_detector.h", "incident_reporting/resource_request_incident.cc", "incident_reporting/resource_request_incident.h", "incident_reporting/state_store.cc",
diff --git a/chrome/browser/safe_browsing/android/services_delegate_android.cc b/chrome/browser/safe_browsing/android/services_delegate_android.cc index 3d5da234..b9307425 100644 --- a/chrome/browser/safe_browsing/android/services_delegate_android.cc +++ b/chrome/browser/safe_browsing/android/services_delegate_android.cc
@@ -70,9 +70,6 @@ void ServicesDelegateAndroid::RefreshState(bool enable) {} -void ServicesDelegateAndroid::ProcessResourceRequest( - const ResourceRequestInfo* request) {} - std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> ServicesDelegateAndroid::CreatePreferenceValidationDelegate(Profile* profile) { return nullptr;
diff --git a/chrome/browser/safe_browsing/android/services_delegate_android.h b/chrome/browser/safe_browsing/android/services_delegate_android.h index eaea439..7004ce0 100644 --- a/chrome/browser/safe_browsing/android/services_delegate_android.h +++ b/chrome/browser/safe_browsing/android/services_delegate_android.h
@@ -29,7 +29,6 @@ SafeBrowsingDatabaseManager* database_manager) override; void ShutdownServices() override; void RefreshState(bool enable) override; - void ProcessResourceRequest(const ResourceRequestInfo* request) override; std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> CreatePreferenceValidationDelegate(Profile* profile) override; void RegisterDelayedAnalysisCallback(
diff --git a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.cc b/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.cc deleted file mode 100644 index b7277142..0000000 --- a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.cc +++ /dev/null
@@ -1,180 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" - -#include <utility> - -#include "base/bind.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/safe_browsing/incident_reporting/incident_receiver.h" -#include "chrome/browser/safe_browsing/incident_reporting/resource_request_incident.h" -#include "components/safe_browsing/core/proto/csd.pb.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/site_instance.h" -#include "crypto/sha2.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" -#include "url/gurl.h" - -namespace { - -Profile* GetProfileForRenderProcessId(int render_process_id) { - // How to get a profile from a RenderProcess id: - // 1) Get the RenderProcessHost - // 2) From 1) Get the BrowserContext - // 3) From 2) Get the Profile. - Profile* profile = nullptr; - content::RenderProcessHost* render_process_host = - content::RenderProcessHost::FromID(render_process_id); - if (render_process_host) { - content::BrowserContext* browser_context = - render_process_host->GetBrowserContext(); - if (browser_context) - profile = Profile::FromBrowserContext(browser_context); - } - return profile; -} - -GURL GetUrlForRenderFrameId(int render_process_id, int render_frame_id) { - content::RenderFrameHost* render_frame_host = - content::RenderFrameHost::FromID(render_process_id, render_frame_id); - if (render_frame_host) - return render_frame_host->GetLastCommittedURL(); - return GURL(); -} - -} // namespace - -namespace safe_browsing { - -namespace { - -// Implementation of SafeBrowsingDatabaseManager::Client that is used to lookup -// a resource blacklist. Can be constructed on any thread. -class ResourceRequestDetectorClient - : public SafeBrowsingDatabaseManager::Client, - public base::RefCountedThreadSafe<ResourceRequestDetectorClient> { - public: - using ResourceRequestIncidentMessage = - ClientIncidentReport::IncidentData::ResourceRequestIncident; - - using OnResultCallback = - base::OnceCallback<void(std::unique_ptr<ResourceRequestIncidentMessage>)>; - - static void Start( - const GURL& resource_url, - const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, - OnResultCallback callback) { - auto client = base::WrapRefCounted(new ResourceRequestDetectorClient( - std::move(database_manager), std::move(callback))); - content::GetIOThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce(&ResourceRequestDetectorClient::StartCheck, - client, resource_url)); - } - - private: - ResourceRequestDetectorClient( - scoped_refptr<SafeBrowsingDatabaseManager> database_manager, - OnResultCallback callback) - : database_manager_(std::move(database_manager)), - callback_(std::move(callback)) {} - - friend class base::RefCountedThreadSafe<ResourceRequestDetectorClient>; - ~ResourceRequestDetectorClient() override {} - - void StartCheck(const GURL& resource_url) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - if (!database_manager_) - return; - - AddRef(); - // If database_manager_->CheckResourceUrl returns false, the resource might - // be blacklisted and the response will come in OnCheckResourceUrlResult - // callback, where AddRef() is balanced by Release(). - // If the check returns true, the resource is not blacklisted and the - // client object may be destroyed immediately. - if (database_manager_->CheckResourceUrl(resource_url, this)) { - Release(); - } - } - - void OnCheckResourceUrlResult(const GURL& url, - SBThreatType threat_type, - const std::string& threat_hash) override { - if (threat_type == SB_THREAT_TYPE_BLACKLISTED_RESOURCE) { - std::unique_ptr<ResourceRequestIncidentMessage> incident_data( - new ResourceRequestIncidentMessage()); - incident_data->set_type(ResourceRequestIncidentMessage::TYPE_PATTERN); - incident_data->set_digest(threat_hash); - content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(std::move(callback_), std::move(incident_data))); - } - Release(); // Balanced in StartCheck. - } - - scoped_refptr<SafeBrowsingDatabaseManager> database_manager_; - OnResultCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(ResourceRequestDetectorClient); -}; - -} // namespace - -ResourceRequestDetector::ResourceRequestDetector( - scoped_refptr<SafeBrowsingDatabaseManager> database_manager, - std::unique_ptr<IncidentReceiver> incident_receiver) - : incident_receiver_(std::move(incident_receiver)), - database_manager_(database_manager), - allow_null_profile_for_testing_(false) {} - -ResourceRequestDetector::~ResourceRequestDetector() { -} - -void ResourceRequestDetector::ProcessResourceRequest( - const ResourceRequestInfo* request) { - // Only look at actual net requests (e.g., not chrome-extensions://id/foo.js). - if (!request->url.SchemeIsHTTPOrHTTPS()) - return; - - if (request->resource_type == blink::mojom::ResourceType::kSubFrame || - request->resource_type == blink::mojom::ResourceType::kScript || - request->resource_type == blink::mojom::ResourceType::kObject) { - ResourceRequestDetectorClient::Start( - request->url, database_manager_, - base::BindOnce(&ResourceRequestDetector::ReportIncidentOnUIThread, - weak_ptr_factory_.GetWeakPtr(), - request->render_process_id, request->render_frame_id)); - } -} - -void ResourceRequestDetector::set_allow_null_profile_for_testing( - bool allow_null_profile_for_testing) { - allow_null_profile_for_testing_ = allow_null_profile_for_testing; -} - -void ResourceRequestDetector::ReportIncidentOnUIThread( - int render_process_id, - int render_frame_id, - std::unique_ptr<ClientIncidentReport_IncidentData_ResourceRequestIncident> - incident_data) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - Profile* profile = GetProfileForRenderProcessId(render_process_id); - if (profile || allow_null_profile_for_testing_) { - // Add the URL obtained from the RenderFrameHost, if available. - GURL host_url = GetUrlForRenderFrameId(render_process_id, render_frame_id); - if (host_url.is_valid()) - incident_data->set_origin(host_url.GetOrigin().spec()); - - incident_receiver_->AddIncidentForProfile( - profile, - std::make_unique<ResourceRequestIncident>(std::move(incident_data))); - } -} - -} // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h b/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h deleted file mode 100644 index 95e7ebd..0000000 --- a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_RESOURCE_REQUEST_DETECTOR_H_ -#define CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_RESOURCE_REQUEST_DETECTOR_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/safe_browsing/incident_reporting/incident_receiver.h" -#include "components/safe_browsing/core/db/database_manager.h" - -namespace safe_browsing { - -class ClientIncidentReport_IncidentData_ResourceRequestIncident; - -struct ResourceRequestInfo { - GURL url; - blink::mojom::ResourceType resource_type; - int render_process_id; - int render_frame_id; -}; - -// Observes network requests and reports suspicious activity. -class ResourceRequestDetector { - public: - ResourceRequestDetector( - scoped_refptr<SafeBrowsingDatabaseManager> sb_database_manager, - std::unique_ptr<IncidentReceiver> incident_receiver); - ~ResourceRequestDetector(); - - // Analyzes the |request| and triggers an incident report on suspicious - // script inclusion. - void ProcessResourceRequest(const ResourceRequestInfo* request); - - protected: - // Testing hook. - void set_allow_null_profile_for_testing(bool allow_null_profile_for_testing); - - private: - void ReportIncidentOnUIThread( - int render_process_id, - int render_frame_id, - std::unique_ptr<ClientIncidentReport_IncidentData_ResourceRequestIncident> - incident_data); - - std::unique_ptr<IncidentReceiver> incident_receiver_; - scoped_refptr<SafeBrowsingDatabaseManager> database_manager_; - bool allow_null_profile_for_testing_; - - base::WeakPtrFactory<ResourceRequestDetector> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ResourceRequestDetector); -}; - -} // namespace safe_browsing - -#endif // CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_RESOURCE_REQUEST_DETECTOR_H_
diff --git a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/resource_request_detector_unittest.cc deleted file mode 100644 index 2a0daad..0000000 --- a/chrome/browser/safe_browsing/incident_reporting/resource_request_detector_unittest.cc +++ /dev/null
@@ -1,214 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" - -#include <utility> - -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "chrome/browser/safe_browsing/incident_reporting/incident.h" -#include "chrome/browser/safe_browsing/incident_reporting/incident_receiver.h" -#include "chrome/browser/safe_browsing/incident_reporting/mock_incident_receiver.h" -#include "components/safe_browsing/core/db/test_database_manager.h" -#include "components/safe_browsing/core/proto/csd.pb.h" -#include "content/public/test/browser_task_environment.h" -#include "crypto/sha2.h" -#include "ipc/ipc_message.h" -#include "net/base/request_priority.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/loader/previews_state.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" -#include "url/gurl.h" - -using ::testing::IsNull; -using ::testing::Return; -using ::testing::StrictMock; -using ::testing::WithArg; -using ::testing::_; - -namespace safe_browsing { - -namespace { - -class FakeResourceRequestDetector : public ResourceRequestDetector { - public: - FakeResourceRequestDetector( - scoped_refptr<SafeBrowsingDatabaseManager> database_manager, - std::unique_ptr<IncidentReceiver> incident_receiver) - : ResourceRequestDetector(database_manager, - std::move(incident_receiver)) { - FakeResourceRequestDetector::set_allow_null_profile_for_testing(true); - } -}; - -class MockSafeBrowsingDatabaseManager : public TestSafeBrowsingDatabaseManager { - public: - MockSafeBrowsingDatabaseManager() {} - - MOCK_METHOD2(CheckResourceUrl, bool( - const GURL& url, - SafeBrowsingDatabaseManager::Client* client)); - - protected: - ~MockSafeBrowsingDatabaseManager() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(MockSafeBrowsingDatabaseManager); -}; - -} // namespace - -ACTION_P3(CallClientWithResult, url, threat_type, threat_hash) { - arg1->OnCheckResourceUrlResult(url, threat_type, threat_hash); - return false; -} - -class ResourceRequestDetectorTest : public testing::Test { - protected: - using ResourceRequestIncidentMessage = - ClientIncidentReport::IncidentData::ResourceRequestIncident; - - ResourceRequestDetectorTest() - : mock_incident_receiver_( - new StrictMock<safe_browsing::MockIncidentReceiver>()), - mock_database_manager_(new StrictMock<MockSafeBrowsingDatabaseManager>), - fake_resource_request_detector_( - std::make_unique<FakeResourceRequestDetector>( - mock_database_manager_, - base::WrapUnique(mock_incident_receiver_))) {} - - void TearDown() override { - fake_resource_request_detector_.reset(); - mock_database_manager_ = nullptr; - base::RunLoop().RunUntilIdle(); - } - - void ExpectNoDatabaseCheck() { - EXPECT_CALL(*mock_database_manager_, CheckResourceUrl(_, _)) - .Times(0); - } - - void ExpectNegativeSyncDatabaseCheck(const std::string& url) { - EXPECT_CALL(*mock_database_manager_, CheckResourceUrl(GURL(url), _)) - .WillOnce(Return(true)); - } - - void ExpectAsyncDatabaseCheck(const std::string& url, - bool is_blacklisted, - const std::string& digest) { - SBThreatType threat_type = is_blacklisted - ? SB_THREAT_TYPE_BLACKLISTED_RESOURCE - : SB_THREAT_TYPE_SAFE; - const GURL gurl(url); - EXPECT_CALL(*mock_database_manager_, CheckResourceUrl(gurl, _)) - .WillOnce(CallClientWithResult(gurl, threat_type, digest)); - } - - void ExpectNoIncident(const std::string& url, - blink::mojom::ResourceType resource_type) { - EXPECT_CALL(*mock_incident_receiver_, DoAddIncidentForProfile(IsNull(), _)) - .Times(0); - - ResourceRequestInfo info; - info.url = GURL(url); - info.resource_type = resource_type; - fake_resource_request_detector_->ProcessResourceRequest(&info); - base::RunLoop().RunUntilIdle(); - } - - void ExpectIncidentAdded(const std::string& url, - blink::mojom::ResourceType resource_type, - ResourceRequestIncidentMessage::Type expected_type, - const std::string& expected_digest) { - std::unique_ptr<Incident> incident; - EXPECT_CALL(*mock_incident_receiver_, DoAddIncidentForProfile(IsNull(), _)) - .WillOnce(WithArg<1>(TakeIncident(&incident))); - - ResourceRequestInfo info; - info.url = GURL(url); - info.resource_type = resource_type; - fake_resource_request_detector_->ProcessResourceRequest(&info); - base::RunLoop().RunUntilIdle(); - - ASSERT_TRUE(incident); - std::unique_ptr<ClientIncidentReport_IncidentData> incident_data = - incident->TakePayload(); - ASSERT_TRUE(incident_data && incident_data->has_resource_request()); - const ResourceRequestIncidentMessage& script_request_incident = - incident_data->resource_request(); - EXPECT_TRUE(script_request_incident.has_digest()); - EXPECT_EQ(expected_digest, script_request_incident.digest()); - EXPECT_EQ(expected_type, script_request_incident.type()); - } - - protected: - content::BrowserTaskEnvironment task_environment_; - - public: - StrictMock<safe_browsing::MockIncidentReceiver>* mock_incident_receiver_; - scoped_refptr<MockSafeBrowsingDatabaseManager> mock_database_manager_; - std::unique_ptr<FakeResourceRequestDetector> fake_resource_request_detector_; - - private: -}; - -TEST_F(ResourceRequestDetectorTest, NoDbCheckForIgnoredResourceTypes) { - ExpectNoDatabaseCheck(); - ExpectNoIncident("http://www.example.com/index.html", - blink::mojom::ResourceType::kMainFrame); -} - -TEST_F(ResourceRequestDetectorTest, NoDbCheckForUnsupportedSchemes) { - ExpectNoDatabaseCheck(); - ExpectNoIncident("file:///usr/local/script.js", - blink::mojom::ResourceType::kScript); - ExpectNoIncident("chrome-extension://abcdefghi/script.js", - blink::mojom::ResourceType::kScript); -} - -TEST_F(ResourceRequestDetectorTest, NoEventForNegativeSynchronousDbCheck) { - const std::string url = "http://www.example.com/script.js"; - ExpectNegativeSyncDatabaseCheck(url); - ExpectNoIncident(url, blink::mojom::ResourceType::kScript); -} - -TEST_F(ResourceRequestDetectorTest, NoEventForNegativeAsynchronousDbCheck) { - const std::string url = "http://www.example.com/script.js"; - ExpectAsyncDatabaseCheck(url, false, ""); - ExpectNoIncident(url, blink::mojom::ResourceType::kScript); -} - -TEST_F(ResourceRequestDetectorTest, EventAddedForSupportedSchemes) { - std::string schemes[] = {"http", "https"}; - const std::string digest = "dummydigest"; - const std::string domain_path = "www.example.com/script.js"; - - for (const auto& scheme : schemes) { - const std::string url = scheme + "://" + domain_path; - ExpectAsyncDatabaseCheck(url, true, digest); - ExpectIncidentAdded(url, blink::mojom::ResourceType::kScript, - ResourceRequestIncidentMessage::TYPE_PATTERN, digest); - } -} - -TEST_F(ResourceRequestDetectorTest, EventAddedForSupportedResourceTypes) { - blink::mojom::ResourceType supported_types[] = { - blink::mojom::ResourceType::kScript, - blink::mojom::ResourceType::kSubFrame, - blink::mojom::ResourceType::kObject, - }; - const std::string url = "http://www.example.com/"; - const std::string digest = "dummydigest"; - for (auto resource_type : supported_types) { - ExpectAsyncDatabaseCheck(url, true, digest); - ExpectIncidentAdded(url, resource_type, - ResourceRequestIncidentMessage::TYPE_PATTERN, digest); - } -} - -} // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index 824dd16e..8f9c14a 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -67,7 +67,6 @@ #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" -#include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" #endif using content::BrowserThread;
diff --git a/chrome/browser/safe_browsing/services_delegate.h b/chrome/browser/safe_browsing/services_delegate.h index 5f6aeb2..6133f1c 100644 --- a/chrome/browser/safe_browsing/services_delegate.h +++ b/chrome/browser/safe_browsing/services_delegate.h
@@ -39,8 +39,6 @@ #endif class IncidentReportingService; class PasswordProtectionService; -class ResourceRequestDetector; -struct ResourceRequestInfo; class SafeBrowsingService; class SafeBrowsingDatabaseManager; struct V4ProtocolConfig; @@ -64,7 +62,6 @@ virtual bool CanCreateDownloadProtectionService() = 0; #endif virtual bool CanCreateIncidentReportingService() = 0; - virtual bool CanCreateResourceRequestDetector() = 0; // Caller takes ownership of the returned object. Cannot use std::unique_ptr // because services may not be implemented for some build configs. @@ -73,7 +70,6 @@ virtual DownloadProtectionService* CreateDownloadProtectionService() = 0; #endif virtual IncidentReportingService* CreateIncidentReportingService() = 0; - virtual ResourceRequestDetector* CreateResourceRequestDetector() = 0; }; // Creates the ServicesDelegate using its's default ServicesCreator. @@ -106,7 +102,6 @@ virtual void RefreshState(bool enable) = 0; // See the SafeBrowsingService methods of the same name. - virtual void ProcessResourceRequest(const ResourceRequestInfo* request) = 0; virtual std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> CreatePreferenceValidationDelegate(Profile* profile) = 0; virtual void RegisterDelayedAnalysisCallback(
diff --git a/chrome/browser/safe_browsing/services_delegate_desktop.cc b/chrome/browser/safe_browsing/services_delegate_desktop.cc index 2233cb6c9..d2a50a35 100644 --- a/chrome/browser/safe_browsing/services_delegate_desktop.cc +++ b/chrome/browser/safe_browsing/services_delegate_desktop.cc
@@ -83,11 +83,6 @@ services_creator_->CanCreateIncidentReportingService()) ? services_creator_->CreateIncidentReportingService() : CreateIncidentReportingService()); - resource_request_detector_.reset( - (services_creator_ && - services_creator_->CanCreateResourceRequestDetector()) - ? services_creator_->CreateResourceRequestDetector() - : CreateResourceRequestDetector()); } void ServicesDelegateDesktop::SetDatabaseManagerForTest( @@ -102,7 +97,6 @@ download_service_.reset(); - resource_request_detector_.reset(); incident_service_.reset(); ServicesDelegate::ShutdownServices(); @@ -114,13 +108,6 @@ download_service_->SetEnabled(enable); } -void ServicesDelegateDesktop::ProcessResourceRequest( - const ResourceRequestInfo* request) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (resource_request_detector_) - resource_request_detector_->ProcessResourceRequest(request); -} - std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> ServicesDelegateDesktop::CreatePreferenceValidationDelegate(Profile* profile) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -163,12 +150,6 @@ return new IncidentReportingService(safe_browsing_service_); } -ResourceRequestDetector* -ServicesDelegateDesktop::CreateResourceRequestDetector() { - return new ResourceRequestDetector(safe_browsing_service_->database_manager(), - incident_service_->GetIncidentReceiver()); -} - void ServicesDelegateDesktop::StartOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> sb_url_loader_factory, scoped_refptr<network::SharedURLLoaderFactory> browser_url_loader_factory,
diff --git a/chrome/browser/safe_browsing/services_delegate_desktop.h b/chrome/browser/safe_browsing/services_delegate_desktop.h index 811003f6..00f0d802 100644 --- a/chrome/browser/safe_browsing/services_delegate_desktop.h +++ b/chrome/browser/safe_browsing/services_delegate_desktop.h
@@ -11,7 +11,6 @@ #include "chrome/browser/safe_browsing/client_side_detection_service.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" -#include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" #include "chrome/browser/safe_browsing/services_delegate.h" namespace safe_browsing { @@ -36,7 +35,6 @@ SafeBrowsingDatabaseManager* database_manager) override; void ShutdownServices() override; void RefreshState(bool enable) override; - void ProcessResourceRequest(const ResourceRequestInfo* request) override; std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> CreatePreferenceValidationDelegate(Profile* profile) override; void RegisterDelayedAnalysisCallback( @@ -61,11 +59,9 @@ scoped_refptr<SafeBrowsingDatabaseManager> CreateDatabaseManager(); DownloadProtectionService* CreateDownloadProtectionService(); IncidentReportingService* CreateIncidentReportingService(); - ResourceRequestDetector* CreateResourceRequestDetector(); std::unique_ptr<DownloadProtectionService> download_service_; std::unique_ptr<IncidentReportingService> incident_service_; - std::unique_ptr<ResourceRequestDetector> resource_request_detector_; // The database manager that handles the database checking and update logic // Accessed on both UI and IO thread.
diff --git a/chrome/browser/safe_browsing/test_safe_browsing_service.cc b/chrome/browser/safe_browsing/test_safe_browsing_service.cc index c65d292..e892e8a 100644 --- a/chrome/browser/safe_browsing/test_safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/test_safe_browsing_service.cc
@@ -110,9 +110,6 @@ bool TestSafeBrowsingService::CanCreateIncidentReportingService() { return true; } -bool TestSafeBrowsingService::CanCreateResourceRequestDetector() { - return false; -} SafeBrowsingDatabaseManager* TestSafeBrowsingService::CreateDatabaseManager() { DCHECK(!use_v4_local_db_manager_); @@ -140,11 +137,6 @@ return nullptr; #endif // BUILDFLAG(FULL_SAFE_BROWSING) } -ResourceRequestDetector* -TestSafeBrowsingService::CreateResourceRequestDetector() { - NOTIMPLEMENTED(); - return nullptr; -} scoped_refptr<network::SharedURLLoaderFactory> TestSafeBrowsingService::GetURLLoaderFactory() {
diff --git a/chrome/browser/safe_browsing/test_safe_browsing_service.h b/chrome/browser/safe_browsing/test_safe_browsing_service.h index d9d24ab..51c092a 100644 --- a/chrome/browser/safe_browsing/test_safe_browsing_service.h +++ b/chrome/browser/safe_browsing/test_safe_browsing_service.h
@@ -86,13 +86,11 @@ bool CanCreateDownloadProtectionService() override; #endif bool CanCreateIncidentReportingService() override; - bool CanCreateResourceRequestDetector() override; SafeBrowsingDatabaseManager* CreateDatabaseManager() override; #if BUILDFLAG(FULL_SAFE_BROWSING) DownloadProtectionService* CreateDownloadProtectionService() override; #endif IncidentReportingService* CreateIncidentReportingService() override; - ResourceRequestDetector* CreateResourceRequestDetector() override; scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override; scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory(
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc index 7cdbc47..5a414ef 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_util.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.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" @@ -29,7 +30,7 @@ #include "services/network/public/cpp/simple_url_loader.h" #include "url/gurl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/signin/chrome_signin_helper.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" #include "components/signin/core/browser/signin_header_helper.h" @@ -164,7 +165,7 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const GURL api_url_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const bool account_consistency_mirror_required_; #endif @@ -181,7 +182,7 @@ LoadDoneCallback callback) : url_loader_factory_(url_loader_factory), api_url_(std::move(api_url)), -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) account_consistency_mirror_required_(account_consistency_mirror_required), #endif callback_(std::move(callback)) { @@ -191,7 +192,7 @@ network::ResourceRequest* request) const { variations::AppendVariationsHeaderUnknownSignedIn( api_url_, variations::InIncognito::kNo, request); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) signin::ChromeConnectedHeaderHelper chrome_connected_header_helper( account_consistency_mirror_required_ ? signin::AccountConsistencyMethod::kMirror
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc index d58cdda9..eadde53 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc
@@ -13,6 +13,7 @@ #include "base/test/mock_callback.h" #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/search/one_google_bar/one_google_bar_data.h" #include "components/signin/core/browser/signin_header_helper.h" #include "content/public/test/browser_task_environment.h" @@ -300,7 +301,7 @@ EXPECT_CALL(callback, Run(_, _)).WillOnce(Quit(&loop)); loop.Run(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, X-Chrome-Connected header is present, but // enable_account_consistency is set to false. std::string header_value; @@ -338,7 +339,7 @@ loop.Run(); // Make sure mirror account consistency is requested. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, X-Chrome-Connected header is present, and // enable_account_consistency is set to true. std::string header_value;
diff --git a/chrome/browser/secure_origin_allowlist_browsertest.cc b/chrome/browser/secure_origin_allowlist_browsertest.cc index 48f7248..972cf15c 100644 --- a/chrome/browser/secure_origin_allowlist_browsertest.cc +++ b/chrome/browser/secure_origin_allowlist_browsertest.cc
@@ -5,6 +5,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ssl/security_state_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -128,7 +129,7 @@ TestVariant::kCommandline, // The legacy policy isn't defined on ChromeOS or Android, so skip tests that // use it on those platforms. -#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID) TestVariant::kPolicyOld, TestVariant::kPolicyOldAndNew, #endif
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_client_service_factory.cc b/chrome/browser/send_tab_to_self/send_tab_to_self_client_service_factory.cc index 251d3da..8c71202c 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_client_service_factory.cc +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_client_service_factory.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/memory/singleton.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/notifications/notification_display_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/send_tab_to_self/send_tab_to_self_client_service.h" @@ -16,7 +17,7 @@ #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "components/user_manager/user.h" #endif @@ -52,7 +53,7 @@ SendTabToSelfSyncService* sync_service = SendTabToSelfSyncServiceFactory::GetForProfile(profile); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Create SendTabToSelfClientService only for profiles of Gaia users. // ChromeOS has system level profiles, such as the sign-in profile, or // users that are not Gaia users, such as public account users. Do not
diff --git a/chrome/browser/serial/chrome_serial_browsertest.cc b/chrome/browser/serial/chrome_serial_browsertest.cc index 56949b4..eb1a78d 100644 --- a/chrome/browser/serial/chrome_serial_browsertest.cc +++ b/chrome/browser/serial/chrome_serial_browsertest.cc
@@ -4,6 +4,7 @@ #include "base/command_line.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/serial/serial_chooser_context.h" #include "chrome/browser/serial/serial_chooser_context_factory.h" #include "chrome/browser/ui/browser.h" @@ -54,7 +55,7 @@ // TODO(crbug/1069695): Flaky on linux-chromeos-chrome. // TODO(crbug/1116072): Flaky on Linux Ozone Tester (X11). -#if defined(OS_CHROMEOS) || defined(USE_OZONE) +#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(USE_OZONE) #define MAYBE_NavigateWithChooserCrossOrigin \ DISABLED_NavigateWithChooserCrossOrigin #else
diff --git a/chrome/browser/service_process/service_process_control.h b/chrome/browser/service_process/service_process_control.h index 6ee902d0..07928e54 100644 --- a/chrome/browser/service_process/service_process_control.h +++ b/chrome/browser/service_process/service_process_control.h
@@ -20,13 +20,14 @@ #include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/upgrade_detector/upgrade_observer.h" #include "chrome/common/service_process.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/service_manager/public/cpp/interface_provider.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #error "Not supported on ChromeOS" #endif
diff --git a/chrome/browser/service_sandbox_type.h b/chrome/browser/service_sandbox_type.h index 374a2163..03c27ae5 100644 --- a/chrome/browser/service_sandbox_type.h +++ b/chrome/browser/service_sandbox_type.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_SERVICE_SANDBOX_TYPE_H_ #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "content/public/browser/service_process_host.h" #include "media/base/media_switches.h" #include "sandbox/policy/sandbox_type.h" @@ -153,7 +154,7 @@ } #endif // !defined(OS_MAC) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // recording::mojom::RecordingService namespace recording { namespace mojom { @@ -169,6 +170,6 @@ content::GetServiceSandboxType<recording::mojom::RecordingService>() { return sandbox::policy::SandboxType::kVideoCapture; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #endif // CHROME_BROWSER_SERVICE_SANDBOX_TYPE_H_
diff --git a/chrome/browser/sharesheet/share_action.cc b/chrome/browser/sharesheet/share_action.cc index 599625b9..9dc3f8e4 100644 --- a/chrome/browser/sharesheet/share_action.cc +++ b/chrome/browser/sharesheet/share_action.cc
@@ -4,7 +4,9 @@ #include "chrome/browser/sharesheet/share_action.h" -#if defined(OS_CHROMEOS) +#include "build/chromeos_buildflags.h" + +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "components/services/app_service/public/cpp/intent_util.h" #endif @@ -12,7 +14,7 @@ bool ShareAction::ShouldShowAction(const apps::mojom::IntentPtr& intent, bool contains_hosted_document) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) return !contains_hosted_document && !apps_util::OnlyShareToDrive(intent) && apps_util::IsIntentValid(intent); #else
diff --git a/chrome/browser/sharesheet/sharesheet_action_cache.cc b/chrome/browser/sharesheet/sharesheet_action_cache.cc index 1502b70..d06bade 100644 --- a/chrome/browser/sharesheet/sharesheet_action_cache.cc +++ b/chrome/browser/sharesheet/sharesheet_action_cache.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/sharesheet/sharesheet_action_cache.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/sharesheet/share_action.h" #include "chrome/browser/sharesheet/sharesheet_types.h" #include "ui/gfx/vector_icon_types.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/nearby_sharing/common/nearby_share_features.h" #include "chrome/browser/nearby_sharing/sharesheet/nearby_share_action.h" #include "chrome/browser/sharesheet/drive_share_action.h" @@ -18,7 +19,7 @@ SharesheetActionCache::SharesheetActionCache() { // ShareActions will be initialised here by calling AddShareAction. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (base::FeatureList::IsEnabled(features::kNearbySharing)) { AddShareAction(std::make_unique<NearbyShareAction>()); }
diff --git a/chrome/browser/sharesheet/sharesheet_service_factory.cc b/chrome/browser/sharesheet/sharesheet_service_factory.cc index 8eeb5e2..bab33d48 100644 --- a/chrome/browser/sharesheet/sharesheet_service_factory.cc +++ b/chrome/browser/sharesheet/sharesheet_service_factory.cc
@@ -6,15 +6,16 @@ #include <memory> +#include "build/chromeos_buildflags.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sharesheet/sharesheet_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/profiles/profile_helper.h" -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace sharesheet { @@ -51,7 +52,7 @@ return nullptr; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) if (chromeos::ProfileHelper::IsSigninProfile(profile)) { return nullptr; } @@ -60,7 +61,7 @@ if (profile->IsGuestSession()) { return chrome::GetBrowserContextOwnInstanceInIncognito(context); } -#endif // OS_CHROMEOS +#endif // BUILDFLAG(IS_CHROMEOS_ASH) return chrome::GetBrowserContextRedirectedInIncognito(context); }
diff --git a/chrome/browser/sharing/sharing_handler_registry_impl.cc b/chrome/browser/sharing/sharing_handler_registry_impl.cc index f10ee16..7a81cdd 100644 --- a/chrome/browser/sharing/sharing_handler_registry_impl.cc +++ b/chrome/browser/sharing/sharing_handler_registry_impl.cc
@@ -6,6 +6,7 @@ #include "chrome/browser/sharing/sharing_handler_registry_impl.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/sharing/ack_message_handler.h" #include "chrome/browser/sharing/ping_message_handler.h" #include "chrome/browser/sharing/sharing_device_registration.h" @@ -25,8 +26,8 @@ #if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || \ defined(OS_CHROMEOS) #include "chrome/browser/sharing/shared_clipboard/remote_copy_message_handler.h" -#endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) - // defined(OS_CHROMEOS) +#endif // defined(OS_WIN) || defined(OS_MAC) || (defined(OS_LINUX) || + // BUILDFLAG(IS_CHROMEOS_LACROS)) defined(OS_CHROMEOS) SharingHandlerRegistryImpl::SharingHandlerRegistryImpl( Profile* profile,
diff --git a/chrome/browser/shell_integration.cc b/chrome/browser/shell_integration.cc index 8c29ed98..21e44bf 100644 --- a/chrome/browser/shell_integration.cc +++ b/chrome/browser/shell_integration.cc
@@ -19,6 +19,7 @@ #include "base/task/task_traits.h" #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/policy/policy_path_parser.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -27,7 +28,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chromeos/constants/chromeos_switches.h" #endif @@ -149,7 +150,7 @@ command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::FilePath profile = cmd_line.GetSwitchValuePath( chromeos::switches::kLoginProfile); if (!profile.empty())
diff --git a/chrome/browser/shell_integration_linux.cc b/chrome/browser/shell_integration_linux.cc index 291251a..c377440d 100644 --- a/chrome/browser/shell_integration_linux.cc +++ b/chrome/browser/shell_integration_linux.cc
@@ -41,6 +41,7 @@ #include "base/threading/thread_restrictions.h" #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/shell_integration.h" #include "chrome/common/buildflags.h" #include "chrome/common/channel_info.h" @@ -107,7 +108,7 @@ // If |protocol| is empty this function sets Chrome as the default browser, // otherwise it sets Chrome as the default handler application for |protocol|. bool SetDefaultWebClient(const std::string& protocol) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) return true; #else std::unique_ptr<base::Environment> env(base::Environment::Create()); @@ -140,7 +141,7 @@ // |protocol|. shell_integration::DefaultWebClientState GetIsDefaultWebClient( const std::string& protocol) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) return shell_integration::UNKNOWN_DEFAULT; #else base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
diff --git a/chrome/browser/shell_integration_linux.h b/chrome/browser/shell_integration_linux.h index 33b1280..ac787c35 100644 --- a/chrome/browser/shell_integration_linux.h +++ b/chrome/browser/shell_integration_linux.h
@@ -8,12 +8,13 @@ #include <string> #include "base/files/file_path.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/web_applications/components/web_app_id.h" #include "chrome/common/buildflags.h" #include "components/services/app_service/public/cpp/file_handler.h" #include "url/gurl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #error shell_integration_linux is for desktop linux only. #endif
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index 8da6a384..37c8d0a 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -172,8 +172,8 @@ signout_source_metric == signin_metrics::SERVER_FORCED_DISABLE || signout_source_metric == signin_metrics::SIGNOUT_PREF_CHANGED; if (signin_util::IsForceSigninEnabled() && !profile_->IsSystemProfile() && - !profile_->IsGuestSession() && !profile_->IsSupervised() && - !keep_window_opened) { + !profile_->IsGuestSession() && !profile_->IsEphemeralGuestProfile() && + !profile_->IsSupervised() && !keep_window_opened) { if (signout_source_metric == signin_metrics::SIGNIN_PREF_CHANGED_DURING_SIGNIN) { // SIGNIN_PREF_CHANGED_DURING_SIGNIN will be triggered when
diff --git a/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc b/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc index 723bd378..d57d8c1 100644 --- a/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc +++ b/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc
@@ -17,6 +17,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/external_protocol/external_protocol_handler.h" #include "chrome/browser/profiles/profile.h" @@ -62,7 +63,7 @@ #include "ui/gfx/geometry/point.h" #include "url/gurl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/test/shell_test_api.h" #include "ui/display/manager/display_manager.h" #include "ui/display/screen.h" @@ -1499,7 +1500,7 @@ EXPECT_TRUE(watcher.did_exit_normally()); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // This test verifies that an OOPIF created in a tab on a secondary display // doesn't initialize its device scale factor based on the primary display. // Note: This test could probably be expanded to run on all ASH platforms.
diff --git a/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc b/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc index 5b51984..6d75574 100644 --- a/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc +++ b/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc
@@ -9,6 +9,7 @@ #include "base/test/scoped_feature_list.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h" #include "chrome/browser/ui/browser.h" @@ -419,7 +420,9 @@ EXPECT_EQ(main_frame, web_contents->GetFocusedFrame()); } -#if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_WIN) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || defined(OS_WIN) // Ensures that renderers know to advance focus to sibling frames and parent // frames in the presence of mouse click initiated focus changes. // Verifies against regression of https://crbug.com/702330
diff --git a/chrome/browser/site_isolation/site_per_process_text_input_browsertest.cc b/chrome/browser/site_isolation/site_per_process_text_input_browsertest.cc index 9e813d744..1b40583 100644 --- a/chrome/browser/site_isolation/site_per_process_text_input_browsertest.cc +++ b/chrome/browser/site_isolation/site_per_process_text_input_browsertest.cc
@@ -10,6 +10,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/location_bar/location_bar.h" @@ -40,7 +41,9 @@ #include "ui/base/ime/text_input_type.h" #include "url/gurl.h" -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "ui/base/ime/linux/text_edit_command_auralinux.h" #include "ui/base/ime/linux/text_edit_key_bindings_delegate_auralinux.h" #endif @@ -851,7 +854,7 @@ // This test makes sure browser correctly tracks focused editable element inside // each RenderFrameHost. // Test is flaky on chromeOS; https://crbug.com/705203. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_TrackingFocusedElementForAllFrames \ DISABLED_TrackingFocusedElementForAllFrames #else @@ -900,7 +903,7 @@ // in both cases the test verifies that WebContents is aware whether or not a // focused editable element exists on the page. // Test is flaky on ChromeOS. crbug.com/705289 -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_TrackPageFocusEditableElement \ DISABLED_TrackPageFocusEditableElement #else @@ -942,7 +945,7 @@ // WebContents to clear focused element and verifies that there is no longer // a focused editable element on the page. // Test is flaky on ChromeOS; https://crbug.com/705203. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_ClearFocusedElementOnPage DISABLED_ClearFocusedElementOnPage #else #define MAYBE_ClearFocusedElementOnPage ClearFocusedElementOnPage @@ -1106,7 +1109,9 @@ // Ensure that a cross-process subframe can utilize keyboard edit commands. // See https://crbug.com/640706. This test is Linux-specific, as it relies on // overriding TextEditKeyBindingsDelegateAuraLinux, which only exists on Linux. -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) IN_PROC_BROWSER_TEST_F(SitePerProcessTextInputManagerTest, SubframeKeyboardEditCommands) { GURL main_url(embedded_test_server()->GetURL(
diff --git a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc index 0013511..df830c42 100644 --- a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc
@@ -12,6 +12,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" @@ -34,7 +35,7 @@ #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "ui/base/l10n/l10n_util.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/common/extensions/extension_constants.h" #endif @@ -335,7 +336,7 @@ if (disable_built_in_tts_engine_for_testing_) return false; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) Profile* profile = Profile::FromBrowserContext(browser_context); // Load the component extensions into this profile. @@ -354,7 +355,7 @@ if (!browser_context || disable_built_in_tts_engine_for_testing_) return true; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::vector<content::VoiceData> voices; GetVoices(browser_context, &voices); bool saw_google_tts = false;
diff --git a/chrome/browser/speech/extension_api/tts_extension_api.cc b/chrome/browser/speech/extension_api/tts_extension_api.cc index 7bc2770..30068b13 100644 --- a/chrome/browser/speech/extension_api/tts_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_extension_api.cc
@@ -14,6 +14,7 @@ #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/values.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/speech/extension_api/tts_extension_api_constants.h" @@ -25,9 +26,9 @@ #include "third_party/blink/public/mojom/speech/speech_synthesis.mojom.h" #include "ui/base/l10n/l10n_util.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/speech/extension_api/tts_engine_extension_observer_chromeos.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace constants = tts_extension_api_constants; @@ -363,11 +364,11 @@ registry.RegisterFunction<TtsPauseFunction>(); registry.RegisterFunction<TtsResumeFunction>(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Ensure we're observing newly added engines for the given context. TtsEngineExtensionObserverChromeOS::GetInstance( Profile::FromBrowserContext(context)); -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } TtsAPI::~TtsAPI() {
diff --git a/chrome/browser/ssl/chrome_security_blocking_page_factory.cc b/chrome/browser/ssl/chrome_security_blocking_page_factory.cc index a7444ff..8f43d5e8 100644 --- a/chrome/browser/ssl/chrome_security_blocking_page_factory.cc +++ b/chrome/browser/ssl/chrome_security_blocking_page_factory.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/time/time.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/interstitials/chrome_settings_page_helper.h" @@ -28,7 +29,7 @@ #if defined(OS_WIN) #include "base/enterprise_util.h" -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #endif @@ -80,7 +81,7 @@ if (base::IsMachineExternallyManaged()) { return true; } -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) if (g_browser_process->platform_part()->browser_policy_connector_chromeos()) { return true; } @@ -319,7 +320,7 @@ #if defined(OS_WIN) report->SetIsEnterpriseManaged(base::IsMachineExternallyManaged()); -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) report->SetIsEnterpriseManaged(g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->IsEnterpriseManaged());
diff --git a/chrome/browser/ssl/security_state_tab_helper.cc b/chrome/browser/ssl/security_state_tab_helper.cc index 53cfff38..c11f6e1c 100644 --- a/chrome/browser/ssl/security_state_tab_helper.cc +++ b/chrome/browser/ssl/security_state_tab_helper.cc
@@ -13,6 +13,7 @@ #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/reputation/reputation_web_contents_observer.h" @@ -49,10 +50,10 @@ #include "url/gurl.h" #include "url/origin.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/policy/policy_cert_service.h" #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(FULL_SAFE_BROWSING) #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" @@ -262,7 +263,7 @@ } bool SecurityStateTabHelper::UsedPolicyInstalledCertificate() const { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) policy::PolicyCertService* service = policy::PolicyCertServiceFactory::GetForProfile( Profile::FromBrowserContext(web_contents()->GetBrowserContext()));
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index 97a0406..9ca4bf2 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -38,6 +38,7 @@ #include "base/time/default_tick_clock.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" @@ -203,7 +204,7 @@ #include "net/cert/x509_util_nss.h" #endif // defined(USE_NSS_CERTS) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/path_service.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/profile_policy_connector.h" @@ -212,7 +213,7 @@ #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service.h" #include "components/session_manager/core/session_manager.h" -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) #include "base/mac/mac_util.h" @@ -4073,7 +4074,7 @@ // Visit a page and establish a WebSocket connection over bad https with // --ignore-certificate-errors-spki-list. The connection should be established // without interstitial page showing. -#if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Chrome OS does not support the flag. IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIWSS, TestWSSExpired) { ASSERT_TRUE(wss_server_expired_.Start()); @@ -4096,11 +4097,11 @@ const base::string16 result = watcher.WaitAndGetTitle(); EXPECT_TRUE(base::LowerCaseEqualsASCII(result, "pass")); } -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) // Test that HTTPS pages with a bad certificate don't show an interstitial if // the public key matches a value from --ignore-certificate-errors-spki-list. -#if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Chrome OS does not support the flag. IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestHTTPS) { ASSERT_TRUE(https_server_mismatched_.Start()); @@ -4117,11 +4118,11 @@ ui_test_utils::GetCurrentTabTitle(browser(), &title); EXPECT_EQ(title, base::ASCIIToUTF16("This script has loaded")); } -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) // Test subresources from an origin with a bad certificate are loaded if the // public key matches a value from --ignore-certificate-errors-spki-list. -#if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. +#if !BUILDFLAG(IS_CHROMEOS_ASH) // Chrome OS does not support the flag. IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestInsecureSubresource) { ASSERT_TRUE(https_server_.Start()); @@ -4144,7 +4145,7 @@ tab, "window.domAutomationController.send(ImageWidth());", &img_width)); EXPECT_GT(img_width, 200); } -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) // Verifies that the interstitial can proceed, even if JavaScript is disabled. IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialJavaScriptProceeds) { @@ -5725,7 +5726,7 @@ ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) class SSLUITestNoCert : public SSLUITest, public CertificateManagerModel::Observer { @@ -5944,7 +5945,7 @@ ssl_test_util::CheckAuthenticatedState(tab_for_profile_2, AuthState::NONE); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // Regression test for http://crbug.com/635833 (crash when a window with no // NavigationEntry commits).
diff --git a/chrome/browser/ssl/ssl_error_controller_client.cc b/chrome/browser/ssl/ssl_error_controller_client.cc index c155c24..39857960 100644 --- a/chrome/browser/ssl/ssl_error_controller_client.cc +++ b/chrome/browser/ssl/ssl_error_controller_client.cc
@@ -14,6 +14,7 @@ #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/interstitials/enterprise_util.h" #include "chrome/browser/profiles/profile.h" @@ -28,7 +29,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h" @@ -139,7 +140,7 @@ void SSLErrorControllerClient::LaunchDateAndTimeSettings() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( ProfileManager::GetActiveUserProfile(), chromeos::settings::mojom::kDateAndTimeSectionPath);
diff --git a/chrome/browser/sync/test/integration/profile_sync_service_harness.cc b/chrome/browser/sync/test/integration/profile_sync_service_harness.cc index d9af26e5..0478372 100644 --- a/chrome/browser/sync/test/integration/profile_sync_service_harness.cc +++ b/chrome/browser/sync/test/integration/profile_sync_service_harness.cc
@@ -25,7 +25,6 @@ #include "chrome/common/channel_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" -#include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_internals_util.h" #include "components/sync/engine/sync_string_conversions.h" #include "components/sync/engine_impl/net/url_translator.h" @@ -259,10 +258,8 @@ void ProfileSyncServiceHarness::ExitSyncPausedStateForPrimaryAccount() { signin::SetRefreshTokenForPrimaryAccount( IdentityManagerFactory::GetForProfile(profile_)); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - // The engine was off in the sync-paused state, so wait for it to start. - AwaitSyncSetupCompletion(); - } + // The engine was off in the sync-paused state, so wait for it to start. + AwaitSyncSetupCompletion(); } bool ProfileSyncServiceHarness::SetupSync() {
diff --git a/chrome/browser/sync/test/integration/sync_auth_test.cc b/chrome/browser/sync/test/integration/sync_auth_test.cc index 9686480..d52ef58e 100644 --- a/chrome/browser/sync/test/integration/sync_auth_test.cc +++ b/chrome/browser/sync/test/integration/sync_auth_test.cc
@@ -19,7 +19,6 @@ #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/driver/profile_sync_service.h" -#include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_token_status.h" #include "content/public/test/browser_test.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -331,17 +330,10 @@ GetClient(0)->EnterSyncPausedStateForPrimaryAccount(); ASSERT_TRUE(GetSyncService(0)->GetAuthError().IsPersistentError()); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - // Sync should have shut itself down. - EXPECT_EQ(GetSyncService(0)->GetTransportState(), - syncer::SyncService::TransportState::PAUSED); - EXPECT_FALSE(GetSyncService(0)->IsEngineInitialized()); - } else { - ASSERT_TRUE(AttemptToTriggerAuthError()); - - // Pausing sync may issue a reconfiguration, so wait until it finishes. - SyncTransportActiveChecker(GetSyncService(0)).Wait(); - } + // Sync should have shut itself down. + EXPECT_EQ(GetSyncService(0)->GetTransportState(), + syncer::SyncService::TransportState::PAUSED); + EXPECT_FALSE(GetSyncService(0)->IsEngineInitialized()); // The active data types should now be empty. EXPECT_TRUE(GetSyncService(0)->GetActiveDataTypes().Empty()); @@ -353,13 +345,8 @@ NoAuthErrorChecker(GetSyncService(0)).Wait(); ASSERT_FALSE(GetSyncService(0)->GetAuthError().IsPersistentError()); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - // Once the auth error is gone, wait for Sync to start up again. - GetClient(0)->AwaitSyncSetupCompletion(); - } else { - // Resuming sync could issue a reconfiguration, so wait until it finishes. - SyncTransportActiveChecker(GetSyncService(0)).Wait(); - } + // Once the auth error is gone, wait for Sync to start up again. + GetClient(0)->AwaitSyncSetupCompletion(); // Now the active data types should be back. EXPECT_TRUE(GetSyncService(0)->IsSyncFeatureActive()); @@ -399,17 +386,10 @@ GetClient(0)->EnterSyncPausedStateForPrimaryAccount(); ASSERT_TRUE(GetSyncService(0)->GetAuthError().IsPersistentError()); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - // Sync should have shut itself down. - EXPECT_EQ(GetSyncService(0)->GetTransportState(), - syncer::SyncService::TransportState::PAUSED); - EXPECT_FALSE(GetSyncService(0)->IsEngineInitialized()); - } else { - ASSERT_TRUE(AttemptToTriggerAuthError()); - - // Pausing sync may issue a reconfiguration, so wait until it finishes. - SyncTransportActiveChecker(GetSyncService(0)).Wait(); - } + // Sync should have shut itself down. + EXPECT_EQ(GetSyncService(0)->GetTransportState(), + syncer::SyncService::TransportState::PAUSED); + EXPECT_FALSE(GetSyncService(0)->IsEngineInitialized()); ASSERT_FALSE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::BOOKMARKS)); ASSERT_FALSE( @@ -429,13 +409,8 @@ // access token again, so wait for that to happen. NoAuthErrorChecker(GetSyncService(0)).Wait(); ASSERT_FALSE(GetSyncService(0)->GetAuthError().IsPersistentError()); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - // Once the auth error is gone, wait for Sync to start up again. - GetClient(0)->AwaitSyncSetupCompletion(); - } else { - // Resuming sync could issue a reconfiguration, so wait until it finishes. - SyncTransportActiveChecker(GetSyncService(0)).Wait(); - } + // Once the auth error is gone, wait for Sync to start up again. + GetClient(0)->AwaitSyncSetupCompletion(); // Resuming sync could issue a reconfiguration, so wait until it finishes. SyncTransportActiveChecker(GetSyncService(0)).Wait();
diff --git a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc index 3f9b7f0..919bfe0 100644 --- a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc
@@ -5,6 +5,7 @@ #include "base/callback_list.h" #include "base/run_loop.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/send_tab_to_self/send_tab_to_self_util.h" #include "chrome/browser/sync/device_info_sync_service_factory.h" @@ -296,7 +297,7 @@ }; // Non-primary accounts don't exist on ChromeOS. -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F( TwoClientSendTabToSelfSyncTestWithSendTabToSelfWhenSignedIn, SignedInClientCanReceive) { @@ -328,4 +329,4 @@ EXPECT_TRUE(device_infos[0]->send_tab_to_self_receiving_enabled()); EXPECT_TRUE(device_infos[1]->send_tab_to_self_receiving_enabled()); } -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java index 76244dc..449f48f 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java
@@ -90,6 +90,22 @@ this.price = price; this.previousPrice = previousPrice; } + + @Override + public boolean equals(Object object) { + if (!(object instanceof PriceDrop)) return false; + PriceDrop priceDrop = (PriceDrop) object; + return this.price.equals(priceDrop.price) + && this.previousPrice.equals(priceDrop.previousPrice); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (price == null ? 0 : price.hashCode()); + result = 31 * result + (previousPrice == null ? 0 : previousPrice.hashCode()); + return result; + } } @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
diff --git a/chrome/browser/themes/theme_service_factory.cc b/chrome/browser/themes/theme_service_factory.cc index caec77bb..4f82e3d 100644 --- a/chrome/browser/themes/theme_service_factory.cc +++ b/chrome/browser/themes/theme_service_factory.cc
@@ -6,6 +6,7 @@ #include "base/no_destructor.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_system_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" @@ -22,7 +23,9 @@ #include "chrome/browser/themes/theme_helper_win.h" #endif -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/themes/theme_service_aura_linux.h" #include "ui/views/linux_ui/linux_ui.h" #endif @@ -77,7 +80,9 @@ KeyedService* ThemeServiceFactory::BuildServiceInstanceFor( content::BrowserContext* profile) const { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) using ThemeService = ThemeServiceAuraLinux; #endif @@ -89,7 +94,9 @@ void ThemeServiceFactory::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) bool default_uses_system_theme = false; const views::LinuxUI* linux_ui = views::LinuxUI::instance();
diff --git a/chrome/browser/themes/theme_syncable_service_unittest.cc b/chrome/browser/themes/theme_syncable_service_unittest.cc index b5aa14b4..bf02f25 100644 --- a/chrome/browser/themes/theme_syncable_service_unittest.cc +++ b/chrome/browser/themes/theme_syncable_service_unittest.cc
@@ -16,6 +16,7 @@ #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/profiles/profile.h" @@ -40,7 +41,7 @@ #include "extensions/common/permissions/permission_set.h" #include "testing/gtest/include/gtest/gtest.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #endif @@ -251,7 +252,7 @@ // Needed for setting up extension service. content::BrowserTaskEnvironment task_environment_; -#if defined OS_CHROMEOS +#if BUILDFLAG(IS_CHROMEOS_ASH) chromeos::ScopedCrosSettingsTestHelper cros_settings_test_helper_; chromeos::ScopedTestUserManager test_user_manager_; #endif
diff --git a/chrome/browser/tracing/chrome_tracing_delegate.cc b/chrome/browser/tracing/chrome_tracing_delegate.cc index 4eb6b5c..a218fbb 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate.cc +++ b/chrome/browser/tracing/chrome_tracing_delegate.cc
@@ -15,6 +15,7 @@ #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -179,7 +180,7 @@ PrefService* local_state = g_browser_process->local_state(); DCHECK(local_state); -#if !defined(OS_CHROMEOS) && defined(OFFICIAL_BUILD) +#if !BUILDFLAG(IS_CHROMEOS_ASH) && defined(OFFICIAL_BUILD) if (!local_state->GetBoolean(metrics::prefs::kMetricsReportingEnabled)) { RecordDisallowedMetric( TracingFinalizationDisallowedReason::kMetricsReportingDisabled);
diff --git a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc index 87c01d66..3029677 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc +++ b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/command_line.h" #include "base/run_loop.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/browser_commands.h" @@ -35,7 +36,7 @@ started_finalizations_count_(0), last_on_started_finalizing_success_(false) {} -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) void SetUpOnMainThread() override { PrefService* local_state = g_browser_process->local_state(); DCHECK(local_state);
diff --git a/chrome/browser/tracing/crash_service_uploader.cc b/chrome/browser/tracing/crash_service_uploader.cc index d879eea..e59f3a4 100644 --- a/chrome/browser/tracing/crash_service_uploader.cc +++ b/chrome/browser/tracing/crash_service_uploader.cc
@@ -18,6 +18,7 @@ #include "base/task/thread_pool.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/tracing/common/tracing_switches.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_task_traits.h" @@ -152,7 +153,7 @@ const char product[] = "Chrome"; #elif defined(OS_MAC) const char product[] = "Chrome_Mac"; -#elif defined(OS_CHROMEOS) +#elif BUILDFLAG(IS_CHROMEOS_ASH) // On ChromeOS, defined(OS_LINUX) also evalutes to true, so the // defined(OS_CHROMEOS) block must come first. const char product[] = "Chrome_ChromeOS";
diff --git a/chrome/browser/translate/chrome_translate_client.cc b/chrome/browser/translate/chrome_translate_client.cc index 1c550b78..3a5a665 100644 --- a/chrome/browser/translate/chrome_translate_client.cc +++ b/chrome/browser/translate/chrome_translate_client.cc
@@ -13,6 +13,7 @@ #include "base/path_service.h" #include "base/strings/string_split.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/infobars/infobar_service.h" @@ -156,7 +157,7 @@ // static std::unique_ptr<translate::TranslatePrefs> ChromeTranslateClient::CreateTranslatePrefs(PrefService* prefs) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) const char* preferred_languages_prefs = language::prefs::kPreferredLanguages; #else const char* preferred_languages_prefs = NULL;
diff --git a/chrome/browser/translate/translate_service.cc b/chrome/browser/translate/translate_service.cc index 9caa6676..9fe8c2e 100644 --- a/chrome/browser/translate/translate_service.cc +++ b/chrome/browser/translate/translate_service.cc
@@ -11,6 +11,7 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/translate/chrome_translate_client.h" @@ -26,7 +27,7 @@ #include "url/gurl.h" #include "url/url_constants.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/file_manager/app_id.h" #include "extensions/common/constants.h" #endif @@ -147,7 +148,7 @@ !url.SchemeIs(url::kFileScheme) && !url.SchemeIs(url::kContentScheme) && !url.SchemeIs(content::kChromeDevToolsScheme) && !url.IsAboutBlank() && -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) !(url.SchemeIs(extensions::kExtensionScheme) && url.DomainIs(file_manager::kFileManagerAppId)) && #endif
diff --git a/chrome/browser/translate/translate_service_unittest.cc b/chrome/browser/translate/translate_service_unittest.cc index b77c679..1f20a29 100644 --- a/chrome/browser/translate/translate_service_unittest.cc +++ b/chrome/browser/translate/translate_service_unittest.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/translate/translate_service.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/url_constants.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" @@ -15,7 +16,7 @@ #include "url/gurl.h" #include "url/url_constants.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/file_manager/app_id.h" #include "extensions/common/constants.h" #endif @@ -49,7 +50,7 @@ GURL file_url = GURL(file); EXPECT_FALSE(TranslateService::IsTranslatableURL(file_url)); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) std::string filemanager = std::string(extensions::kExtensionScheme) + std::string("://") + std::string(file_manager::kFileManagerAppId);
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b36c6e5..cc312e0 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -219,10 +219,10 @@ "webui/engagement/site_engagement_ui.h", "webui/fileicon_source.cc", "webui/fileicon_source.h", - "webui/flags_ui.cc", - "webui/flags_ui.h", - "webui/flags_ui_handler.cc", - "webui/flags_ui_handler.h", + "webui/flags/flags_ui.cc", + "webui/flags/flags_ui.h", + "webui/flags/flags_ui_handler.cc", + "webui/flags/flags_ui_handler.h", "webui/gcm_internals_ui.cc", "webui/gcm_internals_ui.h", "webui/internals/internals_ui.cc", @@ -233,10 +233,10 @@ "webui/interventions_internals/interventions_internals_page_handler.h", "webui/interventions_internals/interventions_internals_ui.cc", "webui/interventions_internals/interventions_internals_ui.h", - "webui/invalidations_message_handler.cc", - "webui/invalidations_message_handler.h", - "webui/invalidations_ui.cc", - "webui/invalidations_ui.h", + "webui/invalidations/invalidations_message_handler.cc", + "webui/invalidations/invalidations_message_handler.h", + "webui/invalidations/invalidations_ui.cc", + "webui/invalidations/invalidations_ui.h", "webui/local_state/local_state_ui.cc", "webui/local_state/local_state_ui.h", "webui/log_web_ui_url.cc", @@ -299,10 +299,10 @@ "webui/user_actions/user_actions_ui.h", "webui/user_actions/user_actions_ui_handler.cc", "webui/user_actions/user_actions_ui_handler.h", - "webui/version_handler.cc", - "webui/version_handler.h", - "webui/version_ui.cc", - "webui/version_ui.h", + "webui/version/version_handler.cc", + "webui/version/version_handler.h", + "webui/version/version_ui.cc", + "webui/version/version_ui.h", "webui/webui_load_timer.cc", "webui/webui_load_timer.h", "webui/webui_util.cc", @@ -773,10 +773,10 @@ "webui/offline/offline_internals_ui_message_handler.h", "webui/video_tutorials/video_player_source.cc", "webui/video_tutorials/video_player_source.h", - "webui/webapks_handler.cc", - "webui/webapks_handler.h", - "webui/webapks_ui.cc", - "webui/webapks_ui.h", + "webui/webapks/webapks_handler.cc", + "webui/webapks/webapks_handler.h", + "webui/webapks/webapks_ui.cc", + "webui/webapks/webapks_ui.h", ] if (enable_feed_v1 || enable_feed_v2) { sources += [ @@ -1242,8 +1242,12 @@ "task_manager/task_manager_columns.h", "task_manager/task_manager_table_model.cc", "task_manager/task_manager_table_model.h", + "thumbnails/background_thumbnail_capturer.h", + "thumbnails/background_thumbnail_video_capturer.cc", + "thumbnails/background_thumbnail_video_capturer.h", "thumbnails/thumbnail_capture_driver.cc", "thumbnails/thumbnail_capture_driver.h", + "thumbnails/thumbnail_capture_info.h", "thumbnails/thumbnail_image.cc", "thumbnails/thumbnail_image.h", "thumbnails/thumbnail_readiness_tracker.cc", @@ -2570,8 +2574,8 @@ "webui/signin/inline_login_handler_chromeos.h", "webui/signin/inline_login_handler_modal_delegate.cc", "webui/signin/inline_login_handler_modal_delegate.h", - "webui/version_handler_chromeos.cc", - "webui/version_handler_chromeos.h", + "webui/version/version_handler_chromeos.cc", + "webui/version/version_handler_chromeos.h", "window_sizer/window_sizer_chromeos.cc", "window_sizer/window_sizer_chromeos.h", ] @@ -2859,6 +2863,8 @@ "views/profiles/profile_picker_view.h", "views/profiles/profile_picker_view_sync_delegate.cc", "views/profiles/profile_picker_view_sync_delegate.h", + "views/profiles/user_manager_profile_dialog_delegate.cc", + "views/profiles/user_manager_profile_dialog_delegate.h", "views/profiles/user_manager_view.cc", "views/profiles/user_manager_view.h", "webui/app_launcher_page_ui.cc", @@ -3208,10 +3214,10 @@ "webui/settings/chrome_cleanup_handler_win.cc", "webui/settings/chrome_cleanup_handler_win.h", "webui/settings_utils_win.cc", - "webui/version_handler_win.cc", - "webui/version_handler_win.h", - "webui/version_util_win.cc", - "webui/version_util_win.h", + "webui/version/version_handler_win.cc", + "webui/version/version_handler_win.h", + "webui/version/version_util_win.cc", + "webui/version/version_util_win.h", ] public_deps += [ "//ui/views",
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 5c8ebf4..d0744373 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -464,6 +464,9 @@ <message name="IDS_AUTOFILL_PROFILE_EDITOR_COUNTRY" desc="Label for a spinner input field containing a list of countries or regions [CHAR-LIMIT=32]"> Country/Region </message> + <message name="IDS_AUTOFILL_PROFILE_EDITOR_HONORIFIC_PREFIX" desc="Label for text input field containing a title that can be auto-filled by Chrome. [CHAR-LIMIT=32]" meaning="A 'Title' field in a web form could be a prefix like Ms., Mx., or Dr. or a position held, like Captain or Rabbi."> + Title + </message> <message name="IDS_AUTOFILL_PROFILE_EDITOR_EMAIL_ADDRESS" desc="Label for text input field containing an e-mail address. [CHAR-LIMIT=32]"> Email </message>
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_AUTOFILL_PROFILE_EDITOR_HONORIFIC_PREFIX.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_AUTOFILL_PROFILE_EDITOR_HONORIFIC_PREFIX.png.sha1 new file mode 100644 index 0000000..ec67b29 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_AUTOFILL_PROFILE_EDITOR_HONORIFIC_PREFIX.png.sha1
@@ -0,0 +1 @@ +4dcf597fed4da10035e80a4f22cf4a73b927a84e \ No newline at end of file
diff --git a/chrome/browser/ui/app_list/arc/arc_usb_host_permission_manager.cc b/chrome/browser/ui/app_list/arc/arc_usb_host_permission_manager.cc index 8096cfd..2c92c5b 100644 --- a/chrome/browser/ui/app_list/arc/arc_usb_host_permission_manager.cc +++ b/chrome/browser/ui/app_list/arc/arc_usb_host_permission_manager.cc
@@ -386,8 +386,10 @@ *current_request.usb_device_entry())) { OnUsbPermissionReceived(std::move(current_request), true); } else { + const base::string16 device_name = + current_request.usb_device_entry()->device_name; ShowUsbAccessPermissionDialog( - profile_, app_id, current_request.usb_device_entry()->device_name, + profile_, app_id, device_name, base::BindOnce(&ArcUsbHostPermissionManager::OnUsbPermissionReceived, weak_ptr_factory_.GetWeakPtr(), std::move(current_request)));
diff --git a/chrome/browser/ui/ash/chrome_new_window_client.cc b/chrome/browser/ui/ash/chrome_new_window_client.cc index 9bf6bf7f..c7d5d41 100644 --- a/chrome/browser/ui/ash/chrome_new_window_client.cc +++ b/chrome/browser/ui/ash/chrome_new_window_client.cc
@@ -27,7 +27,6 @@ #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/web_applications/chrome_camera_app_ui_delegate.h" -#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile_manager.h" @@ -416,14 +415,12 @@ void ChromeNewWindowClient::OpenCrosh() { Profile* profile = ProfileManager::GetActiveUserProfile(); - GURL crosh_url = extensions::TerminalExtensionHelper::GetCroshURL(profile); - if (!crosh_url.is_valid()) - return; chrome::ScopedTabbedBrowserDisplayer displayer(profile); Browser* browser = displayer.browser(); content::WebContents* page = browser->OpenURL(content::OpenURLParams( - crosh_url, content::Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_GENERATED, false)); + GURL(chrome::kChromeUIUntrustedCroshURL), content::Referrer(), + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_GENERATED, + false)); browser->window()->Show(); browser->window()->Activate(); page->Focus();
diff --git a/chrome/browser/ui/ash/keyboard/DIR_METADATA b/chrome/browser/ui/ash/keyboard/DIR_METADATA index c209bae..1ae4c22 100644 --- a/chrome/browser/ui/ash/keyboard/DIR_METADATA +++ b/chrome/browser/ui/ash/keyboard/DIR_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Input>VirtualKeyboard" + component: "OS>Inputs" }
diff --git a/chrome/browser/ui/settings_window_manager_chromeos.cc b/chrome/browser/ui/settings_window_manager_chromeos.cc index 5b03d84..a071241 100644 --- a/chrome/browser/ui/settings_window_manager_chromeos.cc +++ b/chrome/browser/ui/settings_window_manager_chromeos.cc
@@ -5,11 +5,9 @@ #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "ash/public/cpp/app_types.h" -#include "ash/public/cpp/multi_user_window_manager.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h" #include "chrome/browser/ui/ash/window_properties.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator.h" @@ -34,17 +32,6 @@ bool g_force_deprecated_settings_window_for_testing = false; -// This method handles the case of resurfacing the user's OS Settings -// standalone window that may be at the time located on another user's desktop. -void ShowSettingsOnCurrentDesktop(Browser* browser) { - auto* window_manager = MultiUserWindowManagerHelper::GetWindowManager(); - if (window_manager && browser) { - window_manager->ShowWindowForUser(browser->window()->GetNativeWindow(), - window_manager->CurrentAccountId()); - browser->window()->Show(); - } -} - } // namespace // static @@ -84,18 +71,10 @@ // TODO(crbug.com/1067073): Remove legacy Settings Window. if (!UseDeprecatedSettingsWindow(profile)) { - bool did_create; - Browser* browser = web_app::LaunchSystemWebApp( - profile, web_app::SystemAppType::SETTINGS, gurl, - /*params=*/base::nullopt, &did_create); - ShowSettingsOnCurrentDesktop(browser); - // Only notify if we created a new browser. - if (!did_create || !browser) - return; - - for (SettingsWindowManagerObserver& observer : observers_) - observer.OnNewSettingsWindow(browser); - + web_app::LaunchSystemWebApp(profile, web_app::SystemAppType::SETTINGS, + gurl); + // SWA OS Settings don't use SettingsWindowManager to manage windows, don't + // notify SettingsWindowObservers. return; }
diff --git a/chrome/browser/ui/thumbnails/background_thumbnail_capturer.h b/chrome/browser/ui/thumbnails/background_thumbnail_capturer.h new file mode 100644 index 0000000..58d80cb --- /dev/null +++ b/chrome/browser/ui/thumbnails/background_thumbnail_capturer.h
@@ -0,0 +1,26 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_CAPTURER_H_ +#define CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_CAPTURER_H_ + +#include "chrome/browser/ui/thumbnails/thumbnail_capture_info.h" +#include "ui/gfx/geometry/size.h" + +// Captures thumbnails from a background tab's contents. +class BackgroundThumbnailCapturer { + public: + BackgroundThumbnailCapturer() = default; + virtual ~BackgroundThumbnailCapturer() = default; + + // Begins capture. The tab's renderer must be alive. The subclass will + // determine how captured frames are reported to the client. + virtual void Start(const ThumbnailCaptureInfo& capture_info) = 0; + + // Ends capture. After this call, the tab no longer needs to be kept + // alive. + virtual void Stop() = 0; +}; + +#endif // CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_CAPTURER_H_
diff --git a/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.cc b/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.cc new file mode 100644 index 0000000..d9667e3 --- /dev/null +++ b/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.cc
@@ -0,0 +1,161 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.h" + +#include <utility> + +#include "base/metrics/histogram_macros.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" +#include "content/public/browser/render_widget_host_view.h" +#include "content/public/browser/web_contents.h" +#include "ui/gfx/skia_util.h" + +BackgroundThumbnailVideoCapturer::BackgroundThumbnailVideoCapturer( + content::WebContents* contents, + GotFrameCallback got_frame_callback) + : contents_(contents), got_frame_callback_(std::move(got_frame_callback)) { + DCHECK(contents_); + DCHECK(got_frame_callback_); +} + +BackgroundThumbnailVideoCapturer::~BackgroundThumbnailVideoCapturer() = default; + +void BackgroundThumbnailVideoCapturer::Start( + const ThumbnailCaptureInfo& capture_info) { + if (video_capturer_) + return; + + content::RenderWidgetHostView* const source_view = + contents_->GetMainFrame()->GetRenderViewHost()->GetWidget()->GetView(); + if (!source_view) + return; + + capture_info_ = capture_info; + + start_time_ = base::TimeTicks::Now(); + got_first_frame_ = false; + + constexpr int kMaxFrameRate = 2; + video_capturer_ = source_view->CreateVideoCapturer(); + video_capturer_->SetResolutionConstraints(capture_info_.target_size, + capture_info_.target_size, false); + video_capturer_->SetAutoThrottlingEnabled(false); + video_capturer_->SetMinSizeChangePeriod(base::TimeDelta()); + video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB, + gfx::ColorSpace::CreateREC709()); + video_capturer_->SetMinCapturePeriod(base::TimeDelta::FromSeconds(1) / + kMaxFrameRate); + video_capturer_->Start(this); +} + +void BackgroundThumbnailVideoCapturer::Stop() { + if (!video_capturer_) + return; + + video_capturer_->Stop(); + video_capturer_.reset(); + + UMA_HISTOGRAM_MEDIUM_TIMES("Tab.Preview.VideoCaptureDuration", + base::TimeTicks::Now() - start_time_); + start_time_ = base::TimeTicks(); +} + +void BackgroundThumbnailVideoCapturer::OnFrameCaptured( + base::ReadOnlySharedMemoryRegion data, + ::media::mojom::VideoFrameInfoPtr info, + const gfx::Rect& content_rect, + mojo::PendingRemote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + callbacks) { + CHECK(video_capturer_); + const base::TimeTicks time_of_call = base::TimeTicks::Now(); + + mojo::Remote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + callbacks_remote(std::move(callbacks)); + + // Process captured image. + if (!data.IsValid()) { + callbacks_remote->Done(); + return; + } + base::ReadOnlySharedMemoryMapping mapping = data.Map(); + if (!mapping.IsValid()) { + DLOG(ERROR) << "Shared memory mapping failed."; + return; + } + if (mapping.size() < + media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) { + DLOG(ERROR) << "Shared memory size was less than expected."; + return; + } + if (!info->color_space) { + DLOG(ERROR) << "Missing mandatory color space info."; + return; + } + + if (!got_first_frame_) + UMA_HISTOGRAM_TIMES("Tab.Preview.TimeToFirstUsableFrameAfterStartCapture", + time_of_call - start_time_); + got_first_frame_ = true; + + // The SkBitmap's pixels will be marked as immutable, but the installPixels() + // API requires a non-const pointer. So, cast away the const. + void* const pixels = const_cast<void*>(mapping.memory()); + + // Call installPixels() with a |releaseProc| that: 1) notifies the capturer + // that this consumer has finished with the frame, and 2) releases the shared + // memory mapping. + struct FramePinner { + // Keeps the shared memory that backs |frame_| mapped. + base::ReadOnlySharedMemoryMapping mapping; + // Prevents FrameSinkVideoCapturer from recycling the shared memory that + // backs |frame_|. + mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + releaser; + }; + + // Subtract back out the scroll bars if we decided there was enough canvas to + // account for them and still have a decent preview image. + const float scale_ratio = + float{content_rect.width()} / float{capture_info_.copy_rect.width()}; + + const gfx::Insets original_scroll_insets = capture_info_.scrollbar_insets; + const gfx::Insets scroll_insets( + 0, 0, std::round(original_scroll_insets.width() * scale_ratio), + std::round(original_scroll_insets.height() * scale_ratio)); + gfx::Rect effective_content_rect = content_rect; + effective_content_rect.Inset(scroll_insets); + + const gfx::Size bitmap_size(content_rect.right(), content_rect.bottom()); + SkBitmap frame; + frame.installPixels( + SkImageInfo::MakeN32(bitmap_size.width(), bitmap_size.height(), + kPremul_SkAlphaType, + info->color_space->ToSkColorSpace()), + pixels, + media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane, + info->pixel_format, info->coded_size.width()), + [](void* addr, void* context) { + delete static_cast<FramePinner*>(context); + }, + new FramePinner{std::move(mapping), callbacks_remote.Unbind()}); + frame.setImmutable(); + + SkBitmap cropped_frame; + if (frame.extractSubset(&cropped_frame, + gfx::RectToSkIRect(effective_content_rect))) { + UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( + "Tab.Preview.TimeToStoreAfterFrameReceived", + base::TimeTicks::Now() - time_of_call, + base::TimeDelta::FromMicroseconds(10), + base::TimeDelta::FromMilliseconds(10), 50); + got_frame_callback_.Run(cropped_frame); + } +} + +void BackgroundThumbnailVideoCapturer::OnStopped() {} + +void BackgroundThumbnailVideoCapturer::OnLog(const std::string& /*message*/) {}
diff --git a/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.h b/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.h new file mode 100644 index 0000000..cc6da4f --- /dev/null +++ b/chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.h
@@ -0,0 +1,54 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_VIDEO_CAPTURER_H_ +#define CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_VIDEO_CAPTURER_H_ + +#include "base/callback.h" +#include "base/time/time.h" +#include "chrome/browser/ui/thumbnails/background_thumbnail_capturer.h" +#include "components/viz/host/client_frame_sink_video_capturer.h" +#include "third_party/skia/include/core/SkBitmap.h" + +namespace content { +class WebContents; +} // namespace content + +// A thumbnail capturer using viz::ClientFrameSinkVideoCapturer. Gets a +// sequence of frames in the same way as streaming a tab. +class BackgroundThumbnailVideoCapturer + : public BackgroundThumbnailCapturer, + public viz::mojom::FrameSinkVideoConsumer { + public: + using GotFrameCallback = base::RepeatingCallback<void(const SkBitmap&)>; + BackgroundThumbnailVideoCapturer(content::WebContents* contents, + GotFrameCallback got_frame_callback); + ~BackgroundThumbnailVideoCapturer() override; + + // BackgroundThumbnailCapturer: + void Start(const ThumbnailCaptureInfo& capture_info) override; + void Stop() override; + + private: + // viz::mojom::FrameSinkVideoConsumer: + void OnFrameCaptured( + base::ReadOnlySharedMemoryRegion data, + ::media::mojom::VideoFrameInfoPtr info, + const gfx::Rect& content_rect, + mojo::PendingRemote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + callbacks) override; + void OnStopped() override; + void OnLog(const std::string& /*message*/) override; + + content::WebContents* const contents_; + GotFrameCallback got_frame_callback_; + + ThumbnailCaptureInfo capture_info_; + std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_; + + base::TimeTicks start_time_; + bool got_first_frame_ = false; +}; + +#endif // CHROME_BROWSER_UI_THUMBNAILS_BACKGROUND_THUMBNAIL_VIDEO_CAPTURER_H_
diff --git a/chrome/browser/ui/thumbnails/thumbnail_capture_info.h b/chrome/browser/ui/thumbnails/thumbnail_capture_info.h new file mode 100644 index 0000000..6ddfeed --- /dev/null +++ b/chrome/browser/ui/thumbnails/thumbnail_capture_info.h
@@ -0,0 +1,29 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_ +#define CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_ + +#include "ui/gfx/geometry/insets.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" + +// Describes how a thumbnail bitmap should be generated from a target surface. +// All sizes are in pixels, not DIPs. +struct ThumbnailCaptureInfo { + // The total source size (including scrollbars). + gfx::Size source_size; + + // Insets for scrollbars in the source image that should probably be + // ignored for thumbnailing purposes. + gfx::Insets scrollbar_insets; + + // Cropping rectangle for the source canvas, in pixels. + gfx::Rect copy_rect; + + // Size of the target bitmap in pixels. + gfx::Size target_size; +}; + +#endif // CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_
diff --git a/chrome/browser/ui/thumbnails/thumbnail_tab_helper.cc b/chrome/browser/ui/thumbnails/thumbnail_tab_helper.cc index 52ac0a5..0967bcec 100644 --- a/chrome/browser/ui/thumbnails/thumbnail_tab_helper.cc +++ b/chrome/browser/ui/thumbnails/thumbnail_tab_helper.cc
@@ -16,22 +16,18 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/timer/timer.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/resource_coordinator/tab_load_tracker.h" #include "chrome/browser/ui/tabs/tab_style.h" +#include "chrome/browser/ui/thumbnails/background_thumbnail_video_capturer.h" #include "chrome/browser/ui/thumbnails/thumbnail_capture_driver.h" #include "chrome/browser/ui/thumbnails/thumbnail_readiness_tracker.h" #include "chrome/browser/ui/thumbnails/thumbnail_scheduler.h" #include "chrome/browser/ui/thumbnails/thumbnail_scheduler_impl.h" -#include "components/history/core/common/thumbnail_score.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" -#include "media/capture/mojom/video_capture_types.mojom.h" -#include "mojo/public/cpp/bindings/remote.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/scrollbar_size.h" @@ -212,6 +208,11 @@ ThumbnailTabHelper::ThumbnailTabHelper(content::WebContents* contents) : state_(std::make_unique<TabStateTracker>(this, contents)), + background_capturer_(std::make_unique<BackgroundThumbnailVideoCapturer>( + contents, + base::BindRepeating(&ThumbnailTabHelper::StoreThumbnail, + base::Unretained(this), + CaptureType::kVideoFrame))), thumbnail_(base::MakeRefCounted<ThumbnailImage>(state_.get())) {} ThumbnailTabHelper::~ThumbnailTabHelper() { @@ -282,159 +283,29 @@ } void ThumbnailTabHelper::StartVideoCapture() { - if (video_capturer_) - return; - - // This pointer can become null before this method is called - see - // RenderWidgetHost::GetView() for details. content::RenderWidgetHostView* const source_view = state_->GetView(); if (!source_view) return; - // Get the source size and scale. const float scale_factor = source_view->GetDeviceScaleFactor(); const gfx::Size source_size = source_view->GetViewBounds().size(); if (source_size.IsEmpty()) return; - start_video_capture_time_ = base::TimeTicks::Now(); - got_first_frame_ = false; - - // Figure out how large we want the capture target to be. - last_frame_capture_info_ = - GetInitialCaptureInfo(source_size, scale_factor, - /* include_scrollbars_in_capture */ true); - - const gfx::Size& target_size = last_frame_capture_info_.target_size; - constexpr int kMaxFrameRate = 2; - video_capturer_ = source_view->CreateVideoCapturer(); - video_capturer_->SetResolutionConstraints(target_size, target_size, false); - video_capturer_->SetAutoThrottlingEnabled(false); - video_capturer_->SetMinSizeChangePeriod(base::TimeDelta()); - video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB, - gfx::ColorSpace::CreateREC709()); - video_capturer_->SetMinCapturePeriod(base::TimeDelta::FromSeconds(1) / - kMaxFrameRate); - video_capturer_->Start(this); + last_frame_capture_info_ = GetInitialCaptureInfo( + source_size, scale_factor, /* include_scrollbars_in_capture */ true); + background_capturer_->Start(last_frame_capture_info_); } void ThumbnailTabHelper::StopVideoCapture() { - if (!video_capturer_) { - DCHECK_EQ(start_video_capture_time_, base::TimeTicks()); - return; - } - - video_capturer_->Stop(); - video_capturer_.reset(); - - UMA_HISTOGRAM_MEDIUM_TIMES( - "Tab.Preview.VideoCaptureDuration", - base::TimeTicks::Now() - start_video_capture_time_); - - start_video_capture_time_ = base::TimeTicks(); + background_capturer_->Stop(); } -void ThumbnailTabHelper::OnFrameCaptured( - base::ReadOnlySharedMemoryRegion data, - ::media::mojom::VideoFrameInfoPtr info, - const gfx::Rect& content_rect, - mojo::PendingRemote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> - callbacks) { - CHECK(video_capturer_); - const base::TimeTicks time_of_call = base::TimeTicks::Now(); - - mojo::Remote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> - callbacks_remote(std::move(callbacks)); - - // Process captured image. - if (!data.IsValid()) { - callbacks_remote->Done(); - return; - } - base::ReadOnlySharedMemoryMapping mapping = data.Map(); - if (!mapping.IsValid()) { - DLOG(ERROR) << "Shared memory mapping failed."; - return; - } - if (mapping.size() < - media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) { - DLOG(ERROR) << "Shared memory size was less than expected."; - return; - } - if (!info->color_space) { - DLOG(ERROR) << "Missing mandatory color space info."; - return; - } - - if (!got_first_frame_) { - UMA_HISTOGRAM_TIMES("Tab.Preview.TimeToFirstUsableFrameAfterStartCapture", - time_of_call - start_video_capture_time_); - got_first_frame_ = true; - } - - // The SkBitmap's pixels will be marked as immutable, but the installPixels() - // API requires a non-const pointer. So, cast away the const. - void* const pixels = const_cast<void*>(mapping.memory()); - - // Call installPixels() with a |releaseProc| that: 1) notifies the capturer - // that this consumer has finished with the frame, and 2) releases the shared - // memory mapping. - struct FramePinner { - // Keeps the shared memory that backs |frame_| mapped. - base::ReadOnlySharedMemoryMapping mapping; - // Prevents FrameSinkVideoCapturer from recycling the shared memory that - // backs |frame_|. - mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> - releaser; - }; - - // Subtract back out the scroll bars if we decided there was enough canvas to - // account for them and still have a decent preview image. - const float scale_ratio = float{content_rect.width()} / - float{last_frame_capture_info_.copy_rect.width()}; - - const gfx::Insets original_scroll_insets = - last_frame_capture_info_.scrollbar_insets; - const gfx::Insets scroll_insets( - 0, 0, std::round(original_scroll_insets.width() * scale_ratio), - std::round(original_scroll_insets.height() * scale_ratio)); - gfx::Rect effective_content_rect = content_rect; - effective_content_rect.Inset(scroll_insets); - - const gfx::Size bitmap_size(content_rect.right(), content_rect.bottom()); - SkBitmap frame; - frame.installPixels( - SkImageInfo::MakeN32(bitmap_size.width(), bitmap_size.height(), - kPremul_SkAlphaType, - info->color_space->ToSkColorSpace()), - pixels, - media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane, - info->pixel_format, info->coded_size.width()), - [](void* addr, void* context) { - delete static_cast<FramePinner*>(context); - }, - new FramePinner{std::move(mapping), callbacks_remote.Unbind()}); - frame.setImmutable(); - - SkBitmap cropped_frame; - if (frame.extractSubset(&cropped_frame, - gfx::RectToSkIRect(effective_content_rect))) { - UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( - "Tab.Preview.TimeToStoreAfterFrameReceived", - base::TimeTicks::Now() - time_of_call, - base::TimeDelta::FromMicroseconds(10), - base::TimeDelta::FromMilliseconds(10), 50); - StoreThumbnail(CaptureType::kVideoFrame, cropped_frame); - } -} - -void ThumbnailTabHelper::OnStopped() {} - // static -ThumbnailTabHelper::ThumbnailCaptureInfo -ThumbnailTabHelper::GetInitialCaptureInfo(const gfx::Size& source_size, - float scale_factor, - bool include_scrollbars_in_capture) { +ThumbnailCaptureInfo ThumbnailTabHelper::GetInitialCaptureInfo( + const gfx::Size& source_size, + float scale_factor, + bool include_scrollbars_in_capture) { ThumbnailCaptureInfo capture_info; capture_info.source_size = source_size;
diff --git a/chrome/browser/ui/thumbnails/thumbnail_tab_helper.h b/chrome/browser/ui/thumbnails/thumbnail_tab_helper.h index cc143c9..15bd628 100644 --- a/chrome/browser/ui/thumbnails/thumbnail_tab_helper.h +++ b/chrome/browser/ui/thumbnails/thumbnail_tab_helper.h
@@ -11,18 +11,18 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/time/time.h" +#include "chrome/browser/ui/thumbnails/thumbnail_capture_info.h" #include "chrome/browser/ui/thumbnails/thumbnail_image.h" -#include "components/viz/host/client_frame_sink_video_capturer.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "mojo/public/cpp/bindings/pending_remote.h" +class BackgroundThumbnailCapturer; class ThumbnailScheduler; class ThumbnailTabHelper - : public content::WebContentsUserData<ThumbnailTabHelper>, - public viz::mojom::FrameSinkVideoConsumer { + : public content::WebContentsUserData<ThumbnailTabHelper> { public: ~ThumbnailTabHelper() override; @@ -36,23 +36,6 @@ enum class CaptureType; static void RecordCaptureType(CaptureType type); - // Describes how a thumbnail bitmap should be generated from a target surface. - // All sizes are in pixels, not DIPs. - struct ThumbnailCaptureInfo { - // The total source size (including scrollbars). - gfx::Size source_size; - - // Insets for scrollbars in the source image that should probably be - // ignored for thumbnailing purposes. - gfx::Insets scrollbar_insets; - - // Cropping rectangle for the source canvas, in pixels. - gfx::Rect copy_rect; - - // Size of the target bitmap in pixels. - gfx::Size target_size; - }; - explicit ThumbnailTabHelper(content::WebContents* contents); static ThumbnailScheduler& GetScheduler(); @@ -70,14 +53,6 @@ void StoreThumbnail(CaptureType type, const SkBitmap& bitmap); // viz::mojom::FrameSinkVideoConsumer: - void OnFrameCaptured( - base::ReadOnlySharedMemoryRegion data, - ::media::mojom::VideoFrameInfoPtr info, - const gfx::Rect& content_rect, - mojo::PendingRemote<::viz::mojom::FrameSinkVideoConsumerFrameCallbacks> - callbacks) override; - void OnStopped() override; - void OnLog(const std::string& /*message*/) override {} // Returns the dimensions of the multipurpose thumbnail that should be // captured from an entire webpage. Can be cropped or compressed later. @@ -93,13 +68,11 @@ // Copy info from the most recent frame we have captured. ThumbnailCaptureInfo last_frame_capture_info_; - // Captures frames from the WebContents while it's hidden. The capturer count - // of the WebContents is incremented/decremented when a capturer is set/unset. - std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_; - // Private implementation of state tracking. std::unique_ptr<TabStateTracker> state_; + std::unique_ptr<BackgroundThumbnailCapturer> background_capturer_; + // Times for computing metrics. base::TimeTicks start_video_capture_time_;
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views.cc b/chrome/browser/ui/views/overlay/overlay_window_views.cc index fc55e78..91b864a0 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views.cc +++ b/chrome/browser/ui/views/overlay/overlay_window_views.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/numerics/safe_conversions.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" @@ -56,6 +57,9 @@ #endif namespace { + +// Lower bound size of the window is a fixed value to allow for minimal sizes +// on UI affordances, such as buttons. constexpr gfx::Size kMinWindowSize(260, 146); constexpr int kOverlayBorderThickness = 10; @@ -252,6 +256,7 @@ OverlayWindowViews::OverlayWindowViews( content::PictureInPictureWindowController* controller) : controller_(controller), + min_size_(kMinWindowSize), hide_controls_timer_( FROM_HERE, base::TimeDelta::FromMilliseconds(2500), @@ -269,10 +274,6 @@ UpdateMaxSize(work_area); - // Lower bound size of the window is a fixed value to allow for minimal sizes - // on UI affordances, such as buttons. - min_size_ = kMinWindowSize; - gfx::Size window_size = window_bounds_.size(); if (!has_been_shown_) { window_size = gfx::Size(work_area.width() / 5, work_area.height() / 5); @@ -309,7 +310,6 @@ // Update the window size to adhere to the aspect ratio. gfx::Size min_size = min_size_; gfx::Size max_size = max_size_; - gfx::SizeMinMaxToAspectRatio(aspect_ratio, &min_size, &max_size); gfx::Rect window_rect(GetBounds().origin(), window_size); gfx::SizeRectToAspectRatio(resize_edge, aspect_ratio, min_size, max_size, &window_rect); @@ -510,12 +510,22 @@ if (letterbox_region.IsEmpty()) return; - // To avoid one-pixel black line in the window when floated aspect ratio is - // not perfect (e.g. 848x480 for 16:9 video), letterbox region size is the - // same as window size. - if ((std::abs(window_size.width() - letterbox_region.width()) <= 1) && - (std::abs(window_size.height() - letterbox_region.height()) <= 1)) { - letterbox_region.set_size(window_size); + // To avoid black stripes in the window when integer window dimensions don't + // correspond to the video aspect ratio exactly (e.g. 854x480 for 16:9 + // video) force the letterbox region size to be equal to the window size. + const float aspect_ratio = + static_cast<float>(natural_size_.width()) / natural_size_.height(); + if (aspect_ratio > 1 && window_size.height() == letterbox_region.height()) { + const int height_from_width = + base::ClampRound(window_size.width() / aspect_ratio); + if (height_from_width == window_size.height()) + letterbox_region.set_width(window_size.width()); + } else if (aspect_ratio <= 1 && + window_size.width() == letterbox_region.width()) { + const int width_from_height = + base::ClampRound(window_size.height() * aspect_ratio); + if (width_from_height == window_size.width()) + letterbox_region.set_height(window_size.height()); } gfx::Size letterbox_size = letterbox_region.size(); @@ -1053,6 +1063,11 @@ } void OverlayWindowViews::UpdateMaxSize(const gfx::Rect& work_area) { + // An empty |work_area| is not valid, but it is sometimes reported as a + // transient value. + if (work_area.IsEmpty()) + return; + max_size_ = gfx::Size(work_area.width() / 2, work_area.height() / 2); if (!native_widget())
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views.h b/chrome/browser/ui/views/overlay/overlay_window_views.h index 315698a..96fe145 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views.h +++ b/chrome/browser/ui/views/overlay/overlay_window_views.h
@@ -95,6 +95,10 @@ ui::Layer* video_layer_for_testing() const; cc::Layer* GetLayerForTesting() override; + void set_minimum_size_for_testing(const gfx::Size& min_size) { + min_size_ = min_size; + } + private: explicit OverlayWindowViews( content::PictureInPictureWindowController* controller); @@ -104,8 +108,7 @@ // Determine the intended bounds of |this|. This should be called when there // is reason for the bounds to change, such as switching primary displays or - // playing a new video (i.e. different aspect ratio). This also updates - // |min_size_| and |max_size_|. + // playing a new video (i.e. different aspect ratio). gfx::Rect CalculateAndUpdateWindowBounds(); // Set up the views::Views that will be shown on the window.
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views_unittest.cc b/chrome/browser/ui/views/overlay/overlay_window_views_unittest.cc index 0daeb03..0b5d15b4 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views_unittest.cc +++ b/chrome/browser/ui/views/overlay/overlay_window_views_unittest.cc
@@ -80,6 +80,7 @@ SetDisplayWorkArea({0, 0, 1000, 1000}); overlay_window_ = OverlayWindowViews::Create(&pip_window_controller_); + overlay_window_->set_minimum_size_for_testing({200, 100}); } void TearDown() override { @@ -107,6 +108,143 @@ std::unique_ptr<OverlayWindowViews> overlay_window_; }; +TEST_F(OverlayWindowViewsTest, InitialWindowSize_Square) { + // Fit the window taking 1/5 (both dimensions) of the work area as the + // starting size, and applying the size and aspect ratio constraints. + overlay_window().UpdateVideoSize({400, 400}); + EXPECT_EQ(gfx::Size(200, 200), overlay_window().GetBounds().size()); + EXPECT_EQ(gfx::Size(200, 200), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, InitialWindowSize_Horizontal) { + // Fit the window taking 1/5 (both dimensions) of the work area as the + // starting size, and applying the size and aspect ratio constraints. + overlay_window().UpdateVideoSize({400, 200}); + EXPECT_EQ(gfx::Size(400, 200), overlay_window().GetBounds().size()); + EXPECT_EQ(gfx::Size(400, 200), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, InitialWindowSize_Vertical) { + // Fit the window taking 1/5 (both dimensions) of the work area as the + // starting size, and applying the size and aspect ratio constraints. + overlay_window().UpdateVideoSize({400, 500}); + EXPECT_EQ(gfx::Size(200, 250), overlay_window().GetBounds().size()); + EXPECT_EQ(gfx::Size(200, 250), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, Letterboxing) { + overlay_window().UpdateVideoSize({400, 10}); + + // Must fit within the minimum height of 146. But with the aspect ratio of + // 40:1 the width gets exceedingly big and must be limited to the maximum of + // 500. Thus, letterboxing is unavoidable. + EXPECT_EQ(gfx::Size(500, 100), overlay_window().GetBounds().size()); + EXPECT_EQ(gfx::Size(500, 13), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, Pillarboxing) { + overlay_window().UpdateVideoSize({10, 400}); + + // Must fit within the minimum width of 260. But with the aspect ratio of + // 1:40 the height gets exceedingly big and must be limited to the maximum of + // 500. Thus, pillarboxing is unavoidable. + EXPECT_EQ(gfx::Size(200, 500), overlay_window().GetBounds().size()); + EXPECT_EQ(gfx::Size(13, 500), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, Pillarboxing_Square) { + overlay_window().UpdateVideoSize({100, 100}); + + // Pillarboxing also occurs on Linux even with the square aspect ratio, + // because the user is allowed to size the window to the rectangular minimum + // size. + overlay_window().SetSize({200, 100}); + EXPECT_EQ(gfx::Size(100, 100), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, ApproximateAspectRatio_Horizontal) { + // "Horizontal" video. + overlay_window().UpdateVideoSize({320, 240}); + + // The user drags the window resizer horizontally and now the integer window + // dimensions can't reproduce the video aspect ratio exactly. The video + // should still fill the entire window area. + overlay_window().SetSize({320, 240}); + EXPECT_EQ(gfx::Size(320, 240), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({321, 241}); + EXPECT_EQ(gfx::Size(321, 241), + overlay_window().video_layer_for_testing()->size()); + + // Wide video. + overlay_window().UpdateVideoSize({1600, 900}); + + overlay_window().SetSize({444, 250}); + EXPECT_EQ(gfx::Size(444, 250), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({445, 250}); + EXPECT_EQ(gfx::Size(445, 250), + overlay_window().video_layer_for_testing()->size()); + + // Very wide video. + overlay_window().UpdateVideoSize({400, 100}); + + overlay_window().SetSize({478, 120}); + EXPECT_EQ(gfx::Size(478, 120), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({481, 120}); + EXPECT_EQ(gfx::Size(481, 120), + overlay_window().video_layer_for_testing()->size()); +} + +TEST_F(OverlayWindowViewsTest, ApproximateAspectRatio_Vertical) { + // "Vertical" video. + overlay_window().UpdateVideoSize({240, 320}); + + // The user dragged the window resizer vertically and now the integer window + // dimensions can't reproduce the video aspect ratio exactly. The video + // should still fill the entire window area. + overlay_window().SetSize({240, 320}); + EXPECT_EQ(gfx::Size(240, 320), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({239, 319}); + EXPECT_EQ(gfx::Size(239, 319), + overlay_window().video_layer_for_testing()->size()); + + // Narrow video. + overlay_window().UpdateVideoSize({900, 1600}); + + overlay_window().SetSize({250, 444}); + EXPECT_EQ(gfx::Size(250, 444), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({250, 445}); + EXPECT_EQ(gfx::Size(250, 445), + overlay_window().video_layer_for_testing()->size()); + + // Very narrow video. + // NOTE: Window width is bounded by the minimum size. + overlay_window().UpdateVideoSize({100, 400}); + + overlay_window().SetSize({200, 478}); + EXPECT_EQ(gfx::Size(120, 478), + overlay_window().video_layer_for_testing()->size()); + + overlay_window().SetSize({200, 481}); + EXPECT_EQ(gfx::Size(120, 481), + overlay_window().video_layer_for_testing()->size()); +} + TEST_F(OverlayWindowViewsTest, UpdateMaximumSize) { SetDisplayWorkArea({0, 0, 4000, 4000}); @@ -130,3 +268,11 @@ EXPECT_EQ(gfx::Size(500, 500), overlay_window().GetBounds().size()); EXPECT_EQ(gfx::Size(500, 500), overlay_window().GetMaximumSize()); } + +TEST_F(OverlayWindowViewsTest, IgnoreInvalidMaximumSize) { + ASSERT_EQ(gfx::Size(500, 500), overlay_window().GetMaximumSize()); + + SetDisplayWorkArea({0, 0, 0, 0}); + overlay_window().OnNativeWidgetMove(); + EXPECT_EQ(gfx::Size(500, 500), overlay_window().GetMaximumSize()); +}
diff --git a/chrome/browser/ui/views/profiles/profile_menu_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_menu_view_browsertest.cc index aede51f..1750010 100644 --- a/chrome/browser/ui/views/profiles/profile_menu_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_menu_view_browsertest.cc
@@ -54,7 +54,6 @@ #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/consent_level.h" #include "components/signin/public/identity_manager/identity_test_utils.h" -#include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/sync_user_settings.h" #include "components/sync/test/fake_server/fake_server_network_resources.h" @@ -718,10 +717,8 @@ sync_harness()->EnterSyncPausedStateForPrimaryAccount(); // Check that the setup was successful. ASSERT_TRUE(identity_manager()->HasPrimaryAccount()); - if (base::FeatureList::IsEnabled(switches::kStopSyncInPausedState)) { - ASSERT_EQ(syncer::SyncService::TransportState::PAUSED, - sync_service()->GetTransportState()); - } + ASSERT_EQ(syncer::SyncService::TransportState::PAUSED, + sync_service()->GetTransportState()); RunTest(); }
diff --git a/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.cc b/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.cc new file mode 100644 index 0000000..a578b6dd --- /dev/null +++ b/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.cc
@@ -0,0 +1,110 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.h" + +#include "chrome/browser/password_manager/chrome_password_manager_client.h" +#include "chrome/browser/ui/autofill/chrome_autofill_client.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/generated_resources.h" +#include "components/web_modal/modal_dialog_host.h" +#include "components/web_modal/web_contents_modal_dialog_manager.h" +#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/size.h" +#include "ui/views/controls/webview/webview.h" +#include "ui/views/layout/fill_layout.h" +#include "ui/views/view.h" + +UserManagerProfileDialogDelegate::UserManagerProfileDialogDelegate( + UserManagerView* parent, + std::unique_ptr<views::WebView> web_view, + const GURL& url) + : parent_(parent) { + SetHasWindowSizeControls(true); + SetTitle(IDS_PROFILES_GAIA_SIGNIN_TITLE); + SetButtons(ui::DIALOG_BUTTON_NONE); + set_use_custom_frame(false); + + web_view_ = AddChildView(std::move(web_view)); + SetLayoutManager(std::make_unique<views::FillLayout>()); + + web_view_->GetWebContents()->SetDelegate(this); + + ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient( + web_view_->GetWebContents(), + autofill::ChromeAutofillClient::FromWebContents( + web_view_->GetWebContents())); + + web_modal::WebContentsModalDialogManager::CreateForWebContents( + web_view_->GetWebContents()); + web_modal::WebContentsModalDialogManager::FromWebContents( + web_view_->GetWebContents()) + ->SetDelegate(this); + + web_view_->LoadInitialURL(url); + + chrome::RecordDialogCreation(chrome::DialogIdentifier::USER_MANAGER_PROFILE); +} + +UserManagerProfileDialogDelegate::~UserManagerProfileDialogDelegate() = default; + +gfx::Size UserManagerProfileDialogDelegate::CalculatePreferredSize() const { + return gfx::Size(UserManagerProfileDialog::kDialogWidth, + UserManagerProfileDialog::kDialogHeight); +} + +void UserManagerProfileDialogDelegate::DisplayErrorMessage() { + web_view_->LoadInitialURL(GURL(chrome::kChromeUISigninErrorURL)); +} + +web_modal::WebContentsModalDialogHost* +UserManagerProfileDialogDelegate::GetWebContentsModalDialogHost() { + return this; +} + +gfx::NativeView UserManagerProfileDialogDelegate::GetHostView() const { + return GetWidget()->GetNativeView(); +} + +gfx::Point UserManagerProfileDialogDelegate::GetDialogPosition( + const gfx::Size& size) { + gfx::Size widget_size = GetWidget()->GetWindowBoundsInScreen().size(); + return gfx::Point(std::max(0, (widget_size.width() - size.width()) / 2), + std::max(0, (widget_size.height() - size.height()) / 2)); +} + +gfx::Size UserManagerProfileDialogDelegate::GetMaximumDialogSize() { + return GetWidget()->GetWindowBoundsInScreen().size(); +} + +void UserManagerProfileDialogDelegate::AddObserver( + web_modal::ModalDialogHostObserver* observer) {} + +void UserManagerProfileDialogDelegate::RemoveObserver( + web_modal::ModalDialogHostObserver* observer) {} + +ui::ModalType UserManagerProfileDialogDelegate::GetModalType() const { + return ui::MODAL_TYPE_WINDOW; +} + +void UserManagerProfileDialogDelegate::DeleteDelegate() { + OnDialogDestroyed(); + delete this; +} + +views::View* UserManagerProfileDialogDelegate::GetInitiallyFocusedView() { + return static_cast<views::View*>(web_view_); +} + +void UserManagerProfileDialogDelegate::CloseDialog() { + OnDialogDestroyed(); + GetWidget()->Close(); +} + +void UserManagerProfileDialogDelegate::OnDialogDestroyed() { + if (parent_) { + parent_->OnDialogDestroyed(); + parent_ = nullptr; + } +}
diff --git a/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.h b/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.h new file mode 100644 index 0000000..d048afc --- /dev/null +++ b/chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.h
@@ -0,0 +1,79 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PROFILES_USER_MANAGER_PROFILE_DIALOG_DELEGATE_H_ +#define CHROME_BROWSER_UI_VIEWS_PROFILES_USER_MANAGER_PROFILE_DIALOG_DELEGATE_H_ + +#include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h" +#include "chrome/browser/ui/views/profiles/user_manager_view.h" +#include "components/web_modal/web_contents_modal_dialog_host.h" +#include "ui/base/ui_base_types.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/views/window/dialog_delegate.h" + +class GURL; + +namespace views { +class WebView; +class View; +} // namespace views + +namespace gfx { +class Point; +class Size; +} // namespace gfx + +namespace web_modal { +class ModalDialogHostObserver; +} + +class UserManagerProfileDialogDelegate + : public views::DialogDelegateView, + public UserManagerProfileDialog::BaseDialogDelegate, + public ChromeWebModalDialogManagerDelegate, + public web_modal::WebContentsModalDialogHost { + public: + UserManagerProfileDialogDelegate(UserManagerView* parent, + std::unique_ptr<views::WebView> web_view, + const GURL& url); + ~UserManagerProfileDialogDelegate() override; + + UserManagerProfileDialogDelegate(const UserManagerProfileDialogDelegate&) = + delete; + UserManagerProfileDialogDelegate& operator=( + const UserManagerProfileDialogDelegate&) = delete; + + // UserManagerProfileDialog::BaseDialogDelegate + void CloseDialog() override; + + // Display the local error message inside login window. + void DisplayErrorMessage(); + + // ChromeWebModalDialogManagerDelegate + web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost() + override; + + // web_modal::WebContentsModalDialogHost + gfx::NativeView GetHostView() const override; + gfx::Point GetDialogPosition(const gfx::Size& size) override; + gfx::Size GetMaximumDialogSize() override; + void AddObserver(web_modal::ModalDialogHostObserver* observer) override; + void RemoveObserver(web_modal::ModalDialogHostObserver* observer) override; + + private: + // Before its destruction, tells its parent container to reset its reference + // to the UserManagerProfileDialogDelegate. + void OnDialogDestroyed(); + + // views::DialogDelegate: + gfx::Size CalculatePreferredSize() const override; + ui::ModalType GetModalType() const override; + void DeleteDelegate() override; + views::View* GetInitiallyFocusedView() override; + + UserManagerView* parent_; // Not owned. + views::WebView* web_view_; // Owned by the view hierarchy. +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PROFILES_USER_MANAGER_PROFILE_DIALOG_DELEGATE_H_
diff --git a/chrome/browser/ui/views/profiles/user_manager_view.cc b/chrome/browser/ui/views/profiles/user_manager_view.cc index 690641d7..97a7951 100644 --- a/chrome/browser/ui/views/profiles/user_manager_view.cc +++ b/chrome/browser/ui/views/profiles/user_manager_view.cc
@@ -10,7 +10,6 @@ #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_manager.h" @@ -20,7 +19,6 @@ #include "chrome/browser/signin/signin_promo.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/task_manager/web_contents_tags.h" -#include "chrome/browser/ui/autofill/chrome_autofill_client.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_finder.h" @@ -28,13 +26,13 @@ #include "chrome/browser/ui/profile_picker.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/user_manager.h" +#include "chrome/browser/ui/views/profiles/user_manager_profile_dialog_delegate.h" #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/guest_view/browser/guest_view_manager.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" -#include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" @@ -66,102 +64,6 @@ bool g_is_user_manager_view_under_construction = false; } // namespace -// Delegate--------------------------------------------------------------- - -UserManagerProfileDialogDelegate::UserManagerProfileDialogDelegate( - UserManagerView* parent, - views::WebView* web_view, - const std::string& email_address, - const GURL& url) - : parent_(parent), web_view_(web_view), email_address_(email_address) { - SetHasWindowSizeControls(true); - SetTitle(IDS_PROFILES_GAIA_SIGNIN_TITLE); - SetButtons(ui::DIALOG_BUTTON_NONE); - set_use_custom_frame(false); - - AddChildView(web_view_); - SetLayoutManager(std::make_unique<views::FillLayout>()); - - web_view_->GetWebContents()->SetDelegate(this); - - ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient( - web_view_->GetWebContents(), - autofill::ChromeAutofillClient::FromWebContents( - web_view_->GetWebContents())); - - web_modal::WebContentsModalDialogManager::CreateForWebContents( - web_view_->GetWebContents()); - web_modal::WebContentsModalDialogManager::FromWebContents( - web_view_->GetWebContents()) - ->SetDelegate(this); - - web_view_->LoadInitialURL(url); - - chrome::RecordDialogCreation(chrome::DialogIdentifier::USER_MANAGER_PROFILE); -} - -UserManagerProfileDialogDelegate::~UserManagerProfileDialogDelegate() {} - -gfx::Size UserManagerProfileDialogDelegate::CalculatePreferredSize() const { - return gfx::Size(UserManagerProfileDialog::kDialogWidth, - UserManagerProfileDialog::kDialogHeight); -} - -void UserManagerProfileDialogDelegate::DisplayErrorMessage() { - web_view_->LoadInitialURL(GURL(chrome::kChromeUISigninErrorURL)); -} - -web_modal::WebContentsModalDialogHost* -UserManagerProfileDialogDelegate::GetWebContentsModalDialogHost() { - return this; -} - -gfx::NativeView UserManagerProfileDialogDelegate::GetHostView() const { - return GetWidget()->GetNativeView(); -} - -gfx::Point UserManagerProfileDialogDelegate::GetDialogPosition( - const gfx::Size& size) { - gfx::Size widget_size = GetWidget()->GetWindowBoundsInScreen().size(); - return gfx::Point(std::max(0, (widget_size.width() - size.width()) / 2), - std::max(0, (widget_size.height() - size.height()) / 2)); -} - -gfx::Size UserManagerProfileDialogDelegate::GetMaximumDialogSize() { - return GetWidget()->GetWindowBoundsInScreen().size(); -} - -void UserManagerProfileDialogDelegate::AddObserver( - web_modal::ModalDialogHostObserver* observer) {} - -void UserManagerProfileDialogDelegate::RemoveObserver( - web_modal::ModalDialogHostObserver* observer) {} - -ui::ModalType UserManagerProfileDialogDelegate::GetModalType() const { - return ui::MODAL_TYPE_WINDOW; -} - -void UserManagerProfileDialogDelegate::DeleteDelegate() { - OnDialogDestroyed(); - delete this; -} - -views::View* UserManagerProfileDialogDelegate::GetInitiallyFocusedView() { - return static_cast<views::View*>(web_view_); -} - -void UserManagerProfileDialogDelegate::CloseDialog() { - OnDialogDestroyed(); - GetWidget()->Close(); -} - -void UserManagerProfileDialogDelegate::OnDialogDestroyed() { - if (parent_) { - parent_->OnDialogDestroyed(); - parent_ = nullptr; - } -} - // UserManager ----------------------------------------------------------------- // static @@ -385,7 +287,7 @@ // The dialog delegate will be deleted when the widget closes. The created // WebView's lifetime is managed by the delegate. delegate_ = new UserManagerProfileDialogDelegate( - this, new views::WebView(browser_context), email, url); + this, std::make_unique<views::WebView>(browser_context), url); gfx::NativeView parent = g_user_manager_view->GetWidget()->GetNativeView(); views::DialogDelegate::CreateDialogWidget(delegate_, nullptr, parent); delegate_->GetWidget()->Show();
diff --git a/chrome/browser/ui/views/profiles/user_manager_view.h b/chrome/browser/ui/views/profiles/user_manager_view.h index e8ecfa148..2ca1ebf 100644 --- a/chrome/browser/ui/views/profiles/user_manager_view.h +++ b/chrome/browser/ui/views/profiles/user_manager_view.h
@@ -12,64 +12,14 @@ #include "base/macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_window.h" -#include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h" #include "chrome/browser/ui/user_manager.h" #include "components/signin/public/base/signin_metrics.h" -#include "components/web_modal/web_contents_modal_dialog_host.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/window/dialog_delegate.h" class ScopedKeepAlive; class UserManagerView; - -class UserManagerProfileDialogDelegate - : public views::DialogDelegateView, - public UserManagerProfileDialog::BaseDialogDelegate, - public ChromeWebModalDialogManagerDelegate, - public web_modal::WebContentsModalDialogHost { - public: - UserManagerProfileDialogDelegate(UserManagerView* parent, - views::WebView* web_view, - const std::string& email_address, - const GURL& url); - ~UserManagerProfileDialogDelegate() override; - - // UserManagerProfileDialog::BaseDialogDelegate - void CloseDialog() override; - - // Display the local error message inside login window. - void DisplayErrorMessage(); - - // ChromeWebModalDialogManagerDelegate - web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost() - override; - - // web_modal::WebContentsModalDialogHost - gfx::NativeView GetHostView() const override; - gfx::Point GetDialogPosition(const gfx::Size& size) override; - gfx::Size GetMaximumDialogSize() override; - void AddObserver(web_modal::ModalDialogHostObserver* observer) override; - void RemoveObserver(web_modal::ModalDialogHostObserver* observer) override; - - private: - UserManagerProfileDialogDelegate(); - - // Before its destruction, tells its parent container to reset its reference - // to the UserManagerProfileDialogDelegate. - void OnDialogDestroyed(); - - // views::DialogDelegate: - gfx::Size CalculatePreferredSize() const override; - ui::ModalType GetModalType() const override; - void DeleteDelegate() override; - views::View* GetInitiallyFocusedView() override; - - UserManagerView* parent_; // Not owned. - views::WebView* web_view_; - const std::string email_address_; - - DISALLOW_COPY_AND_ASSIGN(UserManagerProfileDialogDelegate); -}; +class UserManagerProfileDialogDelegate; namespace views { class WebView;
diff --git a/chrome/browser/ui/views/tabs/new_tab_button.cc b/chrome/browser/ui/views/tabs/new_tab_button.cc index deabec9..d8e2c08 100644 --- a/chrome/browser/ui/views/tabs/new_tab_button.cc +++ b/chrome/browser/ui/views/tabs/new_tab_button.cc
@@ -132,8 +132,12 @@ bool destroyed = false; destroyed_ = &destroyed; views::ShowSystemMenuAtScreenPixelLocation(views::HWNDForView(this), point); - if (!destroyed) + if (!destroyed) { SetState(views::Button::STATE_NORMAL); + // Zero this pointer to avoid dangling references to the local that will + // soon go out of scope. Only do this if the object was not destroyed. + destroyed_ = nullptr; + } } #endif
diff --git a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.cc b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.cc index 44f3121..8de5e56 100644 --- a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.cc +++ b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.cc
@@ -7,7 +7,7 @@ #include "chrome/browser/about_flags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/lifetime/application_lifetime.h" -#include "chrome/browser/ui/webui/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include "chrome/grit/generated_resources.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "ui/gfx/color_palette.h" @@ -104,10 +104,12 @@ for (const auto& lab : all_labs) { const flags_ui::FeatureEntry* entry = flags_state_->FindFeatureEntryByName(lab.internal_name); - DCHECK_EQ(entry->type, flags_ui::FeatureEntry::FEATURE_VALUE); - int default_index = GetIndexOfEnabledLabState(entry); - menu_item_container_->AddChildView( - CreateLabItem(lab, default_index, entry)); + if (IsFeatureSupportedOnPlatform(entry)) { + DCHECK_EQ(entry->type, flags_ui::FeatureEntry::FEATURE_VALUE); + int default_index = GetIndexOfEnabledLabState(entry); + menu_item_container_->AddChildView( + CreateLabItem(lab, default_index, entry)); + } } // TODO(elainechien): Build UI for 0 experiments case. DCHECK(menu_item_container_->children().size() >= 1); @@ -161,6 +163,14 @@ g_chrome_labs_bubble->SizeToContents(); } +// TODO(elainechien): ChromeOS specific logic for owner access only flags. +// static +bool ChromeLabsBubbleView::IsFeatureSupportedOnPlatform( + const flags_ui::FeatureEntry* entry) { + return (entry && (entry->supported_platforms & + flags_ui::FlagsState::GetCurrentPlatform()) != 0); +} + ChromeLabsBubbleView::~ChromeLabsBubbleView() { g_chrome_labs_bubble = nullptr; }
diff --git a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.h b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.h index a2e1405f..a9f9b4cc 100644 --- a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.h +++ b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view.h
@@ -26,6 +26,9 @@ ~ChromeLabsBubbleView() override; + // This function is exposed for testing. + static bool IsFeatureSupportedOnPlatform(const flags_ui::FeatureEntry* entry); + // Getter functions for testing. static ChromeLabsBubbleView* GetChromeLabsBubbleViewForTesting(); flags_ui::FlagsState* GetFlagsStateForTesting();
diff --git a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view_unittest.cc b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view_unittest.cc index 4152591..1d24843 100644 --- a/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/toolbar/chrome_labs_bubble_view_unittest.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/ui/views/frame/test_with_browser_view.h" #include "chrome/browser/ui/views/toolbar/chrome_labs_button.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "components/flags_ui/feature_entry_macros.h" #include "components/flags_ui/flags_state.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/test/combobox_test_api.h" @@ -162,3 +163,26 @@ lab_item_combobox->SetSelectedRow(0); EXPECT_FALSE(bubble_view->IsRestartPromptVisibleForTesting()); } + +// This test checks that IsFeatureSupportedOnPlatform correctly returns whether +// a feature is supported on a platform. +TEST_F(ChromeLabsBubbleTest, IsFeatureSupportedOnPlatformTest) { + const base::Feature kTestFeature1{"FeatureName1", + base::FEATURE_DISABLED_BY_DEFAULT}; + int os_other_than_current = 1; + while (os_other_than_current == flags_ui::FlagsState::GetCurrentPlatform()) + os_other_than_current <<= 1; + flags_ui::FeatureEntry feature_entry_unsupported{ + "flag1", "", "", os_other_than_current, + FEATURE_VALUE_TYPE(kTestFeature1)}; + EXPECT_FALSE(ChromeLabsBubbleView::IsFeatureSupportedOnPlatform( + &feature_entry_unsupported)); + + const base::Feature kTestFeature2{"FeatureName2", + base::FEATURE_DISABLED_BY_DEFAULT}; + flags_ui::FeatureEntry feature_entry_supported{ + "flag2", "", "", flags_ui::FlagsState::GetCurrentPlatform(), + FEATURE_VALUE_TYPE(kTestFeature2)}; + EXPECT_TRUE(ChromeLabsBubbleView::IsFeatureSupportedOnPlatform( + &feature_entry_supported)); +}
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 354ed84f..968ab1f 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -44,13 +44,13 @@ #include "chrome/browser/ui/webui/domain_reliability_internals_ui.h" #include "chrome/browser/ui/webui/download_internals/download_internals_ui.h" #include "chrome/browser/ui/webui/engagement/site_engagement_ui.h" -#include "chrome/browser/ui/webui/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include "chrome/browser/ui/webui/gcm_internals_ui.h" #include "chrome/browser/ui/webui/identity_internals_ui.h" #include "chrome/browser/ui/webui/internals/internals_ui.h" #include "chrome/browser/ui/webui/interstitials/interstitial_ui.h" #include "chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h" -#include "chrome/browser/ui/webui/invalidations_ui.h" +#include "chrome/browser/ui/webui/invalidations/invalidations_ui.h" #include "chrome/browser/ui/webui/local_state/local_state_ui.h" #include "chrome/browser/ui/webui/log_web_ui_url.h" #include "chrome/browser/ui/webui/media/media_engagement_ui.h" @@ -72,7 +72,7 @@ #include "chrome/browser/ui/webui/translate_internals/translate_internals_ui.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals_ui.h" #include "chrome/browser/ui/webui/user_actions/user_actions_ui.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/browser/web_applications/system_web_app_manager.h" #include "chrome/common/buildflags.h" #include "chrome/common/chrome_features.h" @@ -124,7 +124,7 @@ #include "chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.h" #include "chrome/browser/ui/webui/feed_internals/feed_internals_ui.h" #include "chrome/browser/ui/webui/offline/offline_internals_ui.h" -#include "chrome/browser/ui/webui/webapks_ui.h" +#include "chrome/browser/ui/webui/webapks/webapks_ui.h" #include "components/feed/buildflags.h" #include "components/feed/feed_feature_list.h" #else // defined(OS_ANDROID) @@ -886,8 +886,10 @@ #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(media::kKaleidoscope)) { - if (url.host_piece() == kKaleidoscopeUIHost) + if (url.host_piece() == kKaleidoscopeUIHost || + url.host_piece() == kKaleidoscopeUIWatchHost) { return &NewWebUI<KaleidoscopeUI>; + } } #endif // !defined(OS_ANDROID) #if BUILDFLAG(ENABLE_NACL)
diff --git a/chrome/browser/ui/webui/flags_ui.cc b/chrome/browser/ui/webui/flags/flags_ui.cc similarity index 98% rename from chrome/browser/ui/webui/flags_ui.cc rename to chrome/browser/ui/webui/flags/flags_ui.cc index 698c5c6..1686aa9 100644 --- a/chrome/browser/ui/webui/flags_ui.cc +++ b/chrome/browser/ui/webui/flags/flags_ui.cc
@@ -2,7 +2,7 @@ // 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/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include <memory> #include <string> @@ -17,7 +17,7 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/flags_ui_handler.h" +#include "chrome/browser/ui/webui/flags/flags_ui_handler.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/flags_ui/flags_ui_constants.h" @@ -255,12 +255,11 @@ content::WebUIDataSource::Add(profile, source); } -FlagsUI::~FlagsUI() { -} +FlagsUI::~FlagsUI() {} // static base::RefCountedMemory* FlagsUI::GetFaviconResourceBytes( - ui::ScaleFactor scale_factor) { + ui::ScaleFactor scale_factor) { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( IDR_FLAGS_FAVICON, scale_factor); }
diff --git a/chrome/browser/ui/webui/flags_ui.h b/chrome/browser/ui/webui/flags/flags_ui.h similarity index 89% rename from chrome/browser/ui/webui/flags_ui.h rename to chrome/browser/ui/webui/flags/flags_ui.h index 98bd808..148e7d6 100644 --- a/chrome/browser/ui/webui/flags_ui.h +++ b/chrome/browser/ui/webui/flags/flags_ui.h
@@ -2,8 +2,8 @@ // 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_FLAGS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_FLAGS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -52,4 +52,4 @@ DISALLOW_COPY_AND_ASSIGN(FlagsDeprecatedUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_FLAGS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_H_
diff --git a/chrome/browser/ui/webui/flags_ui_handler.cc b/chrome/browser/ui/webui/flags/flags_ui_handler.cc similarity index 98% rename from chrome/browser/ui/webui/flags_ui_handler.cc rename to chrome/browser/ui/webui/flags/flags_ui_handler.cc index ce70adf..0549859b 100644 --- a/chrome/browser/ui/webui/flags_ui_handler.cc +++ b/chrome/browser/ui/webui/flags/flags_ui_handler.cc
@@ -2,7 +2,7 @@ // 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/flags_ui_handler.h" +#include "chrome/browser/ui/webui/flags/flags_ui_handler.h" #include "base/bind.h" #include "build/chromeos_buildflags.h"
diff --git a/chrome/browser/ui/webui/flags_ui_handler.h b/chrome/browser/ui/webui/flags/flags_ui_handler.h similarity index 89% rename from chrome/browser/ui/webui/flags_ui_handler.h rename to chrome/browser/ui/webui/flags/flags_ui_handler.h index f76e284..743a601 100644 --- a/chrome/browser/ui/webui/flags_ui_handler.h +++ b/chrome/browser/ui/webui/flags/flags_ui_handler.h
@@ -2,15 +2,15 @@ // 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/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include "build/build_config.h" #include "components/flags_ui/feature_entry.h" #include "components/flags_ui/flags_state.h" #include "content/public/browser/web_ui_message_handler.h" -#ifndef CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_HANDLER_H_ namespace flags_ui { class FlagsStorage; @@ -59,4 +59,4 @@ DISALLOW_COPY_AND_ASSIGN(FlagsUIHandler); }; -#endif // CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_FLAGS_FLAGS_UI_HANDLER_H_
diff --git a/chrome/browser/ui/webui/flags_ui_unittest.cc b/chrome/browser/ui/webui/flags/flags_ui_unittest.cc similarity index 96% rename from chrome/browser/ui/webui/flags_ui_unittest.cc rename to chrome/browser/ui/webui/flags/flags_ui_unittest.cc index 59c33e0..ebdc04d 100644 --- a/chrome/browser/ui/webui/flags_ui_unittest.cc +++ b/chrome/browser/ui/webui/flags/flags_ui_unittest.cc
@@ -2,7 +2,7 @@ // 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/flags_ui.h" +#include "chrome/browser/ui/webui/flags/flags_ui.h" #include "base/values.h" #include "content/public/test/browser_task_environment.h"
diff --git a/chrome/browser/ui/webui/invalidations_message_handler.cc b/chrome/browser/ui/webui/invalidations/invalidations_message_handler.cc similarity index 96% rename from chrome/browser/ui/webui/invalidations_message_handler.cc rename to chrome/browser/ui/webui/invalidations/invalidations_message_handler.cc index e4843d06..9987d42a 100644 --- a/chrome/browser/ui/webui/invalidations_message_handler.cc +++ b/chrome/browser/ui/webui/invalidations/invalidations_message_handler.cc
@@ -2,7 +2,7 @@ // 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/invalidations_message_handler.h" +#include "chrome/browser/ui/webui/invalidations/invalidations_message_handler.h" #include <utility> @@ -21,7 +21,6 @@ class InvalidationLogger; } // namespace invalidation - namespace { invalidation::ProfileInvalidationProvider* GetInvalidationProvider( @@ -54,8 +53,8 @@ invalidation::ProfileInvalidationProvider* invalidation_provider = GetInvalidationProvider(Profile::FromWebUI(web_ui())); if (invalidation_provider) { - logger_ = invalidation_provider->GetInvalidationService()-> - GetInvalidationLogger(); + logger_ = invalidation_provider->GetInvalidationService() + ->GetInvalidationLogger(); } if (logger_ && !logger_->IsObserverRegistered(this)) logger_->RegisterObserver(this);
diff --git a/chrome/browser/ui/webui/invalidations_message_handler.h b/chrome/browser/ui/webui/invalidations/invalidations_message_handler.h similarity index 90% rename from chrome/browser/ui/webui/invalidations_message_handler.h rename to chrome/browser/ui/webui/invalidations/invalidations_message_handler.h index c51938f..b4d9b7c 100644 --- a/chrome/browser/ui/webui/invalidations_message_handler.h +++ b/chrome/browser/ui/webui/invalidations/invalidations_message_handler.h
@@ -2,8 +2,8 @@ // 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_INVALIDATIONS_MESSAGE_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_MESSAGE_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_MESSAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_MESSAGE_HANDLER_H_ #include <memory> @@ -62,4 +62,4 @@ DISALLOW_COPY_AND_ASSIGN(InvalidationsMessageHandler); }; -#endif // CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_MESSAGE_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_MESSAGE_HANDLER_H_
diff --git a/chrome/browser/ui/webui/invalidations_ui.cc b/chrome/browser/ui/webui/invalidations/invalidations_ui.cc similarity index 89% rename from chrome/browser/ui/webui/invalidations_ui.cc rename to chrome/browser/ui/webui/invalidations/invalidations_ui.cc index b7114777..d76c0a0e 100644 --- a/chrome/browser/ui/webui/invalidations_ui.cc +++ b/chrome/browser/ui/webui/invalidations/invalidations_ui.cc
@@ -2,12 +2,12 @@ // 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/invalidations_ui.h" +#include "chrome/browser/ui/webui/invalidations/invalidations_ui.h" #include <memory> #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/invalidations_message_handler.h" +#include "chrome/browser/ui/webui/invalidations/invalidations_message_handler.h" #include "chrome/common/url_constants.h" #include "chrome/grit/invalidations_resources.h" #include "content/public/browser/web_ui.h" @@ -40,4 +40,4 @@ } } -InvalidationsUI::~InvalidationsUI() { } +InvalidationsUI::~InvalidationsUI() {}
diff --git a/chrome/browser/ui/webui/invalidations_ui.h b/chrome/browser/ui/webui/invalidations/invalidations_ui.h similarity index 71% rename from chrome/browser/ui/webui/invalidations_ui.h rename to chrome/browser/ui/webui/invalidations/invalidations_ui.h index f4a9cf4..83176b4 100644 --- a/chrome/browser/ui/webui/invalidations_ui.h +++ b/chrome/browser/ui/webui/invalidations/invalidations_ui.h
@@ -2,8 +2,8 @@ // 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_INVALIDATIONS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui_controller.h" @@ -18,4 +18,4 @@ DISALLOW_COPY_AND_ASSIGN(InvalidationsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_UI_H_
diff --git a/chrome/browser/ui/webui/nearby_share/shared_resources.cc b/chrome/browser/ui/webui/nearby_share/shared_resources.cc index e803f28..99f06715 100644 --- a/chrome/browser/ui/webui/nearby_share/shared_resources.cc +++ b/chrome/browser/ui/webui/nearby_share/shared_resources.cc
@@ -16,6 +16,7 @@ static constexpr webui::LocalizedString kLocalizedStrings[] = { {"nearbyShareAccountRowLabel", IDS_NEARBY_ACCOUNT_ROW_LABEL}, {"nearbyShareActionsCancel", IDS_NEARBY_ACTIONS_CANCEL}, + {"nearbyShareActionsClose", IDS_NEARBY_ACTIONS_CLOSE}, {"nearbyShareActionsConfirm", IDS_NEARBY_ACTIONS_CONFIRM}, {"nearbyShareActionsNext", IDS_NEARBY_ACTIONS_NEXT}, {"nearbyShareActionsReject", IDS_NEARBY_ACTIONS_REJECT},
diff --git a/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chrome/browser/ui/webui/omnibox/omnibox_ui.cc index 73ed2e7..5367e64e 100644 --- a/chrome/browser/ui/webui/omnibox/omnibox_ui.cc +++ b/chrome/browser/ui/webui/omnibox/omnibox_ui.cc
@@ -10,8 +10,8 @@ #include "base/feature_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/omnibox/omnibox_page_handler.h" -#include "chrome/browser/ui/webui/version_handler.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_handler.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/url_constants.h" #include "chrome/grit/omnibox_resources.h"
diff --git a/chrome/browser/ui/webui/policy_ui_handler.cc b/chrome/browser/ui/webui/policy_ui_handler.cc index ec28ccc..037e2e9 100644 --- a/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chrome/browser/ui/webui/policy_ui_handler.cc
@@ -36,7 +36,7 @@ #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_select_file_policy.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/grit/chromium_strings.h" @@ -100,7 +100,7 @@ #endif #if defined(OS_WIN) -#include "chrome/browser/ui/webui/version_util_win.h" +#include "chrome/browser/ui/webui/version/version_util_win.h" #endif #if BUILDFLAG(ENABLE_EXTENSIONS)
diff --git a/chrome/browser/ui/webui/settings/chromeos/about_section.cc b/chrome/browser/ui/webui/settings/chromeos/about_section.cc index 1e790c8b..167bc8b 100644 --- a/chrome/browser/ui/webui/settings/chromeos/about_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/about_section.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/device_name_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/common/pref_names.h"
diff --git a/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc b/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc index 7664267..dd8dfde 100644 --- a/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc
@@ -494,7 +494,18 @@ {"manageSwitchAccessSettings", IDS_SETTINGS_MANAGE_SWITCH_ACCESS_SETTINGS}, {"switchAssignmentHeading", IDS_SETTINGS_SWITCH_ASSIGNMENT_HEADING}, - {"assignSwitchSubLabel", IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL}, + {"assignSwitchSubLabel0Switches", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_0_SWITCHES}, + {"assignSwitchSubLabel1Switch", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_1_SWITCH}, + {"assignSwitchSubLabel2Switches", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_2_SWITCHES}, + {"assignSwitchSubLabel3Switches", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_3_SWITCHES}, + {"assignSwitchSubLabel4Switches", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_4_SWITCHES}, + {"assignSwitchSubLabel5OrMoreSwitches", + IDS_SETTINGS_ASSIGN_SWITCH_SUB_LABEL_5_OR_MORE_SWITCHES}, {"assignSelectSwitchLabel", IDS_SETTINGS_ASSIGN_SELECT_SWITCH_LABEL}, {"assignNextSwitchLabel", IDS_SETTINGS_ASSIGN_NEXT_SWITCH_LABEL}, {"assignPreviousSwitchLabel", IDS_SETTINGS_ASSIGN_PREVIOUS_SWITCH_LABEL},
diff --git a/chrome/browser/ui/webui/settings/chromeos/people_section.cc b/chrome/browser/ui/webui/settings/chromeos/people_section.cc index 76d7e39..c65f9d8 100644 --- a/chrome/browser/ui/webui/settings/chromeos/people_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/people_section.cc
@@ -723,7 +723,10 @@ FetchAccounts(); } - if (kerberos_credentials_manager_) { + // No Kerberos search tags are registered here if Kerberos settings are in a + // separate section. + if (kerberos_credentials_manager_ && + !chromeos::features::IsKerberosSettingsSectionEnabled()) { // Kerberos search tags are added/removed dynamically. kerberos_credentials_manager_->AddObserver(this); OnKerberosEnabledStateChanged(); @@ -761,8 +764,10 @@ } PeopleSection::~PeopleSection() { - if (kerberos_credentials_manager_) + if (kerberos_credentials_manager_ && + !chromeos::features::IsKerberosSettingsSectionEnabled()) { kerberos_credentials_manager_->RemoveObserver(this); + } if (chromeos::features::IsSplitSettingsSyncEnabled() && sync_service_) sync_service_->RemoveObserver(this); @@ -905,12 +910,16 @@ profile())); } - std::unique_ptr<chromeos::settings::KerberosAccountsHandler> - kerberos_accounts_handler = - KerberosAccountsHandler::CreateIfKerberosEnabled(profile()); - if (kerberos_accounts_handler) { - // Note that the UI is enabled only if Kerberos is enabled. - web_ui->AddMessageHandler(std::move(kerberos_accounts_handler)); + // No Kerberos handler is created/added here if Kerberos settings are in a + // separate section. + if (!chromeos::features::IsKerberosSettingsSectionEnabled()) { + std::unique_ptr<chromeos::settings::KerberosAccountsHandler> + kerberos_accounts_handler = + KerberosAccountsHandler::CreateIfKerberosEnabled(profile()); + if (kerberos_accounts_handler) { + // Note that the UI is enabled only if Kerberos is enabled. + web_ui->AddMessageHandler(std::move(kerberos_accounts_handler)); + } } }
diff --git a/chrome/browser/ui/webui/settings/safety_check_handler.cc b/chrome/browser/ui/webui/settings/safety_check_handler.cc index 00b27c9..0d00091 100644 --- a/chrome/browser/ui/webui/settings/safety_check_handler.cc +++ b/chrome/browser/ui/webui/settings/safety_check_handler.cc
@@ -18,7 +18,7 @@ #include "chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.h" #include "chrome/browser/password_manager/bulk_leak_check_service_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" @@ -652,13 +652,8 @@ base::FormatNumber(total.value())); } case PasswordsStatus::kSafe: - // TODO(crbug.com/1128904): Clean up the old code path. - if (!base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords)) { - return l10n_util::GetPluralStringFUTF16( - IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT, 0); - } - return l10n_util::GetStringUTF16( - IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE); + return l10n_util::GetPluralStringFUTF16( + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT, 0); case PasswordsStatus::kCompromisedExist: // TODO(crbug.com/1128904): Clean up the old code path. if (!base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords)) { @@ -668,22 +663,22 @@ if (weak.value() == 0) { // Only compromised passwords, no weak passwords. return l10n_util::GetPluralStringFUTF16( - IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS, + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT, compromised.value()); } else { // Both compromised and weak passwords. return l10n_util::GetStringFUTF16( IDS_CONCAT_TWO_STRINGS_WITH_COMMA, l10n_util::GetPluralStringFUTF16( - IDS_SETTINGS_SAFETY_CHECK_COMPROMISED_PASSWORDS, + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT, compromised.value()), l10n_util::GetPluralStringFUTF16( - IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS, weak.value())); + IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT, weak.value())); } case PasswordsStatus::kWeakPasswordsExist: // Only weak passwords. return l10n_util::GetPluralStringFUTF16( - IDS_SETTINGS_SAFETY_CHECK_WEAK_PASSWORDS, weak.value()); + IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT, weak.value()); case PasswordsStatus::kOffline: return l10n_util::GetStringUTF16( IDS_SETTINGS_CHECK_PASSWORDS_ERROR_OFFLINE);
diff --git a/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc b/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc index 2270f7d..157f100 100644 --- a/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
@@ -885,7 +885,7 @@ kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kSafe)); EXPECT_TRUE(event); - VerifyDisplayString(event, "No security issues found"); + VerifyDisplayString(event, "No compromised passwords found"); histogram_tester_.ExpectBucketCount( "Settings.SafetyCheck.PasswordsResult", SafetyCheckHandler::PasswordsStatus::kSafe, 1);
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index bd1d7bd0..2f6c48a 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -33,7 +33,7 @@ #include "chrome/browser/ui/webui/policy_indicator_localized_strings_provider.h" #include "chrome/browser/ui/webui/settings/reset_settings_handler.h" #include "chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h" -#include "chrome/browser/ui/webui/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_features.h" @@ -1319,6 +1319,8 @@ {"siteSettings", IDS_SETTINGS_SITE_SETTINGS}, {"siteSettingsDescription", IDS_SETTINGS_SITE_SETTINGS_DESCRIPTION}, {"clearData", IDS_SETTINGS_CLEAR_DATA}, + {"clearingData", IDS_SETTINGS_CLEARING_DATA}, + {"clearedData", IDS_SETTINGS_CLEARED_DATA}, {"clearBrowsingData", IDS_SETTINGS_CLEAR_BROWSING_DATA}, {"clearBrowsingDataDescription", IDS_SETTINGS_CLEAR_DATA_DESCRIPTION}, {"titleAndCount", IDS_SETTINGS_TITLE_AND_COUNT},
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 10e8bc6d..86bc635 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -317,6 +317,10 @@ features::kNewProfilePicker)); #endif // !BUILDFLAG(IS_CHROMEOS_ASH) + html_source->AddBoolean( + "safetyCheckWeakPasswordsEnabled", + base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords)); + AddSettingsPageUIHandler(std::make_unique<AboutHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<ResetSettingsHandler>(profile)); @@ -333,6 +337,11 @@ plural_string_handler->AddLocalizedString( "movePasswordsToAccount", IDS_SETTINGS_PASSWORD_MOVE_PASSWORDS_TO_ACCOUNT_COUNT); + plural_string_handler->AddLocalizedString( + "safetyCheckPasswordsCompromised", + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT_SHORT); + plural_string_handler->AddLocalizedString( + "safetyCheckPasswordsWeak", IDS_SETTINGS_WEAK_PASSWORDS_COUNT_SHORT); web_ui->AddMessageHandler(std::move(plural_string_handler)); // Add the metrics handler to write uma stats.
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index cd9a7a3..8837394 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc
@@ -355,6 +355,10 @@ "getAccounts", base::BindRepeating(&InlineLoginHandlerChromeOS::GetAccountsInSession, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "skipWelcomePage", + base::BindRepeating(&InlineLoginHandlerChromeOS::HandleSkipWelcomePage, + base::Unretained(this))); } void InlineLoginHandlerChromeOS::SetExtraInitParams( @@ -496,4 +500,9 @@ std::move(account_emails)); } +void InlineLoginHandlerChromeOS::HandleSkipWelcomePage( + const base::ListValue* args) { + // TODO(crbug.com/1144114): write to pref. +} + } // namespace chromeos
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h index bca1c4a0..f38ef60 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h +++ b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h
@@ -41,6 +41,7 @@ void GetAccountsInSession(const base::ListValue* args); void OnGetAccounts(const std::string& callback_id, const std::vector<::account_manager::Account>& accounts); + void HandleSkipWelcomePage(const base::ListValue* args); base::RepeatingClosure close_dialog_closure_; base::WeakPtrFactory<InlineLoginHandlerChromeOS> weak_factory_{this};
diff --git a/chrome/browser/ui/webui/signin/inline_login_ui.cc b/chrome/browser/ui/webui/signin/inline_login_ui.cc index dfdc0528..993a256 100644 --- a/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chrome/browser/ui/webui/signin/inline_login_ui.cc
@@ -188,6 +188,8 @@ IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_TITLE}, {"accountManagerDialogWelcomeBody", IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_BODY}, + {"accountManagerDialogWelcomeCheckbox", + IDS_ACCOUNT_MANAGER_DIALOG_WELCOME_CHECKBOX}, {"accountManagerErrorNoInternetTitle", IDS_ACCOUNT_MANAGER_ERROR_NO_INTERNET_TITLE}, {"accountManagerErrorNoInternetBody",
diff --git a/chrome/browser/ui/webui/signin/profile_picker_handler.cc b/chrome/browser/ui/webui/signin/profile_picker_handler.cc index 47fe176..cd48f9a 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_handler.cc +++ b/chrome/browser/ui/webui/signin/profile_picker_handler.cc
@@ -527,7 +527,7 @@ if (new_profile) { RecordProfilePickerAction(ProfilePickerAction::kLaunchNewProfile); - } else if (profile->IsGuestSession()) { + } else if (profile->IsGuestSession() || profile->IsEphemeralGuestProfile()) { RecordProfilePickerAction(ProfilePickerAction::kLaunchGuestProfile); } else { RecordProfilePickerAction(
diff --git a/chrome/browser/ui/webui/version_handler.cc b/chrome/browser/ui/webui/version/version_handler.cc similarity index 97% rename from chrome/browser/ui/webui/version_handler.cc rename to chrome/browser/ui/webui/version/version_handler.cc index 374a98da..c38ef083 100644 --- a/chrome/browser/ui/webui/version_handler.cc +++ b/chrome/browser/ui/webui/version/version_handler.cc
@@ -2,7 +2,7 @@ // 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/version_handler.h" +#include "chrome/browser/ui/webui/version/version_handler.h" #include <stddef.h> @@ -54,8 +54,7 @@ VersionHandler::VersionHandler() {} -VersionHandler::~VersionHandler() { -} +VersionHandler::~VersionHandler() {} void VersionHandler::RegisterMessages() { web_ui()->RegisterMessageCallback(
diff --git a/chrome/browser/ui/webui/version_handler.h b/chrome/browser/ui/webui/version/version_handler.h similarity index 90% rename from chrome/browser/ui/webui/version_handler.h rename to chrome/browser/ui/webui/version/version_handler.h index db208ac..8c0c75d 100644 --- a/chrome/browser/ui/webui/version_handler.h +++ b/chrome/browser/ui/webui/version/version_handler.h
@@ -2,8 +2,8 @@ // 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_VERSION_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_H_ #include <vector> @@ -48,4 +48,4 @@ DISALLOW_COPY_AND_ASSIGN(VersionHandler); }; -#endif // CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_H_
diff --git a/chrome/browser/ui/webui/version_handler_chromeos.cc b/chrome/browser/ui/webui/version/version_handler_chromeos.cc similarity index 96% rename from chrome/browser/ui/webui/version_handler_chromeos.cc rename to chrome/browser/ui/webui/version/version_handler_chromeos.cc index 869f34a..fdde9bc2 100644 --- a/chrome/browser/ui/webui/version_handler_chromeos.cc +++ b/chrome/browser/ui/webui/version/version_handler_chromeos.cc
@@ -2,7 +2,7 @@ // 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/version_handler_chromeos.h" +#include "chrome/browser/ui/webui/version/version_handler_chromeos.h" #include "base/bind.h" #include "base/task/post_task.h"
diff --git a/chrome/browser/ui/webui/version_handler_chromeos.h b/chrome/browser/ui/webui/version/version_handler_chromeos.h similarity index 77% rename from chrome/browser/ui/webui/version_handler_chromeos.h rename to chrome/browser/ui/webui/version/version_handler_chromeos.h index 0bc597a..b831a0f0 100644 --- a/chrome/browser/ui/webui/version_handler_chromeos.h +++ b/chrome/browser/ui/webui/version/version_handler_chromeos.h
@@ -2,14 +2,14 @@ // 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_VERSION_HANDLER_CHROMEOS_H_ -#define CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_CHROMEOS_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_CHROMEOS_H_ +#define CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_CHROMEOS_H_ #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/ui/webui/version_handler.h" +#include "chrome/browser/ui/webui/version/version_handler.h" #include "chromeos/dbus/util/version_loader.h" // VersionHandlerChromeOS is responsible for loading the Chrome OS @@ -33,4 +33,4 @@ DISALLOW_COPY_AND_ASSIGN(VersionHandlerChromeOS); }; -#endif // CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_CHROMEOS_H_ +#endif // CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_CHROMEOS_H_
diff --git a/chrome/browser/ui/webui/version_handler_win.cc b/chrome/browser/ui/webui/version/version_handler_win.cc similarity index 90% rename from chrome/browser/ui/webui/version_handler_win.cc rename to chrome/browser/ui/webui/version/version_handler_win.cc index 7ce031e..541c822 100644 --- a/chrome/browser/ui/webui/version_handler_win.cc +++ b/chrome/browser/ui/webui/version/version_handler_win.cc
@@ -2,14 +2,14 @@ // 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/version_handler_win.h" +#include "chrome/browser/ui/webui/version/version_handler_win.h" #include "base/bind.h" #include "base/strings/stringprintf.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/win/windows_version.h" -#include "chrome/browser/ui/webui/version_util_win.h" +#include "chrome/browser/ui/webui/version/version_util_win.h" #include "content/public/browser/web_ui.h" VersionHandlerWindows::VersionHandlerWindows() {}
diff --git a/chrome/browser/ui/webui/version_handler_win.h b/chrome/browser/ui/webui/version/version_handler_win.h similarity index 78% rename from chrome/browser/ui/webui/version_handler_win.h rename to chrome/browser/ui/webui/version/version_handler_win.h index 2c424dcc..01d389dd 100644 --- a/chrome/browser/ui/webui/version_handler_win.h +++ b/chrome/browser/ui/webui/version/version_handler_win.h
@@ -2,14 +2,14 @@ // 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_VERSION_HANDLER_WIN_H_ -#define CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_WIN_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_WIN_H_ +#define CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_WIN_H_ #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/ui/webui/version_handler.h" +#include "chrome/browser/ui/webui/version/version_handler.h" // VersionHandlerWindows is responsible for loading the Windows OS version. class VersionHandlerWindows : public VersionHandler { @@ -32,4 +32,4 @@ DISALLOW_COPY_AND_ASSIGN(VersionHandlerWindows); }; -#endif // CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_WIN_H_ +#endif // CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_HANDLER_WIN_H_
diff --git a/chrome/browser/ui/webui/version_handler_win_unittest.cc b/chrome/browser/ui/webui/version/version_handler_win_unittest.cc similarity index 95% rename from chrome/browser/ui/webui/version_handler_win_unittest.cc rename to chrome/browser/ui/webui/version/version_handler_win_unittest.cc index 9345bb0..3e9f9fa 100644 --- a/chrome/browser/ui/webui/version_handler_win_unittest.cc +++ b/chrome/browser/ui/webui/version/version_handler_win_unittest.cc
@@ -2,12 +2,12 @@ // 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/version_handler_win.h" +#include "chrome/browser/ui/webui/version/version_handler_win.h" #include "base/test/scoped_os_info_override_win.h" #include "base/test/test_reg_util_win.h" #include "base/win/registry.h" -#include "chrome/browser/ui/webui/version_handler_win.h" +#include "chrome/browser/ui/webui/version/version_handler_win.h" #include "testing/gtest/include/gtest/gtest.h" class WebUIWindowsVersion : public testing::Test {
diff --git a/chrome/browser/ui/webui/version_ui.cc b/chrome/browser/ui/webui/version/version_ui.cc similarity index 95% rename from chrome/browser/ui/webui/version_ui.cc rename to chrome/browser/ui/webui/version/version_ui.cc index 065bb69b..8068565 100644 --- a/chrome/browser/ui/webui/version_ui.cc +++ b/chrome/browser/ui/webui/version/version_ui.cc
@@ -2,7 +2,7 @@ // 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/version_ui.h" +#include "chrome/browser/ui/webui/version/version_ui.h" #include <memory> @@ -13,8 +13,8 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/version_handler.h" -#include "chrome/browser/ui/webui/version_util_win.h" +#include "chrome/browser/ui/webui/version/version_handler.h" +#include "chrome/browser/ui/webui/version/version_util_win.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/common/url_constants.h" @@ -40,7 +40,7 @@ #endif #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ui/webui/version_handler_chromeos.h" +#include "chrome/browser/ui/webui/version/version_handler_chromeos.h" #endif #if defined(OS_MAC) @@ -48,7 +48,7 @@ #endif #if defined(OS_WIN) -#include "chrome/browser/ui/webui/version_handler_win.h" +#include "chrome/browser/ui/webui/version/version_handler_win.h" #endif using content::WebUIDataSource;
diff --git a/chrome/browser/ui/webui/version_ui.h b/chrome/browser/ui/webui/version/version_ui.h similarity index 83% rename from chrome/browser/ui/webui/version_ui.h rename to chrome/browser/ui/webui/version/version_ui.h index 29a2921..4ba0c5d 100644 --- a/chrome/browser/ui/webui/version_ui.h +++ b/chrome/browser/ui/webui/version/version_ui.h
@@ -2,8 +2,8 @@ // 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_VERSION_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_VERSION_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui_controller.h" @@ -26,4 +26,4 @@ DISALLOW_COPY_AND_ASSIGN(VersionUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_VERSION_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UI_H_
diff --git a/chrome/browser/ui/webui/version_util_win.cc b/chrome/browser/ui/webui/version/version_util_win.cc similarity index 97% rename from chrome/browser/ui/webui/version_util_win.cc rename to chrome/browser/ui/webui/version/version_util_win.cc index aeca2374..e8af2eb 100644 --- a/chrome/browser/ui/webui/version_util_win.cc +++ b/chrome/browser/ui/webui/version/version_util_win.cc
@@ -2,7 +2,7 @@ // 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/version_util_win.h" +#include "chrome/browser/ui/webui/version/version_util_win.h" #include "base/strings/stringprintf.h" #include "base/win/windows_version.h"
diff --git a/chrome/browser/ui/webui/version_util_win.h b/chrome/browser/ui/webui/version/version_util_win.h similarity index 78% rename from chrome/browser/ui/webui/version_util_win.h rename to chrome/browser/ui/webui/version/version_util_win.h index d534732..b328bd5a 100644 --- a/chrome/browser/ui/webui/version_util_win.h +++ b/chrome/browser/ui/webui/version/version_util_win.h
@@ -2,8 +2,8 @@ // 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_VERSION_UTIL_WIN_H_ -#define CHROME_BROWSER_UI_WEBUI_VERSION_UTIL_WIN_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UTIL_WIN_H_ +#define CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UTIL_WIN_H_ #include <string> @@ -24,4 +24,4 @@ } // namespace win } // namespace version_utils -#endif // CHROME_BROWSER_UI_WEBUI_VERSION_UTIL_WIN_H_ +#endif // CHROME_BROWSER_UI_WEBUI_VERSION_VERSION_UTIL_WIN_H_
diff --git a/chrome/browser/ui/webui/webapks_handler.cc b/chrome/browser/ui/webui/webapks/webapks_handler.cc similarity index 97% rename from chrome/browser/ui/webui/webapks_handler.cc rename to chrome/browser/ui/webui/webapks/webapks_handler.cc index dde0be2..c30a2dcb40 100644 --- a/chrome/browser/ui/webui/webapks_handler.cc +++ b/chrome/browser/ui/webui/webapks/webapks_handler.cc
@@ -2,7 +2,7 @@ // 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/webapks_handler.h" +#include "chrome/browser/ui/webui/webapks/webapks_handler.h" #include <string>
diff --git a/chrome/browser/ui/webui/webapks_handler.h b/chrome/browser/ui/webui/webapks/webapks_handler.h similarity index 88% rename from chrome/browser/ui/webui/webapks_handler.h rename to chrome/browser/ui/webui/webapks/webapks_handler.h index bcb67234..a4a25f7 100644 --- a/chrome/browser/ui/webui/webapks_handler.h +++ b/chrome/browser/ui/webui/webapks/webapks_handler.h
@@ -2,8 +2,8 @@ // 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_WEBAPKS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WEBAPKS_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_HANDLER_H_ #include <memory> @@ -45,4 +45,4 @@ DISALLOW_COPY_AND_ASSIGN(WebApksHandler); }; -#endif // CHROME_BROWSER_UI_WEBUI_WEBAPKS_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_HANDLER_H_
diff --git a/chrome/browser/ui/webui/webapks_ui.cc b/chrome/browser/ui/webui/webapks/webapks_ui.cc similarity index 90% rename from chrome/browser/ui/webui/webapks_ui.cc rename to chrome/browser/ui/webui/webapks/webapks_ui.cc index 9e45e8dc..f5dcb36d 100644 --- a/chrome/browser/ui/webui/webapks_ui.cc +++ b/chrome/browser/ui/webui/webapks/webapks_ui.cc
@@ -2,13 +2,13 @@ // 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/webapks_ui.h" +#include "chrome/browser/ui/webui/webapks/webapks_ui.h" #include <memory> #include <string> #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/webapks_handler.h" +#include "chrome/browser/ui/webui/webapks/webapks_handler.h" #include "chrome/common/url_constants.h" #include "chrome/grit/webapks_ui_resources.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/webapks_ui.h b/chrome/browser/ui/webui/webapks/webapks_ui.h similarity index 74% rename from chrome/browser/ui/webui/webapks_ui.h rename to chrome/browser/ui/webui/webapks/webapks_ui.h index c2a1f0c9..6c1f52df 100644 --- a/chrome/browser/ui/webui/webapks_ui.h +++ b/chrome/browser/ui/webui/webapks/webapks_ui.h
@@ -2,8 +2,8 @@ // 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_WEBAPKS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_WEBAPKS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui_controller.h" @@ -18,4 +18,4 @@ DISALLOW_COPY_AND_ASSIGN(WebApksUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_WEBAPKS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WEBAPKS_WEBAPKS_UI_H_
diff --git a/chrome/browser/unload_browsertest.cc b/chrome/browser/unload_browsertest.cc index f327108..d61b4dc1e 100644 --- a/chrome/browser/unload_browsertest.cc +++ b/chrome/browser/unload_browsertest.cc
@@ -12,6 +12,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -515,7 +516,7 @@ // Tests terminating the browser with a beforeunload handler. // Currently only ChromeOS shuts down gracefully. -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserTerminateBeforeUnload) { NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); EXPECT_EQ(kill(base::GetCurrentProcessHandle(), SIGTERM), 0);
diff --git a/chrome/browser/updates/announcement_notification/BUILD.gn b/chrome/browser/updates/announcement_notification/BUILD.gn index c9fc53c6..476c934 100644 --- a/chrome/browser/updates/announcement_notification/BUILD.gn +++ b/chrome/browser/updates/announcement_notification/BUILD.gn
@@ -50,6 +50,7 @@ deps = [ ":announcement_notification", + "//build:chromeos_buildflags", "//chrome/test:test_support", "//skia", "//testing/gmock",
diff --git a/chrome/browser/updates/announcement_notification/announcement_notification_service_unittest.cc b/chrome/browser/updates/announcement_notification/announcement_notification_service_unittest.cc index 08549be..eaddf88a 100644 --- a/chrome/browser/updates/announcement_notification/announcement_notification_service_unittest.cc +++ b/chrome/browser/updates/announcement_notification/announcement_notification_service_unittest.cc
@@ -14,6 +14,7 @@ #include "base/test/simple_test_clock.h" #include "base/time/time.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_features.h" @@ -102,7 +103,9 @@ else disabled_features.push_back(kAnnouncementNotification); -#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || \ +// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch +// of lacros-chrome is complete. +#if defined(OS_WIN) || (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) || \ defined(OS_MAC) if (ephemeral_guest_profile) enabled_features.push_back(
diff --git a/chrome/browser/upgrade_detector/upgrade_detector.h b/chrome/browser/upgrade_detector/upgrade_detector.h index a78dd0d0..8fb7c37 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector.h +++ b/chrome/browser/upgrade_detector/upgrade_detector.h
@@ -11,6 +11,7 @@ #include "base/sequence_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/upgrade_detector/upgrade_observer.h" #include "components/prefs/pref_change_registrar.h" @@ -108,7 +109,7 @@ return critical_update_acknowledged_; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) bool is_factory_reset_required() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return is_factory_reset_required_; @@ -118,7 +119,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return is_rollback_; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) UpgradeNotificationAnnoyanceLevel upgrade_notification_stage() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -259,7 +260,7 @@ upgrade_notification_stage_ = stage; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) void set_is_factory_reset_required(bool is_factory_reset_required) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is_factory_reset_required_ = is_factory_reset_required; @@ -269,7 +270,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is_rollback_ = is_rollback; } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) private: FRIEND_TEST_ALL_PREFIXES(AppMenuModelTest, Basics); @@ -311,7 +312,7 @@ // Whether the user has acknowledged the critical update. bool critical_update_acknowledged_; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Whether a factory reset is needed to complete an update. bool is_factory_reset_required_ = false; @@ -319,7 +320,7 @@ // to an earlier version of Chrome OS, which results in the device being // wiped when it's rebooted. bool is_rollback_ = false; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // A timer to check to see if we've been idle for long enough to show the // critical warning. Should only be set if |upgrade_available_| is
diff --git a/chrome/browser/upgrade_detector/upgrade_detector_impl_unittest.cc b/chrome/browser/upgrade_detector/upgrade_detector_impl_unittest.cc index 0b71b9b..b82a6de2 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector_impl_unittest.cc +++ b/chrome/browser/upgrade_detector/upgrade_detector_impl_unittest.cc
@@ -14,6 +14,7 @@ #include "base/time/tick_clock.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/upgrade_detector/installed_version_poller.h" #include "chrome/browser/upgrade_detector/upgrade_observer.h" #include "chrome/common/pref_names.h" @@ -24,9 +25,9 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) #include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h" -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_WIN) #include "chrome/install_static/install_modes.h" @@ -166,9 +167,9 @@ ScopedTestingLocalState scoped_local_state_; InstalledVersionPoller::ScopedDisableForTesting scoped_poller_disabler_; -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) policy::FakeBrowserDMTokenStorage dm_token_storage_; -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) DISALLOW_COPY_AND_ASSIGN(UpgradeDetectorImplTest); }; @@ -405,9 +406,9 @@ } private: -#if !defined(OS_CHROMEOS) +#if !BUILDFLAG(IS_CHROMEOS_ASH) policy::FakeBrowserDMTokenStorage dm_token_storage_; -#endif // !defined(OS_CHROMEOS) +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) DISALLOW_COPY_AND_ASSIGN(UpgradeDetectorImplTimerTest); };
diff --git a/chrome/browser/usb/usb_chooser_context_unittest.cc b/chrome/browser/usb/usb_chooser_context_unittest.cc index d745b50..01fc46ca 100644 --- a/chrome/browser/usb/usb_chooser_context_unittest.cc +++ b/chrome/browser/usb/usb_chooser_context_unittest.cc
@@ -10,6 +10,7 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "chrome/browser/usb/usb_chooser_context_factory.h" @@ -702,7 +703,7 @@ *unrelated_device_info)); } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) class DeviceLoginScreenWebUsbChooserContextTest : public UsbChooserContextTest { public: @@ -774,7 +775,7 @@ kInvalidRequestingOrigins, *specific_device_info); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace {
diff --git a/chrome/browser/usb/web_usb_detector_unittest.cc b/chrome/browser/usb/web_usb_detector_unittest.cc index 248d0baa..333bad8 100644 --- a/chrome/browser/usb/web_usb_detector_unittest.cc +++ b/chrome/browser/usb/web_usb_detector_unittest.cc
@@ -10,6 +10,7 @@ #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/notifications/notification_display_service_tester.h" @@ -30,7 +31,7 @@ #include "ui/message_center/public/cpp/notification_delegate.h" #include "url/gurl.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user_manager.h" @@ -69,7 +70,7 @@ void SetUp() override { BrowserWithTestWindowTest::SetUp(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>( std::make_unique<chromeos::FakeChromeUserManager>()); @@ -94,7 +95,7 @@ void TearDown() override { BrowserWithTestWindowTest::TearDown(); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) user_manager_enabler_.reset(); #endif web_usb_detector_.reset(); @@ -103,7 +104,7 @@ void Initialize() { web_usb_detector_->Initialize(); } protected: -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) chromeos::FakeChromeUserManager* GetFakeUserManager() { return static_cast<chromeos::FakeChromeUserManager*>( user_manager::UserManager::Get());
diff --git a/chrome/browser/web_applications/preinstalled_web_apps/BUILD.gn b/chrome/browser/web_applications/preinstalled_web_apps/BUILD.gn index cb6b93c..09ea5bc9 100644 --- a/chrome/browser/web_applications/preinstalled_web_apps/BUILD.gn +++ b/chrome/browser/web_applications/preinstalled_web_apps/BUILD.gn
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromeos/ui_mode.gni") import("//chrome/browser/buildflags.gni") source_set("preinstalled_web_apps") { @@ -38,7 +39,7 @@ "youtube.h", ] - if (is_chromeos) { + if (is_chromeos_ash) { sources += [ "google_calendar.cc", "google_calendar.h",
diff --git a/chrome/browser/web_launch/web_launch_files_helper.cc b/chrome/browser/web_launch/web_launch_files_helper.cc index b5c737c..c3787f6 100644 --- a/chrome/browser/web_launch/web_launch_files_helper.cc +++ b/chrome/browser/web_launch/web_launch_files_helper.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/files/file_path.h" +#include "build/chromeos_buildflags.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" @@ -77,7 +78,7 @@ // system implementation. content::NativeFileSystemEntryFactory::PathType MaybeRemapPath( base::FilePath* entry_path) { -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) base::FilePath virtual_path; auto* external_mount_points = storage::ExternalMountPoints::GetSystemInstance();
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc index aeb99ff0..3dcc011 100644 --- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc +++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc
@@ -18,6 +18,7 @@ #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webauthn/authenticator_request_dialog.h" @@ -46,7 +47,7 @@ #include "device/fido/win/authenticator.h" #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/webauthn_request_registrar.h" #include "ui/aura/window.h" #endif @@ -468,7 +469,7 @@ } #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ChromeAuthenticatorRequestDelegate::ChromeOSGenerateRequestIdCallback ChromeAuthenticatorRequestDelegate::GetGenerateRequestIdCallback( content::RenderFrameHost* render_frame_host) { @@ -476,7 +477,7 @@ render_frame_host->GetNativeView()->GetToplevelWindow(); return ash::WebAuthnRequestRegistrar::Get()->GetRegisterCallback(window); } -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) void ChromeAuthenticatorRequestDelegate::UpdateLastTransportUsed( device::FidoTransportProtocol transport) {
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h index e575d1f9..722bbd37 100644 --- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h +++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h
@@ -15,6 +15,7 @@ #include "base/strings/string_piece.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/webauthn/authenticator_request_dialog_model.h" #include "content/public/browser/authenticator_request_client_delegate.h" #include "device/fido/cable/cable_discovery_data.h" @@ -57,10 +58,10 @@ override; #endif // defined(OS_MAC) -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) ChromeOSGenerateRequestIdCallback GetGenerateRequestIdCallback( content::RenderFrameHost* render_frame_host) override; -#endif // defined(OS_CHROMEOS) +#endif // BUILDFLAG(IS_CHROMEOS_ASH) base::WeakPtr<ChromeAuthenticatorRequestDelegate> AsWeakPtr();
diff --git a/chrome/browser/webshare/share_service_browsertest.cc b/chrome/browser/webshare/share_service_browsertest.cc index 0aeffc4..cafac061 100644 --- a/chrome/browser/webshare/share_service_browsertest.cc +++ b/chrome/browser/webshare/share_service_browsertest.cc
@@ -4,6 +4,7 @@ #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_features.h"
diff --git a/chrome/browser/webshare/share_service_impl.cc b/chrome/browser/webshare/share_service_impl.cc index 7bfc923..4c241ee 100644 --- a/chrome/browser/webshare/share_service_impl.cc +++ b/chrome/browser/webshare/share_service_impl.cc
@@ -10,6 +10,7 @@ #include "base/feature_list.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/chrome_features.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" @@ -25,7 +26,7 @@ ShareServiceImpl::ShareServiceImpl(content::RenderFrameHost& render_frame_host) : content::WebContentsObserver( content::WebContents::FromRenderFrameHost(&render_frame_host)), -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) sharesheet_client_(web_contents()), #endif render_frame_host_(&render_frame_host) { @@ -171,7 +172,7 @@ // the blobs. } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) sharesheet_client_.Share(title, text, share_url, std::move(files), std::move(callback)); #elif defined(OS_WIN)
diff --git a/chrome/browser/webshare/share_service_impl.h b/chrome/browser/webshare/share_service_impl.h index 6c4fe12d..97104c9 100644 --- a/chrome/browser/webshare/share_service_impl.h +++ b/chrome/browser/webshare/share_service_impl.h
@@ -10,10 +10,11 @@ #include "base/strings/string_piece.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "content/public/browser/web_contents_observer.h" #include "third_party/blink/public/mojom/webshare/webshare.mojom.h" -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/webshare/chromeos/sharesheet_client.h" #endif @@ -52,7 +53,7 @@ void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; private: -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) webshare::SharesheetClient sharesheet_client_; #endif content::RenderFrameHost* render_frame_host_;
diff --git a/chrome/browser/webshare/share_service_unittest.cc b/chrome/browser/webshare/share_service_unittest.cc index 8ae1070..a832c4e 100644 --- a/chrome/browser/webshare/share_service_unittest.cc +++ b/chrome/browser/webshare/share_service_unittest.cc
@@ -11,6 +11,7 @@ #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/webshare/share_service_impl.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" @@ -25,7 +26,7 @@ using blink::mojom::ShareError; -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/sharesheet/sharesheet_types.h" #include "chrome/browser/webshare/chromeos/sharesheet_client.h" #endif @@ -44,7 +45,7 @@ ChromeRenderViewHostTestHarness::SetUp(); share_service_ = std::make_unique<ShareServiceImpl>(*main_rfh()); -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) webshare::SharesheetClient::SetSharesheetCallbackForTesting( base::BindRepeating(&ShareServiceUnitTest::AcceptShareRequest)); #endif @@ -129,7 +130,7 @@ return builder; } -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) static void AcceptShareRequest(content::WebContents* web_contents, const std::vector<base::FilePath>& file_paths, const std::vector<std::string>& content_types, @@ -226,7 +227,7 @@ } #endif -#if defined(OS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, like Android, we prevent sharing of Android applications. TEST_F(ShareServiceUnitTest, AndroidPackage) { EXPECT_EQ(ShareError::PERMISSION_DENIED,
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 16214c0..a8ae543 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-master-1607363880-fd3f1baf2a5dc6b74a86d40eb9ec18d09a3815d8.profdata +chrome-linux-master-1607407031-3aa7c176f7320c5baa78db92893fe31481ff0a44.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index da4f6e4..bb9d2de 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-master-1607363880-e91185c7ee902dd489788046475ba4c3a284e8fb.profdata +chrome-mac-master-1607407031-63b5db867e1f1fedbce39b6034a36fb366360e89.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index e54b088..11304f2 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-master-1607353071-d7cc2aeaf74b32bdf69634e0f6483d7e4b0ffed2.profdata +chrome-win32-master-1607396289-70fddd0960b2020da66aa7308994f58594fe5850.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 7d922ff..2d99a9a 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-master-1607353071-6048a593794456949e3ffd6a87397fecfdc4317e.profdata +chrome-win64-master-1607396289-b814d12d89d9aa0b6942a46cc974733f2726887a.profdata
diff --git a/chrome/common/cloud_print/cloud_print_constants.cc b/chrome/common/cloud_print/cloud_print_constants.cc index bb6110d4..3fed592 100644 --- a/chrome/common/cloud_print/cloud_print_constants.cc +++ b/chrome/common/cloud_print/cloud_print_constants.cc
@@ -7,7 +7,8 @@ namespace cloud_print { const char kCloudPrintUserAgent[] = "GoogleCloudPrintProxy"; -const char kChromeCloudPrintProxyHeader[] = "X-CloudPrint-Proxy: Chrome"; +const char kChromeCloudPrintProxyHeaderName[] = "X-CloudPrint-Proxy"; +const char kChromeCloudPrintProxyHeaderValue[] = "Chrome"; const char kCloudPrintPushNotificationsSource[] = "cloudprint.google.com"; const char kProxyIdValue[] = "proxy";
diff --git a/chrome/common/cloud_print/cloud_print_constants.h b/chrome/common/cloud_print/cloud_print_constants.h index 3940ef3..1a0dc6e 100644 --- a/chrome/common/cloud_print/cloud_print_constants.h +++ b/chrome/common/cloud_print/cloud_print_constants.h
@@ -10,8 +10,10 @@ // The string to be appended to the user-agent for cloud print requests. extern const char kCloudPrintUserAgent[]; -// The proxy header required by cloud print server. -extern const char kChromeCloudPrintProxyHeader[]; +// The proxy header name required by cloud print server. +extern const char kChromeCloudPrintProxyHeaderName[]; +// The proxy header value required by cloud print server. +extern const char kChromeCloudPrintProxyHeaderValue[]; // The source of cloud print notifications. extern const char kCloudPrintPushNotificationsSource[];
diff --git a/chrome/common/extensions/extension_constants.cc b/chrome/common/extensions/extension_constants.cc index 3ed876bd..7d52075 100644 --- a/chrome/common/extensions/extension_constants.cc +++ b/chrome/common/extensions/extension_constants.cc
@@ -38,8 +38,6 @@ const char kGooglePlusAppId[] = "dlppkpafhbajpcmmoheippocdidnckmm"; const char kGoogleSheetsAppId[] = "felcaaldnbdncclmgdcncolpebgiejap"; const char kGoogleSlidesAppId[] = "aapocclcgogkmnckokdopfmhonfmgoek"; -const char kHTermAppId[] = "pnhechapfaindjhompbnflcldabbghjo"; -const char kHTermDevAppId[] = "okddffdblfhhnmhodogpojmfkjmhinfp"; const char kIdentityApiUiAppId[] = "ahjaciijnoiaklcomgnblndopackapon"; const char kTextEditorAppId[] = "mmfbcljfglbokpmkimbfghdkjmjhdgbg"; const char kInAppPaymentsSupportAppId[] = "nmmhkkegccagdldgiimedpiccmgmieda"; @@ -63,8 +61,6 @@ kGooglePlusAppId, kGoogleSheetsAppId, kGoogleSlidesAppId, - kHTermAppId, - kHTermDevAppId, kIdentityApiUiAppId, kTextEditorAppId, kInAppPaymentsSupportAppId,
diff --git a/chrome/common/extensions/extension_constants.h b/chrome/common/extensions/extension_constants.h index 2d4247de..d7df55d 100644 --- a/chrome/common/extensions/extension_constants.h +++ b/chrome/common/extensions/extension_constants.h
@@ -79,12 +79,6 @@ // The extension id of the Google Slides application. extern const char kGoogleSlidesAppId[]; -// The extension id of the HTerm app for ChromeOS. -extern const char kHTermAppId[]; - -// The extension id of the HTerm dev app for ChromeOS. -extern const char kHTermDevAppId[]; - // The extension id of the Identity API UI application. extern const char kIdentityApiUiAppId[];
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index e9c8c71..45c27696 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -1340,7 +1340,26 @@ bool ChromeContentRendererClient::IsOriginIsolatedPepperPlugin( const base::FilePath& plugin_path) { - return plugin_path.value() == ChromeContentClient::kPDFPluginPath; + // Hosting plugins in-process is inherently incompatible with attempting to + // process-isolate plugins from different origins. + auto* cmdline = base::CommandLine::ForCurrentProcess(); + if (cmdline->HasSwitch(switches::kPpapiInProcess)) { + // The kPpapiInProcess switch should only be used by tests. In particular, + // we expect that the PDF plugin should always be isolated in the product + // (and that the switch won't interfere with PDF isolation). + CHECK_NE(ChromeContentClient::kPDFPluginPath, plugin_path.value()); + + return false; + } + +#if BUILDFLAG(ENABLE_NACL) + // Don't isolate the NaCl plugin (preserving legacy behavior). + if (plugin_path.value() == ChromeContentClient::kNaClPluginFileName) + return false; +#endif + + // Isolate all the other plugins (including the PDF plugin + test plugins). + return true; } #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_EXTENSIONS)
diff --git a/chrome/service/DIR_METADATA b/chrome/service/DIR_METADATA new file mode 100644 index 0000000..7619ec17e --- /dev/null +++ b/chrome/service/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Services>CloudPrint" +}
diff --git a/chrome/service/OWNERS b/chrome/service/OWNERS index ed1bd3ce..aa6ec96c 100644 --- a/chrome/service/OWNERS +++ b/chrome/service/OWNERS
@@ -2,5 +2,3 @@ per-file service_utility_process_host_receiver_bindings.*=set noparent per-file service_utility_process_host_receiver_bindings.*=file://ipc/SECURITY_OWNERS - -# COMPONENT: Services>CloudPrint
diff --git a/chrome/service/cloud_print/cloud_print_auth.cc b/chrome/service/cloud_print/cloud_print_auth.cc index e956456..09fdf66 100644 --- a/chrome/service/cloud_print/cloud_print_auth.cc +++ b/chrome/service/cloud_print/cloud_print_auth.cc
@@ -71,7 +71,7 @@ request_ = CloudPrintURLFetcher::Create(partial_traffic_annotation_); request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_AUTH_CODE, get_authcode_url, this, - kCloudPrintAuthMaxRetryCount, std::string()); + kCloudPrintAuthMaxRetryCount); } void CloudPrintAuth::AuthenticateWithRobotToken(
diff --git a/chrome/service/cloud_print/cloud_print_connector.cc b/chrome/service/cloud_print/cloud_print_connector.cc index d94c4f8c..0e7090e 100644 --- a/chrome/service/cloud_print/cloud_print_connector.cc +++ b/chrome/service/cloud_print/cloud_print_connector.cc
@@ -347,8 +347,8 @@ ResponseHandler handler) { next_response_handler_ = handler; request_ = CloudPrintURLFetcher::Create(partial_traffic_annotation_); - request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_UPDATE_JOB, - url, this, max_retries, std::string()); + request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_UPDATE_JOB, url, this, + max_retries); } void CloudPrintConnector::StartPostRequest( @@ -360,8 +360,8 @@ ResponseHandler handler) { next_response_handler_ = handler; request_ = CloudPrintURLFetcher::Create(partial_traffic_annotation_); - request_->StartPostRequest( - type, url, this, max_retries, mime_type, post_data, std::string()); + request_->StartPostRequest(type, url, this, max_retries, mime_type, + post_data); } void CloudPrintConnector::ReportUserMessage(const std::string& message_id, @@ -380,7 +380,7 @@ CloudPrintURLFetcher::Create(partial_traffic_annotation_); user_message_request_->StartPostRequest( CloudPrintURLFetcher::REQUEST_USER_MESSAGE, url, this, 1, mime_type, - post_data, std::string()); + post_data); } bool CloudPrintConnector::RemovePrinterFromList(
diff --git a/chrome/service/cloud_print/cloud_print_url_fetcher.cc b/chrome/service/cloud_print/cloud_print_url_fetcher.cc index 10f1b17b..541a5536 100644 --- a/chrome/service/cloud_print/cloud_print_url_fetcher.cc +++ b/chrome/service/cloud_print/cloud_print_url_fetcher.cc
@@ -136,14 +136,22 @@ return (request_.get() == source); } -void CloudPrintURLFetcher::StartGetRequest( +void CloudPrintURLFetcher::StartGetRequest(RequestType type, + const GURL& url, + Delegate* delegate, + int max_retries) { + StartRequestHelper(type, url, net::URLFetcher::GET, delegate, max_retries, + std::string(), std::string(), std::string()); +} + +void CloudPrintURLFetcher::StartGetRequestWithAcceptHeader( RequestType type, const GURL& url, Delegate* delegate, int max_retries, - const std::string& additional_headers) { + const std::string& accept_header) { StartRequestHelper(type, url, net::URLFetcher::GET, delegate, max_retries, - std::string(), std::string(), additional_headers); + std::string(), std::string(), accept_header); } void CloudPrintURLFetcher::StartPostRequest( @@ -152,10 +160,9 @@ Delegate* delegate, int max_retries, const std::string& post_data_mime_type, - const std::string& post_data, - const std::string& additional_headers) { + const std::string& post_data) { StartRequestHelper(type, url, net::URLFetcher::POST, delegate, max_retries, - post_data_mime_type, post_data, additional_headers); + post_data_mime_type, post_data, std::string()); } void CloudPrintURLFetcher::OnURLFetchComplete( @@ -244,13 +251,13 @@ int max_retries, const std::string& post_data_mime_type, const std::string& post_data, - const std::string& additional_headers) { + const std::string& additional_accept_header) { DCHECK(delegate); type_ = type; UMA_HISTOGRAM_ENUMERATION("CloudPrint.UrlFetcherRequestType", type, REQUEST_MAX); // Persist the additional headers in case we need to retry the request. - additional_headers_ = additional_headers; + additional_accept_header_ = additional_accept_header; net::NetworkTrafficAnnotationTag traffic_annotation = net::CompleteNetworkTrafficAnnotation("cloud_print", partial_traffic_annotation_, @@ -288,15 +295,13 @@ } void CloudPrintURLFetcher::SetupRequestHeaders() { + request_->ClearExtraRequestHeaders(); std::string headers = delegate_->GetAuthHeader(); - if (!headers.empty()) - headers += "\r\n"; - headers += kChromeCloudPrintProxyHeader; - if (!additional_headers_.empty()) { - headers += "\r\n"; - headers += additional_headers_; + request_->AddExtraRequestHeader(kChromeCloudPrintProxyHeaderName, + kChromeCloudPrintProxyHeaderValue); + if (!additional_accept_header_.empty()) { + request_->AddExtraRequestHeader("Accept", additional_accept_header_); } - request_->SetExtraRequestHeaders(headers); } CloudPrintURLFetcher::~CloudPrintURLFetcher() {}
diff --git a/chrome/service/cloud_print/cloud_print_url_fetcher.h b/chrome/service/cloud_print/cloud_print_url_fetcher.h index fbff96b..0dec8cda 100644 --- a/chrome/service/cloud_print/cloud_print_url_fetcher.h +++ b/chrome/service/cloud_print/cloud_print_url_fetcher.h
@@ -122,15 +122,18 @@ void StartGetRequest(RequestType type, const GURL& url, Delegate* delegate, - int max_retries, - const std::string& additional_headers); + int max_retries); + void StartGetRequestWithAcceptHeader(RequestType type, + const GURL& url, + Delegate* delegate, + int max_retries, + const std::string& accept_header); void StartPostRequest(RequestType type, const GURL& url, Delegate* delegate, int max_retries, const std::string& post_data_mime_type, - const std::string& post_data, - const std::string& additional_headers); + const std::string& post_data); // net::URLFetcherDelegate implementation. void OnURLFetchComplete(const net::URLFetcher* source) override; @@ -152,13 +155,13 @@ int max_retries, const std::string& post_data_mime_type, const std::string& post_data, - const std::string& additional_headers); + const std::string& additional_accept_header); void SetupRequestHeaders(); std::unique_ptr<net::URLFetcher> request_; Delegate* delegate_; int num_retries_; - std::string additional_headers_; + std::string additional_accept_header_; std::string post_data_mime_type_; std::string post_data_;
diff --git a/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc b/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc index 5a00318..1329d62 100644 --- a/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc +++ b/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc
@@ -236,7 +236,7 @@ max_retries_ = max_retries; start_time_ = Time::Now(); fetcher_->StartGetRequest(CloudPrintURLFetcher::REQUEST_MAX, url, this, - max_retries_, std::string()); + max_retries_); } CloudPrintURLFetcher::ResponseAction @@ -305,7 +305,7 @@ response_count_++; if (response_count_ < 20) { fetcher_->StartGetRequest(CloudPrintURLFetcher::REQUEST_MAX, url, this, - max_retries_, std::string()); + max_retries_); } else { // We have already sent 20 requests continuously. And we expect that // it takes more than 1 second due to the overload protection settings.
diff --git a/chrome/service/cloud_print/cloud_print_wipeout.cc b/chrome/service/cloud_print/cloud_print_wipeout.cc index 40db126..09f0ef6 100644 --- a/chrome/service/cloud_print/cloud_print_wipeout.cc +++ b/chrome/service/cloud_print/cloud_print_wipeout.cc
@@ -42,8 +42,8 @@ printer_id, "connector_disabled"); request_ = CloudPrintURLFetcher::Create(partial_traffic_annotation_); - request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_UNREGISTER, - url, this, kMaxWipeoutAttempts, std::string()); + request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_UNREGISTER, url, this, + kMaxWipeoutAttempts); } CloudPrintURLFetcher::ResponseAction CloudPrintWipeout::HandleJSONData(
diff --git a/chrome/service/cloud_print/job_status_updater.cc b/chrome/service/cloud_print/job_status_updater.cc index 063faf44..99e3583 100644 --- a/chrome/service/cloud_print/job_status_updater.cc +++ b/chrome/service/cloud_print/job_status_updater.cc
@@ -80,11 +80,9 @@ request_ = CloudPrintURLFetcher::Create(partial_traffic_annotation_); request_->StartGetRequest( CloudPrintURLFetcher::REQUEST_UPDATE_JOB, - GetUrlForJobStatusUpdate( - cloud_print_server_url_, job_id_, last_job_details_), - this, - kCloudPrintAPIMaxRetryCount, - std::string()); + GetUrlForJobStatusUpdate(cloud_print_server_url_, job_id_, + last_job_details_), + this, kCloudPrintAPIMaxRetryCount); } } }
diff --git a/chrome/service/cloud_print/printer_job_handler.cc b/chrome/service/cloud_print/printer_job_handler.cc index 84430c1..7d1a567 100644 --- a/chrome/service/cloud_print/printer_job_handler.cc +++ b/chrome/service/cloud_print/printer_job_handler.cc
@@ -328,8 +328,7 @@ request_url = GURL(job_details_.print_ticket_url_); } request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_TICKET, - request_url, this, kJobDataMaxRetryCount, - std::string()); + request_url, this, kJobDataMaxRetryCount); return CloudPrintURLFetcher::STOP_PROCESSING; } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( @@ -363,11 +362,9 @@ job_details_.print_ticket_mime_type_ = mime_type; SetNextDataHandler(&PrinterJobHandler::HandlePrintDataResponse); request_ = CloudPrintURLFetcher::Create(kPartialTrafficAnnotation); - std::string accept_headers = "Accept: "; - accept_headers += print_system_->GetSupportedMimeTypes(); - request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_DATA, - GURL(job_details_.print_data_url_), this, kJobDataMaxRetryCount, - accept_headers); + request_->StartGetRequestWithAcceptHeader( + CloudPrintURLFetcher::REQUEST_DATA, GURL(job_details_.print_data_url_), + this, kJobDataMaxRetryCount, print_system_->GetSupportedMimeTypes()); } else { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_INVALID_TICKET, JOB_HANDLER_MAX); @@ -479,7 +476,7 @@ CloudPrintURLFetcher::REQUEST_JOB_FETCH, GetUrlForJobFetch(cloud_print_server_url_, printer_info_cloud_.printer_id, job_fetch_reason_), - this, kCloudPrintAPIMaxRetryCount, std::string()); + this, kCloudPrintAPIMaxRetryCount); last_job_fetch_time_ = base::TimeTicks::Now(); VLOG(1) << "CP_CONNECTOR: Last job fetch time" << ", printer name: " << printer_info_.printer_name @@ -567,7 +564,7 @@ CloudPrintURLFetcher::REQUEST_UPDATE_JOB, GetUrlForJobStatusUpdate(cloud_print_server_url_, job_details_.job_id_, status, error), - this, kCloudPrintAPIMaxRetryCount, std::string()); + this, kCloudPrintAPIMaxRetryCount); } void PrinterJobHandler::RunScheduledJobCheck() { @@ -752,13 +749,9 @@ request_ = CloudPrintURLFetcher::Create(kPartialTrafficAnnotation); request_->StartPostRequest( CloudPrintURLFetcher::REQUEST_UPDATE_PRINTER, - GetUrlForPrinterUpdate( - cloud_print_server_url_, printer_info_cloud_.printer_id), - this, - kCloudPrintAPIMaxRetryCount, - mime_type, - post_data, - std::string()); + GetUrlForPrinterUpdate(cloud_print_server_url_, + printer_info_cloud_.printer_id), + this, kCloudPrintAPIMaxRetryCount, mime_type, post_data); } else { // We are done here. Go to the Stop state VLOG(1) << "CP_CONNECTOR: Stopping printer job handler"
diff --git a/chrome/services/file_util/DIR_METADATA b/chrome/services/file_util/DIR_METADATA new file mode 100644 index 0000000..1864297 --- /dev/null +++ b/chrome/services/file_util/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Services>Safebrowsing" +}
diff --git a/chrome/services/file_util/OWNERS b/chrome/services/file_util/OWNERS deleted file mode 100644 index 85d233d..0000000 --- a/chrome/services/file_util/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Services>Safebrowsing
diff --git a/chrome/services/ipp_parser/DIR_METADATA b/chrome/services/ipp_parser/DIR_METADATA new file mode 100644 index 0000000..ad3cb1a --- /dev/null +++ b/chrome/services/ipp_parser/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Printing>CUPS" +}
diff --git a/chrome/services/ipp_parser/OWNERS b/chrome/services/ipp_parser/OWNERS index 19a3181..5a872c7 100644 --- a/chrome/services/ipp_parser/OWNERS +++ b/chrome/services/ipp_parser/OWNERS
@@ -1,3 +1,2 @@ luum@chromium.org skau@chromium.org -# COMPONENT: Internals>Printing>CUPS
diff --git a/chrome/services/media_gallery_util/DIR_METADATA b/chrome/services/media_gallery_util/DIR_METADATA new file mode 100644 index 0000000..8defaf8 --- /dev/null +++ b/chrome/services/media_gallery_util/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Platform>Apps>MediaGalleries" +}
diff --git a/chrome/services/media_gallery_util/OWNERS b/chrome/services/media_gallery_util/OWNERS index 65216a6b..7ccf0e0 100644 --- a/chrome/services/media_gallery_util/OWNERS +++ b/chrome/services/media_gallery_util/OWNERS
@@ -1,2 +1 @@ file://chrome/browser/media_galleries/OWNERS -# COMPONENT: Platform>Apps>MediaGalleries
diff --git a/chrome/services/printing/DIR_METADATA b/chrome/services/printing/DIR_METADATA new file mode 100644 index 0000000..d446a5934 --- /dev/null +++ b/chrome/services/printing/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Printing" +}
diff --git a/chrome/services/printing/OWNERS b/chrome/services/printing/OWNERS index 01ea38e..9b08c66 100644 --- a/chrome/services/printing/OWNERS +++ b/chrome/services/printing/OWNERS
@@ -1,2 +1 @@ file://printing/OWNERS -# COMPONENT: Internals>Printing
diff --git a/chrome/services/printing/print_backend_service_impl.cc b/chrome/services/printing/print_backend_service_impl.cc index d38d57b..e19ad94 100644 --- a/chrome/services/printing/print_backend_service_impl.cc +++ b/chrome/services/printing/print_backend_service_impl.cc
@@ -37,4 +37,25 @@ std::move(callback).Run(print_backend_->GetDefaultPrinterName()); } +void PrintBackendServiceImpl::GetPrinterSemanticCapsAndDefaults( + const std::string& printer_name, + mojom::PrintBackendService::GetPrinterSemanticCapsAndDefaultsCallback + callback) { + if (!print_backend_) { + std::move(callback).Run(base::nullopt); + return; + } + + PrinterSemanticCapsAndDefaults printer_caps; + const bool result = print_backend_->GetPrinterSemanticCapsAndDefaults( + printer_name, &printer_caps); + if (!result) { + DLOG(ERROR) << "GetPrinterSemanticCapsAndDefaults failed, last error is " + << logging::GetLastSystemErrorCode(); + std::move(callback).Run(base::nullopt); + return; + } + std::move(callback).Run(std::move(printer_caps)); +} + } // namespace printing
diff --git a/chrome/services/printing/print_backend_service_impl.h b/chrome/services/printing/print_backend_service_impl.h index 1ff1e26..21fba2f9 100644 --- a/chrome/services/printing/print_backend_service_impl.h +++ b/chrome/services/printing/print_backend_service_impl.h
@@ -30,12 +30,18 @@ using GetDefaultPrinterCallback = base::OnceCallback<void(const base::Optional<std::string>& printer_name)>; + using GetPrinterSemanticCapsAndDefaultsCallback = base::OnceCallback<void( + base::Optional<PrinterSemanticCapsAndDefaults> printer_caps)>; // mojom::PrintBackendService implementation: void Init(const std::string& locale) override; void GetDefaultPrinterName( mojom::PrintBackendService::GetDefaultPrinterNameCallback callback) override; + void GetPrinterSemanticCapsAndDefaults( + const std::string& printer_name, + mojom::PrintBackendService::GetPrinterSemanticCapsAndDefaultsCallback + callback) override; scoped_refptr<PrintBackend> print_backend_;
diff --git a/chrome/services/printing/public/mojom/BUILD.gn b/chrome/services/printing/public/mojom/BUILD.gn index c4a948d..b9c14b76 100644 --- a/chrome/services/printing/public/mojom/BUILD.gn +++ b/chrome/services/printing/public/mojom/BUILD.gn
@@ -36,6 +36,7 @@ if (is_win || is_mac || is_linux || is_chromeos) { sources += [ "print_backend_service.mojom" ] + deps += [ "//printing/backend/mojom" ] } cpp_typemaps = [
diff --git a/chrome/services/printing/public/mojom/print_backend_service.mojom b/chrome/services/printing/public/mojom/print_backend_service.mojom index 8d4a125d..85f41aa 100644 --- a/chrome/services/printing/public/mojom/print_backend_service.mojom +++ b/chrome/services/printing/public/mojom/print_backend_service.mojom
@@ -4,6 +4,8 @@ module printing.mojom; +import "printing/backend/mojom/print_backend.mojom"; + // The main interface to Chrome's Print Backend Service, which performs // printer queries and commands to operating system printer drivers in an // isolated process. @@ -16,4 +18,9 @@ // No value for `printer_name` is provided if there is a failure. GetDefaultPrinterName() => (string? printer_name); + + // Gets the semantic capabilities and defaults for a specific printer. + // No value provided for `printer_caps` if there is a failure. + GetPrinterSemanticCapsAndDefaults(string printer_name) + => (PrinterSemanticCapsAndDefaults? printer_caps); };
diff --git a/chrome/services/qrcode_generator/DIR_METADATA b/chrome/services/qrcode_generator/DIR_METADATA new file mode 100644 index 0000000..e64cd2d --- /dev/null +++ b/chrome/services/qrcode_generator/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "UI>Browser>Sharing" +}
diff --git a/chrome/services/qrcode_generator/OWNERS b/chrome/services/qrcode_generator/OWNERS index 945a5a2..2512ad6 100644 --- a/chrome/services/qrcode_generator/OWNERS +++ b/chrome/services/qrcode_generator/OWNERS
@@ -1,4 +1,2 @@ # Send-tab-to-self (Chrome Sharing team) owns this feature. file://components/send_tab_to_self/OWNERS - -# COMPONENT: UI>Browser>Sharing
diff --git a/chrome/services/removable_storage_writer/DIR_METADATA b/chrome/services/removable_storage_writer/DIR_METADATA new file mode 100644 index 0000000..26cbc57 --- /dev/null +++ b/chrome/services/removable_storage_writer/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Services" +}
diff --git a/chrome/services/removable_storage_writer/OWNERS b/chrome/services/removable_storage_writer/OWNERS deleted file mode 100644 index eaf0589..0000000 --- a/chrome/services/removable_storage_writer/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Internals>Services
diff --git a/chrome/services/sharing/DIR_METADATA b/chrome/services/sharing/DIR_METADATA new file mode 100644 index 0000000..e64cd2d --- /dev/null +++ b/chrome/services/sharing/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "UI>Browser>Sharing" +}
diff --git a/chrome/services/sharing/OWNERS b/chrome/services/sharing/OWNERS index 5a73dd4..bab389c 100644 --- a/chrome/services/sharing/OWNERS +++ b/chrome/services/sharing/OWNERS
@@ -1,2 +1 @@ file://chrome/browser/sharing/OWNERS -# COMPONENT: UI>Browser>Sharing \ No newline at end of file
diff --git a/chrome/services/sharing/nearby/DIR_METADATA b/chrome/services/sharing/nearby/DIR_METADATA new file mode 100644 index 0000000..ac713319 --- /dev/null +++ b/chrome/services/sharing/nearby/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "UI>Browser>Sharing>Nearby" +}
diff --git a/chrome/services/sharing/nearby/OWNERS b/chrome/services/sharing/nearby/OWNERS index 49592df..46b5a73 100644 --- a/chrome/services/sharing/nearby/OWNERS +++ b/chrome/services/sharing/nearby/OWNERS
@@ -1,2 +1 @@ file://chrome/browser/nearby_sharing/OWNERS -# COMPONENT: UI>Browser>Sharing>Nearby
diff --git a/chrome/services/speech/DIR_METADATA b/chrome/services/speech/DIR_METADATA new file mode 100644 index 0000000..31d4aba4 --- /dev/null +++ b/chrome/services/speech/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Media" +}
diff --git a/chrome/services/speech/OWNERS b/chrome/services/speech/OWNERS index d21dfa0..f3461861 100644 --- a/chrome/services/speech/OWNERS +++ b/chrome/services/speech/OWNERS
@@ -1,4 +1,2 @@ -# COMPONENT: Internals>Media - evliu@google.com beccahughes@chromium.org
diff --git a/chrome/services/util_win/DIR_METADATA b/chrome/services/util_win/DIR_METADATA new file mode 100644 index 0000000..0dd97e4 --- /dev/null +++ b/chrome/services/util_win/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Services>ServiceManager" +}
diff --git a/chrome/services/util_win/OWNERS b/chrome/services/util_win/OWNERS index 228d7be2..cab4a9f8 100644 --- a/chrome/services/util_win/OWNERS +++ b/chrome/services/util_win/OWNERS
@@ -1,3 +1,2 @@ pmonette@chromium.org noel@chromium.org -# COMPONENT: Internals>Services>ServiceManager
diff --git a/chrome/services/wilco_dtc_supportd/DIR_METADATA b/chrome/services/wilco_dtc_supportd/DIR_METADATA new file mode 100644 index 0000000..4c21d96 --- /dev/null +++ b/chrome/services/wilco_dtc_supportd/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Enterprise" +}
diff --git a/chrome/services/wilco_dtc_supportd/OWNERS b/chrome/services/wilco_dtc_supportd/OWNERS index d7e3023..ea3bb324 100644 --- a/chrome/services/wilco_dtc_supportd/OWNERS +++ b/chrome/services/wilco_dtc_supportd/OWNERS
@@ -4,5 +4,3 @@ # Backup reviewers: emaxx@chromium.org pmarko@chromium.org - -# COMPONENT: Enterprise
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 73f8419..1915842 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3216,6 +3216,7 @@ "../browser/lacros/keystore_service_lacros_browsertest.cc", "../browser/lacros/media_session_lacros_browsertest.cc", "../browser/lacros/message_center_lacros_browsertest.cc", + "../browser/lacros/metrics_reporting_lacros_browsertest.cc", "../browser/lacros/screen_manager_lacros_browsertest.cc", ] @@ -3635,6 +3636,7 @@ "../browser/policy/messaging_layer/storage/test_storage_module.h", "../browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc", "../browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc", + "../browser/policy/messaging_layer/upload/record_upload_request_builder_unittest.cc", "../browser/policy/messaging_layer/upload/upload_client_unittest.cc", "../browser/policy/messaging_layer/util/shared_queue_unittest.cc", "../browser/policy/messaging_layer/util/shared_vector_unittest.cc", @@ -3918,7 +3920,7 @@ "../browser/process_singleton_win_unittest.cc", "../browser/profiles/profile_shortcut_manager_unittest_win.cc", "../browser/shell_integration_win_unittest.cc", - "../browser/ui/webui/version_handler_win_unittest.cc", + "../browser/ui/webui/version/version_handler_win_unittest.cc", "../browser/upgrade_detector/get_installed_version_win_unittest.cc", "../browser/upgrade_detector/registry_monitor_unittest.cc", "../browser/win/chrome_elf_init_unittest.cc", @@ -4659,7 +4661,7 @@ "../browser/ui/webui/downloads/downloads_list_tracker_unittest.cc", "../browser/ui/webui/downloads/mock_downloads_page.cc", "../browser/ui/webui/downloads/mock_downloads_page.h", - "../browser/ui/webui/flags_ui_unittest.cc", + "../browser/ui/webui/flags/flags_ui_unittest.cc", "../browser/ui/webui/history/browsing_history_handler_unittest.cc", "../browser/ui/webui/managed_ui_handler_unittest.cc", "../browser/ui/webui/management_ui_handler_unittest.cc", @@ -5669,7 +5671,6 @@ "../browser/safe_browsing/incident_reporting/mock_incident_receiver.h", "../browser/safe_browsing/incident_reporting/platform_state_store_unittest.cc", "../browser/safe_browsing/incident_reporting/preference_validation_delegate_unittest.cc", - "../browser/safe_browsing/incident_reporting/resource_request_detector_unittest.cc", "../browser/safe_browsing/incident_reporting/state_store_unittest.cc", "../browser/safe_browsing/incident_reporting/tracked_preference_incident_unittest.cc", "../browser/safe_browsing/local_two_phase_testserver.cc",
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index f30fb6a..aad4c6ca 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -104,6 +104,8 @@ 'MobileEmulationCapabilityTest.testTapElement', # https://bugs.chromium.org/p/chromium/issues/detail?id=1011225 'ChromeDriverTest.testActionsMultiTouchPoint', + # Flaky: https://crbug.com/1156576. + 'ChromeDriverTestLegacy.testContextMenuEventFired', ] _DESKTOP_NEGATIVE_FILTER = [
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index c4175ce1..2d0bed9 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -262,6 +262,11 @@ ] } + if (is_chromeos_ash || is_win) { + deps += [ "inline_login:preprocess" ] + data += [ "$root_gen_dir/chrome/test/data/webui/inline_login/inline_login_test_util.js" ] + } + if (is_chromeos_ash) { data += [ "$root_gen_dir/chrome/test/data/webui/chromeos/fake_network_config_mojom.m.js", @@ -302,6 +307,7 @@ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/fake_nearby_contact_manager.m.js", "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/fake_nearby_share_settings.m.js", "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_contact_visibility_test.m.js", + "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_device_icon_test.m.js", "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_onboarding_page_test.m.js", "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_page_template_test.m.js", "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_visibility_page_test.m.js",
diff --git a/chrome/test/data/webui/inline_login/BUILD.gn b/chrome/test/data/webui/inline_login/BUILD.gn index 444558e..a2ecb32 100644 --- a/chrome/test/data/webui/inline_login/BUILD.gn +++ b/chrome/test/data/webui/inline_login/BUILD.gn
@@ -3,6 +3,13 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/grit/preprocess_if_expr.gni") + +preprocess_if_expr("preprocess") { + in_folder = "./" + out_folder = "$target_gen_dir" + in_files = [ "inline_login_test_util.js" ] +} js_type_check("closure_compile") { is_polymer3 = true
diff --git a/chrome/test/data/webui/inline_login/inline_login_test_util.js b/chrome/test/data/webui/inline_login/inline_login_test_util.js index 0a3fd56..7fea472 100644 --- a/chrome/test/data/webui/inline_login/inline_login_test_util.js +++ b/chrome/test/data/webui/inline_login/inline_login_test_util.js
@@ -71,6 +71,9 @@ 'showIncognito', 'getAccounts', 'dialogClose', + // <if expr="chromeos"> + 'skipWelcomePage', + // </if> ]); } @@ -119,4 +122,11 @@ dialogClose() { this.methodCalled('dialogClose'); } + + // <if expr="chromeos"> + /** @override */ + skipWelcomePage(skip) { + this.methodCalled('skipWelcomePage', skip); + } + // </if> }
diff --git a/chrome/test/data/webui/nearby_share/BUILD.gn b/chrome/test/data/webui/nearby_share/BUILD.gn index da4ab98..ccd6d5f 100644 --- a/chrome/test/data/webui/nearby_share/BUILD.gn +++ b/chrome/test/data/webui/nearby_share/BUILD.gn
@@ -18,11 +18,8 @@ deps = [ ":fake_mojo_interfaces", ":nearby_confirmation_page_test", - ":nearby_device_icon_test", - ":nearby_device_test", ":nearby_discovery_page_test", ":nearby_preview_test", - ":nearby_progress_test", ":nearby_share_app_test", ] } @@ -43,24 +40,6 @@ externs_list = [ "$externs_path/mocha-2.5.js" ] } -js_library("nearby_device_test") { - deps = [ - "..:chai_assert", - "//chrome/browser/resources/nearby_share:nearby_device", - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - ] - externs_list = [ "$externs_path/mocha-2.5.js" ] -} - -js_library("nearby_device_icon_test") { - deps = [ - "..:chai_assert", - "//chrome/browser/resources/nearby_share:nearby_device_icon", - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - ] - externs_list = [ "$externs_path/mocha-2.5.js" ] -} - js_library("nearby_discovery_page_test") { deps = [ ":fake_mojo_interfaces", @@ -79,15 +58,6 @@ externs_list = [ "$externs_path/mocha-2.5.js" ] } -js_library("nearby_progress_test") { - deps = [ - "..:chai_assert", - "//chrome/browser/resources/nearby_share:nearby_progress", - "//chrome/browser/ui/webui/nearby_share:mojom_js_library_for_compile", - ] - externs_list = [ "$externs_path/mocha-2.5.js" ] -} - js_library("nearby_share_app_test") { deps = [ "..:chai_assert",
diff --git a/chrome/test/data/webui/nearby_share/nearby_browsertest.js b/chrome/test/data/webui/nearby_share/nearby_browsertest.js index 3d22f18..211e840b 100644 --- a/chrome/test/data/webui/nearby_share/nearby_browsertest.js +++ b/chrome/test/data/webui/nearby_share/nearby_browsertest.js
@@ -41,11 +41,8 @@ }; [['ConfirmationPage', 'nearby_confirmation_page_test.js'], - ['Device', 'nearby_device_test.js'], - ['DeviceIcon', 'nearby_device_icon_test.js'], ['DiscoveryPage', 'nearby_discovery_page_test.js'], ['Preview', 'nearby_preview_test.js'], - ['Progress', 'nearby_progress_test.js'], ['ShareApp', 'nearby_share_app_test.js'], ].forEach(test => registerTest(...test));
diff --git a/chrome/test/data/webui/nearby_share/nearby_device_icon_test.js b/chrome/test/data/webui/nearby_share/nearby_device_icon_test.js deleted file mode 100644 index fff38ca4..0000000 --- a/chrome/test/data/webui/nearby_share/nearby_device_icon_test.js +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// So that mojo is defined. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; - -import 'chrome://nearby/nearby_device_icon.js'; -import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; - -import {assertEquals} from '../chai_assert.js'; - -suite('DeviceIconTest', function() { - /** @type {!NearbyDeviceIconElement} */ - let deviceIconElement; - - setup(function() { - deviceIconElement = /** @type {!NearbyDeviceIconElement} */ ( - document.createElement('nearby-device-icon')); - document.body.appendChild(deviceIconElement); - }); - - teardown(function() { - deviceIconElement.remove(); - }); - - test('renders component', function() { - assertEquals('NEARBY-DEVICE-ICON', deviceIconElement.tagName); - }); - - test('renders default icon', function() { - const renderedIcon = deviceIconElement.$$('#icon').icon; - assertEquals('nearby-share:laptop', renderedIcon); - }); - - const iconTests = [ - { - type: nearbyShare.mojom.ShareTargetType.kPhone, - expected: 'nearby-share:smartphone' - }, - { - type: nearbyShare.mojom.ShareTargetType.kTablet, - expected: 'nearby-share:tablet' - }, - { - type: nearbyShare.mojom.ShareTargetType.kLaptop, - expected: 'nearby-share:laptop' - }, - { - type: nearbyShare.mojom.ShareTargetType.kUnknown, - expected: 'nearby-share:laptop' - }, - ]; - - iconTests.forEach(function({type, expected}) { - test(`renders ${expected}`, function() { - const shareTarget = /** @type {!nearbyShare.mojom.ShareTarget} */ ({ - id: {high: 0, low: 0}, - name: 'Device Name', - type, - }); - deviceIconElement.shareTarget = shareTarget; - - const renderedIcon = deviceIconElement.$$('#icon').icon; - assertEquals(expected, renderedIcon); - }); - }); -});
diff --git a/chrome/test/data/webui/nearby_share/shared/BUILD.gn b/chrome/test/data/webui/nearby_share/shared/BUILD.gn index e10ef4a8..ccfd3c8 100644 --- a/chrome/test/data/webui/nearby_share/shared/BUILD.gn +++ b/chrome/test/data/webui/nearby_share/shared/BUILD.gn
@@ -13,8 +13,11 @@ "fake_nearby_contact_manager.js", "fake_nearby_share_settings.js", "nearby_contact_visibility_test.js", + "nearby_device_icon_test.js", + "nearby_device_test.js", "nearby_onboarding_page_test.js", "nearby_page_template_test.js", + "nearby_progress_test.js", "nearby_visibility_page_test.js", ] namespace_rewrites = test_namespace_rewrites + [ @@ -36,8 +39,11 @@ ":fake_nearby_contact_manager.m", ":fake_nearby_share_settings.m", ":nearby_contact_visibility_test.m", + ":nearby_device_icon_test.m", + ":nearby_device_test.m", ":nearby_onboarding_page_test.m", ":nearby_page_template_test.m", + ":nearby_progress_test.m", ":nearby_visibility_page_test.m", ] } @@ -61,6 +67,26 @@ externs_list = [ "$externs_path/mocha-2.5.js" ] } +js_library("nearby_device_icon_test.m") { + sources = [ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_device_icon_test.m.js" ] + deps = [ + "../..:chai_assert", + "//chrome/browser/resources/nearby_share/shared:nearby_device_icon.m", + ] + extra_deps = [ ":modulize" ] + externs_list = [ "$externs_path/mocha-2.5.js" ] +} + +js_library("nearby_device_test.m") { + sources = [ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_device_test.m.js" ] + deps = [ + "../..:chai_assert", + "//chrome/browser/resources/nearby_share/shared:nearby_device.m", + ] + extra_deps = [ ":modulize" ] + externs_list = [ "$externs_path/mocha-2.5.js" ] +} + js_library("nearby_onboarding_page_test.m") { sources = [ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_onboarding_page_test.m.js" ] deps = [ @@ -85,6 +111,16 @@ externs_list = [ "$externs_path/mocha-2.5.js" ] } +js_library("nearby_progress_test.m") { + sources = [ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/nearby_progress_test.m.js" ] + deps = [ + "../..:chai_assert", + "//chrome/browser/resources/nearby_share/shared:nearby_progress.m", + ] + extra_deps = [ ":modulize" ] + externs_list = [ "$externs_path/mocha-2.5.js" ] +} + js_library("fake_nearby_share_settings.m") { sources = [ "$root_gen_dir/chrome/test/data/webui/nearby_share/shared/fake_nearby_share_settings.m.js" ] deps = [
diff --git a/chrome/test/data/webui/nearby_share/shared/nearby_device_icon_test.js b/chrome/test/data/webui/nearby_share/shared/nearby_device_icon_test.js new file mode 100644 index 0000000..3e878ac --- /dev/null +++ b/chrome/test/data/webui/nearby_share/shared/nearby_device_icon_test.js
@@ -0,0 +1,66 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// clang-format off +// So that mojo is defined. +// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +// #import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; +// #import 'chrome://nearby/shared/nearby_device_icon.m.js'; +// #import 'chrome://nearby/mojo/nearby_share_target_types.mojom-lite.js'; +// #import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; +// #import {assertEquals} from '../../chai_assert.js'; +// clang-format on + +suite('DeviceIconTest', function() { + /** @type {!NearbyDeviceIconElement} */ + let deviceIconElement; + + setup(function() { + deviceIconElement = /** @type {!NearbyDeviceIconElement} */ ( + document.createElement('nearby-device-icon')); + document.body.appendChild(deviceIconElement); + }); + + teardown(function() { + deviceIconElement.remove(); + }); + + test('renders component', function() { + assertEquals('NEARBY-DEVICE-ICON', deviceIconElement.tagName); + }); + + test('renders default icon', function() { + const renderedIcon = deviceIconElement.$$('#icon').icon; + assertEquals('nearby-share:laptop', renderedIcon); + }); + + function testIcon(type, expected) { + const shareTarget = /** @type {!nearbyShare.mojom.ShareTarget} */ ({ + id: {high: 0, low: 0}, + name: 'Device Name', + type, + }); + deviceIconElement.shareTarget = shareTarget; + + const renderedIcon = deviceIconElement.$$('#icon').icon; + assertEquals(expected, renderedIcon); + } + + test('renders phone', function() { + testIcon(nearbyShare.mojom.ShareTargetType.kPhone, + 'nearby-share:smartphone'); + }); + + test('renders tablet', function() { + testIcon(nearbyShare.mojom.ShareTargetType.kTablet, 'nearby-share:tablet'); + }); + + test('renders laptop', function() { + testIcon(nearbyShare.mojom.ShareTargetType.kLaptop, 'nearby-share:laptop'); + }); + + test('renders unknown as laptop', function() { + testIcon(nearbyShare.mojom.ShareTargetType.kUnknown, 'nearby-share:laptop'); + }); +});
diff --git a/chrome/test/data/webui/nearby_share/nearby_device_test.js b/chrome/test/data/webui/nearby_share/shared/nearby_device_test.js similarity index 69% rename from chrome/test/data/webui/nearby_share/nearby_device_test.js rename to chrome/test/data/webui/nearby_share/shared/nearby_device_test.js index cf35399..692ad3e0 100644 --- a/chrome/test/data/webui/nearby_share/nearby_device_test.js +++ b/chrome/test/data/webui/nearby_share/shared/nearby_device_test.js
@@ -2,14 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// clang-format off // So that mojo is defined. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; - -import 'chrome://nearby/nearby_device.js'; -import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; - -import {assertEquals} from '../chai_assert.js'; +// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +// #import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; +// #import 'chrome://nearby/mojo/nearby_share_target_types.mojom-lite.js'; +// #import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; +// #import 'chrome://nearby/shared/nearby_device.m.js'; +// #import {assertEquals} from '../../chai_assert.js'; +// clang-format on suite('DeviceTest', function() { /** @type {!NearbyDeviceElement} */
diff --git a/chrome/test/data/webui/nearby_share/shared/nearby_page_template_test.js b/chrome/test/data/webui/nearby_share/shared/nearby_page_template_test.js index 6bef077..259358b5 100644 --- a/chrome/test/data/webui/nearby_share/shared/nearby_page_template_test.js +++ b/chrome/test/data/webui/nearby_share/shared/nearby_page_template_test.js
@@ -36,6 +36,7 @@ assertFalse(isVisible('#utilityButton')); assertFalse(isVisible('#actionButton')); assertFalse(isVisible('#cancelButton')); + assertFalse(isVisible('#closeButton')); }); test('Everything on', async function() { @@ -52,6 +53,7 @@ assertTrue(isVisible('#utilityButton')); assertTrue(isVisible('#actionButton')); assertTrue(isVisible('#cancelButton')); + assertFalse(isVisible('#closeButton')); /** @type {boolean} */ let utilityTriggered = false; @@ -74,4 +76,28 @@ element.$$('#actionButton').click(); assertTrue(actionTrigger); }); + + test('Close only', async function() { + element.title = 'title'; + element.subTitle = 'subTitle'; + element.utilityButtonLabel = 'utility'; + element.cancelButtonLabel = 'cancel'; + element.actionButtonLabel = 'action'; + element.closeOnly = true; + + await test_util.waitAfterNextRender(element); + + assertEquals('title', element.$$('#pageTitle').innerHTML.trim()); + assertEquals('subTitle', element.$$('#pageSubTitle').innerHTML.trim()); + assertFalse(isVisible('#utilityButton')); + assertFalse(isVisible('#actionButton')); + assertFalse(isVisible('#cancelButton')); + assertTrue(isVisible('#closeButton')); + + /** @type {boolean} */ + let closeTrigger = false; + element.addEventListener('close', () => closeTrigger = true); + element.$$('#closeButton').click(); + assertTrue(closeTrigger); + }); });
diff --git a/chrome/test/data/webui/nearby_share/nearby_progress_test.js b/chrome/test/data/webui/nearby_share/shared/nearby_progress_test.js similarity index 70% rename from chrome/test/data/webui/nearby_share/nearby_progress_test.js rename to chrome/test/data/webui/nearby_share/shared/nearby_progress_test.js index 4d18741..53b9b74 100644 --- a/chrome/test/data/webui/nearby_share/nearby_progress_test.js +++ b/chrome/test/data/webui/nearby_share/shared/nearby_progress_test.js
@@ -2,14 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// clang-format off // So that mojo is defined. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; - -import 'chrome://nearby/nearby_progress.js'; -import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; - -import {assertEquals} from '../chai_assert.js'; +// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +// #import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; +// #import 'chrome://nearby/mojo/nearby_share_target_types.mojom-lite.js'; +// #import 'chrome://nearby/mojo/nearby_share.mojom-lite.js'; +// #import 'chrome://nearby/shared/nearby_progress.m.js'; +// #import {assertEquals} from '../../chai_assert.js'; +// clang-format on suite('ProgressTest', function() { /** @type {!NearbyProgressElement} */
diff --git a/chrome/test/data/webui/nearby_share/shared/nearby_shared_browsertest.js b/chrome/test/data/webui/nearby_share/shared/nearby_shared_browsertest.js index 859cc8b..3c2f98a 100644 --- a/chrome/test/data/webui/nearby_share/shared/nearby_shared_browsertest.js +++ b/chrome/test/data/webui/nearby_share/shared/nearby_shared_browsertest.js
@@ -38,6 +38,41 @@ } }; +/** + * @extends {NearbySharedBrowserTest} + */ +var NearbyDeviceIconTest = class extends NearbySharedBrowserTest { + /** @override */ + get browsePreload() { + return super.browsePreload + 'shared/nearby_device_icon.html'; + } + /** @override */ + get extraLibraries() { + return super.extraLibraries.concat([ + 'nearby_device_icon_test.js', + ]); + } +}; + +TEST_F('NearbyDeviceIconTest', 'All', () => mocha.run()); + +/** + * @extends {NearbySharedBrowserTest} + */ +var NearbyDeviceTest = class extends NearbySharedBrowserTest { + /** @override */ + get browsePreload() { + return super.browsePreload + 'shared/nearby_device.html'; + } + /** @override */ + get extraLibraries() { + return super.extraLibraries.concat([ + 'nearby_device_test.js', + ]); + } +}; + +TEST_F('NearbyDeviceTest', 'All', () => mocha.run()); /** * @extends {NearbySharedBrowserTest} @@ -94,6 +129,24 @@ /** * @extends {NearbySharedBrowserTest} */ +var NearbyProgressTest = class extends NearbySharedBrowserTest { + /** @override */ + get browsePreload() { + return super.browsePreload + 'shared/nearby_progress.html'; + } + /** @override */ + get extraLibraries() { + return super.extraLibraries.concat([ + 'nearby_progress_test.js', + ]); + } +}; + +TEST_F('NearbyProgressTest', 'All', () => mocha.run()); + +/** + * @extends {NearbySharedBrowserTest} + */ var NearbyContactVisibilityTest = class extends NearbySharedBrowserTest { /** @override */ get browsePreload() {
diff --git a/chrome/test/data/webui/nearby_share/shared/nearby_shared_v3_browsertest.js b/chrome/test/data/webui/nearby_share/shared/nearby_shared_v3_browsertest.js index cf5207f4..1a85d23 100644 --- a/chrome/test/data/webui/nearby_share/shared/nearby_shared_v3_browsertest.js +++ b/chrome/test/data/webui/nearby_share/shared/nearby_shared_v3_browsertest.js
@@ -39,8 +39,11 @@ } }; -[['OnboardingPage', 'nearby_onboarding_page_test.m.js'], +[['DeviceIcon', 'nearby_device_icon_test.m.js'], + ['Device', 'nearby_device_test.m.js'], + ['OnboardingPage', 'nearby_onboarding_page_test.m.js'], ['PageTemplate', 'nearby_page_template_test.m.js'], + ['Progress', 'nearby_progress_test.m.js'], ['VisibilityPage', 'nearby_visibility_page_test.m.js'], ['ContactVisibility', 'nearby_contact_visibility_test.m.js'], ].forEach(test => registerTest(...test));
diff --git a/chrome/test/data/webui/new_tab_page/app_test.js b/chrome/test/data/webui/new_tab_page/app_test.js index 5da2218..260c57ea 100644 --- a/chrome/test/data/webui/new_tab_page/app_test.js +++ b/chrome/test/data/webui/new_tab_page/app_test.js
@@ -480,10 +480,12 @@ { id: 'foo', element: document.createElement('div'), + title: 'Foo Title', }, { id: 'bar', element: document.createElement('div'), + title: 'Bar Title', } ]); $$(app, 'ntp-middle-slot-promo') @@ -505,43 +507,45 @@ test('modules can be dismissed and restored', async () => { // Arrange. + let dismissCalled = false; let restoreCalled = false; - const moduleElement = document.createElement('div'); // Act. moduleResolver.resolve([{ id: 'foo', - element: moduleElement, + element: document.createElement('div'), + title: 'Foo Title', + actions: { + dismiss: () => { + dismissCalled = true; + return 'Foo was removed'; + }, + restore: () => { + restoreCalled = true; + }, + } }]); await flushTasks(); // Wait for module descriptor resolution. // Assert. const modules = app.shadowRoot.querySelectorAll('ntp-module-wrapper'); assertEquals(1, modules.length); + assertNotStyle($$(modules[0], '#dismissButton'), 'display', 'none'); assertFalse($$(app, '#dismissModuleToast').open); // Act. - moduleElement.dispatchEvent(new CustomEvent('dismiss-module', { - bubbles: true, - composed: true, - detail: { - message: 'Foo', - restoreCallback: _ => { - restoreCalled = true; - }, - }, - })); + $$(modules[0], '#dismissButton').click(); await flushTasks(); // Assert. assertTrue($$(app, '#dismissModuleToast').open); assertEquals( - 'Removed Foo', + 'Foo was removed', $$(app, '#dismissModuleToastMessage').textContent.trim()); assertNotStyle($$(app, '#undoDismissModuleButton'), 'display', 'none'); + assertTrue(dismissCalled); assertEquals( 'foo', await testProxy.handler.whenCalled('onDismissModule')); - assertFalse(restoreCalled); // Act. $$(app, '#undoDismissModuleButton').click();
diff --git a/chrome/test/data/webui/new_tab_page/modules/module_registry_test.js b/chrome/test/data/webui/new_tab_page/modules/module_registry_test.js index 0b4ac38..2792cc5 100644 --- a/chrome/test/data/webui/new_tab_page/modules/module_registry_test.js +++ b/chrome/test/data/webui/new_tab_page/modules/module_registry_test.js
@@ -12,7 +12,10 @@ const bazModule = document.createElement('div'); const bazModuleResolver = new PromiseResolver(); ModuleRegistry.getInstance().registerModules([ - new ModuleDescriptor('foo', 100, () => Promise.resolve(fooModule)), + new ModuleDescriptor('foo', 100, () => Promise.resolve({ + element: fooModule, + title: 'Foo Title', + })), new ModuleDescriptor('bar', 200, () => null), new ModuleDescriptor('baz', 300, () => bazModuleResolver.promise), ]); @@ -20,16 +23,21 @@ // Act. const modulesPromise = ModuleRegistry.getInstance().initializeModules(); // Delayed promise resolution to test async module instantiation. - bazModuleResolver.resolve(bazModule); + bazModuleResolver.resolve({ + element: bazModule, + title: 'Baz Title', + }); const modules = await modulesPromise; // Assert. assertEquals(2, modules.length); assertEquals('foo', modules[0].id); assertEquals(100, modules[0].heightPx); + assertEquals('Foo Title', modules[0].title); assertDeepEquals(fooModule, modules[0].element); assertEquals('baz', modules[1].id); assertEquals(300, modules[1].heightPx); + assertEquals('Baz Title', modules[1].title); assertDeepEquals(bazModule, modules[1].element); }); });
diff --git a/chrome/test/data/webui/new_tab_page/modules/module_wrapper_test.js b/chrome/test/data/webui/new_tab_page/modules/module_wrapper_test.js index 66ba2cf..f340bf9 100644 --- a/chrome/test/data/webui/new_tab_page/modules/module_wrapper_test.js +++ b/chrome/test/data/webui/new_tab_page/modules/module_wrapper_test.js
@@ -22,10 +22,12 @@ moduleWrapper.descriptor = { id: 'foo', heightPx: 100, + title: 'Foo Title', element: moduleElement, }; // Assert. + assertEquals('Foo Title', moduleWrapper.$.title.textContent); assertEquals(100, $$(moduleWrapper, '#moduleElement').offsetHeight); assertDeepEquals( moduleElement, $$(moduleWrapper, '#moduleElement').children[0]); @@ -36,12 +38,14 @@ moduleWrapper.descriptor = { id: 'foo', heightPx: 100, + title: 'Foo Title', element: moduleElement, }; assertThrows(() => { moduleWrapper.descriptor = { id: 'foo', heightPx: 100, + title: 'Foo Title', element: moduleElement, }; });
diff --git a/chrome/test/data/webui/new_tab_page/modules/task_module/module_test.js b/chrome/test/data/webui/new_tab_page/modules/task_module/module_test.js index 99a77f0e..dff5ed7 100644 --- a/chrome/test/data/webui/new_tab_page/modules/task_module/module_test.js +++ b/chrome/test/data/webui/new_tab_page/modules/task_module/module_test.js
@@ -4,7 +4,7 @@ import {shoppingTasksDescriptor, TaskModuleHandlerProxy} from 'chrome://new-tab-page/new_tab_page.js'; import {TestBrowserProxy} from 'chrome://test/test_browser_proxy.m.js'; -import {eventToPromise, flushTasks} from 'chrome://test/test_util.m.js'; +import {eventToPromise} from 'chrome://test/test_util.m.js'; suite('NewTabPageModulesTaskModuleTest', () => { /** @@ -180,30 +180,25 @@ }; testProxy.handler.setResultFor('getPrimaryTask', Promise.resolve({task})); - // Arrange. - await shoppingTasksDescriptor.initialize(); - const moduleElement = shoppingTasksDescriptor.element; - document.body.append(moduleElement); - await flushTasks(); // Act. - const waitForDismissEvent = eventToPromise('dismiss-module', moduleElement); - const dismissButton = - moduleElement.shadowRoot.querySelector('ntp-module-header') - .shadowRoot.querySelector('#dismissButton'); - dismissButton.click(); - const dismissEvent = await waitForDismissEvent; - const toastMessage = dismissEvent.detail.message; - const restoreCallback = dismissEvent.detail.restoreCallback; + await shoppingTasksDescriptor.initialize(); // Assert. - assertEquals('Hello world', toastMessage); + assertEquals('function', typeof shoppingTasksDescriptor.actions.dismiss); + assertEquals('function', typeof shoppingTasksDescriptor.actions.restore); + + // Act. + const toastMessage = shoppingTasksDescriptor.actions.dismiss(); + + // Assert. + assertEquals('Removed Hello world', toastMessage); assertDeepEquals( [taskModule.mojom.TaskModuleType.kShopping, 'Hello world'], await testProxy.handler.whenCalled('dismissTask')); // Act. - restoreCallback(); + shoppingTasksDescriptor.actions.restore(); // Assert. assertDeepEquals(
diff --git a/chrome/test/data/webui/settings/chromeos/switch_access_subpage_tests.js b/chrome/test/data/webui/settings/chromeos/switch_access_subpage_tests.js index ba30c74a..122cc154 100644 --- a/chrome/test/data/webui/settings/chromeos/switch_access_subpage_tests.js +++ b/chrome/test/data/webui/settings/chromeos/switch_access_subpage_tests.js
@@ -95,6 +95,19 @@ settings.Router.getInstance().resetRouteForTesting(); }); + /** + * @param {!Array<string>} switches New switch assignments for select action. + * @return {string} Sub-label text from the select link row. + */ + function getSublabelForSelectUpdates(switches) { + cr.webUIListenerCallback( + 'switch-access-assignments-changed', + {select: switches, next: [], previous: []}); + + return page.$$('#selectLinkRow').$$('#subLabel').textContent.trim(); + } + + test('Switch assignment key display', function() { initPage(); @@ -113,6 +126,32 @@ assertEquals(0, page.previousAssignments_.length); }); + test('Switch assignment sub-labels', function() { + initPage(); + + assertEquals('0 switches assigned', getSublabelForSelectUpdates([])); + assertEquals('Backspace', getSublabelForSelectUpdates(['Backspace'])); + assertEquals( + 'Backspace, Tab', getSublabelForSelectUpdates(['Backspace', 'Tab'])); + assertEquals( + 'Backspace, Tab, Enter', + getSublabelForSelectUpdates(['Backspace', 'Tab', 'Enter'])); + assertEquals( + 'Backspace, Tab, Enter, and 1 more switch', + getSublabelForSelectUpdates(['Backspace', 'Tab', 'Enter', 'a'])); + assertEquals( + 'Backspace, Tab, Enter, and 2 more switches', + getSublabelForSelectUpdates(['Backspace', 'Tab', 'Enter', 'a', 'b'])); + assertEquals( + 'Backspace, Tab, Enter, and 3 more switches', + getSublabelForSelectUpdates( + ['Backspace', 'Tab', 'Enter', 'a', 'b', 'c'])); + assertEquals( + 'Backspace, Tab, Enter, and 4 more switches', + getSublabelForSelectUpdates( + ['Backspace', 'Tab', 'Enter', 'a', 'b', 'c', 'd'])); + }); + test('Switch access action assignment dialog', async function() { initPage();
diff --git a/chrome/third_party/DIR_METADATA b/chrome/third_party/DIR_METADATA new file mode 100644 index 0000000..9cfc120 --- /dev/null +++ b/chrome/third_party/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "A-N/A" +}
diff --git a/chrome/third_party/OWNERS b/chrome/third_party/OWNERS deleted file mode 100644 index 0bad6a2..0000000 --- a/chrome/third_party/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: A-N/A
diff --git a/chrome/third_party/mozilla_security_manager/DIR_METADATA b/chrome/third_party/mozilla_security_manager/DIR_METADATA new file mode 100644 index 0000000..0ca0a96 --- /dev/null +++ b/chrome/third_party/mozilla_security_manager/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Network>Certificate" +}
diff --git a/chrome/third_party/mozilla_security_manager/OWNERS b/chrome/third_party/mozilla_security_manager/OWNERS index 31a5940..79dbd13 100644 --- a/chrome/third_party/mozilla_security_manager/OWNERS +++ b/chrome/third_party/mozilla_security_manager/OWNERS
@@ -1,4 +1,3 @@ mattm@chromium.org rsleevi@chromium.org wtc@chromium.org -# COMPONENT: Internals>Network>Certificate
diff --git a/chrome/tools/DIR_METADATA b/chrome/tools/DIR_METADATA new file mode 100644 index 0000000..a6143e7 --- /dev/null +++ b/chrome/tools/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "UI>Shell" +}
diff --git a/chrome/tools/OWNERS b/chrome/tools/OWNERS deleted file mode 100644 index 036a36bd..0000000 --- a/chrome/tools/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: UI>Shell
diff --git a/chrome/tools/build/mac/DIR_METADATA b/chrome/tools/build/mac/DIR_METADATA new file mode 100644 index 0000000..a406931 --- /dev/null +++ b/chrome/tools/build/mac/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail: { + component: "Build" +} +team_email: "build@chromium.org"
diff --git a/chrome/tools/build/mac/OWNERS b/chrome/tools/build/mac/OWNERS index 759521d..163563f9 100644 --- a/chrome/tools/build/mac/OWNERS +++ b/chrome/tools/build/mac/OWNERS
@@ -1,5 +1,2 @@ mark@chromium.org rsesek@chromium.org - -# TEAM: build@chromium.org -# COMPONENT: Build
diff --git a/chrome/tools/build/win/DIR_METADATA b/chrome/tools/build/win/DIR_METADATA new file mode 100644 index 0000000..a406931 --- /dev/null +++ b/chrome/tools/build/win/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail: { + component: "Build" +} +team_email: "build@chromium.org"
diff --git a/chrome/tools/build/win/OWNERS b/chrome/tools/build/win/OWNERS index e6b4b8f..9b598b1 100644 --- a/chrome/tools/build/win/OWNERS +++ b/chrome/tools/build/win/OWNERS
@@ -6,6 +6,3 @@ # FILES.cfg OWNERS as in parent owner file. per-file FILES.cfg=kerz@chromium.org per-file FILES.cfg=mmoss@chromium.org - -# TEAM: build@chromium.org -# COMPONENT: Build
diff --git a/chrome/tools/convert_dict/DIR_METADATA b/chrome/tools/convert_dict/DIR_METADATA new file mode 100644 index 0000000..079a366 --- /dev/null +++ b/chrome/tools/convert_dict/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals" +}
diff --git a/chrome/tools/convert_dict/OWNERS b/chrome/tools/convert_dict/OWNERS deleted file mode 100644 index f136fc1..0000000 --- a/chrome/tools/convert_dict/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Internals
diff --git a/chrome/tools/safe_browsing/DIR_METADATA b/chrome/tools/safe_browsing/DIR_METADATA new file mode 100644 index 0000000..1864297 --- /dev/null +++ b/chrome/tools/safe_browsing/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Services>Safebrowsing" +}
diff --git a/chrome/tools/safe_browsing/OWNERS b/chrome/tools/safe_browsing/OWNERS deleted file mode 100644 index 85d233d..0000000 --- a/chrome/tools/safe_browsing/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Services>Safebrowsing
diff --git a/chrome/tools/service_discovery_sniffer/DIR_METADATA b/chrome/tools/service_discovery_sniffer/DIR_METADATA new file mode 100644 index 0000000..7619ec17e --- /dev/null +++ b/chrome/tools/service_discovery_sniffer/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Services>CloudPrint" +}
diff --git a/chrome/tools/service_discovery_sniffer/OWNERS b/chrome/tools/service_discovery_sniffer/OWNERS index 3b8d2d0..be0f423b 100644 --- a/chrome/tools/service_discovery_sniffer/OWNERS +++ b/chrome/tools/service_discovery_sniffer/OWNERS
@@ -1,3 +1 @@ file://cloud_print/OWNERS - -# COMPONENT: Services>CloudPrint
diff --git a/chrome/tools/test/DIR_METADATA b/chrome/tools/test/DIR_METADATA new file mode 100644 index 0000000..9b3e0b2 --- /dev/null +++ b/chrome/tools/test/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Tests" +}
diff --git a/chrome/tools/test/OWNERS b/chrome/tools/test/OWNERS deleted file mode 100644 index 15fbac6..0000000 --- a/chrome/tools/test/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Tests
diff --git a/chrome/tools/tracing/DIR_METADATA b/chrome/tools/tracing/DIR_METADATA new file mode 100644 index 0000000..4eae747 --- /dev/null +++ b/chrome/tools/tracing/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Speed>Tracing" +}
diff --git a/chrome/tools/tracing/OWNERS b/chrome/tools/tracing/OWNERS deleted file mode 100644 index 804c7d45..0000000 --- a/chrome/tools/tracing/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -# COMPONENT: Speed>Tracing
diff --git a/chrome/updater/update_service_internal_impl.cc b/chrome/updater/update_service_internal_impl.cc index 6742d226..c9b8589 100644 --- a/chrome/updater/update_service_internal_impl.cc +++ b/chrome/updater/update_service_internal_impl.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" +#include "base/containers/queue.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" @@ -27,29 +28,96 @@ #include "components/update_client/update_client.h" namespace updater { +namespace { -UpdateServiceInternalImpl::UpdateServiceInternalImpl( - scoped_refptr<updater::Configurator> config) +class CheckForUpdatesTask : public UpdateServiceInternalImpl::Task { + public: + CheckForUpdatesTask(scoped_refptr<updater::Configurator> config, + base::OnceClosure callback); + void Run() override; + + // Provides a way to remove apps from the persisted data if the app is no + // longer installed on the machine. + void UnregisterMissingApps(); + + private: + ~CheckForUpdatesTask() override = default; + + struct AppInfo { + AppInfo(const std::string& app_id, + const base::Version& app_version, + const base::FilePath& ecp) + : app_id_(app_id), app_version_(app_version), ecp_(ecp) {} + std::string app_id_; + base::Version app_version_; + base::FilePath ecp_; + }; + + struct PingInfo { + PingInfo(const std::string& app_id, + const base::Version& app_version, + int ping_reason) + : app_id_(app_id), + app_version_(app_version), + ping_reason_(ping_reason) {} + std::string app_id_; + base::Version app_version_; + int ping_reason_; + }; + + // Returns a list of apps registered with the updater. + std::vector<AppInfo> GetRegisteredApps(); + + // Returns a list of apps that need to be unregistered. + std::vector<PingInfo> GetAppIDsToRemove(const std::vector<AppInfo>& apps); + + // Callback to run after a `MaybeCheckForUpdates` has finished. + // Triggers the completion of the whole task. + void MaybeCheckForUpdatesDone(); + + // Unregisters the apps in `app_ids_to_remove` and starts an update check + // if necessary. + void RemoveAppIDsAndSendUninstallPings( + const std::vector<PingInfo>& app_ids_to_remove); + + // After an uninstall ping has been processed, reduces the number of pings + // that we need to wait on before checking for updates. + void UninstallPingSent(update_client::Error error); + + // Returns true if there are uninstall ping tasks which haven't finished. + // Returns false if `number_of_pings_remaining_` is 0. + // `number_of_pings_remaining_` is only updated on the tasks's sequence. + bool WaitingOnUninstallPings() const; + + // Checks for updates of all registered applications if it has been longer + // than the last check time by NextCheckDelay() amount defined in the + // config. + void MaybeCheckForUpdates(); + + // Callback to run after `UnregisterMissingApps` has finished. + // Triggers `MaybeCheckForUpdates`. + void UnregisterMissingAppsDone(); + + SEQUENCE_CHECKER(sequence_checker_); + scoped_refptr<updater::Configurator> config_; + scoped_refptr<updater::PersistedData> persisted_data_; + scoped_refptr<update_client::UpdateClient> update_client_; + base::OnceClosure callback_; + int number_of_pings_remaining_; +}; + +CheckForUpdatesTask::CheckForUpdatesTask( + scoped_refptr<updater::Configurator> config, + base::OnceClosure callback) : config_(config), persisted_data_( base::MakeRefCounted<PersistedData>(config_->GetPrefService())), update_client_(update_client::UpdateClientFactory(config_)), + callback_(std::move(callback)), number_of_pings_remaining_(0) {} -void UpdateServiceInternalImpl::Run(base::OnceClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - callback_ = std::move(callback); - UnregisterMissingApps(GetRegisteredApps()); -} - -void UpdateServiceInternalImpl::InitializeUpdateService( - base::OnceClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::move(callback).Run(); -} - -std::vector<UpdateServiceInternalImpl::AppInfo> -UpdateServiceInternalImpl::GetRegisteredApps() { +std::vector<CheckForUpdatesTask::AppInfo> +CheckForUpdatesTask::GetRegisteredApps() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::vector<AppInfo> apps_to_unregister; @@ -66,12 +134,12 @@ return apps_to_unregister; } -bool UpdateServiceInternalImpl::WaitingOnUninstallPings() const { +bool CheckForUpdatesTask::WaitingOnUninstallPings() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return number_of_pings_remaining_ > 0; } -void UpdateServiceInternalImpl::MaybeCheckForUpdates() { +void CheckForUpdatesTask::MaybeCheckForUpdates() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); scoped_refptr<UpdateServiceImpl> update_service = base::MakeRefCounted<UpdateServiceImpl>(config_); @@ -86,8 +154,9 @@ base::TimeDelta::FromSeconds(config_->NextCheckDelay())) { VLOG(0) << "Skipping checking for updates: " << timeSinceUpdate.InMinutes(); - base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, - std::move(callback_)); + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&CheckForUpdatesTask::MaybeCheckForUpdatesDone, this)); return; } @@ -105,27 +174,33 @@ } std::move(closure).Run(); }, - base::BindOnce(std::move(callback_)), config_)); + base::BindOnce(&CheckForUpdatesTask::MaybeCheckForUpdatesDone, this), + config_)); } -void UpdateServiceInternalImpl::UnregisterMissingApps( - const std::vector<AppInfo>& apps) { +void CheckForUpdatesTask::MaybeCheckForUpdatesDone() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + std::move(callback_).Run(); +} + +void CheckForUpdatesTask::UnregisterMissingApps() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, - base::BindOnce(&UpdateServiceInternalImpl::GetAppIDsToRemove, this, apps), - base::BindOnce( - &UpdateServiceInternalImpl::RemoveAppIDsAndSendUninstallPings, this)); + base::BindOnce(&CheckForUpdatesTask::GetAppIDsToRemove, this, + GetRegisteredApps()), + base::BindOnce(&CheckForUpdatesTask::RemoveAppIDsAndSendUninstallPings, + this)); } -void UpdateServiceInternalImpl::UnregisterMissingAppsDone() { +void CheckForUpdatesTask::UnregisterMissingAppsDone() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); MaybeCheckForUpdates(); } -std::vector<UpdateServiceInternalImpl::PingInfo> -UpdateServiceInternalImpl::GetAppIDsToRemove(const std::vector<AppInfo>& apps) { +std::vector<CheckForUpdatesTask::PingInfo> +CheckForUpdatesTask::GetAppIDsToRemove(const std::vector<AppInfo>& apps) { std::vector<PingInfo> app_ids_to_remove; for (const auto& app : apps) { // Skip if app_id is equal to updater app id. @@ -144,7 +219,12 @@ return app_ids_to_remove; } -void UpdateServiceInternalImpl::RemoveAppIDsAndSendUninstallPings( +void CheckForUpdatesTask::Run() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + UnregisterMissingApps(); +} + +void CheckForUpdatesTask::RemoveAppIDsAndSendUninstallPings( const std::vector<PingInfo>& app_ids_to_remove) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -161,28 +241,66 @@ if (persisted_data_->RemoveApp(app_id)) { VLOG(1) << "Uninstall ping for app id: " << app_id << ". Ping reason: " << ping_reason; - number_of_pings_remaining_++; + ++number_of_pings_remaining_; update_client_->SendUninstallPing( app_id, app_version, ping_reason, - base::BindOnce(&UpdateServiceInternalImpl::UninstallPingSent, this)); + base::BindOnce(&CheckForUpdatesTask::UninstallPingSent, this)); } else { VLOG(0) << "Could not remove registration of app " << app_id; } } } -void UpdateServiceInternalImpl::UninstallPingSent(update_client::Error error) { - number_of_pings_remaining_--; +void CheckForUpdatesTask::UninstallPingSent(update_client::Error error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + --number_of_pings_remaining_; if (error != update_client::Error::NONE) VLOG(0) << __func__ << ": Error: " << static_cast<int>(error); if (!WaitingOnUninstallPings()) - std::move(base::BindOnce( - &UpdateServiceInternalImpl::UnregisterMissingAppsDone, this)) + std::move( + base::BindOnce(&CheckForUpdatesTask::UnregisterMissingAppsDone, this)) .Run(); } +} // namespace + +UpdateServiceInternalImpl::UpdateServiceInternalImpl( + scoped_refptr<updater::Configurator> config) + : config_(config) {} + +void UpdateServiceInternalImpl::Run(base::OnceClosure callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + auto task = base::MakeRefCounted<CheckForUpdatesTask>( + config_, base::BindOnce(&UpdateServiceInternalImpl::TaskDone, this, + std::move(callback))); + // Queues the task to be run. If no other tasks are running, runs the task. + tasks_.push(task); + if (tasks_.size() == 1) + RunNextTask(); +} + +void UpdateServiceInternalImpl::InitializeUpdateService( + base::OnceClosure callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + std::move(callback).Run(); +} + +void UpdateServiceInternalImpl::TaskDone(base::OnceClosure callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + std::move(callback).Run(); + tasks_.pop(); + RunNextTask(); +} + +void UpdateServiceInternalImpl::RunNextTask() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!tasks_.empty()) { + tasks_.front()->Run(); + } +} + void UpdateServiceInternalImpl::Uninitialize() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); PrefsCommitPendingWrites(config_->GetPrefService());
diff --git a/chrome/updater/update_service_internal_impl.h b/chrome/updater/update_service_internal_impl.h index aaa3f377..3527ed9 100644 --- a/chrome/updater/update_service_internal_impl.h +++ b/chrome/updater/update_service_internal_impl.h
@@ -10,21 +10,16 @@ #include "base/callback.h" #include "base/callback_forward.h" +#include "base/containers/queue.h" #include "base/files/file_path.h" #include "base/memory/scoped_refptr.h" #include "base/sequence_checker.h" #include "base/version.h" #include "chrome/updater/update_service_internal.h" -namespace update_client { -enum class Error; -class UpdateClient; -} // namespace update_client - namespace updater { class Configurator; -class PersistedData; // All functions and callbacks must be called on the same sequence. class UpdateServiceInternalImpl : public UpdateServiceInternal { @@ -38,68 +33,30 @@ void Uninitialize() override; + class Task : public base::RefCountedThreadSafe<Task> { + public: + virtual void Run() = 0; + + protected: + friend class base::RefCountedThreadSafe<Task>; + + virtual ~Task() = default; + }; + + // Callback to run after a `Task` has finished. + void TaskDone(base::OnceClosure callback); + private: ~UpdateServiceInternalImpl() override; + void RunNextTask(); + SEQUENCE_CHECKER(sequence_checker_); - - struct AppInfo { - AppInfo(const std::string& app_id, - const base::Version& app_version, - const base::FilePath& ecp) - : app_id_(app_id), app_version_(app_version), ecp_(ecp) {} - std::string app_id_; - base::Version app_version_; - base::FilePath ecp_; - }; - - struct PingInfo { - PingInfo(const std::string& app_id, - const base::Version& app_version, - int ping_reason) - : app_id_(app_id), - app_version_(app_version), - ping_reason_(ping_reason) {} - std::string app_id_; - base::Version app_version_; - int ping_reason_; - }; - - // Checks for updates of all registered applications if it has been longer - // than the last check time by NextCheckDelay() amount defined in the config. - void MaybeCheckForUpdates(); - - // Returns a list of apps registered with the updater. - std::vector<AppInfo> GetRegisteredApps(); - - void UnregisterMissingAppsDone(); - - // Provides a way to remove apps from the persisted data if the app is no - // longer installed on the machine. - void UnregisterMissingApps(const std::vector<AppInfo>& apps); - - // After an uninstall ping has been processed, reduces the number of pings - // that we need to wait on before checking for updates. - void UninstallPingSent(update_client::Error error); - - // Returns true if there are uninstall ping tasks which haven't finished. - // Returns false if |number_of_pings_remaining_| is 0. - bool WaitingOnUninstallPings() const; - - // Returns a list of apps that need to be unregistered. - std::vector<UpdateServiceInternalImpl::PingInfo> GetAppIDsToRemove( - const std::vector<AppInfo>& apps); - - // Unregisters the apps in |app_ids_to_remove| and starts an update check - // if necessary. - void RemoveAppIDsAndSendUninstallPings( - const std::vector<PingInfo>& app_ids_to_remove); - scoped_refptr<updater::Configurator> config_; - scoped_refptr<updater::PersistedData> persisted_data_; - scoped_refptr<update_client::UpdateClient> update_client_; - base::OnceClosure callback_; - int number_of_pings_remaining_; + + // The queue prevents multiple Task instances from running simultaneously and + // processes them sequentially. + base::queue<scoped_refptr<Task>> tasks_; }; } // namespace updater
diff --git a/chrome/utility/DIR_METADATA b/chrome/utility/DIR_METADATA new file mode 100644 index 0000000..26cbc57 --- /dev/null +++ b/chrome/utility/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Services" +}
diff --git a/chrome/utility/OWNERS b/chrome/utility/OWNERS index 37c88a25..09560c0 100644 --- a/chrome/utility/OWNERS +++ b/chrome/utility/OWNERS
@@ -7,5 +7,3 @@ per-file services.*=rockot@google.com per-file browser_exposed_utility_interfaces.cc=set noparent per-file browser_exposed_utility_interfaces.cc=file://ipc/SECURITY_OWNERS - -# COMPONENT: Internals>Services
diff --git a/chrome/utility/importer/DIR_METADATA b/chrome/utility/importer/DIR_METADATA new file mode 100644 index 0000000..9730c88 --- /dev/null +++ b/chrome/utility/importer/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "UI>Browser>Import" +}
diff --git a/chrome/utility/importer/OWNERS b/chrome/utility/importer/OWNERS index c4d478c..2e18838e 100644 --- a/chrome/utility/importer/OWNERS +++ b/chrome/utility/importer/OWNERS
@@ -6,5 +6,3 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS - -# COMPONENT: UI>Browser>Import
diff --git a/chrome/utility/safe_browsing/DIR_METADATA b/chrome/utility/safe_browsing/DIR_METADATA new file mode 100644 index 0000000..1864297 --- /dev/null +++ b/chrome/utility/safe_browsing/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Services>Safebrowsing" +}
diff --git a/chrome/utility/safe_browsing/OWNERS b/chrome/utility/safe_browsing/OWNERS index fede9e2..70e4b68 100644 --- a/chrome/utility/safe_browsing/OWNERS +++ b/chrome/utility/safe_browsing/OWNERS
@@ -1,5 +1,3 @@ drubery@chromium.org nparker@chromium.org vakh@chromium.org - -# COMPONENT: Services>Safebrowsing
diff --git a/chromecast/browser/BUILD.gn b/chromecast/browser/BUILD.gn index 5903109e..2e11eee 100644 --- a/chromecast/browser/BUILD.gn +++ b/chromecast/browser/BUILD.gn
@@ -159,6 +159,7 @@ "service/cast_service_simple.h", "service_connector.cc", "service_connector.h", + "service_manager_connection.cc", "service_manager_connection.h", "service_manager_context.cc", "service_manager_context.h",
diff --git a/chromecast/browser/extensions/cast_extensions_browser_client.cc b/chromecast/browser/extensions/cast_extensions_browser_client.cc index 0cc9311..7847aed 100644 --- a/chromecast/browser/extensions/cast_extensions_browser_client.cc +++ b/chromecast/browser/extensions/cast_extensions_browser_client.cc
@@ -134,7 +134,7 @@ bool CastExtensionsBrowserClient::AllowCrossRendererResourceLoad( const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito, @@ -143,7 +143,7 @@ const ProcessMap& process_map) { bool allowed = false; if (url_request_util::AllowCrossRendererResourceLoad( - request, resource_type, page_transition, child_id, is_incognito, + request, destination, page_transition, child_id, is_incognito, extension, extensions, process_map, &allowed)) { return allowed; }
diff --git a/chromecast/browser/extensions/cast_extensions_browser_client.h b/chromecast/browser/extensions/cast_extensions_browser_client.h index 81951664..99be42f 100644 --- a/chromecast/browser/extensions/cast_extensions_browser_client.h +++ b/chromecast/browser/extensions/cast_extensions_browser_client.h
@@ -14,6 +14,7 @@ #include "extensions/browser/kiosk/kiosk_delegate.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" class PrefService; @@ -71,14 +72,15 @@ const std::string& content_security_policy, mojo::PendingRemote<network::mojom::URLLoaderClient> client, bool send_cors_header) override; - bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map) override; + bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map) override; PrefService* GetPrefServiceForContext( content::BrowserContext* context) override; void GetEarlyExtensionPrefsObservers(
diff --git a/chromecast/browser/service_manager_connection.cc b/chromecast/browser/service_manager_connection.cc new file mode 100644 index 0000000..8657eda --- /dev/null +++ b/chromecast/browser/service_manager_connection.cc
@@ -0,0 +1,229 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/browser/service_manager_connection.h" + +#include <map> +#include <queue> +#include <utility> +#include <vector> + +#include "base/bind.h" +#include "base/macros.h" +#include "base/no_destructor.h" +#include "base/task/current_thread.h" +#include "base/thread_annotations.h" +#include "base/threading/thread_checker.h" +#include "base/threading/thread_task_runner_handle.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "services/service_manager/public/cpp/service.h" +#include "services/service_manager/public/cpp/service_receiver.h" +#include "services/service_manager/public/mojom/constants.mojom.h" +#include "services/service_manager/public/mojom/interface_provider.mojom.h" + +namespace chromecast { +namespace { + +std::unique_ptr<ServiceManagerConnection>& GetConnectionForProcess() { + static base::NoDestructor<std::unique_ptr<ServiceManagerConnection>> + connection; + return *connection; +} + +} // namespace + +// A ref-counted object which owns the IO thread state of a +// ServiceManagerConnection. This includes Service and ServiceFactory +// bindings. +class ServiceManagerConnection::IOThreadContext + : public base::RefCountedThreadSafe<IOThreadContext>, + public service_manager::Service { + public: + IOThreadContext( + mojo::PendingReceiver<service_manager::mojom::Service> service_receiver, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, + mojo::PendingReceiver<service_manager::mojom::Connector> + connector_receiver) + : pending_service_receiver_(std::move(service_receiver)), + io_task_runner_(io_task_runner), + pending_connector_receiver_(std::move(connector_receiver)) { + // This will be reattached by any of the IO thread functions on first call. + io_thread_checker_.DetachFromThread(); + } + + // Safe to call from any thread. + void Start() { + DCHECK(!started_); + + started_ = true; + io_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&IOThreadContext::StartOnIOThread, this)); + } + + // Safe to call from whichever thread called Start() (or may have called + // Start()). Must be called before IO thread shutdown. + void ShutDown() { + if (!started_) + return; + + bool posted = io_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&IOThreadContext::ShutDownOnIOThread, this)); + DCHECK(posted); + } + + private: + friend class base::RefCountedThreadSafe<IOThreadContext>; + + class MessageLoopObserver : public base::CurrentThread::DestructionObserver { + public: + explicit MessageLoopObserver(base::WeakPtr<IOThreadContext> context) + : context_(context) { + base::CurrentThread::Get()->AddDestructionObserver(this); + } + + ~MessageLoopObserver() override { + base::CurrentThread::Get()->RemoveDestructionObserver(this); + } + + void ShutDown() { + if (!is_active_) + return; + + // The call into |context_| below may reenter ShutDown(), hence we set + // |is_active_| to false here. + is_active_ = false; + if (context_) + context_->ShutDownOnIOThread(); + + delete this; + } + + private: + void WillDestroyCurrentMessageLoop() override { + DCHECK(is_active_); + ShutDown(); + } + + bool is_active_ = true; + base::WeakPtr<IOThreadContext> context_; + + DISALLOW_COPY_AND_ASSIGN(MessageLoopObserver); + }; + + ~IOThreadContext() override {} + + void StartOnIOThread() { + // Should bind |io_thread_checker_| to the context's thread. + DCHECK(io_thread_checker_.CalledOnValidThread()); + service_receiver_ = std::make_unique<service_manager::ServiceReceiver>( + this, std::move(pending_service_receiver_)); + service_receiver_->GetConnector()->BindConnectorReceiver( + std::move(pending_connector_receiver_)); + + // MessageLoopObserver owns itself. + message_loop_observer_ = + new MessageLoopObserver(weak_factory_.GetWeakPtr()); + } + + void ShutDownOnIOThread() { + DCHECK(io_thread_checker_.CalledOnValidThread()); + + weak_factory_.InvalidateWeakPtrs(); + + // Note that this method may be invoked by MessageLoopObserver observing + // MessageLoop destruction. In that case, this call to ShutDown is + // effectively a no-op. In any case it's safe. + if (message_loop_observer_) { + message_loop_observer_->ShutDown(); + message_loop_observer_ = nullptr; + } + + // Resetting the ServiceContext below may otherwise release the last + // reference to this IOThreadContext. We keep it alive until the stack + // unwinds. + scoped_refptr<IOThreadContext> keepalive(this); + + service_receiver_.reset(); + } + + ///////////////////////////////////////////////////////////////////////////// + // service_manager::Service implementation + + void OnBindInterface(const service_manager::BindSourceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe) override {} + + base::ThreadChecker io_thread_checker_; + bool started_ = false; + + // Temporary state established on construction and consumed on the IO thread + // once the connection is started. + mojo::PendingReceiver<service_manager::mojom::Service> + pending_service_receiver_; + scoped_refptr<base::SequencedTaskRunner> io_task_runner_; + mojo::PendingReceiver<service_manager::mojom::Connector> + pending_connector_receiver_; + + // TaskRunner on which to run our owner's callbacks, i.e. the ones passed to + // Start(). + std::unique_ptr<service_manager::ServiceReceiver> service_receiver_; + + // Not owned. + MessageLoopObserver* message_loop_observer_ = nullptr; + + base::WeakPtrFactory<IOThreadContext> weak_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(IOThreadContext); +}; + +// static +void ServiceManagerConnection::SetForProcess( + std::unique_ptr<ServiceManagerConnection> connection) { + DCHECK(!GetConnectionForProcess()); + GetConnectionForProcess() = std::move(connection); +} + +// static +ServiceManagerConnection* ServiceManagerConnection::GetForProcess() { + return GetConnectionForProcess().get(); +} + +// static +void ServiceManagerConnection::DestroyForProcess() { + // This joins the service manager controller thread. + GetConnectionForProcess().reset(); +} + +// static +std::unique_ptr<ServiceManagerConnection> ServiceManagerConnection::Create( + mojo::PendingReceiver<service_manager::mojom::Service> receiver, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) { + return std::make_unique<ServiceManagerConnection>(std::move(receiver), + io_task_runner); +} + +ServiceManagerConnection::ServiceManagerConnection( + mojo::PendingReceiver<service_manager::mojom::Service> receiver, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) { + mojo::PendingReceiver<service_manager::mojom::Connector> connector_receiver; + connector_ = service_manager::Connector::Create(&connector_receiver); + context_ = new IOThreadContext(std::move(receiver), io_task_runner, + std::move(connector_receiver)); +} + +ServiceManagerConnection::~ServiceManagerConnection() { + context_->ShutDown(); +} + +void ServiceManagerConnection::Start() { + context_->Start(); +} + +service_manager::Connector* ServiceManagerConnection::GetConnector() { + return connector_.get(); +} + +} // namespace chromecast
diff --git a/chromecast/browser/service_manager_connection.h b/chromecast/browser/service_manager_connection.h index 5d2f499..65ce667 100644 --- a/chromecast/browser/service_manager_connection.h +++ b/chromecast/browser/service_manager_connection.h
@@ -5,13 +5,82 @@ #ifndef CHROMECAST_BROWSER_SERVICE_MANAGER_CONNECTION_H_ #define CHROMECAST_BROWSER_SERVICE_MANAGER_CONNECTION_H_ -#include "content/public/common/service_manager_connection.h" +#include <memory> +#include <string> + +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "services/service_manager/public/cpp/identity.h" +#include "services/service_manager/public/cpp/service.h" +#include "services/service_manager/public/mojom/connector.mojom-forward.h" +#include "services/service_manager/public/mojom/service.mojom-forward.h" + +namespace service_manager { +class Connector; +} namespace chromecast { -// Temporary alias until the downstream internal repository can update its -// #includes to reference this file rather than the one in Content. -using ServiceManagerConnection = content::ServiceManagerConnection; +// Encapsulates a connection to a //services/service_manager. +// Access a global instance on the thread the ServiceContext was bound by +// calling Holder::Get(). +// Clients can add service_manager::Service implementations whose exposed +// interfaces +// will be exposed to inbound connections to this object's Service. +// Alternatively clients can define named services that will be constructed when +// requests for those service names are received. +class ServiceManagerConnection { + public: + ServiceManagerConnection( + mojo::PendingReceiver<service_manager::mojom::Service> receiver, + scoped_refptr<base::SequencedTaskRunner> io_task_runner); + ServiceManagerConnection(const ServiceManagerConnection&) = delete; + ServiceManagerConnection& operator=(const ServiceManagerConnection) = delete; + ~ServiceManagerConnection(); + + // Stores an instance of |connection| in TLS for the current process. Must be + // called on the thread the connection was created on. + static void SetForProcess( + std::unique_ptr<ServiceManagerConnection> connection); + + // Returns the per-process instance, or nullptr if the Service Manager + // connection has not yet been bound. Must be called on the thread the + // connection was created on. + static ServiceManagerConnection* GetForProcess(); + + // Destroys the per-process instance. Must be called on the thread the + // connection was created on. + static void DestroyForProcess(); + + // Creates a ServiceManagerConnection from |request|. The connection binds + // its interfaces and accept new connections on |io_task_runner| only. Note + // that no incoming connections are accepted until Start() is called. + static std::unique_ptr<ServiceManagerConnection> Create( + mojo::PendingReceiver<service_manager::mojom::Service> receiver, + scoped_refptr<base::SequencedTaskRunner> io_task_runner); + + // Begins accepting incoming connections. + void Start(); + + // Returns the service_manager::Connector received via this connection's + // Service + // implementation. Use this to initiate connections as this object's Identity. + service_manager::Connector* GetConnector(); + + private: + class IOThreadContext; + + void OnConnectionLost(); + void GetInterface(service_manager::mojom::InterfaceProvider* provider, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle); + + std::unique_ptr<service_manager::Connector> connector_; + scoped_refptr<IOThreadContext> context_; + base::WeakPtrFactory<ServiceManagerConnection> weak_factory_{this}; +}; } // namespace chromecast
diff --git a/chromecast/media/cma/BUILD.gn b/chromecast/media/cma/BUILD.gn index c8a5287..907c72e 100644 --- a/chromecast/media/cma/BUILD.gn +++ b/chromecast/media/cma/BUILD.gn
@@ -79,8 +79,18 @@ # Building the required proto files here cause a linker issue on # Android because both protobuf_full and protobuf_lite get included. if (!is_android) { - sources += [ "backend/proxy/cma_backend_proxy_unittest.cc" ] - deps += [ "//chromecast/media/cma/backend/proxy" ] + sources += [ + "backend/proxy/cma_backend_proxy_unittest.cc", + "backend/proxy/proxy_call_translator_unittest.cc", + "backend/proxy/push_buffer_queue_unittest.cc", + ] + deps += [ + "//chromecast/media/cma/backend/proxy", + "//chromecast/media/cma/backend/proxy:cast_audio_decoder_service_proto", + + # TODO(b/174874712): Remove the explicit gRPC dependency. + "//third_party/grpc:grpc++", + ] } if (enable_video_with_mixed_audio) {
diff --git a/chromecast/media/cma/DEPS b/chromecast/media/cma/DEPS new file mode 100644 index 0000000..46ed6bc7 --- /dev/null +++ b/chromecast/media/cma/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+third_party/grpc", +]
diff --git a/chromecast/media/cma/backend/proxy/BUILD.gn b/chromecast/media/cma/backend/proxy/BUILD.gn index 02c03ec..215b97a 100644 --- a/chromecast/media/cma/backend/proxy/BUILD.gn +++ b/chromecast/media/cma/backend/proxy/BUILD.gn
@@ -38,9 +38,14 @@ "cast_runtime_audio_channel_broker.h", "cma_backend_proxy.cc", "cma_backend_proxy.h", + "cma_proxy_handler.h", "multizone_audio_decoder_proxy.h", "multizone_audio_decoder_proxy_impl.cc", "multizone_audio_decoder_proxy_impl.h", + "proxy_call_translator.cc", + "proxy_call_translator.h", + "push_buffer_queue.cc", + "push_buffer_queue.h", ] deps = [ @@ -49,5 +54,7 @@ "//chromecast/base", "//chromecast/media/api", "//chromecast/public/media", + "//third_party/grpc:grpc++", + "//third_party/protobuf:protobuf_full", ] }
diff --git a/chromecast/media/cma/backend/proxy/cma_proxy_handler.h b/chromecast/media/cma/backend/proxy/cma_proxy_handler.h new file mode 100644 index 0000000..4aace33a --- /dev/null +++ b/chromecast/media/cma/backend/proxy/cma_proxy_handler.h
@@ -0,0 +1,93 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_ + +#include "base/memory/ref_counted.h" + +namespace chromecast { + +class TaskRunner; + +namespace media { + +struct AudioConfig; + +class CmaProxyHandler { + public: + // The mode in which Cast Core should operate. + enum class AudioDecoderOperationMode { + // Both multiroom and audio rendering is enabled. + kAll = 0, + + // Only multiroom is enabled and audio rendering is disabled. This should + // be used if the runtime is taking over responsibility for rendering audio. + kMultiroomOnly = 1, + + // Only audio rendering is enabled and multiroom is disabled. + kAudioOnly = 2 + }; + + // The current state of the remote CMA backend. + enum class PipelineState { + kUninitialized = 0, + kStopped = 1, + kPlaying = 2, + kPaused = 3, + }; + + // Observer for changes on the remote client. + class Client { + public: + virtual ~Client() = default; + + // Called when an error occurs upon calling any gRPC Method. + virtual void OnError() = 0; + + // Called when the Start(), Stop(), Pause(), or Resume() methods + // successfully change the current pipeline state. + virtual void OnPipelineStateChange(PipelineState state) = 0; + + // Called following the successful processing of a batch of PushBuffer + // calls. + virtual void OnBytesDecoded(int64_t decoded_byte_count) = 0; + }; + + virtual ~CmaProxyHandler() = default; + + // Create a new implementation-specific CmaProxyHandler. Each provided + // object must exist for the duration of the created instance's lifetime, and + // all callbacks for |client| will be called on |task_runner|. + static std::unique_ptr<CmaProxyHandler> Create(TaskRunner* task_runner, + Client* client); + + // Calls to the corresponding gRPC Methods. These functions may be called from + // any thread. + virtual void Initialize(const std::string& cast_session_id, + AudioDecoderOperationMode decoder_mode) = 0; + virtual void Start(int64_t start_pts) = 0; + virtual void Stop() = 0; + virtual void Pause() = 0; + virtual void Resume() = 0; + virtual void SetPlaybackRate(float rate) = 0; + virtual void SetVolume(float multiplier) = 0; + + // Push the provided data or config to a queue, for processing at a later + // point when resources are available. Returns true if the data was + // successfully pushed to the queue and false otherwise. These functions may + // be called from any thread. + // + // NOTES: + // - SetConfig is expected to be called prior to any PushBuffer calls. + // - SetConfig may be called later on as-well, after which time the new config + // will be used for all following PushBuffer calls. + virtual bool SetConfig(const AudioConfig& config) = 0; + virtual bool PushBuffer(scoped_refptr<DecoderBufferBase> buffer) = 0; +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_
diff --git a/chromecast/media/cma/backend/proxy/proxy_call_translator.cc b/chromecast/media/cma/backend/proxy/proxy_call_translator.cc new file mode 100644 index 0000000..a5f2262 --- /dev/null +++ b/chromecast/media/cma/backend/proxy/proxy_call_translator.cc
@@ -0,0 +1,358 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/media/cma/backend/proxy/proxy_call_translator.h" + +#include "base/bind.h" +#include "base/callback.h" +#include "base/callback_forward.h" +#include "base/time/time.h" +#include "chromecast/public/media/decoder_config.h" +#include "chromecast/public/task_runner.h" +#include "third_party/openscreen/src/cast/cast_core/api/runtime/cast_audio_decoder_service.grpc.pb.h" +#include "third_party/protobuf/src/google/protobuf/util/time_util.h" + +namespace chromecast { +namespace media { +namespace { + +CmaProxyHandler::PipelineState ToClientTypes( + CastRuntimeAudioChannelBroker::Handler::PipelineState state) { + switch (state) { + case CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_UNINITIALIZED: + return CmaProxyHandler::PipelineState::kUninitialized; + case CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_STOPPED: + return CmaProxyHandler::PipelineState::kStopped; + case CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_PLAYING: + return CmaProxyHandler::PipelineState::kPlaying; + case CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_PAUSED: + return CmaProxyHandler::PipelineState::kPaused; + default: + NOTREACHED(); + return CmaProxyHandler::PipelineState::kUninitialized; + } +} + +cast::media::AudioConfiguration_AudioCodec ToGrpcTypes(AudioCodec codec) { + switch (codec) { + case kAudioCodecUnknown: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_UNKNOWN; + case kCodecAAC: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_AAC; + case kCodecMP3: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_MP3; + case kCodecPCM: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_PCM; + case kCodecPCM_S16BE: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_PCM_S16BE; + case kCodecVorbis: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_VORBIS; + case kCodecOpus: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_OPUS; + case kCodecEAC3: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_EAC3; + case kCodecAC3: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_AC3; + case kCodecDTS: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_DTS; + case kCodecFLAC: + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_FLAC; + case kCodecMpegHAudio: + return cast::media:: + AudioConfiguration_AudioCodec_AUDIO_CODEC_MPEG_H_AUDIO; + default: + NOTREACHED(); + return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_UNKNOWN; + } +} + +cast::media::AudioConfiguration_ChannelLayout ToGrpcTypes( + ChannelLayout channel_layout) { + switch (channel_layout) { + case ChannelLayout::UNSUPPORTED: + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_UNSUPPORTED; + case ChannelLayout::MONO: + return cast::media::AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_MONO; + case ChannelLayout::STEREO: + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_STEREO; + case ChannelLayout::SURROUND_5_1: + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_SURROUND_5_1; + case ChannelLayout::BITSTREAM: + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_BITSTREAM; + case ChannelLayout::DISCRETE: + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_DISCRETE; + default: + NOTREACHED(); + return cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_UNSUPPORTED; + } +} + +cast::media::AudioConfiguration_SampleFormat ToGrpcTypes( + SampleFormat sample_format) { + switch (sample_format) { + case kUnknownSampleFormat: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_UNKNOWN; + case kSampleFormatU8: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_U8; + case kSampleFormatS16: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S16; + case kSampleFormatS32: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S32; + case kSampleFormatF32: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_F32; + case kSampleFormatPlanarS16: + return cast::media:: + AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S16; + case kSampleFormatPlanarF32: + return cast::media:: + AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_F32; + case kSampleFormatPlanarS32: + return cast::media:: + AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S32; + case kSampleFormatS24: + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S24; + default: + NOTREACHED(); + return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_UNKNOWN; + } +} + +cast::media::CastAudioDecoderMode ToGrpcTypes( + CmaProxyHandler::AudioDecoderOperationMode operation_mode) { + switch (operation_mode) { + case CmaProxyHandler::AudioDecoderOperationMode::kAll: + return cast::media::CAST_AUDIO_DECODER_MODE_ALL; + case CmaProxyHandler::AudioDecoderOperationMode::kMultiroomOnly: + return cast::media::CAST_AUDIO_DECODER_MODE_MULTIROOM_ONLY; + case CmaProxyHandler::AudioDecoderOperationMode::kAudioOnly: + return cast::media::CAST_AUDIO_DECODER_MODE_AUDIO_ONLY; + } +} + +CastRuntimeAudioChannelBroker::Handler::PushBufferRequest ToGrpcTypes( + scoped_refptr<DecoderBufferBase> buffer) { + auto* decode_buffer = new cast::media::AudioDecoderBuffer; + decode_buffer->set_pts_micros(buffer->timestamp()); + decode_buffer->set_data(buffer->data(), buffer->data_size()); + decode_buffer->set_end_of_stream(buffer->end_of_stream()); + + CastRuntimeAudioChannelBroker::Handler::PushBufferRequest request; + + // NOTE: This transfers ownership of |decode_buffer| to |request|. + request.set_allocated_buffer(decode_buffer); + + return request; +} + +CastRuntimeAudioChannelBroker::Handler::PushBufferRequest ToGrpcTypes( + const AudioConfig& audio_config) { + auto* audio_config_internal = new cast::media::AudioConfiguration; + audio_config_internal->set_codec(ToGrpcTypes(audio_config.codec)); + audio_config_internal->set_channel_layout( + ToGrpcTypes(audio_config.channel_layout)); + audio_config_internal->set_sample_format( + ToGrpcTypes(audio_config.sample_format)); + audio_config_internal->set_bytes_per_channel(audio_config.bytes_per_channel); + audio_config_internal->set_channel_number(audio_config.channel_number); + audio_config_internal->set_samples_per_second( + audio_config.samples_per_second); + + // NOTE: This copies the data. + audio_config_internal->set_extra_data(audio_config.extra_data.data(), + audio_config.extra_data.size()); + + CastRuntimeAudioChannelBroker::Handler::PushBufferRequest request; + + // NOTE: This transfers ownership of |audio_config_internal| to |request|. + request.set_allocated_audio_config(audio_config_internal); + + return request; +} + +// Helper to convert from Chromium callback type (OnceCallback) to Chromecast's +// TaskRunner's Task type. +class OnceCallbackTask : public TaskRunner::Task { + public: + OnceCallbackTask(base::OnceClosure callback) + : callback_(std::move(callback)) {} + + ~OnceCallbackTask() override = default; + + private: + // TaskRunner::Task overrides: + void Run() override { std::move(callback_).Run(); } + + base::OnceClosure callback_; +}; + +} // namespace + +// static +std::unique_ptr<CmaProxyHandler> CmaProxyHandler::Create( + TaskRunner* task_runner, + Client* client) { + return std::make_unique<ProxyCallTranslator>(task_runner, client); +} + +ProxyCallTranslator::ProxyCallTranslator(TaskRunner* client_task_runner, + CmaProxyHandler::Client* client) + : ProxyCallTranslator(client_task_runner, + client, + CastRuntimeAudioChannelBroker::Create(this)) {} + +ProxyCallTranslator::ProxyCallTranslator( + TaskRunner* client_task_runner, + CmaProxyHandler::Client* client, + std::unique_ptr<CastRuntimeAudioChannelBroker> decoder_channel) + : decoder_channel_(std::move(decoder_channel)), + client_task_runner_(client_task_runner), + client_(client), + weak_factory_(this) { + DCHECK(decoder_channel_.get()); + DCHECK(client_task_runner_); + DCHECK(client_); +} + +ProxyCallTranslator::~ProxyCallTranslator() = default; + +void ProxyCallTranslator::Initialize( + const std::string& cast_session_id, + CmaProxyHandler::AudioDecoderOperationMode decoder_mode) { + decoder_channel_->InitializeAsync(cast_session_id, ToGrpcTypes(decoder_mode)); +} + +void ProxyCallTranslator::Start(int64_t start_pts) { + decoder_channel_->StartAsync(start_pts); +} + +void ProxyCallTranslator::Stop() { + decoder_channel_->StopAsync(); +} + +void ProxyCallTranslator::Pause() { + decoder_channel_->PauseAsync(); +} + +void ProxyCallTranslator::Resume() { + decoder_channel_->ResumeAsync(); +} + +void ProxyCallTranslator::SetPlaybackRate(float rate) { + decoder_channel_->SetPlaybackAsync(rate); +} + +void ProxyCallTranslator::SetVolume(float multiplier) { + decoder_channel_->SetVolumeAsync(multiplier); +} + +bool ProxyCallTranslator::SetConfig(const AudioConfig& config) { + return ProcessPushBufferRequest(ToGrpcTypes(config)); +} + +bool ProxyCallTranslator::PushBuffer(scoped_refptr<DecoderBufferBase> buffer) { + return ProcessPushBufferRequest(ToGrpcTypes(std::move(buffer))); +} + +bool ProxyCallTranslator::ProcessPushBufferRequest(PushBufferRequest request) { + // TODO(rwkeane) + NOTIMPLEMENTED(); + return false; +} + +ProxyCallTranslator::PushBufferRequest ProxyCallTranslator::GetBufferedData() { + // TODO(rwkeane) + NOTIMPLEMENTED(); + return PushBufferRequest{}; +} + +bool ProxyCallTranslator::HasBufferedData() { + // TODO(rwkeane) + NOTIMPLEMENTED(); + return false; +} + +void ProxyCallTranslator::HandleInitializeResponse( + CastRuntimeAudioChannelBroker::StatusCode status) { + HandleError(status); +} + +void ProxyCallTranslator::HandleSetVolumeResponse( + CastRuntimeAudioChannelBroker::StatusCode status) { + HandleError(status); +} + +void ProxyCallTranslator::HandleSetPlaybackResponse( + CastRuntimeAudioChannelBroker::StatusCode status) { + HandleError(status); +} + +void ProxyCallTranslator::HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState state, + CastRuntimeAudioChannelBroker::StatusCode status) { + if (!HandleError(status)) { + return; + } + + auto* task = new OnceCallbackTask( + base::BindOnce(&ProxyCallTranslator::OnPipelineStateChangeTask, + weak_factory_.GetWeakPtr(), ToClientTypes(state))); + client_task_runner_->PostTask(task, 0); +} + +void ProxyCallTranslator::HandlePushBufferResponse( + int64_t decoded_bytes, + CastRuntimeAudioChannelBroker::StatusCode status) { + if (!HandleError(status)) { + return; + } + + auto* task = new OnceCallbackTask( + base::BindOnce(&ProxyCallTranslator::OnBytesDecodedTask, + weak_factory_.GetWeakPtr(), decoded_bytes)); + client_task_runner_->PostTask(task, 0); +} + +void ProxyCallTranslator::HandleGetMediaTimeResponse( + base::Optional<MediaTime> time, + CastRuntimeAudioChannelBroker::StatusCode status) { + NOTREACHED(); +} + +bool ProxyCallTranslator::HandleError( + CastRuntimeAudioChannelBroker::StatusCode status) { + if (status == CastRuntimeAudioChannelBroker::StatusCode::kOk) { + return true; + } + + auto* task = new OnceCallbackTask(base::BindOnce( + &ProxyCallTranslator::OnErrorTask, weak_factory_.GetWeakPtr())); + client_task_runner_->PostTask(task, 0); + return false; +} + +void ProxyCallTranslator::OnErrorTask() { + client_->OnError(); +} + +void ProxyCallTranslator::OnPipelineStateChangeTask( + CmaProxyHandler::PipelineState state) { + client_->OnPipelineStateChange(state); +} + +void ProxyCallTranslator::OnBytesDecodedTask(int64_t decoded_byte_count) { + client_->OnBytesDecoded(decoded_byte_count); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/proxy/proxy_call_translator.h b/chromecast/media/cma/backend/proxy/proxy_call_translator.h new file mode 100644 index 0000000..3ea29f6 --- /dev/null +++ b/chromecast/media/cma/backend/proxy/proxy_call_translator.h
@@ -0,0 +1,107 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_ + +#include <memory> + +#include "base/memory/ref_counted.h" +#include "base/optional.h" +#include "chromecast/media/api/decoder_buffer_base.h" +#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" +#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" + +namespace chromecast { + +class TaskRunner; + +namespace media { + +struct AudioConfig; + +// This class is responsible for translating between entities used by the +// client CmaBackend and entities used by the internal gRPC Channel. +// Calls made to all methods of this class may be made from any thread. +class ProxyCallTranslator : public CmaProxyHandler, + public CastRuntimeAudioChannelBroker::Handler { + public: + // Creates a new ProxyCallTranslator. All provided entities must exist for the + // duration of this instance's lifetime. All calls to |client| will be made + // on |client_task_runner|. + ProxyCallTranslator(TaskRunner* client_task_runner, + CmaProxyHandler::Client* client); + ~ProxyCallTranslator() override; + + // CmaProxyHandler overrides: + void Initialize( + const std::string& cast_session_id, + CmaProxyHandler::AudioDecoderOperationMode decoder_mode) override; + void Start(int64_t start_pts) override; + void Stop() override; + void Pause() override; + void Resume() override; + void SetPlaybackRate(float rate) override; + void SetVolume(float multiplier) override; + bool SetConfig(const AudioConfig& config) override; + bool PushBuffer(scoped_refptr<DecoderBufferBase> buffer) override; + + private: + friend class ProxyCallTranslatorTest; + + using MediaTime = CastRuntimeAudioChannelBroker::Handler::MediaTime; + using PipelineState = CastRuntimeAudioChannelBroker::Handler::PipelineState; + using PushBufferRequest = + CastRuntimeAudioChannelBroker::Handler::PushBufferRequest; + + ProxyCallTranslator( + TaskRunner* client_task_runner, + CmaProxyHandler::Client* client, + std::unique_ptr<CastRuntimeAudioChannelBroker> decoder_channel); + + // CastRuntimeAudioChannelBroker::Handler overrides: + PushBufferRequest GetBufferedData() override; + bool HasBufferedData() override; + void HandleInitializeResponse( + CastRuntimeAudioChannelBroker::StatusCode status) override; + void HandleStateChangeResponse( + PipelineState state, + CastRuntimeAudioChannelBroker::StatusCode status) override; + void HandleSetVolumeResponse( + CastRuntimeAudioChannelBroker::StatusCode status) override; + void HandleSetPlaybackResponse( + CastRuntimeAudioChannelBroker::StatusCode status) override; + void HandlePushBufferResponse( + int64_t decoded_bytes, + CastRuntimeAudioChannelBroker::StatusCode status) override; + void HandleGetMediaTimeResponse( + base::Optional<MediaTime> time, + CastRuntimeAudioChannelBroker::StatusCode status) override; + + bool ProcessPushBufferRequest(PushBufferRequest request); + + // Helper to share error handling code. + bool HandleError(CastRuntimeAudioChannelBroker::StatusCode status); + + // Helpers to simplify use of callbacks for tasks posted to + // |client_task_runner_|. + void OnErrorTask(); + void OnPipelineStateChangeTask(CmaProxyHandler::PipelineState state); + void OnBytesDecodedTask(int64_t decoded_byte_count); + + std::unique_ptr<CastRuntimeAudioChannelBroker> decoder_channel_; + TaskRunner* const client_task_runner_; + CmaProxyHandler::Client* const client_; + + // NOTE: All weak_ptrs created from this factory must be dereferenced on + // |client_task_runner_|. Unfortunately, due to the structure of the + // chromecast::TaskRunner class, weak_ptr validation is not guaranteed so this + // assumption cannot be validated outside of the WeakPtr class. + base::WeakPtrFactory<ProxyCallTranslator> weak_factory_; +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_
diff --git a/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc b/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc new file mode 100644 index 0000000..0fb88679 --- /dev/null +++ b/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc
@@ -0,0 +1,221 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/media/cma/backend/proxy/proxy_call_translator.h" + +#include <memory> + +#include "base/memory/scoped_refptr.h" +#include "base/test/test_simple_task_runner.h" +#include "chromecast/base/task_runner_impl.h" +#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" +#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromecast { +namespace media { +namespace { + +class MockTranslatorClient : public CmaProxyHandler::Client { + public: + ~MockTranslatorClient() override = default; + + MOCK_METHOD0(OnError, void()); + MOCK_METHOD1(OnPipelineStateChange, void(CmaProxyHandler::PipelineState)); + MOCK_METHOD1(OnBytesDecoded, void(int64_t)); + MOCK_METHOD2(OnMediaTimeUpdate, void(int64_t, base::TimeTicks)); + MOCK_METHOD0(OnEndOfStream, void()); +}; + +class MockDecoderChannel : public CastRuntimeAudioChannelBroker { + public: + ~MockDecoderChannel() override = default; + + MOCK_METHOD2( + InitializeAsync, + void(const std::string&, + CastRuntimeAudioChannelBroker::CastAudioDecoderMode decoder_mode)); + MOCK_METHOD1(SetVolumeAsync, void(float)); + MOCK_METHOD1(SetPlaybackAsync, void(double)); + MOCK_METHOD0(GetMediaTimeAsync, void()); + MOCK_METHOD1(StartAsync, void(int64_t)); + MOCK_METHOD0(StopAsync, void()); + MOCK_METHOD0(PauseAsync, void()); + MOCK_METHOD0(ResumeAsync, void()); +}; + +} // namespace + +class ProxyCallTranslatorTest : public testing::Test { + public: + ProxyCallTranslatorTest() + : task_runner_(new base::TestSimpleTaskRunner()), + chromecast_task_runner_(task_runner_), + decoder_channel_not_owned_( + std::make_unique<testing::StrictMock<MockDecoderChannel>>()), + decoder_channel_(decoder_channel_not_owned_.get()), + translator_(&chromecast_task_runner_, + &translator_client_, + std::move(decoder_channel_not_owned_)), + translator_as_handler_( + static_cast<CastRuntimeAudioChannelBroker::Handler*>( + &translator_)) {} + + ~ProxyCallTranslatorTest() override = default; + + protected: + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + TaskRunnerImpl chromecast_task_runner_; + testing::StrictMock<MockTranslatorClient> translator_client_; + std::unique_ptr<testing::StrictMock<MockDecoderChannel>> + decoder_channel_not_owned_; + testing::StrictMock<MockDecoderChannel>* decoder_channel_; + + ProxyCallTranslator translator_; + CastRuntimeAudioChannelBroker::Handler* translator_as_handler_; + + const CastRuntimeAudioChannelBroker::StatusCode failure_status_ = + CastRuntimeAudioChannelBroker::StatusCode::kUnknown; + const CastRuntimeAudioChannelBroker::StatusCode success_status_ = + CastRuntimeAudioChannelBroker::StatusCode::kOk; +}; + +TEST_F(ProxyCallTranslatorTest, TestExternalInitialize) { + std::string session_id = "foo"; + EXPECT_CALL( + *decoder_channel_, + InitializeAsync(session_id, cast::media::CAST_AUDIO_DECODER_MODE_ALL)); + translator_.Initialize(session_id, + CmaProxyHandler::AudioDecoderOperationMode::kAll); + + session_id = "bar"; + EXPECT_CALL( + *decoder_channel_, + InitializeAsync(session_id, + cast::media::CAST_AUDIO_DECODER_MODE_MULTIROOM_ONLY)); + translator_.Initialize( + session_id, CmaProxyHandler::AudioDecoderOperationMode::kMultiroomOnly); + + session_id = "foobar"; + EXPECT_CALL(*decoder_channel_, + InitializeAsync(session_id, + cast::media::CAST_AUDIO_DECODER_MODE_AUDIO_ONLY)); + translator_.Initialize( + session_id, CmaProxyHandler::AudioDecoderOperationMode::kAudioOnly); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalStart) { + constexpr int64_t start_pts = 42; + EXPECT_CALL(*decoder_channel_, StartAsync(start_pts)); + translator_.Start(start_pts); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalStop) { + EXPECT_CALL(*decoder_channel_, StopAsync()); + translator_.Stop(); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalPause) { + EXPECT_CALL(*decoder_channel_, PauseAsync()); + translator_.Pause(); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalResume) { + EXPECT_CALL(*decoder_channel_, ResumeAsync()); + translator_.Resume(); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalSetPlaybackRate) { + constexpr float rate = 42; + EXPECT_CALL(*decoder_channel_, SetPlaybackAsync(rate)); + translator_.SetPlaybackRate(rate); +} + +TEST_F(ProxyCallTranslatorTest, TestExternalSetVolume) { + constexpr float multiplier = 42; + EXPECT_CALL(*decoder_channel_, SetVolumeAsync(multiplier)); + translator_.SetVolume(multiplier); +} + +TEST_F(ProxyCallTranslatorTest, TestInternalHandleInitializeFailure) { + EXPECT_CALL(translator_client_, OnError()); + translator_as_handler_->HandleInitializeResponse(failure_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TestHandleStateChangeFailure) { + EXPECT_CALL(translator_client_, OnError()); + translator_as_handler_->HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_UNINITIALIZED, + failure_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TestHandleSetVolumeFailure) { + EXPECT_CALL(translator_client_, OnError()); + translator_as_handler_->HandleSetVolumeResponse(failure_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TesSetPlaybackFailure) { + EXPECT_CALL(translator_client_, OnError()); + translator_as_handler_->HandleSetPlaybackResponse(failure_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TestPushBufferFailure) { + EXPECT_CALL(translator_client_, OnError()); + translator_as_handler_->HandlePushBufferResponse(42, failure_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TestStateChangeSuccess) { + EXPECT_CALL( + translator_client_, + OnPipelineStateChange(CmaProxyHandler::PipelineState::kUninitialized)); + translator_as_handler_->HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_UNINITIALIZED, + success_status_); + task_runner_->RunPendingTasks(); + + EXPECT_CALL(translator_client_, + OnPipelineStateChange(CmaProxyHandler::PipelineState::kStopped)); + translator_as_handler_->HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_STOPPED, + success_status_); + task_runner_->RunPendingTasks(); + + EXPECT_CALL(translator_client_, + OnPipelineStateChange(CmaProxyHandler::PipelineState::kPlaying)); + translator_as_handler_->HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_PLAYING, + success_status_); + task_runner_->RunPendingTasks(); + + EXPECT_CALL(translator_client_, + OnPipelineStateChange(CmaProxyHandler::PipelineState::kPaused)); + translator_as_handler_->HandleStateChangeResponse( + CastRuntimeAudioChannelBroker::Handler::PipelineState:: + PIPELINE_STATE_PAUSED, + success_status_); + task_runner_->RunPendingTasks(); +} + +TEST_F(ProxyCallTranslatorTest, TestPushBufferSuccess) { + EXPECT_CALL(translator_client_, OnBytesDecoded(42)); + translator_as_handler_->HandlePushBufferResponse(42, success_status_); + task_runner_->RunPendingTasks(); + + EXPECT_CALL(translator_client_, OnBytesDecoded(112358)); + translator_as_handler_->HandlePushBufferResponse(112358, success_status_); + task_runner_->RunPendingTasks(); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/proxy/push_buffer_queue.cc b/chromecast/media/cma/backend/proxy/push_buffer_queue.cc new file mode 100644 index 0000000..3c8960d8 --- /dev/null +++ b/chromecast/media/cma/backend/proxy/push_buffer_queue.cc
@@ -0,0 +1,281 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/media/cma/backend/proxy/push_buffer_queue.h" + +#include <atomic> + +#include "base/notreached.h" +#include "base/template_util.h" +#include "chromecast/media/api/decoder_buffer_base.h" +#include "third_party/protobuf/src/google/protobuf/util/delimited_message_util.h" + +namespace chromecast { +namespace media { +namespace { + +// The number of consecutive failed read attempts before the buffer is +// determined to be in an invalid state. +int kMaximumFailedReadAttempts = 10; + +// The maximum size of a read/write window used by the underlying buffer. This +// is the maximum size of the array which will be cached for upcoming use. +// size_t type is used here to simplify comparison logic later on. +size_t kWindowSizeBytes = 32; + +} // namespace + +// static +constexpr size_t PushBufferQueue::kBufferSizeBytes; + +PushBufferQueue::PushBufferQueue() + : producer_handler_(this), + consumer_handler_(this), + consumer_stream_(base::in_place_t(), &consumer_handler_), + protobuf_consumer_stream_(base::in_place_t(), + &consumer_stream_.value(), + 1), + producer_stream_(base::in_place_t(), &producer_handler_) { + DETACH_FROM_SEQUENCE(producer_sequence_checker_); + DETACH_FROM_SEQUENCE(consumer_sequence_checker_); +} + +PushBufferQueue::~PushBufferQueue() = default; + +bool PushBufferQueue::PushBuffer(const PushBufferRequest& request) { + auto success = PushBufferImpl(request); + if (success) { + producer_handler_.ApplyNewBytesWritten(); + } + + return success; +} + +bool PushBufferQueue::PushBufferImpl(const PushBufferRequest& request) { + DCHECK_CALLED_ON_VALID_SEQUENCE(producer_sequence_checker_); + + bytes_written_during_current_write_ = 0; + + // NOTE: This method is used instead of SerializeDelimitedToZeroCopyStream() + // due to bugs in the method's implementation. See b/173477672. + DCHECK(producer_stream_.has_value()); + bool success = google::protobuf::util::SerializeDelimitedToOstream( + request, &producer_stream_.value()); + + if (success) { + producer_handler_.overflow(); + } else { + // Now the stream is in a bad state, so recreate it. This should only occur + // when the entire |buffer_| is full at time of writing. + bytes_written_during_current_write_ = 0; + producer_handler_.overflow(); + producer_stream_ = base::nullopt; + producer_stream_.emplace(&producer_handler_); + } + + return success; +} + +bool PushBufferQueue::HasBufferedData() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(consumer_sequence_checker_); + return !is_in_invalid_state_ && GetAvailableyByteCount() != size_t{0}; +} + +base::Optional<PushBufferQueue::PushBufferRequest> +PushBufferQueue::GetBufferedData() { + auto result = GetBufferedDataImpl(); + if (result.has_value()) { + consumer_handler_.ApplyNewBytesRead(); + } + + return result; +} + +base::Optional<PushBufferQueue::PushBufferRequest> +PushBufferQueue::GetBufferedDataImpl() { + DCHECK_CALLED_ON_VALID_SEQUENCE(consumer_sequence_checker_); + DCHECK(HasBufferedData()); + + bytes_read_during_current_read_ = 0; + PushBufferRequest request; + + DCHECK(protobuf_consumer_stream_.has_value()); + bool succeeded = google::protobuf::util::ParseDelimitedFromZeroCopyStream( + &request, &protobuf_consumer_stream_.value(), nullptr /* clean_eof */); + + // This case will only occur in one of the following cases: + // - Reading a PushBuffer at the same time it is being written. + // - An error occurs while reading from the stream (specifically, a PushBuffer + // was serialized incorrectly). + // The former case is not expected to occur, but is handled to be safe. + // The latter case is only expected if the buffer is written to when not + // enough space is available to handle the new write. + // + // TODO(rwkeane): Eliminate handling of the former case after validating this + // doesn't occur in practice. + if (!succeeded) { + consecuitive_read_failures_++; + if (+consecuitive_read_failures_ > kMaximumFailedReadAttempts) { + // This means that data was probably serialized incorrectly. + is_in_invalid_state_ = true; + } + + // Reset the read pointers so that future reads re-read the old data. + bytes_read_during_current_read_ = 0; + consumer_handler_.ResetReadPointers(); + + // If |!succeeded|, the streams have ended up in an unexpected state and + // need to be recreated. + protobuf_consumer_stream_ = base::nullopt; + consumer_stream_ = base::nullopt; + consumer_stream_.emplace(&consumer_handler_); + protobuf_consumer_stream_.emplace(&consumer_stream_.value(), 1); + + return base::nullopt; + } + + consecuitive_read_failures_ = 0; + + return request; +} + +int PushBufferQueue::GetAvailableyByteCount() const { + const int total_bytes_read = + bytes_read_so_far_.load(std::memory_order_relaxed) + + consumer_handler_.GetReadOffset(); + const int total_bytes_written = + bytes_written_so_far_.load(std::memory_order_relaxed); + return total_bytes_written - total_bytes_read; +} + +PushBufferQueue::ProducerHandler::ProducerHandler(PushBufferQueue* queue) + : queue_(queue) { + DCHECK(queue_); +} + +PushBufferQueue::ProducerHandler::~ProducerHandler() = default; + +int PushBufferQueue::ProducerHandler::overflow(int ch) { + // Get the number of bytes read and written so far. + const size_t current_read_bytes = + queue_->bytes_read_so_far_.load(std::memory_order_acquire); + const int currently_written_bytes = UpdateBytesWritten(); + DCHECK_GE(static_cast<size_t>(currently_written_bytes), current_read_bytes); + + // Calculates the current size of the buffer. + const size_t bytes_currently_used = + currently_written_bytes - current_read_bytes; + DCHECK_LE(bytes_currently_used, kBufferSizeBytes); + + // Calculates the number of bytes that should be included in the next write + // window, which is the least of: + // - |kWindowSizeBytes| + // - The number that can be written before wrapping around to the beginning of + // the underlying array, + // - The number of bytes available before the current read pointer. + const size_t current_write_index = currently_written_bytes % kBufferSizeBytes; + const size_t available_writable_bytes = + std::min(kBufferSizeBytes - current_write_index, + current_read_bytes + kBufferSizeBytes - currently_written_bytes); + const size_t new_window_size = + std::min(kWindowSizeBytes, available_writable_bytes); + + // If there is no writable area, then return a special value per method + // contact. + if (new_window_size == 0) { + setp(epptr(), epptr()); + return std::char_traits<char>::eof(); + } + + // Update the pointers that determine the writable area and write the given + // value |ch| if one was given. + setp(&queue_->buffer_[current_write_index], + &queue_->buffer_[current_write_index + new_window_size]); + const bool should_write_ch = (ch != std::char_traits<char>::eof()); + if (should_write_ch) { + sputc(static_cast<char>(ch)); + } + return 1; // This can be any value except std::char_traits<char>::eof(). +} + +void PushBufferQueue::ProducerHandler::ApplyNewBytesWritten() { + queue_->bytes_written_so_far_.fetch_add( + queue_->bytes_written_during_current_write_, std::memory_order_relaxed); + queue_->bytes_written_during_current_write_ = 0; +} + +size_t PushBufferQueue::ProducerHandler::UpdateBytesWritten() { + const int change_in_write_count = pptr() - pbase(); + DCHECK_GE(change_in_write_count, 0); + queue_->bytes_written_during_current_write_ += change_in_write_count; + return queue_->bytes_written_so_far_.load(std::memory_order_relaxed) + + queue_->bytes_written_during_current_write_; +} + +PushBufferQueue::ConsumerHandler::ConsumerHandler(PushBufferQueue* queue) + : queue_(queue) { + DCHECK(queue_); +} + +PushBufferQueue::ConsumerHandler::~ConsumerHandler() = default; + +int PushBufferQueue::ConsumerHandler::underflow() { + // Get the written and read bytes. + const size_t currently_written_bytes = + queue_->bytes_written_so_far_.load(std::memory_order_acquire); + const size_t current_read_bytes = UpdateBytesRead(); + DCHECK_GE(currently_written_bytes, current_read_bytes); + + // Stop reading at either the end of the array or the current write index, + // whichever is sooner. While there may be more data wrapped around after the + // end of the array, that can be handled as part of the next underflow() call. + const size_t avail = currently_written_bytes - current_read_bytes; + const size_t begin = current_read_bytes % kBufferSizeBytes; + const size_t end = std::min(begin + avail, kBufferSizeBytes); + const size_t new_window_size = std::min(end - begin, kWindowSizeBytes); + + // This means that there are no bytes left to read. Return a special value per + // method contract. + if (new_window_size == 0) { + return std::char_traits<char>::eof(); + } + + // Otherwise, there is still readable data. Update the readable window and + // return the current character per method contact. Because + // std::char_traits<char>::eof() is a special return code, cast to a uint to + // avoid all negative results (EOF is guaranteed to be negative by the stl). + DCHECK_LE(current_read_bytes + new_window_size, currently_written_bytes); + setg(&queue_->buffer_[begin], &queue_->buffer_[begin], + &queue_->buffer_[begin + new_window_size]); + return static_cast<uint8_t>(queue_->buffer_[begin]); +} + +void PushBufferQueue::ConsumerHandler::ResetReadPointers() { + const size_t begin = + queue_->bytes_read_so_far_.load(std::memory_order_relaxed) % + kBufferSizeBytes; + setg(&queue_->buffer_[begin], &queue_->buffer_[begin], + &queue_->buffer_[begin]); +} + +void PushBufferQueue::ConsumerHandler::ApplyNewBytesRead() { + queue_->bytes_read_so_far_.fetch_add(queue_->bytes_read_during_current_read_, + std::memory_order_relaxed); + queue_->bytes_read_during_current_read_ = 0; +} + +size_t PushBufferQueue::ConsumerHandler::UpdateBytesRead() { + const int change_in_read_count = GetReadOffset(); + DCHECK_GE(change_in_read_count, 0); + queue_->bytes_read_during_current_read_ += change_in_read_count; + return queue_->bytes_read_so_far_.load(std::memory_order_relaxed) + + queue_->bytes_read_during_current_read_; +} + +int PushBufferQueue::ConsumerHandler::GetReadOffset() const { + return gptr() - eback(); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/proxy/push_buffer_queue.h b/chromecast/media/cma/backend/proxy/push_buffer_queue.h new file mode 100644 index 0000000..ed47ea1d --- /dev/null +++ b/chromecast/media/cma/backend/proxy/push_buffer_queue.h
@@ -0,0 +1,190 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_ + +#include <atomic> +#include <istream> +#include <ostream> + +#include "base/optional.h" +#include "base/sequence_checker.h" +#include "chromecast/media/api/decoder_buffer_base.h" +#include "third_party/openscreen/src/cast/cast_core/api/runtime/cast_audio_decoder_service.pb.h" +#include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h" + +namespace chromecast { +namespace media { + +struct AudioConfig; + +// This class is responsible for buffering both DecoderBuffer and AudioConfig +// data, which are pushed together over gRPC using the PushData() API call. +// Two sequences are expected to simultaneously access this object: +// - A PRODUCER sequence, which will push new data in. +// - A CONSUMER thread which will pull this data back out of the data structure. +// +// This is achieved through serializing this protobuf into bytes, then storing +// these bytes in a lockless FIFO. +class PushBufferQueue { + public: + using PushBufferRequest = cast::media::PushBufferRequest; + + // The amount of space to allocate in the buffer. + static constexpr size_t kBufferSizeBytes = 0x01 << 12; // 4 kB. + + PushBufferQueue(); + ~PushBufferQueue(); + + // Pushes the data stored in the associated type to the queue underlying this + // object. Returns true if the operation was successful, and false otherwise. + // + // May only be called by the PRODUCER. + bool PushBuffer(const PushBufferRequest& request); + + // Returns true if there is data available for reading. + // + // May only be called by the CONSUMER. + bool HasBufferedData() const; + + // Attempts to read the top PushBufferRequest on the queue, returning the + // instance on success and empty if not enough data is available yet. + // + // May only be called by the CONSUMER. + base::Optional<PushBufferRequest> GetBufferedData(); + + private: + // These classes exist for the following 2 reasons: + // 1) Readability. Separating of the Read and Write methods is simpler + // 2) Thread safety guarantees. The stl provides no guarantees of thread + // safety within a single instance of std::basic_streambuf<char>, even + // though there should be no overlap between the resources used by both. + // In an ideal world, this functionality could all live in the + // |PushBufferQueue| class. + // + // The approach used by basic_streambuf is to maintain a 'window' on the data + // from which it reads/writes. When the window runs out, underflow() or read + // or overflow() for write is called to get the next window. + // These allow this class to be used as a thread-safe circular read/write + // buffer by input and output streams, as required for use with protobuf + // serialization and deserialization utilities. + // + // Methods in |ProducerHandler| may only be called from the PRODUCER. + class ProducerHandler : public std::basic_streambuf<char> { + public: + explicit ProducerHandler(PushBufferQueue* queue); + ~ProducerHandler() override; + + // std::basic_streambuf<char> overrides: + int overflow(int ch = std::char_traits<char>::eof()) override; + + // Stores the new value of |bytes_written_so_far_| following a successful + // write. + void ApplyNewBytesWritten(); + + private: + // Updates |bytes_written_during_current_write_| and returns the total + // number of bytes written including these new bytes. + size_t UpdateBytesWritten(); + + PushBufferQueue* const queue_; + }; + + // Methods in |ConsumerHandler| may only be called from the CONSUMER. + class ConsumerHandler : public std::basic_streambuf<char> { + public: + explicit ConsumerHandler(PushBufferQueue* queue); + ~ConsumerHandler() override; + + // std::basic_streambuf<char> overrides: + int underflow() override; + + // Returns the number of bytes that have been read so far but not accounted + // for by |queue_->bytes_read_so_far_|. + int GetReadOffset() const; + + // Resets the get area for this streambuf to start at the location pointed + // to by |bytes_read_so_far_| and configures the stream to call underflow() + // during its next read. + void ResetReadPointers(); + + // Stores the new value of |bytes_read_so_far_| following a successful read. + void ApplyNewBytesRead(); + + private: + // Updates |bytes_read_during_current_read_| and returns the total number of + // bytes read including these new bytes. + size_t UpdateBytesRead(); + + PushBufferQueue* const queue_; + }; + + // Friend declaration is needed to test some edge cases that can be hit when + // simultaneous reads and writes are ongoing. + friend class PushBufferQueueTests; + + // Give access to helper types. + friend class ProducerHandler; + friend class ConsumerHandler; + + // Gets the number of buffered bytes. May only be called from the CONSUMER. + int GetAvailableyByteCount() const; + + // Helper methods to be used for test hooks. + bool PushBufferImpl(const PushBufferRequest& request); + base::Optional<PushBufferRequest> GetBufferedDataImpl(); + + // Buffer where serialized PushBufferRequest data is stored. + char buffer_[kBufferSizeBytes]; + + // Total number of bytes read or written by completed operations so far. + // Atomics are used both to ensure that read and write operations are atomic + // on all systems and to ensure that different values for these values aren't + // loaded from each CPU's physical cache. Size_t types are used intentionally + // to allow for wrap-around. + std::atomic_size_t bytes_read_so_far_{0}; + std::atomic_size_t bytes_written_so_far_{0}; + + // The number of bytes read during the current GetBufferedData() call. This is + // necessary due to internal details of how an IstreamInputStream handles + // end-of-stream conditions. May only be accessed or modified by the + // CONSUMER. + int bytes_read_during_current_read_ = 0; + + // The number of bytes written during the current PushBuffer call. This helps + // to prevent reads of PushBuffer instances currently being written. May only + // be accessed by the PRODUCER. + int bytes_written_during_current_write_ = 0; + + // Tracks whether this buffer is in a valid state for further reads to occur. + // May only be used by the CONSUMER. + int consecuitive_read_failures_ = 0; + bool is_in_invalid_state_ = false; + + // Helpers for keeping CONSUMER and PRODUCER sequences independent. + ProducerHandler producer_handler_; + ConsumerHandler consumer_handler_; + + // Sequence checkers for thread safety validation: + SEQUENCE_CHECKER(producer_sequence_checker_); + SEQUENCE_CHECKER(consumer_sequence_checker_); + + // Input streams backed by this instance. They must be optional so that they + // can be re-created following a failed read. These should only be used by the + // CONSUMER. + base::Optional<std::istream> consumer_stream_; + base::Optional<google::protobuf::io::IstreamInputStream> + protobuf_consumer_stream_; + + // Output stream backed by this instance. This must be optional so it can be + // re-created following a failed write. It should only be used by the + // PRODUCER. + base::Optional<std::ostream> producer_stream_; +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_
diff --git a/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc b/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc new file mode 100644 index 0000000..724a441 --- /dev/null +++ b/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc
@@ -0,0 +1,337 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/media/cma/backend/proxy/push_buffer_queue.h" + +#include <atomic> +#include <sstream> + +#include "base/bind.h" +#include "base/location.h" +#include "base/optional.h" +#include "base/threading/thread.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/openscreen/src/cast/cast_core/api/runtime/cast_audio_decoder_service.grpc.pb.h" + +namespace chromecast { +namespace media { + +class PushBufferQueueTests : public testing::Test { + public: + PushBufferQueueTests() + : first_audio_buffer_(CreateAudioBufferRequest(0, false, 1, 2, 255)), + second_audio_buffer_(CreateAudioBufferRequest(2, false, 6, 4, 2, 0)), + third_audio_buffer_( + CreateAudioBufferRequest(4, true, 0, 1, 1, 2, 3, 5, 8)), + fourth_audio_buffer_( + CreateAudioBufferRequest(42, true, 4, 8, 15, 16, 23, 42)), + fifth_audio_buffer_(CreateAudioBufferRequest(1, false)) { + std::vector<uint8_t> extra_data{0, 1, 7, 127, 255}; + + auto* config = new cast::media::AudioConfiguration; + config->set_codec( + cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_MP3); + config->set_channel_layout( + cast::media:: + AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_SURROUND_5_1); + config->set_sample_format( + cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S32); + config->set_bytes_per_channel(42); + config->set_channel_number(-1); + config->set_samples_per_second(112358); + config->set_extra_data(extra_data.data(), extra_data.size()); + + first_audio_config_.set_allocated_audio_config(config); + } + + void ReadData(const std::string& name, + const PushBufferQueue::PushBufferRequest& target_buffer) { + ASSERT_TRUE(queue_.HasBufferedData()) << name; + base::Optional<PushBufferRequest> get = queue_.GetBufferedData(); + ASSERT_TRUE(get.has_value()) << name; + CheckEqual("first", get.value(), target_buffer); + } + + protected: + using PushBufferRequest = PushBufferQueue::PushBufferRequest; + using AudioDecoderBuffer = cast::media::AudioDecoderBuffer; + + template <typename... TData> + static PushBufferRequest CreateAudioBufferRequest(int64_t pts_micros, + bool end_of_stream, + TData... data) { + return CreateAudioBufferRequest(pts_micros, end_of_stream, + std::vector<uint8_t>{uint8_t{data}...}); + } + + static PushBufferRequest CreateAudioBufferRequest( + int64_t pts_micros, + bool end_of_stream, + std::vector<uint8_t> data_vector) { + PushBufferRequest request; + auto* audio_buffer = new AudioDecoderBuffer; + audio_buffer->set_pts_micros(pts_micros); + audio_buffer->set_end_of_stream(end_of_stream); + audio_buffer->set_data(data_vector.data(), data_vector.size()); + + request.set_allocated_buffer(audio_buffer); + return request; + } + + void CheckEqual(const std::string& name, + const PushBufferRequest& first, + const PushBufferRequest& second) { + std::string failure_str = "failed on " + std::move(name); + + ASSERT_EQ(first.has_buffer(), second.has_buffer()) << failure_str; + ASSERT_EQ(first.has_audio_config(), second.has_audio_config()) + << failure_str; + + if (first.has_buffer()) { + EXPECT_EQ(first.buffer().pts_micros(), second.buffer().pts_micros()) + << failure_str; + EXPECT_EQ(first.buffer().end_of_stream(), second.buffer().end_of_stream()) + << failure_str; + EXPECT_EQ(first.buffer().data(), second.buffer().data()) << failure_str; + } + + if (first.has_audio_config()) { + EXPECT_EQ(first.audio_config().codec(), second.audio_config().codec()) + << failure_str; + EXPECT_EQ(first.audio_config().channel_layout(), + second.audio_config().channel_layout()) + << failure_str; + EXPECT_EQ(first.audio_config().sample_format(), + second.audio_config().sample_format()) + << failure_str; + EXPECT_EQ(first.audio_config().bytes_per_channel(), + second.audio_config().bytes_per_channel()) + << failure_str; + EXPECT_EQ(first.audio_config().channel_number(), + second.audio_config().channel_number()) + << failure_str; + EXPECT_EQ(first.audio_config().samples_per_second(), + second.audio_config().samples_per_second()) + << failure_str; + EXPECT_EQ(first.audio_config().extra_data(), + second.audio_config().extra_data()) + << failure_str; + } + } + + void UpdateBufferWriteStreamPositions() { + queue_.producer_handler_.overflow(); + queue_.producer_handler_.ApplyNewBytesWritten(); + } + + std::string GetIterationName(int iteration_id) { + std::stringstream ss; + ss << "iteration " << iteration_id; + return ss.str(); + } + + bool StartPushBuffer(const PushBufferRequest& request) { + return queue_.PushBufferImpl(request); + } + + base::Optional<PushBufferQueue::PushBufferRequest> StartGetBufferedData() { + return queue_.GetBufferedDataImpl(); + } + + void FinishPushBuffer() { queue_.producer_handler_.ApplyNewBytesWritten(); } + + void FinishGetBufferedData() { queue_.consumer_handler_.ApplyNewBytesRead(); } + + std::istream* consumer_stream() { return &queue_.consumer_stream_.value(); } + std::ostream* producer_stream() { return &queue_.producer_stream_.value(); } + + size_t available_bytes() { return queue_.GetAvailableyByteCount(); } + + PushBufferQueue queue_; + + // Some test data + PushBufferRequest first_audio_buffer_; + PushBufferRequest second_audio_buffer_; + PushBufferRequest third_audio_buffer_; + PushBufferRequest fourth_audio_buffer_; + PushBufferRequest fifth_audio_buffer_; + PushBufferRequest first_audio_config_; +}; + +TEST_F(PushBufferQueueTests, TestPushOrdering) { + EXPECT_FALSE(queue_.HasBufferedData()); + + queue_.PushBuffer(first_audio_buffer_); + queue_.PushBuffer(second_audio_buffer_); + queue_.PushBuffer(first_audio_config_); + queue_.PushBuffer(third_audio_buffer_); + + ReadData("first", first_audio_buffer_); + ReadData("second", second_audio_buffer_); + + queue_.PushBuffer(fourth_audio_buffer_); + + ReadData("config", first_audio_config_); + ReadData("third", third_audio_buffer_); + ReadData("fourth", fourth_audio_buffer_); + + EXPECT_FALSE(queue_.HasBufferedData()); + queue_.PushBuffer(fifth_audio_buffer_); + + ReadData("fifth", fifth_audio_buffer_); + + EXPECT_FALSE(queue_.HasBufferedData()); +} + +TEST_F(PushBufferQueueTests, TestPushLargeBuffer) { + std::vector<uint8_t> data; + for (int i = 0; i < 256; i++) { + data.push_back(i); + } + + auto buffer = CreateAudioBufferRequest(0, false, data); + + queue_.PushBuffer(buffer); + + ReadData("big buffer", buffer); +} + +TEST_F(PushBufferQueueTests, TestWrapAround) { + auto first_buffer = CreateAudioBufferRequest(0, false, 0, 1); + queue_.PushBuffer(first_buffer); + + for (size_t i = 1; i < PushBufferQueue::kBufferSizeBytes * 3; i++) { + const std::string name = GetIterationName(i); + const uint8_t previous_id = (i - 1) % 256; + const uint8_t current_id = i % 256; + const uint8_t next_id = (i + 1) % 256; + auto buffer = CreateAudioBufferRequest( + 0, false, std::vector<uint8_t>{current_id, next_id}); + auto old_buffer = CreateAudioBufferRequest( + 0, false, std::vector<uint8_t>{previous_id, current_id}); + + // Make sure the length is 6. 7 is prime, so guaranteed to hit all possible + // positions in |buffer_| when an extra bit is used for the size. + std::string serialized_str; + buffer.SerializeToString(&serialized_str); + ASSERT_EQ(serialized_str.size(), size_t{6}) << name; + + ASSERT_TRUE(queue_.HasBufferedData()) << name; + ASSERT_TRUE(queue_.PushBuffer(buffer)) << name; + + ReadData(name, old_buffer); + } +} + +TEST_F(PushBufferQueueTests, TestWriteEntireBuffer) { + for (size_t i = 0; i < (PushBufferQueue::kBufferSizeBytes >> 3); i++) { + auto buffer = CreateAudioBufferRequest(0, false, 0, 1, 2); + + // Make sure the length is 8 after serialization (with the extra length + // bit). + std::string serialized_str; + buffer.SerializeToString(&serialized_str); + ASSERT_EQ(serialized_str.size(), size_t{7}); + ASSERT_TRUE(queue_.PushBuffer(buffer)) << GetIterationName(i); + } + + auto failing_buffer = CreateAudioBufferRequest(0, false); + EXPECT_FALSE(queue_.PushBuffer(failing_buffer)); + + for (size_t i = 0; i < (PushBufferQueue::kBufferSizeBytes >> 3); i++) { + auto buffer = CreateAudioBufferRequest(0, false, 0, 1, 2); + ReadData(GetIterationName(i), buffer); + } + + // Make sure writing still works after the failed write above. + EXPECT_FALSE(queue_.HasBufferedData()); + queue_.PushBuffer(first_audio_buffer_); + + ReadData("first", first_audio_buffer_); + + EXPECT_FALSE(queue_.HasBufferedData()); +} + +TEST_F(PushBufferQueueTests, TestReadingFromPartialWrite) { + std::string serialized_str; + first_audio_buffer_.SerializeToString(&serialized_str); + char size = static_cast<char>(serialized_str.size()); + ASSERT_GT(size, 2); + + *producer_stream() << size << serialized_str[0] << serialized_str[1]; + UpdateBufferWriteStreamPositions(); + + ASSERT_TRUE(queue_.HasBufferedData()); + base::Optional<PushBufferRequest> pulled_buffer = queue_.GetBufferedData(); + EXPECT_FALSE(pulled_buffer.has_value()); + EXPECT_TRUE(queue_.HasBufferedData()); + + for (size_t i = 2; i < serialized_str.size(); i++) { + *producer_stream() << serialized_str[i]; + } + UpdateBufferWriteStreamPositions(); + + ASSERT_TRUE(queue_.HasBufferedData()); + pulled_buffer = queue_.GetBufferedData(); + ASSERT_TRUE(pulled_buffer.has_value()); + CheckEqual("buffer", pulled_buffer.value(), first_audio_buffer_); +} + +TEST_F(PushBufferQueueTests, InterleaveProduceAndConsume) { + EXPECT_FALSE(queue_.HasBufferedData()); + + EXPECT_TRUE(StartPushBuffer(first_audio_buffer_)); + EXPECT_FALSE(queue_.HasBufferedData()); + + FinishPushBuffer(); + + ReadData("first", first_audio_buffer_); + + ASSERT_TRUE(StartPushBuffer(second_audio_buffer_)); + + FinishGetBufferedData(); + + EXPECT_FALSE(queue_.HasBufferedData()); + + FinishPushBuffer(); + + ReadData("second", second_audio_buffer_); + + EXPECT_FALSE(queue_.HasBufferedData()); +} + +TEST_F(PushBufferQueueTests, TestMultithreaded) { + queue_.PushBuffer(first_audio_buffer_); + queue_.PushBuffer(second_audio_buffer_); + + base::Thread consumer_thread("Consumer Thread"); + consumer_thread.StartAndWaitForTesting(); + { + auto task_runner = consumer_thread.task_runner(); + auto this_ptr = base::Unretained(this); + task_runner->PostTask( + FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, + "first", first_audio_buffer_)); + + task_runner->PostTask( + FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, + "second", second_audio_buffer_)); + + queue_.PushBuffer(third_audio_buffer_); + queue_.PushBuffer(fourth_audio_buffer_); + task_runner->PostTask( + FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, + "third", third_audio_buffer_)); + task_runner->PostTask( + FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, + "fourth", fourth_audio_buffer_)); + } + + consumer_thread.FlushForTesting(); + consumer_thread.Stop(); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 765e183e..b80b7dbc 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -13649.0.0 \ No newline at end of file +13650.0.0 \ No newline at end of file
diff --git a/chromeos/components/camera_app_ui/BUILD.gn b/chromeos/components/camera_app_ui/BUILD.gn index 34a6a2f..25b308a0 100644 --- a/chromeos/components/camera_app_ui/BUILD.gn +++ b/chromeos/components/camera_app_ui/BUILD.gn
@@ -44,6 +44,7 @@ "//mojo/public/cpp/bindings", "//mojo/public/cpp/platform", "//mojo/public/js:resources_grit", + "//net", "//services/network/public/mojom", "//ui/views", "//ui/webui",
diff --git a/chromeos/components/camera_app_ui/camera_app_helper_impl.cc b/chromeos/components/camera_app_ui/camera_app_helper_impl.cc index e35303d..53e66da 100644 --- a/chromeos/components/camera_app_ui/camera_app_helper_impl.cc +++ b/chromeos/components/camera_app_ui/camera_app_helper_impl.cc
@@ -8,8 +8,10 @@ #include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/window_properties.h" +#include "base/strings/string_number_conversions.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/web_contents.h" +#include "net/base/url_util.h" #include "ui/aura/window.h" namespace chromeos_camera { @@ -37,6 +39,19 @@ return false; } +base::Optional<uint32_t> ParseIntentIdFromUrl(const GURL& url) { + std::string id_str; + if (!net::GetValueForKeyInQuery(url, "intentId", &id_str)) { + return base::nullopt; + } + + uint32_t intent_id; + if (!base::StringToUint(id_str, &intent_id)) { + return base::nullopt; + } + return intent_id; +} + } // namespace CameraAppHelperImpl::CameraAppHelperImpl( @@ -46,6 +61,7 @@ : camera_app_ui_(camera_app_ui), camera_result_callback_(std::move(camera_result_callback)), has_external_screen_(HasExternalScreen()), + pending_intent_id_(base::nullopt), window_(window) { DCHECK(window); window->SetProperty(ash::kCanConsumeSystemKeysKey, true); @@ -58,12 +74,22 @@ ash::TabletMode::Get()->RemoveObserver(this); ash::ScreenBacklight::Get()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); + + if (pending_intent_id_.has_value()) { + camera_result_callback_.Run(*pending_intent_id_, + arc::mojom::CameraIntentAction::CANCEL, {}, + base::DoNothing()); + } } void CameraAppHelperImpl::Bind( mojo::PendingReceiver<mojom::CameraAppHelper> receiver) { receiver_.reset(); receiver_.Bind(std::move(receiver)); + + if (camera_app_ui_) { + pending_intent_id_ = ParseIntentIdFromUrl(camera_app_ui_->url()); + } } void CameraAppHelperImpl::HandleCameraResult( @@ -71,6 +97,11 @@ arc::mojom::CameraIntentAction action, const std::vector<uint8_t>& data, HandleCameraResultCallback callback) { + if (pending_intent_id_.has_value() && *pending_intent_id_ == intent_id && + (action == arc::mojom::CameraIntentAction::FINISH || + action == arc::mojom::CameraIntentAction::CANCEL)) { + pending_intent_id_ = base::nullopt; + } camera_result_callback_.Run(intent_id, action, data, std::move(callback)); }
diff --git a/chromeos/components/camera_app_ui/camera_app_helper_impl.h b/chromeos/components/camera_app_ui/camera_app_helper_impl.h index cb471e4..b67d086 100644 --- a/chromeos/components/camera_app_ui/camera_app_helper_impl.h +++ b/chromeos/components/camera_app_ui/camera_app_helper_impl.h
@@ -10,6 +10,7 @@ #include "ash/public/cpp/screen_backlight.h" #include "ash/public/cpp/tablet_mode_observer.h" #include "base/macros.h" +#include "base/optional.h" #include "chromeos/components/camera_app_ui/camera_app_helper.mojom.h" #include "chromeos/components/camera_app_ui/camera_app_ui.h" #include "chromeos/components/camera_app_ui/camera_app_window_state_controller.h" @@ -90,6 +91,8 @@ bool has_external_screen_; + base::Optional<uint32_t> pending_intent_id_; + aura::Window* window_; mojo::Remote<TabletModeMonitor> tablet_mode_monitor_;
diff --git a/chromeos/components/camera_app_ui/camera_app_ui.cc b/chromeos/components/camera_app_ui/camera_app_ui.cc index 5644bf9..c4fb636 100644 --- a/chromeos/components/camera_app_ui/camera_app_ui.cc +++ b/chromeos/components/camera_app_ui/camera_app_ui.cc
@@ -244,6 +244,10 @@ web_ui()->GetWebContents()->GetBrowserContext()); } +const GURL& CameraAppUI::url() { + return web_ui()->GetWebContents()->GetURL(); +} + WEB_UI_CONTROLLER_TYPE_IMPL(CameraAppUI) } // namespace chromeos
diff --git a/chromeos/components/camera_app_ui/camera_app_ui.h b/chromeos/components/camera_app_ui/camera_app_ui.h index bd98e589..a48db6d2 100644 --- a/chromeos/components/camera_app_ui/camera_app_ui.h +++ b/chromeos/components/camera_app_ui/camera_app_ui.h
@@ -61,6 +61,8 @@ CameraAppWindowManager* app_window_manager(); + const GURL& url(); + private: std::unique_ptr<CameraAppUIDelegate> delegate_;
diff --git a/chromeos/components/camera_app_ui/camera_app_window_state_controller.cc b/chromeos/components/camera_app_ui/camera_app_window_state_controller.cc index 738e191..d19174a 100644 --- a/chromeos/components/camera_app_ui/camera_app_window_state_controller.cc +++ b/chromeos/components/camera_app_ui/camera_app_window_state_controller.cc
@@ -4,6 +4,8 @@ #include "chromeos/components/camera_app_ui/camera_app_window_state_controller.h" +#include "ash/public/cpp/tablet_mode.h" + namespace chromeos { CameraAppWindowStateController::CameraAppWindowStateController( @@ -37,26 +39,54 @@ } void CameraAppWindowStateController::Minimize(MinimizeCallback callback) { + if (GetCurrentWindowState() == WindowStateType::MINIMIZED) { + std::move(callback).Run(); + return; + } minimize_callbacks_.push(std::move(callback)); widget_->Minimize(); } void CameraAppWindowStateController::Restore(RestoreCallback callback) { + auto current_state = GetCurrentWindowState(); + + // In tablet mode, it won't do anything when calling restore() for windows + // which are already maximized. Therefore, for maximized windows, trigger the + // callback immediately. + if (current_state == WindowStateType::REGULAR || + (ash::TabletMode::Get()->InTabletMode() && + (current_state == WindowStateType::MAXIMIZED || + current_state == WindowStateType::FULLSCREEN))) { + std::move(callback).Run(); + return; + } restore_callbacks_.push(std::move(callback)); widget_->Restore(); } void CameraAppWindowStateController::Maximize(MaximizeCallback callback) { + if (GetCurrentWindowState() == WindowStateType::MAXIMIZED) { + std::move(callback).Run(); + return; + } maximize_callbacks_.push(std::move(callback)); widget_->Maximize(); } void CameraAppWindowStateController::Fullscreen(FullscreenCallback callback) { + if (GetCurrentWindowState() == WindowStateType::FULLSCREEN) { + std::move(callback).Run(); + return; + } fullscreen_callbacks_.push(std::move(callback)); widget_->SetFullscreen(true); } void CameraAppWindowStateController::Focus(FocusCallback callback) { + if (widget_->IsActive()) { + std::move(callback).Run(); + return; + } focus_callbacks_.push(std::move(callback)); widget_->Activate(); }
diff --git a/chromeos/components/camera_app_ui/resources/BUILD.gn b/chromeos/components/camera_app_ui/resources/BUILD.gn index df61bc4..7649918 100644 --- a/chromeos/components/camera_app_ui/resources/BUILD.gn +++ b/chromeos/components/camera_app_ui/resources/BUILD.gn
@@ -75,6 +75,7 @@ "js/async_job_queue.js", "js/background.js", "js/background_ops.js", + "js/barcode_chip.js", "js/chrome_util.js", "js/dom.js", "js/dynamic_import.js",
diff --git a/chromeos/components/camera_app_ui/resources/camera_app_resources.grd b/chromeos/components/camera_app_ui/resources/camera_app_resources.grd index 5d97b9d5..cdbc84c 100644 --- a/chromeos/components/camera_app_ui/resources/camera_app_resources.grd +++ b/chromeos/components/camera_app_ui/resources/camera_app_resources.grd
@@ -20,6 +20,7 @@ <structure name="IDR_CAMERA_BACKGROUND_JS" file="js/background.js" type="chrome_html" /> <structure name="IDR_CAMERA_BACKGROUND_OPS_JS" file="js/background_ops.js" type="chrome_html" /> <structure name="IDR_CAMERA_BARCODE_JS" file="js/models/barcode.js" type="chrome_html" /> + <structure name="IDR_CAMERA_BARCODE_CHIP_JS" file="js/barcode_chip.js" type="chrome_html" /> <structure name="IDR_CAMERA_BARCODE_WORKER_JS" file="js/models/barcode_worker.js" type="chrome_html" /> <structure name="IDR_CAMERA_BARCODE_WORKER_INTERFACE_JS" file="js/models/barcode_worker_interface.js" type="chrome_html" /> <structure name="IDR_CAMERA_BROWSER_PROXY_INTERFACE_JS" file="js/browser_proxy/browser_proxy_interface.js" type="chrome_html" /> @@ -154,49 +155,51 @@ <include name="IDR_CAMERA_TICK_FINAL_OGG" file="sounds/tick_final.ogg" type="BINDATA" /> <include name="IDR_CAMERA_TICK_INC_OGG" file="sounds/tick_inc.ogg" type="BINDATA" /> <include name="IDR_CAMERA_TICK_START_OGG" file="sounds/tick_start.ogg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_MODE_SQUARE_SVG" file="images/camera_mode_square.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_BUTTON_BACK_SVG" file="images/settings_button_back.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_MODE_PORTRAIT_SVG" file="images/camera_mode_portrait.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_3S_SVG" file="images/camera_button_timer_on_3s.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SPINNER_SVG" file="images/spinner.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_OFF_SVG" file="images/camera_button_grid_off.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_ON_SVG" file="images/camera_button_mic_on.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_MODE_VIDEO_SVG" file="images/camera_mode_video.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_SVG" file="images/camera_shutter_photo_stop.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_OFF_SVG" file="images/camera_button_mic_off.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_EXPERT_SVG" file="images/settings_expert.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_RESOLUTION_SVG" file="images/settings_resolution.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_APP_ICONS_48_PNG" file="images/camera_app_icons_48.png" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_OFF_SVG" file="images/camera_button_timer_off.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_ACTIVE_SVG" file="images/camera_shutter_photo_start_active.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_APP_ICONS_128_PNG" file="images/camera_app_icons_128.png" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_APP_ICONS_192_PNG" file="images/camera_app_icons_192.png" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_TIMER_DURATION_SVG" file="images/settings_timer_duration.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_HELP_SVG" file="images/settings_help.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_ON_SVG" file="images/camera_button_mirror_on.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_BUTTON_EXPAND_SVG" file="images/settings_button_expand.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_ON_SVG" file="images/camera_button_grid_on.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_DEVICE_SVG" file="images/camera_button_switch_device.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_HOVER_SVG" file="images/camera_shutter_photo_stop_hover.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_GRID_TYPE_SVG" file="images/settings_grid_type.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_OFF_SVG" file="images/camera_button_mirror_off.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_SVG" file="images/camera_shutter_photo_start.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_PHOTO_SVG" file="images/camera_button_switch_photo.svg" type="BINDATA" /> - <include name="IDR_CAMERA_SETTINGS_FEEDBACK_SVG" file="images/settings_feedback.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_VIDEO_SVG" file="images/camera_button_switch_video.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_HOVER_SVG" file="images/camera_shutter_photo_start_hover.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_PAUSE_SVG" file="images/camera_shutter_video_pause.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_10S_SVG" file="images/camera_button_timer_on_10s.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_MODE_PHOTO_SVG" file="images/camera_mode_photo.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_FOCUS_AIM_SVG" file="images/camera_focus_aim.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_BUTTON_SETTINGS_SVG" file="images/camera_button_settings.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_INTENT_PLAY_VIDEO_SVG" file="images/camera_intent_play_video.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_APP_ICONS_48_PNG" file="images/camera_app_icons_48.png" type="BINDATA" /> + <include name="IDR_CAMERA_BARCODE_URL_SVG" file="images/barcode_url.svg" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_BUTTON_FPS_30_SVG" file="images/camera_button_fps_30.svg" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_BUTTON_FPS_60_SVG" file="images/camera_button_fps_60.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_OFF_SVG" file="images/camera_button_grid_off.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_ON_SVG" file="images/camera_button_grid_on.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_OFF_SVG" file="images/camera_button_mic_off.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_ON_SVG" file="images/camera_button_mic_on.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_OFF_SVG" file="images/camera_button_mirror_off.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_ON_SVG" file="images/camera_button_mirror_on.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_SETTINGS_SVG" file="images/camera_button_settings.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_DEVICE_SVG" file="images/camera_button_switch_device.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_PHOTO_SVG" file="images/camera_button_switch_photo.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_VIDEO_SVG" file="images/camera_button_switch_video.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_OFF_SVG" file="images/camera_button_timer_off.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_10S_SVG" file="images/camera_button_timer_on_10s.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_3S_SVG" file="images/camera_button_timer_on_3s.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_FOCUS_AIM_SVG" file="images/camera_focus_aim.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_INTENT_PLAY_VIDEO_SVG" file="images/camera_intent_play_video.svg" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_INTENT_RESULT_CANCEL_SVG" file="images/camera_intent_result_cancel.svg" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_INTENT_RESULT_CONFIRM_SVG" file="images/camera_intent_result_confirm.svg" type="BINDATA" /> - <include name="IDR_CAMERA_CAMERA_INTRO_BANNER_ICON_SVG" file="images/camera_intro_banner_icon.svg" type="BINDATA" /> <include name="IDR_CAMERA_CAMERA_INTRO_BANNER_CLOSE_SVG" file="images/camera_intro_banner_close.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_INTRO_BANNER_ICON_SVG" file="images/camera_intro_banner_icon.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_MODE_PHOTO_SVG" file="images/camera_mode_photo.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_MODE_PORTRAIT_SVG" file="images/camera_mode_portrait.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_MODE_SQUARE_SVG" file="images/camera_mode_square.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_MODE_VIDEO_SVG" file="images/camera_mode_video.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_ACTIVE_SVG" file="images/camera_shutter_photo_start_active.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_HOVER_SVG" file="images/camera_shutter_photo_start_hover.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_SVG" file="images/camera_shutter_photo_start.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_HOVER_SVG" file="images/camera_shutter_photo_stop_hover.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_SVG" file="images/camera_shutter_photo_stop.svg" type="BINDATA" /> + <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_PAUSE_SVG" file="images/camera_shutter_video_pause.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_BUTTON_BACK_SVG" file="images/settings_button_back.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_BUTTON_EXPAND_SVG" file="images/settings_button_expand.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_EXPERT_SVG" file="images/settings_expert.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_FEEDBACK_SVG" file="images/settings_feedback.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_GRID_TYPE_SVG" file="images/settings_grid_type.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_HELP_SVG" file="images/settings_help.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_RESOLUTION_SVG" file="images/settings_resolution.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SETTINGS_TIMER_DURATION_SVG" file="images/settings_timer_duration.svg" type="BINDATA" /> + <include name="IDR_CAMERA_SPINNER_SVG" file="images/spinner.svg" type="BINDATA" /> </includes> </release> </grit>
diff --git a/chromeos/components/camera_app_ui/resources/css/main.css b/chromeos/components/camera_app_ui/resources/css/main.css index e79158d..8a21390 100644 --- a/chromeos/components/camera_app_ui/resources/css/main.css +++ b/chromeos/components/camera_app_ui/resources/css/main.css
@@ -1498,3 +1498,65 @@ body:not(.mode-switching):not(.streaming):not(.review-result) #spinner { visibility: visible; } + +.barcode-chip-container { + opacity: 0; + visibility: hidden; +} + +/* TODO(b/172879638): Tune the animation according to the final motion spec. */ +.barcode-chip-container.animate { + animation: 8s show-barcode-chip ease-out; + visibility: visible; +} + +@keyframes show-barcode-chip { + 0% { + opacity: 0; + } + 3%, + 97% { + opacity: 1; + } + 100% { + opacity: 0; + } +} + +/* TODO(b/172879638): Tune the position and layout after we finalized the + * responsive window design. */ +.barcode-chip-url { + align-items: center; + background: rgb(32, 33, 36); + border-radius: 16px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 4px 8px rgba(0, 0, 0, 0.15); + box-sizing: border-box; + display: flex; + font: 400 15px Roboto; + height: 32px; + left: 50%; + padding: 8px; + position: absolute; + top: 15%; + transform: translate(-50%, -50%); + z-index: 50; +} + +.barcode-chip-url::before { + background: url(/images/barcode_url.svg) no-repeat; + content: ''; + display: inline-block; + height: 20px; + margin-inline-end: 6px; + vertical-align: middle; + width: 20px; +} + +.barcode-chip-url > a { + color: rgb(138, 180, 248); + max-width: 416px; + overflow: hidden; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; +}
diff --git a/chromeos/components/camera_app_ui/resources/images/barcode_url.svg b/chromeos/components/camera_app_ui/resources/images/barcode_url.svg new file mode 100644 index 0000000..2580b44 --- /dev/null +++ b/chromeos/components/camera_app_ui/resources/images/barcode_url.svg
@@ -0,0 +1,3 @@ +<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M10 3C6.136 3 3 6.136 3 10C3 13.864 6.136 17 10 17C13.864 17 17 13.864 17 10C17 6.136 13.864 3 10 3ZM4.4 10C4.4 9.573 4.456 9.153 4.547 8.754L7.893 12.1V12.8C7.893 13.57 8.523 14.2 9.293 14.2V15.551C6.542 15.201 4.4 12.849 4.4 10ZM12.793 12.8C13.423 12.8 13.941 13.213 14.123 13.78C15.033 12.786 15.6 11.456 15.6 10C15.6 7.655 14.144 5.639 12.093 4.813V5.1C12.093 5.87 11.463 6.5 10.693 6.5H9.293V7.9C9.293 8.285 8.978 8.6 8.593 8.6H7.193V10H11.393C11.778 10 12.093 10.315 12.093 10.7V12.8H12.793Z" fill="#8BB5F9"/> +</svg>
diff --git a/chromeos/components/camera_app_ui/resources/images/images.gni b/chromeos/components/camera_app_ui/resources/images/images.gni index 0daf5667..24159cd 100644 --- a/chromeos/components/camera_app_ui/resources/images/images.gni +++ b/chromeos/components/camera_app_ui/resources/images/images.gni
@@ -3,6 +3,7 @@ # found in the LICENSE file. in_app_assets = [ + "barcode_url.svg", "camera_button_fps_30.svg", "camera_button_fps_60.svg", "camera_button_grid_off.svg",
diff --git a/chromeos/components/camera_app_ui/resources/js/BUILD.gn b/chromeos/components/camera_app_ui/resources/js/BUILD.gn index f2e1e1d..93beb35 100644 --- a/chromeos/components/camera_app_ui/resources/js/BUILD.gn +++ b/chromeos/components/camera_app_ui/resources/js/BUILD.gn
@@ -55,6 +55,7 @@ "async_job_queue.js", "background.js", "background_ops.js", + "barcode_chip.js", "browser_proxy/browser_proxy.js", "browser_proxy/browser_proxy_interface.js", "browser_proxy/webui_browser_proxy.js",
diff --git a/chromeos/components/camera_app_ui/resources/js/barcode_chip.js b/chromeos/components/camera_app_ui/resources/js/barcode_chip.js new file mode 100644 index 0000000..a62f50c --- /dev/null +++ b/chromeos/components/camera_app_ui/resources/js/barcode_chip.js
@@ -0,0 +1,62 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import * as dom from './dom.js'; +import * as toast from './toast.js'; +import * as util from './util.js'; + +/** + * Checks whether a string is a regular url link with http or https protocol. + * @param {string} s + * @return {boolean} + */ +function isSafeUrl(s) { + try { + const url = new URL(s); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + console.warn('Reject url with protocol:', url.protocol); + return false; + } + return true; + } catch (e) { + return false; + } +} + +/** + * Shows an actionable url chip. + * @param {string} url + */ +function showUrl(url) { + const el = dom.get('.barcode-chip-container', HTMLDivElement); + const anchor = dom.getFrom(el, 'a', HTMLAnchorElement); + Object.assign(anchor, { + href: url, + textContent: url, + }); + // TODO(b/172879638): Handle a11y. + util.animateOnce(el); + // TODO(b/172879638): Show copy button. +} + +/** + * Shows an actionable text chip. + * @param {string} text + */ +function showText(text) { + // TODO(b/172879638): Show text properly. + toast.showDebugMessage(text); +} + +/** + * Shows an actionable chip for the string detected from a barcode. + * @param {string} s + */ +export function show(s) { + if (isSafeUrl(s)) { + showUrl(s); + } else { + showText(s); + } +}
diff --git a/chromeos/components/camera_app_ui/resources/js/main.js b/chromeos/components/camera_app_ui/resources/js/main.js index 879daee..29536ca 100644 --- a/chromeos/components/camera_app_ui/resources/js/main.js +++ b/chromeos/components/camera_app_ui/resources/js/main.js
@@ -345,12 +345,10 @@ } browserProxy.setupUnloadListener(() => { - const intent = bgOps.getIntent(); - if (intent !== null && !intent.done) { - // TODO(crbug.com/1125997): Move the task to ServiceWorker once it is - // supported on SWA. - intent.cancel(); - } + // For SWA, we don't cancel the unhandled intent here since there is no + // guarantee that asynchronous calls in unload listener can be executed + // properly. Therefore, we moved the logic for canceling unhandled intent to + // Chrome (CameraAppHelper). if (appWindow !== null) { appWindow.notifyClosed(); }
diff --git a/chromeos/components/camera_app_ui/resources/js/models/barcode.js b/chromeos/components/camera_app_ui/resources/js/models/barcode.js index 5d2eeba..6eca1ce 100644 --- a/chromeos/components/camera_app_ui/resources/js/models/barcode.js +++ b/chromeos/components/camera_app_ui/resources/js/models/barcode.js
@@ -63,6 +63,7 @@ if (this.intervalId_ !== null) { return; } + // TODO(b/172879638): Move |prevCode| related logic to barcode_chip.js. let prevCode = null; this.intervalId_ = setAsyncInterval(async () => { const code = await this.scan_();
diff --git a/chromeos/components/camera_app_ui/resources/js/views/camera/preview.js b/chromeos/components/camera_app_ui/resources/js/views/camera/preview.js index b7ef0c3..8d3628c 100644 --- a/chromeos/components/camera_app_ui/resources/js/views/camera/preview.js +++ b/chromeos/components/camera_app_ui/resources/js/views/camera/preview.js
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import * as barcodeChip from '../../barcode_chip.js'; import {browserProxy} from '../../browser_proxy/browser_proxy.js'; import * as dom from '../../dom.js'; import {BarcodeScanner} from '../../models/barcode.js'; import {DeviceOperator, parseMetadata} from '../../mojo/device_operator.js'; import * as nav from '../../nav.js'; import * as state from '../../state.js'; -import * as toast from '../../toast.js'; import * as util from '../../util.js'; import {windowController} from '../../window_controller/window_controller.js'; @@ -162,9 +162,8 @@ this.onNewStreamNeeded_(); } }, 100); - this.scanner_ = new BarcodeScanner(this.video_, (code) => { - // TODO(b/172879638): Show this with a actionable toast. - toast.showDebugMessage(code); + this.scanner_ = new BarcodeScanner(this.video_, (value) => { + barcodeChip.show(value); }); this.updateScanBarcode_(); this.updateShowMetadata_(); @@ -213,6 +212,7 @@ if (this.scanner_ === null) { return; } + // TODO(b/172879638): Only enables barcode scanning in Photo mode. if (state.get(state.State.EXPERT) && state.get(state.State.SCAN_BARCODE)) { this.scanner_.start(); } else {
diff --git a/chromeos/components/camera_app_ui/resources/js/window_controller/mojo_window_controller.js b/chromeos/components/camera_app_ui/resources/js/window_controller/mojo_window_controller.js index afb72a74..94d728d 100644 --- a/chromeos/components/camera_app_ui/resources/js/window_controller/mojo_window_controller.js +++ b/chromeos/components/camera_app_ui/resources/js/window_controller/mojo_window_controller.js
@@ -45,41 +45,41 @@ /** @override */ async minimize() { - assertInstanceof( - this.windowStateController_, - chromeosCamera.mojom.WindowStateControllerRemote) + return assertInstanceof( + this.windowStateController_, + chromeosCamera.mojom.WindowStateControllerRemote) .minimize(); } /** @override */ async maximize() { - assertInstanceof( - this.windowStateController_, - chromeosCamera.mojom.WindowStateControllerRemote) + return assertInstanceof( + this.windowStateController_, + chromeosCamera.mojom.WindowStateControllerRemote) .maximize(); } /** @override */ async restore() { - assertInstanceof( - this.windowStateController_, - chromeosCamera.mojom.WindowStateControllerRemote) + return assertInstanceof( + this.windowStateController_, + chromeosCamera.mojom.WindowStateControllerRemote) .restore(); } /** @override */ async fullscreen() { - assertInstanceof( - this.windowStateController_, - chromeosCamera.mojom.WindowStateControllerRemote) + return assertInstanceof( + this.windowStateController_, + chromeosCamera.mojom.WindowStateControllerRemote) .fullscreen(); } /** @override */ async focus() { - assertInstanceof( - this.windowStateController_, - chromeosCamera.mojom.WindowStateControllerRemote) + return assertInstanceof( + this.windowStateController_, + chromeosCamera.mojom.WindowStateControllerRemote) .focus(); }
diff --git a/chromeos/components/camera_app_ui/resources/views/main.html b/chromeos/components/camera_app_ui/resources/views/main.html index 95633e4f..e315f8a 100644 --- a/chromeos/components/camera_app_ui/resources/views/main.html +++ b/chromeos/components/camera_app_ui/resources/views/main.html
@@ -400,6 +400,11 @@ </div> </div> <div class="centered-overlay" id="toast" aria-live="polite"></div> + <div class="barcode-chip-container"> + <div class="barcode-chip-url"> + <a target="_blank"></a> + </div> + </div> <div id="tooltip" aria-hidden="true"></div> <audio id="sound-tick-final" src="/sounds/tick_final.ogg" data-timeout="1000">
diff --git a/chromeos/components/help_app_ui/help_app_ui.cc b/chromeos/components/help_app_ui/help_app_ui.cc index 2214793..0732a23 100644 --- a/chromeos/components/help_app_ui/help_app_ui.cc +++ b/chromeos/components/help_app_ui/help_app_ui.cc
@@ -80,10 +80,6 @@ ContentSettingsType::JAVASCRIPT, ContentSettingsType::SOUND, }); - - // JavaScript errors are reported via CrashReportPrivate.reportError. Don't - // send duplicate reports via WebUI. - web_ui->DisableJavaScriptErrorReporting(); } HelpAppUI::~HelpAppUI() = default; @@ -110,6 +106,12 @@ std::make_unique<HelpAppPageHandler>(this, std::move(receiver)); } +bool HelpAppUI::IsJavascriptErrorReportingEnabled() { + // JavaScript errors are reported via CrashReportPrivate.reportError. Don't + // send duplicate reports via WebUI. + return false; +} + WEB_UI_CONTROLLER_TYPE_IMPL(HelpAppUI) } // namespace chromeos
diff --git a/chromeos/components/help_app_ui/help_app_ui.h b/chromeos/components/help_app_ui/help_app_ui.h index 970632e..894b7c8 100644 --- a/chromeos/components/help_app_ui/help_app_ui.h +++ b/chromeos/components/help_app_ui/help_app_ui.h
@@ -37,6 +37,8 @@ HelpAppUIDelegate* delegate() { return delegate_.get(); } + bool IsJavascriptErrorReportingEnabled() override; + private: // help_app_ui::mojom::PageHandlerFactory: void CreatePageHandler(
diff --git a/chromeos/components/media_app_ui/media_app_ui.cc b/chromeos/components/media_app_ui/media_app_ui.cc index 5aa892f..c703ddb1 100644 --- a/chromeos/components/media_app_ui/media_app_ui.cc +++ b/chromeos/components/media_app_ui/media_app_ui.cc
@@ -96,10 +96,6 @@ // Add ability to request chrome-untrusted: URLs. web_ui->AddRequestableScheme(content::kChromeUIUntrustedScheme); - - // JavaScript errors are reported via CrashReportPrivate.reportError. Don't - // send duplicate reports via WebUI. - web_ui->DisableJavaScriptErrorReporting(); } MediaAppUI::~MediaAppUI() = default; @@ -116,6 +112,12 @@ std::make_unique<MediaAppPageHandler>(this, std::move(receiver)); } +bool MediaAppUI::IsJavascriptErrorReportingEnabled() { + // JavaScript errors are reported via CrashReportPrivate.reportError. Don't + // send duplicate reports via WebUI. + return false; +} + WEB_UI_CONTROLLER_TYPE_IMPL(MediaAppUI) } // namespace chromeos
diff --git a/chromeos/components/media_app_ui/media_app_ui.h b/chromeos/components/media_app_ui/media_app_ui.h index 865fc43..508c38f 100644 --- a/chromeos/components/media_app_ui/media_app_ui.h +++ b/chromeos/components/media_app_ui/media_app_ui.h
@@ -31,6 +31,8 @@ mojo::PendingReceiver<media_app_ui::mojom::PageHandlerFactory> receiver); MediaAppUIDelegate* delegate() { return delegate_.get(); } + bool IsJavascriptErrorReportingEnabled() override; + private: // media_app_ui::mojom::PageHandlerFactory: void CreatePageHandler(mojo::PendingReceiver<media_app_ui::mojom::PageHandler>
diff --git a/chromeos/crosapi/mojom/BUILD.gn b/chromeos/crosapi/mojom/BUILD.gn index d0105e4..cda7e22 100644 --- a/chromeos/crosapi/mojom/BUILD.gn +++ b/chromeos/crosapi/mojom/BUILD.gn
@@ -14,6 +14,7 @@ "file_manager.mojom", "keystore_service.mojom", "message_center.mojom", + "metrics_reporting.mojom", "notification.mojom", "screen_manager.mojom", "select_file.mojom",
diff --git a/chromeos/crosapi/mojom/crosapi.mojom b/chromeos/crosapi/mojom/crosapi.mojom index e0af8d3..011b5242 100644 --- a/chromeos/crosapi/mojom/crosapi.mojom +++ b/chromeos/crosapi/mojom/crosapi.mojom
@@ -10,6 +10,7 @@ import "chromeos/crosapi/mojom/file_manager.mojom"; import "chromeos/crosapi/mojom/keystore_service.mojom"; import "chromeos/crosapi/mojom/message_center.mojom"; +import "chromeos/crosapi/mojom/metrics_reporting.mojom"; import "chromeos/crosapi/mojom/screen_manager.mojom"; import "chromeos/crosapi/mojom/select_file.mojom"; import "mojo/public/mojom/base/big_string.mojom"; @@ -40,8 +41,8 @@ // milestone when you added it, to help us reason about compatibility between // lacros-chrome and older ash-chrome binaries. // -// Next version: 8 -// Next method id: 13 +// Next version: 9 +// Next method id: 14 [Stable, Uuid="8b79c34f-2bf8-4499-979a-b17cac522c1e"] interface AshChromeService { // Binds Chrome OS Account Manager for Identity management. @@ -62,6 +63,11 @@ // Added in M86. BindMessageCenter@3(pending_receiver<MessageCenter> receiver); + // Binds the MetricsReporting interface for metrics reporting consent. + // Added in M89. + [MinVersion=8] + BindMetricsReporting@13(pending_receiver<MetricsReporting> receiver); + // Binds the ScreenManager interface for interacting with windows, screens and // displays. // Added in M86.
diff --git a/chromeos/crosapi/mojom/metrics_reporting.mojom b/chromeos/crosapi/mojom/metrics_reporting.mojom new file mode 100644 index 0000000..3667a61 --- /dev/null +++ b/chromeos/crosapi/mojom/metrics_reporting.mojom
@@ -0,0 +1,30 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module crosapi.mojom; + +// Interface for observers of metrics reporting consent. Implemented by +// lacros-chrome. Used by ash-chrome to send update notifications. +[Stable, Uuid="3bfcacbc-ab16-4731-9e11-3523983915d0"] +interface MetricsReportingObserver { + // Called when the metrics reporting state changes. + OnMetricsReportingChanged@0(bool enabled); +}; + +// Interface for metrics reporting consent. Implemented by ash-chrome. +// Next version: 1 +// Next method id: 2 +[Stable, Uuid="a2336315-84ad-413f-9190-9eb2906408f6"] +interface MetricsReporting { + // Adds an observer for metrics-related state. The observer is fired + // immediately with the current state. + AddObserver@0(pending_remote<MetricsReportingObserver> observer); + + // Sets the OS-level metrics reporting consent. This also affects crash + // report uploads. Lacros is allowed to do this for UX reasons. We have a + // toggle for metrics consent in lacros browser settings, in addition to the + // one in OS settings, and we want to keep both. Returns a value for possible + // future extension. + SetMetricsReportingEnabled@1(bool enabled) => (); +};
diff --git a/chromeos/ime/DIR_METADATA b/chromeos/ime/DIR_METADATA index e40e2774..1ae4c22 100644 --- a/chromeos/ime/DIR_METADATA +++ b/chromeos/ime/DIR_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Input>Text>IME" + component: "OS>Inputs" }
diff --git a/chromeos/lacros/lacros_chrome_service_impl.cc b/chromeos/lacros/lacros_chrome_service_impl.cc index ce91c97..26b354ab 100644 --- a/chromeos/lacros/lacros_chrome_service_impl.cc +++ b/chromeos/lacros/lacros_chrome_service_impl.cc
@@ -213,6 +213,12 @@ std::move(pending_receiver)); } + void BindMetricsReportingReceiver( + mojo::PendingReceiver<crosapi::mojom::MetricsReporting> receiver) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + ash_chrome_service_->BindMetricsReporting(std::move(receiver)); + } + base::WeakPtr<LacrosChromeServiceNeverBlockingState> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } @@ -516,6 +522,22 @@ weak_sequenced_state_, std::move(remote))); } +bool LacrosChromeServiceImpl::IsMetricsReportingAvailable() { + base::Optional<uint32_t> version = AshChromeServiceVersion(); + return version && version.value() >= AshChromeService::MethodMinVersions:: + kBindMetricsReportingMinVersion; +} + +void LacrosChromeServiceImpl::BindMetricsReporting( + mojo::PendingReceiver<crosapi::mojom::MetricsReporting> receiver) { + DCHECK(IsMetricsReportingAvailable()); + never_blocking_sequence_->PostTask( + FROM_HERE, + base::BindOnce( + &LacrosChromeServiceNeverBlockingState::BindMetricsReportingReceiver, + weak_sequenced_state_, std::move(receiver))); +} + bool LacrosChromeServiceImpl::IsCertDbAvailable() { base::Optional<uint32_t> version = AshChromeServiceVersion(); return version &&
diff --git a/chromeos/lacros/lacros_chrome_service_impl.h b/chromeos/lacros/lacros_chrome_service_impl.h index b949e812..c728dcc69 100644 --- a/chromeos/lacros/lacros_chrome_service_impl.h +++ b/chromeos/lacros/lacros_chrome_service_impl.h
@@ -19,6 +19,7 @@ #include "chromeos/crosapi/mojom/feedback.mojom.h" #include "chromeos/crosapi/mojom/keystore_service.mojom.h" #include "chromeos/crosapi/mojom/message_center.mojom.h" +#include "chromeos/crosapi/mojom/metrics_reporting.mojom.h" #include "chromeos/crosapi/mojom/screen_manager.mojom.h" #include "chromeos/crosapi/mojom/select_file.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -162,6 +163,14 @@ void BindMediaControllerManager( mojo::PendingReceiver<media_session::mojom::MediaControllerManager> remote); + + // Whether the MetricsReporting API is available. + bool IsMetricsReportingAvailable(); + + // Binds a receiver for the MetricsReporting API. May be called on any thread. + void BindMetricsReporting( + mojo::PendingReceiver<crosapi::mojom::MetricsReporting> receiver); + // cert_database_remote() can only be used when this method returns true; bool IsCertDbAvailable();
diff --git a/chromeos/services/ime/DIR_METADATA b/chromeos/services/ime/DIR_METADATA index e40e2774..1ae4c22 100644 --- a/chromeos/services/ime/DIR_METADATA +++ b/chromeos/services/ime/DIR_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Input>Text>IME" + component: "OS>Inputs" }
diff --git a/components/arc/ime/DIR_METADATA b/components/arc/ime/DIR_METADATA index e40e2774..e568bf01 100644 --- a/components/arc/ime/DIR_METADATA +++ b/components/arc/ime/DIR_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Input>Text>IME" + component: "Platform>Apps>ARC" }
diff --git a/components/autofill/android/provider/autofill_provider_android.cc b/components/autofill/android/provider/autofill_provider_android.cc index 2d7344240..56f0830 100644 --- a/components/autofill/android/provider/autofill_provider_android.cc +++ b/components/autofill/android/provider/autofill_provider_android.cc
@@ -355,6 +355,11 @@ } } +void AutofillProviderAndroid::OnServerPredictionsAvailable( + AutofillHandlerProxy* handler) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + void AutofillProviderAndroid::Reset(AutofillHandlerProxy* handler) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (handler == handler_.get()) {
diff --git a/components/autofill/android/provider/autofill_provider_android.h b/components/autofill/android/provider/autofill_provider_android.h index cddf4f9f..40d600f 100644 --- a/components/autofill/android/provider/autofill_provider_android.h +++ b/components/autofill/android/provider/autofill_provider_android.h
@@ -68,6 +68,7 @@ void OnFormsSeen(AutofillHandlerProxy* handler, const std::vector<FormData>& forms) override; void OnHidePopup(AutofillHandlerProxy* handler) override; + void OnServerPredictionsAvailable(AutofillHandlerProxy* handler) override; void Reset(AutofillHandlerProxy* handler) override;
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc index ba0c5dd..44f6f30 100644 --- a/components/autofill/content/browser/content_autofill_driver.cc +++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -61,7 +61,7 @@ content::RenderFrameHost* render_frame_host, AutofillClient* client, const std::string& app_locale, - AutofillManager::AutofillDownloadManagerState enable_download_manager, + AutofillHandler::AutofillDownloadManagerState enable_download_manager, AutofillProvider* provider) : render_frame_host_(render_frame_host), autofill_manager_(nullptr), @@ -70,7 +70,7 @@ // AutofillManager isn't used if provider is valid, Autofill provider is // currently used by Android WebView only. if (provider) { - SetAutofillProvider(provider); + SetAutofillProvider(provider, enable_download_manager); } else { SetAutofillManager(std::make_unique<AutofillManager>( this, client, app_locale, enable_download_manager)); @@ -158,8 +158,10 @@ void ContentAutofillDriver::PropagateAutofillPredictions( const std::vector<FormStructure*>& forms) { - autofill_manager_->client()->PropagateAutofillPredictions(render_frame_host_, - forms); + AutofillHandler* handler = + autofill_manager_ ? autofill_manager_ : autofill_handler_.get(); + DCHECK(handler); + handler->PropagateAutofillPredictions(render_frame_host_, forms); } void ContentAutofillDriver::HandleParsedForms( @@ -402,9 +404,11 @@ view->GetRenderWidgetHost()->RemoveKeyPressEventCallback(handler); } -void ContentAutofillDriver::SetAutofillProvider(AutofillProvider* provider) { - autofill_handler_ = - std::make_unique<AutofillHandlerProxy>(this, log_manager_, provider); +void ContentAutofillDriver::SetAutofillProvider( + AutofillProvider* provider, + AutofillHandler::AutofillDownloadManagerState enable_download_manager) { + autofill_handler_ = std::make_unique<AutofillHandlerProxy>( + this, log_manager_, provider, enable_download_manager); GetAutofillAgent()->SetUserGestureRequired(false); GetAutofillAgent()->SetSecureContextRequired(true); GetAutofillAgent()->SetFocusRequiresScroll(false); @@ -450,7 +454,8 @@ void ContentAutofillDriver::SetAutofillProviderForTesting( AutofillProvider* provider) { - SetAutofillProvider(provider); + SetAutofillProvider(provider, AutofillHandler::AutofillDownloadManagerState:: + DISABLE_AUTOFILL_DOWNLOAD_MANAGER); // AutofillManager isn't used if provider is valid. autofill_manager_ = nullptr; }
diff --git a/components/autofill/content/browser/content_autofill_driver.h b/components/autofill/content/browser/content_autofill_driver.h index 61f4467d..ab21b7c 100644 --- a/components/autofill/content/browser/content_autofill_driver.h +++ b/components/autofill/content/browser/content_autofill_driver.h
@@ -63,7 +63,7 @@ content::RenderFrameHost* render_frame_host, AutofillClient* client, const std::string& app_locale, - AutofillManager::AutofillDownloadManagerState enable_download_manager, + AutofillHandler::AutofillDownloadManagerState enable_download_manager, AutofillProvider* provider); ~ContentAutofillDriver() override; @@ -181,7 +181,9 @@ void RemoveHandler( const content::RenderWidgetHost::KeyPressEventCallback& handler) override; - void SetAutofillProvider(AutofillProvider* provider); + void SetAutofillProvider( + AutofillProvider* provider, + AutofillHandler::AutofillDownloadManagerState enable_download_manager); // Returns whether navigator.credentials.get({otp: {transport:"sms"}}) has // been used.
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 20427bb..250b371e8 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -623,6 +623,7 @@ "autofill_profile_sync_util_unittest.cc", "autofill_profile_validation_util_unittest.cc", "autofill_profile_validator_unittest.cc", + "autofill_provider_unittest.cc", "autofill_regexes_unittest.cc", "autofill_subject_unittest.cc", "autofill_type_unittest.cc",
diff --git a/components/autofill/core/browser/autofill_handler.h b/components/autofill/core/browser/autofill_handler.h index 1abb9fa..67d7d2b 100644 --- a/components/autofill/core/browser/autofill_handler.h +++ b/components/autofill/core/browser/autofill_handler.h
@@ -123,6 +123,12 @@ // Invoked when the options of a select element in the |form| changed. virtual void SelectFieldOptionsDidChange(const FormData& form) = 0; + // Invoked when the field type predictions are downloaded from the autofill + // server. + virtual void PropagateAutofillPredictions( + content::RenderFrameHost* rfh, + const std::vector<FormStructure*>& forms) = 0; + // Resets cache. virtual void Reset();
diff --git a/components/autofill/core/browser/autofill_handler_proxy.cc b/components/autofill/core/browser/autofill_handler_proxy.cc index 3643899..cf0d2ce8 100644 --- a/components/autofill/core/browser/autofill_handler_proxy.cc +++ b/components/autofill/core/browser/autofill_handler_proxy.cc
@@ -10,12 +10,14 @@ using base::TimeTicks; -AutofillHandlerProxy::AutofillHandlerProxy(AutofillDriver* driver, - LogManager* log_manager, - AutofillProvider* provider) +AutofillHandlerProxy::AutofillHandlerProxy( + AutofillDriver* driver, + LogManager* log_manager, + AutofillProvider* provider, + AutofillHandler::AutofillDownloadManagerState enable_download_manager) : AutofillHandler(driver, log_manager, - DISABLE_AUTOFILL_DOWNLOAD_MANAGER, + enable_download_manager, version_info::Channel::UNKNOWN), provider_(provider) {} @@ -90,7 +92,16 @@ void AutofillHandlerProxy::SelectFieldOptionsDidChange(const FormData& form) {} +void AutofillHandlerProxy::PropagateAutofillPredictions( + content::RenderFrameHost* rfh, + const std::vector<FormStructure*>& forms) { + has_server_prediction_ = true; + provider_->OnServerPredictionsAvailable(this); +} + void AutofillHandlerProxy::Reset() { + AutofillHandler::Reset(); + has_server_prediction_ = false; provider_->Reset(this); }
diff --git a/components/autofill/core/browser/autofill_handler_proxy.h b/components/autofill/core/browser/autofill_handler_proxy.h index a849caa..d178402 100644 --- a/components/autofill/core/browser/autofill_handler_proxy.h +++ b/components/autofill/core/browser/autofill_handler_proxy.h
@@ -15,9 +15,11 @@ // This class forwards AutofillHandler calls to AutofillProvider. class AutofillHandlerProxy : public AutofillHandler { public: - AutofillHandlerProxy(AutofillDriver* driver, - LogManager* log_manager, - AutofillProvider* provider); + AutofillHandlerProxy( + AutofillDriver* driver, + LogManager* log_manager, + AutofillProvider* provider, + AutofillHandler::AutofillDownloadManagerState enable_download_manager); ~AutofillHandlerProxy() override; void OnFocusNoLongerOnForm(bool had_interacted_form) override; @@ -36,6 +38,8 @@ return weak_ptr_factory_.GetWeakPtr(); } + bool has_server_prediction() const { return has_server_prediction_; } + protected: void OnFormSubmittedImpl(const FormData& form, bool known_success, @@ -74,7 +78,12 @@ void OnAfterProcessParsedForms( const std::set<FormType>& form_types) override {} + void PropagateAutofillPredictions( + content::RenderFrameHost* rfh, + const std::vector<FormStructure*>& forms) override; + private: + bool has_server_prediction_ = false; AutofillProvider* provider_; base::WeakPtrFactory<AutofillHandlerProxy> weak_ptr_factory_{this};
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index 3446e002..effb44a 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -1388,6 +1388,12 @@ TriggerRefill(form); } +void AutofillManager::PropagateAutofillPredictions( + content::RenderFrameHost* rfh, + const std::vector<FormStructure*>& forms) { + client_->PropagateAutofillPredictions(rfh, forms); +} + void AutofillManager::OnCreditCardFetched(bool did_succeed, const CreditCard* credit_card, const base::string16& cvc) {
diff --git a/components/autofill/core/browser/autofill_manager.h b/components/autofill/core/browser/autofill_manager.h index a0ca353..33f5c8f 100644 --- a/components/autofill/core/browser/autofill_manager.h +++ b/components/autofill/core/browser/autofill_manager.h
@@ -219,6 +219,9 @@ void OnDidEndTextFieldEditing() override; void OnHidePopup() override; void SelectFieldOptionsDidChange(const FormData& form) override; + void PropagateAutofillPredictions( + content::RenderFrameHost* rfh, + const std::vector<FormStructure*>& forms) override; void Reset() override; // AutocompleteHistoryManager::SuggestionsHandler:
diff --git a/components/autofill/core/browser/autofill_provider.h b/components/autofill/core/browser/autofill_provider.h index c624e6f..2b1d2b6e 100644 --- a/components/autofill/core/browser/autofill_provider.h +++ b/components/autofill/core/browser/autofill_provider.h
@@ -69,6 +69,8 @@ virtual void OnHidePopup(AutofillHandlerProxy* handler) = 0; + virtual void OnServerPredictionsAvailable(AutofillHandlerProxy* handler) = 0; + virtual void Reset(AutofillHandlerProxy* handler) = 0; void SendFormDataToRenderer(AutofillHandlerProxy* handler,
diff --git a/components/autofill/core/browser/autofill_provider_unittest.cc b/components/autofill/core/browser/autofill_provider_unittest.cc new file mode 100644 index 0000000..cf0d4650 --- /dev/null +++ b/components/autofill/core/browser/autofill_provider_unittest.cc
@@ -0,0 +1,90 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/browser/autofill_handler_proxy.h" +#include "components/autofill/core/browser/test_autofill_provider.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace autofill { + +class AutofillHandlerProxyTestHelper : public AutofillHandlerProxy { + public: + explicit AutofillHandlerProxyTestHelper(AutofillProvider* autofill_provider) + : AutofillHandlerProxy(nullptr, + nullptr, + autofill_provider, + DISABLE_AUTOFILL_DOWNLOAD_MANAGER) {} + + void SimulatePropagateAutofillPredictions() { + PropagateAutofillPredictions(nullptr, std::vector<FormStructure*>()); + } + + void SimulateOnQueryFormFieldAutofillImpl() { + OnQueryFormFieldAutofillImpl(0, FormData(), FormFieldData(), gfx::RectF(), + /*autoselect_first_suggestion=*/false); + } +}; + +class AutofillProviderTestHelper : public TestAutofillProvider { + public: + bool HasServerPrediction() const { return handler_->has_server_prediction(); } + + private: + // AutofillProvider + void OnQueryFormFieldAutofill(AutofillHandlerProxy* handler, + int32_t id, + const FormData& form, + const FormFieldData& field, + const gfx::RectF& bounding_box, + bool autoselect_first_suggestion) override { + handler_ = handler; + } + + AutofillHandlerProxy* handler_; +}; + +class AutofillProviderTest : public testing::Test { + public: + void SetUp() override { + autofill_provider_test_helper_ = + std::make_unique<AutofillProviderTestHelper>(); + autofill_handler_proxy_test_helper_ = + std::make_unique<AutofillHandlerProxyTestHelper>( + autofill_provider_test_helper_.get()); + } + + AutofillProviderTestHelper* autofill_provider_test_helper() { + return autofill_provider_test_helper_.get(); + } + + AutofillHandlerProxyTestHelper* autofill_handler_proxy_test_helper() { + return autofill_handler_proxy_test_helper_.get(); + } + + private: + std::unique_ptr<AutofillProviderTestHelper> autofill_provider_test_helper_; + std::unique_ptr<AutofillHandlerProxyTestHelper> + autofill_handler_proxy_test_helper_; +}; + +TEST_F(AutofillProviderTest, HasServerPredictionAfterQuery) { + // Simulate the result arrives after starting autofill. + autofill_handler_proxy_test_helper()->SimulateOnQueryFormFieldAutofillImpl(); + EXPECT_FALSE(autofill_provider_test_helper()->HasServerPrediction()); + autofill_handler_proxy_test_helper()->SimulatePropagateAutofillPredictions(); + EXPECT_TRUE(autofill_provider_test_helper()->HasServerPrediction()); + autofill_handler_proxy_test_helper()->Reset(); + EXPECT_FALSE(autofill_provider_test_helper()->HasServerPrediction()); +} + +TEST_F(AutofillProviderTest, HasServerPredictionBeforeQuery) { + // Simulate the result arrives before starting autofill. + autofill_handler_proxy_test_helper()->SimulatePropagateAutofillPredictions(); + autofill_handler_proxy_test_helper()->SimulateOnQueryFormFieldAutofillImpl(); + EXPECT_TRUE(autofill_provider_test_helper()->HasServerPrediction()); + autofill_handler_proxy_test_helper()->Reset(); + EXPECT_FALSE(autofill_provider_test_helper()->HasServerPrediction()); +} + +} // namespace autofill
diff --git a/components/autofill/core/browser/test_autofill_provider.h b/components/autofill/core/browser/test_autofill_provider.h index 25a3c10e..c249fc6 100644 --- a/components/autofill/core/browser/test_autofill_provider.h +++ b/components/autofill/core/browser/test_autofill_provider.h
@@ -49,6 +49,8 @@ void OnFormsSeen(AutofillHandlerProxy* handler, const std::vector<FormData>& forms) override {} void OnHidePopup(AutofillHandlerProxy* handler) override {} + void OnServerPredictionsAvailable(AutofillHandlerProxy* handler) override {} + void Reset(AutofillHandlerProxy* handler) override {} };
diff --git a/components/autofill_assistant/browser/actions/action_delegate.h b/components/autofill_assistant/browser/actions/action_delegate.h index 2765a58..deba417 100644 --- a/components/autofill_assistant/browser/actions/action_delegate.h +++ b/components/autofill_assistant/browser/actions/action_delegate.h
@@ -170,7 +170,8 @@ write_callback) = 0; using GetFullCardCallback = - base::OnceCallback<void(std::unique_ptr<autofill::CreditCard> card, + base::OnceCallback<void(const ClientStatus& status, + std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc)>; // Asks for the full card information for |credit_card|. Might require the
diff --git a/components/autofill_assistant/browser/actions/mock_action_delegate.h b/components/autofill_assistant/browser/actions/mock_action_delegate.h index 97a883b1..5a28613 100644 --- a/components/autofill_assistant/browser/actions/mock_action_delegate.h +++ b/components/autofill_assistant/browser/actions/mock_action_delegate.h
@@ -181,16 +181,9 @@ WriteUserData, void(base::OnceCallback<void(UserData*, UserData::FieldChange*)>)); - void GetFullCard(const autofill::CreditCard* credit_card, - ActionDelegate::GetFullCardCallback callback) override { - OnGetFullCard(credit_card, callback); - } - - MOCK_METHOD2( - OnGetFullCard, - void(const autofill::CreditCard* credit_card, - base::OnceCallback<void(std::unique_ptr<autofill::CreditCard> card, - const base::string16& cvc)>& callback)); + MOCK_METHOD2(GetFullCard, + void(const autofill::CreditCard* credit_card, + ActionDelegate::GetFullCardCallback callback)); MOCK_METHOD2(GetFieldValue, void(const ElementFinder::Result& element,
diff --git a/components/autofill_assistant/browser/actions/use_credit_card_action.cc b/components/autofill_assistant/browser/actions/use_credit_card_action.cc index 38b369192..65544a7 100644 --- a/components/autofill_assistant/browser/actions/use_credit_card_action.cc +++ b/components/autofill_assistant/browser/actions/use_credit_card_action.cc
@@ -139,13 +139,15 @@ } void UseCreditCardAction::OnGetFullCard( + const ClientStatus& status, std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc) { action_stopwatch_.StartActiveTime(); - if (!card) { - EndAction(ClientStatus(GET_FULL_CARD_FAILED)); + if (!status.ok()) { + EndAction(status); return; } + DCHECK(card); std::vector<RequiredField> required_fields; for (const auto& required_field_proto : proto_.use_card().required_fields()) {
diff --git a/components/autofill_assistant/browser/actions/use_credit_card_action.h b/components/autofill_assistant/browser/actions/use_credit_card_action.h index 7bf36ff..727d73e 100644 --- a/components/autofill_assistant/browser/actions/use_credit_card_action.h +++ b/components/autofill_assistant/browser/actions/use_credit_card_action.h
@@ -44,7 +44,8 @@ void OnWaitForElement(const ClientStatus& element_status); // Called after getting full credit card with its cvc. - void OnGetFullCard(std::unique_ptr<autofill::CreditCard> card, + void OnGetFullCard(const ClientStatus& status, + std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc); // Called when the form credit card has been filled.
diff --git a/components/autofill_assistant/browser/actions/use_credit_card_action_unittest.cc b/components/autofill_assistant/browser/actions/use_credit_card_action_unittest.cc index c0ae3a81..c8d0d24 100644 --- a/components/autofill_assistant/browser/actions/use_credit_card_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/use_credit_card_action_unittest.cc
@@ -37,7 +37,6 @@ using ::testing::Eq; using ::testing::Expectation; using ::testing::InSequence; -using ::testing::Invoke; using ::testing::NotNull; using ::testing::Pointee; using ::testing::Return; @@ -71,22 +70,26 @@ ON_CALL(mock_action_delegate_, GetPersonalDataManager) .WillByDefault(Return(&mock_personal_data_manager_)); ON_CALL(mock_action_delegate_, RunElementChecks) - .WillByDefault(Invoke([this](BatchElementChecker* checker) { + .WillByDefault([this](BatchElementChecker* checker) { checker->Run(&mock_web_controller_); - })); + }); ON_CALL(mock_action_delegate_, OnShortWaitForElement(_, _)) .WillByDefault(RunOnceCallback<1>(OkClientStatus(), base::TimeDelta::FromSeconds(0))); - ON_CALL(mock_action_delegate_, OnGetFullCard) - .WillByDefault(Invoke([](const autofill::CreditCard* credit_card, - base::OnceCallback<void( - std::unique_ptr<autofill::CreditCard> card, - const base::string16& cvc)>& callback) { - std::move(callback).Run( - credit_card ? std::make_unique<autofill::CreditCard>(*credit_card) - : nullptr, - base::UTF8ToUTF16(kFakeCvc)); - })); + ON_CALL(mock_action_delegate_, GetFullCard) + .WillByDefault( + [](const autofill::CreditCard* credit_card, + base::OnceCallback<void(const ClientStatus&, + std::unique_ptr<autofill::CreditCard>, + const base::string16&)> callback) { + std::move(callback).Run( + credit_card ? OkClientStatus() + : ClientStatus(GET_FULL_CARD_FAILED), + credit_card + ? std::make_unique<autofill::CreditCard>(*credit_card) + : nullptr, + base::UTF8ToUTF16(kFakeCvc)); + }); test_util::MockFindAnyElement(mock_web_controller_); }
diff --git a/components/autofill_assistant/browser/script_executor.cc b/components/autofill_assistant/browser/script_executor.cc index 86b779d..80910397 100644 --- a/components/autofill_assistant/browser/script_executor.cc +++ b/components/autofill_assistant/browser/script_executor.cc
@@ -422,10 +422,8 @@ std::move(callback).Run(link, user_data, user_model); } -void ScriptExecutor::GetFullCard( - const autofill::CreditCard* credit_card, - base::OnceCallback<void(std::unique_ptr<autofill::CreditCard> card, - const base::string16& cvc)> callback) { +void ScriptExecutor::GetFullCard(const autofill::CreditCard* credit_card, + GetFullCardCallback callback) { DCHECK(credit_card); // User might be asked to provide the cvc. @@ -441,10 +439,11 @@ } void ScriptExecutor::OnGetFullCard(GetFullCardCallback callback, + const ClientStatus& status, std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc) { delegate_->EnterState(AutofillAssistantState::RUNNING); - std::move(callback).Run(std::move(card), cvc); + std::move(callback).Run(status, std::move(card), cvc); } void ScriptExecutor::Prompt(
diff --git a/components/autofill_assistant/browser/script_executor.h b/components/autofill_assistant/browser/script_executor.h index 0963706e..ab6e678c 100644 --- a/components/autofill_assistant/browser/script_executor.h +++ b/components/autofill_assistant/browser/script_executor.h
@@ -430,6 +430,7 @@ UserData* user_data, const UserModel* user_model); void OnGetFullCard(GetFullCardCallback callback, + const ClientStatus& status, std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc); void OnChosen(UserAction::Callback callback,
diff --git a/components/autofill_assistant/browser/self_delete_full_card_requester.cc b/components/autofill_assistant/browser/self_delete_full_card_requester.cc index f0848b3..a282672 100644 --- a/components/autofill_assistant/browser/self_delete_full_card_requester.cc +++ b/components/autofill_assistant/browser/self_delete_full_card_requester.cc
@@ -14,6 +14,7 @@ #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/payments/full_card_request.h" #include "components/autofill/core/browser/personal_data_manager.h" +#include "components/autofill_assistant/browser/client_status.h" #include "content/public/browser/web_contents.h" namespace autofill_assistant { @@ -55,18 +56,36 @@ const FullCardRequest& /* full_card_request */, const autofill::CreditCard& card, const base::string16& cvc) { - std::move(callback_).Run(std::make_unique<autofill::CreditCard>(card), cvc); + std::move(callback_).Run(OkClientStatus(), + std::make_unique<autofill::CreditCard>(card), cvc); delete this; } void SelfDeleteFullCardRequester::OnFullCardRequestFailed( FullCardRequest::FailureType failure_type) { - // Failed might because of cancel, so return nullptr to notice caller. - // - // TODO(crbug.com/806868): Split the fail notification so that "cancel" and - // "wrong cvc" states can be handled differently. One should prompt a retry, - // the other a graceful shutdown - the current behavior. - std::move(callback_).Run(nullptr, base::string16()); + ClientStatus status(GET_FULL_CARD_FAILED); + AutofillErrorInfoProto::GetFullCardFailureType error_type = + AutofillErrorInfoProto::UNKNOWN_FAILURE_TYPE; + switch (failure_type) { + case FullCardRequest::FailureType::PROMPT_CLOSED: + error_type = AutofillErrorInfoProto::PROMPT_CLOSED; + break; + case FullCardRequest::FailureType::VERIFICATION_DECLINED: + error_type = AutofillErrorInfoProto::VERIFICATION_DECLINED; + break; + case FullCardRequest::FailureType::GENERIC_FAILURE: + error_type = AutofillErrorInfoProto::GENERIC_FAILURE; + break; + default: + // Adding the default case such that additions to + // FullCardRequest::FailureType do not need to add new cases to Autofill + // Assistant code. + break; + } + status.mutable_details() + ->mutable_autofill_error_info() + ->set_get_full_card_failure_type(error_type); + std::move(callback_).Run(status, nullptr, base::string16()); delete this; } } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto index 84771bb0..c77ec61cd 100644 --- a/components/autofill_assistant/browser/service.proto +++ b/components/autofill_assistant/browser/service.proto
@@ -877,6 +877,28 @@ // Errors that occurred during fallback filling of autofill fields. repeated AutofillFieldError autofill_field_error = 5; + + // These values should match the values in FullCardRequest::FailureType. + enum GetFullCardFailureType { + UNKNOWN_FAILURE_TYPE = 0; + + // The user closed the prompt. The following scenarios are possible: + // 1) The user declined to enter their CVC and closed the prompt. + // 2) The user provided their CVC, got auth declined and then closed the + // prompt without attempting a second time. + // 3) The user provided their CVC and closed the prompt before waiting for + // the result. + PROMPT_CLOSED = 1; + + // The card could not be looked up due to card auth declined or failed. + VERIFICATION_DECLINED = 2; + + // The request failed for technical reasons, such as a closing page or lack + // of network connection. + GENERIC_FAILURE = 3; + } + // Failure type from the |FullCardRequest|. + optional GetFullCardFailureType get_full_card_failure_type = 6; } // Message to report |SetFormFieldValueProto| related errors for debugging
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index 071f9f16..ea288e1 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -106,6 +106,8 @@ ShellSurface::~ShellSurface() { DCHECK(!scoped_configure_); + // Client is gone by now, so don't call callbask. + configure_callback_.Reset(); if (widget_) ash::WindowState::Get(widget_->GetNativeWindow())->RemoveObserver(this); } @@ -551,8 +553,8 @@ // If surface is being resized, save the resize direction. if (window_state && window_state->is_dragged() && !ends_drag) resize_component = window_state->drag_details()->window_component; - uint32_t serial = 0; + if (!configure_callback_.is_null()) { if (window_state) { serial = configure_callback_.Run( @@ -604,7 +606,8 @@ } auto end_drag = [](ShellSurface* shell_surface, ash::ToplevelWindowEventHandler::DragResult result) { - shell_surface->EndDrag(); + if (result != ash::ToplevelWindowEventHandler::DragResult::WINDOW_DESTROYED) + shell_surface->EndDrag(); }; if (gesture_target) {
diff --git a/components/exo/shell_surface_base.cc b/components/exo/shell_surface_base.cc index 978e366..619de8a 100644 --- a/components/exo/shell_surface_base.cc +++ b/components/exo/shell_surface_base.cc
@@ -329,6 +329,12 @@ // Remove activation observer before hiding widget to prevent it from // casuing the configure callback to be called. WMHelper::GetInstance()->RemoveActivationObserver(this); + + // Client is gone by now, so don't call callbacks. + close_callback_.Reset(); + pre_close_callback_.Reset(); + surface_destroyed_callback_.Reset(); + if (widget_) { widget_->GetNativeWindow()->RemoveObserver(this); widget_->RemoveObserver(this);
diff --git a/components/exo/shell_surface_unittest.cc b/components/exo/shell_surface_unittest.cc index c176fc09..6e57d80 100644 --- a/components/exo/shell_surface_unittest.cc +++ b/components/exo/shell_surface_unittest.cc
@@ -17,6 +17,7 @@ #include "base/callback.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/bind.h" #include "components/exo/buffer.h" #include "components/exo/permission.h" #include "components/exo/shell_surface_util.h" @@ -472,11 +473,17 @@ } TEST_F(ShellSurfaceTest, StartMove) { + // TODO: Ractor out the shell surface creation. + gfx::Size buffer_size(64, 64); + std::unique_ptr<Buffer> buffer( + new Buffer(exo_test_helper()->CreateGpuMemoryBuffer(buffer_size))); std::unique_ptr<Surface> surface(new Surface); std::unique_ptr<ShellSurface> shell_surface(new ShellSurface(surface.get())); // Map shell surface. + surface->Attach(buffer.get()); surface->Commit(); + ASSERT_TRUE(shell_surface->GetWidget()); // The interactive move should end when surface is destroyed. shell_surface->StartMove(); @@ -486,11 +493,16 @@ } TEST_F(ShellSurfaceTest, StartResize) { + gfx::Size buffer_size(64, 64); + std::unique_ptr<Buffer> buffer( + new Buffer(exo_test_helper()->CreateGpuMemoryBuffer(buffer_size))); std::unique_ptr<Surface> surface(new Surface); std::unique_ptr<ShellSurface> shell_surface(new ShellSurface(surface.get())); // Map shell surface. + surface->Attach(buffer.get()); surface->Commit(); + ASSERT_TRUE(shell_surface->GetWidget()); // The interactive resize should end when surface is destroyed. shell_surface->StartResize(HTBOTTOMRIGHT); @@ -499,6 +511,45 @@ surface.reset(); } +TEST_F(ShellSurfaceTest, StartResizeAndDestroyShell) { + gfx::Size buffer_size(64, 64); + std::unique_ptr<Buffer> buffer( + new Buffer(exo_test_helper()->CreateGpuMemoryBuffer(buffer_size))); + std::unique_ptr<Surface> surface(new Surface); + std::unique_ptr<ShellSurface> shell_surface(new ShellSurface(surface.get())); + + uint32_t serial = 0; + auto configure_callback = base::BindRepeating( + [](uint32_t* const serial_ptr, const gfx::Size& size, + chromeos::WindowStateType state_type, bool resizing, bool activated, + const gfx::Vector2d& origin_offset) { return ++(*serial_ptr); }, + &serial); + + // Map shell surface. + surface->Attach(buffer.get()); + shell_surface->set_configure_callback(configure_callback); + + surface->Commit(); + ASSERT_TRUE(shell_surface->GetWidget()); + + // The interactive resize should end when surface is destroyed. + shell_surface->StartResize(HTBOTTOMRIGHT); + + // Go through configure/commit stage to update the resize component. + shell_surface->AcknowledgeConfigure(serial); + surface->Commit(); + + shell_surface->set_configure_callback(base::BindRepeating( + [](const gfx::Size& size, chromeos::WindowStateType state_type, + bool resizing, bool activated, const gfx::Vector2d& origin_offset) { + ADD_FAILURE() << "Configure Should not be called"; + return uint32_t{0}; + })); + + // Test that destroying the surface before resize ends is OK. + shell_surface.reset(); +} + TEST_F(ShellSurfaceTest, SetGeometry) { gfx::Size buffer_size(64, 64); std::unique_ptr<Buffer> buffer(
diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc index 84f3e051..4254410 100644 --- a/components/printing/browser/print_manager.cc +++ b/components/printing/browser/print_manager.cc
@@ -92,6 +92,10 @@ #endif } +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) +void PrintManager::ShowScriptedPrintPreview(bool source_is_modifiable) {} +#endif + const mojo::AssociatedRemote<printing::mojom::PrintRenderFrame>& PrintManager::GetPrintRenderFrame(content::RenderFrameHost* rfh) { auto it = print_render_frames_.find(rfh);
diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h index 72765e53..4a74bed0 100644 --- a/components/printing/browser/print_manager.h +++ b/components/printing/browser/print_manager.h
@@ -60,6 +60,9 @@ void DidShowPrintDialog() override; void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie) override; +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) + void ShowScriptedPrintPreview(bool source_is_modifiable) override; +#endif protected: explicit PrintManager(content::WebContents* contents);
diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index 2c19fe7..6139d7e8 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom
@@ -313,4 +313,10 @@ // Tells the browser printing failed. PrintingFailed(int32 cookie); + + // Tells the browser to show the print preview, when the document is + // sufficiently loaded such that the renderer can determine whether it is + // modifiable or not. + [EnableIf=enable_print_preview] + ShowScriptedPrintPreview(bool is_modifiable); };
diff --git a/components/printing/common/print_messages.h b/components/printing/common/print_messages.h index 80c98a5..0167ee8 100644 --- a/components/printing/common/print_messages.h +++ b/components/printing/common/print_messages.h
@@ -325,11 +325,6 @@ // Run a nested run loop in the renderer until print preview for // window.print() finishes. IPC_SYNC_MESSAGE_ROUTED0_0(PrintHostMsg_SetupScriptedPrintPreview) - -// Tell the browser to show the print preview, when the document is sufficiently -// loaded such that the renderer can determine whether it is modifiable or not. -IPC_MESSAGE_ROUTED1(PrintHostMsg_ShowScriptedPrintPreview, - bool /* is_modifiable */) #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) #endif // COMPONENTS_PRINTING_COMMON_PRINT_MESSAGES_H_
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 07c52050..fe293f9 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -2381,8 +2381,8 @@ void PrintRenderFrameHelper::ShowScriptedPrintPreview() { if (is_scripted_preview_delayed_) { is_scripted_preview_delayed_ = false; - Send(new PrintHostMsg_ShowScriptedPrintPreview( - routing_id(), print_preview_context_.IsModifiable())); + GetPrintManagerHost()->ShowScriptedPrintPreview( + print_preview_context_.IsModifiable()); } } @@ -2414,8 +2414,8 @@ // Shows scripted print preview in two stages. // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by // pumping messages here. - // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the - // document has been loaded. + // 2. ShowScriptedPrintPreview() shows preview once the document has been + // loaded. is_scripted_preview_delayed_ = true; if (is_loading_ && print_preview_context_.IsPlugin()) { // Wait for DidStopLoading. Plugins may not know the correct
diff --git a/components/printing/test/print_render_frame_helper_browsertest.cc b/components/printing/test/print_render_frame_helper_browsertest.cc index 29be45e..8b58c95 100644 --- a/components/printing/test/print_render_frame_helper_browsertest.cc +++ b/components/printing/test/print_render_frame_helper_browsertest.cc
@@ -329,8 +329,10 @@ params->params->should_print_backgrounds = should_print_backgrounds.value(); std::move(callback).Run(std::move(params), canceled); } - void DidShowPrintDialog() override {} +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) + void ShowScriptedPrintPreview(bool source_is_modifiable) override {} +#endif bool IsPrinted() { return is_printed_; } void SetExpectedPagesCount(uint32_t number_pages) {
diff --git a/components/remote_cocoa/app_shim/BUILD.gn b/components/remote_cocoa/app_shim/BUILD.gn index a9bf35e..83ec524 100644 --- a/components/remote_cocoa/app_shim/BUILD.gn +++ b/components/remote_cocoa/app_shim/BUILD.gn
@@ -67,6 +67,7 @@ "//ui/base/ime:ime", "//ui/events", "//ui/gfx", + "//ui/gfx/geometry", "//ui/strings:ui_strings_grit", ] frameworks = [
diff --git a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h index 7068e5d2..cd6adf3 100644 --- a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h +++ b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h
@@ -235,7 +235,7 @@ bool is_maximizable) override; void SetOpacity(float opacity) override; void SetWindowLevel(int32_t level) override; - void SetContentAspectRatio(const gfx::SizeF& aspect_ratio) override; + void SetAspectRatio(const gfx::SizeF& aspect_ratio) override; void SetCALayerParams(const gfx::CALayerParams& ca_layer_params) override; void SetWindowTitle(const base::string16& title) override; void SetIgnoresMouseEvents(bool ignores_mouse_events) override;
diff --git a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm index cad39d6..d2b8854 100644 --- a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm +++ b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
@@ -1223,10 +1223,11 @@ [window_ setCollectionBehavior:behavior]; } -void NativeWidgetNSWindowBridge::SetContentAspectRatio( +void NativeWidgetNSWindowBridge::SetAspectRatio( const gfx::SizeF& aspect_ratio) { - [window_ setContentAspectRatio:NSMakeSize(aspect_ratio.width(), - aspect_ratio.height())]; + DCHECK(!aspect_ratio.IsEmpty()); + [window_delegate_ + setAspectRatio:aspect_ratio.width() / aspect_ratio.height()]; } void NativeWidgetNSWindowBridge::SetCALayerParams(
diff --git a/components/remote_cocoa/app_shim/views_nswindow_delegate.h b/components/remote_cocoa/app_shim/views_nswindow_delegate.h index a18e1861..93fefce 100644 --- a/components/remote_cocoa/app_shim/views_nswindow_delegate.h +++ b/components/remote_cocoa/app_shim/views_nswindow_delegate.h
@@ -8,6 +8,7 @@ #import <Cocoa/Cocoa.h> #import "base/mac/scoped_nsobject.h" +#include "base/optional.h" #include "components/remote_cocoa/app_shim/remote_cocoa_app_shim_export.h" namespace remote_cocoa { @@ -21,6 +22,19 @@ @private remote_cocoa::NativeWidgetNSWindowBridge* _parent; // Weak. Owns this. base::scoped_nsobject<NSCursor> _cursor; + base::Optional<float> _aspectRatio; + + // Only valid during a live resize. + // Used to keep track of whether a resize is happening horizontally or + // vertically, even if physically the user is resizing in both directions. + // The value is significant when |_aspectRatio| is set, i.e., we are + // responsible for maintaining the aspect ratio of the window. As the user is + // dragging one of the corners to resize, we need the resize to be either + // horizontal or vertical all the time, so we pick one of the directions and + // stick to it. This is necessary to achieve stable results, because in order + // to keep the aspect ratio fixed we override one window dimension with a + // value computed from the other dimension. + base::Optional<bool> _resizingHorizontally; } // If set, the cursor set in -[NSResponder updateCursor:] when the window is @@ -46,6 +60,14 @@ returnCode:(NSInteger)returnCode contextInfo:(void*)contextInfo; +// Set the aspect ratio of the window. Window resizes will be constrained in an +// attempt to maintain the aspect ratio. +// Cocoa provides this functionality via the [NSWindow aspectRatio] property, +// but its implementation prioritizes the aspect ratio over the minimum size: +// one of the dimensions can go below the minimum size if that's what it takes +// to maintain the aspect ratio. This is inacceptable for us. +- (void)setAspectRatio:(float)aspectRatio; + @end #endif // COMPONENTS_REMOTE_COCOA_APP_SHIM_VIEWS_NSWINDOW_DELEGATE_H_
diff --git a/components/remote_cocoa/app_shim/views_nswindow_delegate.mm b/components/remote_cocoa/app_shim/views_nswindow_delegate.mm index f6200119..3623959 100644 --- a/components/remote_cocoa/app_shim/views_nswindow_delegate.mm +++ b/components/remote_cocoa/app_shim/views_nswindow_delegate.mm
@@ -7,11 +7,13 @@ #include "base/bind.h" #include "base/check.h" #include "base/mac/mac_util.h" +#include "base/numerics/ranges.h" #include "base/threading/thread_task_runner_handle.h" #import "components/remote_cocoa/app_shim/bridged_content_view.h" #import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_host_helper.h" #include "components/remote_cocoa/common/native_widget_ns_window_host.mojom.h" +#include "ui/gfx/geometry/resize_utils.h" @implementation ViewsNSWindowDelegate @@ -101,6 +103,35 @@ DCHECK(!_parent->target_fullscreen_state()); } +- (void)setAspectRatio:(float)aspectRatio { + _aspectRatio = aspectRatio; +} + +- (NSSize)windowWillResize:(NSWindow*)window toSize:(NSSize)size { + if (!_aspectRatio) + return size; + + if (!_resizingHorizontally) { + const auto widthDelta = size.width - [window frame].size.width; + const auto heightDelta = size.height - [window frame].size.height; + _resizingHorizontally = std::abs(widthDelta) > std::abs(heightDelta); + } + + gfx::Rect resizedWindowRect(gfx::Point([window frame].origin), + gfx::Size(size)); + gfx::SizeRectToAspectRatio(*_resizingHorizontally ? gfx::ResizeEdge::kRight + : gfx::ResizeEdge::kBottom, + *_aspectRatio, gfx::Size([window minSize]), + gfx::Size([window maxSize]), &resizedWindowRect); + // Discard any updates to |resizedWindowRect| origin as Cocoa takes care of + // that. + return resizedWindowRect.size().ToCGSize(); +} + +- (void)windowDidEndLiveResize:(NSNotification*)notification { + _resizingHorizontally.reset(); +} + - (void)windowDidResize:(NSNotification*)notification { _parent->OnSizeChanged(); }
diff --git a/components/remote_cocoa/common/native_widget_ns_window.mojom b/components/remote_cocoa/common/native_widget_ns_window.mojom index b3dea656..693ce5c 100644 --- a/components/remote_cocoa/common/native_widget_ns_window.mojom +++ b/components/remote_cocoa/common/native_widget_ns_window.mojom
@@ -186,8 +186,8 @@ // Set the window level of the NSWindow. SetWindowLevel(int32 level); - // Set the content aspect ratio of the NSWindow. - SetContentAspectRatio(gfx.mojom.SizeF aspect_ratio); + // Set the aspect ratio of the NSWindow. |aspect_ratio| must not be empty. + SetAspectRatio(gfx.mojom.SizeF aspect_ratio); // Specify the content to draw in the NSView. SetCALayerParams(gfx.mojom.CALayerParams ca_layer_params);
diff --git a/components/services/storage/dom_storage/local_storage_impl.cc b/components/services/storage/dom_storage/local_storage_impl.cc index 984464f..de0796d 100644 --- a/components/services/storage/dom_storage/local_storage_impl.cc +++ b/components/services/storage/dom_storage/local_storage_impl.cc
@@ -431,12 +431,12 @@ LocalStorageImpl* context_; url::Origin origin_; - std::unique_ptr<StorageAreaImpl> area_; // Holds the same value as |area_|. The reason for this is that // during destruction of the StorageAreaImpl instance we might still get // called and need access to the StorageAreaImpl instance. The unique_ptr // could already be null, but this field should still be valid. StorageAreaImpl* area_ptr_; + std::unique_ptr<StorageAreaImpl> area_; bool deleted_old_data_ = false; bool has_bindings_ = false; };
diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc index 4ada388..508dac7 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc
@@ -486,12 +486,7 @@ auto disable_reasons = GetDisableReasons(); disable_reasons.RemoveAll(SyncService::DisableReasonSet( DISABLE_REASON_USER_CHOICE, DISABLE_REASON_PLATFORM_OVERRIDE)); - return disable_reasons.Empty() && !IsInPausedState(); -} - -bool ProfileSyncService::IsInPausedState() const { - return auth_manager_->IsSyncPaused() && - base::FeatureList::IsEnabled(switches::kStopSyncInPausedState); + return disable_reasons.Empty() && !auth_manager_->IsSyncPaused(); } void ProfileSyncService::OnProtocolEvent(const ProtocolEvent& event) { @@ -788,8 +783,8 @@ if (!IsEngineAllowedToRun()) { // We generally shouldn't have an engine while in a disabled state, but it // can happen if this method gets called during ShutdownImpl(). - return IsInPausedState() ? TransportState::PAUSED - : TransportState::DISABLED; + return auth_manager_->IsSyncPaused() ? TransportState::PAUSED + : TransportState::DISABLED; } if (!engine_ || !engine_->IsInitialized()) {
diff --git a/components/sync/driver/profile_sync_service.h b/components/sync/driver/profile_sync_service.h index 34280f8..83a4664 100644 --- a/components/sync/driver/profile_sync_service.h +++ b/components/sync/driver/profile_sync_service.h
@@ -285,10 +285,6 @@ bool IsEngineAllowedToRun() const; - // Same as GetTransportState() returning PAUSED. In this state, the engine - // shouldn't run. - bool IsInPausedState() const; - // Reconfigures the data type manager with the latest enabled types. // Note: Does not initialize the engine if it is not already initialized. // If a Sync setup is currently in progress (i.e. a settings UI is open), then
diff --git a/components/sync/driver/profile_sync_service_unittest.cc b/components/sync/driver/profile_sync_service_unittest.cc index 9a0ae3c..ba3d40e 100644 --- a/components/sync/driver/profile_sync_service_unittest.cc +++ b/components/sync/driver/profile_sync_service_unittest.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" +#include "base/callback_helpers.h" #include "base/command_line.h" #include "base/run_loop.h" #include "base/test/bind.h" @@ -329,19 +330,6 @@ SyncClientMock* sync_client_; // Owned by |service_|. }; -class ProfileSyncServiceTestWithStopSyncInPausedState - : public ProfileSyncServiceTest { - public: - ProfileSyncServiceTestWithStopSyncInPausedState() { - override_features_.InitAndEnableFeature(switches::kStopSyncInPausedState); - } - - ~ProfileSyncServiceTestWithStopSyncInPausedState() override = default; - - private: - base::test::ScopedFeatureList override_features_; -}; - class ProfileSyncServiceTestWithSyncInvalidationsServiceCreated : public ProfileSyncServiceTest { public: @@ -807,7 +795,7 @@ EXPECT_CALL(*component_factory(), CreateSyncEngine) .WillOnce( Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, base::RepeatingClosure())))); + &init_account_id, base::DoNothing())))); InitializeForNthSync(); ASSERT_EQ(SyncService::TransportState::ACTIVE, service()->GetTransportState()); @@ -840,9 +828,6 @@ // Checks that CREDENTIALS_REJECTED_BY_CLIENT resets the access token and stops // Sync. Regression test for https://crbug.com/824791. TEST_F(ProfileSyncServiceTest, CredentialsRejectedByClient_StopSync) { - base::test::ScopedFeatureList feature; - feature.InitAndEnableFeature(switches::kStopSyncInPausedState); - CoreAccountId init_account_id; SignIn(); @@ -850,7 +835,7 @@ EXPECT_CALL(*component_factory(), CreateSyncEngine) .WillOnce( Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, base::RepeatingClosure())))); + &init_account_id, base::DoNothing())))); InitializeForNthSync(); ASSERT_EQ(SyncService::TransportState::ACTIVE, service()->GetTransportState()); @@ -898,70 +883,6 @@ service()->RemoveObserver(&observer); } -TEST_F(ProfileSyncServiceTest, CredentialsRejectedByClient_DoNotStopSync) { - base::test::ScopedFeatureList feature; - feature.InitAndDisableFeature(switches::kStopSyncInPausedState); - - CoreAccountId init_account_id; - - bool invalidate_credentials_called = false; - base::RepeatingClosure invalidate_credentials_callback = - base::BindRepeating([](bool* called) { *called = true; }, - base::Unretained(&invalidate_credentials_called)); - - SignIn(); - CreateService(ProfileSyncService::MANUAL_START); - EXPECT_CALL(*component_factory(), CreateSyncEngine) - .WillOnce( - Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, invalidate_credentials_callback)))); - InitializeForNthSync(); - ASSERT_EQ(SyncService::TransportState::ACTIVE, - service()->GetTransportState()); - - TestSyncServiceObserver observer; - service()->AddObserver(&observer); - - const CoreAccountId primary_account_id = - identity_manager()->GetPrimaryAccountId(); - - // Make sure the expected account_id was passed to the SyncEngine. - ASSERT_EQ(primary_account_id, init_account_id); - - // At this point, the real SyncEngine would try to connect to the server, fail - // (because it has no access token), and eventually call - // OnConnectionStatusChange(CONNECTION_AUTH_ERROR). Since our fake SyncEngine - // doesn't do any of this, call that explicitly here. - service()->OnConnectionStatusChange(CONNECTION_AUTH_ERROR); - - base::RunLoop().RunUntilIdle(); - ASSERT_FALSE(service()->GetAccessTokenForTest().empty()); - ASSERT_EQ(GoogleServiceAuthError::AuthErrorNone(), service()->GetAuthError()); - ASSERT_EQ(GoogleServiceAuthError::AuthErrorNone(), observer.auth_error()); - - // Simulate the credentials getting locally rejected by the client by setting - // the refresh token to a special invalid value. - identity_test_env()->SetInvalidRefreshTokenForPrimaryAccount(); - const GoogleServiceAuthError rejected_by_client = - GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( - GoogleServiceAuthError::InvalidGaiaCredentialsReason:: - CREDENTIALS_REJECTED_BY_CLIENT); - ASSERT_EQ(rejected_by_client, - identity_test_env() - ->identity_manager() - ->GetErrorStateOfRefreshTokenForAccount(primary_account_id)); - EXPECT_TRUE(service()->GetAccessTokenForTest().empty()); - EXPECT_TRUE(invalidate_credentials_called); - - // The observer should have been notified of the auth error state. - EXPECT_EQ(rejected_by_client, observer.auth_error()); - // The Sync engine should still be running. - EXPECT_EQ(SyncService::TransportState::ACTIVE, - service()->GetTransportState()); - - service()->RemoveObserver(&observer); -} - // CrOS does not support signout. #if !BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(ProfileSyncServiceTest, SignOutRevokeAccessToken) { @@ -972,7 +893,7 @@ EXPECT_CALL(*component_factory(), CreateSyncEngine) .WillOnce( Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, base::RepeatingClosure())))); + &init_account_id, base::DoNothing())))); InitializeForNthSync(); ASSERT_EQ(SyncService::TransportState::ACTIVE, service()->GetTransportState()); @@ -1079,7 +1000,7 @@ EXPECT_CALL(*component_factory(), CreateSyncEngine) .WillOnce( Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, base::RepeatingClosure())))); + &init_account_id, base::DoNothing())))); InitializeForNthSync(); ASSERT_EQ(SyncService::TransportState::ACTIVE, service()->GetTransportState()); @@ -1140,7 +1061,7 @@ EXPECT_CALL(*component_factory(), CreateSyncEngine) .WillOnce( Return(ByMove(std::make_unique<FakeSyncEngineCollectCredentials>( - &init_account_id, base::RepeatingClosure())))); + &init_account_id, base::DoNothing())))); InitializeForNthSync(); ASSERT_EQ(SyncService::TransportState::ACTIVE, service()->GetTransportState()); @@ -1391,8 +1312,7 @@ // Regression test for crbug.com/1043642, can be removed once // ProfileSyncService usages after shutdown are addressed. -TEST_F(ProfileSyncServiceTestWithStopSyncInPausedState, - ShouldProvideDisableReasonsAfterShutdown) { +TEST_F(ProfileSyncServiceTest, ShouldProvideDisableReasonsAfterShutdown) { SignIn(); CreateService(ProfileSyncService::MANUAL_START); InitializeForFirstSync();
diff --git a/components/sync/driver/sync_driver_switches.cc b/components/sync/driver/sync_driver_switches.cc index 33a0aa79..757c8964 100644 --- a/components/sync/driver/sync_driver_switches.cc +++ b/components/sync/driver/sync_driver_switches.cc
@@ -40,10 +40,6 @@ // sure that it's what you want. const char kSyncShortNudgeDelayForTest[] = "sync-short-nudge-delay-for-test"; -// If enabled, the sync engine will be shut down in the "paused" state. -const base::Feature kStopSyncInPausedState{"StopSyncInPausedState", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Allows custom passphrase users to receive Wallet data for secondary accounts // while in transport-only mode. const base::Feature kSyncAllowWalletDataInTransportModeWithCustomPassphrase{
diff --git a/components/sync/driver/sync_driver_switches.h b/components/sync/driver/sync_driver_switches.h index eb828dc..ff0a86cb 100644 --- a/components/sync/driver/sync_driver_switches.h +++ b/components/sync/driver/sync_driver_switches.h
@@ -25,7 +25,6 @@ extern const char kSyncShortInitialRetryOverride[]; extern const char kSyncShortNudgeDelayForTest[]; -extern const base::Feature kStopSyncInPausedState; extern const base::Feature kSyncAllowWalletDataInTransportModeWithCustomPassphrase; extern const base::Feature kSyncAutofillWalletOfferData;
diff --git a/components/sync/engine/sync_engine_switches.cc b/components/sync/engine/sync_engine_switches.cc index 92c6b650..0ebfee9 100644 --- a/components/sync/engine/sync_engine_switches.cc +++ b/components/sync/engine/sync_engine_switches.cc
@@ -21,6 +21,6 @@ "SyncSupportTrustedVaultPassphrase", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kSyncTriggerFullKeystoreMigration{ - "SyncTriggerFullKeystoreMigration", base::FEATURE_ENABLED_BY_DEFAULT}; + "SyncTriggerFullKeystoreMigration", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace switches
diff --git a/components/translate/core/browser/translate_language_list.cc b/components/translate/core/browser/translate_language_list.cc index f781fce..cbb4870 100644 --- a/components/translate/core/browser/translate_language_list.cc +++ b/components/translate/core/browser/translate_language_list.cc
@@ -36,9 +36,9 @@ // The default list of languages the Google translation server supports. // We use this list until we receive the list that the server exposes. -// Server also supports "hmm" (Hmong) and "jw" (Javanese), but these are -// excluded because Chrome l10n library does not support it. This list must be -// sorted in alphabetical order and contain no duplicates. +// Server also supports "hmm" (Hmong), "jw" (Javanese) and "rw" (Kinyarwanda), +// but these are excluded because Chrome l10n library does not support it. This +// list must be sorted in alphabetical order and contain no duplicates. const char* const kDefaultSupportedLanguages[] = { "af", // Afrikaans "am", // Amharic @@ -107,6 +107,7 @@ "nl", // Dutch "no", // Norwegian "ny", // Nyanja + "or", // Odia (Oriya) "pa", // Punjabi "pl", // Polish "ps", // Pashto @@ -130,8 +131,11 @@ "te", // Telugu "tg", // Tajik "th", // Thai + "tk", // Turkmen "tl", // Tagalog "tr", // Turkish + "tt", // Tatar + "ug", // Uyghur "uk", // Ukrainian "ur", // Urdu "uz", // Uzbek @@ -209,8 +213,8 @@ // static GURL TranslateLanguageList::TranslateLanguageUrl() { - std::string url = translate::GetTranslateSecurityOrigin().spec() + - kLanguageListFetchPath; + std::string url = + translate::GetTranslateSecurityOrigin().spec() + kLanguageListFetchPath; return GURL(url); }
diff --git a/components/web_package/web_bundle_parser.cc b/components/web_package/web_bundle_parser.cc index 3fa0edd..cba04b8 100644 --- a/components/web_package/web_bundle_parser.cc +++ b/components/web_package/web_bundle_parser.cc
@@ -278,10 +278,10 @@ if (url.has_ref() || url.has_username() || url.has_password()) return GURL(); - // For now, we allow only http: and https: schemes in Web Bundle URLs. + // For now, we allow only http:, https: and urn: schemes in Web Bundle URLs. // TODO(crbug.com/966753): Revisit this once // https://github.com/WICG/webpackage/issues/468 is resolved. - if (!url.SchemeIsHTTPOrHTTPS()) + if (!url.SchemeIsHTTPOrHTTPS() && !url.SchemeIs("urn")) return GURL(); return url;
diff --git a/content/browser/android/web_contents_observer_proxy.cc b/content/browser/android/web_contents_observer_proxy.cc index 58d3d40f3..c75fc96 100644 --- a/content/browser/android/web_contents_observer_proxy.cc +++ b/content/browser/android/web_contents_observer_proxy.cc
@@ -21,6 +21,7 @@ #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" +#include "url/android/gurl_android.h" using base::android::AttachCurrentThread; using base::android::JavaParamRef; @@ -100,25 +101,23 @@ void WebContentsObserverProxy::DidStartLoading() { JNIEnv* env = AttachCurrentThread(); - ScopedJavaLocalRef<jstring> jstring_url( - ConvertUTF8ToJavaString(env, web_contents()->GetVisibleURL().spec())); if (auto* entry = web_contents()->GetController().GetPendingEntry()) { base_url_of_last_started_data_url_ = entry->GetBaseURLForDataURL(); } - Java_WebContentsObserverProxy_didStartLoading(env, java_observer_, - jstring_url); + Java_WebContentsObserverProxy_didStartLoading( + env, java_observer_, + url::GURLAndroid::FromNativeGURL(env, web_contents()->GetVisibleURL())); } void WebContentsObserverProxy::DidStopLoading() { JNIEnv* env = AttachCurrentThread(); - std::string url_string = web_contents()->GetLastCommittedURL().spec(); - SetToBaseURLForDataURLIfNeeded(&url_string); + GURL url = web_contents()->GetLastCommittedURL(); + bool assume_valid = SetToBaseURLForDataURLIfNeeded(&url); // DidStopLoading is the last event we should get. base_url_of_last_started_data_url_ = GURL::EmptyGURL(); - ScopedJavaLocalRef<jstring> jstring_url(ConvertUTF8ToJavaString( - env, url_string)); - Java_WebContentsObserverProxy_didStopLoading(env, java_observer_, - jstring_url); + Java_WebContentsObserverProxy_didStopLoading( + env, java_observer_, url::GURLAndroid::FromNativeGURL(env, url), + assume_valid); } void WebContentsObserverProxy::LoadProgressChanged(double progress) { @@ -130,12 +129,9 @@ const GURL& validated_url, int error_code) { JNIEnv* env = AttachCurrentThread(); - ScopedJavaLocalRef<jstring> jstring_url( - ConvertUTF8ToJavaString(env, validated_url.spec())); - - Java_WebContentsObserverProxy_didFailLoad(env, java_observer_, - !render_frame_host->GetParent(), - error_code, jstring_url); + Java_WebContentsObserverProxy_didFailLoad( + env, java_observer_, !render_frame_host->GetParent(), error_code, + url::GURLAndroid::FromNativeGURL(env, validated_url)); } void WebContentsObserverProxy::DidChangeVisibleSecurityState() { @@ -177,13 +173,12 @@ const GURL& validated_url) { JNIEnv* env = AttachCurrentThread(); - std::string url_string = validated_url.spec(); - SetToBaseURLForDataURLIfNeeded(&url_string); + GURL url = validated_url; + bool assume_valid = SetToBaseURLForDataURLIfNeeded(&url); - ScopedJavaLocalRef<jstring> jstring_url( - ConvertUTF8ToJavaString(env, url_string)); Java_WebContentsObserverProxy_didFinishLoad( - env, java_observer_, render_frame_host->GetRoutingID(), jstring_url, + env, java_observer_, render_frame_host->GetRoutingID(), + url::GURLAndroid::FromNativeGURL(env, url), assume_valid, !render_frame_host->GetParent()); } @@ -252,21 +247,23 @@ Java_WebContentsObserverProxy_titleWasSet(env, java_observer_, jstring_title); } -void WebContentsObserverProxy::SetToBaseURLForDataURLIfNeeded( - std::string* url) { +bool WebContentsObserverProxy::SetToBaseURLForDataURLIfNeeded(GURL* url) { NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); // Note that GetBaseURLForDataURL is only used by the Android WebView. // FIXME: Should we only return valid specs and "about:blank" for invalid // ones? This may break apps. if (entry && !entry->GetBaseURLForDataURL().is_empty()) { - *url = entry->GetBaseURLForDataURL().possibly_invalid_spec(); + *url = entry->GetBaseURLForDataURL(); + return false; } else if (!base_url_of_last_started_data_url_.is_empty()) { // NavigationController can lose the pending entry and recreate it without // a base URL if there has been a loadUrl("javascript:...") after // loadDataWithBaseUrl. - *url = base_url_of_last_started_data_url_.possibly_invalid_spec(); + *url = base_url_of_last_started_data_url_; + return false; } + return true; } void WebContentsObserverProxy::ViewportFitChanged(
diff --git a/content/browser/android/web_contents_observer_proxy.h b/content/browser/android/web_contents_observer_proxy.h index 5764b7d..8140ec36 100644 --- a/content/browser/android/web_contents_observer_proxy.h +++ b/content/browser/android/web_contents_observer_proxy.h
@@ -62,7 +62,7 @@ void WebContentsDestroyed() override; void DidChangeThemeColor() override; void MediaEffectivelyFullscreenChanged(bool is_fullscreen) override; - void SetToBaseURLForDataURLIfNeeded(std::string* url); + bool SetToBaseURLForDataURLIfNeeded(GURL* url); void ViewportFitChanged(blink::mojom::ViewportFit value) override; void OnWebContentsFocused(RenderWidgetHost*) override; void OnWebContentsLostFocus(RenderWidgetHost*) override;
diff --git a/content/browser/file_system_access/native_file_system_directory_handle_impl.cc b/content/browser/file_system_access/native_file_system_directory_handle_impl.cc index de58fb9b..2472c89 100644 --- a/content/browser/file_system_access/native_file_system_directory_handle_impl.cc +++ b/content/browser/file_system_access/native_file_system_directory_handle_impl.cc
@@ -4,6 +4,7 @@ #include "content/browser/file_system_access/native_file_system_directory_handle_impl.h" +#include "base/i18n/file_util_icu.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -12,6 +13,7 @@ #include "content/browser/file_system_access/native_file_system_transfer_token_impl.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/escape.h" +#include "net/base/filename_util.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_operation_runner.h" #include "storage/common/file_system/file_system_util.h" @@ -30,27 +32,6 @@ using HandleType = NativeFileSystemPermissionContext::HandleType; -namespace { - -// Returns true when |name| contains a path separator like "/". -bool ContainsPathSeparator(const std::string& name) { - const base::FilePath filepath_name = storage::StringToFilePath(name); - - const size_t separator_position = - filepath_name.value().find_first_of(base::FilePath::kSeparators); - - return separator_position != base::FilePath::StringType::npos; -} - -// Returns true when |name| is "." or "..". -bool IsCurrentOrParentDirectory(const std::string& name) { - const base::FilePath filepath_name = storage::StringToFilePath(name); - return filepath_name.value() == base::FilePath::kCurrentDirectory || - filepath_name.value() == base::FilePath::kParentDirectory; -} - -} // namespace - NativeFileSystemDirectoryHandleImpl::NativeFileSystemDirectoryHandleImpl( NativeFileSystemManagerImpl* manager, const BindingContext& context, @@ -379,9 +360,10 @@ blink::mojom::NativeFileSystemErrorPtr get_child_url_result = GetChildURL(basename, &child_url); - // All entries must exist in this directory as a direct child with a valid - // |basename|. - CHECK_EQ(get_child_url_result->status, NativeFileSystemStatus::kOk); + // Skip any entries with names that aren't allowed to be accessed by + // this API, such as files with disallowed characters in their names. + if (get_child_url_result->status != NativeFileSystemStatus::kOk) + continue; entries.push_back( CreateEntry(basename, child_url, @@ -412,25 +394,97 @@ url, recurse); } +namespace { + +// Returns whether the specified extension receives special handling by the +// Windows shell. +bool IsShellIntegratedExtension(const base::FilePath::StringType& extension) { + base::FilePath::StringType extension_lower = base::ToLowerASCII(extension); + + // .lnk files may be used to execute arbitrary code (see + // https://nvd.nist.gov/vuln/detail/CVE-2010-2568). + if (extension_lower == FILE_PATH_LITERAL("lnk")) + return true; + + // Setting a file's extension to a CLSID may conceal its actual file type on + // some Windows versions (see https://nvd.nist.gov/vuln/detail/CVE-2004-0420). + if (!extension_lower.empty() && + (extension_lower.front() == FILE_PATH_LITERAL('{')) && + (extension_lower.back() == FILE_PATH_LITERAL('}'))) + return true; + return false; +} + +} // namespace + +// static +bool NativeFileSystemDirectoryHandleImpl::IsSafePathComponent( + const std::string& name) { + // This method is similar to net::IsSafePortablePathComponent, with a few + // notable differences where the net version does not consider names safe + // while here we do want to allow them. These cases are: + // - Names starting with a '.'. These would be hidden files in most file + // managers, but are something we explicitly want to support for the + // File System Access API, for names like .git. + // - Names that end in '.local'. For downloads writing to such files is + // dangerous since it might modify what code is executed when an executable + // is ran from the same directory. For the File System Access API this + // isn't really a problem though, since if a website can write to a .local + // file via a FileSystemDirectoryHandle they can also just modify the + // executables in the directory directly. + // + // TODO(https://crbug.com/1154757): Unify this with + // net::IsSafePortablePathComponent, with the result probably ending up in + // base/i18n/file_util_icu.h. + + const base::FilePath component = storage::StringToFilePath(name); + // Empty names, or names that contain path separators are invalid. + if (component.empty() || component != component.BaseName() || + component != component.StripTrailingSeparators()) { + return false; + } + + base::string16 component16; +#if defined(OS_WIN) + component16.assign(component.value().begin(), component.value().end()); +#else + std::string component8 = component.AsUTF8Unsafe(); + if (!base::UTF8ToUTF16(component8.c_str(), component8.size(), &component16)) + return false; +#endif + // base::i18n::IsFilenameLegal blocks names that start with '.', so strip out + // a leading '.' before passing it to that method. + // TODO(mek): Consider making IsFilenameLegal more flexible to support this + // use case. + if (component16[0] == '.') + component16 = component16.substr(1); + if (!base::i18n::IsFilenameLegal(component16)) + return false; + + base::FilePath::StringType extension = component.Extension(); + if (!extension.empty()) + extension.erase(extension.begin()); // Erase preceding '.'. + if (IsShellIntegratedExtension(extension)) + return false; + + if (base::TrimString(component.value(), FILE_PATH_LITERAL("."), + base::TRIM_TRAILING) != component.value()) { + return false; + } + + if (net::IsReservedNameOnWindows(component.value())) + return false; + + return true; +} + blink::mojom::NativeFileSystemErrorPtr NativeFileSystemDirectoryHandleImpl::GetChildURL( const std::string& basename, storage::FileSystemURL* result) { - // TODO(mek): Rather than doing URL serialization and parsing we should just - // have a way to get a child FileSystemURL directly from its parent. - - if (basename.empty()) { + if (!IsSafePathComponent(basename)) { return native_file_system_error::FromStatus( - NativeFileSystemStatus::kInvalidArgument, - "Name can't be an empty string."); - } - - if (ContainsPathSeparator(basename) || IsCurrentOrParentDirectory(basename)) { - // |basename| must refer to a entry that exists in this directory as a - // direct child. - return native_file_system_error::FromStatus( - NativeFileSystemStatus::kInvalidArgument, - "Name contains invalid characters."); + NativeFileSystemStatus::kInvalidArgument, "Name is not allowed."); } const storage::FileSystemURL parent = url();
diff --git a/content/browser/file_system_access/native_file_system_directory_handle_impl.h b/content/browser/file_system_access/native_file_system_directory_handle_impl.h index 360fdbc5..537b2a6 100644 --- a/content/browser/file_system_access/native_file_system_directory_handle_impl.h +++ b/content/browser/file_system_access/native_file_system_directory_handle_impl.h
@@ -57,6 +57,14 @@ mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken> token) override; + // The File System Access API should not give access to files that might + // trigger special handling from the operating system. This method is used to + // validate that all paths passed to GetFileHandle/GetDirectoryHandle are safe + // to be exposed to the web. + // TODO(https://crbug.com/1154757): Merge this with + // net::IsSafePortablePathComponent. + static bool IsSafePathComponent(const std::string& name); + private: // This method creates the file if it does not currently exists. I.e. it is // the implementation for passing create=true to GetFile.
diff --git a/content/browser/file_system_access/native_file_system_directory_handle_impl_unittest.cc b/content/browser/file_system_access/native_file_system_directory_handle_impl_unittest.cc new file mode 100644 index 0000000..2601bc9 --- /dev/null +++ b/content/browser/file_system_access/native_file_system_directory_handle_impl_unittest.cc
@@ -0,0 +1,196 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/file_system_access/native_file_system_directory_handle_impl.h" + +#include <iterator> +#include <string> + +#include "base/bind.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/test/bind.h" +#include "base/test/task_environment.h" +#include "build/build_config.h" +#include "content/browser/file_system_access/fixed_native_file_system_permission_grant.h" +#include "content/public/test/browser_task_environment.h" +#include "storage/browser/test/test_file_system_context.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +using storage::FileSystemURL; + +class NativeFileSystemDirectoryHandleImplTest : public testing::Test { + public: + NativeFileSystemDirectoryHandleImplTest() + : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} + + void SetUp() override { + ASSERT_TRUE(dir_.CreateUniqueTempDir()); + + file_system_context_ = storage::CreateFileSystemContextForTesting( + /*quota_manager_proxy=*/nullptr, dir_.GetPath()); + + chrome_blob_context_ = base::MakeRefCounted<ChromeBlobStorageContext>(); + chrome_blob_context_->InitializeOnIOThread(base::FilePath(), + base::FilePath(), nullptr); + + manager_ = base::MakeRefCounted<NativeFileSystemManagerImpl>( + file_system_context_, chrome_blob_context_, + /*permission_context=*/nullptr, + /*off_the_record=*/false); + + auto url_and_fs = manager_->CreateFileSystemURLFromPath( + test_src_origin_, NativeFileSystemEntryFactory::PathType::kLocal, + dir_.GetPath()); + + handle_ = std::make_unique<NativeFileSystemDirectoryHandleImpl>( + manager_.get(), + NativeFileSystemManagerImpl::BindingContext( + test_src_origin_, test_src_url_, /*worker_process_id=*/1), + url_and_fs.url, + NativeFileSystemManagerImpl::SharedHandleState( + allow_grant_, allow_grant_, std::move(url_and_fs.file_system))); + } + + void TearDown() override { task_environment_.RunUntilIdle(); } + + protected: + const GURL test_src_url_ = GURL("http://example.com/foo"); + const url::Origin test_src_origin_ = url::Origin::Create(test_src_url_); + + BrowserTaskEnvironment task_environment_; + + base::ScopedTempDir dir_; + scoped_refptr<storage::FileSystemContext> file_system_context_; + scoped_refptr<ChromeBlobStorageContext> chrome_blob_context_; + scoped_refptr<NativeFileSystemManagerImpl> manager_; + + scoped_refptr<FixedNativeFileSystemPermissionGrant> allow_grant_ = + base::MakeRefCounted<FixedNativeFileSystemPermissionGrant>( + FixedNativeFileSystemPermissionGrant::PermissionStatus::GRANTED, + base::FilePath()); + std::unique_ptr<NativeFileSystemDirectoryHandleImpl> handle_; +}; + +TEST_F(NativeFileSystemDirectoryHandleImplTest, IsSafePathComponent) { + constexpr const char* kSafePathComponents[] = { + "a", "a.txt", "a b.txt", "My Computer", ".a", "lnk.zip", "lnk", "a.local", + }; + + constexpr const char* kUnsafePathComponents[] = { + "", + ".", + "..", + "...", + "con", + "con.zip", + "NUL", + "NUL.zip", + "a.", + "a\"a", + "a<a", + "a>a", + "a?a", + "a/", + "a\\", + "a ", + "a . .", + " Computer", + "My Computer.{a}", + "My Computer.{20D04FE0-3AEA-1069-A2D8-08002B30309D}", + "a\\a", + "a.lnk", + "a/a", + "C:\\", + "C:/", + "C:", + }; + + for (const char* component : kSafePathComponents) { + EXPECT_TRUE( + NativeFileSystemDirectoryHandleImpl::IsSafePathComponent(component)) + << component; + } + for (const char* component : kUnsafePathComponents) { + EXPECT_FALSE( + NativeFileSystemDirectoryHandleImpl::IsSafePathComponent(component)) + << component; + } +} + +namespace { +class TestNativeFileSystemDirectoryEntriesListener + : public blink::mojom::NativeFileSystemDirectoryEntriesListener { + public: + TestNativeFileSystemDirectoryEntriesListener( + std::vector<blink::mojom::NativeFileSystemEntryPtr>* entries, + base::OnceClosure done) + : entries_(entries), done_(std::move(done)) {} + + void DidReadDirectory( + blink::mojom::NativeFileSystemErrorPtr result, + std::vector<blink::mojom::NativeFileSystemEntryPtr> entries, + bool has_more_entries) override { + EXPECT_EQ(result->status, blink::mojom::NativeFileSystemStatus::kOk); + entries_->insert(entries_->end(), std::make_move_iterator(entries.begin()), + std::make_move_iterator(entries.end())); + if (!has_more_entries) { + std::move(done_).Run(); + } + } + + private: + std::vector<blink::mojom::NativeFileSystemEntryPtr>* entries_; + base::OnceClosure done_; +}; +} // namespace + +TEST_F(NativeFileSystemDirectoryHandleImplTest, GetEntries) { + constexpr const char* kSafeNames[] = {"a", "a.txt", "My Computer", "lnk.txt", + "a.local"}; + constexpr const char* kUnsafeNames[] = { + "con", "con.zip", "NUL", "a.", + "a\"a", "a . .", "a.lnk", "My Computer.{a}", + }; + for (const char* name : kSafeNames) { + ASSERT_TRUE(base::WriteFile(dir_.GetPath().AppendASCII(name), "data")) + << name; + } + for (const char* name : kUnsafeNames) { + base::FilePath file_path = dir_.GetPath().AppendASCII(name); + bool success = base::WriteFile(file_path, "data"); +#if !defined(OS_WIN) + // Some of the unsafe names are not legal file names on Windows. This is + // okay, and doesn't materially effect the outcome of the test, so just + // ignore any failures writing these files to disk. + EXPECT_TRUE(success) << "Failed to create file " << file_path; +#else + ignore_result(success); +#endif + } + + std::vector<blink::mojom::NativeFileSystemEntryPtr> entries; + base::RunLoop loop; + mojo::PendingRemote<blink::mojom::NativeFileSystemDirectoryEntriesListener> + listener; + mojo::MakeSelfOwnedReceiver( + std::make_unique<TestNativeFileSystemDirectoryEntriesListener>( + &entries, loop.QuitClosure()), + listener.InitWithNewPipeAndPassReceiver()); + handle_->GetEntries(std::move(listener)); + loop.Run(); + + std::vector<std::string> names; + for (const auto& entry : entries) { + names.push_back(entry->name); + } + EXPECT_THAT(names, testing::UnorderedElementsAreArray(kSafeNames)); +} + +} // namespace content
diff --git a/content/browser/file_system_access/native_file_system_file_handle_impl_unittest.cc b/content/browser/file_system_access/native_file_system_file_handle_impl_unittest.cc index 193e241..43eb0c9c 100644 --- a/content/browser/file_system_access/native_file_system_file_handle_impl_unittest.cc +++ b/content/browser/file_system_access/native_file_system_file_handle_impl_unittest.cc
@@ -28,8 +28,6 @@ #include "storage/browser/test/test_file_system_context.h" #include "testing/gtest/include/gtest/gtest.h" -using storage::FileSystemURL; - namespace content { using blink::mojom::PermissionStatus;
diff --git a/content/browser/indexed_db/indexed_db_compaction_task.cc b/content/browser/indexed_db/indexed_db_compaction_task.cc index c8484df..a2caede 100644 --- a/content/browser/indexed_db/indexed_db_compaction_task.cc +++ b/content/browser/indexed_db/indexed_db_compaction_task.cc
@@ -4,6 +4,7 @@ #include "content/browser/indexed_db/indexed_db_compaction_task.h" +#include "content/browser/indexed_db/indexed_db_tracing.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" namespace content { @@ -21,6 +22,7 @@ IndexedDBPreCloseTaskQueue::StopReason reason) {} bool IndexedDBCompactionTask::RunRound() { + IDB_TRACE("CompactRange"); database()->CompactRange(nullptr, nullptr); return true; }
diff --git a/content/browser/indexed_db/indexed_db_control_wrapper.cc b/content/browser/indexed_db/indexed_db_control_wrapper.cc index af11a21..e45e150 100644 --- a/content/browser/indexed_db/indexed_db_control_wrapper.cc +++ b/content/browser/indexed_db/indexed_db_control_wrapper.cc
@@ -205,11 +205,9 @@ if (indexed_db_control_.is_bound()) return; - IndexedDBContextImpl* idb_context = GetIndexedDBContextInternal(); - idb_context->IDBTaskRunner()->PostTask( + context_->IDBTaskRunner()->PostTask( FROM_HERE, - base::BindOnce(&IndexedDBContextImpl::Bind, - base::WrapRefCounted(idb_context), + base::BindOnce(&IndexedDBContextImpl::Bind, context_, indexed_db_control_.BindNewPipeAndPassReceiver())); }
diff --git a/content/browser/indexed_db/indexed_db_tracing.h b/content/browser/indexed_db/indexed_db_tracing.h index 7e00c1f..f70bee7e 100644 --- a/content/browser/indexed_db/indexed_db_tracing.h +++ b/content/browser/indexed_db/indexed_db_tracing.h
@@ -5,7 +5,8 @@ #ifndef CONTENT_BROWSER_INDEXED_DB_INDEXED_DB_TRACING_H_ #define CONTENT_BROWSER_INDEXED_DB_INDEXED_DB_TRACING_H_ -#include "base/trace_event/trace_event.h" +#include "base/trace_event/base_tracing.h" + #define IDB_TRACE(a) TRACE_EVENT0("IndexedDB", (a)); #define IDB_TRACE1(a, arg1_name, arg1_val) \ TRACE_EVENT1("IndexedDB", (a), (arg1_name), (arg1_val));
diff --git a/content/browser/network_service_restart_browsertest.cc b/content/browser/network_service_restart_browsertest.cc index 58458bf2..a2997cb 100644 --- a/content/browser/network_service_restart_browsertest.cc +++ b/content/browser/network_service_restart_browsertest.cc
@@ -160,6 +160,9 @@ void SetUpCommandLine(base::CommandLine* command_line) override { #if BUILDFLAG(ENABLE_PLUGINS) + // TODO(lukasza, kmoon): https://crbug.com/702993: Remove this dependency + // (and //ppapi/tests/corb_test_plugin.cc + BUILD.gn dependencies) once + // PDF support doesn't depend on PPAPI anymore. ASSERT_TRUE(ppapi::RegisterCorbTestPlugin(command_line)); #endif ContentBrowserTest::SetUpCommandLine(command_line); @@ -1130,34 +1133,58 @@ } #if BUILDFLAG(ENABLE_PLUGINS) -// Make sure that "trusted" plugins continue to be able to issue cross-origin -// requests after a network process crash. +// Make sure that "trusted" plugins continue to be able to issue requests that +// are cross-origin (wrt the host frame) after a network process crash: +// - html frame: main-frame.com/title1.html +// \-- plugin document: cross.origin.com/.../js.txt (`plugin_document_url`) +// \-- request from plugin: cross.origin.com/.../js.txt +// This mimics the behavior of PDFs, which only issue requests for the plugin +// document (e.q. network::ResourceRequest::request_initiator is same-origin wrt +// ResourceRequest::url). +// +// This primarily verifies that OnNetworkServiceCrashRestorePluginExceptions in +// render_process_host_impl.cc refreshes AddAllowedRequestInitiatorForPlugin +// data after a NetworkService crash. +// +// See also https://crbug.com/874515 and https://crbug.com/846339. +// +// TODO(lukasza, kmoon): https://crbug.com/702993: Remove this test once PDF +// support doesn't depend on PPAPI anymore. IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, Plugin) { if (IsInProcessNetworkService()) return; auto* web_contents = shell()->web_contents(); - ASSERT_TRUE(NavigateToURL(web_contents, - embedded_test_server()->GetURL("/title1.html"))); + ASSERT_TRUE(NavigateToURL( + web_contents, + embedded_test_server()->GetURL("main.frame.com", "/title1.html"))); - // Load the test plugin (see ppapi::RegisterCorbTestPlugin). - const char kLoadingScript[] = R"( + // Load cross-origin document into the test plugin (see + // ppapi::RegisterCorbTestPlugin). + // + // The document has to be a MIME type that CORB will allow (such as + // javascript) - it cannot be a pdf or json, because these would be blocked by + // CORB (the real PDF plugin works because the plugin is hosted in a Chrome + // Extension where CORB is turned off). + GURL plugin_document_url = embedded_test_server()->GetURL( + "cross.origin.com", "/site_isolation/js.txt"); + const char kLoadingScriptTemplate[] = R"( var obj = document.createElement('object'); obj.id = 'plugin'; - obj.data = 'test.swf'; - obj.type = 'application/x-shockwave-flash'; + obj.data = $1; + obj.type = 'application/x-fake-pdf-for-testing'; obj.width = 400; obj.height = 400; document.body.appendChild(obj); )"; - ASSERT_TRUE(ExecJs(web_contents, kLoadingScript)); + EXPECT_FALSE( + web_contents->GetMainFrame()->GetLastCommittedOrigin().IsSameOriginWith( + url::Origin::Create(plugin_document_url))); + ASSERT_TRUE(ExecJs(web_contents, + JsReplace(kLoadingScriptTemplate, plugin_document_url))); - // Ask the plugin to perform a cross-origin, CORB-eligible (i.e. - // application/json + nosniff) URL request. Plugins with universal access - // should not be subject to CORS/CORB and so the request should go through. - // See also https://crbug.com/874515 and https://crbug.com/846339. - GURL cross_origin_url = embedded_test_server()->GetURL( - "cross.origin.com", "/site_isolation/nosniff.json"); + // Ask the plugin to re-request the document URL (similarly to what the PDF + // plugin does to get chunks of linearized PDFs). const char kFetchScriptTemplate[] = R"( new Promise(function (resolve, reject) { var obj = document.getElementById('plugin'); @@ -1173,10 +1200,11 @@ obj.postMessage('requestUrl: ' + $1); }); )"; - std::string fetch_script = JsReplace(kFetchScriptTemplate, cross_origin_url); + std::string fetch_script = + JsReplace(kFetchScriptTemplate, plugin_document_url); ASSERT_EQ( "msg-from-plugin: requestUrl: RESPONSE BODY: " - "runMe({ \"name\" : \"chromium\" });\n", + "var j = 0; document.write(j);\n", EvalJs(web_contents, fetch_script)); // Crash the Network Service process and wait until host frame's @@ -1185,11 +1213,11 @@ main_frame()->FlushNetworkAndNavigationInterfacesForTesting(); // Try the fetch again - it should still work (i.e. the mechanism for relaxing - // CORB for universal-access-plugins should be resilient to network process - // crashes). See also https://crbug.com/891904. + // request_initiator_origin_lock enforcement should be resilient to network + // process crashes). ASSERT_EQ( "msg-from-plugin: requestUrl: RESPONSE BODY: " - "runMe({ \"name\" : \"chromium\" });\n", + "var j = 0; document.write(j);\n", EvalJs(web_contents, fetch_script)); } #endif
diff --git a/content/browser/plugin_service_impl.cc b/content/browser/plugin_service_impl.cc index 7caf0071..68fe719 100644 --- a/content/browser/plugin_service_impl.cc +++ b/content/browser/plugin_service_impl.cc
@@ -170,37 +170,27 @@ return nullptr; } - if (info->permissions & ppapi::PERMISSION_FLASH) { - // Flash has its own flavour of CORS, so CORB needs to allow all responses - // and rely on Flash to enforce same-origin policy. See also - // https://crbug.com/874515 and https://crbug.com/816318#c5. - // - // Note that ppapi::PERMISSION_FLASH is present not only in the Flash - // plugin. This permission is also present in plugins added from the cmdline - // and so will be also present for "PPAPI Tests" plugin used for - // OutOfProcessPPAPITest.URLLoaderTrusted and related tests. - // - // TODO(lukasza, laforge): https://crbug.com/702995: Remove the code below - // once Flash support is removed from Chromium (probably around 2020 - see - // https://www.chromium.org/flash-roadmap). - RenderProcessHostImpl::AddCorbExceptionForPlugin(render_process_id); - } else if (info->permissions & ppapi::PERMISSION_PDF) { - // We want to limit ability to bypass |request_initiator_origin_lock| to - // trustworthy renderers. PDF plugin is okay, because it is always hosted - // by the PDF extension (mhjfbmdgcfjbbpaeojofohoefgiehjai) or - // chrome://print, both of which we assume are trustworthy (the extension - // process can also host other extensions, but this is okay). - // - // The CHECKs below help verify that |render_process_id| does not host - // web-controlled content. This is a defense-in-depth for verifying that - // ShouldAllowPluginCreation called above is doing the right thing. - auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); - ProcessLock renderer_lock = policy->GetProcessLock(render_process_id); - CHECK(!renderer_lock.matches_scheme(url::kHttpScheme) && - !renderer_lock.matches_scheme(url::kHttpsScheme)); - CHECK(embedder_origin.scheme() != url::kHttpScheme); - CHECK(embedder_origin.scheme() != url::kHttpsScheme); - CHECK(!embedder_origin.opaque()); + if (info->permissions & ppapi::PERMISSION_PDF) { + // Extra assertions for the PDF plugin. These assertions do not apply to + // the test plugin. + if (0 == (info->permissions & ppapi::PERMISSION_TESTING)) { + // We want to limit ability to bypass |request_initiator_origin_lock| to + // trustworthy renderers. PDF plugin is okay, because it is always hosted + // by the PDF extension (mhjfbmdgcfjbbpaeojofohoefgiehjai) or + // chrome://print, both of which we assume are trustworthy (the extension + // process can also host other extensions, but this is okay). + // + // The CHECKs below help verify that |render_process_id| does not host + // web-controlled content. This is a defense-in-depth for verifying that + // ShouldAllowPluginCreation called above is doing the right thing. + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + ProcessLock renderer_lock = policy->GetProcessLock(render_process_id); + CHECK(!renderer_lock.matches_scheme(url::kHttpScheme) && + !renderer_lock.matches_scheme(url::kHttpsScheme)); + CHECK(embedder_origin.scheme() != url::kHttpScheme); + CHECK(embedder_origin.scheme() != url::kHttpsScheme); + CHECK(!embedder_origin.opaque()); + } // In some scenarios, the PDF plugin can issue fetch requests that will need // to be proxied by |render_process_id| - such proxying needs to bypass
diff --git a/content/browser/renderer_host/input/touch_action_browsertest.cc b/content/browser/renderer_host/input/touch_action_browsertest.cc index 853ada6..de43c62 100644 --- a/content/browser/renderer_host/input/touch_action_browsertest.cc +++ b/content/browser/renderer_host/input/touch_action_browsertest.cc
@@ -826,7 +826,6 @@ public: TouchActionBrowserTestEnableCursorControl() { feature_list_.InitWithFeatures({::features::kSwipeToMoveCursor}, {}); - DCHECK(base::FeatureList::IsEnabled(::features::kSwipeToMoveCursor)); } private: @@ -838,6 +837,8 @@ // scroll, and changes the selection. IN_PROC_BROWSER_TEST_F(TouchActionBrowserTestEnableCursorControl, BasicCursorControl) { + if (!::features::IsSwipeToMoveCursorEnabled()) + return; base::HistogramTester histograms; LoadURL(kContentEditableDataURL.c_str()); @@ -869,6 +870,8 @@ // changed and scroll should happen. IN_PROC_BROWSER_TEST_F(TouchActionBrowserTestEnableCursorControl, NoCursorControlForHorizontalScrollable) { + if (!::features::IsSwipeToMoveCursorEnabled()) + return; base::HistogramTester histograms; LoadURL(kContentEditableHorizontalScrollableDataURL.c_str()); @@ -900,6 +903,8 @@ // Ensure the swipe is not triggering cursor control. IN_PROC_BROWSER_TEST_F(TouchActionBrowserTestEnableCursorControl, NoCursorControlForNonPassiveLisenter) { + if (!::features::IsSwipeToMoveCursorEnabled()) + return; LoadURL(kContentEditableNonPassiveHandlerDataURL.c_str()); EXPECT_EQ(32, @@ -925,6 +930,8 @@ // scroll, and changes the selection. IN_PROC_BROWSER_TEST_F(TouchActionBrowserTestEnableCursorControl, CursorControlOnInput) { + if (!::features::IsSwipeToMoveCursorEnabled()) + return; base::HistogramTester histograms; // input size larger than the text size, not horizontally scrollable. LoadURL(base::StringPrintf(kInputTagCursorControl.c_str(), 40).c_str()); @@ -953,6 +960,8 @@ // right to left. Ensure the swipe is doing scrolling other than cursor control. IN_PROC_BROWSER_TEST_F(TouchActionBrowserTestEnableCursorControl, NoCursorControlOnHorizontalScrollableInput) { + if (!::features::IsSwipeToMoveCursorEnabled()) + return; base::HistogramTester histograms; // Make the input size smaller than the text size, so it horizontally // scrollable.
diff --git a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc index 81fc356..4861f7a 100644 --- a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc +++ b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
@@ -206,9 +206,22 @@ DISALLOW_COPY_AND_ASSIGN(TouchSelectionControllerClientAuraTest); }; +class TouchSelectionControllerClientAuraCAPFeatureTest + : public TouchSelectionControllerClientAuraTest, + public testing::WithParamInterface<bool> { + void SetUpCommandLine(base::CommandLine* command_line) override { + TouchSelectionControllerClientAuraTest::SetUpCommandLine(command_line); + command_line->AppendSwitchASCII(GetParam() + ? switches::kEnableBlinkFeatures + : switches::kDisableBlinkFeatures, + "CompositeAfterPaint"); + } +}; + // Tests that long-pressing on a text brings up selection handles and the quick // menu properly. -IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraTest, BasicSelection) { +IN_PROC_BROWSER_TEST_P(TouchSelectionControllerClientAuraCAPFeatureTest, + BasicSelection) { // Set the test page up. ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/touch_selection.html")); InitSelectionController(); @@ -242,6 +255,10 @@ rwhva->selection_controller()->GetVisibleRectBetweenBounds()); } +INSTANTIATE_TEST_SUITE_P(TouchSelectionForCAPFeatureTests, + TouchSelectionControllerClientAuraCAPFeatureTest, + testing::Bool()); + class GestureEventWaiter : public RenderWidgetHost::InputEventObserver { public: explicit GestureEventWaiter(RenderWidgetHost* rwh, @@ -790,7 +807,8 @@ } // Tests that the quick menu and touch handles are hidden during an scroll. -IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraTest, HiddenOnScroll) { +IN_PROC_BROWSER_TEST_P(TouchSelectionControllerClientAuraCAPFeatureTest, + HiddenOnScroll) { // Set the test page up. ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/touch_selection.html")); InitSelectionController(); @@ -882,9 +900,24 @@ } }; +class TouchSelectionControllerClientAuraScaleFactorCAPFeatureTest + : public TouchSelectionControllerClientAuraScaleFactorTest, + public testing::WithParamInterface<bool> { + public: + void SetUpCommandLine(base::CommandLine* command_line) override { + TouchSelectionControllerClientAuraScaleFactorTest::SetUpCommandLine( + command_line); + command_line->AppendSwitchASCII(GetParam() + ? switches::kEnableBlinkFeatures + : switches::kDisableBlinkFeatures, + "CompositeAfterPaint"); + } +}; + // Tests that selection handles are properly positioned at 2x DSF. -IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraScaleFactorTest, - SelectionHandleCoordinates) { +IN_PROC_BROWSER_TEST_P( + TouchSelectionControllerClientAuraScaleFactorCAPFeatureTest, + SelectionHandleCoordinates) { // Set the test page up. ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/touch_selection.html")); InitSelectionController(); @@ -978,6 +1011,11 @@ rwhva->selection_controller()->GetVisibleRectBetweenBounds()); } +INSTANTIATE_TEST_SUITE_P( + TouchSelectionScaleFactorForCAPFeatureTests, + TouchSelectionControllerClientAuraScaleFactorCAPFeatureTest, + testing::Bool()); + // Tests that insertion handles are properly positioned at 2x DSF. IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraScaleFactorTest, InsertionHandleCoordinates) {
diff --git a/content/browser/renderer_host/render_frame_host_delegate.cc b/content/browser/renderer_host/render_frame_host_delegate.cc index a50786d6..51f81aa 100644 --- a/content/browser/renderer_host/render_frame_host_delegate.cc +++ b/content/browser/renderer_host/render_frame_host_delegate.cc
@@ -104,7 +104,7 @@ std::unique_ptr<WebUIImpl> RenderFrameHostDelegate::CreateWebUIForRenderFrameHost( - RenderFrameHost* frame_host, + RenderFrameHostImpl* frame_host, const GURL& url) { return nullptr; }
diff --git a/content/browser/renderer_host/render_frame_host_delegate.h b/content/browser/renderer_host/render_frame_host_delegate.h index 8cb5744..c9fffe2 100644 --- a/content/browser/renderer_host/render_frame_host_delegate.h +++ b/content/browser/renderer_host/render_frame_host_delegate.h
@@ -357,7 +357,7 @@ // Creates a WebUI object for a frame navigating to |url|. If no WebUI // applies, returns null. virtual std::unique_ptr<WebUIImpl> CreateWebUIForRenderFrameHost( - RenderFrameHost* frame_host, + RenderFrameHostImpl* frame_host, const GURL& url); // Called by |frame| to notify that it has received an update on focused
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index a990d24..9f18769 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -1574,6 +1574,10 @@ std::move(serializer_handler)); } +void RenderFrameHostImpl::SetWantErrorMessageStackTrace() { + GetNavigationControl()->SetWantErrorMessageStackTrace(); +} + void RenderFrameHostImpl::ExecuteMediaPlayerActionAtLocation( const gfx::Point& location, const blink::mojom::MediaPlayerAction& action) { @@ -2047,6 +2051,23 @@ return view->GetWebContentsAccessibility(); } +void RenderFrameHostImpl::ValidateStateForBug1146573() { + // This implies that a crashed frame has been reinitialized instead of + // replaced. The only time this should happen is + // InitializeMainRenderFrameForImmediateUse and it resets must_be_replaced_ so + // should not trigger this. + if (must_be_replaced_ && render_frame_created_) { + SCOPED_CRASH_KEY_BOOL(ValidateStateForBug1146573, IsMainFrame, + is_main_frame()); + SCOPED_CRASH_KEY_BOOL(ValidateStateForBug1146573, ProcessID, + GetProcess()->GetID()); + SCOPED_CRASH_KEY_BOOL(ValidateStateForBug1146573, RoutingID, + GetRoutingID()); + NOTREACHED(); + base::debug::DumpWithoutCrashing(); + } +} + void RenderFrameHostImpl::RenderProcessExited( RenderProcessHost* host, const ChildProcessTerminationInfo& info) { @@ -2066,6 +2087,7 @@ web_bundle_handle_.reset(); must_be_replaced_ = true; + ValidateStateForBug1146573(); has_committed_any_navigation_ = false; #if defined(OS_ANDROID) @@ -2388,6 +2410,7 @@ bool was_created = render_frame_created_; render_frame_created_ = created; + ValidateStateForBug1146573(); // Clear all the user data associated with this RenderFrameHost when its // RenderFrame is recreated after a crash. Checking @@ -3207,6 +3230,9 @@ // TODO(https://crbug.com/1146573): Delete this. SCOPED_CRASH_KEY_BOOL(Bug1146573, Live, IsRenderFrameLive()); SCOPED_CRASH_KEY_BOOL(Bug1146573, MustBeReplaced, must_be_replaced()); + SCOPED_CRASH_KEY_BOOL(Bug1146573, IsMainFrame, is_main_frame()); + SCOPED_CRASH_KEY_BOOL(Bug1146573, ProcessID, GetProcess()->GetID()); + SCOPED_CRASH_KEY_BOOL(Bug1146573, RoutingID, GetRoutingID()); CHECK(ShouldCreateNewHostForSameSiteSubframe()); // The unload handlers already ran for this document during the
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index eaa2f25..02d8558 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -930,6 +930,11 @@ no_create_browser_accessibility_manager_for_testing_ = flag; } + // Indicates that this process wants the |untrusted_stack_trace| parameter of + // FrameHost.DidAddMessageToConsole() to be filled in as much as possible for + // log_level == kError messages. + void SetWantErrorMessageStackTrace(); + // Indicates that a navigation is ready to commit and can be // handled by this RenderFrame. // |subresource_loader_params| is used in network service land to pass @@ -2572,6 +2577,9 @@ const ukm::SourceId document_ukm_source_id, ukm::UkmRecorder* ukm_recorder); + // TODO(https://crbug.com/1146573): Remove this when the bug is closed. + void ValidateStateForBug1146573(); + // The RenderViewHost that this RenderFrameHost is associated with. // // It is kept alive as long as any RenderFrameHosts or RenderFrameProxyHosts
diff --git a/content/browser/renderer_host/render_frame_host_manager.cc b/content/browser/renderer_host/render_frame_host_manager.cc index 04e360f..5cfd148 100644 --- a/content/browser/renderer_host/render_frame_host_manager.cc +++ b/content/browser/renderer_host/render_frame_host_manager.cc
@@ -767,6 +767,14 @@ pending->GetSiteInstance()->GetSiteURL().spec()); SCOPED_CRASH_KEY_BOOL(ValidateSpeculative, MustBeReplaced, current->must_be_replaced()); + SCOPED_CRASH_KEY_BOOL(ValidateSpeculative, OldProcessID, + current->GetProcess()->GetID()); + SCOPED_CRASH_KEY_BOOL(ValidateSpeculative, OldRoutingID, + current->GetRoutingID()); + SCOPED_CRASH_KEY_BOOL(ValidateSpeculative, NewProcessID, + pending->GetProcess()->GetID()); + SCOPED_CRASH_KEY_BOOL(ValidateSpeculative, NewRoutingID, + pending->GetRoutingID()); NOTREACHED(); base::debug::DumpWithoutCrashing(); }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 0c1b981..57cb30e 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -1127,10 +1127,9 @@ return *instance; } -// Keep track of plugin process IDs that require exceptions from CORB, -// request_initiator_origin_lock checks (for particular origins), or both. +// Keep track of plugin process IDs that require exceptions for particular +// initiator origins. struct PluginExceptionsForNetworkService { - bool is_corb_disabled = false; std::set<url::Origin> allowed_request_initiators; }; std::map<int, PluginExceptionsForNetworkService>& @@ -1147,9 +1146,6 @@ const int process_id = it.first; const PluginExceptionsForNetworkService& exceptions = it.second; - if (exceptions.is_corb_disabled) - network_service->AddCorbExceptionForPlugin(process_id); - for (const url::Origin& origin : exceptions.allowed_request_initiators) network_service->AddAllowedRequestInitiatorForPlugin(process_id, origin); } @@ -1181,15 +1177,6 @@ return true; // success } -void AddCorbExceptionForPluginOnUIThread(int process_id) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!PrepareToAddNewPluginExceptions(process_id)) - return; - - GetPluginExceptionsForNetworkService()[process_id].is_corb_disabled = true; - GetNetworkService()->AddCorbExceptionForPlugin(process_id); -} - void AddAllowedRequestInitiatorForPluginOnUIThread( int process_id, const url::Origin& allowed_request_initiator) { @@ -2137,15 +2124,6 @@ } // static -void RenderProcessHostImpl::AddCorbExceptionForPlugin(int process_id) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&AddCorbExceptionForPluginOnUIThread, process_id)); -} - -// static void RenderProcessHostImpl::AddAllowedRequestInitiatorForPlugin( int process_id, const url::Origin& allowed_request_initiator) {
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 0679c731..dd8f042 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -647,14 +647,6 @@ mojo::PendingReceiver<blink::mojom::WebSocketConnector> receiver) override; - // Disables CORB (Cross-Origin Read Blocking) and - // |request_initiator_origin_lock| enforcement for |process_id|. - // - // The exception will be removed when the corresponding RenderProcessHostImpl - // is destroyed (see - // |cleanup_network_service_plugin_exceptions_upon_destruction_|). - static void AddCorbExceptionForPlugin(int process_id); - // Allows |process_id| to use an additional |allowed_request_initiator| // (bypassing |request_initiator_origin_lock| enforcement). //
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 8a50e72..82c8b29 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -7769,7 +7769,7 @@ } std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost( - RenderFrameHost* frame_host, + RenderFrameHostImpl* frame_host, const GURL& url) { return CreateWebUI(frame_host, url); } @@ -8064,7 +8064,7 @@ } std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI( - RenderFrameHost* frame_host, + RenderFrameHostImpl* frame_host, const GURL& url) { TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host", base::trace_event::ToTracedValue(frame_host), "url",
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index d0473ee..388a53b 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -108,6 +108,7 @@ class NFCHost; class Portal; class RenderFrameHost; +class RenderFrameHostImpl; class RenderViewHost; class RenderViewHostDelegateView; class RenderWidgetHostImpl; @@ -640,7 +641,7 @@ SiteInstance* source_site_instance) const override; void EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) override; std::unique_ptr<WebUIImpl> CreateWebUIForRenderFrameHost( - RenderFrameHost* frame_host, + RenderFrameHostImpl* frame_host, const GURL& url) override; void SetFocusedFrame(FrameTreeNode* node, SiteInstance* source) override; void DidCallFocus() override; @@ -1631,7 +1632,7 @@ // Internal helper to create WebUI objects associated with |this|. |url| is // used to determine which WebUI should be created (if any). - std::unique_ptr<WebUIImpl> CreateWebUI(RenderFrameHost* frame_host, + std::unique_ptr<WebUIImpl> CreateWebUI(RenderFrameHostImpl* frame_host, const GURL& url); void SetJavaScriptDialogManagerForTesting(
diff --git a/content/browser/webui/web_ui_browsertest.cc b/content/browser/webui/web_ui_browsertest.cc index 7cbdb9a..ce4aaa8 100644 --- a/content/browser/webui/web_ui_browsertest.cc +++ b/content/browser/webui/web_ui_browsertest.cc
@@ -18,6 +18,7 @@ #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "build/build_config.h" +#include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/webui/content_web_ui_controller_factory.h" #include "content/browser/webui/web_ui_impl.h" #include "content/public/browser/child_process_security_policy.h"
diff --git a/content/browser/webui/web_ui_impl.cc b/content/browser/webui/web_ui_impl.cc index 543bb92..b77005280 100644 --- a/content/browser/webui/web_ui_impl.cc +++ b/content/browser/webui/web_ui_impl.cc
@@ -62,7 +62,7 @@ return result; } -WebUIImpl::WebUIImpl(WebContentsImpl* contents, RenderFrameHost* frame_host) +WebUIImpl::WebUIImpl(WebContentsImpl* contents, RenderFrameHostImpl* frame_host) : bindings_(BINDINGS_POLICY_WEB_UI), requestable_schemes_({kChromeUIScheme, url::kFileScheme}), frame_host_(frame_host), @@ -127,10 +127,9 @@ if (frame_host_->GetParent()) return; - static_cast<RenderFrameHostImpl*>(frame_host_) - ->GetFrameBindingsControl() - ->BindWebUI(remote_.BindNewPipeAndPassReceiver(), - receiver_.BindNewPipeAndPassRemote()); + frame_host_->GetFrameBindingsControl()->BindWebUI( + remote_.BindNewPipeAndPassReceiver(), + receiver_.BindNewPipeAndPassRemote()); } void WebUIImpl::InvalidateMojoConnection() { @@ -273,12 +272,6 @@ return &handlers_; } -void WebUIImpl::DisableJavaScriptErrorReporting() { -#if defined(OS_LINUX) || defined(OS_CHROMEOS) - web_contents_observer_->DisableJavaScriptErrorReporting(); -#endif -} - // WebUIImpl, protected: ------------------------------------------------------- void WebUIImpl::AddMessageHandler(
diff --git a/content/browser/webui/web_ui_impl.h b/content/browser/webui/web_ui_impl.h index 7148949..2fcd9dc 100644 --- a/content/browser/webui/web_ui_impl.h +++ b/content/browser/webui/web_ui_impl.h
@@ -22,6 +22,7 @@ namespace content { class RenderFrameHost; +class RenderFrameHostImpl; class WebContentsImpl; class WebUIMainFrameObserver; @@ -29,7 +30,8 @@ public mojom::WebUIHost, public base::SupportsWeakPtr<WebUIImpl> { public: - explicit WebUIImpl(WebContentsImpl* contents, RenderFrameHost* frame_host); + explicit WebUIImpl(WebContentsImpl* contents, + RenderFrameHostImpl* frame_host); ~WebUIImpl() override; // Called when a RenderFrame is created for a WebUI (reload after a renderer @@ -91,11 +93,13 @@ const std::vector<const base::Value*>& args) override; std::vector<std::unique_ptr<WebUIMessageHandler>>* GetHandlersForTesting() override; - void DisableJavaScriptErrorReporting() override; const mojo::Remote<mojom::WebUI>& GetRemoteForTest() const { return remote_; } + WebUIMainFrameObserver* GetWebUIMainFrameObserverForTest() const { + return web_contents_observer_.get(); + } - RenderFrameHost* frame_host() const { return frame_host_; } + RenderFrameHostImpl* frame_host() const { return frame_host_; } private: friend class WebUIMainFrameObserver; @@ -122,7 +126,7 @@ std::vector<std::string> requestable_schemes_; // RenderFrameHost associated with |this|. - RenderFrameHost* frame_host_; + RenderFrameHostImpl* frame_host_; // Non-owning pointer to the WebContentsImpl this WebUI is associated with. WebContentsImpl* web_contents_;
diff --git a/content/browser/webui/web_ui_main_frame_observer.cc b/content/browser/webui/web_ui_main_frame_observer.cc index 0991b438..3a50bba 100644 --- a/content/browser/webui/web_ui_main_frame_observer.cc +++ b/content/browser/webui/web_ui_main_frame_observer.cc
@@ -18,7 +18,9 @@ #include "base/strings/utf_string_conversions.h" #include "components/crash/content/browser/error_reporting/javascript_error_report.h" #include "components/crash/content/browser/error_reporting/js_error_report_processor.h" +#include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/public/browser/web_contents.h" +#include "content/public/browser/web_ui_controller.h" #include "content/public/common/content_features.h" #include "content/public/common/url_constants.h" #include "url/gurl.h" @@ -29,13 +31,8 @@ WebUIMainFrameObserver::WebUIMainFrameObserver(WebUIImpl* web_ui, WebContents* contents) : WebContentsObserver(contents), web_ui_(web_ui) {} -WebUIMainFrameObserver::~WebUIMainFrameObserver() = default; -#if defined(OS_LINUX) || defined(OS_CHROMEOS) -void WebUIMainFrameObserver::DisableJavaScriptErrorReporting() { - error_reporting_enabled_ = false; -} -#endif +WebUIMainFrameObserver::~WebUIMainFrameObserver() = default; void WebUIMainFrameObserver::DidFinishNavigation( NavigationHandle* navigation_handle) { @@ -57,9 +54,15 @@ int32_t line_no, const base::string16& source_id, const base::Optional<base::string16>& untrusted_stack_trace) { + // TODO(iby) Change all VLOGs to DVLOGs once tast tests are stable. VLOG(3) << "OnDidAddMessageToConsole called for " << message; + if (untrusted_stack_trace) { + VLOG(3) << "stack is " << *untrusted_stack_trace; + } + if (!error_reporting_enabled_) { - VLOG(3) << "Message not reported, error reporting disabled for this page"; + VLOG(3) << "Message not reported, error reporting disabled for this page " + "or experiment is off"; return; } @@ -68,12 +71,6 @@ return; } - if (!base::FeatureList::IsEnabled( - features::kSendWebUIJavaScriptErrorReports)) { - VLOG(3) << "Message not reported, error report sending flag off"; - return; - } - // Some WebUI pages have another WebUI page in an <iframe>. Both // WebUIMainFrameObservers will get a callback when either page gets an error. // To avoid duplicates, only report on errors from this page's frame. @@ -131,6 +128,31 @@ processor->SendErrorReport(std::move(report), base::DoNothing(), web_contents()->GetBrowserContext()); } + +void WebUIMainFrameObserver::RenderFrameCreated( + RenderFrameHost* render_frame_host) { + if (!base::FeatureList::IsEnabled( + features::kSendWebUIJavaScriptErrorReports)) { + return; + } + + if (render_frame_host != web_ui_->frame_host()) { + return; + } + + error_reporting_enabled_ = + web_ui_->GetController()->IsJavascriptErrorReportingEnabled(); + + // If we are collecting error reports, make sure the main frame sends us + // stacks along with those messages. Warning: Don't call + // RenderFrameHostImpl::SetWantErrorMessageStackTrace() before the remote + // frame is created, or it will lock up the communications channel. (See + // https://crbug.com/1154866). + if (error_reporting_enabled_) { + web_ui_->frame_host()->SetWantErrorMessageStackTrace(); + } +} + #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) } // namespace content
diff --git a/content/browser/webui/web_ui_main_frame_observer.h b/content/browser/webui/web_ui_main_frame_observer.h index 8ec64e1..6d7d754 100644 --- a/content/browser/webui/web_ui_main_frame_observer.h +++ b/content/browser/webui/web_ui_main_frame_observer.h
@@ -35,10 +35,6 @@ WebUIMainFrameObserver(const WebUIMainFrameObserver& rhs) = delete; WebUIMainFrameObserver& operator=(const WebUIMainFrameObserver& rhs) = delete; -#if defined(OS_LINUX) || defined(OS_CHROMEOS) - void DisableJavaScriptErrorReporting(); -#endif - protected: friend class WebUIMainFrameObserverTest; @@ -58,12 +54,13 @@ int32_t line_no, const base::string16& source_id, const base::Optional<base::string16>& untrusted_stack_trace) override; + void RenderFrameCreated(RenderFrameHost* render_frame_host) override; #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) private: #if defined(OS_LINUX) || defined(OS_CHROMEOS) // Do we report JavaScript errors ? - bool error_reporting_enabled_ = true; + bool error_reporting_enabled_ = false; #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) WebUIImpl* web_ui_;
diff --git a/content/browser/webui/web_ui_main_frame_observer_unittest.cc b/content/browser/webui/web_ui_main_frame_observer_unittest.cc index 70b9d73..ad0b09d3 100644 --- a/content/browser/webui/web_ui_main_frame_observer_unittest.cc +++ b/content/browser/webui/web_ui_main_frame_observer_unittest.cc
@@ -14,6 +14,7 @@ #include "components/crash/content/browser/error_reporting/javascript_error_report.h" #include "components/crash/content/browser/error_reporting/js_error_report_processor.h" #include "content/public/browser/site_instance.h" +#include "content/public/browser/web_ui_controller.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" @@ -69,6 +70,27 @@ int error_report_count_ = 0; BrowserContext* browser_context_ = nullptr; }; + +class MockWebUIController : public WebUIController { + public: + explicit MockWebUIController(WebUI* web_ui) : WebUIController(web_ui) {} + + bool IsJavascriptErrorReportingEnabled() override { + return enable_javascript_error_reporting_; + } + void enable_javascript_error_reporting( + bool enable_javascript_error_reporting) { + enable_javascript_error_reporting_ = enable_javascript_error_reporting; + } + + private: + bool enable_javascript_error_reporting_ = true; + + WEB_UI_CONTROLLER_TYPE_DECL(); +}; + +WEB_UI_CONTROLLER_TYPE_IMPL(MockWebUIController) + } // namespace class WebUIMainFrameObserverTest : public RenderViewHostTestHarness { @@ -81,13 +103,14 @@ "true"}}); site_instance_ = SiteInstance::Create(browser_context()); SetContents(TestWebContents::Create(browser_context(), site_instance_)); - CHECK(main_rfh()); // Since we just created the web_contents() pointer with - // TestWebContents::Create, the static_cast is safe. + // TestWebContents::Create, the static_casts are safe. web_ui_ = std::make_unique<WebUIImpl>( - static_cast<TestWebContents*>(web_contents()), main_rfh()); - observer_ = - std::make_unique<WebUIMainFrameObserver>(web_ui_.get(), web_contents()); + static_cast<TestWebContents*>(web_contents()), + static_cast<TestWebContents*>(web_contents())->GetMainFrame()); + web_ui_->SetController( + std::make_unique<MockWebUIController>(web_ui_.get())); + process()->Init(); previous_processor_ = JsErrorReportProcessor::Get(); processor_ = base::MakeRefCounted<FakeJsErrorReportProcessor>( @@ -106,16 +129,22 @@ // can. previous_processor_.reset(); processor_.reset(); - observer_.reset(); web_ui_.reset(); site_instance_.reset(); RenderViewHostTestHarness::TearDown(); } - // Calls observer_->OnDidAddMessageToConsole with the given arguments. This - // is just here so that we don't need to FRIEND_TEST_ALL_PREFIXES for each - // and every test. + // Simulate the remote renderer becoming alive. + void CreateRenderFrame() { + static_cast<TestWebContents*>(web_contents()) + ->GetRenderViewHost() + ->CreateRenderView(base::nullopt, 0, false); + } + + // Calls the observer's OnDidAddMessageToConsole with the given arguments. + // This is just here so that we don't need to FRIEND_TEST_ALL_PREFIXES for + // each and every test. void CallOnDidAddMessageToConsole( RenderFrameHost* source_frame, blink::mojom::ConsoleMessageLevel log_level, @@ -123,15 +152,14 @@ int32_t line_no, const base::string16& source_id, const base::Optional<base::string16>& stack_trace) { - observer_->OnDidAddMessageToConsole(source_frame, log_level, message, - line_no, source_id, stack_trace); + web_ui_->GetWebUIMainFrameObserverForTest()->OnDidAddMessageToConsole( + source_frame, log_level, message, line_no, source_id, stack_trace); } protected: base::test::ScopedFeatureList scoped_feature_list_; scoped_refptr<SiteInstance> site_instance_; std::unique_ptr<WebUIImpl> web_ui_; - std::unique_ptr<WebUIMainFrameObserver> observer_; scoped_refptr<FakeJsErrorReportProcessor> processor_; scoped_refptr<JsErrorReportProcessor> previous_processor_; @@ -150,6 +178,7 @@ constexpr char WebUIMainFrameObserverTest::kStackTrace8[]; TEST_F(WebUIMainFrameObserverTest, ErrorReported) { + CreateRenderFrame(); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, kMessage16, 5, kSourceId16, kStackTrace16); @@ -169,6 +198,7 @@ } TEST_F(WebUIMainFrameObserverTest, NoStackTrace) { + CreateRenderFrame(); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, kMessage16, 5, kSourceId16, base::nullopt); @@ -178,6 +208,7 @@ } TEST_F(WebUIMainFrameObserverTest, NonErrorsIgnored) { + CreateRenderFrame(); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kWarning, kMessage16, 5, kSourceId16, kStackTrace16); @@ -192,6 +223,7 @@ } TEST_F(WebUIMainFrameObserverTest, NoProcessorDoesntCrash) { + CreateRenderFrame(); FakeJsErrorReportProcessor::SetDefault(nullptr); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, @@ -203,6 +235,7 @@ scoped_feature_list_.Reset(); scoped_feature_list_.InitAndDisableFeature( features::kSendWebUIJavaScriptErrorReports); + CreateRenderFrame(); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, kMessage16, 5, kSourceId16, kStackTrace16); @@ -211,6 +244,7 @@ } TEST_F(WebUIMainFrameObserverTest, NotSentIfInvalidURL) { + CreateRenderFrame(); CallOnDidAddMessageToConsole( web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, kMessage16, 5, base::UTF8ToUTF16("invalid URL"), kStackTrace16); @@ -219,7 +253,9 @@ } TEST_F(WebUIMainFrameObserverTest, NotSentIfDisabledForPage) { - observer_->DisableJavaScriptErrorReporting(); + static_cast<MockWebUIController*>(web_ui_->GetController()) + ->enable_javascript_error_reporting(false); + CreateRenderFrame(); CallOnDidAddMessageToConsole(web_ui_->frame_host(), blink::mojom::ConsoleMessageLevel::kError, kMessage16, 5, kSourceId16, kStackTrace16); @@ -228,6 +264,7 @@ } TEST_F(WebUIMainFrameObserverTest, URLPathIsPreservedOtherPartsRemoved) { + CreateRenderFrame(); struct URLTest { const char* const input; const char* const expected; @@ -270,6 +307,7 @@ } TEST_F(WebUIMainFrameObserverTest, ErrorsNotReportedInOtherFrames) { + CreateRenderFrame(); auto another_contents = TestWebContents::Create(browser_context(), site_instance_); CHECK(another_contents->GetMainFrame()); @@ -281,6 +319,7 @@ } TEST_F(WebUIMainFrameObserverTest, ErrorsNotReportedForNonChromeURLs) { + CreateRenderFrame(); const char* const kNonChromeSourceURLs[] = { "chrome-untrusted://media-app", "chrome-error://chromewebdata/",
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index ef85167..81511b97 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -134,8 +134,6 @@ "pepper_renderer_instance_data.h", "process_type.cc", "resource_messages.h", - "service_manager/service_manager_connection_impl.cc", - "service_manager/service_manager_connection_impl.h", "service_worker/service_worker_loader_helpers.cc", "service_worker/service_worker_loader_helpers.h", "service_worker/service_worker_utils.cc",
diff --git a/content/common/frame.mojom b/content/common/frame.mojom index e959809..d75eee23 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom
@@ -202,6 +202,11 @@ bool wants_result, int32 world_id) => (mojo_base.mojom.Value result); + // Indicates that the frame host (browser) wants the |untrusted_stack_trace| + // parameter of DidAddMessageToConsole() filled in for Error messages if at + // all possible. + SetWantErrorMessageStackTrace(); + // Requests that a provisional RenderFrame swap itself into the frame tree, // replacing the RenderFrameProxy that it is associated with. This is used // with remote-to-local frame navigations when the RenderFrameProxy @@ -517,8 +522,9 @@ // error reporting service. |source_id| is usually a URL. // |untrusted_stack_trace| should only be printed or sent to other services; // it's untrusted and should not be parsed to get a structured stack trace. - // The stack trace is only present if the message is from an exception and - // only if Frame.SetWantExceptionStackTrace has been called for this frame. + // The stack trace is only present if + // FrameNavigationControl.SetWantErrorMessageStackTrace has been called for + // this frame and the log_level is kError. DidAddMessageToConsole( blink.mojom.ConsoleMessageLevel log_level, mojo_base.mojom.BigString16 msg,
diff --git a/content/common/service_manager/service_manager_connection_impl.cc b/content/common/service_manager/service_manager_connection_impl.cc deleted file mode 100644 index 1b6ffd6c..0000000 --- a/content/common/service_manager/service_manager_connection_impl.cc +++ /dev/null
@@ -1,378 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/service_manager/service_manager_connection_impl.h" - -#include <map> -#include <queue> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/callback_helpers.h" -#include "base/compiler_specific.h" -#include "base/lazy_instance.h" -#include "base/macros.h" -#include "base/task/current_thread.h" -#include "base/thread_annotations.h" -#include "base/threading/thread_checker.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build/build_config.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/service_receiver.h" -#include "services/service_manager/public/mojom/constants.mojom.h" -#include "services/service_manager/public/mojom/interface_provider.mojom.h" - -namespace content { -namespace { - -base::LazyInstance<std::unique_ptr<ServiceManagerConnection>>::Leaky - g_connection_for_process = LAZY_INSTANCE_INITIALIZER; - -ServiceManagerConnection::Factory* service_manager_connection_factory = nullptr; - -} // namespace - -// A ref-counted object which owns the IO thread state of a -// ServiceManagerConnectionImpl. This includes Service and ServiceFactory -// bindings. -class ServiceManagerConnectionImpl::IOThreadContext - : public base::RefCountedThreadSafe<IOThreadContext>, - public service_manager::Service { - public: - IOThreadContext( - mojo::PendingReceiver<service_manager::mojom::Service> service_receiver, - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - mojo::PendingReceiver<service_manager::mojom::Connector> - connector_receiver) - : pending_service_receiver_(std::move(service_receiver)), - io_task_runner_(io_task_runner), - pending_connector_receiver_(std::move(connector_receiver)) { - // This will be reattached by any of the IO thread functions on first call. - io_thread_checker_.DetachFromThread(); - } - - void SetDefaultServiceRequestHandler( - const ServiceManagerConnection::DefaultServiceRequestHandler& handler) { - DCHECK(!started_); - default_request_handler_ = handler; - } - - // Safe to call from any thread. - void Start(base::OnceClosure stop_callback) { - DCHECK(!started_); - - started_ = true; - callback_task_runner_ = base::ThreadTaskRunnerHandle::Get(); - stop_callback_ = std::move(stop_callback); - io_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&IOThreadContext::StartOnIOThread, this)); - } - - void Stop() { - io_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&IOThreadContext::StopOnIOThread, this)); - } - - // Safe to call from whichever thread called Start() (or may have called - // Start()). Must be called before IO thread shutdown. - void ShutDown() { - if (!started_) - return; - - bool posted = io_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&IOThreadContext::ShutDownOnIOThread, this)); - DCHECK(posted); - } - - void AddServiceRequestHandler(const std::string& name, - const ServiceRequestHandler& handler) { - AddServiceRequestHandlerWithCallback( - name, - base::BindRepeating(&WrapServiceRequestHandlerNoCallback, handler)); - } - - void AddServiceRequestHandlerWithCallback( - const std::string& name, - const ServiceRequestHandlerWithCallback& handler) { - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&ServiceManagerConnectionImpl::IOThreadContext:: - AddServiceRequestHandlerOnIoThread, - this, name, handler)); - } - - private: - friend class base::RefCountedThreadSafe<IOThreadContext>; - - class MessageLoopObserver : public base::CurrentThread::DestructionObserver { - public: - explicit MessageLoopObserver(base::WeakPtr<IOThreadContext> context) - : context_(context) { - base::CurrentThread::Get()->AddDestructionObserver(this); - } - - ~MessageLoopObserver() override { - base::CurrentThread::Get()->RemoveDestructionObserver(this); - } - - void ShutDown() { - if (!is_active_) - return; - - // The call into |context_| below may reenter ShutDown(), hence we set - // |is_active_| to false here. - is_active_ = false; - if (context_) - context_->ShutDownOnIOThread(); - - delete this; - } - - private: - void WillDestroyCurrentMessageLoop() override { - DCHECK(is_active_); - ShutDown(); - } - - bool is_active_ = true; - base::WeakPtr<IOThreadContext> context_; - - DISALLOW_COPY_AND_ASSIGN(MessageLoopObserver); - }; - - ~IOThreadContext() override {} - - static void WrapServiceRequestHandlerNoCallback( - const ServiceRequestHandler& handler, - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - CreatePackagedServiceInstanceCallback callback) { - handler.Run(std::move(receiver)); - std::move(callback).Run(base::GetCurrentProcId()); - } - - void StartOnIOThread() { - // Should bind |io_thread_checker_| to the context's thread. - DCHECK(io_thread_checker_.CalledOnValidThread()); - service_receiver_ = std::make_unique<service_manager::ServiceReceiver>( - this, std::move(pending_service_receiver_)); - service_receiver_->GetConnector()->BindConnectorReceiver( - std::move(pending_connector_receiver_)); - - // MessageLoopObserver owns itself. - message_loop_observer_ = - new MessageLoopObserver(weak_factory_.GetWeakPtr()); - } - - void StopOnIOThread() { - request_handlers_.clear(); - } - - void ShutDownOnIOThread() { - DCHECK(io_thread_checker_.CalledOnValidThread()); - - weak_factory_.InvalidateWeakPtrs(); - - // Note that this method may be invoked by MessageLoopObserver observing - // MessageLoop destruction. In that case, this call to ShutDown is - // effectively a no-op. In any case it's safe. - if (message_loop_observer_) { - message_loop_observer_->ShutDown(); - message_loop_observer_ = nullptr; - } - - // Resetting the ServiceContext below may otherwise release the last - // reference to this IOThreadContext. We keep it alive until the stack - // unwinds. - scoped_refptr<IOThreadContext> keepalive(this); - - service_receiver_.reset(); - - StopOnIOThread(); - } - - void AddServiceRequestHandlerOnIoThread( - const std::string& name, - const ServiceRequestHandlerWithCallback& handler) { - DCHECK(io_thread_checker_.CalledOnValidThread()); - auto result = request_handlers_.insert(std::make_pair(name, handler)); - DCHECK(result.second) << "ServiceRequestHandler for " << name - << " already exists."; - } - - ///////////////////////////////////////////////////////////////////////////// - // service_manager::Service implementation - - void OnBindInterface(const service_manager::BindSourceInfo& source_info, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override {} - - void CreatePackagedServiceInstance( - const std::string& service_name, - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - CreatePackagedServiceInstanceCallback callback) override { - DCHECK(io_thread_checker_.CalledOnValidThread()); - auto it = request_handlers_.find(service_name); - if (it == request_handlers_.end()) { - if (default_request_handler_) { - callback_task_runner_->PostTask( - FROM_HERE, base::BindOnce(default_request_handler_, service_name, - std::move(receiver))); - } else { - LOG(ERROR) << "Can't create service " << service_name - << ". No handler found."; - } - std::move(callback).Run(base::nullopt); - } else { - it->second.Run(std::move(receiver), std::move(callback)); - } - } - - void OnDisconnected() override { - callback_task_runner_->PostTask(FROM_HERE, std::move(stop_callback_)); - } - - base::ThreadChecker io_thread_checker_; - bool started_ = false; - - ServiceManagerConnection::DefaultServiceRequestHandler - default_request_handler_; - - // Temporary state established on construction and consumed on the IO thread - // once the connection is started. - mojo::PendingReceiver<service_manager::mojom::Service> - pending_service_receiver_; - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - mojo::PendingReceiver<service_manager::mojom::Connector> - pending_connector_receiver_; - - // TaskRunner on which to run our owner's callbacks, i.e. the ones passed to - // Start(). - scoped_refptr<base::SequencedTaskRunner> callback_task_runner_; - - // Callback to run if the service is stopped by the service manager. - base::OnceClosure stop_callback_; - - std::unique_ptr<service_manager::ServiceReceiver> service_receiver_; - - // Not owned. - MessageLoopObserver* message_loop_observer_ = nullptr; - - std::map<std::string, ServiceRequestHandlerWithCallback> request_handlers_; - - base::WeakPtrFactory<IOThreadContext> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(IOThreadContext); -}; - -//////////////////////////////////////////////////////////////////////////////// -// ServiceManagerConnection, public: - -// static -void ServiceManagerConnection::SetForProcess( - std::unique_ptr<ServiceManagerConnection> connection) { - DCHECK(!g_connection_for_process.Get()); - g_connection_for_process.Get() = std::move(connection); -} - -// static -ServiceManagerConnection* ServiceManagerConnection::GetForProcess() { - return g_connection_for_process.Get().get(); -} - -// static -void ServiceManagerConnection::DestroyForProcess() { - // This joins the service manager controller thread. - g_connection_for_process.Get().reset(); -} - -// static -void ServiceManagerConnection::SetFactoryForTest(Factory* factory) { - DCHECK(!g_connection_for_process.Get()); - service_manager_connection_factory = factory; -} - -// static -std::unique_ptr<ServiceManagerConnection> ServiceManagerConnection::Create( - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - scoped_refptr<base::SequencedTaskRunner> io_task_runner) { - if (service_manager_connection_factory) - return service_manager_connection_factory->Run(); - return std::make_unique<ServiceManagerConnectionImpl>(std::move(receiver), - io_task_runner); -} - -ServiceManagerConnection::~ServiceManagerConnection() {} - -//////////////////////////////////////////////////////////////////////////////// -// ServiceManagerConnectionImpl, public: - -ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - scoped_refptr<base::SequencedTaskRunner> io_task_runner) { - mojo::PendingReceiver<service_manager::mojom::Connector> connector_receiver; - connector_ = service_manager::Connector::Create(&connector_receiver); - context_ = new IOThreadContext(std::move(receiver), io_task_runner, - std::move(connector_receiver)); -} - -ServiceManagerConnectionImpl::~ServiceManagerConnectionImpl() { - context_->ShutDown(); -} - -//////////////////////////////////////////////////////////////////////////////// -// ServiceManagerConnectionImpl, ServiceManagerConnection implementation: - -void ServiceManagerConnectionImpl::Start() { - context_->Start( - base::BindOnce(&ServiceManagerConnectionImpl::OnConnectionLost, - weak_factory_.GetWeakPtr())); -} - -void ServiceManagerConnectionImpl::Stop() { - context_->Stop(); -} - -service_manager::Connector* ServiceManagerConnectionImpl::GetConnector() { - return connector_.get(); -} - -void ServiceManagerConnectionImpl::SetConnectionLostClosure( - base::OnceClosure closure) { - connection_lost_handler_ = std::move(closure); -} - -void ServiceManagerConnectionImpl::AddServiceRequestHandler( - const std::string& name, - const ServiceRequestHandler& handler) { - context_->AddServiceRequestHandler(name, handler); -} - -void ServiceManagerConnectionImpl::AddServiceRequestHandlerWithCallback( - const std::string& name, - const ServiceRequestHandlerWithCallback& handler) { - context_->AddServiceRequestHandlerWithCallback(name, handler); -} - -void ServiceManagerConnectionImpl::SetDefaultServiceRequestHandler( - const DefaultServiceRequestHandler& handler) { - context_->SetDefaultServiceRequestHandler(handler); -} - -void ServiceManagerConnectionImpl::OnConnectionLost() { - if (!connection_lost_handler_.is_null()) - std::move(connection_lost_handler_).Run(); -} - -void ServiceManagerConnectionImpl::GetInterface( - service_manager::mojom::InterfaceProvider* provider, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle request_handle) { - provider->GetInterface(interface_name, std::move(request_handle)); -} - -} // namespace content
diff --git a/content/common/service_manager/service_manager_connection_impl.h b/content/common/service_manager/service_manager_connection_impl.h deleted file mode 100644 index 64232384..0000000 --- a/content/common/service_manager/service_manager_connection_impl.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_ -#define CONTENT_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/sequenced_task_runner.h" -#include "content/common/content_export.h" -#include "content/public/common/service_manager_connection.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/mojom/service.mojom.h" - -namespace service_manager { -class Connector; -} - -namespace content { - -class CONTENT_EXPORT ServiceManagerConnectionImpl - : public ServiceManagerConnection { - public: - explicit ServiceManagerConnectionImpl( - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - scoped_refptr<base::SequencedTaskRunner> io_task_runner); - ~ServiceManagerConnectionImpl() override; - - private: - class IOThreadContext; - - // ServiceManagerConnection: - void Start() override; - void Stop() override; - service_manager::Connector* GetConnector() override; - void SetConnectionLostClosure(base::OnceClosure closure) override; - void AddServiceRequestHandler( - const std::string& name, - const ServiceRequestHandler& handler) override; - void AddServiceRequestHandlerWithCallback( - const std::string& name, - const ServiceRequestHandlerWithCallback& handler) override; - void SetDefaultServiceRequestHandler( - const DefaultServiceRequestHandler& handler) override; - - void OnConnectionLost(); - void GetInterface(service_manager::mojom::InterfaceProvider* provider, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle request_handle); - - std::unique_ptr<service_manager::Connector> connector_; - scoped_refptr<IOThreadContext> context_; - - base::OnceClosure connection_lost_handler_; - - base::WeakPtrFactory<ServiceManagerConnectionImpl> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ServiceManagerConnectionImpl); -}; - -} // namespace content - -#endif // CONTENT_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_
diff --git a/content/common/service_manager/service_manager_connection_impl_unittest.cc b/content/common/service_manager/service_manager_connection_impl_unittest.cc deleted file mode 100644 index b4100168..0000000 --- a/content/common/service_manager/service_manager_connection_impl_unittest.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/service_manager/service_manager_connection_impl.h" - -#include "base/callback_helpers.h" -#include "base/synchronization/waitable_event.h" -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "services/service_manager/public/cpp/constants.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/cpp/service.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace content { -namespace { - -constexpr char kTestServiceName[] = "test service"; - -} // namespace - -TEST(ServiceManagerConnectionImplTest, ServiceLaunchThreading) { - base::test::SingleThreadTaskEnvironment task_environment; - base::Thread io_thread("ServiceManagerConnectionImplTest IO Thread"); - io_thread.Start(); - mojo::Remote<service_manager::mojom::Service> service; - ServiceManagerConnectionImpl connection_impl( - service.BindNewPipeAndPassReceiver(), io_thread.task_runner()); - ServiceManagerConnection& connection = connection_impl; - base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - connection.AddServiceRequestHandler( - kTestServiceName, - base::BindLambdaForTesting( - [&event](mojo::PendingReceiver<service_manager::mojom::Service>) { - event.Signal(); - })); - connection.Start(); - - mojo::PendingRemote<service_manager::mojom::Service> packaged_service; - mojo::PendingRemote<service_manager::mojom::ProcessMetadata> metadata; - ignore_result(metadata.InitWithNewPipeAndPassReceiver()); - service->CreatePackagedServiceInstance( - service_manager::Identity(kTestServiceName, base::Token::CreateRandom(), - base::Token(), base::Token::CreateRandom()), - packaged_service.InitWithNewPipeAndPassReceiver(), std::move(metadata)); - event.Wait(); -} - -} // namespace content
diff --git a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsObserverProxy.java b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsObserverProxy.java index d3429de..7d54ac5 100644 --- a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsObserverProxy.java +++ b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsObserverProxy.java
@@ -13,6 +13,7 @@ import org.chromium.content_public.browser.NavigationHandle; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.ui.base.WindowAndroid; +import org.chromium.url.GURL; /** * Serves as a compound observer proxy for dispatching WebContentsObserver callbacks, @@ -121,7 +122,7 @@ @Override @CalledByNative - public void didStartLoading(String url) { + public void didStartLoading(GURL url) { for (mObserversIterator.rewind(); mObserversIterator.hasNext();) { mObserversIterator.next().didStartLoading(url); } @@ -129,9 +130,9 @@ @Override @CalledByNative - public void didStopLoading(String url) { + public void didStopLoading(GURL url, boolean isKnownValid) { for (mObserversIterator.rewind(); mObserversIterator.hasNext();) { - mObserversIterator.next().didStopLoading(url); + mObserversIterator.next().didStopLoading(url, isKnownValid); } } @@ -153,7 +154,7 @@ @Override @CalledByNative - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingUrl) { for (mObserversIterator.rewind(); mObserversIterator.hasNext();) { mObserversIterator.next().didFailLoad(isMainFrame, errorCode, failingUrl); } @@ -201,9 +202,9 @@ @Override @CalledByNative - public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) { + public void didFinishLoad(long frameId, GURL url, boolean isKnownValid, boolean isMainFrame) { for (mObserversIterator.rewind(); mObserversIterator.hasNext();) { - mObserversIterator.next().didFinishLoad(frameId, validatedUrl, isMainFrame); + mObserversIterator.next().didFinishLoad(frameId, url, isKnownValid, isMainFrame); } }
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java b/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java index 4c96122..2473b365 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java
@@ -9,6 +9,7 @@ import org.chromium.blink.mojom.ViewportFit; import org.chromium.ui.base.WindowAndroid; +import org.chromium.url.GURL; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -87,13 +88,17 @@ * Called when the a page starts loading. * @param url The validated url for the loading page. */ - public void didStartLoading(String url) {} + public void didStartLoading(GURL url) {} /** * Called when the a page finishes loading. - * @param url The validated url for the page. + * @param url The url for the page. + * @param isKnownValid Whether the url is known to be valid. + * TODO(yfriedman): There's currently a layering violation and this is needed for aw/ + * For chrome, the url will always be valid. + * */ - public void didStopLoading(String url) {} + public void didStopLoading(GURL url, boolean isKnownValid) {} /** * Called when a page's load progress has changed. @@ -112,7 +117,7 @@ * @param errorCode Error code for the occurring error. * @param failingUrl The url that was loading when the error occurred. */ - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) {} + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingUrl) {} /** * Called when the page had painted something non-empty. @@ -143,10 +148,11 @@ /** * Notifies that a load has finished for a given frame. * @param frameId A positive, non-zero integer identifying the navigating frame. - * @param validatedUrl The validated URL that is being navigated to. + * @param url The validated URL that is being navigated to. + * @param isKnownValid Whether the URL is known to be valid. * @param isMainFrame Whether the load is happening for the main frame. */ - public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) {} + public void didFinishLoad(long frameId, GURL url, boolean isKnownValid, boolean isMainFrame) {} /** * Notifies that the document has finished loading for the given frame.
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java b/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java index 34664cf..bf61216 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java
@@ -26,6 +26,7 @@ import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.CriteriaNotSatisfiedException; +import org.chromium.base.test.util.DisabledTest; import org.chromium.content.R; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.test.ContentJUnit4ClassRunner; @@ -62,6 +63,7 @@ @Test @LargeTest + @DisabledTest(message = "https://crbug.com/1156419") public void testDeleteWordMarkedWithSuggestionMarker() throws InterruptedException, Throwable, TimeoutException { WebContents webContents = mRule.getWebContents();
diff --git a/content/public/browser/render_process_host.h b/content/public/browser/render_process_host.h index 1e09b69..1c0c0de 100644 --- a/content/public/browser/render_process_host.h +++ b/content/public/browser/render_process_host.h
@@ -544,13 +544,12 @@ // Controls whether the destructor of RenderProcessHost*Impl* will end up // cleaning the memory used by the exception added via - // RenderProcessHostImpl::AddCorbExceptionForPlugin and - // AddAllowedRequestInitiatorForPlugin. + // RenderProcessHostImpl::AddAllowedRequestInitiatorForPlugin. // // TODO(lukasza): https://crbug.com/652474: This method shouldn't be part of // the //content public API, because it shouldn't be called by anyone other // than RenderProcessHostImpl (from underneath - // RenderProcessHostImpl::AddCorbExceptionForPlugin). + // RenderProcessHostImpl::AddAllowedRequestInitiatorForPlugin). virtual void CleanupNetworkServicePluginExceptionsUponDestruction() = 0; // Returns a string that contains information useful for debugging
diff --git a/content/public/browser/web_ui.h b/content/public/browser/web_ui.h index 4d5d6ba4..fa6f10c 100644 --- a/content/public/browser/web_ui.h +++ b/content/public/browser/web_ui.h
@@ -130,19 +130,6 @@ const std::string& function_name, const std::vector<const base::Value*>& args) = 0; - // Controls whether the engineering team receives JavaScript error reports for - // this WebUI. For example, WebUIs may report JavaScript errors and unhandled - // exceptions to an error reporting service if this function isn't called. - // - // WebUIs may want to call this function if they are reporting errors via - // other channels and don't want duplicates. For instance, a WebUI which uses - // crashReportPrivate to report JS errors might call this function to avoid - // duplicate reports. WebUIs might also call this function to avoid noise if - // the engineering team doesn't expect to fix reported errors; for instance, - // a low-usage debugging page might turn off error reports if the owners feel - // any reported bugs would be too low priority to bother with. - virtual void DisableJavaScriptErrorReporting() = 0; - // Allows mutable access to this WebUI's message handlers for testing. virtual std::vector<std::unique_ptr<WebUIMessageHandler>>* GetHandlersForTesting() = 0;
diff --git a/content/public/browser/web_ui_controller.cc b/content/public/browser/web_ui_controller.cc index 739aab6..6f2fc19 100644 --- a/content/public/browser/web_ui_controller.cc +++ b/content/public/browser/web_ui_controller.cc
@@ -16,4 +16,8 @@ return nullptr; } +bool WebUIController::IsJavascriptErrorReportingEnabled() { + return true; +} + } // namespace content
diff --git a/content/public/browser/web_ui_controller.h b/content/public/browser/web_ui_controller.h index 1c7d821..8b40865 100644 --- a/content/public/browser/web_ui_controller.h +++ b/content/public/browser/web_ui_controller.h
@@ -57,6 +57,20 @@ : nullptr; } + // Controls whether the engineering team receives JavaScript error reports for + // this WebUI. For example, WebUIs may report JavaScript errors and unhandled + // exceptions to an error reporting service if this function isn't called. + // + // WebUIs may want to override this function if they are reporting errors via + // other channels and don't want duplicates. For instance, a WebUI which uses + // crashReportPrivate to report JS errors might override this function to + // return to false in order to avoid duplicate reports. WebUIs might also + // override this function to return false to avoid noise if the engineering + // team doesn't expect to fix reported errors; for instance, a low-usage + // debugging page might turn off error reports if the owners feel any reported + // bugs would be too low priority to bother with. + virtual bool IsJavascriptErrorReportingEnabled(); + protected: // TODO(calamity): Make this abstract once all subclasses implement GetType(). virtual Type GetType();
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn index df6b4852..d854c24 100644 --- a/content/public/common/BUILD.gn +++ b/content/public/common/BUILD.gn
@@ -151,7 +151,6 @@ "sandbox_init.h", "sandboxed_process_launcher_delegate.cc", "sandboxed_process_launcher_delegate.h", - "service_manager_connection.h", "socket_permission_request.h", "stop_find_action.h", "storage_quota_params.h",
diff --git a/content/public/common/service_manager_connection.h b/content/public/common/service_manager_connection.h deleted file mode 100644 index 88aa291..0000000 --- a/content/public/common/service_manager_connection.h +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_PUBLIC_COMMON_SERVICE_MANAGER_CONNECTION_H_ -#define CONTENT_PUBLIC_COMMON_SERVICE_MANAGER_CONNECTION_H_ - -#include <memory> - -#include "base/callback_forward.h" -#include "base/sequenced_task_runner.h" -#include "content/common/content_export.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/mojom/connector.mojom-forward.h" -#include "services/service_manager/public/mojom/service.mojom-forward.h" - -namespace service_manager { -class Connector; -} - -namespace content { - -// Encapsulates a connection to a //services/service_manager. -// Access a global instance on the thread the ServiceContext was bound by -// calling Holder::Get(). -// Clients can add service_manager::Service implementations whose exposed -// interfaces -// will be exposed to inbound connections to this object's Service. -// Alternatively clients can define named services that will be constructed when -// requests for those service names are received. -// Clients must call any of the registration methods when receiving -// ContentBrowserClient::RegisterInProcessServices(). -class CONTENT_EXPORT ServiceManagerConnection { - public: - using ServiceRequestHandler = base::RepeatingCallback<void( - mojo::PendingReceiver<service_manager::mojom::Service>)>; - using ServiceRequestHandlerWithCallback = base::RepeatingCallback<void( - mojo::PendingReceiver<service_manager::mojom::Service>, - service_manager::Service::CreatePackagedServiceInstanceCallback)>; - using Factory = - base::RepeatingCallback<std::unique_ptr<ServiceManagerConnection>(void)>; - - // Stores an instance of |connection| in TLS for the current process. Must be - // called on the thread the connection was created on. - static void SetForProcess( - std::unique_ptr<ServiceManagerConnection> connection); - - // Returns the per-process instance, or nullptr if the Service Manager - // connection has not yet been bound. Must be called on the thread the - // connection was created on. - static ServiceManagerConnection* GetForProcess(); - - // Destroys the per-process instance. Must be called on the thread the - // connection was created on. - static void DestroyForProcess(); - - virtual ~ServiceManagerConnection(); - - // Sets the factory used to create the ServiceManagerConnection. This must be - // called before the ServiceManagerConnection has been created. - static void SetFactoryForTest(Factory* factory); - - // Creates a ServiceManagerConnection from |request|. The connection binds - // its interfaces and accept new connections on |io_task_runner| only. Note - // that no incoming connections are accepted until Start() is called. - static std::unique_ptr<ServiceManagerConnection> Create( - mojo::PendingReceiver<service_manager::mojom::Service> receiver, - scoped_refptr<base::SequencedTaskRunner> io_task_runner); - - // Begins accepting incoming connections. - virtual void Start() = 0; - - // Stops accepting incoming connections. This happens asynchronously by - // posting to the IO thread, and cannot be undone. - virtual void Stop() = 0; - - // Returns the service_manager::Connector received via this connection's - // Service - // implementation. Use this to initiate connections as this object's Identity. - virtual service_manager::Connector* GetConnector() = 0; - - // Sets a closure that is called when the connection is lost. Note that - // connection may already have been closed, in which case |closure| will be - // run immediately before returning from this function. - virtual void SetConnectionLostClosure(base::OnceClosure closure) = 0; - - // Adds a generic ServiceRequestHandler for a given service name. This - // will be used to satisfy any incoming calls to CreateService() which - // reference the given name. - virtual void AddServiceRequestHandler( - const std::string& name, - const ServiceRequestHandler& handler) = 0; - - // Similar to above but for registering handlers which want to communicate - // additional information the process hosting the new service. - virtual void AddServiceRequestHandlerWithCallback( - const std::string& name, - const ServiceRequestHandlerWithCallback& handler) = 0; - - // Sets a request handler to use if no registered handlers were interested in - // an incoming service request. Must be called before |Start()|. - using DefaultServiceRequestHandler = base::RepeatingCallback<void( - const std::string& service_name, - mojo::PendingReceiver<service_manager::mojom::Service>)>; - virtual void SetDefaultServiceRequestHandler( - const DefaultServiceRequestHandler& handler) = 0; -}; - -} // namespace content - -#endif // CONTENT_PUBLIC_COMMON_SERVICE_MANAGER_CONNECTION_H_
diff --git a/content/public/renderer/content_renderer_client.cc b/content/public/renderer/content_renderer_client.cc index 6aea489..78174b92 100644 --- a/content/public/renderer/content_renderer_client.cc +++ b/content/public/renderer/content_renderer_client.cc
@@ -4,7 +4,9 @@ #include "content/public/renderer/content_renderer_client.h" +#include "base/command_line.h" #include "build/build_config.h" +#include "content/public/common/content_switches.h" #include "media/base/demuxer.h" #include "media/base/renderer_factory.h" #include "third_party/blink/public/common/security/protocol_handler_security_level.h" @@ -150,7 +152,13 @@ bool ContentRendererClient::IsOriginIsolatedPepperPlugin( const base::FilePath& plugin_path) { - return false; + // Hosting plugins in-process is inherently incompatible with attempting to + // process-isolate plugins from different origins. + auto* cmdline = base::CommandLine::ForCurrentProcess(); + if (cmdline->HasSwitch(switches::kPpapiInProcess)) + return false; + + return true; } void ContentRendererClient::AddSupportedKeySystems(
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/TestWebContentsObserver.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/TestWebContentsObserver.java index 179a3b6..0297d3df 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/TestWebContentsObserver.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/TestWebContentsObserver.java
@@ -10,6 +10,7 @@ import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper; import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnPageStartedHelper; import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnReceivedErrorHelper; +import org.chromium.url.GURL; /** * The default WebContentsObserver used by ContentView tests. The below callbacks can be @@ -52,21 +53,21 @@ * stop working! */ @Override - public void didStartLoading(String url) { + public void didStartLoading(GURL url) { super.didStartLoading(url); - mOnPageStartedHelper.notifyCalled(url); + mOnPageStartedHelper.notifyCalled(url.getPossiblyInvalidSpec()); } @Override - public void didStopLoading(String url) { - super.didStopLoading(url); - mOnPageFinishedHelper.notifyCalled(url); + public void didStopLoading(GURL url, boolean isKnownValid) { + super.didStopLoading(url, isKnownValid); + mOnPageFinishedHelper.notifyCalled(url.getPossiblyInvalidSpec()); } @Override - public void didFailLoad(boolean isMainFrame, int errorCode, String failingUrl) { + public void didFailLoad(boolean isMainFrame, int errorCode, GURL failingUrl) { super.didFailLoad(isMainFrame, errorCode, failingUrl); - mOnReceivedErrorHelper.notifyCalled(errorCode, "Error " + errorCode, failingUrl); + mOnReceivedErrorHelper.notifyCalled(errorCode, "Error " + errorCode, failingUrl.getSpec()); } @Override
diff --git a/content/public/test/ppapi_test_utils.cc b/content/public/test/ppapi_test_utils.cc index c76839af..ce36836c 100644 --- a/content/public/test/ppapi_test_utils.cc +++ b/content/public/test/ppapi_test_utils.cc
@@ -73,17 +73,17 @@ return RegisterPlugins(command_line, plugins); } -bool RegisterFlashTestPluginLibrary(base::CommandLine* command_line, - const StringType& library_name) { +bool RegisterFakePdfPluginLibrary(base::CommandLine* command_line, + const StringType& library_name) { std::vector<PluginInfo> plugins; - // Register a fake Flash with 100.0 version (to avoid outdated checks). - base::FilePath::StringType fake_flash_parameter = - base::FilePath::FromUTF8Unsafe(std::string("#") + "Shockwave Flash" + + // Register a fake PDF plugin with 100.0 version (to avoid outdated checks). + base::FilePath::StringType fake_pdf_parameter = + base::FilePath::FromUTF8Unsafe(std::string("#") + "Fake PDF" + "#Description#100.0") .value(); plugins.push_back( - PluginInfo(library_name, fake_flash_parameter, - FILE_PATH_LITERAL("application/x-shockwave-flash"))); + PluginInfo(library_name, fake_pdf_parameter, + FILE_PATH_LITERAL("application/x-fake-pdf-for-testing"))); return RegisterPlugins(command_line, plugins); } @@ -111,7 +111,7 @@ bool RegisterCorbTestPlugin(base::CommandLine* command_line) { StringType library_name = base::FilePath::FromUTF8Unsafe(ppapi::kCorbTestPluginName).value(); - return RegisterFlashTestPluginLibrary(command_line, library_name); + return RegisterFakePdfPluginLibrary(command_line, library_name); } bool RegisterBlinkTestPlugin(base::CommandLine* command_line) {
diff --git a/content/public/test/ppapi_test_utils.h b/content/public/test/ppapi_test_utils.h index 3cfb28f..6fbe4b0b 100644 --- a/content/public/test/ppapi_test_utils.h +++ b/content/public/test/ppapi_test_utils.h
@@ -37,7 +37,7 @@ const base::FilePath::StringType& extra_registration_parameters) WARN_UNUSED_RESULT; -// Registers the Flash-imitating CORB-testing plugin. +// Registers the PDF-imitating CORB-testing plugin. bool RegisterCorbTestPlugin(base::CommandLine* command_line) WARN_UNUSED_RESULT; // Registers the Blink test plugin to application/x-blink-test-plugin.
diff --git a/content/public/test/test_web_ui.cc b/content/public/test/test_web_ui.cc index 6c0bfea..f8de9ec1 100644 --- a/content/public/test/test_web_ui.cc +++ b/content/public/test/test_web_ui.cc
@@ -155,8 +155,6 @@ return &handlers_; } -void TestWebUI::DisableJavaScriptErrorReporting() {} - TestWebUI::CallData::CallData(const std::string& function_name) : function_name_(function_name) { }
diff --git a/content/public/test/test_web_ui.h b/content/public/test/test_web_ui.h index b0f1f896..6808185 100644 --- a/content/public/test/test_web_ui.h +++ b/content/public/test/test_web_ui.h
@@ -68,7 +68,6 @@ const std::vector<const base::Value*>& args) override; std::vector<std::unique_ptr<WebUIMessageHandler>>* GetHandlersForTesting() override; - void DisableJavaScriptErrorReporting() override; class CallData { public:
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 7fa6996..57e9b97 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -85,8 +85,6 @@ "loader/resource_dispatcher.h", "loader/sync_load_context.cc", "loader/sync_load_context.h", - "loader/url_loader_client_impl.cc", - "loader/url_loader_client_impl.h", "loader/web_url_loader_impl.cc", "loader/web_url_loader_impl.h", "loader/web_worker_fetch_context_impl.cc",
diff --git a/content/renderer/accessibility/blink_ax_tree_source.cc b/content/renderer/accessibility/blink_ax_tree_source.cc index 469fff5..665087d 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.cc +++ b/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -51,8 +51,6 @@ using base::ASCIIToUTF16; using base::UTF16ToUTF8; using blink::WebAXObject; -using blink::WebAXObjectAttribute; -using blink::WebAXObjectVectorAttribute; using blink::WebDocument; using blink::WebElement; using blink::WebFrame; @@ -82,56 +80,6 @@ dst->AddIntListAttribute(attr, ids); } -class AXNodeDataSparseAttributeAdapter - : public blink::WebAXSparseAttributeClient { - public: - explicit AXNodeDataSparseAttributeAdapter(ui::AXNodeData* dst) : dst_(dst) { - DCHECK(dst_); - } - ~AXNodeDataSparseAttributeAdapter() override = default; - - private: - ui::AXNodeData* dst_; - - void AddObjectAttribute(WebAXObjectAttribute attribute, - const WebAXObject& value) override { - switch (attribute) { - case WebAXObjectAttribute::kAriaActiveDescendant: - // TODO(dmazzoni): WebAXObject::ActiveDescendant currently returns - // more information than the sparse interface does. - // ******** Why is this a TODO? ******** - break; - case WebAXObjectAttribute::kAriaErrorMessage: - // Use WebAXObject::ErrorMessage(), which provides both ARIA error - // messages as well as built-in HTML form validation messages. - break; - default: - NOTREACHED(); - } - } - - void AddObjectVectorAttribute( - WebAXObjectVectorAttribute attribute, - const blink::WebVector<WebAXObject>& value) override { - switch (attribute) { - case WebAXObjectVectorAttribute::kAriaControls: - AddIntListAttributeFromWebObjects( - ax::mojom::IntListAttribute::kControlsIds, value, dst_); - break; - case WebAXObjectVectorAttribute::kAriaDetails: - AddIntListAttributeFromWebObjects( - ax::mojom::IntListAttribute::kDetailsIds, value, dst_); - break; - case WebAXObjectVectorAttribute::kAriaFlowTo: - AddIntListAttributeFromWebObjects( - ax::mojom::IntListAttribute::kFlowtoIds, value, dst_); - break; - default: - NOTREACHED(); - } - } -}; - WebAXObject ParentObjectUnignored(WebAXObject child) { WebAXObject parent = child.ParentObject(); while (!parent.IsDetached() && !parent.AccessibilityIsIncludedInTree()) @@ -581,7 +529,6 @@ SerializeBoundingBoxAttributes(src, dst); cached_bounding_boxes_[dst->id] = dst->relative_bounds; - SerializeSparseAttributes(src, dst); SerializeChooserPopupAttributes(src, dst); if (accessibility_mode_.has_mode(ui::AXMode::kScreenReader)) { @@ -651,12 +598,6 @@ } } -void BlinkAXTreeSource::SerializeSparseAttributes(WebAXObject src, - ui::AXNodeData* dst) const { - AXNodeDataSparseAttributeAdapter sparse_attribute_adapter(dst); - src.GetSparseAXAttributes(sparse_attribute_adapter); -} - void BlinkAXTreeSource::SerializeNameAndDescriptionAttributes( WebAXObject src, ui::AXNodeData* dst) const {
diff --git a/content/renderer/accessibility/blink_ax_tree_source.h b/content/renderer/accessibility/blink_ax_tree_source.h index c91d40a..cb8a9bb 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.h +++ b/content/renderer/accessibility/blink_ax_tree_source.h
@@ -136,8 +136,6 @@ void SerializeBoundingBoxAttributes(blink::WebAXObject src, ui::AXNodeData* dst) const; - void SerializeSparseAttributes(blink::WebAXObject src, - ui::AXNodeData* dst) const; void SerializeNameAndDescriptionAttributes(blink::WebAXObject src, ui::AXNodeData* dst) const; void SerializeInlineTextBoxAttributes(blink::WebAXObject src,
diff --git a/content/renderer/loader/resource_dispatcher.cc b/content/renderer/loader/resource_dispatcher.cc index 1b2ff5d..4b059e0 100644 --- a/content/renderer/loader/resource_dispatcher.cc +++ b/content/renderer/loader/resource_dispatcher.cc
@@ -25,7 +25,6 @@ #include "content/common/navigation_params.h" #include "content/public/renderer/resource_dispatcher_delegate.h" #include "content/renderer/loader/sync_load_context.h" -#include "content/renderer/loader/url_loader_client_impl.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_thread_impl.h" #include "net/base/load_flags.h" @@ -46,6 +45,7 @@ #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "third_party/blink/public/platform/resource_load_info_notifier_wrapper.h" #include "third_party/blink/public/platform/sync_load_response.h" +#include "third_party/blink/public/platform/web_mojo_url_loader_client.h" #include "third_party/blink/public/platform/web_request_peer.h" namespace content { @@ -131,6 +131,41 @@ return it->second.get(); } +void ResourceDispatcher::FollowPendingRedirect( + PendingRequestInfo* request_info) { + if (request_info->has_pending_redirect && + request_info->should_follow_redirect) { + request_info->has_pending_redirect = false; + // net::URLRequest clears its request_start on redirect, so should we. + request_info->local_request_start = base::TimeTicks::Now(); + // Redirect URL may not be handled by the network service, so force a + // restart in case another URLLoaderFactory should handle the URL. + if (request_info->redirect_requires_loader_restart) { + request_info->url_loader->FollowRedirectForcingRestart(); + } else { + request_info->url_loader->FollowRedirect( + request_info->removed_headers, {} /* modified_headers */, + {} /* modified_cors_exempt_headers */); + } + } +} + +void ResourceDispatcher::OnTransferSizeUpdated(int request_id, + int32_t transfer_size_diff) { + DCHECK_GT(transfer_size_diff, 0); + PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); + if (!request_info) + return; + + // TODO(yhirano): Consider using int64_t in + // blink::WebRequestPeer::OnTransferSizeUpdated. + request_info->peer->OnTransferSizeUpdated(transfer_size_diff); + if (!GetPendingRequestInfo(request_id)) + return; + request_info->resource_load_info_notifier_wrapper + ->NotifyResourceTransferSizeUpdated(transfer_size_diff); +} + void ResourceDispatcher::OnUploadProgress(int request_id, int64_t position, int64_t size) { @@ -183,16 +218,6 @@ } } -void ResourceDispatcher::OnStartLoadingResponseBody( - int request_id, - mojo::ScopedDataPipeConsumerHandle body) { - PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); - if (!request_info) - return; - - request_info->peer->OnStartLoadingResponseBody(std::move(body)); -} - void ResourceDispatcher::OnReceivedRedirect( int request_id, const net::RedirectInfo& redirect_info, @@ -248,23 +273,14 @@ } } -void ResourceDispatcher::FollowPendingRedirect( - PendingRequestInfo* request_info) { - if (request_info->has_pending_redirect && - request_info->should_follow_redirect) { - request_info->has_pending_redirect = false; - // net::URLRequest clears its request_start on redirect, so should we. - request_info->local_request_start = base::TimeTicks::Now(); - // Redirect URL may not be handled by the network service, so force a - // restart in case another URLLoaderFactory should handle the URL. - if (request_info->redirect_requires_loader_restart) { - request_info->url_loader->FollowRedirectForcingRestart(); - } else { - request_info->url_loader->FollowRedirect( - request_info->removed_headers, {} /* modified_headers */, - {} /* modified_cors_exempt_headers */); - } - } +void ResourceDispatcher::OnStartLoadingResponseBody( + int request_id, + mojo::ScopedDataPipeConsumerHandle body) { + PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); + if (!request_info) + return; + + request_info->peer->OnStartLoadingResponseBody(std::move(body)); } void ResourceDispatcher::OnRequestComplete( @@ -317,6 +333,14 @@ peer->OnCompletedRequest(renderer_status); } +void ResourceDispatcher::EvictFromBackForwardCache(int request_id) { + PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); + if (!request_info) + return; + + return request_info->peer->EvictFromBackForwardCache(); +} + bool ResourceDispatcher::RemovePendingRequest( int request_id, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { @@ -393,30 +417,6 @@ request_info->url_loader->SetPriority(new_priority, intra_priority_value); } -void ResourceDispatcher::OnTransferSizeUpdated(int request_id, - int32_t transfer_size_diff) { - DCHECK_GT(transfer_size_diff, 0); - PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); - if (!request_info) - return; - - // TODO(yhirano): Consider using int64_t in - // blink::WebRequestPeer::OnTransferSizeUpdated. - request_info->peer->OnTransferSizeUpdated(transfer_size_diff); - if (!GetPendingRequestInfo(request_id)) - return; - request_info->resource_load_info_notifier_wrapper - ->NotifyResourceTransferSizeUpdated(transfer_size_diff); -} - -void ResourceDispatcher::EvictFromBackForwardCache(int request_id) { - PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); - if (!request_info) - return; - - return request_info->peer->EvictFromBackForwardCache(); -} - void ResourceDispatcher::SetCorsExemptHeaderList( const std::vector<std::string>& list) { cors_exempt_header_list_ = list; @@ -547,9 +547,10 @@ pending_request->previews_state = request->previews_state; - std::unique_ptr<URLLoaderClientImpl> client(new URLLoaderClientImpl( - request_id, this, loading_task_runner, - url_loader_factory->BypassRedirectChecks(), request->url)); + std::unique_ptr<blink::WebMojoURLLoaderClient> client( + new blink::WebMojoURLLoaderClient( + request_id, this, loading_task_runner, + url_loader_factory->BypassRedirectChecks(), request->url)); std::unique_ptr<blink::ThrottlingURLLoader> url_loader = blink::ThrottlingURLLoader::CreateLoaderAndStart(
diff --git a/content/renderer/loader/resource_dispatcher.h b/content/renderer/loader/resource_dispatcher.h index c2b2738..33cb49e 100644 --- a/content/renderer/loader/resource_dispatcher.h +++ b/content/renderer/loader/resource_dispatcher.h
@@ -33,6 +33,7 @@ #include "third_party/blink/public/mojom/blob/blob_registry.mojom-forward.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" +#include "third_party/blink/public/platform/web_mojo_url_loader_client_observer.h" #include "third_party/blink/public/platform/web_url_loader.h" #include "third_party/blink/public/platform/web_url_request.h" #include "url/gurl.h" @@ -42,6 +43,7 @@ } namespace blink { +class WebMojoURLLoaderClient; class WebRequestPeer; class ResourceLoadInfoNotifierWrapper; class ThrottlingURLLoader; @@ -62,12 +64,12 @@ namespace content { class ResourceDispatcherDelegate; -class URLLoaderClientImpl; // This class serves as a communication interface to the ResourceDispatcherHost // in the browser process. It can be used from any child process. // Virtual methods are for tests. -class CONTENT_EXPORT ResourceDispatcher { +class CONTENT_EXPORT ResourceDispatcher + : public blink::WebMojoURLLoaderClientObserver { public: // Generates ids for requests initiated by child processes unique to the // particular process, counted up from 0 (browser initiated requests count @@ -79,7 +81,7 @@ static int MakeRequestID(); ResourceDispatcher(); - virtual ~ResourceDispatcher(); + ~ResourceDispatcher() override; // Call this method to load the resource synchronously (i.e., in one shot). // This is an alternative to the StartAsync method. Be warned that this method @@ -160,10 +162,6 @@ return weak_factory_.GetWeakPtr(); } - void OnTransferSizeUpdated(int request_id, int32_t transfer_size_diff); - - void EvictFromBackForwardCache(int request_id); - // Sets the CORS exempt header list for sanity checking. void SetCorsExemptHeaderList(const std::vector<std::string>& list); @@ -221,7 +219,7 @@ // For mojo loading. std::unique_ptr<blink::ThrottlingURLLoader> url_loader; - std::unique_ptr<URLLoaderClientImpl> url_loader_client; + std::unique_ptr<blink::WebMojoURLLoaderClient> url_loader_client; // The Client Hints headers that need to be removed from a redirect. std::vector<std::string> removed_headers; @@ -239,19 +237,28 @@ // Follows redirect, if any, for the given request. void FollowPendingRedirect(PendingRequestInfo* request_info); - // Message response handlers, called by the message handler for this process. - void OnUploadProgress(int request_id, int64_t position, int64_t size); - void OnReceivedResponse(int request_id, network::mojom::URLResponseHeadPtr); - void OnReceivedCachedMetadata(int request_id, mojo_base::BigBuffer data); + // Implements blink::WebMojoURLLoaderClientObserver. + void OnTransferSizeUpdated(int request_id, + int32_t transfer_size_diff) override; + void OnUploadProgress(int request_id, + int64_t position, + int64_t size) override; + void OnReceivedResponse(int request_id, + network::mojom::URLResponseHeadPtr) override; + void OnReceivedCachedMetadata(int request_id, + mojo_base::BigBuffer data) override; void OnReceivedRedirect( int request_id, const net::RedirectInfo& redirect_info, - network::mojom::URLResponseHeadPtr response_head, - scoped_refptr<base::SingleThreadTaskRunner> task_runner); - void OnStartLoadingResponseBody(int request_id, - mojo::ScopedDataPipeConsumerHandle body); - void OnRequestComplete(int request_id, - const network::URLLoaderCompletionStatus& status); + network::mojom::URLResponseHeadPtr head, + scoped_refptr<base::SingleThreadTaskRunner> task_runner) override; + void OnStartLoadingResponseBody( + int request_id, + mojo::ScopedDataPipeConsumerHandle body) override; + void OnRequestComplete( + int request_id, + const network::URLLoaderCompletionStatus& status) override; + void EvictFromBackForwardCache(int request_id) override; void ToLocalURLResponseHead( const PendingRequestInfo& request_info,
diff --git a/content/renderer/loader/url_loader_client_impl_unittest.cc b/content/renderer/loader/url_loader_client_impl_unittest.cc deleted file mode 100644 index c8a7e7e..0000000 --- a/content/renderer/loader/url_loader_client_impl_unittest.cc +++ /dev/null
@@ -1,737 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/loader/url_loader_client_impl.h" - -#include <vector> -#include "base/run_loop.h" -#include "base/test/scoped_feature_list.h" -#include "base/test/task_environment.h" -#include "content/renderer/loader/resource_dispatcher.h" -#include "content/renderer/loader/test_request_peer.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/redirect_info.h" -#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "services/network/public/mojom/url_response_head.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/features.h" -#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" -#include "third_party/blink/public/platform/resource_load_info_notifier_wrapper.h" -#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" - -namespace content { - -namespace { - -constexpr size_t kDataPipeCapacity = 4096; - -std::string ReadOneChunk(mojo::ScopedDataPipeConsumerHandle* handle) { - char buffer[kDataPipeCapacity]; - uint32_t read_bytes = kDataPipeCapacity; - MojoResult result = - (*handle)->ReadData(buffer, &read_bytes, MOJO_READ_DATA_FLAG_NONE); - if (result != MOJO_RESULT_OK) - return ""; - return std::string(buffer, read_bytes); -} - -std::string GetRequestPeerContextBody(TestRequestPeer::Context* context) { - if (context->body_handle) { - context->data += ReadOneChunk(&context->body_handle); - } - return context->data; -} - -} // namespace - -class URLLoaderClientImplTest : public ::testing::Test, - public network::mojom::URLLoaderFactory, - public ::testing::WithParamInterface<bool> { - protected: - URLLoaderClientImplTest() : dispatcher_(new ResourceDispatcher()) { - if (DeferWithBackForwardCacheEnabled()) { - scoped_feature_list_.InitAndEnableFeature( - blink::features::kLoadingTasksUnfreezable); - } - auto request = std::make_unique<network::ResourceRequest>(); - request_id_ = dispatcher_->StartAsync( - std::move(request), 0 /* loader_option */, - blink::scheduler::GetSingleThreadTaskRunnerForTesting(), - TRAFFIC_ANNOTATION_FOR_TESTS, false, - std::make_unique<TestRequestPeer>(dispatcher_.get(), - &request_peer_context_), - base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(this), - std::vector<std::unique_ptr<blink::URLLoaderThrottle>>(), - std::make_unique<blink::ResourceLoadInfoNotifierWrapper>( - /*resource_load_info_notifier=*/nullptr)); - request_peer_context_.request_id = request_id_; - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(url_loader_client_); - } - - bool DeferWithBackForwardCacheEnabled() { return GetParam(); } - - void TearDown() override { url_loader_client_.reset(); } - - void CreateLoaderAndStart( - mojo::PendingReceiver<network::mojom::URLLoader> receiver, - int32_t routing_id, - int32_t request_id, - uint32_t options, - const network::ResourceRequest& url_request, - mojo::PendingRemote<network::mojom::URLLoaderClient> client, - const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) - override { - url_loader_client_.Bind(std::move(client)); - } - - void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) - override { - NOTREACHED(); - } - - static MojoCreateDataPipeOptions DataPipeOptions() { - MojoCreateDataPipeOptions options; - options.struct_size = sizeof(MojoCreateDataPipeOptions); - options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; - options.element_num_bytes = 1; - options.capacity_num_bytes = kDataPipeCapacity; - return options; - } - - base::test::SingleThreadTaskEnvironment task_environment_; - base::test::ScopedFeatureList scoped_feature_list_; - std::unique_ptr<ResourceDispatcher> dispatcher_; - TestRequestPeer::Context request_peer_context_; - int request_id_ = 0; - mojo::Remote<network::mojom::URLLoaderClient> url_loader_client_; -}; - -TEST_P(URLLoaderClientImplTest, OnReceiveResponse) { - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - - EXPECT_FALSE(request_peer_context_.received_response); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); -} - -TEST_P(URLLoaderClientImplTest, ResponseBody) { - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - - EXPECT_FALSE(request_peer_context_.received_response); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - - mojo::DataPipe data_pipe(DataPipeOptions()); - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - uint32_t size = 5; - MojoResult result = data_pipe.producer_handle->WriteData( - "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); - ASSERT_EQ(MOJO_RESULT_OK, result); - EXPECT_EQ(5u, size); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, OnReceiveRedirect) { - net::RedirectInfo redirect_info; - - url_loader_client_->OnReceiveRedirect(redirect_info, - network::mojom::URLResponseHead::New()); - - EXPECT_EQ(0, request_peer_context_.seen_redirects); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, request_peer_context_.seen_redirects); -} - -TEST_P(URLLoaderClientImplTest, OnReceiveCachedMetadata) { - std::vector<uint8_t> data; - data.push_back('a'); - mojo_base::BigBuffer metadata(data); - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - url_loader_client_->OnReceiveCachedMetadata(std::move(metadata)); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_EQ(0u, request_peer_context_.cached_metadata.size()); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - ASSERT_EQ(1u, request_peer_context_.cached_metadata.size()); - EXPECT_EQ('a', request_peer_context_.cached_metadata.data()[0]); -} - -TEST_P(URLLoaderClientImplTest, OnTransferSizeUpdated) { - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - url_loader_client_->OnTransferSizeUpdated(4); - url_loader_client_->OnTransferSizeUpdated(4); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_EQ(8, request_peer_context_.total_encoded_data_length); -} - -TEST_P(URLLoaderClientImplTest, OnCompleteWithResponseBody) { - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - uint32_t size = 5; - MojoResult result = data_pipe.producer_handle->WriteData( - "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); - ASSERT_EQ(MOJO_RESULT_OK, result); - EXPECT_EQ(5u, size); - data_pipe.producer_handle.reset(); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.complete); - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_TRUE(request_peer_context_.complete); -} - -// Due to the lack of ordering guarantee, it is possible that the response body -// bytes arrives after the completion message. URLLoaderClientImpl should -// restore the order. -TEST_P(URLLoaderClientImplTest, OnCompleteShouldBeTheLastMessage) { - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnComplete(status); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - - uint32_t size = 5; - MojoResult result = data_pipe.producer_handle->WriteData( - "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); - ASSERT_EQ(MOJO_RESULT_OK, result); - EXPECT_EQ(5u, size); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, CancelOnReceiveResponse) { - request_peer_context_.cancel_on_receive_response = true; - - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_FALSE(request_peer_context_.cancelled); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_TRUE(request_peer_context_.cancelled); -} - -TEST_P(URLLoaderClientImplTest, Defer) { - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe; - data_pipe.producer_handle.reset(); // Empty body. - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); -} - -TEST_P(URLLoaderClientImplTest, DeferWithResponseBody) { - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - std::string msg1 = "hello"; - uint32_t size = msg1.size(); - ASSERT_EQ(MOJO_RESULT_OK, data_pipe.producer_handle->WriteData( - msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg1.size(), size); - data_pipe.producer_handle.reset(); - - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, - DeferredAndDeferredWithBackForwardCacheTransitions) { - if (!DeferWithBackForwardCacheEnabled()) - return; - // Call OnReceiveResponse and OnStartLoadingResponseBody while - // deferred (not for back-forward cache). - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::ScopedDataPipeProducerHandle producer_handle; - mojo::ScopedDataPipeConsumerHandle consumer_handle; - ASSERT_EQ(MOJO_RESULT_OK, - mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); - url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Write data to the response body pipe. - std::string msg1 = "he"; - uint32_t size = msg1.size(); - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg1.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Defer for back-forward cache. - dispatcher_->SetDefersLoading( - request_id_, - blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); - std::string msg2 = "ll"; - size = msg2.size(); - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg2.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg2.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Defer not for back-forward cache again. - dispatcher_->SetDefersLoading( - request_id_, - blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); - std::string msg3 = "o"; - size = msg3.size(); - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg3.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg3.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Stop deferring. - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - - // Write more data to the pipe while not deferred. - std::string msg4 = "world"; - size = msg4.size(); - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg4.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg4.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("helloworld", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, - DeferredWithBackForwardCacheStoppedDeferringBeforeClosing) { - if (!DeferWithBackForwardCacheEnabled()) - return; - // Call OnReceiveResponse, OnStartLoadingResponseBody, OnComplete while - // deferred. - dispatcher_->SetDefersLoading( - request_id_, - blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::ScopedDataPipeProducerHandle producer_handle; - mojo::ScopedDataPipeConsumerHandle consumer_handle; - ASSERT_EQ(MOJO_RESULT_OK, - mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); - url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); - network::URLLoaderCompletionStatus status; - url_loader_client_->OnComplete(status); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Write data to the response body pipe, but don't close the connection yet. - std::string msg1 = "hello"; - uint32_t size = msg1.size(); - // We expect that the other end of the pipe to be ready to read the data - // immediately. - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg1.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Stop deferring. OnComplete message shouldn't be dispatched yet because - // we're still waiting for the response body pipe to be closed. - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - // When the body is buffered, we'll wait until the pipe is closed before - // sending the OnComplete message. - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - - // Write more data to the pipe while not deferred. - std::string msg2 = "world"; - size = msg2.size(); - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg2.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg2.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("helloworld", GetRequestPeerContextBody(&request_peer_context_)); - - // Close the response body pipe. - producer_handle.reset(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - EXPECT_EQ("helloworld", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, DeferBodyWithoutOnComplete) { - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - // Call OnStartLoadingResponseBody while deferred. - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - mojo::ScopedDataPipeProducerHandle producer_handle; - mojo::ScopedDataPipeConsumerHandle consumer_handle; - ASSERT_EQ(MOJO_RESULT_OK, - mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); - url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Write data to the response body pipe, but don't close the connection yet. - std::string msg1 = "hello"; - uint32_t size = msg1.size(); - // We expect that the other end of the pipe to be ready to read the data - // immediately. - ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( - msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); - EXPECT_EQ(msg1.size(), size); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Stop deferring. - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - - // Close the response body pipe. - producer_handle.reset(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); -} - -TEST_P(URLLoaderClientImplTest, DeferredWithBackForwardCacheLongResponseBody) { - if (!DeferWithBackForwardCacheEnabled()) - return; - // Call OnReceiveResponse, OnStartLoadingResponseBody, OnComplete while - // deferred. - dispatcher_->SetDefersLoading( - request_id_, - blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::ScopedDataPipeProducerHandle producer_handle; - mojo::ScopedDataPipeConsumerHandle consumer_handle; - ASSERT_EQ(MOJO_RESULT_OK, - mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); - url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); - network::URLLoaderCompletionStatus status; - url_loader_client_->OnComplete(status); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - - // Write to the response body pipe. It will take several writes. - const uint32_t body_size = 70000; - uint32_t bytes_remaining = body_size; - std::string body(body_size, '*'); - while (bytes_remaining > 0) { - uint32_t start_position = body_size - bytes_remaining; - uint32_t bytes_sent = bytes_remaining; - MojoResult result = producer_handle->WriteData( - body.c_str() + start_position, &bytes_sent, MOJO_WRITE_DATA_FLAG_NONE); - if (result == MOJO_RESULT_SHOULD_WAIT) { - // When we buffer the body the pipe gets drained asynchronously, so it's - // possible to keep writing to the pipe if we wait. - base::RunLoop().RunUntilIdle(); - continue; - } - EXPECT_EQ(MOJO_RESULT_OK, result); - EXPECT_GE(bytes_remaining, bytes_sent); - bytes_remaining -= bytes_sent; - } - // Ensure we've written all that we can write. When buffering is disabled, we - // can only write |body_size| - |bytes_remaining| bytes. - const uint32_t bytes_written = body_size - bytes_remaining; - EXPECT_EQ(body_size, bytes_written); - producer_handle.reset(); - - // Stop deferring. - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - // When the body is buffered, BodyBuffer shouldn't be finished writing to the - // new response body pipe at this point (because nobody is reading it). - EXPECT_FALSE(request_peer_context_.complete); - - // Calling GetRequestPeerContextBody to read data from the new response body - // pipe will make BodyBuffer write the rest of the body to the pipe. - uint32_t bytes_read = 0; - while (bytes_read < bytes_written) { - bytes_read = GetRequestPeerContextBody(&request_peer_context_).size(); - base::RunLoop().RunUntilIdle(); - } - // Ensure that we've read everything we've written. - EXPECT_EQ(bytes_written, bytes_read); - EXPECT_EQ(body, GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_TRUE(request_peer_context_.complete); -} - -// As "transfer size update" message is handled specially in the implementation, -// we have a separate test. -TEST_P(URLLoaderClientImplTest, DeferWithTransferSizeUpdated) { - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - uint32_t size = 5; - MojoResult result = data_pipe.producer_handle->WriteData( - "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); - ASSERT_EQ(MOJO_RESULT_OK, result); - EXPECT_EQ(5u, size); - data_pipe.producer_handle.reset(); - - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnTransferSizeUpdated(4); - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); -} - -TEST_P(URLLoaderClientImplTest, SetDeferredDuringFlushingDeferredMessage) { - request_peer_context_.defer_on_redirect = true; - - net::RedirectInfo redirect_info; - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveRedirect(redirect_info, - network::mojom::URLResponseHead::New()); - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe(DataPipeOptions()); - uint32_t size = 5; - MojoResult result = data_pipe.producer_handle->WriteData( - "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); - ASSERT_EQ(MOJO_RESULT_OK, result); - EXPECT_EQ(5u, size); - data_pipe.producer_handle.reset(); - - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - url_loader_client_->OnTransferSizeUpdated(4); - url_loader_client_->OnComplete(status); - - EXPECT_EQ(0, request_peer_context_.seen_redirects); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(0, request_peer_context_.seen_redirects); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - EXPECT_EQ(0, request_peer_context_.seen_redirects); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, request_peer_context_.seen_redirects); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ("", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - EXPECT_FALSE(request_peer_context_.cancelled); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, request_peer_context_.seen_redirects); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - EXPECT_EQ("hello", GetRequestPeerContextBody(&request_peer_context_)); - EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); - EXPECT_FALSE(request_peer_context_.cancelled); -} - -TEST_P(URLLoaderClientImplTest, - SetDeferredDuringFlushingDeferredMessageOnTransferSizeUpdated) { - request_peer_context_.defer_on_transfer_size_updated = true; - - network::URLLoaderCompletionStatus status; - - url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); - mojo::DataPipe data_pipe; - data_pipe.producer_handle.reset(); // Empty body. - url_loader_client_->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - - url_loader_client_->OnTransferSizeUpdated(4); - url_loader_client_->OnComplete(status); - - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kDeferred); - - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - EXPECT_FALSE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); - - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_FALSE(request_peer_context_.complete); - EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); - EXPECT_FALSE(request_peer_context_.cancelled); - - dispatcher_->SetDefersLoading(request_id_, - blink::WebURLLoader::DeferType::kNotDeferred); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(request_peer_context_.received_response); - EXPECT_TRUE(request_peer_context_.complete); - EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); - EXPECT_FALSE(request_peer_context_.cancelled); -} - -INSTANTIATE_TEST_SUITE_P(All, URLLoaderClientImplTest, ::testing::Bool()); - -} // namespace content
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index 14eadece..267e292 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -613,10 +613,6 @@ request->corb_detachable = true; } - if (resource_type == blink::mojom::ResourceType::kPluginResource) { - request->corb_excluded = true; - } - auto throttles = url_request_extra_data->TakeURLLoaderThrottles().ReleaseVector(); // The frame request blocker is only for a frame's subresources.
diff --git a/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc b/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc index 7b290bef..b98b9cb 100644 --- a/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc +++ b/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc
@@ -155,6 +155,10 @@ render_frame->CreatePlugin(GetPluginInfo().ToWebPluginInfo(), params); return *plugin; } + + bool IsOriginIsolatedPepperPlugin(const base::FilePath& ignored) override { + return false; + } }; PP_Module pp_module_;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index be4c68f5..ca84ee3 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -2648,6 +2648,11 @@ save_with_empty_url); } +void RenderFrameImpl::SetWantErrorMessageStackTrace() { + want_error_message_stack_trace_ = true; + v8::Isolate::GetCurrent()->SetCaptureStackTraceForUncaughtExceptions(true); +} + #if defined(OS_ANDROID) void RenderFrameImpl::ExtractSmartClipData( const gfx::Rect& rect, @@ -4021,8 +4026,13 @@ observer.DidMatchCSS(newly_matching_selectors, stopped_matching_selectors); } -bool RenderFrameImpl::ShouldReportDetailedMessageForSource( +bool RenderFrameImpl::ShouldReportDetailedMessageForSourceAndSeverity( + blink::mojom::ConsoleMessageLevel log_level, const blink::WebString& source) { + if (want_error_message_stack_trace_ && + log_level == blink::mojom::ConsoleMessageLevel::kError) { + return true; + } return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource( source.Utf16()); } @@ -4032,7 +4042,8 @@ const blink::WebString& source_name, unsigned source_line, const blink::WebString& stack_trace) { - if (ShouldReportDetailedMessageForSource(source_name)) { + if (ShouldReportDetailedMessageForSourceAndSeverity(message.level, + source_name)) { for (auto& observer : observers_) { observer.DetailedConsoleMessageAdded( message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(),
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 1a9b998..d6c5d44 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -522,6 +522,7 @@ bool wants_result, int32_t world_id, JavaScriptExecuteRequestInIsolatedWorldCallback callback) override; + void SetWantErrorMessageStackTrace() override; void SwapIn() override; // mojom::MhtmlFileWriter implementation: @@ -587,7 +588,8 @@ const blink::WebVector<blink::WebString>& newly_matching_selectors, const blink::WebVector<blink::WebString>& stopped_matching_selectors) override; - bool ShouldReportDetailedMessageForSource( + bool ShouldReportDetailedMessageForSourceAndSeverity( + blink::mojom::ConsoleMessageLevel log_level, const blink::WebString& source) override; void DidAddMessageToConsole(const blink::WebConsoleMessage& message, const blink::WebString& source_name, @@ -1436,6 +1438,10 @@ // sent back from the renderer in the control calls. base::UnguessableToken devtools_frame_token_; + // True if the frame host wants stack traces on JavaScript console messages of + // kError severity. + bool want_error_message_stack_trace_ = false; + // Contains a representation of the accessibility tree stored in content for // use inside of Blink. std::unique_ptr<blink::WebComputedAXTree> computed_ax_tree_;
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 1fa8724..8a1a231 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -38,6 +38,7 @@ #include "content/public/common/content_switches.h" #include "content/public/common/gpu_stream_constants.h" #include "content/public/common/service_names.mojom.h" +#include "content/public/common/url_utils.h" #include "content/public/common/webplugininfo.h" #include "content/public/renderer/content_renderer_client.h" #include "content/public/renderer/render_frame.h" @@ -345,6 +346,13 @@ report_security_info, request_id); } +bool RendererBlinkPlatformImpl::IsRedirectSafe(const GURL& from_url, + const GURL& to_url) { + return IsSafeRedirectTarget(from_url, to_url) && + (!GetContentClient()->renderer() || // null in unit tests. + GetContentClient()->renderer()->IsSafeRedirectTarget(to_url)); +} + void RendererBlinkPlatformImpl::CacheMetadataInCacheStorage( const blink::WebURL& url, base::Time response_time,
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 0bbe077c..9d4f2a7 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -100,6 +100,7 @@ blink::WebURLResponse* response, bool report_security_info, int request_id) override; + bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) override; blink::WebString DefaultLocale() override; void SuddenTerminationChanged(bool enabled) override; blink::WebString DatabaseCreateOriginIdentifier(
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index bf098db..8736cbf 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1801,6 +1801,7 @@ "../browser/file_system/browser_file_system_helper_unittest.cc", "../browser/file_system/file_system_operation_runner_unittest.cc", "../browser/file_system_access/file_system_chooser_unittest.cc", + "../browser/file_system_access/native_file_system_directory_handle_impl_unittest.cc", "../browser/file_system_access/native_file_system_file_handle_impl_unittest.cc", "../browser/file_system_access/native_file_system_file_writer_impl_unittest.cc", "../browser/file_system_access/native_file_system_handle_base_unittest.cc", @@ -2066,7 +2067,6 @@ "../common/input/touch_event_stream_validator_unittest.cc", "../common/inter_process_time_ticks_converter_unittest.cc", "../common/net/ip_address_space_util_unittest.cc", - "../common/service_manager/service_manager_connection_impl_unittest.cc", "../common/service_worker/service_worker_utils_unittest.cc", "../common/state_transitions_unittest.cc", "../common/user_agent_unittest.cc", @@ -2092,7 +2092,6 @@ "../renderer/loader/sync_load_context_unittest.cc", "../renderer/loader/test_request_peer.cc", "../renderer/loader/test_request_peer.h", - "../renderer/loader/url_loader_client_impl_unittest.cc", "../renderer/loader/web_url_loader_impl_unittest.cc", "../renderer/media/batching_media_log_unittest.cc", "../renderer/media/inspector_media_event_handler_unittest.cc",
diff --git a/content/web_test/renderer/web_ax_object_proxy.cc b/content/web_test/renderer/web_ax_object_proxy.cc index 62fcf80..a7d269cf 100644 --- a/content/web_test/renderer/web_ax_object_proxy.cc +++ b/content/web_test/renderer/web_ax_object_proxy.cc
@@ -273,29 +273,6 @@ DISALLOW_COPY_AND_ASSIGN(AttributesCollector); }; -class SparseAttributeAdapter : public blink::WebAXSparseAttributeClient { - public: - SparseAttributeAdapter() {} - ~SparseAttributeAdapter() override {} - - std::map<blink::WebAXObjectAttribute, blink::WebAXObject> object_attributes; - std::map<blink::WebAXObjectVectorAttribute, - blink::WebVector<blink::WebAXObject>> - object_vector_attributes; - - private: - void AddObjectAttribute(blink::WebAXObjectAttribute attribute, - const blink::WebAXObject& value) override { - object_attributes[attribute] = value; - } - - void AddObjectVectorAttribute( - blink::WebAXObjectVectorAttribute attribute, - const blink::WebVector<blink::WebAXObject>& value) override { - object_vector_attributes[attribute] = value; - } -}; - } // namespace gin::WrapperInfo WebAXObjectProxy::kWrapperInfo = {gin::kEmbedderNativeGin}; @@ -1169,67 +1146,76 @@ v8::Local<v8::Object> WebAXObjectProxy::AriaActiveDescendantElement() { UpdateLayout(); - SparseAttributeAdapter attribute_adapter; - accessibility_object_.GetSparseAXAttributes(attribute_adapter); - blink::WebAXObject element = - attribute_adapter.object_attributes - [blink::WebAXObjectAttribute::kAriaActiveDescendant]; - return factory_->GetOrCreate(element); + int ax_id = GetAXNodeData().GetIntAttribute( + ax::mojom::IntAttribute::kActivedescendantId); + + if (!ax_id) + return v8::Local<v8::Object>(); + + blink::WebAXObject web_ax_object = blink::WebAXObject::FromWebDocumentByID( + accessibility_object_.GetDocument(), ax_id); + return factory_->GetOrCreate(web_ax_object); } v8::Local<v8::Object> WebAXObjectProxy::AriaControlsElementAtIndex( unsigned index) { UpdateLayout(); - SparseAttributeAdapter attribute_adapter; - accessibility_object_.GetSparseAXAttributes(attribute_adapter); - blink::WebVector<blink::WebAXObject> elements = - attribute_adapter.object_vector_attributes - [blink::WebAXObjectVectorAttribute::kAriaControls]; - size_t element_count = elements.size(); + auto ax_ids = GetAXNodeData().GetIntListAttribute( + ax::mojom::IntListAttribute::kControlsIds); + size_t element_count = ax_ids.size(); + if (index >= element_count) return v8::Local<v8::Object>(); - return factory_->GetOrCreate(elements[index]); + blink::WebAXObject web_ax_object = blink::WebAXObject::FromWebDocumentByID( + accessibility_object_.GetDocument(), ax_ids[index]); + + return factory_->GetOrCreate(web_ax_object); } v8::Local<v8::Object> WebAXObjectProxy::AriaDetailsElementAtIndex( unsigned index) { UpdateLayout(); - SparseAttributeAdapter attribute_adapter; - accessibility_object_.GetSparseAXAttributes(attribute_adapter); - blink::WebVector<blink::WebAXObject> elements = - attribute_adapter.object_vector_attributes - [blink::WebAXObjectVectorAttribute::kAriaDetails]; - size_t element_count = elements.size(); + auto ax_ids = GetAXNodeData().GetIntListAttribute( + ax::mojom::IntListAttribute::kDetailsIds); + size_t element_count = ax_ids.size(); + if (index >= element_count) return v8::Local<v8::Object>(); - return factory_->GetOrCreate(elements[index]); + blink::WebAXObject web_ax_object = blink::WebAXObject::FromWebDocumentByID( + accessibility_object_.GetDocument(), ax_ids[index]); + + return factory_->GetOrCreate(web_ax_object); } v8::Local<v8::Object> WebAXObjectProxy::AriaErrorMessageElement() { UpdateLayout(); - SparseAttributeAdapter attribute_adapter; - accessibility_object_.GetSparseAXAttributes(attribute_adapter); - blink::WebAXObject element = - attribute_adapter - .object_attributes[blink::WebAXObjectAttribute::kAriaErrorMessage]; - return factory_->GetOrCreate(element); + int ax_id = + GetAXNodeData().GetIntAttribute(ax::mojom::IntAttribute::kErrormessageId); + + if (!ax_id) + return v8::Local<v8::Object>(); + + blink::WebAXObject web_ax_object = blink::WebAXObject::FromWebDocumentByID( + accessibility_object_.GetDocument(), ax_id); + return factory_->GetOrCreate(web_ax_object); } v8::Local<v8::Object> WebAXObjectProxy::AriaFlowToElementAtIndex( unsigned index) { UpdateLayout(); - SparseAttributeAdapter attribute_adapter; - accessibility_object_.GetSparseAXAttributes(attribute_adapter); - blink::WebVector<blink::WebAXObject> elements = - attribute_adapter.object_vector_attributes - [blink::WebAXObjectVectorAttribute::kAriaFlowTo]; - size_t element_count = elements.size(); + auto ax_ids = GetAXNodeData().GetIntListAttribute( + ax::mojom::IntListAttribute::kFlowtoIds); + size_t element_count = ax_ids.size(); + if (index >= element_count) return v8::Local<v8::Object>(); - return factory_->GetOrCreate(elements[index]); + blink::WebAXObject web_ax_object = blink::WebAXObject::FromWebDocumentByID( + accessibility_object_.GetDocument(), ax_ids[index]); + + return factory_->GetOrCreate(web_ax_object); } v8::Local<v8::Object> WebAXObjectProxy::AriaOwnsElementAtIndex(unsigned index) {
diff --git a/device/bluetooth/bluetooth_device.cc b/device/bluetooth/bluetooth_device.cc index cb2f951e..21d7c38 100644 --- a/device/bluetooth/bluetooth_device.cc +++ b/device/bluetooth/bluetooth_device.cc
@@ -62,6 +62,15 @@ UpdateDeviceUUIDs(); } +void BluetoothDevice::DeviceUUIDs::ReplaceServiceUUIDs( + UUIDList new_service_uuids) { + service_uuids_.clear(); + for (auto& it : new_service_uuids) { + service_uuids_.insert(std::move(it)); + } + UpdateDeviceUUIDs(); +} + void BluetoothDevice::DeviceUUIDs::ClearServiceUUIDs() { service_uuids_.clear(); UpdateDeviceUUIDs();
diff --git a/device/bluetooth/bluetooth_device.h b/device/bluetooth/bluetooth_device.h index 9166b61..ff7ca02 100644 --- a/device/bluetooth/bluetooth_device.h +++ b/device/bluetooth/bluetooth_device.h
@@ -672,6 +672,8 @@ void ReplaceServiceUUIDs( const BluetoothDevice::GattServiceMap& gatt_services); + void ReplaceServiceUUIDs(UUIDList new_service_uuids); + void ClearServiceUUIDs(); // Returns the union of Advertised UUIDs and Service UUIDs.
diff --git a/device/bluetooth/bluez/bluetooth_adapter_bluez.cc b/device/bluetooth/bluez/bluetooth_adapter_bluez.cc index 73c29914..1cee8010 100644 --- a/device/bluetooth/bluez/bluetooth_adapter_bluez.cc +++ b/device/bluetooth/bluez/bluetooth_adapter_bluez.cc
@@ -775,6 +775,8 @@ device_bluez->UpdateManufacturerData(); else if (property_name == properties->advertising_data_flags.name()) device_bluez->UpdateAdvertisingDataFlags(); + else if (property_name == properties->uuids.name()) + device_bluez->UpdateServiceUUIDs(); if (property_name == properties->bluetooth_class.name() || property_name == properties->appearance.name() || @@ -1274,18 +1276,20 @@ base::BindOnce(&BluetoothAdapterBlueZ::OnAdvertisementReceived, weak_ptr_factory_.GetWeakPtr(), device->GetAddress(), device->GetName() ? *(device->GetName()) : std::string(), - rssi, device->GetAppearance()); + rssi, device->GetAppearance(), device->object_path()); ble_scan_parser_->Parse(eir, std::move(callback)); } #endif // BUILDFLAG(IS_ASH) } #if BUILDFLAG(IS_ASH) -void BluetoothAdapterBlueZ::OnAdvertisementReceived(std::string device_address, - std::string device_name, - uint8_t rssi, - uint16_t device_appearance, - ScanRecordPtr scan_record) { +void BluetoothAdapterBlueZ::OnAdvertisementReceived( + std::string device_address, + std::string device_name, + uint8_t rssi, + uint16_t device_appearance, + const dbus::ObjectPath& device_path, + ScanRecordPtr scan_record) { // Ignore the packet if it could not be parsed successfully. if (!scan_record) return; @@ -1299,6 +1303,14 @@ scan_record->tx_power, device_appearance, scan_record->service_uuids, service_data_map, manufacturer_data_map); } + + BluetoothDeviceBlueZ* device = GetDeviceWithPath(device_path); + if (!device) { + BLUETOOTH_LOG(ERROR) << "Device " << device_path.value() << " not found!"; + return; + } + + device->SetAdvertisedUUIDs(scan_record->service_uuids); } #endif // BUILDFLAG(IS_ASH)
diff --git a/device/bluetooth/bluez/bluetooth_adapter_bluez.h b/device/bluetooth/bluez/bluetooth_adapter_bluez.h index 177fc639..3f43883 100644 --- a/device/bluetooth/bluez/bluetooth_adapter_bluez.h +++ b/device/bluetooth/bluez/bluetooth_adapter_bluez.h
@@ -198,6 +198,7 @@ std::string device_name, uint8_t rssi, uint16_t device_appearance, + const dbus::ObjectPath& device_path, ScanRecordPtr scan_record); #endif // BUILDFLAG(IS_ASH)
diff --git a/device/bluetooth/bluez/bluetooth_bluez_unittest.cc b/device/bluetooth/bluez/bluetooth_bluez_unittest.cc index 4be52c8..ea2d7ff 100644 --- a/device/bluetooth/bluez/bluetooth_bluez_unittest.cc +++ b/device/bluetooth/bluez/bluetooth_bluez_unittest.cc
@@ -36,6 +36,7 @@ #include "device/bluetooth/dbus/fake_bluetooth_input_client.h" #include "device/bluetooth/test/test_bluetooth_adapter_observer.h" #include "device/bluetooth/test/test_pairing_delegate.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -4587,4 +4588,77 @@ EXPECT_FALSE(device->battery_percentage().has_value()); } +TEST_F(BluetoothBlueZTest, DeviceUUIDsCombinedFromServiceAndAdvertisement) { + // Simulate addition and removal of service and advertisement UUIDs. + GetAdapter(); + + fake_bluetooth_device_client_->CreateDevice( + dbus::ObjectPath(bluez::FakeBluetoothAdapterClient::kAdapterPath), + dbus::ObjectPath(bluez::FakeBluetoothDeviceClient::kLowEnergyPath)); + BluetoothDevice* device = + adapter_->GetDevice(bluez::FakeBluetoothDeviceClient::kLowEnergyAddress); + ASSERT_TRUE(device); + + BluetoothDeviceBlueZ* device_bluez = + static_cast<BluetoothDeviceBlueZ*>(device); + + bluez::FakeBluetoothDeviceClient::Properties* properties = + fake_bluetooth_device_client_->GetProperties( + dbus::ObjectPath(bluez::FakeBluetoothDeviceClient::kLowEnergyPath)); + + // Have these 9 UUIDs divided into 3 groups: + // -UUIDs which is available from the start, but later is missing + // -UUIDs which is not available in the beginning, but later is added + // -UUIDs which is always available + // In each group, they are further divided into 3 groups: + // -advertisement UUIDs + // -service UUIDs (from SDP / GATT) + // -UUIDs which appear in both + BluetoothUUID uuidInitAdv = BluetoothUUID("1111"); + BluetoothUUID uuidInitServ = BluetoothUUID("2222"); + BluetoothUUID uuidInitBoth = BluetoothUUID("3333"); + BluetoothUUID uuidLaterAdv = BluetoothUUID("4444"); + BluetoothUUID uuidLaterServ = BluetoothUUID("5555"); + BluetoothUUID uuidLaterBoth = BluetoothUUID("6666"); + BluetoothUUID uuidAlwaysAdv = BluetoothUUID("7777"); + BluetoothUUID uuidAlwaysServ = BluetoothUUID("8888"); + BluetoothUUID uuidAlwaysBoth = BluetoothUUID("9999"); + + BluetoothAdapter::UUIDList uuidsInitAdv{uuidInitAdv, uuidInitBoth, + uuidAlwaysAdv, uuidAlwaysBoth}; + BluetoothAdapter::UUIDList uuidsLaterAdv{uuidLaterAdv, uuidLaterBoth, + uuidAlwaysAdv, uuidAlwaysBoth}; + + std::vector<std::string> uuidsInitServ{ + uuidInitServ.canonical_value(), uuidInitBoth.canonical_value(), + uuidAlwaysServ.canonical_value(), uuidAlwaysBoth.canonical_value()}; + std::vector<std::string> uuidsLaterServ{ + uuidLaterServ.canonical_value(), uuidLaterBoth.canonical_value(), + uuidAlwaysServ.canonical_value(), uuidAlwaysBoth.canonical_value()}; + + device_bluez->SetAdvertisedUUIDs(uuidsInitAdv); + properties->uuids.ReplaceValue(uuidsInitServ); + + // The result should be the union of service and advertisement UUIDs + BluetoothDevice::UUIDSet dev_uuids = device->GetUUIDs(); + EXPECT_THAT(dev_uuids, ::testing::ElementsAre( + uuidInitAdv, uuidInitServ, uuidInitBoth, + uuidAlwaysAdv, uuidAlwaysServ, uuidAlwaysBoth)); + + // advertisement UUIDs updated + device_bluez->SetAdvertisedUUIDs(uuidsLaterAdv); + dev_uuids = device->GetUUIDs(); + EXPECT_THAT(dev_uuids, + ::testing::ElementsAre(uuidInitServ, uuidInitBoth, uuidLaterAdv, + uuidLaterBoth, uuidAlwaysAdv, + uuidAlwaysServ, uuidAlwaysBoth)); + + // service UUIDs updated + properties->uuids.ReplaceValue(uuidsLaterServ); + dev_uuids = device->GetUUIDs(); + EXPECT_THAT(dev_uuids, ::testing::ElementsAre( + uuidLaterAdv, uuidLaterServ, uuidLaterBoth, + uuidAlwaysAdv, uuidAlwaysServ, uuidAlwaysBoth)); +} + } // namespace bluez
diff --git a/device/bluetooth/bluez/bluetooth_device_bluez.cc b/device/bluetooth/bluez/bluetooth_device_bluez.cc index 709cf2a..b602946e 100644 --- a/device/bluetooth/bluez/bluetooth_device_bluez.cc +++ b/device/bluetooth/bluez/bluetooth_device_bluez.cc
@@ -153,6 +153,7 @@ UpdateServiceData(); UpdateManufacturerData(); UpdateAdvertisingDataFlags(); + UpdateServiceUUIDs(); } BluetoothDeviceBlueZ::~BluetoothDeviceBlueZ() { @@ -382,19 +383,7 @@ } BluetoothDevice::UUIDSet BluetoothDeviceBlueZ::GetUUIDs() const { - bluez::BluetoothDeviceClient::Properties* properties = - bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->GetProperties( - object_path_); - DCHECK(properties); - - UUIDSet uuids; - const std::vector<std::string>& dbus_uuids = properties->uuids.value(); - for (const std::string& dbus_uuid : dbus_uuids) { - device::BluetoothUUID uuid(dbus_uuid); - DCHECK(uuid.IsValid()); - uuids.insert(std::move(uuid)); - } - return uuids; + return device_uuids_.GetUUIDs(); } base::Optional<int8_t> BluetoothDeviceBlueZ::GetInquiryRSSI() const { @@ -750,6 +739,28 @@ advertising_data_flags_ = properties->advertising_data_flags.value()[0]; } +void BluetoothDeviceBlueZ::UpdateServiceUUIDs() { + bluez::BluetoothDeviceClient::Properties* properties = + bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->GetProperties( + object_path_); + if (!properties) + return; + + UUIDList uuids; + for (const std::string& dbus_uuid : properties->uuids.value()) { + device::BluetoothUUID uuid(dbus_uuid); + DCHECK(uuid.IsValid()); + uuids.push_back(std::move(uuid)); + } + + device_uuids_.ReplaceServiceUUIDs(uuids); +} + +void BluetoothDeviceBlueZ::SetAdvertisedUUIDs( + const BluetoothDevice::UUIDList& uuids) { + device_uuids_.ReplaceAdvertisedUUIDs(uuids); +} + BluetoothPairingBlueZ* BluetoothDeviceBlueZ::BeginPairing( BluetoothDevice::PairingDelegate* pairing_delegate) { pairing_.reset(new BluetoothPairingBlueZ(this, pairing_delegate));
diff --git a/device/bluetooth/bluez/bluetooth_device_bluez.h b/device/bluetooth/bluez/bluetooth_device_bluez.h index 68ad4e3..7be1e822 100644 --- a/device/bluetooth/bluez/bluetooth_device_bluez.h +++ b/device/bluetooth/bluez/bluetooth_device_bluez.h
@@ -144,6 +144,21 @@ // from UpdateServiceData() also applies here. void UpdateAdvertisingDataFlags(); + // Called by BluetoothAdapterBlueZ to update device_uuids_ defined in + // BluetoothDevice when receiving DevicePropertyChanged event for the UUIDs + // property. Note that BlueZ's implementation returns service UUIDs (SDP or + // GATT) when they are available, otherwise it contains the EIR or + // advertisement UUIDs. However, currently there is no way of knowing which + // one we will get. Since the advertised UUIDs can be tracked while we receive + // advertisement packets, here we assume it contains the service UUIDs. Both + // are merged behind the scenes, so GetUUIDs() would return the expected + // result. + void UpdateServiceUUIDs(); + + // Called by BluetoothAdapterBlueZ to update device_uuids_ defined in + // BluetoothDevice when receiving advertisement data. + void SetAdvertisedUUIDs(const BluetoothDevice::UUIDList& uuids); + // Creates a pairing object with the given delegate |pairing_delegate| and // establishes it as the pairing context for this device. All pairing-related // method calls will be forwarded to this object until it is released.
diff --git a/extensions/BUILD.gn b/extensions/BUILD.gn index 5bd3560..2081698 100644 --- a/extensions/BUILD.gn +++ b/extensions/BUILD.gn
@@ -159,6 +159,7 @@ "//extensions/common/api", "//extensions/common/api:extensions_features", "//net:test_support", + "//services/network/public/mojom", "//testing/gmock", "//testing/gtest", "//third_party/cld_3/src/src:cld_3",
diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index a2836e3..7f93bfed 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn
@@ -414,6 +414,7 @@ "//ppapi/buildflags", "//services/device/public/mojom", "//services/metrics/public/cpp:metrics_cpp", + "//services/network/public/mojom", "//services/preferences/public/cpp", "//services/service_manager/public/cpp", "//skia",
diff --git a/extensions/browser/api/virtual_keyboard/DIR_METADATA b/extensions/browser/api/virtual_keyboard/DIR_METADATA index f33c0cee..c860705 100644 --- a/extensions/browser/api/virtual_keyboard/DIR_METADATA +++ b/extensions/browser/api/virtual_keyboard/DIR_METADATA
@@ -7,5 +7,6 @@ # https://source.chromium.org/chromium/infra/infra/+/master:go/src/infra/tools/dirmd/proto/dir_metadata.proto monorail { - component: "UI>Input>VirtualKeyboard" -} \ No newline at end of file + component: "OS>Inputs" # for Chrome/Chromium OS only. + # For OSes other than Chrome/Chromium OS, please use "UI>Input>VirtualKeyboard". +}
diff --git a/extensions/browser/api/virtual_keyboard_private/DIR_METADATA b/extensions/browser/api/virtual_keyboard_private/DIR_METADATA index f33c0cee..0296738 100644 --- a/extensions/browser/api/virtual_keyboard_private/DIR_METADATA +++ b/extensions/browser/api/virtual_keyboard_private/DIR_METADATA
@@ -7,5 +7,5 @@ # https://source.chromium.org/chromium/infra/infra/+/master:go/src/infra/tools/dirmd/proto/dir_metadata.proto monorail { - component: "UI>Input>VirtualKeyboard" -} \ No newline at end of file + component: "OS>Inputs" +}
diff --git a/extensions/browser/extension_protocols.cc b/extensions/browser/extension_protocols.cc index df71296..fe04db6a 100644 --- a/extensions/browser/extension_protocols.cc +++ b/extensions/browser/extension_protocols.cc
@@ -92,10 +92,10 @@ #include "net/http/http_response_info.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "services/network/public/cpp/url_loader_completion_status.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/loader/resource_type_util.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "url/origin.h" #include "url/url_util.h" @@ -261,7 +261,7 @@ // // Called on the UI thread. bool AllowExtensionResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito, @@ -270,7 +270,7 @@ const ExtensionSet& extensions, const ProcessMap& process_map) { const bool is_main_frame = - resource_type == blink::mojom::ResourceType::kMainFrame; + destination == network::mojom::RequestDestination::kDocument; if (is_incognito && !ExtensionCanLoadInIncognito(is_main_frame, extension, extension_enabled_in_incognito)) { @@ -301,18 +301,18 @@ // in browser process during update check when // ServiceWorkerImportedScriptUpdateCheck is enabled. if (child_id == content::ChildProcessHost::kInvalidUniqueID && - (blink::IsResourceTypeFrame(resource_type) || + (blink::IsRequestDestinationFrame(destination) || (base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker) && - resource_type == blink::mojom::ResourceType::kWorker) || - resource_type == blink::mojom::ResourceType::kSharedWorker || - resource_type == blink::mojom::ResourceType::kScript || - resource_type == blink::mojom::ResourceType::kServiceWorker)) { + destination == network::mojom::RequestDestination::kWorker) || + destination == network::mojom::RequestDestination::kSharedWorker || + destination == network::mojom::RequestDestination::kScript || + destination == network::mojom::RequestDestination::kServiceWorker)) { return true; } // Allow the extension module embedder to grant permission for loads. if (ExtensionsBrowserClient::Get()->AllowCrossRendererResourceLoad( - request, resource_type, page_transition, child_id, is_incognito, + request, destination, page_transition, child_id, is_incognito, extension, extensions, process_map)) { return true; } @@ -552,8 +552,7 @@ extensions::util::IsIncognitoEnabled(extension_id, browser_context_); if (!AllowExtensionResourceLoad( - request, - static_cast<blink::mojom::ResourceType>(request.resource_type), + request, request.destination, static_cast<ui::PageTransition>(request.transition_type), render_process_id_, browser_context_->IsOffTheRecord(), extension.get(), incognito_enabled, enabled_extensions,
diff --git a/extensions/browser/extensions_browser_client.h b/extensions/browser/extensions_browser_client.h index 7a222e3f..c2d194e 100644 --- a/extensions/browser/extensions_browser_client.h +++ b/extensions/browser/extensions_browser_client.h
@@ -22,8 +22,8 @@ #include "mojo/public/cpp/bindings/binder_map.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/public/mojom/url_loader.mojom-forward.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "ui/base/page_transition_types.h" class ExtensionFunctionRegistry; @@ -177,7 +177,7 @@ // webview and dev tools. May be called on either the UI or IO thread. virtual bool AllowCrossRendererResourceLoad( const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito,
diff --git a/extensions/browser/test_extensions_browser_client.cc b/extensions/browser/test_extensions_browser_client.cc index 7b30d1f7..e8f34046 100644 --- a/extensions/browser/test_extensions_browser_client.cc +++ b/extensions/browser/test_extensions_browser_client.cc
@@ -140,7 +140,7 @@ bool TestExtensionsBrowserClient::AllowCrossRendererResourceLoad( const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito,
diff --git a/extensions/browser/test_extensions_browser_client.h b/extensions/browser/test_extensions_browser_client.h index fa16933..968af0b 100644 --- a/extensions/browser/test_extensions_browser_client.h +++ b/extensions/browser/test_extensions_browser_client.h
@@ -20,6 +20,7 @@ #include "extensions/browser/updater/extension_cache.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" namespace extensions { class KioskDelegate; @@ -99,14 +100,15 @@ mojo::PendingRemote<network::mojom::URLLoaderClient> client, bool send_cors_header) override; - bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map) override; + bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map) override; PrefService* GetPrefServiceForContext( content::BrowserContext* context) override; void GetEarlyExtensionPrefsObservers(
diff --git a/extensions/browser/url_request_util.cc b/extensions/browser/url_request_util.cc index 698fee7..8c032be 100644 --- a/extensions/browser/url_request_util.cc +++ b/extensions/browser/url_request_util.cc
@@ -21,22 +21,23 @@ namespace extensions { namespace url_request_util { -bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map, - bool* allowed) { +bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map, + bool* allowed) { const GURL& url = request.url; base::StringPiece resource_path = url.path_piece(); // This logic is performed for main frame requests in // ExtensionNavigationThrottle::WillStartRequest. if (child_id != -1 || - resource_type != blink::mojom::ResourceType::kMainFrame) { + destination != network::mojom::RequestDestination::kDocument) { // Extensions with webview: allow loading certain resources by guest // renderers with privileged partition IDs as specified in owner's extension // the manifest file. @@ -83,7 +84,7 @@ // Navigating the main frame to an extension URL is allowed, even if not // explicitly listed as web_accessible_resource. - if (resource_type == blink::mojom::ResourceType::kMainFrame) { + if (destination == network::mojom::RequestDestination::kDocument) { *allowed = true; return true; } @@ -91,7 +92,8 @@ // When navigating in subframe, allow if it is the same origin // as the top-level frame. This can only be the case if the subframe // request is coming from the extension process. - if (resource_type == blink::mojom::ResourceType::kSubFrame && + if ((destination == network::mojom::RequestDestination::kIframe || + destination == network::mojom::RequestDestination::kFrame) && process_map.Contains(child_id)) { *allowed = true; return true;
diff --git a/extensions/browser/url_request_util.h b/extensions/browser/url_request_util.h index 006da32..7c9011a 100644 --- a/extensions/browser/url_request_util.h +++ b/extensions/browser/url_request_util.h
@@ -9,7 +9,7 @@ #include "base/optional.h" #include "base/strings/string_piece.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" +#include "services/network/public/mojom/fetch_api.mojom.h" #include "ui/base/page_transition_types.h" namespace network { @@ -28,15 +28,16 @@ // Sets allowed=true to allow a chrome-extension:// resource request coming from // renderer A to access a resource in an extension running in renderer B. // Returns false when it couldn't determine if the resource is allowed or not -bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map, - bool* allowed); +bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map, + bool* allowed); // Helper method that is called by both AllowCrossRendererResourceLoad and // ExtensionNavigationThrottle to share logic.
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.cc index f74b02a..ea65234 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.cc
@@ -15,20 +15,19 @@ WiFiDisplayAudioEncoder::~WiFiDisplayAudioEncoder() = default; -void WiFiDisplayAudioEncoder::Create( - const wds::AudioCodec& audio_codec, - const AudioEncoderCallback& encoder_callback) { +void WiFiDisplayAudioEncoder::Create(const wds::AudioCodec& audio_codec, + AudioEncoderCallback encoder_callback) { // Create a format specific encoder. switch (audio_codec.format) { case wds::LPCM: - CreateLPCM(audio_codec, encoder_callback); + CreateLPCM(audio_codec, std::move(encoder_callback)); return; default: break; } // Report failure. - encoder_callback.Run(nullptr); + std::move(encoder_callback).Run(nullptr); } size_t WiFiDisplayAudioEncoder::GetAudioCodecMode() const {
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.h b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.h index b2dfc951..73d7d5f 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.h +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.h
@@ -18,10 +18,10 @@ public blink::WebMediaStreamAudioSink { public: using AudioEncoderCallback = - base::Callback<void(scoped_refptr<WiFiDisplayAudioEncoder>)>; + base::OnceCallback<void(scoped_refptr<WiFiDisplayAudioEncoder>)>; static void Create(const wds::AudioCodec& audio_codec, - const AudioEncoderCallback& encoder_callback); + AudioEncoderCallback encoder_callback); protected: static const size_t kInvalidCodecModeValue = ~static_cast<size_t>(0u); @@ -29,7 +29,7 @@ // A factory method that creates a new encoder instance for Linear Pulse-Code // Modulation (LPCM) audio encoding. static void CreateLPCM(const wds::AudioCodec& audio_codec, - const AudioEncoderCallback& encoder_callback); + AudioEncoderCallback encoder_callback); explicit WiFiDisplayAudioEncoder(const wds::AudioCodec& audio_codec); ~WiFiDisplayAudioEncoder() override;
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder_lpcm.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder_lpcm.cc index b07bb3b..4ad1614 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder_lpcm.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder_lpcm.cc
@@ -226,9 +226,9 @@ void WiFiDisplayAudioEncoder::CreateLPCM( const wds::AudioCodec& audio_codec, - const AudioEncoderCallback& encoder_callback) { - encoder_callback.Run( - base::MakeRefCounted<WiFiDisplayAudioEncoderLPCM>(audio_codec)); + AudioEncoderCallback encoder_callback) { + std::move(encoder_callback) + .Run(base::MakeRefCounted<WiFiDisplayAudioEncoderLPCM>(audio_codec)); } } // namespace extensions
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.cc index 3be6bffa..9f56357 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.cc
@@ -30,15 +30,14 @@ WiFiDisplayMediaEncoder::WiFiDisplayMediaEncoder() = default; WiFiDisplayMediaEncoder::~WiFiDisplayMediaEncoder() = default; -void WiFiDisplayMediaEncoder::SetCallbacks( - const EncodedUnitCallback& encoded_callback, - const base::Closure& error_callback) { +void WiFiDisplayMediaEncoder::SetCallbacks(EncodedUnitCallback encoded_callback, + base::OnceClosure error_callback) { DCHECK(client_thread_checker_.CalledOnValidThread()); // This is not thread-safe if encoding has been started thus allow // this to be called only once. - DCHECK(encoded_callback_.is_null() && error_callback_.is_null()); - encoded_callback_ = media::BindToCurrentLoop(encoded_callback); - error_callback_ = media::BindToCurrentLoop(error_callback); + DCHECK(!encoded_callback_ && !error_callback_); + encoded_callback_ = media::BindToCurrentLoop(std::move(encoded_callback)); + error_callback_ = media::BindToCurrentLoop(std::move(error_callback)); } } // namespace extensions
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.h b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.h index b9194e8..8994a777 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.h +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_encoder.h
@@ -49,7 +49,7 @@ : public base::RefCountedThreadSafe<WiFiDisplayMediaEncoder> { public: using EncodedUnitCallback = - base::Callback<void(std::unique_ptr<WiFiDisplayEncodedUnit>)>; + base::OnceCallback<void(std::unique_ptr<WiFiDisplayEncodedUnit>)>; // Creates an elementary stream info describing the stream of encoded units // which this encoder generates and passes to a callback set using @@ -61,8 +61,8 @@ // Sets callbacks for the obtained encoder instance: // |encoded_callback| is invoked to return the next encoded unit // |error_callback| is invoked to report a fatal encoder error - void SetCallbacks(const EncodedUnitCallback& encoded_callback, - const base::Closure& error_callback); + void SetCallbacks(EncodedUnitCallback encoded_callback, + base::OnceClosure error_callback); protected: friend class base::RefCountedThreadSafe<WiFiDisplayMediaEncoder>; @@ -72,7 +72,7 @@ base::ThreadChecker client_thread_checker_; EncodedUnitCallback encoded_callback_; - base::Closure error_callback_; + base::OnceClosure error_callback_; }; } // namespace extensions
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.cc index 0fe8172..7e36883 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.cc
@@ -113,17 +113,17 @@ void WiFiDisplayMediaManager::Play() { is_playing_ = true; if (!player_) { - auto service_callback = base::Bind( - &WiFiDisplayMediaManager::RegisterMediaService, - base::Unretained(this), + auto service_callback = base::BindOnce( + &WiFiDisplayMediaManager::RegisterMediaService, base::Unretained(this), base::ThreadTaskRunnerHandle::Get()); base::PostTaskAndReplyWithResult( io_task_runner_.get(), FROM_HERE, - base::BindOnce(&WiFiDisplayMediaPipeline::Create, GetSessionType(), - video_encoder_parameters_, optimal_audio_codec_, - sink_ip_address_, sink_rtp_ports_, - service_callback, // To be invoked on IO thread. - media::BindToCurrentLoop(error_callback_)), + base::BindOnce( + &WiFiDisplayMediaPipeline::Create, GetSessionType(), + video_encoder_parameters_, optimal_audio_codec_, sink_ip_address_, + sink_rtp_ports_, + std::move(service_callback), // To be invoked on IO thread. + media::BindToCurrentLoop(error_callback_)), base::BindOnce(&WiFiDisplayMediaManager::OnPlayerCreated, weak_factory_.GetWeakPtr())); return; @@ -141,9 +141,9 @@ if (!video_track_.isNull()) { // To be called on IO thread. - auto on_raw_video_frame = base::Bind( - &WiFiDisplayMediaPipeline::InsertRawVideoFrame, - base::Unretained(player_)); + auto on_raw_video_frame = + base::BindRepeating(&WiFiDisplayMediaPipeline::InsertRawVideoFrame, + base::Unretained(player_)); video_sink_.reset( new WiFiDisplayVideoSink(video_track_, on_raw_video_frame)); video_sink_->Start(); @@ -397,10 +397,9 @@ video_encoder_parameters_.profile = optimal_video_format_.profile; video_encoder_parameters_.level = optimal_video_format_.level; video_encoder_parameters_.create_memory_callback = - media::BindToCurrentLoop(base::Bind(&CreateVideoEncodeMemory)); - video_encoder_parameters_.vea_create_callback = - media::BindToCurrentLoop( - base::Bind(&content::CreateVideoEncodeAccelerator)); + media::BindToCurrentLoop(base::BindRepeating(&CreateVideoEncodeMemory)); + video_encoder_parameters_.vea_create_callback = media::BindToCurrentLoop( + base::BindRepeating(&content::CreateVideoEncodeAccelerator)); return true; } @@ -448,9 +447,9 @@ DCHECK(content::RenderThread::Get()); player_ = player.release(); - auto completion_callback = base::Bind( - &WiFiDisplayMediaManager::OnMediaPipelineInitialized, - weak_factory_.GetWeakPtr()); + auto completion_callback = + base::BindOnce(&WiFiDisplayMediaManager::OnMediaPipelineInitialized, + weak_factory_.GetWeakPtr()); io_task_runner_->PostTask( FROM_HERE, base::BindOnce(&WiFiDisplayMediaPipeline::Initialize, @@ -475,10 +474,10 @@ void WiFiDisplayMediaManager::RegisterMediaService( const scoped_refptr<base::SingleThreadTaskRunner>& main_runner, mojo::PendingReceiver<mojom::WiFiDisplayMediaService> receiver, - const base::Closure& on_completed) { + const base::OnceClosure& on_completed) { auto connect_service_callback = - base::Bind(&WiFiDisplayMediaManager::ConnectToRemoteService, - base::Unretained(this), base::Passed(&receiver)); + base::BindOnce(&WiFiDisplayMediaManager::ConnectToRemoteService, + base::Unretained(this), std::move(receiver)); main_runner->PostTaskAndReply(FROM_HERE, connect_service_callback, media::BindToCurrentLoop(on_completed));
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.h b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.h index 9d2f220b..66c3ecd 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.h +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_manager.h
@@ -30,7 +30,7 @@ class WiFiDisplayMediaManager : public wds::SourceMediaManager { public: - using ErrorCallback = base::Callback<void(const std::string&)>; + using ErrorCallback = base::RepeatingCallback<void(const std::string&)>; WiFiDisplayMediaManager(const blink::WebMediaStreamTrack& video_track, const blink::WebMediaStreamTrack& audio_track,
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_packetizer_unittest.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_packetizer_unittest.cc index 94b57051..28f3a67 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_packetizer_unittest.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_packetizer_unittest.cc
@@ -111,8 +111,9 @@ : WiFiDisplayMediaPacketizer( delay_for_unit_time_stamps, stream_infos, - base::Bind(&FakeMediaPacketizer::OnPacketizedMediaDatagramPacket, - base::Unretained(this))) {} + base::BindRepeating( + &FakeMediaPacketizer::OnPacketizedMediaDatagramPacket, + base::Unretained(this))) {} // Extend the interface in order to allow to bypass packetization of units to // Packetized Elementary Stream (PES) packets and further to Transport Stream
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.cc index 8d421914..c478c24 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.cc
@@ -25,14 +25,14 @@ const wds::AudioCodec& audio_codec, const net::IPAddress& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, - const RegisterMediaServiceCallback& service_callback, + RegisterMediaServiceCallback service_callback, const ErrorCallback& error_callback) : type_(type), video_parameters_(video_parameters), audio_codec_(audio_codec), sink_ip_address_(sink_ip_address), sink_rtp_ports_(sink_rtp_ports), - service_callback_(service_callback), + service_callback_(std::move(service_callback)), error_callback_(error_callback), weak_factory_(this) {} @@ -43,7 +43,7 @@ const wds::AudioCodec& audio_codec, const net::IPAddress& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, - const RegisterMediaServiceCallback& service_callback, + RegisterMediaServiceCallback service_callback, const ErrorCallback& error_callback) { return std::unique_ptr<WiFiDisplayMediaPipeline>( new WiFiDisplayMediaPipeline(type, @@ -79,18 +79,16 @@ LAST = MEDIA_SERVICE }; -void WiFiDisplayMediaPipeline::Initialize( - const InitCompletionCallback& callback) { +void WiFiDisplayMediaPipeline::Initialize(InitCompletionCallback callback) { DCHECK(!audio_encoder_ && !video_encoder_ && !packetizer_); - OnInitialize(callback, InitializationStep::FIRST, true); + OnInitialize(std::move(callback), InitializationStep::FIRST, true); } -void WiFiDisplayMediaPipeline::OnInitialize( - const InitCompletionCallback& callback, - InitializationStep current_step, - bool success) { +void WiFiDisplayMediaPipeline::OnInitialize(InitCompletionCallback callback, + InitializationStep current_step, + bool success) { if (!success) { - callback.Run(false); + std::move(callback).Run(false); return; } @@ -98,9 +96,9 @@ if (current_step < InitializationStep::LAST) { InitializationStep next_step = static_cast<InitializationStep>( static_cast<unsigned>(current_step) + 1u); - init_step_callback = - base::Bind(&WiFiDisplayMediaPipeline::OnInitialize, - weak_factory_.GetWeakPtr(), callback, next_step); + init_step_callback = base::BindOnce(&WiFiDisplayMediaPipeline::OnInitialize, + weak_factory_.GetWeakPtr(), + std::move(callback), next_step); } switch (current_step) { @@ -108,8 +106,8 @@ DCHECK(!audio_encoder_); if (type_ & wds::AudioSession) { auto result_callback = - base::Bind(&WiFiDisplayMediaPipeline::OnAudioEncoderCreated, - weak_factory_.GetWeakPtr(), init_step_callback); + base::BindOnce(&WiFiDisplayMediaPipeline::OnAudioEncoderCreated, + weak_factory_.GetWeakPtr(), init_step_callback); WiFiDisplayAudioEncoder::Create(audio_codec_, result_callback); } else { init_step_callback.Run(true); @@ -118,9 +116,9 @@ case InitializationStep::VIDEO_ENCODER: DCHECK(!video_encoder_); if (type_ & wds::VideoSession) { - auto result_callback = - base::Bind(&WiFiDisplayMediaPipeline::OnVideoEncoderCreated, - weak_factory_.GetWeakPtr(), init_step_callback); + auto result_callback = base::BindOnce( + &WiFiDisplayMediaPipeline::OnVideoEncoderCreated, + weak_factory_.GetWeakPtr(), std::move(init_step_callback)); WiFiDisplayVideoEncoder::Create(video_parameters_, result_callback); } else { init_step_callback.Run(true); @@ -134,8 +132,8 @@ case InitializationStep::MEDIA_SERVICE: service_callback_.Run( media_service_.BindNewPipeAndPassReceiver(), - base::Bind(&WiFiDisplayMediaPipeline::OnMediaServiceRegistered, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&WiFiDisplayMediaPipeline::OnMediaServiceRegistered, + weak_factory_.GetWeakPtr(), std::move(callback))); break; } } @@ -156,59 +154,63 @@ packetizer_.reset(new WiFiDisplayMediaPacketizer( base::TimeDelta::FromMilliseconds(200), stream_infos, - base::Bind(&WiFiDisplayMediaPipeline::OnPacketizedMediaDatagramPacket, - base::Unretained(this)))); + base::BindRepeating( + &WiFiDisplayMediaPipeline::OnPacketizedMediaDatagramPacket, + base::Unretained(this)))); } void WiFiDisplayMediaPipeline::OnAudioEncoderCreated( - const InitStepCompletionCallback& callback, + InitStepCompletionCallback callback, scoped_refptr<WiFiDisplayAudioEncoder> audio_encoder) { DCHECK(!audio_encoder_); if (!audio_encoder) { - callback.Run(false); + std::move(callback).Run(false); return; } audio_encoder_ = std::move(audio_encoder); auto encoded_callback = - base::Bind(&WiFiDisplayMediaPipeline::OnEncodedAudioUnit, - weak_factory_.GetWeakPtr()); - auto error_callback = base::Bind(error_callback_, kErrorAudioEncoderError); + base::BindOnce(&WiFiDisplayMediaPipeline::OnEncodedAudioUnit, + weak_factory_.GetWeakPtr()); + auto error_callback = + base::BindOnce(error_callback_, kErrorAudioEncoderError); audio_encoder_->SetCallbacks(encoded_callback, error_callback); - callback.Run(true); + std::move(callback).Run(true); } void WiFiDisplayMediaPipeline::OnVideoEncoderCreated( - const InitStepCompletionCallback& callback, + InitStepCompletionCallback callback, scoped_refptr<WiFiDisplayVideoEncoder> video_encoder) { DCHECK(!video_encoder_); if (!video_encoder) { - callback.Run(false); + std::move(callback).Run(false); return; } video_encoder_ = std::move(video_encoder); - auto encoded_callback = base::Bind( - &WiFiDisplayMediaPipeline::OnEncodedVideoFrame, - weak_factory_.GetWeakPtr()); - auto error_callback = base::Bind(error_callback_, kErrorVideoEncoderError); + auto encoded_callback = + base::BindOnce(&WiFiDisplayMediaPipeline::OnEncodedVideoFrame, + weak_factory_.GetWeakPtr()); + auto error_callback = + base::BindOnce(error_callback_, kErrorVideoEncoderError); video_encoder_->SetCallbacks(encoded_callback, error_callback); - callback.Run(true); + std::move(callback).Run(true); } void WiFiDisplayMediaPipeline::OnMediaServiceRegistered( - const InitCompletionCallback& callback) { + InitCompletionCallback callback) { DCHECK(media_service_); - auto error_callback = base::Bind(error_callback_, kErrorUnableSendMedia); + auto error_callback = + base::BindRepeating(error_callback_, kErrorUnableSendMedia); media_service_.set_disconnect_handler(error_callback); media_service_->SetDestinationPoint( net::IPEndPoint(sink_ip_address_, static_cast<uint16_t>(sink_rtp_ports_.first)), - callback); + std::move(callback)); } void WiFiDisplayMediaPipeline::OnEncodedAudioUnit(
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.h b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.h index 5335b3e..9ebd8cf 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.h +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_media_pipeline.h
@@ -33,10 +33,10 @@ class WiFiDisplayMediaPipeline { public: using ErrorCallback = base::Callback<void(const std::string&)>; - using InitCompletionCallback = base::Callback<void(bool)>; - using RegisterMediaServiceCallback = - base::Callback<void(mojo::PendingReceiver<mojom::WiFiDisplayMediaService>, - const base::Closure&)>; + using InitCompletionCallback = base::OnceCallback<void(bool)>; + using RegisterMediaServiceCallback = base::OnceCallback<void( + mojo::PendingReceiver<mojom::WiFiDisplayMediaService>, + const base::Closure&)>; static std::unique_ptr<WiFiDisplayMediaPipeline> Create( wds::SessionType type, @@ -44,11 +44,11 @@ const wds::AudioCodec& audio_codec, const net::IPAddress& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, - const RegisterMediaServiceCallback& service_callback, + RegisterMediaServiceCallback service_callback, const ErrorCallback& error_callback); ~WiFiDisplayMediaPipeline(); // Note: to be called only once. - void Initialize(const InitCompletionCallback& callback); + void Initialize(InitCompletionCallback callback); void InsertRawVideoFrame(scoped_refptr<media::VideoFrame> video_frame, base::TimeTicks reference_time); @@ -67,20 +67,20 @@ const wds::AudioCodec& audio_codec, const net::IPAddress& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, - const RegisterMediaServiceCallback& service_callback, + RegisterMediaServiceCallback service_callback, const ErrorCallback& error_callback); void CreateMediaPacketizer(); - void OnInitialize(const InitCompletionCallback& callback, + void OnInitialize(InitCompletionCallback callback, InitializationStep current_step, bool success); void OnAudioEncoderCreated( - const InitStepCompletionCallback& callback, + InitStepCompletionCallback callback, scoped_refptr<WiFiDisplayAudioEncoder> audio_encoder); void OnVideoEncoderCreated( - const InitStepCompletionCallback& callback, + InitStepCompletionCallback callback, scoped_refptr<WiFiDisplayVideoEncoder> video_encoder); - void OnMediaServiceRegistered(const InitCompletionCallback& callback); + void OnMediaServiceRegistered(InitCompletionCallback callback); void OnEncodedAudioUnit(std::unique_ptr<WiFiDisplayEncodedUnit> unit); void OnEncodedVideoFrame(std::unique_ptr<WiFiDisplayEncodedFrame> frame);
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_session.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_session.cc index fca818a..fdc5a22 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_session.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_session.cc
@@ -40,14 +40,13 @@ DCHECK(params_.render_frame); wds::LogSystem::set_error_func(&LogWDSError); params.render_frame->GetBrowserInterfaceBroker()->GetInterface(&service_); - service_.set_connection_error_handler(base::Bind( - &WiFiDisplaySession::OnIPCConnectionError, - weak_factory_.GetWeakPtr())); + service_.set_connection_error_handler(base::BindRepeating( + &WiFiDisplaySession::OnIPCConnectionError, weak_factory_.GetWeakPtr())); mojo::Remote<WiFiDisplaySessionServiceClient> client; receiver_.Bind(client.BindNewPipeAndPassReceiver()); service_->SetClient(std::move(client)); - receiver_.set_disconnect_handler(base::Bind( + receiver_.set_disconnect_handler(base::BindRepeating( &WiFiDisplaySession::OnIPCConnectionError, weak_factory_.GetWeakPtr())); } @@ -79,8 +78,8 @@ media_manager_.reset(new WiFiDisplayMediaManager( params_.video_track, params_.audio_track, sink_ip_address, params_.render_frame->GetBrowserInterfaceBroker(), - base::Bind(&WiFiDisplaySession::OnMediaError, - weak_factory_.GetWeakPtr()))); + base::BindRepeating(&WiFiDisplaySession::OnMediaError, + weak_factory_.GetWeakPtr()))); wfd_source_.reset(wds::Source::Create(this, media_manager_.get(), this)); wfd_source_->Start(); } @@ -137,11 +136,10 @@ timers_.insert(std::pair<int, std::unique_ptr<base::RepeatingTimer>>( ++timer_id_, std::move(timer))); DCHECK(insert_ret.second); - insert_ret.first->second->Start(FROM_HERE, - base::TimeDelta::FromSeconds(seconds), - base::Bind(&wds::Source::OnTimerEvent, - base::Unretained(wfd_source_.get()), - timer_id_)); + insert_ret.first->second->Start( + FROM_HERE, base::TimeDelta::FromSeconds(seconds), + base::BindOnce(&wds::Source::OnTimerEvent, + base::Unretained(wfd_source_.get()), timer_id_)); return static_cast<unsigned>(timer_id_); }
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.cc index a21d571..17a51af 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.cc
@@ -53,20 +53,20 @@ } // static -void WiFiDisplayVideoEncoder::Create( - const InitParameters& params, - const VideoEncoderCallback& encoder_callback) { - CreateVEA(params, base::Bind(&OnCreatedVEA, params, encoder_callback)); +void WiFiDisplayVideoEncoder::Create(const InitParameters& params, + VideoEncoderCallback encoder_callback) { + CreateVEA(params, + base::BindOnce(&OnCreatedVEA, params, std::move(encoder_callback))); } // static void WiFiDisplayVideoEncoder::OnCreatedVEA( const InitParameters& params, - const VideoEncoderCallback& encoder_callback, + VideoEncoderCallback encoder_callback, scoped_refptr<WiFiDisplayVideoEncoder> vea_encoder) { if (vea_encoder) { // An accelerated encoder was created successfully. Pass it on. - encoder_callback.Run(vea_encoder); + std::move(encoder_callback).Run(vea_encoder); } else { // An accelerated encoder was not created. Fall back to a software encoder. CreateSVC(params, encoder_callback);
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.h b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.h index 8219c52..f68596d7a5 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.h +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.h
@@ -26,7 +26,7 @@ class WiFiDisplayVideoEncoder : public WiFiDisplayMediaEncoder { public: using VideoEncoderCallback = - base::Callback<void(scoped_refptr<WiFiDisplayVideoEncoder>)>; + base::OnceCallback<void(scoped_refptr<WiFiDisplayVideoEncoder>)>; using ReceiveVideoEncodeAcceleratorCallback = base::Callback<void(scoped_refptr<base::SingleThreadTaskRunner>, @@ -37,7 +37,8 @@ using ReceiveEncodeMemoryCallback = base::Callback<void(base::UnsafeSharedMemoryRegion)>; using CreateEncodeMemoryCallback = - base::Callback<void(size_t size, const ReceiveEncodeMemoryCallback&)>; + base::RepeatingCallback<void(size_t size, + const ReceiveEncodeMemoryCallback&)>; struct InitParameters { InitParameters(); @@ -64,7 +65,7 @@ // |params|, the encoder instance is returned as an argument of // |result_callback| ('nullptr' argument means encoder creation failure). static void Create(const InitParameters& params, - const VideoEncoderCallback& encoder_callback); + VideoEncoderCallback encoder_callback); // WiFiDisplayMediaEncoder WiFiDisplayElementaryStreamInfo CreateElementaryStreamInfo() const final; @@ -83,14 +84,14 @@ // A factory method that creates a new encoder instance which uses OpenH264 // SVC encoder for encoding. static void CreateSVC(const InitParameters& params, - const VideoEncoderCallback& encoder_callback); + VideoEncoderCallback encoder_callback); // A factory method that creates a new encoder instance which uses Video // Encode Accelerator (VEA) for encoding. static void CreateVEA(const InitParameters& params, - const VideoEncoderCallback& encoder_callback); + VideoEncoderCallback encoder_callback); static void OnCreatedVEA(const InitParameters& params, - const VideoEncoderCallback& encoder_callback, + VideoEncoderCallback encoder_callback, scoped_refptr<WiFiDisplayVideoEncoder> vea_encoder); explicit WiFiDisplayVideoEncoder(
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_svc.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_svc.cc index 3f744af..caa6a44 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_svc.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_svc.cc
@@ -36,7 +36,7 @@ class WiFiDisplayVideoEncoderSVC final : public WiFiDisplayVideoEncoder { public: static void Create(const InitParameters& params, - const VideoEncoderCallback& encoder_callback); + VideoEncoderCallback encoder_callback); private: WiFiDisplayVideoEncoderSVC( @@ -57,9 +57,8 @@ }; // static -void WiFiDisplayVideoEncoderSVC::Create( - const InitParameters& params, - const VideoEncoderCallback& encoder_callback) { +void WiFiDisplayVideoEncoderSVC::Create(const InitParameters& params, + VideoEncoderCallback encoder_callback) { // TODO(e_hakkinen): Use normal media thread once it is exposed to extensions // and can be passed to this class. std::unique_ptr<base::Thread> media_thread( @@ -73,7 +72,7 @@ base::WrapRefCounted(new WiFiDisplayVideoEncoderSVC( base::ThreadTaskRunnerHandle::Get(), std::move(media_thread))), params), - base::BindOnce(encoder_callback)); + base::BindOnce(std::move(encoder_callback))); } WiFiDisplayVideoEncoderSVC::WiFiDisplayVideoEncoderSVC( @@ -200,10 +199,9 @@ } // namespace // static -void WiFiDisplayVideoEncoder::CreateSVC( - const InitParameters& params, - const VideoEncoderCallback& encoder_callback) { - WiFiDisplayVideoEncoderSVC::Create(params, encoder_callback); +void WiFiDisplayVideoEncoder::CreateSVC(const InitParameters& params, + VideoEncoderCallback encoder_callback) { + WiFiDisplayVideoEncoderSVC::Create(params, std::move(encoder_callback)); } } // namespace extensions
diff --git a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_vea.cc b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_vea.cc index 0112c18..7c0f8104 100644 --- a/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_vea.cc +++ b/extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder_vea.cc
@@ -29,7 +29,7 @@ public: static void Create( const InitParameters& params, - const VideoEncoderCallback& encoder_callback, + VideoEncoderCallback encoder_callback, scoped_refptr<base::SingleThreadTaskRunner> media_task_runner, std::unique_ptr<media::VideoEncodeAccelerator> vea); @@ -91,11 +91,11 @@ // static void WiFiDisplayVideoEncoderVEA::Create( const InitParameters& params, - const VideoEncoderCallback& encoder_callback, + VideoEncoderCallback encoder_callback, scoped_refptr<base::SingleThreadTaskRunner> media_task_runner, std::unique_ptr<media::VideoEncodeAccelerator> vea) { if (!vea || !media_task_runner) { - encoder_callback.Run(nullptr); + std::move(encoder_callback).Run(nullptr); return; } @@ -106,7 +106,7 @@ std::move(media_task_runner), vea.release(), params.create_memory_callback)), params), - base::BindOnce(encoder_callback)); + base::BindOnce(std::move(encoder_callback))); } WiFiDisplayVideoEncoderVEA::WiFiDisplayVideoEncoderVEA( @@ -148,7 +148,8 @@ for (size_t i = 0; i < input_count; ++i) { create_video_encode_memory_cb_.Run( output_buffer_size, - base::Bind(&WiFiDisplayVideoEncoderVEA::OnCreateSharedMemory, this)); + base::BindOnce(&WiFiDisplayVideoEncoderVEA::OnCreateSharedMemory, + this)); } } @@ -239,11 +240,10 @@ } // namespace // static -void WiFiDisplayVideoEncoder::CreateVEA( - const InitParameters& params, - const VideoEncoderCallback& encoder_callback) { - auto on_vea_cb = - base::Bind(&WiFiDisplayVideoEncoderVEA::Create, params, encoder_callback); +void WiFiDisplayVideoEncoder::CreateVEA(const InitParameters& params, + VideoEncoderCallback encoder_callback) { + auto on_vea_cb = base::BindOnce(&WiFiDisplayVideoEncoderVEA::Create, params, + std::move(encoder_callback)); params.vea_create_callback.Run(media::BindToCurrentLoop(on_vea_cb)); }
diff --git a/extensions/shell/BUILD.gn b/extensions/shell/BUILD.gn index 13525ab..10e1dd2 100644 --- a/extensions/shell/BUILD.gn +++ b/extensions/shell/BUILD.gn
@@ -68,6 +68,7 @@ "//extensions/shell/browser/system_logs", "//extensions/shell/common/api", "//extensions/shell/common/api:extensions_features", + "//services/network/public/mojom", "//third_party/blink/public:blink", "//ui/base", "//ui/base/ime/init",
diff --git a/extensions/shell/browser/DEPS b/extensions/shell/browser/DEPS index ef4e0ac3..ae9d705 100644 --- a/extensions/shell/browser/DEPS +++ b/extensions/shell/browser/DEPS
@@ -30,6 +30,7 @@ "+services/metrics/public/cpp/ukm_source_id.h", "+services/network/public/cpp/session_cookie_delete_predicate.h", "+services/network/public/mojom/cors_origin_pattern.mojom.h", + "+services/network/public/mojom/fetch_api.mojom.h", "+services/network/public/mojom/url_loader.mojom.h", "+storage/browser/quota", "+third_party/skia/include",
diff --git a/extensions/shell/browser/shell_extensions_browser_client.cc b/extensions/shell/browser/shell_extensions_browser_client.cc index d0cd0e9..936f7b2 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.cc +++ b/extensions/shell/browser/shell_extensions_browser_client.cc
@@ -140,7 +140,7 @@ bool ShellExtensionsBrowserClient::AllowCrossRendererResourceLoad( const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, + network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito, @@ -149,7 +149,7 @@ const ProcessMap& process_map) { bool allowed = false; if (url_request_util::AllowCrossRendererResourceLoad( - request, resource_type, page_transition, child_id, is_incognito, + request, destination, page_transition, child_id, is_incognito, extension, extensions, process_map, &allowed)) { return allowed; }
diff --git a/extensions/shell/browser/shell_extensions_browser_client.h b/extensions/shell/browser/shell_extensions_browser_client.h index bfdd6c7..b8614fc 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.h +++ b/extensions/shell/browser/shell_extensions_browser_client.h
@@ -17,6 +17,7 @@ #include "extensions/browser/kiosk/kiosk_delegate.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/fetch_api.mojom.h" class PrefService; @@ -71,14 +72,15 @@ const std::string& content_security_policy, mojo::PendingRemote<network::mojom::URLLoaderClient> client, bool send_cors_header) override; - bool AllowCrossRendererResourceLoad(const network::ResourceRequest& request, - blink::mojom::ResourceType resource_type, - ui::PageTransition page_transition, - int child_id, - bool is_incognito, - const Extension* extension, - const ExtensionSet& extensions, - const ProcessMap& process_map) override; + bool AllowCrossRendererResourceLoad( + const network::ResourceRequest& request, + network::mojom::RequestDestination destination, + ui::PageTransition page_transition, + int child_id, + bool is_incognito, + const Extension* extension, + const ExtensionSet& extensions, + const ProcessMap& process_map) override; PrefService* GetPrefServiceForContext( content::BrowserContext* context) override; void GetEarlyExtensionPrefsObservers(
diff --git a/fuchsia/cast_streaming/BUILD.gn b/fuchsia/cast_streaming/BUILD.gn index 2711065d..bb7f8e1 100644 --- a/fuchsia/cast_streaming/BUILD.gn +++ b/fuchsia/cast_streaming/BUILD.gn
@@ -6,6 +6,19 @@ import("//testing/test.gni") +source_set("cast_streaming_config_conversions") { + deps = [ + "//base", + "//media", + "//third_party/openscreen/src/cast/streaming:common", + ] + visibility = [ ":*" ] + sources = [ + "config_conversions.cc", + "config_conversions.h", + ] +} + source_set("cast_streaming_message_port") { deps = [ "//base", @@ -25,6 +38,7 @@ source_set("cast_streaming") { deps = [ + ":cast_streaming_config_conversions", ":cast_streaming_message_port", "//base", "//components/openscreen_platform", @@ -52,6 +66,33 @@ ] } +source_set("cast_streaming_test_sender") { + testonly = true + deps = [ + ":cast_streaming_config_conversions", + ":cast_streaming_message_port", + "//base", + "//components/openscreen_platform", + "//components/openscreen_platform:openscreen_platform_network_service", + "//media", + "//media/mojo/common", + "//media/mojo/mojom", + "//mojo/public/cpp/system", + "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.web", + "//third_party/openscreen/src/cast/common:public", + "//third_party/openscreen/src/cast/streaming:sender", + "//third_party/openscreen/src/platform:api", + "//third_party/openscreen/src/util", + ] + visibility = [ ":*" ] + sources = [ + "test/cast_message_port_sender_impl.cc", + "test/cast_message_port_sender_impl.h", + "test/cast_streaming_test_sender.cc", + "test/cast_streaming_test_sender.h", + ] +} + test("cast_streaming_unittests") { sources = [ "cast_message_port_impl_unittest.cc" ] deps = [
diff --git a/fuchsia/cast_streaming/cast_streaming_session.cc b/fuchsia/cast_streaming/cast_streaming_session.cc index de1cdcc..53f2ad5 100644 --- a/fuchsia/cast_streaming/cast_streaming_session.cc +++ b/fuchsia/cast_streaming/cast_streaming_session.cc
@@ -5,14 +5,13 @@ #include "fuchsia/cast_streaming/public/cast_streaming_session.h" #include "base/bind.h" -#include "base/notreached.h" #include "base/timer/timer.h" #include "components/openscreen_platform/network_context.h" #include "components/openscreen_platform/network_util.h" #include "components/openscreen_platform/task_runner.h" #include "fuchsia/cast_streaming/cast_message_port_impl.h" +#include "fuchsia/cast_streaming/config_conversions.h" #include "fuchsia/cast_streaming/stream_consumer.h" -#include "media/base/media_util.h" #include "media/mojo/common/mojo_decoder_buffer_converter.h" #include "mojo/public/cpp/system/data_pipe.h" #include "third_party/openscreen/src/cast/streaming/receiver.h" @@ -20,63 +19,6 @@ namespace { -media::AudioDecoderConfig AudioCaptureConfigToAudioDecoderConfig( - const openscreen::cast::AudioCaptureConfig& audio_capture_config) { - // Gather data for the audio decoder config. - media::AudioCodec media_audio_codec = media::AudioCodec::kUnknownAudioCodec; - switch (audio_capture_config.codec) { - case openscreen::cast::AudioCodec::kAac: - media_audio_codec = media::AudioCodec::kCodecAAC; - break; - case openscreen::cast::AudioCodec::kOpus: - media_audio_codec = media::AudioCodec::kCodecOpus; - break; - default: - NOTREACHED(); - break; - } - - return media::AudioDecoderConfig( - media_audio_codec, media::SampleFormat::kSampleFormatF32, - media::GuessChannelLayout(audio_capture_config.channels), - audio_capture_config.sample_rate /* samples_per_second */, - media::EmptyExtraData(), media::EncryptionScheme::kUnencrypted); -} - -media::VideoDecoderConfig VideoCaptureConfigToVideoDecoderConfig( - const openscreen::cast::VideoCaptureConfig& video_capture_config) { - // Gather data for the video decoder config. - uint32_t video_width = video_capture_config.resolutions[0].width; - uint32_t video_height = video_capture_config.resolutions[0].height; - gfx::Size video_size(video_width, video_height); - gfx::Rect video_rect(video_width, video_height); - - media::VideoCodec media_video_codec = media::VideoCodec::kUnknownVideoCodec; - media::VideoCodecProfile video_codec_profile = - media::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; - switch (video_capture_config.codec) { - case openscreen::cast::VideoCodec::kH264: - media_video_codec = media::VideoCodec::kCodecH264; - video_codec_profile = media::VideoCodecProfile::H264PROFILE_BASELINE; - break; - case openscreen::cast::VideoCodec::kVp8: - media_video_codec = media::VideoCodec::kCodecVP8; - video_codec_profile = media::VideoCodecProfile::VP8PROFILE_MIN; - break; - case openscreen::cast::VideoCodec::kHevc: - case openscreen::cast::VideoCodec::kVp9: - default: - NOTREACHED(); - break; - } - - return media::VideoDecoderConfig( - media_video_codec, video_codec_profile, - media::VideoDecoderConfig::AlphaMode::kIsOpaque, media::VideoColorSpace(), - media::VideoTransformation(), video_size, video_rect, video_size, - media::EmptyExtraData(), media::EncryptionScheme::kUnencrypted); -} - bool CreateDataPipeForStreamType(media::DemuxerStream::Type type, mojo::ScopedDataPipeProducerHandle* producer, mojo::ScopedDataPipeConsumerHandle* consumer) {
diff --git a/fuchsia/cast_streaming/config_conversions.cc b/fuchsia/cast_streaming/config_conversions.cc new file mode 100644 index 0000000..056f19ff --- /dev/null +++ b/fuchsia/cast_streaming/config_conversions.cc
@@ -0,0 +1,112 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia/cast_streaming/config_conversions.h" + +#include "base/notreached.h" +#include "media/base/media_util.h" + +namespace cast_streaming { + +openscreen::cast::AudioCaptureConfig AudioDecoderConfigToAudioCaptureConfig( + const media::AudioDecoderConfig& audio_config) { + openscreen::cast::AudioCaptureConfig audio_capture_config; + + switch (audio_config.codec()) { + case media::AudioCodec::kCodecAAC: + audio_capture_config.codec = openscreen::cast::AudioCodec::kAac; + break; + case media::AudioCodec::kCodecOpus: + audio_capture_config.codec = openscreen::cast::AudioCodec::kOpus; + break; + default: + NOTREACHED(); + } + + audio_capture_config.channels = + media::ChannelLayoutToChannelCount(audio_config.channel_layout()); + audio_capture_config.sample_rate = audio_config.samples_per_second(); + + return audio_capture_config; +} + +openscreen::cast::VideoCaptureConfig VideoDecoderConfigToVideoCaptureConfig( + const media::VideoDecoderConfig& video_config) { + openscreen::cast::VideoCaptureConfig video_capture_config; + + switch (video_config.codec()) { + case media::VideoCodec::kCodecH264: + video_capture_config.codec = openscreen::cast::VideoCodec::kH264; + break; + case media::VideoCodec::kCodecVP8: + video_capture_config.codec = openscreen::cast::VideoCodec::kVp8; + break; + default: + NOTREACHED(); + } + + video_capture_config.resolutions.push_back( + {video_config.visible_rect().width(), + video_config.visible_rect().height()}); + return video_capture_config; +} + +media::AudioDecoderConfig AudioCaptureConfigToAudioDecoderConfig( + const openscreen::cast::AudioCaptureConfig& audio_capture_config) { + // Gather data for the audio decoder config. + media::AudioCodec media_audio_codec = media::AudioCodec::kUnknownAudioCodec; + switch (audio_capture_config.codec) { + case openscreen::cast::AudioCodec::kAac: + media_audio_codec = media::AudioCodec::kCodecAAC; + break; + case openscreen::cast::AudioCodec::kOpus: + media_audio_codec = media::AudioCodec::kCodecOpus; + break; + default: + NOTREACHED(); + break; + } + + return media::AudioDecoderConfig( + media_audio_codec, media::SampleFormat::kSampleFormatF32, + media::GuessChannelLayout(audio_capture_config.channels), + audio_capture_config.sample_rate /* samples_per_second */, + media::EmptyExtraData(), media::EncryptionScheme::kUnencrypted); +} + +media::VideoDecoderConfig VideoCaptureConfigToVideoDecoderConfig( + const openscreen::cast::VideoCaptureConfig& video_capture_config) { + // Gather data for the video decoder config. + uint32_t video_width = video_capture_config.resolutions[0].width; + uint32_t video_height = video_capture_config.resolutions[0].height; + gfx::Size video_size(video_width, video_height); + gfx::Rect video_rect(video_width, video_height); + + media::VideoCodec media_video_codec = media::VideoCodec::kUnknownVideoCodec; + media::VideoCodecProfile video_codec_profile = + media::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; + switch (video_capture_config.codec) { + case openscreen::cast::VideoCodec::kH264: + media_video_codec = media::VideoCodec::kCodecH264; + video_codec_profile = media::VideoCodecProfile::H264PROFILE_BASELINE; + break; + case openscreen::cast::VideoCodec::kVp8: + media_video_codec = media::VideoCodec::kCodecVP8; + video_codec_profile = media::VideoCodecProfile::VP8PROFILE_MIN; + break; + case openscreen::cast::VideoCodec::kHevc: + case openscreen::cast::VideoCodec::kVp9: + default: + NOTREACHED(); + break; + } + + return media::VideoDecoderConfig( + media_video_codec, video_codec_profile, + media::VideoDecoderConfig::AlphaMode::kIsOpaque, media::VideoColorSpace(), + media::VideoTransformation(), video_size, video_rect, video_size, + media::EmptyExtraData(), media::EncryptionScheme::kUnencrypted); +} + +} // namespace cast_streaming
diff --git a/fuchsia/cast_streaming/config_conversions.h b/fuchsia/cast_streaming/config_conversions.h new file mode 100644 index 0000000..766a61f2 --- /dev/null +++ b/fuchsia/cast_streaming/config_conversions.h
@@ -0,0 +1,30 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_CAST_STREAMING_CONFIG_CONVERSIONS_H_ +#define FUCHSIA_CAST_STREAMING_CONFIG_CONVERSIONS_H_ + +#include "media/base/audio_decoder_config.h" +#include "media/base/video_decoder_config.h" +#include "third_party/openscreen/src/cast/streaming/capture_configs.h" + +namespace cast_streaming { + +// Utility functions to convert between media and Open Screen types. + +openscreen::cast::AudioCaptureConfig AudioDecoderConfigToAudioCaptureConfig( + const media::AudioDecoderConfig& audio_config); + +openscreen::cast::VideoCaptureConfig VideoDecoderConfigToVideoCaptureConfig( + const media::VideoDecoderConfig& video_config); + +media::AudioDecoderConfig AudioCaptureConfigToAudioDecoderConfig( + const openscreen::cast::AudioCaptureConfig& audio_capture_config); + +media::VideoDecoderConfig VideoCaptureConfigToVideoDecoderConfig( + const openscreen::cast::VideoCaptureConfig& video_capture_config); + +} // namespace cast_streaming + +#endif // FUCHSIA_CAST_STREAMING_CONFIG_CONVERSIONS_H_
diff --git a/fuchsia/cast_streaming/test/cast_message_port_sender_impl.cc b/fuchsia/cast_streaming/test/cast_message_port_sender_impl.cc new file mode 100644 index 0000000..277cf3b --- /dev/null +++ b/fuchsia/cast_streaming/test/cast_message_port_sender_impl.cc
@@ -0,0 +1,105 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia/cast_streaming/test/cast_message_port_sender_impl.h" + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/logging.h" +#include "base/values.h" +#include "fuchsia/cast_streaming/message_serialization.h" +#include "third_party/openscreen/src/platform/base/error.h" + +namespace cast_streaming { + +CastMessagePortSenderImpl::CastMessagePortSenderImpl( + std::unique_ptr<cast_api_bindings::MessagePort> message_port, + base::OnceClosure on_close) + : message_port_(std::move(message_port)), on_close_(std::move(on_close)) { + VLOG(1) << __func__; + message_port_->SetReceiver(this); +} + +CastMessagePortSenderImpl::~CastMessagePortSenderImpl() = default; + +void CastMessagePortSenderImpl::MaybeClose() { + if (message_port_) { + message_port_.reset(); + } + if (client_) { + client_->OnError( + openscreen::Error(openscreen::Error::Code::kCastV2CastSocketError)); + if (on_close_) { + std::move(on_close_).Run(); + } + } +} + +void CastMessagePortSenderImpl::SetClient( + openscreen::cast::MessagePort::Client* client, + std::string client_sender_id) { + VLOG(2) << __func__; + CHECK(client); + CHECK(!client_); + client_ = client; +} + +void CastMessagePortSenderImpl::ResetClient() { + client_ = nullptr; + MaybeClose(); +} + +void CastMessagePortSenderImpl::PostMessage( + const std::string& sender_id, + const std::string& message_namespace, + const std::string& message) { + VLOG(3) << __func__; + if (!message_port_) { + return; + } + + VLOG(3) << "Received Open Screen message. SenderId: " << sender_id + << ". Namespace: " << message_namespace << ". Message: " << message; + message_port_->PostMessage( + SerializeCastMessage(sender_id, message_namespace, message)); +} + +bool CastMessagePortSenderImpl::OnMessage( + base::StringPiece message, + std::vector<std::unique_ptr<cast_api_bindings::MessagePort>> ports) { + VLOG(3) << __func__; + + // If |client_| was cleared, |message_port_| should have been reset. + CHECK(client_); + + if (!ports.empty()) { + // We should never receive any ports for Cast Streaming. + MaybeClose(); + return false; + } + + std::string sender_id; + std::string message_namespace; + std::string str_message; + if (!DeserializeCastMessage(message, &sender_id, &message_namespace, + &str_message)) { + LOG(ERROR) << "Received bad message. " << message; + client_->OnError( + openscreen::Error(openscreen::Error::Code::kCastV2InvalidMessage)); + return false; + } + VLOG(3) << "Received Cast message. SenderId: " << sender_id + << ". Namespace: " << message_namespace + << ". Message: " << str_message; + + client_->OnMessage(sender_id, message_namespace, str_message); + return true; +} + +void CastMessagePortSenderImpl::OnPipeError() { + VLOG(3) << __func__; + MaybeClose(); +} + +} // namespace cast_streaming
diff --git a/fuchsia/cast_streaming/test/cast_message_port_sender_impl.h b/fuchsia/cast_streaming/test/cast_message_port_sender_impl.h new file mode 100644 index 0000000..13c6137 --- /dev/null +++ b/fuchsia/cast_streaming/test/cast_message_port_sender_impl.h
@@ -0,0 +1,54 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_CAST_STREAMING_TEST_CAST_MESSAGE_PORT_SENDER_IMPL_H_ +#define FUCHSIA_CAST_STREAMING_TEST_CAST_MESSAGE_PORT_SENDER_IMPL_H_ + +#include "base/callback.h" +#include "components/cast/message_port/message_port.h" +#include "third_party/openscreen/src/cast/common/public/message_port.h" + +namespace cast_streaming { + +// Adapter for a cast MessagePort that provides an Open Screen MessagePort +// implementation for a Cast Streaming Sender. +class CastMessagePortSenderImpl + : public openscreen::cast::MessagePort, + public cast_api_bindings::MessagePort::Receiver { + public: + explicit CastMessagePortSenderImpl( + std::unique_ptr<cast_api_bindings::MessagePort> message_port, + base::OnceClosure on_close); + ~CastMessagePortSenderImpl() final; + + CastMessagePortSenderImpl(const CastMessagePortSenderImpl&) = delete; + CastMessagePortSenderImpl& operator=(const CastMessagePortSenderImpl&) = + delete; + + // openscreen::cast::MessagePort implementation. + void SetClient(Client* client, std::string client_sender_id) final; + void ResetClient() final; + void PostMessage(const std::string& sender_id, + const std::string& message_namespace, + const std::string& message) final; + + private: + // Resets |message_port_| if it is open and signals an error to |client_| if + // |client_| is set. + void MaybeClose(); + + // cast_api_bindings::MessagePort::Receiver implementation. + bool OnMessage( + base::StringPiece message, + std::vector<std::unique_ptr<cast_api_bindings::MessagePort>> ports) final; + void OnPipeError() final; + + Client* client_ = nullptr; + std::unique_ptr<cast_api_bindings::MessagePort> message_port_; + base::OnceClosure on_close_; +}; + +} // namespace cast_streaming + +#endif // FUCHSIA_CAST_STREAMING_TEST_CAST_MESSAGE_PORT_SENDER_IMPL_H_
diff --git a/fuchsia/cast_streaming/test/cast_streaming_test_sender.cc b/fuchsia/cast_streaming/test/cast_streaming_test_sender.cc new file mode 100644 index 0000000..a6711144 --- /dev/null +++ b/fuchsia/cast_streaming/test/cast_streaming_test_sender.cc
@@ -0,0 +1,215 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_SENDER_SESSION_TEST_H_ +#define FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_SENDER_SESSION_TEST_H_ + +#include "fuchsia/cast_streaming/test/cast_streaming_test_sender.h" + +#include "base/logging.h" +#include "base/run_loop.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "fuchsia/cast_streaming/config_conversions.h" +#include "third_party/openscreen/src/cast/streaming/capture_recommendations.h" + +namespace cast_streaming { + +namespace { + +// Converts |data_buffer| into an Open Screen EncodedFrame. The caller must keep +// a reference to |data_buffer| while using the returned EncodedFrame since they +// point to the same data. +openscreen::cast::EncodedFrame DataBufferToEncodedFrame( + const scoped_refptr<media::DataBuffer>& data_buffer, + bool is_key_frame, + openscreen::cast::FrameId frame_id, + openscreen::cast::FrameId* last_referenced_frame_id, + int rtp_timebase) { + CHECK(data_buffer); + CHECK(!data_buffer->end_of_stream()); + + openscreen::cast::EncodedFrame encoded_frame; + encoded_frame.frame_id = frame_id; + if (is_key_frame) { + encoded_frame.dependency = + openscreen::cast::EncodedFrame::Dependency::KEY_FRAME; + *last_referenced_frame_id = encoded_frame.frame_id; + } else { + encoded_frame.dependency = + openscreen::cast::EncodedFrame::Dependency::DEPENDS_ON_ANOTHER; + } + encoded_frame.referenced_frame_id = *last_referenced_frame_id; + + std::chrono::milliseconds timestamp( + data_buffer->timestamp().InMilliseconds()); + encoded_frame.rtp_timestamp = + openscreen::cast::RtpTimeTicks::FromTimeSinceOrigin< + std::chrono::milliseconds>(timestamp, rtp_timebase); + encoded_frame.reference_time = openscreen::Clock::time_point(timestamp); + + encoded_frame.data = absl::Span<uint8_t>(data_buffer->writable_data(), + data_buffer->data_size()); + + return encoded_frame; +} + +} // namespace + +CastStreamingTestSender::CastStreamingTestSender() + : task_runner_(base::SequencedTaskRunnerHandle::Get()), + environment_(&openscreen::Clock::now, &task_runner_) {} + +CastStreamingTestSender::~CastStreamingTestSender() = default; + +bool CastStreamingTestSender::Start( + std::unique_ptr<cast_api_bindings::MessagePort> message_port, + net::IPAddress receiver_address, + base::Optional<media::AudioDecoderConfig> audio_config, + base::Optional<media::VideoDecoderConfig> video_config) { + VLOG(1) << __func__; + CHECK(!is_active_); + CHECK(!sender_session_); + CHECK(audio_config || video_config); + + // Instantiate the |sender_session_|. + message_port_ = std::make_unique<CastMessagePortSenderImpl>( + std::move(message_port), + base::BindOnce(&CastStreamingTestSender::OnCastChannelClosed, + base::Unretained(this))); + sender_session_ = std::make_unique<openscreen::cast::SenderSession>( + openscreen::IPAddress::kV6LoopbackAddress(), this, &environment_, + message_port_.get()); + + std::vector<openscreen::cast::AudioCaptureConfig> audio_configs; + if (audio_config) { + audio_configs.push_back( + AudioDecoderConfigToAudioCaptureConfig(audio_config.value())); + } + + std::vector<openscreen::cast::VideoCaptureConfig> video_configs; + if (video_config) { + video_configs.push_back( + VideoDecoderConfigToVideoCaptureConfig(video_config.value())); + } + + openscreen::Error error = sender_session_->Negotiate( + std::move(audio_configs), std::move(video_configs)); + + if (error == openscreen::Error::None()) { + return true; + } + + LOG(ERROR) << "Failed to start sender session. " << error.ToString(); + sender_session_.reset(); + message_port_.reset(); + return false; +} + +void CastStreamingTestSender::Stop() { + VLOG(1) << __func__; + + sender_session_.reset(); + message_port_.reset(); + audio_sender_ = nullptr; + video_sender_ = nullptr; + audio_decoder_config_.reset(); + video_decoder_config_.reset(); + is_active_ = false; + + if (sender_stopped_closure_) { + std::move(sender_stopped_closure_).Run(); + } +} + +void CastStreamingTestSender::SendAudioBuffer( + scoped_refptr<media::DataBuffer> audio_buffer) { + VLOG(3) << __func__; + CHECK(audio_sender_); + + if (audio_sender_->EnqueueFrame(DataBufferToEncodedFrame( + audio_buffer, true /* is_key_frame */, + audio_sender_->GetNextFrameId(), &last_audio_reference_frame_id_, + audio_sender_->rtp_timebase())) != + openscreen::cast::Sender::EnqueueFrameResult::OK) { + Stop(); + } +} + +void CastStreamingTestSender::SendVideoBuffer( + scoped_refptr<media::DataBuffer> video_buffer, + bool is_key_frame) { + VLOG(3) << __func__; + CHECK(video_sender_); + + if (video_sender_->EnqueueFrame(DataBufferToEncodedFrame( + video_buffer, is_key_frame, video_sender_->GetNextFrameId(), + &last_video_reference_frame_id_, video_sender_->rtp_timebase())) != + openscreen::cast::Sender::EnqueueFrameResult::OK) { + Stop(); + } +} + +void CastStreamingTestSender::RunUntilStarted() { + VLOG(1) << __func__; + while (!is_active_) { + base::RunLoop run_loop; + CHECK(!sender_started_closure_); + sender_started_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + } +} + +void CastStreamingTestSender::RunUntilStopped() { + VLOG(1) << __func__; + while (is_active_) { + base::RunLoop run_loop; + CHECK(!sender_stopped_closure_); + sender_stopped_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + } +} + +void CastStreamingTestSender::OnCastChannelClosed() { + VLOG(1) << __func__; + Stop(); +} + +void CastStreamingTestSender::OnNegotiated( + const openscreen::cast::SenderSession* session, + openscreen::cast::SenderSession::ConfiguredSenders senders, + openscreen::cast::capture_recommendations::Recommendations + capture_recommendations) { + VLOG(1) << __func__; + CHECK_EQ(session, sender_session_.get()); + CHECK(senders.audio_sender || senders.video_sender); + + if (senders.audio_sender) { + audio_sender_ = senders.audio_sender; + audio_decoder_config_ = + AudioCaptureConfigToAudioDecoderConfig(senders.audio_config); + } + + if (senders.video_sender) { + video_sender_ = senders.video_sender; + video_decoder_config_ = + VideoCaptureConfigToVideoDecoderConfig(senders.video_config); + } + + is_active_ = true; + if (sender_started_closure_) { + std::move(sender_started_closure_).Run(); + } +} + +void CastStreamingTestSender::OnError( + const openscreen::cast::SenderSession* session, + openscreen::Error error) { + LOG(ERROR) << "Sender Session error: " << error.ToString(); + CHECK_EQ(session, sender_session_.get()); + Stop(); +} + +} // namespace cast_streaming + +#endif // FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_SENDER_SESSION_TEST_H_
diff --git a/fuchsia/cast_streaming/test/cast_streaming_test_sender.h b/fuchsia/cast_streaming/test/cast_streaming_test_sender.h new file mode 100644 index 0000000..2c27dd2 --- /dev/null +++ b/fuchsia/cast_streaming/test/cast_streaming_test_sender.h
@@ -0,0 +1,122 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_TEST_SENDER_H_ +#define FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_TEST_SENDER_H_ + +#include "base/callback.h" +#include "base/optional.h" +#include "base/sequenced_task_runner.h" +#include "components/cast/message_port/message_port.h" +#include "components/openscreen_platform/task_runner.h" +#include "fuchsia/cast_streaming/test/cast_message_port_sender_impl.h" +#include "media/base/audio_decoder_config.h" +#include "media/base/data_buffer.h" +#include "media/base/video_decoder_config.h" +#include "net/base/ip_address.h" +#include "third_party/openscreen/src/cast/streaming/sender_session.h" + +namespace cast_streaming { + +// Cast Streaming Sender implementation for testing. This class provides basic +// functionality for starting a Cast Streaming Sender and sending audio and +// video frames to a Cast Streaming Receiver. Example usage: +// +// std::unique_ptr<cast_api_bindings::MessagePort> sender_message_port; +// std::unique_ptr<cast_api_bindings::MessagePort> receiver_message_port; +// cast_api_bindings::MessagePort::CreatePair(&sender_message_port, +// &receiver_message_port); +// +// // Send |receiver_message_port| to a Receiver and start it. +// +// CastStreamingTestSender sender; +// if !(sender.Start( +// std::move(sender_message_port), net::IPAddress::IPv6Localhost(), +// audio_config, video_config)) { +// return; +// } +// sender.RunUntilStarted(); +// sender.SendAudioBuffer(audio_buffer); +// sender.SendVideoBuffer(video_buffer); +// sender.Stop(); +// sender.RunUntilStopped(); +class CastStreamingTestSender : public openscreen::cast::SenderSession::Client { + public: + CastStreamingTestSender(); + ~CastStreamingTestSender() final; + + CastStreamingTestSender(const CastStreamingTestSender&) = delete; + CastStreamingTestSender& operator=(const CastStreamingTestSender&) = delete; + + // Uses |message_port| as the Sender-end of a Cast Streaming MessagePort to + // start a Cast Streaming Session with a Cast Streaming Receiver at + // |receiver_address|. At least one of |audio_config| or |video_config| must + // be set. Returns true on success. + bool Start(std::unique_ptr<cast_api_bindings::MessagePort> message_port, + net::IPAddress receiver_address, + base::Optional<media::AudioDecoderConfig> audio_config, + base::Optional<media::VideoDecoderConfig> video_config); + + // Ends the Cast Streaming Session. + void Stop(); + + // Sends |audio_buffer| or |video_buffer| to the Receiver. These can only be + // called when is_active() returns true. + void SendAudioBuffer(scoped_refptr<media::DataBuffer> audio_buffer); + void SendVideoBuffer(scoped_refptr<media::DataBuffer> video_buffer, + bool is_key_frame); + + // After a successful call to Start(), will run until the Cast Streaming + // Sender Session is active. After this call, is_active() will return true + // and at least one of audio_decoder_config() or video_decoder_config() will + // be set. + void RunUntilStarted(); + + // Runs until is_active() returns false. + void RunUntilStopped(); + + bool is_active() const { return is_active_; } + const base::Optional<media::AudioDecoderConfig>& audio_decoder_config() + const { + return audio_decoder_config_; + } + const base::Optional<media::VideoDecoderConfig>& video_decoder_config() + const { + return video_decoder_config_; + } + + private: + void OnCastChannelClosed(); + + // openscreen::cast::SenderSession::Client implementation. + void OnNegotiated(const openscreen::cast::SenderSession* session, + openscreen::cast::SenderSession::ConfiguredSenders senders, + openscreen::cast::capture_recommendations::Recommendations + capture_recommendations) final; + void OnError(const openscreen::cast::SenderSession* session, + openscreen::Error error) final; + + openscreen_platform::TaskRunner task_runner_; + openscreen::cast::Environment environment_; + + std::unique_ptr<openscreen::cast::SenderSession> sender_session_; + std::unique_ptr<CastMessagePortSenderImpl> message_port_; + + openscreen::cast::Sender* audio_sender_ = nullptr; + openscreen::cast::Sender* video_sender_ = nullptr; + openscreen::cast::FrameId last_audio_reference_frame_id_; + openscreen::cast::FrameId last_video_reference_frame_id_; + + bool is_active_ = false; + base::Optional<media::AudioDecoderConfig> audio_decoder_config_; + base::Optional<media::VideoDecoderConfig> video_decoder_config_; + + // Used to implement RunUntilStarted() and RunUntilStopped(). + base::OnceClosure sender_started_closure_; + base::OnceClosure sender_stopped_closure_; +}; + +} // namespace cast_streaming + +#endif // FUCHSIA_CAST_STREAMING_TEST_CAST_STREAMING_TEST_SENDER_H_
diff --git a/fuchsia/runners/cast/api_bindings_client.cc b/fuchsia/runners/cast/api_bindings_client.cc index 809a119d..42c06d1f 100644 --- a/fuchsia/runners/cast/api_bindings_client.cc +++ b/fuchsia/runners/cast/api_bindings_client.cc
@@ -54,6 +54,12 @@ DCHECK(bindings_) << "AttachToFrame() was called before bindings were received."; + if (!bindings_service_) { + LOG(ERROR) << "ApiBindings channel disconnect before attaching Frame."; + std::move(on_error_callback).Run(); + return; + } + connector_ = connector; frame_ = frame;
diff --git a/fuchsia/runners/cast/api_bindings_client_browsertest.cc b/fuchsia/runners/cast/api_bindings_client_browsertest.cc index 16bdc88..d015c5c 100644 --- a/fuchsia/runners/cast/api_bindings_client_browsertest.cc +++ b/fuchsia/runners/cast/api_bindings_client_browsertest.cc
@@ -37,7 +37,8 @@ void SetUp() override { cr_fuchsia::WebEngineBrowserTest::SetUp(); } protected: - void StartClient() { + void StartClient(bool disconnect_before_attach, + base::OnceClosure on_error_closure) { base::ScopedAllowBlockingForTesting allow_blocking; // Get the bindings from |api_service_|. @@ -53,8 +54,13 @@ connector_ = std::make_unique<NamedMessagePortConnectorFuchsia>(frame_.get()); + if (disconnect_before_attach) + api_service_binding_.Unbind(); + + base::RunLoop().RunUntilIdle(); + client_->AttachToFrame(frame_.get(), connector_.get(), - base::MakeExpectedNotRunClosure(FROM_HERE)); + std::move(on_error_closure)); } void SetUpOnMainThread() override { @@ -91,7 +97,7 @@ binding_list.emplace_back(std::move(echo_binding)); api_service_.set_bindings(std::move(binding_list)); - StartClient(); + StartClient(false, base::MakeExpectedNotRunClosure(FROM_HERE)); base::RunLoop post_message_responses_loop; base::RepeatingClosure post_message_response_closure = @@ -143,4 +149,13 @@ post_message_responses_loop.Run(); } +IN_PROC_BROWSER_TEST_F(ApiBindingsClientTest, + ClientDisconnectsBeforeFrameAttached) { + bool error_signaled = false; + StartClient( + true, base::BindOnce([](bool* error_signaled) { *error_signaled = true; }, + base::Unretained(&error_signaled))); + EXPECT_TRUE(error_signaled); +} + } // namespace
diff --git a/google_apis/gaia/oauth2_api_call_flow.h b/google_apis/gaia/oauth2_api_call_flow.h index f9910d6..0684d497 100644 --- a/google_apis/gaia/oauth2_api_call_flow.h +++ b/google_apis/gaia/oauth2_api_call_flow.h
@@ -51,19 +51,22 @@ // with the request. virtual std::string GetRequestTypeForBody(const std::string& body); - // Called when the API call ends to check whether it succeeded, and decide - // which of the following 2 process functions to call. Should be overriden by - // subclasses if the expected success response code is not 200 or 204. + // Called when the API call ends without network error to check whether the + // request succeeded, to decide which of the following 2 process functions to + // call. Should be overriden by subclasses if the expected success response + // code is not 200 or 204. virtual bool IsExpectedSuccessCode(int code) const; // Sub-classes can expose an appropriate observer interface by implementing // these template methods. - // Called when the API call finished successfully. |body| may be null. + // Called when there is no network error and IsExpectedSuccessCode() returns + // true. |body| may be null. virtual void ProcessApiCallSuccess( const network::mojom::URLResponseHead* head, std::unique_ptr<std::string> body) = 0; - // Called when the API call failed. |head| or |body| might be null. + // Called when there is a network error or IsExpectedSuccessCode() returns + // false. |head| or |body| might be null. virtual void ProcessApiCallFailure( int net_error, const network::mojom::URLResponseHead* head,
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index b3e8582c..1eb384ea 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -285,12 +285,12 @@ std::unique_ptr<content::WebContents> web_contents, HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents.get()), + browser_context_(browser_context), + render_process_host_(web_contents->GetMainFrame()->GetProcess()), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(std::move(web_contents)), agent_host_( - content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())), - browser_context_(browser_context), - render_process_host_(web_contents_->GetMainFrame()->GetProcess()) { + content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())) { #if BUILDFLAG(ENABLE_PRINTING) HeadlessPrintManager::CreateForWebContents(web_contents_.get()); // TODO(weili): Add support for printing OOPIFs.
diff --git a/headless/lib/browser/headless_web_contents_impl.h b/headless/lib/browser/headless_web_contents_impl.h index 3281913..ee3d0fe0 100644 --- a/headless/lib/browser/headless_web_contents_impl.h +++ b/headless/lib/browser/headless_web_contents_impl.h
@@ -141,6 +141,11 @@ viz::BeginFrameArgs::kStartingFrameNumber; bool begin_frame_control_enabled_ = false; + HeadlessBrowserContextImpl* browser_context_; // Not owned. + // TODO(alexclarke): With OOPIF there may be more than one renderer, we need + // to fix this. See crbug.com/715924 + content::RenderProcessHost* render_process_host_; // Not owned. + class Delegate; std::unique_ptr<Delegate> web_contents_delegate_; std::unique_ptr<HeadlessWindowTreeHost> window_tree_host_; @@ -151,11 +156,6 @@ bool devtools_target_ready_notification_sent_ = false; bool render_process_exited_ = false; - HeadlessBrowserContextImpl* browser_context_; // Not owned. - // TODO(alexclarke): With OOPIF there may be more than one renderer, we need - // to fix this. See crbug.com/715924 - content::RenderProcessHost* render_process_host_; // Not owned. - base::ObserverList<HeadlessWebContents::Observer>::Unchecked observers_; class PendingFrame;
diff --git a/infra/config/generated/commit-queue.cfg b/infra/config/generated/commit-queue.cfg index 47c487d..ba8feed 100644 --- a/infra/config/generated/commit-queue.cfg +++ b/infra/config/generated/commit-queue.cfg
@@ -897,17 +897,6 @@ location_regexp_exclude: ".+/[+]/infra/config/.+" } builders { - name: "chromium/try/ios-simulator-code-coverage" - includable_only: true - } - builders { - name: "chromium/try/ios-simulator-coverage-exp" - experiment_percentage: 3 - location_regexp: ".*" - location_regexp_exclude: ".+/[+]/docs/.+" - location_regexp_exclude: ".+/[+]/infra/config/.+" - } - builders { name: "chromium/try/ios-simulator-cronet" location_regexp: ".+/[+]/components/cronet/.+" location_regexp: ".+/[+]/components/grpc_support/.+" @@ -923,13 +912,6 @@ location_regexp_exclude: ".+/[+]/infra/config/.+" } builders { - name: "chromium/try/ios-simulator-full-configs-coverage-exp" - experiment_percentage: 3 - location_regexp: ".+/[+]/ios/.+" - location_regexp_exclude: ".+/[+]/docs/.+" - location_regexp_exclude: ".+/[+]/infra/config/.+" - } - builders { name: "chromium/try/ios-simulator-multi-window" includable_only: true }
diff --git a/infra/config/generated/cq-builders.md b/infra/config/generated/cq-builders.md index 2985486c..b31dc6bf 100644 --- a/infra/config/generated/cq-builders.md +++ b/infra/config/generated/cq-builders.md
@@ -373,15 +373,6 @@ by CQ. These are often used to test new configurations before they are added as required builders. -* [ios-simulator-coverage-exp](https://ci.chromium.org/p/chromium/builders/try/ios-simulator-coverage-exp) ([definition](https://cs.chromium.org/search?q=package:%5Echromium$+file:/cq.star$+-file:/beta/+-file:/stable/+ios-simulator-coverage-exp)) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+ios-simulator-coverage-exp)) - * Experiment percentage: 3 - -* [ios-simulator-full-configs-coverage-exp](https://ci.chromium.org/p/chromium/builders/try/ios-simulator-full-configs-coverage-exp) ([definition](https://cs.chromium.org/search?q=package:%5Echromium$+file:/cq.star$+-file:/beta/+-file:/stable/+ios-simulator-full-configs-coverage-exp)) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+ios-simulator-full-configs-coverage-exp)) - * Experiment percentage: 3 - - Path regular expressions: - * [`//ios/.+`](https://cs.chromium.org/chromium/src/ios/) - * [linux-perfetto-rel](https://ci.chromium.org/p/chromium/builders/try/linux-perfetto-rel) ([definition](https://cs.chromium.org/search?q=package:%5Echromium$+file:/cq.star$+-file:/beta/+-file:/stable/+linux-perfetto-rel)) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+linux-perfetto-rel)) * Experiment percentage: 100
diff --git a/infra/config/generated/cr-buildbucket.cfg b/infra/config/generated/cr-buildbucket.cfg index 51105ee..4d48d142 100644 --- a/infra/config/generated/cr-buildbucket.cfg +++ b/infra/config/generated/cr-buildbucket.cfg
@@ -32047,120 +32047,6 @@ } } builders { - name: "ios-simulator-code-coverage" - swarming_host: "chromium-swarm.appspot.com" - swarming_tags: "vpython:native-python-wrapper" - dimensions: "builder:ios-simulator-code-coverage" - dimensions: "cpu:x86-64" - dimensions: "os:Mac-10.15" - dimensions: "pool:luci.chromium.try" - exe { - cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" - cipd_version: "refs/heads/master" - cmd: "recipes" - } - properties: "{\"$build/code_coverage\":{\"coverage_exclude_sources\":\"ios_test_files_and_test_utils\",\"coverage_test_types\":[\"unit\"],\"use_clang_coverage\":true},\"$build/goma\":{\"rpc_extra_params\":\"?prod\",\"server_host\":\"goma.chromium.org\",\"use_luci_auth\":true},\"$kitchen\":{\"devshell\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"tryserver.chromium.mac\",\"recipe\":\"chromium_trybot\",\"xcode_build_version\":\"12a7209\"}" - execution_timeout_secs: 14400 - expiration_secs: 7200 - caches { - name: "win_toolchain" - path: "win_toolchain" - } - caches { - name: "xcode_ios_12a7209" - path: "xcode_ios_12a7209.app" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium.resultdb.result_sink" - value: 100 - } - experiments { - key: "luci.use_realms" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" - } - } - } - } - } - builders { - name: "ios-simulator-coverage-exp" - swarming_host: "chromium-swarm.appspot.com" - swarming_tags: "vpython:native-python-wrapper" - dimensions: "builder:ios-simulator-coverage-exp" - dimensions: "cpu:x86-64" - dimensions: "os:Mac-10.15" - dimensions: "pool:luci.chromium.try" - exe { - cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" - cipd_version: "refs/heads/master" - cmd: "recipes" - } - properties: "{\"$build/code_coverage\":{\"coverage_exclude_sources\":\"ios_test_files_and_test_utils\",\"coverage_test_types\":[\"unit\"],\"use_clang_coverage\":true},\"$build/goma\":{\"rpc_extra_params\":\"?prod\",\"server_host\":\"goma.chromium.org\",\"use_luci_auth\":true},\"$kitchen\":{\"devshell\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"tryserver.chromium.mac\",\"recipe\":\"chromium_trybot\",\"xcode_build_version\":\"12a7209\"}" - execution_timeout_secs: 14400 - expiration_secs: 7200 - caches { - name: "win_toolchain" - path: "win_toolchain" - } - caches { - name: "xcode_ios_12a7209" - path: "xcode_ios_12a7209.app" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium.resultdb.result_sink" - value: 100 - } - experiments { - key: "luci.use_realms" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" - } - } - } - } - } - builders { name: "ios-simulator-cronet" swarming_host: "chromium-swarm.appspot.com" swarming_tags: "vpython:native-python-wrapper" @@ -32275,63 +32161,6 @@ } } builders { - name: "ios-simulator-full-configs-coverage-exp" - swarming_host: "chromium-swarm.appspot.com" - swarming_tags: "vpython:native-python-wrapper" - dimensions: "builder:ios-simulator-full-configs-coverage-exp" - dimensions: "cpu:x86-64" - dimensions: "os:Mac-10.15" - dimensions: "pool:luci.chromium.try" - exe { - cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" - cipd_version: "refs/heads/master" - cmd: "recipes" - } - properties: "{\"$build/code_coverage\":{\"coverage_exclude_sources\":\"ios_test_files_and_test_utils\",\"coverage_test_types\":[\"unit\"],\"use_clang_coverage\":true},\"$build/goma\":{\"rpc_extra_params\":\"?prod\",\"server_host\":\"goma.chromium.org\",\"use_luci_auth\":true},\"$kitchen\":{\"devshell\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"tryserver.chromium.mac\",\"recipe\":\"chromium_trybot\",\"xcode_build_version\":\"12a7209\"}" - execution_timeout_secs: 14400 - expiration_secs: 7200 - caches { - name: "win_toolchain" - path: "win_toolchain" - } - caches { - name: "xcode_ios_12a7209" - path: "xcode_ios_12a7209.app" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium.resultdb.result_sink" - value: 100 - } - experiments { - key: "luci.use_realms" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "luci-resultdb" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" - } - } - } - } - } - builders { name: "ios-simulator-multi-window" swarming_host: "chromium-swarm.appspot.com" swarming_tags: "vpython:native-python-wrapper"
diff --git a/infra/config/generated/goma-usage.pyl b/infra/config/generated/goma-usage.pyl index eeddbc84..d90300f 100644 --- a/infra/config/generated/goma-usage.pyl +++ b/infra/config/generated/goma-usage.pyl
@@ -3,9 +3,9 @@ # This is consumed by presubmit checks that need to validate the config { - # 61550 (scheduler total) + 344990 (weighted CQ total) - # (weighted CQ total) = 6899.8 (CQ total) * 50 (CQ weight) - '*weighted total*': 406540, + # 61550 (scheduler total) + 344750 (weighted CQ total) + # (weighted CQ total) = 6895 (CQ total) * 50 (CQ weight) + '*weighted total*': 406300, 'scheduler': { '*total*': 61550, 'triggered': { @@ -545,7 +545,7 @@ }, }, 'cq': { - '*total*': 6899.8, + '*total*': 6895, 'try/android-binary-size': 150, 'try/android-cronet-arm-dbg': 80, 'try/android-lollipop-arm-rel': 150, @@ -580,16 +580,10 @@ 'try/fuchsia_x64': 80, # jobs count assumes an 8-core machine 'try/ios-simulator': 80, - # 80 jobs x 3% experiment - # jobs count assumes an 8-core machine - 'try/ios-simulator-coverage-exp': 2.4, # jobs count assumes an 8-core machine 'try/ios-simulator-cronet': 80, # jobs count assumes an 8-core machine 'try/ios-simulator-full-configs': 80, - # 80 jobs x 3% experiment - # jobs count assumes an 8-core machine - 'try/ios-simulator-full-configs-coverage-exp': 2.4, 'try/linux-blink-rel': 80, 'try/linux-chromeos-compile-dbg': 80, 'try/linux-chromeos-rel': 150,
diff --git a/infra/config/generated/luci-milo.cfg b/infra/config/generated/luci-milo.cfg index 4c0782fc..5289574 100644 --- a/infra/config/generated/luci-milo.cfg +++ b/infra/config/generated/luci-milo.cfg
@@ -11979,21 +11979,12 @@ name: "buildbucket/luci.chromium.try/ios-simulator" } builders { - name: "buildbucket/luci.chromium.try/ios-simulator-code-coverage" - } - builders { - name: "buildbucket/luci.chromium.try/ios-simulator-coverage-exp" - } - builders { name: "buildbucket/luci.chromium.try/ios-simulator-cronet" } builders { name: "buildbucket/luci.chromium.try/ios-simulator-full-configs" } builders { - name: "buildbucket/luci.chromium.try/ios-simulator-full-configs-coverage-exp" - } - builders { name: "buildbucket/luci.chromium.try/ios-simulator-multi-window" } builders { @@ -13114,21 +13105,12 @@ name: "buildbucket/luci.chromium.try/ios-simulator" } builders { - name: "buildbucket/luci.chromium.try/ios-simulator-code-coverage" - } - builders { - name: "buildbucket/luci.chromium.try/ios-simulator-coverage-exp" - } - builders { name: "buildbucket/luci.chromium.try/ios-simulator-cronet" } builders { name: "buildbucket/luci.chromium.try/ios-simulator-full-configs" } builders { - name: "buildbucket/luci.chromium.try/ios-simulator-full-configs-coverage-exp" - } - builders { name: "buildbucket/luci.chromium.try/ios-simulator-multi-window" } builders {
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index 99feda62..04c3d0d5 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -1356,23 +1356,6 @@ ) try_.chromium_mac_ios_builder( - name = "ios-simulator-code-coverage", - use_clang_coverage = True, - coverage_exclude_sources = "ios_test_files_and_test_utils", - coverage_test_types = ["unit"], - os = os.MAC_10_15, -) - -try_.chromium_mac_ios_builder( - name = "ios-simulator-coverage-exp", - use_clang_coverage = True, - coverage_exclude_sources = "ios_test_files_and_test_utils", - coverage_test_types = ["unit"], - os = os.MAC_10_15, - tryjob = try_.job(experiment_percentage = 3), -) - -try_.chromium_mac_ios_builder( name = "ios-simulator-cronet", branch_selector = branches.STANDARD_MILESTONE, main_list_view = "try", @@ -1404,20 +1387,6 @@ ) try_.chromium_mac_ios_builder( - name = "ios-simulator-full-configs-coverage-exp", - use_clang_coverage = True, - coverage_exclude_sources = "ios_test_files_and_test_utils", - coverage_test_types = ["unit"], - os = os.MAC_10_15, - tryjob = try_.job( - experiment_percentage = 3, - location_regexp = [ - ".+/[+]/ios/.+", - ], - ), -) - -try_.chromium_mac_ios_builder( name = "ios-simulator-multi-window", )
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h index 080a177d..7552028 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h
@@ -26,7 +26,7 @@ @interface SigninPromoView : UIView @property(nonatomic, weak) id<SigninPromoViewDelegate> delegate; -@property(nonatomic) SigninPromoViewMode mode; +@property(nonatomic) IdentityPromoViewMode mode; @property(nonatomic, readonly) UIImageView* imageView; @property(nonatomic, readonly) UILabel* textLabel; @property(nonatomic, readonly) UIButton* primaryButton;
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm index ab635991..8e08c98 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm
@@ -202,8 +202,8 @@ constraintEqualToConstant:kCloseButtonWidthHeight], ]]; // Default mode. - _mode = SigninPromoViewModeColdState; - [self activateColdMode]; + _mode = IdentityPromoViewModeNoAccounts; + [self activateNoAccountsMode]; } return self; } @@ -212,24 +212,24 @@ _delegate = nil; } -- (void)setMode:(SigninPromoViewMode)mode { +- (void)setMode:(IdentityPromoViewMode)mode { if (mode == _mode) { return; } _mode = mode; switch (_mode) { - case SigninPromoViewModeColdState: - [self activateColdMode]; + case IdentityPromoViewModeNoAccounts: + [self activateNoAccountsMode]; return; - case SigninPromoViewModeWarmState: - [self activateWarmMode]; + case IdentityPromoViewModeSigninWithAccount: + [self activateSigninWithAccountMode]; return; } NOTREACHED(); } -- (void)activateColdMode { - DCHECK_EQ(_mode, SigninPromoViewModeColdState); +- (void)activateNoAccountsMode { + DCHECK_EQ(_mode, IdentityPromoViewModeNoAccounts); UIImage* logo = nil; #if BUILDFLAG(GOOGLE_CHROME_BRANDING) logo = [UIImage imageNamed:@"signin_promo_logo_chrome_color"]; @@ -241,13 +241,13 @@ _secondaryButton.hidden = YES; } -- (void)activateWarmMode { - DCHECK_EQ(_mode, SigninPromoViewModeWarmState); +- (void)activateSigninWithAccountMode { + DCHECK_EQ(_mode, IdentityPromoViewModeSigninWithAccount); _secondaryButton.hidden = NO; } - (void)setProfileImage:(UIImage*)image { - DCHECK_EQ(SigninPromoViewModeWarmState, _mode); + DCHECK_EQ(IdentityPromoViewModeSigninWithAccount, _mode); self.imageView.image = CircularImageFromImage(image, kProfileImageFixedSize); } @@ -270,10 +270,10 @@ - (void)onPrimaryButtonAction:(id)unused { switch (_mode) { - case SigninPromoViewModeColdState: + case IdentityPromoViewModeNoAccounts: [_delegate signinPromoViewDidTapSigninWithNewAccount:self]; break; - case SigninPromoViewModeWarmState: + case IdentityPromoViewModeSigninWithAccount: [_delegate signinPromoViewDidTapSigninWithDefaultAccount:self]; break; } @@ -297,7 +297,7 @@ - (NSArray<UIAccessibilityCustomAction*>*)accessibilityCustomActions { NSMutableArray* actions = [NSMutableArray array]; - if (_mode == SigninPromoViewModeWarmState) { + if (_mode == IdentityPromoViewModeSigninWithAccount) { NSString* secondaryActionName = [self.secondaryButton titleForState:UIControlStateNormal]; UIAccessibilityCustomAction* secondaryCustomAction =
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_configurator.mm b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_configurator.mm index 9a7f3a0..d271710d 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_configurator.mm +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_configurator.mm
@@ -63,14 +63,14 @@ - (void)configureSigninPromoView:(SigninPromoView*)signinPromoView { signinPromoView.closeButton.hidden = !self.hasCloseButton; if (!self.userEmail) { - signinPromoView.mode = SigninPromoViewModeColdState; + signinPromoView.mode = IdentityPromoViewModeNoAccounts; NSString* signInString = GetNSString(IDS_IOS_OPTIONS_IMPORT_DATA_TITLE_SIGNIN); signinPromoView.accessibilityLabel = signInString; [signinPromoView.primaryButton setTitle:signInString forState:UIControlStateNormal]; } else { - signinPromoView.mode = SigninPromoViewModeWarmState; + signinPromoView.mode = IdentityPromoViewModeSigninWithAccount; NSString* name = self.userFullName.length ? self.userFullName : self.userEmail; base::string16 name16 = SysNSStringToUTF16(name);
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_constants.h b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_constants.h index cbb7da9..dd618918 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_constants.h +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_constants.h
@@ -7,12 +7,12 @@ #import <Foundation/Foundation.h> -typedef NS_ENUM(NSInteger, SigninPromoViewMode) { +typedef NS_ENUM(NSInteger, IdentityPromoViewMode) { // No identity available on the device. - SigninPromoViewModeColdState, - // At least one identity is available on the device and the user can sign + IdentityPromoViewModeNoAccounts, + // At least one identity is available on the device and the user can sign in // without entering their credentials. - SigninPromoViewModeWarmState, + IdentityPromoViewModeSigninWithAccount, }; extern NSString* const kSigninPromoViewId;
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_unittest.mm b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_unittest.mm index c65abfa..6730eef 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view_unittest.mm +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view_unittest.mm
@@ -20,11 +20,11 @@ UIWindow* currentWindow = [[UIApplication sharedApplication] keyWindow]; SigninPromoView* view = [[SigninPromoView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; - view.mode = SigninPromoViewModeColdState; + view.mode = IdentityPromoViewModeNoAccounts; [currentWindow.rootViewController.view addSubview:view]; UIImage* chromiumLogo = view.imageView.image; EXPECT_NE(nil, chromiumLogo); - view.mode = SigninPromoViewModeWarmState; + view.mode = IdentityPromoViewModeSigninWithAccount; UIImage* customImage = [[UIImage alloc] init]; [view setProfileImage:customImage]; EXPECT_NE(nil, view.imageView.image); @@ -39,9 +39,9 @@ UIWindow* currentWindow = [[UIApplication sharedApplication] keyWindow]; SigninPromoView* view = [[SigninPromoView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; - view.mode = SigninPromoViewModeColdState; + view.mode = IdentityPromoViewModeNoAccounts; [currentWindow.rootViewController.view addSubview:view]; EXPECT_TRUE(view.secondaryButton.hidden); - view.mode = SigninPromoViewModeWarmState; + view.mode = IdentityPromoViewModeSigninWithAccount; EXPECT_FALSE(view.secondaryButton.hidden); }
diff --git a/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.h b/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.h index 2a9807c..6aedbf8 100644 --- a/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.h +++ b/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.h
@@ -64,12 +64,12 @@ // Checks that the sign-in promo view (with a close button) is visible using the // right mode. -+ (void)verifySigninPromoVisibleWithMode:(SigninPromoViewMode)mode; ++ (void)verifySigninPromoVisibleWithMode:(IdentityPromoViewMode)mode; // Checks that the sign-in promo view is visible using the right mode. If // |closeButton| is set to YES, the close button in the sign-in promo has to be // visible. -+ (void)verifySigninPromoVisibleWithMode:(SigninPromoViewMode)mode ++ (void)verifySigninPromoVisibleWithMode:(IdentityPromoViewMode)mode closeButton:(BOOL)closeButton; // Checks that the sign-in promo view is not visible.
diff --git a/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.mm b/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.mm index 2479459..94b45f9 100644 --- a/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.mm +++ b/ios/chrome/browser/ui/authentication/signin_earl_grey_ui.mm
@@ -146,11 +146,11 @@ [[EarlGrey selectElementWithMatcher:buttonMatcher] performAction:grey_tap()]; } -+ (void)verifySigninPromoVisibleWithMode:(SigninPromoViewMode)mode { ++ (void)verifySigninPromoVisibleWithMode:(IdentityPromoViewMode)mode { [self verifySigninPromoVisibleWithMode:mode closeButton:YES]; } -+ (void)verifySigninPromoVisibleWithMode:(SigninPromoViewMode)mode ++ (void)verifySigninPromoVisibleWithMode:(IdentityPromoViewMode)mode closeButton:(BOOL)closeButton { [ChromeEarlGreyUI waitForAppToIdle]; @@ -167,13 +167,13 @@ grey_sufficientlyVisible(), nil)] assertWithMatcher:grey_notNil()]; switch (mode) { - case SigninPromoViewModeColdState: + case IdentityPromoViewModeNoAccounts: [[EarlGrey selectElementWithMatcher:grey_allOf(SecondarySignInButton(), grey_sufficientlyVisible(), nil)] assertWithMatcher:grey_nil()]; break; - case SigninPromoViewModeWarmState: + case IdentityPromoViewModeSigninWithAccount: if (![ChromeEarlGrey isIllustratedEmptyStatesEnabled]) { [[EarlGrey selectElementWithMatcher:grey_allOf(SecondarySignInButton(),
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm index bcee967..d14bc37 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm
@@ -84,21 +84,22 @@ ->AddIdentity(expected_default_identity_); } - // Tests the mediator as a cold state with a new created configurator. - void TestColdState() { + // Tests the mediator with a new created configurator when no accounts are on + // the device. + void TestSigninPromoWithNoAccounts() { EXPECT_EQ(nil, mediator_.defaultIdentity); - CheckColdStateConfigurator([mediator_ createConfigurator]); + CheckNoAccountsConfigurator([mediator_ createConfigurator]); } - // Adds an identity and tests the mediator as a warm state. - void TestWarmState() { + // Adds an identity and tests the mediator. + void TestSigninPromoWithAccount() { // Expect to receive an update to the consumer with a configurator. ExpectConfiguratorNotification(YES /* identity changed */); AddDefaultIdentity(); // Check the configurator received by the consumer. - CheckWarmStateConfigurator(configurator_); + CheckSigninWithAccountConfigurator(configurator_); // Check a new created configurator. - CheckWarmStateConfigurator([mediator_ createConfigurator]); + CheckSigninWithAccountConfigurator([mediator_ createConfigurator]); // The consumer should receive a notification related to the image. CheckForImageNotification(); } @@ -117,28 +118,31 @@ identityChanged:identity_changed]); } - // Expects the signin promo view to be configured in a cold state. - void ExpectColdStateConfiguration() { - OCMExpect([signin_promo_view_ setMode:SigninPromoViewModeColdState]); + // Expects the signin promo view to be configured with no accounts on the + // device. + void ExpectNoAccountsConfiguration() { + OCMExpect([signin_promo_view_ setMode:IdentityPromoViewModeNoAccounts]); NSString* title = GetNSString(IDS_IOS_OPTIONS_IMPORT_DATA_TITLE_SIGNIN); OCMExpect([signin_promo_view_ setAccessibilityLabel:title]); OCMExpect([primary_button_ setTitle:title forState:UIControlStateNormal]); image_view_profile_image_ = nil; } - // Checks a cold state configurator. - void CheckColdStateConfigurator(SigninPromoViewConfigurator* configurator) { + // Checks a configurator with no accounts on the device. + void CheckNoAccountsConfigurator(SigninPromoViewConfigurator* configurator) { EXPECT_NE(nil, configurator); - ExpectColdStateConfiguration(); + ExpectNoAccountsConfiguration(); OCMExpect([close_button_ setHidden:close_button_hidden_]); [configurator configureSigninPromoView:signin_promo_view_]; EXPECT_EQ(nil, image_view_profile_image_); } - // Expects the signin promo view to be configured in a warm state. - void ExpectWarmStateConfiguration() { + // Expects the signin promo view to be configured when accounts are on the + // device. + void ExpectSigninWithAccountConfiguration() { EXPECT_EQ(expected_default_identity_, mediator_.defaultIdentity); - OCMExpect([signin_promo_view_ setMode:SigninPromoViewModeWarmState]); + OCMExpect( + [signin_promo_view_ setMode:IdentityPromoViewModeSigninWithAccount]); OCMExpect([signin_promo_view_ setProfileImage:[OCMArg checkWithBlock:^BOOL(id value) { image_view_profile_image_ = value; @@ -159,10 +163,11 @@ forState:UIControlStateNormal]); } - // Checks a warm state configurator. - void CheckWarmStateConfigurator(SigninPromoViewConfigurator* configurator) { + // Checks a configurator with accounts on the device. + void CheckSigninWithAccountConfigurator( + SigninPromoViewConfigurator* configurator) { EXPECT_NE(nil, configurator); - ExpectWarmStateConfiguration(); + ExpectSigninWithAccountConfiguration(); OCMExpect([close_button_ setHidden:YES]); [configurator configureSigninPromoView:signin_promo_view_]; EXPECT_NE(nil, image_view_profile_image_); @@ -176,7 +181,7 @@ EXPECT_TRUE(ios::FakeChromeIdentityService::GetInstanceFromChromeProvider() ->WaitForServiceCallbacksToComplete()); // Check the configurator received by the consumer. - CheckWarmStateConfigurator(configurator_); + CheckSigninWithAccountConfigurator(configurator_); } // Mediator used for the tests. @@ -184,7 +189,7 @@ // User full name for the identity; NSString* user_full_name_; - // Identity used for the warm state. + // Identity used for sign-in. FakeChromeIdentity* expected_default_identity_; // Configurator received from the consumer. @@ -203,48 +208,49 @@ BOOL close_button_hidden_; }; -// Tests signin promo view and its configurator in cold state. -TEST_F(SigninPromoViewMediatorTest, ColdStateConfigureSigninPromoView) { +// Tests signin promo view and its configurator with no accounts on the device. +TEST_F(SigninPromoViewMediatorTest, NoAccountsConfigureSigninPromoView) { CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS); - TestColdState(); + TestSigninPromoWithNoAccounts(); } -// Tests signin promo view and its configurator in cold state in settings view. +// Tests signin promo view and its configurator settings view with no accounts +// on the device. TEST_F(SigninPromoViewMediatorTest, - ColdStateConfigureSigninPromoViewFromSettings) { + NoAccountsConfigureSigninPromoViewFromSettings) { close_button_hidden_ = NO; CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); - TestColdState(); + TestSigninPromoWithNoAccounts(); } -// Tests signin promo view and its configurator in warm state. -TEST_F(SigninPromoViewMediatorTest, WarmStateConfigureSigninPromoView) { +// Tests signin promo view and its configurator with accounts on the device. +TEST_F(SigninPromoViewMediatorTest, SigninWithAccountConfigureSigninPromoView) { CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS); - TestWarmState(); + TestSigninPromoWithAccount(); } -// Tests signin promo view and its configurator in warm state, with an identity +// Tests signin promo view and its configurator with an identity // without full name. TEST_F(SigninPromoViewMediatorTest, - WarmStateConfigureSigninPromoViewWithoutFullName) { + SigninWithAccountConfigureSigninPromoViewWithoutFullName) { user_full_name_ = nil; CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS); - TestWarmState(); + TestSigninPromoWithAccount(); } -// Tests the scenario with the sign-in promo in cold state, and then adding an -// identity to update the view in warm state. +// Tests the scenario with the sign-in promo when no accounts on the device, and +// then add an identity to update the view. TEST_F(SigninPromoViewMediatorTest, ConfigureSigninPromoViewWithColdAndWarm) { CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS); - TestColdState(); - TestWarmState(); + TestSigninPromoWithNoAccounts(); + TestSigninPromoWithAccount(); } -// Tests the scenario with the sign-in promo in warm state, and then removing -// the identity to update the view in cold state. +// Tests the scenario with the sign-in promo with accounts on the device, and +// then removing the identity to update the view. TEST_F(SigninPromoViewMediatorTest, ConfigureSigninPromoViewWithWarmAndCold) { CreateMediator(signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS); - TestWarmState(); + TestSigninPromoWithAccount(); // Expect to receive a new configuration from -[Consumer // configureSigninPromoWithConfigurator:identityChanged:]. ExpectConfiguratorNotification(YES /* identity changed */); @@ -252,7 +258,7 @@ ->ForgetIdentity(expected_default_identity_, nil); expected_default_identity_ = nil; // Check the received configurator. - CheckColdStateConfigurator(configurator_); + CheckNoAccountsConfigurator(configurator_); } // Tests the view state before and after calling -[SigninPromoViewMediator
diff --git a/ios/chrome/browser/ui/bookmarks/bookmarks_promo_egtest.mm b/ios/chrome/browser/ui/bookmarks/bookmarks_promo_egtest.mm index 832e508f..fa0adc71 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmarks_promo_egtest.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmarks_promo_egtest.mm
@@ -66,7 +66,7 @@ // Check that sign-in promo view is visible. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Go to child node. [BookmarkEarlGreyUI openMobileBookmarks]; @@ -99,7 +99,7 @@ // Check that sign-in promo view is visible. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Tap the dismiss button. [[EarlGrey @@ -124,7 +124,7 @@ // Check that sign-in promo view are visible. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Tap the primary button. [[EarlGrey @@ -139,7 +139,7 @@ // Check that the bookmarks UI reappeared and the cell is still here. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; } // Tests the tapping on the primary button of sign-in promo view in a warm @@ -155,7 +155,7 @@ // Check that promo is visible. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; // Tap the primary button. [[EarlGrey @@ -170,7 +170,7 @@ // Check that the bookmarks UI reappeared and the cell is still here. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; } @@ -188,7 +188,7 @@ // Check that sign-in promo view are visible. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; // Tap the secondary button. [[EarlGrey @@ -207,7 +207,7 @@ // Check that the bookmarks UI reappeared and the cell is still here. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; } // Tests that the sign-in promo should not be shown after been shown 19 times. @@ -216,7 +216,7 @@ [BookmarkEarlGreyUI openBookmarks]; // Check the sign-in promo view is visible. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Check the sign-in promo already-seen state didn't change. [BookmarkEarlGrey verifyPromoAlreadySeen:NO]; GREYAssertEqual(20, [BookmarkEarlGrey numberOfTimesPromoAlreadySeen],
diff --git a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios_unittest.mm b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios_unittest.mm index 3624eb3..9f368ab 100644 --- a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios_unittest.mm +++ b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios_unittest.mm
@@ -138,7 +138,13 @@ [textfield_ resignFirstResponder]; } -TEST_F(OmniboxTextFieldTest, SelectedRanges) { +// TODO:(crbug.com/1156541): Re-enable this test on devices. +#if TARGET_OS_SIMULATOR +#define MAYBE_SelectedRanges SelectedRanges +#else +#define MAYBE_SelectedRanges FLAKY_SelectedRanges +#endif +TEST_F(OmniboxTextFieldTest, MAYBE_SelectedRanges) { base::FilePath test_data_directory; ASSERT_TRUE(base::PathService::Get(ios::DIR_TEST_DATA, &test_data_directory)); base::FilePath test_file = test_data_directory.Append(
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_egtest.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_egtest.mm index 4ddfb11..5a25ae5 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_egtest.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_egtest.mm
@@ -174,15 +174,15 @@ grey_sufficientlyVisible(), nil)] performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)]; - // Sign-in promo should be visible with cold state. + // Sign-in promo should be visible with no accounts on the device. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts closeButton:NO]; FakeChromeIdentity* fakeIdentity = [SigninEarlGrey fakeIdentity1]; [SigninEarlGrey addFakeIdentity:fakeIdentity]; - // Sign-in promo should be visible with warm state. + // Sign-in promo should be visible with an account on the device. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount closeButton:NO]; [self closeRecentTabs]; [SigninEarlGrey forgetFakeIdentity:fakeIdentity]; @@ -200,7 +200,7 @@ performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts closeButton:NO]; // Tap on "Other Devices", to hide the sign-in promo. @@ -226,7 +226,7 @@ grey_sufficientlyVisible(), nil)] performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount closeButton:NO]; [self closeRecentTabs]; [SigninEarlGrey forgetFakeIdentity:fakeIdentity]; @@ -314,7 +314,7 @@ performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts closeButton:NO]; }
diff --git a/ios/chrome/browser/ui/settings/language/language_settings_mediator_unittest.mm b/ios/chrome/browser/ui/settings/language/language_settings_mediator_unittest.mm index fdd706f..e167860 100644 --- a/ios/chrome/browser/ui/settings/language/language_settings_mediator_unittest.mm +++ b/ios/chrome/browser/ui/settings/language/language_settings_mediator_unittest.mm
@@ -207,7 +207,7 @@ TEST_F(LanguageSettingsMediatorTest, TestAcceptLanguagesItems) { translate_prefs()->AddToLanguageList("fa", /*force_blocked=*/false); translate_prefs()->AddToLanguageList("en-US", /*force_blocked=*/false); - translate_prefs()->AddToLanguageList("ug", /*force_blocked=*/false); + translate_prefs()->AddToLanguageList("to", /*force_blocked=*/false); translate_prefs()->SetRecentTargetLanguage("fa"); translate_prefs()->UnblockLanguage("en-US"); @@ -225,7 +225,7 @@ EXPECT_FALSE(acceptLanguagesItems[1].targetLanguage); EXPECT_FALSE(acceptLanguagesItems[1].blocked); - EXPECT_EQ("ug", acceptLanguagesItems[2].languageCode); + EXPECT_EQ("to", acceptLanguagesItems[2].languageCode); EXPECT_FALSE(acceptLanguagesItems[2].supportsTranslate); EXPECT_FALSE(acceptLanguagesItems[2].targetLanguage); EXPECT_TRUE(acceptLanguagesItems[2].blocked);
diff --git a/ios/chrome/browser/ui/settings/signin_settings_egtest.mm b/ios/chrome/browser/ui/settings/signin_settings_egtest.mm index 4eb24d8..ef92813 100644 --- a/ios/chrome/browser/ui/settings/signin_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/signin_settings_egtest.mm
@@ -36,11 +36,11 @@ @implementation SigninSettingsTestCase -// Tests the primary button with a cold state. -- (void)testSignInPromoWithColdStateUsingPrimaryButton { +// Tests the primary button with no accounts on the device. +- (void)testSignInPromoWithNoAccountsOnDeviceUsingPrimaryButton { [ChromeEarlGreyUI openSettingsMenu]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; [ChromeEarlGreyUI tapSettingsMenuButton:PrimarySignInButton()]; // Cancel the sign-in operation. @@ -48,17 +48,17 @@ kSkipSigninAccessibilityIdentifier)] performAction:grey_tap()]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; } -// Tests signing in, using the primary button with a warm state. -- (void)testSignInPromoWithWarmStateUsingPrimaryButton { +// Tests signing in, using the primary button with one account on the device. +- (void)testSignInPromoWithAccountUsingPrimaryButton { FakeChromeIdentity* fakeIdentity = [SigninEarlGrey fakeIdentity1]; [SigninEarlGrey addFakeIdentity:fakeIdentity]; [ChromeEarlGreyUI openSettingsMenu]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; [ChromeEarlGreyUI tapSettingsMenuButton:PrimarySignInButton()]; [SigninEarlGreyUI tapSigninConfirmationDialog]; @@ -69,14 +69,14 @@ assertWithMatcher:grey_interactable()]; } -// Tests signing in, using the secondary button with a warm state. +// Tests signing in, using the secondary button with one account on the device. - (void)testSignInPromoWithWarmStateUsingSecondaryButton { FakeChromeIdentity* fakeIdentity = [SigninEarlGrey fakeIdentity1]; [SigninEarlGrey addFakeIdentity:fakeIdentity]; [ChromeEarlGreyUI openSettingsMenu]; [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeWarmState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeSigninWithAccount]; [ChromeEarlGreyUI tapSettingsMenuButton:SecondarySignInButton()]; [SigninEarlGreyUI selectIdentityWithEmail:fakeIdentity.userEmail]; [SigninEarlGreyUI tapSigninConfirmationDialog]; @@ -96,7 +96,7 @@ [ChromeEarlGreyUI openSettingsMenu]; // Check the sign-in promo view is visible. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Check the sign-in promo will not be shown anymore. int newDisplayedCount = [SigninSettingsAppInterface settingsSigninPromoDisplayedCount]; @@ -119,7 +119,7 @@ [ChromeEarlGreyUI openSettingsMenu]; // Check the sign-in promo view is visible. [SigninEarlGreyUI - verifySigninPromoVisibleWithMode:SigninPromoViewModeColdState]; + verifySigninPromoVisibleWithMode:IdentityPromoViewModeNoAccounts]; // Tap on dismiss button. [[EarlGrey selectElementWithMatcher:grey_allOf(grey_accessibilityID(
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 index d250f38df..2a5a26f 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -b454fae9849ece33c703d1a3bde06ee60197a0b2 \ No newline at end of file +e295002bd33e15d59b0160590277c88a3335ff0a \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 index efa7611..da085c56 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -a317078fa0a4d0079cbd5a275538552e1d9ede19 \ No newline at end of file +7f1f0777c00e76fb01a81231c569b3c197ba69c5 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 index ecc56cc..abd4d9ba 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -562263f237c7382847b69ea22c1b0dba5853073f \ No newline at end of file +33c985d365790ff96f7a76232b83252f0be6b5d1 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 index 0df4b4d..97cd244a 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -fe68565446e72a0a7cd4e2ffac6f5e86e01fc5c4 \ No newline at end of file +d9c9e33713acd1d53f190a0924ef7c0ad15c1ac3 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 index 7f78e24..52961eb 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -cdbd06a1732ec1887617c5039a2dee8e0488e504 \ No newline at end of file +c371688399efa3f16b110e3323887aca7edfe143 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 index c18d95f..cc7289f01 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -ea15561121422ae27385eeab1b08d7421a2ecfbd \ No newline at end of file +26996bf670eac9c2569921d5009b8d8478406002 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 index 9cae45a..8bdeaa9 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -fffa3c78f5e0729e28c1861331165b0286d0a557 \ No newline at end of file +f710580c06b9e0505b1f9ef4cb1877ff1f89632b \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 index 7456ff1..09af3ec 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -421d1ab197fe12fbd664714a8a7dcab788f37891 \ No newline at end of file +04007aa36063a42a572490b1426684d3e168eb21 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 index 88a739cb..a41fa7c 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -d5d9fee309d9b734373e4402423c140b675b072d \ No newline at end of file +9d7a8f6ebccab200f4fceca1fa0d4a1dafc486ca \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 index 8d9c189..7a0aac0 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -13142588a0c496256f44259ec817da796d848e71 \ No newline at end of file +02600fc0c944b95a87abaac95581168382c8129d \ No newline at end of file
diff --git a/media/capture/BUILD.gn b/media/capture/BUILD.gn index 344cc9a..dc5681b 100644 --- a/media/capture/BUILD.gn +++ b/media/capture/BUILD.gn
@@ -310,6 +310,8 @@ "video/chromeos/token_manager.h", "video/chromeos/vendor_tag_ops_delegate.cc", "video/chromeos/vendor_tag_ops_delegate.h", + "video/chromeos/video_capture_device_chromeos_delegate.cc", + "video/chromeos/video_capture_device_chromeos_delegate.h", "video/chromeos/video_capture_device_chromeos_halv3.cc", "video/chromeos/video_capture_device_chromeos_halv3.h", "video/chromeos/video_capture_device_factory_chromeos.cc",
diff --git a/media/capture/video/chromeos/camera_hal_delegate.cc b/media/capture/video/chromeos/camera_hal_delegate.cc index abfcaf6..1b7135e5 100644 --- a/media/capture/video/chromeos/camera_hal_delegate.cc +++ b/media/capture/video/chromeos/camera_hal_delegate.cc
@@ -25,6 +25,7 @@ #include "media/capture/video/chromeos/camera_buffer_factory.h" #include "media/capture/video/chromeos/camera_hal_dispatcher_impl.h" #include "media/capture/video/chromeos/camera_metadata_utils.h" +#include "media/capture/video/chromeos/video_capture_device_chromeos_delegate.h" #include "media/capture/video/chromeos/video_capture_device_chromeos_halv3.h" namespace media { @@ -205,13 +206,17 @@ bridge->OnDeviceClosed(device_id); }, device_descriptor.device_id, camera_app_device_bridge); - return std::make_unique<VideoCaptureDeviceChromeOSHalv3>( + auto delegate = std::make_unique<VideoCaptureDeviceChromeOSDelegate>( std::move(task_runner_for_screen_observer), device_descriptor, this, camera_app_device, std::move(cleanup_callback)); - } else { return std::make_unique<VideoCaptureDeviceChromeOSHalv3>( + std::move(delegate)); + } else { + auto delegate = std::make_unique<VideoCaptureDeviceChromeOSDelegate>( std::move(task_runner_for_screen_observer), device_descriptor, this, nullptr, base::DoNothing()); + return std::make_unique<VideoCaptureDeviceChromeOSHalv3>( + std::move(delegate)); } }
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc index 4ed3df67..97a4fa6 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc
@@ -216,7 +216,9 @@ CameraHalDispatcherImpl::CameraHalDispatcherImpl() : proxy_thread_("CameraProxyThread"), blocking_io_thread_("CameraBlockingIOThread"), - camera_hal_server_callbacks_(this) { + camera_hal_server_callbacks_(this), + active_client_observers_( + new base::ObserverListThreadSafe<CameraActiveClientObserver>()) { // This event is for adding camera category to categories list. TRACE_EVENT0("camera", "CameraHalDispatcherImpl"); base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc b/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc index 0c78af2..5ff82d1 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc
@@ -76,6 +76,16 @@ DISALLOW_COPY_AND_ASSIGN(MockCameraHalClient); }; +class MockCameraActiveClientObserver : public CameraActiveClientObserver { + public: + void OnActiveClientChange(cros::mojom::CameraClientType type, + bool is_active) override { + DoOnActiveClientChange(type, is_active); + } + MOCK_METHOD2(DoOnActiveClientChange, + void(cros::mojom::CameraClientType, bool)); +}; + } // namespace class CameraHalDispatcherImplTest : public ::testing::Test { @@ -253,4 +263,32 @@ DoLoop(); } +// Test that CameraHalDispatcherImpl correctly fires CameraActiveClientObserver +// when a camera device is opened or closed by a client. +TEST_F(CameraHalDispatcherImplTest, CameraActiveClientObserverTest) { + MockCameraActiveClientObserver observer; + dispatcher_->AddActiveClientObserver(&observer); + + EXPECT_CALL(observer, DoOnActiveClientChange( + cros::mojom::CameraClientType::TESTING, true)) + .Times(1) + .WillOnce( + InvokeWithoutArgs(this, &CameraHalDispatcherImplTest::QuitRunLoop)); + dispatcher_->CameraDeviceActivityChange( + /*camera_id=*/0, /*opened=*/true, cros::mojom::CameraClientType::TESTING); + + DoLoop(); + + EXPECT_CALL(observer, DoOnActiveClientChange( + cros::mojom::CameraClientType::TESTING, false)) + .Times(1) + .WillOnce( + InvokeWithoutArgs(this, &CameraHalDispatcherImplTest::QuitRunLoop)); + dispatcher_->CameraDeviceActivityChange( + /*camera_id=*/0, /*opened=*/false, + cros::mojom::CameraClientType::TESTING); + + DoLoop(); +} + } // namespace media
diff --git a/media/capture/video/chromeos/video_capture_device_chromeos_delegate.cc b/media/capture/video/chromeos/video_capture_device_chromeos_delegate.cc new file mode 100644 index 0000000..b8b8a3b --- /dev/null +++ b/media/capture/video/chromeos/video_capture_device_chromeos_delegate.cc
@@ -0,0 +1,309 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/capture/video/chromeos/video_capture_device_chromeos_delegate.h" + +#include <memory> +#include <string> +#include <utility> + +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/location.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/platform_thread.h" +#include "base/trace_event/trace_event.h" +#include "chromeos/dbus/power/power_manager_client.h" +#include "media/base/bind_to_current_loop.h" +#include "media/capture/video/chromeos/camera_device_delegate.h" +#include "media/capture/video/chromeos/camera_hal_delegate.h" +#include "ui/display/display.h" +#include "ui/display/display_observer.h" +#include "ui/display/screen.h" + +namespace media { + +class VideoCaptureDeviceChromeOSDelegate::PowerManagerClientProxy + : public base::RefCountedThreadSafe<PowerManagerClientProxy>, + public chromeos::PowerManagerClient::Observer { + public: + PowerManagerClientProxy() = default; + + void Init(base::WeakPtr<VideoCaptureDeviceChromeOSDelegate> device, + scoped_refptr<base::SingleThreadTaskRunner> device_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> dbus_task_runner) { + device_ = std::move(device); + device_task_runner_ = std::move(device_task_runner); + dbus_task_runner_ = std::move(dbus_task_runner); + + dbus_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&PowerManagerClientProxy::InitOnDBusThread, this)); + } + + void Shutdown() { + dbus_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&PowerManagerClientProxy::ShutdownOnDBusThread, this)); + } + + void UnblockSuspend(const base::UnguessableToken& unblock_suspend_token) { + dbus_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&PowerManagerClientProxy::UnblockSuspendOnDBusThread, + this, unblock_suspend_token)); + } + + private: + friend class base::RefCountedThreadSafe<PowerManagerClientProxy>; + + ~PowerManagerClientProxy() override = default; + + void InitOnDBusThread() { + DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); + chromeos::PowerManagerClient::Get()->AddObserver(this); + } + + void ShutdownOnDBusThread() { + DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); + chromeos::PowerManagerClient::Get()->RemoveObserver(this); + } + + void UnblockSuspendOnDBusThread( + const base::UnguessableToken& unblock_suspend_token) { + DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); + chromeos::PowerManagerClient::Get()->UnblockSuspend(unblock_suspend_token); + } + + // chromeos::PowerManagerClient::Observer: + void SuspendImminent(power_manager::SuspendImminent::Reason reason) final { + auto token = base::UnguessableToken::Create(); + chromeos::PowerManagerClient::Get()->BlockSuspend( + token, "VideoCaptureDeviceChromeOSDelegate"); + device_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&VideoCaptureDeviceChromeOSDelegate::CloseDevice, + device_, token)); + } + + void SuspendDone(base::TimeDelta sleep_duration) final { + device_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&VideoCaptureDeviceChromeOSDelegate::OpenDevice, + device_)); + } + + base::WeakPtr<VideoCaptureDeviceChromeOSDelegate> device_; + scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> dbus_task_runner_; + + DISALLOW_COPY_AND_ASSIGN(PowerManagerClientProxy); +}; + +VideoCaptureDeviceChromeOSDelegate::VideoCaptureDeviceChromeOSDelegate( + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, + const VideoCaptureDeviceDescriptor& device_descriptor, + scoped_refptr<CameraHalDelegate> camera_hal_delegate, + CameraAppDeviceImpl* camera_app_device, + base::OnceClosure cleanup_callback) + : device_descriptor_(device_descriptor), + camera_hal_delegate_(std::move(camera_hal_delegate)), + capture_task_runner_(base::ThreadTaskRunnerHandle::Get()), + camera_device_ipc_thread_(std::string("CameraDeviceIpcThread") + + device_descriptor.device_id), + screen_observer_delegate_( + ScreenObserverDelegate::Create(this, ui_task_runner)), + lens_facing_(device_descriptor.facing), + // External cameras have lens_facing as MEDIA_VIDEO_FACING_NONE. + // We don't want to rotate the frame even if the device rotates. + rotates_with_device_(lens_facing_ != + VideoFacingMode::MEDIA_VIDEO_FACING_NONE), + rotation_(0), + camera_app_device_(camera_app_device), + cleanup_callback_(std::move(cleanup_callback)), + power_manager_client_proxy_( + base::MakeRefCounted<PowerManagerClientProxy>()), + client_type_(ClientType::kPreviewClient) { + power_manager_client_proxy_->Init(weak_ptr_factory_.GetWeakPtr(), + capture_task_runner_, + std::move(ui_task_runner)); +} + +VideoCaptureDeviceChromeOSDelegate::~VideoCaptureDeviceChromeOSDelegate() { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + DCHECK(!camera_device_ipc_thread_.IsRunning()); + screen_observer_delegate_->RemoveObserver(); + power_manager_client_proxy_->Shutdown(); + std::move(cleanup_callback_).Run(); +} + +// VideoCaptureDevice implementation. +void VideoCaptureDeviceChromeOSDelegate::AllocateAndStart( + const VideoCaptureParams& params, + std::unique_ptr<Client> client) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + DCHECK(!camera_device_delegate_); + TRACE_EVENT0("camera", "Start Device"); + if (!camera_device_ipc_thread_.Start()) { + std::string error_msg = "Failed to start device thread"; + LOG(ERROR) << error_msg; + client->OnError( + media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread, + FROM_HERE, error_msg); + return; + } + capture_params_ = params; + device_context_ = std::make_unique<CameraDeviceContext>(); + if (device_context_->AddClient(client_type_, std::move(client))) { + camera_device_delegate_ = std::make_unique<CameraDeviceDelegate>( + device_descriptor_, camera_hal_delegate_, + camera_device_ipc_thread_.task_runner(), camera_app_device_, + client_type_); + OpenDevice(); + } +} + +void VideoCaptureDeviceChromeOSDelegate::StopAndDeAllocate() { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + if (!camera_device_delegate_) { + return; + } + CloseDevice(base::UnguessableToken()); + camera_device_ipc_thread_.Stop(); + camera_device_delegate_.reset(); + device_context_->RemoveClient(client_type_); + device_context_.reset(); +} + +void VideoCaptureDeviceChromeOSDelegate::TakePhoto(TakePhotoCallback callback) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + DCHECK(camera_device_delegate_); + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, base::BindOnce(&CameraDeviceDelegate::TakePhoto, + camera_device_delegate_->GetWeakPtr(), + std::move(callback))); +} + +void VideoCaptureDeviceChromeOSDelegate::GetPhotoState( + GetPhotoStateCallback callback) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, base::BindOnce(&CameraDeviceDelegate::GetPhotoState, + camera_device_delegate_->GetWeakPtr(), + std::move(callback))); +} + +void VideoCaptureDeviceChromeOSDelegate::SetPhotoOptions( + mojom::PhotoSettingsPtr settings, + SetPhotoOptionsCallback callback) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, base::BindOnce(&CameraDeviceDelegate::SetPhotoOptions, + camera_device_delegate_->GetWeakPtr(), + std::move(settings), std::move(callback))); +} + +void VideoCaptureDeviceChromeOSDelegate::OpenDevice() { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + + if (!camera_device_delegate_) { + return; + } + // It's safe to pass unretained |device_context_| here since + // VideoCaptureDeviceChromeOSDelegate owns |camera_device_delegate_| and makes + // sure |device_context_| outlives |camera_device_delegate_|. + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, + base::BindOnce(&CameraDeviceDelegate::AllocateAndStart, + camera_device_delegate_->GetWeakPtr(), capture_params_, + base::Unretained(device_context_.get()))); + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, + base::BindOnce(&CameraDeviceDelegate::SetRotation, + camera_device_delegate_->GetWeakPtr(), rotation_)); +} + +void VideoCaptureDeviceChromeOSDelegate::CloseDevice( + base::UnguessableToken unblock_suspend_token) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + + if (!camera_device_delegate_) { + return; + } + // We do our best to allow the camera HAL cleanly shut down the device. In + // general we don't trust the camera HAL so if the device does not close in + // time we simply terminate the Mojo channel by resetting + // |camera_device_delegate_|. + base::WaitableEvent device_closed( + base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED); + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, base::BindOnce(&CameraDeviceDelegate::StopAndDeAllocate, + camera_device_delegate_->GetWeakPtr(), + base::BindOnce( + [](base::WaitableEvent* device_closed) { + device_closed->Signal(); + }, + base::Unretained(&device_closed)))); + base::TimeDelta kWaitTimeoutSecs = base::TimeDelta::FromSeconds(3); + device_closed.TimedWait(kWaitTimeoutSecs); + if (!unblock_suspend_token.is_empty()) + power_manager_client_proxy_->UnblockSuspend(unblock_suspend_token); +} + +void VideoCaptureDeviceChromeOSDelegate::SetDisplayRotation( + const display::Display& display) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + if (display.IsInternal()) + SetRotation(display.rotation() * 90); +} + +void VideoCaptureDeviceChromeOSDelegate::SetRotation(int rotation) { + DCHECK(capture_task_runner_->BelongsToCurrentThread()); + if (!rotates_with_device_) { + rotation = 0; + } else if (lens_facing_ == VideoFacingMode::MEDIA_VIDEO_FACING_ENVIRONMENT) { + // Original frame when |rotation| = 0 + // ----------------------- + // | * | + // | * * | + // | * * | + // | ******* | + // | * * | + // | * * | + // ----------------------- + // + // |rotation| = 90, this is what back camera sees + // ----------------------- + // | ******** | + // | * **** | + // | * *** | + // | * *** | + // | * **** | + // | ******** | + // ----------------------- + // + // |rotation| = 90, this is what front camera sees + // ----------------------- + // | ******** | + // | **** * | + // | *** * | + // | *** * | + // | **** * | + // | ******** | + // ----------------------- + // + // Therefore, for back camera, we need to rotate (360 - |rotation|). + rotation = (360 - rotation) % 360; + } + rotation_ = rotation; + if (camera_device_ipc_thread_.IsRunning()) { + camera_device_ipc_thread_.task_runner()->PostTask( + FROM_HERE, + base::BindOnce(&CameraDeviceDelegate::SetRotation, + camera_device_delegate_->GetWeakPtr(), rotation_)); + } +} + +} // namespace media
diff --git a/media/capture/video/chromeos/video_capture_device_chromeos_delegate.h b/media/capture/video/chromeos/video_capture_device_chromeos_delegate.h new file mode 100644 index 0000000..2b82e40 --- /dev/null +++ b/media/capture/video/chromeos/video_capture_device_chromeos_delegate.h
@@ -0,0 +1,117 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_CAPTURE_VIDEO_CHROMEOS_VIDEO_CAPTURE_DEVICE_CHROMEOS_DELEGATE_H_ +#define MEDIA_CAPTURE_VIDEO_CHROMEOS_VIDEO_CAPTURE_DEVICE_CHROMEOS_DELEGATE_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" +#include "base/threading/thread.h" +#include "media/capture/video/chromeos/camera_device_context.h" +#include "media/capture/video/chromeos/display_rotation_observer.h" +#include "media/capture/video/video_capture_device.h" +#include "media/capture/video/video_capture_device_descriptor.h" +#include "media/capture/video_capture_types.h" + +namespace display { + +class Display; + +} // namespace display + +namespace media { + +class CameraAppDeviceImpl; +class CameraHalDelegate; +class CameraDeviceDelegate; + +// Implementation of VideoCaptureDevice for ChromeOS with CrOS camera HALv3. +class CAPTURE_EXPORT VideoCaptureDeviceChromeOSDelegate final + : public VideoCaptureDevice, + public DisplayRotationObserver { + public: + VideoCaptureDeviceChromeOSDelegate( + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, + const VideoCaptureDeviceDescriptor& device_descriptor, + scoped_refptr<CameraHalDelegate> camera_hal_delegate, + CameraAppDeviceImpl* camera_app_device, + base::OnceClosure cleanup_callback); + + ~VideoCaptureDeviceChromeOSDelegate() final; + + // VideoCaptureDevice implementation. + void AllocateAndStart(const VideoCaptureParams& params, + std::unique_ptr<Client> client) final; + void StopAndDeAllocate() final; + void TakePhoto(TakePhotoCallback callback) final; + void GetPhotoState(GetPhotoStateCallback callback) final; + void SetPhotoOptions(mojom::PhotoSettingsPtr settings, + SetPhotoOptionsCallback callback) final; + + private: + // Helper to interact with PowerManagerClient on DBus original thread. + class PowerManagerClientProxy; + + void OpenDevice(); + void CloseDevice(base::UnguessableToken unblock_suspend_token); + + // DisplayRotationDelegate implementation. + void SetDisplayRotation(const display::Display& display) final; + void SetRotation(int rotation); + + const VideoCaptureDeviceDescriptor device_descriptor_; + + // A reference to the CameraHalDelegate instance in the VCD factory. This is + // used by AllocateAndStart to query camera info and create the camera device. + const scoped_refptr<CameraHalDelegate> camera_hal_delegate_; + + // A reference to the thread that all the VideoCaptureDevice interface methods + // are expected to be called on. + const scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner_; + + // The thread that all the Mojo operations of |camera_device_delegate_| take + // place. Started in AllocateAndStart and stopped in StopAndDeAllocate, where + // the access to the base::Thread methods are sequenced on + // |capture_task_runner_|. + base::Thread camera_device_ipc_thread_; + + VideoCaptureParams capture_params_; + // |device_context_| is created and owned by + // VideoCaptureDeviceChromeOSDelegate and is only accessed by + // |camera_device_delegate_|. + std::unique_ptr<CameraDeviceContext> device_context_; + + // Internal delegate doing the actual capture setting, buffer allocation and + // circulation with the camera HAL. Created in AllocateAndStart and deleted in + // StopAndDeAllocate on |capture_task_runner_|. All methods of + // |camera_device_delegate_| operate on |camera_device_ipc_thread_|. + std::unique_ptr<CameraDeviceDelegate> camera_device_delegate_; + + scoped_refptr<ScreenObserverDelegate> screen_observer_delegate_; + const VideoFacingMode lens_facing_; + // Whether the incoming frames should rotate when the device rotates. + const bool rotates_with_device_; + int rotation_; + + CameraAppDeviceImpl* camera_app_device_; // Weak. + + base::OnceClosure cleanup_callback_; + + scoped_refptr<PowerManagerClientProxy> power_manager_client_proxy_; + + // The client type in CameraDeviceContext. + ClientType client_type_; + + base::WeakPtrFactory<VideoCaptureDeviceChromeOSDelegate> weak_ptr_factory_{ + this}; + + DISALLOW_IMPLICIT_CONSTRUCTORS(VideoCaptureDeviceChromeOSDelegate); +}; + +} // namespace media + +#endif // MEDIA_CAPTURE_VIDEO_CHROMEOS_VIDEO_CAPTURE_DEVICE_CHROMEOS_DELEGATE_H_
diff --git a/media/capture/video/chromeos/video_capture_device_chromeos_halv3.cc b/media/capture/video/chromeos/video_capture_device_chromeos_halv3.cc index 6b9999e..34a6eaef 100644 --- a/media/capture/video/chromeos/video_capture_device_chromeos_halv3.cc +++ b/media/capture/video/chromeos/video_capture_device_chromeos_halv3.cc
@@ -1,309 +1,44 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. +// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/capture/video/chromeos/video_capture_device_chromeos_halv3.h" -#include <memory> -#include <string> -#include <utility> - -#include "base/bind.h" -#include "base/callback_helpers.h" -#include "base/location.h" -#include "base/synchronization/waitable_event.h" -#include "base/threading/platform_thread.h" -#include "base/trace_event/trace_event.h" -#include "chromeos/dbus/power/power_manager_client.h" -#include "media/base/bind_to_current_loop.h" -#include "media/capture/video/chromeos/camera_device_context.h" -#include "media/capture/video/chromeos/camera_device_delegate.h" -#include "media/capture/video/chromeos/camera_hal_delegate.h" -#include "ui/display/display.h" -#include "ui/display/display_observer.h" -#include "ui/display/screen.h" +#include "media/capture/video/chromeos/video_capture_device_chromeos_delegate.h" namespace media { -class VideoCaptureDeviceChromeOSHalv3::PowerManagerClientProxy - : public base::RefCountedThreadSafe<PowerManagerClientProxy>, - public chromeos::PowerManagerClient::Observer { - public: - PowerManagerClientProxy() = default; - - void Init(base::WeakPtr<VideoCaptureDeviceChromeOSHalv3> device, - scoped_refptr<base::SingleThreadTaskRunner> device_task_runner, - scoped_refptr<base::SingleThreadTaskRunner> dbus_task_runner) { - device_ = std::move(device); - device_task_runner_ = std::move(device_task_runner); - dbus_task_runner_ = std::move(dbus_task_runner); - - dbus_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&PowerManagerClientProxy::InitOnDBusThread, this)); - } - - void Shutdown() { - dbus_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&PowerManagerClientProxy::ShutdownOnDBusThread, this)); - } - - void UnblockSuspend(const base::UnguessableToken& unblock_suspend_token) { - dbus_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&PowerManagerClientProxy::UnblockSuspendOnDBusThread, - this, unblock_suspend_token)); - } - - private: - friend class base::RefCountedThreadSafe<PowerManagerClientProxy>; - - ~PowerManagerClientProxy() override = default; - - void InitOnDBusThread() { - DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); - chromeos::PowerManagerClient::Get()->AddObserver(this); - } - - void ShutdownOnDBusThread() { - DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); - chromeos::PowerManagerClient::Get()->RemoveObserver(this); - } - - void UnblockSuspendOnDBusThread( - const base::UnguessableToken& unblock_suspend_token) { - DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence()); - chromeos::PowerManagerClient::Get()->UnblockSuspend(unblock_suspend_token); - } - - // chromeos::PowerManagerClient::Observer: - void SuspendImminent(power_manager::SuspendImminent::Reason reason) final { - auto token = base::UnguessableToken::Create(); - chromeos::PowerManagerClient::Get()->BlockSuspend( - token, "VideoCaptureDeviceChromeOSHalv3"); - device_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&VideoCaptureDeviceChromeOSHalv3::CloseDevice, - device_, token)); - } - - void SuspendDone(base::TimeDelta sleep_duration) final { - device_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&VideoCaptureDeviceChromeOSHalv3::OpenDevice, device_)); - } - - base::WeakPtr<VideoCaptureDeviceChromeOSHalv3> device_; - scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_; - scoped_refptr<base::SingleThreadTaskRunner> dbus_task_runner_; - - DISALLOW_COPY_AND_ASSIGN(PowerManagerClientProxy); -}; - VideoCaptureDeviceChromeOSHalv3::VideoCaptureDeviceChromeOSHalv3( - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, - const VideoCaptureDeviceDescriptor& device_descriptor, - scoped_refptr<CameraHalDelegate> camera_hal_delegate, - CameraAppDeviceImpl* camera_app_device, - base::OnceClosure cleanup_callback) - : device_descriptor_(device_descriptor), - camera_hal_delegate_(std::move(camera_hal_delegate)), - capture_task_runner_(base::ThreadTaskRunnerHandle::Get()), - camera_device_ipc_thread_(std::string("CameraDeviceIpcThread") + - device_descriptor.device_id), - screen_observer_delegate_( - ScreenObserverDelegate::Create(this, ui_task_runner)), - lens_facing_(device_descriptor.facing), - // External cameras have lens_facing as MEDIA_VIDEO_FACING_NONE. - // We don't want to rotate the frame even if the device rotates. - rotates_with_device_(lens_facing_ != - VideoFacingMode::MEDIA_VIDEO_FACING_NONE), - rotation_(0), - camera_app_device_(camera_app_device), - cleanup_callback_(std::move(cleanup_callback)), - power_manager_client_proxy_( - base::MakeRefCounted<PowerManagerClientProxy>()), - client_type_(ClientType::kPreviewClient) { - power_manager_client_proxy_->Init(weak_ptr_factory_.GetWeakPtr(), - capture_task_runner_, - std::move(ui_task_runner)); -} + std::unique_ptr<VideoCaptureDeviceChromeOSDelegate> delegate) + : vcd_delegate_(std::move(delegate)) {} VideoCaptureDeviceChromeOSHalv3::~VideoCaptureDeviceChromeOSHalv3() { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - DCHECK(!camera_device_ipc_thread_.IsRunning()); - screen_observer_delegate_->RemoveObserver(); - power_manager_client_proxy_->Shutdown(); - std::move(cleanup_callback_).Run(); } // VideoCaptureDevice implementation. void VideoCaptureDeviceChromeOSHalv3::AllocateAndStart( const VideoCaptureParams& params, std::unique_ptr<Client> client) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - DCHECK(!camera_device_delegate_); - TRACE_EVENT0("camera", "Start Device"); - if (!camera_device_ipc_thread_.Start()) { - std::string error_msg = "Failed to start device thread"; - LOG(ERROR) << error_msg; - client->OnError( - media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread, - FROM_HERE, error_msg); - return; - } - capture_params_ = params; - device_context_ = std::make_unique<CameraDeviceContext>(); - if (device_context_->AddClient(client_type_, std::move(client))) { - camera_device_delegate_ = std::make_unique<CameraDeviceDelegate>( - device_descriptor_, camera_hal_delegate_, - camera_device_ipc_thread_.task_runner(), camera_app_device_, - client_type_); - OpenDevice(); - } + vcd_delegate_->AllocateAndStart(params, std::move(client)); } void VideoCaptureDeviceChromeOSHalv3::StopAndDeAllocate() { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - - if (!camera_device_delegate_) { - return; - } - CloseDevice(base::UnguessableToken()); - camera_device_ipc_thread_.Stop(); - camera_device_delegate_.reset(); - device_context_->RemoveClient(client_type_); - device_context_.reset(); + vcd_delegate_->StopAndDeAllocate(); } void VideoCaptureDeviceChromeOSHalv3::TakePhoto(TakePhotoCallback callback) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - DCHECK(camera_device_delegate_); - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&CameraDeviceDelegate::TakePhoto, - camera_device_delegate_->GetWeakPtr(), - std::move(callback))); + vcd_delegate_->TakePhoto(std::move(callback)); } void VideoCaptureDeviceChromeOSHalv3::GetPhotoState( GetPhotoStateCallback callback) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&CameraDeviceDelegate::GetPhotoState, - camera_device_delegate_->GetWeakPtr(), - std::move(callback))); + vcd_delegate_->GetPhotoState(std::move(callback)); } void VideoCaptureDeviceChromeOSHalv3::SetPhotoOptions( mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&CameraDeviceDelegate::SetPhotoOptions, - camera_device_delegate_->GetWeakPtr(), - std::move(settings), std::move(callback))); -} - -void VideoCaptureDeviceChromeOSHalv3::OpenDevice() { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - - if (!camera_device_delegate_) { - return; - } - // It's safe to pass unretained |device_context_| here since - // VideoCaptureDeviceChromeOSHalv3 owns |camera_device_delegate_| and makes - // sure |device_context_| outlives |camera_device_delegate_|. - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&CameraDeviceDelegate::AllocateAndStart, - camera_device_delegate_->GetWeakPtr(), capture_params_, - base::Unretained(device_context_.get()))); - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&CameraDeviceDelegate::SetRotation, - camera_device_delegate_->GetWeakPtr(), rotation_)); -} - -void VideoCaptureDeviceChromeOSHalv3::CloseDevice( - base::UnguessableToken unblock_suspend_token) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - - if (!camera_device_delegate_) { - return; - } - // We do our best to allow the camera HAL cleanly shut down the device. In - // general we don't trust the camera HAL so if the device does not close in - // time we simply terminate the Mojo channel by resetting - // |camera_device_delegate_|. - base::WaitableEvent device_closed( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&CameraDeviceDelegate::StopAndDeAllocate, - camera_device_delegate_->GetWeakPtr(), - base::BindOnce( - [](base::WaitableEvent* device_closed) { - device_closed->Signal(); - }, - base::Unretained(&device_closed)))); - base::TimeDelta kWaitTimeoutSecs = base::TimeDelta::FromSeconds(3); - device_closed.TimedWait(kWaitTimeoutSecs); - if (!unblock_suspend_token.is_empty()) - power_manager_client_proxy_->UnblockSuspend(unblock_suspend_token); -} - -void VideoCaptureDeviceChromeOSHalv3::SetDisplayRotation( - const display::Display& display) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - if (display.IsInternal()) - SetRotation(display.rotation() * 90); -} - -void VideoCaptureDeviceChromeOSHalv3::SetRotation(int rotation) { - DCHECK(capture_task_runner_->BelongsToCurrentThread()); - if (!rotates_with_device_) { - rotation = 0; - } else if (lens_facing_ == VideoFacingMode::MEDIA_VIDEO_FACING_ENVIRONMENT) { - // Original frame when |rotation| = 0 - // ----------------------- - // | * | - // | * * | - // | * * | - // | ******* | - // | * * | - // | * * | - // ----------------------- - // - // |rotation| = 90, this is what back camera sees - // ----------------------- - // | ******** | - // | * **** | - // | * *** | - // | * *** | - // | * **** | - // | ******** | - // ----------------------- - // - // |rotation| = 90, this is what front camera sees - // ----------------------- - // | ******** | - // | **** * | - // | *** * | - // | *** * | - // | **** * | - // | ******** | - // ----------------------- - // - // Therefore, for back camera, we need to rotate (360 - |rotation|). - rotation = (360 - rotation) % 360; - } - rotation_ = rotation; - if (camera_device_ipc_thread_.IsRunning()) { - camera_device_ipc_thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&CameraDeviceDelegate::SetRotation, - camera_device_delegate_->GetWeakPtr(), rotation_)); - } + vcd_delegate_->SetPhotoOptions(std::move(settings), std::move(callback)); } } // namespace media
diff --git a/media/capture/video/chromeos/video_capture_device_chromeos_halv3.h b/media/capture/video/chromeos/video_capture_device_chromeos_halv3.h index 9f5a03e..b20f76f2 100644 --- a/media/capture/video/chromeos/video_capture_device_chromeos_halv3.h +++ b/media/capture/video/chromeos/video_capture_device_chromeos_halv3.h
@@ -1,4 +1,4 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. +// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -7,39 +7,18 @@ #include <memory> -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread.h" -#include "media/capture/video/chromeos/camera_device_context.h" -#include "media/capture/video/chromeos/display_rotation_observer.h" #include "media/capture/video/video_capture_device.h" -#include "media/capture/video/video_capture_device_descriptor.h" -#include "media/capture/video_capture_types.h" - -namespace display { - -class Display; - -} // namespace display namespace media { -class CameraAppDeviceImpl; -class CameraHalDelegate; -class CameraDeviceDelegate; +class VideoCaptureDeviceChromeOSDelegate; // Implementation of VideoCaptureDevice for ChromeOS with CrOS camera HALv3. class CAPTURE_EXPORT VideoCaptureDeviceChromeOSHalv3 final - : public VideoCaptureDevice, - public DisplayRotationObserver { + : public VideoCaptureDevice { public: - VideoCaptureDeviceChromeOSHalv3( - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, - const VideoCaptureDeviceDescriptor& device_descriptor, - scoped_refptr<CameraHalDelegate> camera_hal_delegate, - CameraAppDeviceImpl* camera_app_device, - base::OnceClosure cleanup_callback); + explicit VideoCaptureDeviceChromeOSHalv3( + std::unique_ptr<VideoCaptureDeviceChromeOSDelegate> delegate); ~VideoCaptureDeviceChromeOSHalv3() final; @@ -53,59 +32,7 @@ SetPhotoOptionsCallback callback) final; private: - // Helper to interact with PowerManagerClient on DBus original thread. - class PowerManagerClientProxy; - - void OpenDevice(); - void CloseDevice(base::UnguessableToken unblock_suspend_token); - - // DisplayRotationDelegate implementation. - void SetDisplayRotation(const display::Display& display) final; - void SetRotation(int rotation); - - const VideoCaptureDeviceDescriptor device_descriptor_; - - // A reference to the CameraHalDelegate instance in the VCD factory. This is - // used by AllocateAndStart to query camera info and create the camera device. - const scoped_refptr<CameraHalDelegate> camera_hal_delegate_; - - // A reference to the thread that all the VideoCaptureDevice interface methods - // are expected to be called on. - const scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner_; - - // The thread that all the Mojo operations of |camera_device_delegate_| take - // place. Started in AllocateAndStart and stopped in StopAndDeAllocate, where - // the access to the base::Thread methods are sequenced on - // |capture_task_runner_|. - base::Thread camera_device_ipc_thread_; - - VideoCaptureParams capture_params_; - // |device_context_| is created and owned by VideoCaptureDeviceChromeOSHalv3 - // and is only accessed by |camera_device_delegate_|. - std::unique_ptr<CameraDeviceContext> device_context_; - - // Internal delegate doing the actual capture setting, buffer allocation and - // circulation with the camera HAL. Created in AllocateAndStart and deleted in - // StopAndDeAllocate on |capture_task_runner_|. All methods of - // |camera_device_delegate_| operate on |camera_device_ipc_thread_|. - std::unique_ptr<CameraDeviceDelegate> camera_device_delegate_; - - scoped_refptr<ScreenObserverDelegate> screen_observer_delegate_; - const VideoFacingMode lens_facing_; - // Whether the incoming frames should rotate when the device rotates. - const bool rotates_with_device_; - int rotation_; - - CameraAppDeviceImpl* camera_app_device_; // Weak. - - base::OnceClosure cleanup_callback_; - - scoped_refptr<PowerManagerClientProxy> power_manager_client_proxy_; - - // The client type in CameraDeviceContext. - ClientType client_type_; - - base::WeakPtrFactory<VideoCaptureDeviceChromeOSHalv3> weak_ptr_factory_{this}; + std::unique_ptr<VideoCaptureDeviceChromeOSDelegate> vcd_delegate_; DISALLOW_IMPLICIT_CONSTRUCTORS(VideoCaptureDeviceChromeOSHalv3); };
diff --git a/media/gpu/test/video.cc b/media/gpu/test/video.cc index 55dcf93c..b94d0807 100644 --- a/media/gpu/test/video.cc +++ b/media/gpu/test/video.cc
@@ -131,6 +131,7 @@ new_video->thumbnail_checksums_ = thumbnail_checksums_; new_video->profile_ = profile_; new_video->codec_ = codec_; + new_video->bit_depth_ = bit_depth_; new_video->frame_rate_ = frame_rate_; new_video->num_frames_ = num_frames_; new_video->num_fragments_ = num_fragments_; @@ -239,6 +240,10 @@ LOG(ERROR) << "Decoding is currently only supported for VP9 videos"; return false; } + if (bit_depth_ != 8u) { + LOG(ERROR) << "Decoding is currently only supported for 8bpp videos"; + return false; + } // The VpxVideoDecoder requires running on a SequencedTaskRunner, so we can't // decode the video on the main test thread. @@ -294,6 +299,10 @@ return profile_; } +uint8_t Video::BitDepth() const { + return bit_depth_; +} + VideoPixelFormat Video::PixelFormat() const { return pixel_format_; } @@ -389,6 +398,21 @@ codec_ = converted_codec.value(); } + // Find the video's bit depth. This is optional and only required for encoded + // video streams. + const base::Value* bit_depth = + metadata->FindKeyOfType("bit_depth", base::Value::Type::INTEGER); + if (bit_depth) { + bit_depth_ = base::checked_cast<uint8_t>(bit_depth->GetInt()); + } else { + if (profile_ == VP9PROFILE_PROFILE2) { + LOG(ERROR) << "Bit depth is unspecified for VP9 profile 2"; + return false; + } + constexpr uint8_t kDefaultBitDepth = 8u; + bit_depth_ = kDefaultBitDepth; + } + // Find the video's pixel format, only required for raw video streams. pixel_format_ = VideoPixelFormat::PIXEL_FORMAT_UNKNOWN; const base::Value* pixel_format =
diff --git a/media/gpu/test/video.h b/media/gpu/test/video.h index 4f0df62c..0a12e53 100644 --- a/media/gpu/test/video.h +++ b/media/gpu/test/video.h
@@ -64,6 +64,8 @@ VideoCodec Codec() const; // Get the video's codec profile. VideoCodecProfile Profile() const; + // Get the video's color bit depth. + uint8_t BitDepth() const; // Get the video's pixel format. VideoPixelFormat PixelFormat() const; // Get the video frame rate. @@ -143,9 +145,11 @@ // List of thumbnail checksums. std::vector<std::string> thumbnail_checksums_; - // Video codec and profile for encoded videos. + // Video codec, profile and bit depth for encoded videos. VideoCodecProfile profile_ = VIDEO_CODEC_PROFILE_UNKNOWN; VideoCodec codec_ = kUnknownVideoCodec; + uint8_t bit_depth_ = 0u; + // Pixel format for raw videos. VideoPixelFormat pixel_format_ = VideoPixelFormat::PIXEL_FORMAT_UNKNOWN;
diff --git a/media/gpu/vaapi/vaapi_video_decoder.cc b/media/gpu/vaapi/vaapi_video_decoder.cc index c54588e0..f8944c8 100644 --- a/media/gpu/vaapi/vaapi_video_decoder.cc +++ b/media/gpu/vaapi/vaapi_video_decoder.cc
@@ -10,8 +10,10 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" +#include "base/containers/fixed_flat_map.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/stl_util.h" #include "base/trace_event/trace_event.h" #include "gpu/config/gpu_switches.h" #include "media/base/bind_to_current_loop.h" @@ -46,23 +48,22 @@ // Size of the timestamp cache, needs to be large enough for frame-reordering. constexpr size_t kTimestampCacheSize = 128; -// Returns the preferred VA_RT_FORMAT for the given |profile|. -unsigned int GetVaFormatForVideoCodecProfile(VideoCodecProfile profile) { - if (profile == VP9PROFILE_PROFILE2 || profile == VP9PROFILE_PROFILE3) - return VA_RT_FORMAT_YUV420_10BPP; - return VA_RT_FORMAT_YUV420; -} - -gfx::BufferFormat GetBufferFormat(VideoCodecProfile profile) { +base::Optional<VideoPixelFormat> GetPixelFormatForBitDepth(uint8_t bit_depth) { + constexpr auto kSupportedBitDepthAndGfxFormats = base::MakeFixedFlatMap< + uint8_t, gfx::BufferFormat>({ #if defined(USE_OZONE) - if (profile == VP9PROFILE_PROFILE2 || profile == VP9PROFILE_PROFILE3) - return gfx::BufferFormat::P010; - return gfx::BufferFormat::YUV_420_BIPLANAR; + {8u, gfx::BufferFormat::YUV_420_BIPLANAR}, {10u, gfx::BufferFormat::P010}, #else - return gfx::BufferFormat::RGBX_8888; -#endif + {8u, gfx::BufferFormat::RGBX_8888}, +#endif // defined(USE_OZONE) + }); + if (!base::Contains(kSupportedBitDepthAndGfxFormats, bit_depth)) { + VLOGF(1) << "Unsupported bit depth: " << base::strict_cast<int>(bit_depth); + return base::nullopt; + } + return GfxBufferFormatToVideoPixelFormat( + kSupportedBitDepthAndGfxFormats.at(bit_depth)); } - } // namespace VaapiVideoDecoder::DecodeTask::DecodeTask(scoped_refptr<DecoderBuffer> buffer, @@ -452,8 +453,7 @@ base::BindOnce(&VaapiVideoDecoder::ReleaseVideoFrame, weak_this_); return new VASurface(surface_id, frame->layout().coded_size(), - GetVaFormatForVideoCodecProfile(profile_), - std::move(release_frame_cb)); + va_surface->format(), std::move(release_frame_cb)); } void VaapiVideoDecoder::SurfaceReady(scoped_refptr<VASurface> va_surface, @@ -512,14 +512,17 @@ DCHECK(output_frames_.empty()); VLOGF(2); + const uint8_t bit_depth = decoder_->GetBitDepth(); + const base::Optional<VideoPixelFormat> format = + GetPixelFormatForBitDepth(bit_depth); + if (!format) { + SetState(State::kError); + return; + } const gfx::Rect visible_rect = decoder_->GetVisibleRect(); const gfx::Size natural_size = GetNaturalSize(visible_rect, pixel_aspect_ratio_); const gfx::Size pic_size = decoder_->GetPicSize(); - const base::Optional<VideoPixelFormat> format = - GfxBufferFormatToVideoPixelFormat( - GetBufferFormat(decoder_->GetProfile())); - CHECK(format); auto format_fourcc = Fourcc::FromVideoPixelFormat(*format); CHECK(format_fourcc); if (!frame_pool_->Initialize(
diff --git a/media/gpu/video_decode_accelerator_tests.cc b/media/gpu/video_decode_accelerator_tests.cc index b9e75cd2..fbaa17b 100644 --- a/media/gpu/video_decode_accelerator_tests.cc +++ b/media/gpu/video_decode_accelerator_tests.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/files/file_util.h" +#include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" #include "media/base/test_data_util.h" #include "media/gpu/test/video.h" @@ -103,14 +104,15 @@ output_folder, g_env->GetFrameOutputFormat(), g_env->GetFrameOutputLimit()); } - - // VP9 profile 2 supports 10 and 12 bit color depths, but we currently - // assume a profile 2 stream contains 10 bit color depth only. - // TODO(hiroh): Add bit depth info to Video class and follow it here. + if (g_env->Video()->BitDepth() != 8u && + g_env->Video()->BitDepth() != 10u) { + LOG(ERROR) << "Unsupported bit depth: " + << base::strict_cast<int>(g_env->Video()->BitDepth()); + return nullptr; + } const VideoPixelFormat validation_format = - g_env->Video()->Profile() == VP9PROFILE_PROFILE2 - ? PIXEL_FORMAT_YUV420P10 - : PIXEL_FORMAT_I420; + g_env->Video()->BitDepth() == 10 ? PIXEL_FORMAT_YUV420P10 + : PIXEL_FORMAT_I420; frame_processors.push_back(media::test::MD5VideoFrameValidator::Create( video->FrameChecksums(), validation_format, std::move(frame_writer))); }
diff --git a/media/test/data/test-25fps.vp9_2.json b/media/test/data/test-25fps.vp9_2.json index fc38be3..db1fbd2 100644 --- a/media/test/data/test-25fps.vp9_2.json +++ b/media/test/data/test-25fps.vp9_2.json
@@ -1,5 +1,6 @@ { "profile": "VP9PROFILE_PROFILE2", + "bit_depth": 10, "width": 320, "height": 240, "frame_rate": 25,
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index a4bc81c9..83d70d4 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -662,19 +662,29 @@ // insecure scheme, unless it is a localhost url, or the CookieAccessDelegate // otherwise denotes them as trustworthy // (`delegate_treats_url_as_trustworthy`). - if (IsSecure()) { - CookieAccessScheme cookie_access_scheme = - cookie_util::ProvisionalAccessScheme(url); - if (cookie_access_scheme == CookieAccessScheme::kNonCryptographic && - params.delegate_treats_url_as_trustworthy) { - cookie_access_scheme = CookieAccessScheme::kTrustworthy; - } - if (cookie_access_scheme == CookieAccessScheme::kNonCryptographic) { - status.AddExclusionReason(CookieInclusionStatus::EXCLUDE_SECURE_ONLY); - } else if (cookie_access_scheme == CookieAccessScheme::kTrustworthy) { - status.AddWarningReason( - CookieInclusionStatus::WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC); - } + bool is_allowed_to_access_secure_cookies = false; + CookieAccessScheme cookie_access_scheme = + cookie_util::ProvisionalAccessScheme(url); + if (cookie_access_scheme == CookieAccessScheme::kNonCryptographic && + params.delegate_treats_url_as_trustworthy) { + cookie_access_scheme = CookieAccessScheme::kTrustworthy; + } + switch (cookie_access_scheme) { + case CookieAccessScheme::kNonCryptographic: + if (IsSecure()) + status.AddExclusionReason(CookieInclusionStatus::EXCLUDE_SECURE_ONLY); + break; + case CookieAccessScheme::kTrustworthy: + is_allowed_to_access_secure_cookies = true; + if (IsSecure()) { + status.AddWarningReason( + CookieInclusionStatus:: + WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC); + } + break; + case CookieAccessScheme::kCryptographic: + is_allowed_to_access_secure_cookies = true; + break; } // Don't include cookies for requests that don't apply to the cookie domain. if (!IsDomainMatch(url.host())) @@ -771,21 +781,56 @@ // TODO(chlily): Log metrics. return CookieAccessResult(effective_same_site, status, - params.access_semantics); + params.access_semantics, + is_allowed_to_access_secure_cookies); } CookieAccessResult CanonicalCookie::IsSetPermittedInContext( + const GURL& source_url, const CookieOptions& options, const CookieAccessParams& params) const { CookieAccessResult access_result; - IsSetPermittedInContext(options, params, &access_result); + IsSetPermittedInContext(source_url, options, params, &access_result); return access_result; } void CanonicalCookie::IsSetPermittedInContext( + const GURL& source_url, const CookieOptions& options, const CookieAccessParams& params, CookieAccessResult* access_result) const { + CookieAccessScheme access_scheme = + cookie_util::ProvisionalAccessScheme(source_url); + if (access_scheme == CookieAccessScheme::kNonCryptographic && + params.delegate_treats_url_as_trustworthy) { + access_scheme = CookieAccessScheme::kTrustworthy; + } + + switch (access_scheme) { + case CookieAccessScheme::kNonCryptographic: + access_result->is_allowed_to_access_secure_cookies = false; + if (IsSecure()) { + access_result->status.AddExclusionReason( + CookieInclusionStatus::EXCLUDE_SECURE_ONLY); + } + break; + + case CookieAccessScheme::kCryptographic: + // All cool! + access_result->is_allowed_to_access_secure_cookies = true; + break; + + case CookieAccessScheme::kTrustworthy: + access_result->is_allowed_to_access_secure_cookies = true; + if (IsSecure()) { + // OK, but want people aware of this. + access_result->status.AddWarningReason( + CookieInclusionStatus:: + WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC); + } + break; + } + access_result->access_semantics = params.access_semantics; if (options.exclude_httponly() && IsHttpOnly()) { DVLOG(net::cookie_util::kVlogSetCookies)
diff --git a/net/cookies/canonical_cookie.h b/net/cookies/canonical_cookie.h index 4bed1a1..19a47412 100644 --- a/net/cookies/canonical_cookie.h +++ b/net/cookies/canonical_cookie.h
@@ -312,11 +312,13 @@ // in a secure scheme, since whether the scheme is secure isn't part of // |options|. CookieAccessResult IsSetPermittedInContext( + const GURL& source_url, const CookieOptions& options, const CookieAccessParams& params) const; // Overload that updates an existing |status| rather than returning a new one. - void IsSetPermittedInContext(const CookieOptions& options, + void IsSetPermittedInContext(const GURL& source_url, + const CookieOptions& options, const CookieAccessParams& params, CookieAccessResult* access_result) const;
diff --git a/net/cookies/canonical_cookie_unittest.cc b/net/cookies/canonical_cookie_unittest.cc index d453618..3482b545 100644 --- a/net/cookies/canonical_cookie_unittest.cc +++ b/net/cookies/canonical_cookie_unittest.cc
@@ -10,7 +10,10 @@ #include "build/build_config.h" #include "net/base/features.h" #include "net/cookies/cookie_constants.h" +#include "net/cookies/cookie_inclusion_status.h" #include "net/cookies/cookie_options.h" +#include "testing/gmock/include/gmock/gmock-matchers.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/third_party/mozilla/url_parse.h" @@ -29,8 +32,71 @@ EXPECT_EQ(line, CanonicalCookie::BuildCookieLine(list)); } +// Helper for checking CookieAccessResults. Should be called with matchers (or +// values) for each of the fields of a CookieAccessResult. +MATCHER_P4(MatchesCookieAccessResult, + status, + effective_same_site, + access_semantics, + is_allowed_to_access_secure_cookies, + "") { + return testing::ExplainMatchResult( + testing::AllOf( + testing::Field(&CookieAccessResult::status, status), + testing::Field(&CookieAccessResult::effective_same_site, + effective_same_site), + testing::Field(&CookieAccessResult::access_semantics, + access_semantics), + testing::Field( + &CookieAccessResult::is_allowed_to_access_secure_cookies, + is_allowed_to_access_secure_cookies)), + arg, result_listener); +} + +// Helper for checking that status.HasDowngradeWarning() == true. +MATCHER(HasDowngradeWarning, "") { + CookieInclusionStatus status = arg; + return testing::ExplainMatchResult(true, status.HasDowngradeWarning(), + result_listener); +} + +// Helper for checking that status.HasWarningReason(reason) == true. +MATCHER_P(HasWarningReason, reason, "") { + CookieInclusionStatus status = arg; + return testing::ExplainMatchResult(true, status.HasWarningReason(reason), + result_listener); +} + +// Helper for checking that status.HasExclusionReason(reason) == true. +MATCHER_P(HasExclusionReason, reason, "") { + CookieInclusionStatus status = arg; + return testing::ExplainMatchResult(true, status.HasExclusionReason(reason), + result_listener); +} + +// Helper for checking that status.HasExactlyExclusionReasonsForTesting(reasons) +// == true. +MATCHER_P(HasExactlyExclusionReasonsForTesting, reasons, "") { + CookieInclusionStatus status = arg; + return testing::ExplainMatchResult( + true, status.HasExactlyExclusionReasonsForTesting(reasons), + result_listener); +} + +// Helper for checking that status.IsInclude() == true. +MATCHER(IsInclude, "") { + CookieInclusionStatus status = arg; + return testing::ExplainMatchResult(true, status.IsInclude(), result_listener); +} + } // namespace +using testing::_; +using testing::AllOf; +using testing::Eq; +using testing::Not; +using testing::Property; + TEST(CanonicalCookieTest, Constructor) { base::Time current_time = base::Time::Now(); @@ -961,14 +1027,15 @@ CookieOptions request_options; request_options.set_same_site_cookie_context( test.request_options_samesite_context); - net::CookieAccessResult access_result = cookie->IncludeForRequestURL( - url, request_options, - CookieAccessParams{access_semantics, - /*delegate_treats_url_as_trustworthy=*/false}); - EXPECT_EQ(test.expected_inclusion_status, access_result.status); - EXPECT_EQ(test.expected_effective_samesite, - access_result.effective_same_site); + EXPECT_THAT( + cookie->IncludeForRequestURL( + url, request_options, + CookieAccessParams{access_semantics, + /*delegate_treats_url_as_trustworthy=*/false}), + MatchesCookieAccessResult(test.expected_inclusion_status, + test.expected_effective_samesite, + access_semantics, true)); } } @@ -1437,18 +1504,20 @@ "name", "value", "other-domain.com", "/bar", creation_time, base::Time(), base::Time(), true /* secure */, true /* httponly */, CookieSameSite::STRICT_MODE, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_TRUE( - cookie1 - ->IncludeForRequestURL( - url, options, - CookieAccessParams{CookieAccessSemantics::UNKNOWN, - /*delegate_treats_url_as_trustworthy=*/false}) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus::EXCLUDE_HTTP_ONLY, - CookieInclusionStatus::EXCLUDE_SECURE_ONLY, - CookieInclusionStatus::EXCLUDE_DOMAIN_MISMATCH, - CookieInclusionStatus::EXCLUDE_NOT_ON_PATH, - CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT})); + EXPECT_THAT( + cookie1->IncludeForRequestURL( + url, options, + CookieAccessParams{CookieAccessSemantics::UNKNOWN, + /*delegate_treats_url_as_trustworthy=*/false}), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting({ + CookieInclusionStatus::EXCLUDE_HTTP_ONLY, + CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + CookieInclusionStatus::EXCLUDE_DOMAIN_MISMATCH, + CookieInclusionStatus::EXCLUDE_NOT_ON_PATH, + CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT, + }), + _, _, false)); // Test Create() CookieInclusionStatus create_status; @@ -1464,15 +1533,16 @@ auto cookie3 = CanonicalCookie::Create( url, "name=value;HttpOnly;SameSite=Lax", creation_time, server_time); ASSERT_TRUE(cookie3); - EXPECT_TRUE( - cookie3 - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( + EXPECT_THAT( + cookie3->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting( {CookieInclusionStatus::EXCLUDE_HTTP_ONLY, - CookieInclusionStatus::EXCLUDE_SAMESITE_LAX})); + CookieInclusionStatus::EXCLUDE_SAMESITE_LAX}), + _, _, false)); } TEST(CanonicalCookieTest, PartialCompare) { @@ -2498,7 +2568,8 @@ } TEST(CanonicalCookieTest, IsSetPermittedInContext) { - GURL url("http://www.example.com/test"); + GURL url("https://www.example.com/test"); + GURL insecure_url("http://www.example.com/test"); base::Time current_time = base::Time::Now(); auto cookie_scriptable = CanonicalCookie::CreateUnsafeCookieForTesting( @@ -2514,36 +2585,43 @@ CookieOptions context_network; context_network.set_include_httponly(); - EXPECT_TRUE(cookie_scriptable - ->IsSetPermittedInContext( - context_network, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_scriptable - ->IsSetPermittedInContext( - context_script, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_scriptable->IsSetPermittedInContext( + insecure_url, context_network, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}), + _, _, false)); + EXPECT_THAT( + cookie_scriptable->IsSetPermittedInContext( + url, context_network, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_scriptable->IsSetPermittedInContext( + url, context_script, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); - EXPECT_TRUE(cookie_httponly - ->IsSetPermittedInContext( - context_network, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_httponly - ->IsSetPermittedInContext( - context_script, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus::EXCLUDE_HTTP_ONLY})); + EXPECT_THAT( + cookie_httponly->IsSetPermittedInContext( + url, context_network, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_httponly->IsSetPermittedInContext( + url, context_script, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_HTTP_ONLY}), + _, _, true)); CookieOptions context_cross_site; CookieOptions context_same_site_lax; @@ -2580,99 +2658,84 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_TRUE(cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); { // Schemeful Same-Site disabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_cross.IsInclude()); - EXPECT_FALSE(status_strict_to_cross.HasDowngradeWarning()); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_lax_to_cross.IsInclude()); - EXPECT_FALSE(status_lax_to_cross.HasDowngradeWarning()); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); } { // Schemeful Same-Site enabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_cross.IsInclude()); - EXPECT_FALSE(status_strict_to_cross.HasDowngradeWarning()); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_unrestricted - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_lax_to_cross.IsInclude()); - EXPECT_FALSE(status_lax_to_cross.HasDowngradeWarning()); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_unrestricted->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); } } @@ -2682,108 +2745,103 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_TRUE(cookie_same_site_lax - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus::EXCLUDE_SAMESITE_LAX})); - EXPECT_TRUE(cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_SAMESITE_LAX}), + _, _, true)); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); { // Schemeful Same-Site disabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_cross.IsInclude()); - EXPECT_TRUE(status_strict_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_STRICT_CROSS_DOWNGRADE_LAX_SAMESITE)); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_lax_to_cross.IsInclude()); - EXPECT_TRUE(status_lax_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_LAX_CROSS_DOWNGRADE_LAX_SAMESITE)); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT(cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), + HasWarningReason( + CookieInclusionStatus:: + WARN_STRICT_CROSS_DOWNGRADE_LAX_SAMESITE)), + _, _, true)); + EXPECT_THAT(cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), + HasWarningReason( + CookieInclusionStatus:: + WARN_LAX_CROSS_DOWNGRADE_LAX_SAMESITE)), + _, _, true)); } { // Schemeful Same-Site enabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_FALSE(status_strict_to_cross.IsInclude()); - EXPECT_TRUE(status_strict_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_STRICT_CROSS_DOWNGRADE_LAX_SAMESITE)); - EXPECT_TRUE(status_strict_to_cross.HasExclusionReason( - CookieInclusionStatus::EXCLUDE_SAMESITE_LAX)); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_lax - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_FALSE(status_lax_to_cross.IsInclude()); - EXPECT_TRUE(status_lax_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_LAX_CROSS_DOWNGRADE_LAX_SAMESITE)); - EXPECT_TRUE(status_strict_to_cross.HasExclusionReason( - CookieInclusionStatus::EXCLUDE_SAMESITE_LAX)); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT(cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(Not(IsInclude()), + HasWarningReason( + CookieInclusionStatus:: + WARN_STRICT_CROSS_DOWNGRADE_LAX_SAMESITE), + HasExclusionReason( + CookieInclusionStatus::EXCLUDE_SAMESITE_LAX)), + _, _, true)); + EXPECT_THAT( + cookie_same_site_lax->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(Not(IsInclude()), + HasWarningReason(CookieInclusionStatus:: + WARN_LAX_CROSS_DOWNGRADE_LAX_SAMESITE), + HasExclusionReason( + CookieInclusionStatus::EXCLUDE_SAMESITE_LAX)), + _, _, true)); } } @@ -2796,108 +2854,106 @@ // TODO(morlovich): Do compatibility testing on whether set of strict in lax // context really should be accepted. - EXPECT_TRUE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT})); - EXPECT_TRUE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + CookieInclusionStatus::MakeFromReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT}), + _, _, true)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); { // Schemeful Same-Site disabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_cross.IsInclude()); - EXPECT_TRUE(status_strict_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_STRICT_CROSS_DOWNGRADE_STRICT_SAMESITE)); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_lax_to_cross.IsInclude()); - EXPECT_TRUE(status_lax_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_LAX_CROSS_DOWNGRADE_STRICT_SAMESITE)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), + HasWarningReason( + CookieInclusionStatus:: + WARN_STRICT_CROSS_DOWNGRADE_STRICT_SAMESITE)), + _, _, true)); + EXPECT_THAT(cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), + HasWarningReason( + CookieInclusionStatus:: + WARN_LAX_CROSS_DOWNGRADE_STRICT_SAMESITE)), + _, _, true)); } { // Schemeful Same-Site enabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kSchemefulSameSite); - CookieInclusionStatus status_strict_to_lax = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_TRUE(status_strict_to_lax.IsInclude()); - EXPECT_FALSE(status_strict_to_lax.HasDowngradeWarning()); - CookieInclusionStatus status_strict_to_cross = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_FALSE(status_strict_to_cross.IsInclude()); - EXPECT_TRUE(status_strict_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_STRICT_CROSS_DOWNGRADE_STRICT_SAMESITE)); - EXPECT_TRUE(status_strict_to_cross.HasExclusionReason( - CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT)); - CookieInclusionStatus status_lax_to_cross = - cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_lax_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status; - EXPECT_FALSE(status_lax_to_cross.IsInclude()); - EXPECT_TRUE(status_lax_to_cross.HasWarningReason( - CookieInclusionStatus::WARN_LAX_CROSS_DOWNGRADE_STRICT_SAMESITE)); - EXPECT_TRUE(status_strict_to_cross.HasExclusionReason( - CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_lax, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(IsInclude(), Not(HasDowngradeWarning())), _, _, true)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(Not(IsInclude()), + HasWarningReason( + CookieInclusionStatus:: + WARN_STRICT_CROSS_DOWNGRADE_STRICT_SAMESITE), + HasExclusionReason( + CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT)), + _, _, true)); + EXPECT_THAT( + cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_lax_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + AllOf(Not(IsInclude()), + HasWarningReason( + CookieInclusionStatus:: + WARN_LAX_CROSS_DOWNGRADE_STRICT_SAMESITE), + HasExclusionReason( + CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT)), + _, _, true)); } // Even with Schemeful Same-Site enabled, cookies semantics could change the @@ -2906,29 +2962,26 @@ base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kSchemefulSameSite); - EXPECT_FALSE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_FALSE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT(cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(Not(IsInclude()), _, _, true)); + EXPECT_THAT(cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(Not(IsInclude()), _, _, true)); // LEGACY semantics should allow cookies which Schemeful Same-Site would // normally block. - EXPECT_TRUE(cookie_same_site_strict - ->IsSetPermittedInContext( - context_same_site_strict_to_cross, - CookieAccessParams( - CookieAccessSemantics::LEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT(cookie_same_site_strict->IsSetPermittedInContext( + url, context_same_site_strict_to_cross, + CookieAccessParams( + CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); } } @@ -2943,144 +2996,135 @@ base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kSameSiteByDefaultCookies); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus:: - EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + HasExactlyExclusionReasonsForTesting( + std::vector<CookieInclusionStatus::ExclusionReason>( + {CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})), + _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); } { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kSameSiteByDefaultCookies); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus:: - EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::LEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::LEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::LEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_cross_site, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.HasExactlyExclusionReasonsForTesting( - {CookieInclusionStatus:: - EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_lax, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); - EXPECT_TRUE(cookie_same_site_unspecified - ->IsSetPermittedInContext( - context_same_site_strict, - CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .status.IsInclude()); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + HasExactlyExclusionReasonsForTesting( + std::vector<CookieInclusionStatus::ExclusionReason>( + {CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})), + _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_cross_site, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + HasExactlyExclusionReasonsForTesting( + std::vector<CookieInclusionStatus::ExclusionReason>( + {CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX})), + _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_lax, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); + EXPECT_THAT( + cookie_same_site_unspecified->IsSetPermittedInContext( + url, context_same_site_strict, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(IsInclude(), _, _, true)); } } @@ -3096,14 +3140,13 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_EQ( - cookie_no_restriction - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::NO_RESTRICTION); + EXPECT_THAT( + cookie_no_restriction->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(_, CookieEffectiveSameSite::NO_RESTRICTION, _, + false)); // Test IsSetPermitted CookieEffectiveSameSite for // CanonicalCookie with CookieSameSite::LAX_MODE. @@ -3112,14 +3155,13 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_EQ( - cookie_lax - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::LAX_MODE); + EXPECT_THAT( + cookie_lax->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(_, CookieEffectiveSameSite::LAX_MODE, _, + false)); // Test IsSetPermitted CookieEffectiveSameSite for // CanonicalCookie with CookieSameSite::STRICT_MODE. @@ -3128,14 +3170,13 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::STRICT_MODE, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_EQ( - cookie_strict - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::STRICT_MODE); + EXPECT_THAT( + cookie_strict->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(_, CookieEffectiveSameSite::STRICT_MODE, _, + false)); // Test IsSetPermitted CookieEffectiveSameSite for // CanonicalCookie with CookieSameSite::UNSPECIFIED. @@ -3149,41 +3190,87 @@ base::Time(), true /*secure*/, false /*httponly*/, CookieSameSite::UNSPECIFIED, COOKIE_PRIORITY_DEFAULT, false); - EXPECT_EQ( - cookie_old_unspecified - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::LAX_MODE); + EXPECT_THAT( + cookie_old_unspecified->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(_, CookieEffectiveSameSite::LAX_MODE, _, + false)); - EXPECT_EQ( - cookie_unspecified - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::UNKNOWN, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE); + EXPECT_THAT( + cookie_unspecified->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::UNKNOWN, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + _, CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE, _, false)); - EXPECT_EQ( - cookie_unspecified - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::NONLEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE); + EXPECT_THAT( + cookie_unspecified->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::NONLEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult( + _, CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE, _, false)); - EXPECT_EQ( - cookie_unspecified - ->IsSetPermittedInContext( - options, CookieAccessParams( - CookieAccessSemantics::LEGACY, - false /* delegate_treats_url_as_trustworthy */)) - .effective_same_site, - CookieEffectiveSameSite::NO_RESTRICTION); + EXPECT_THAT( + cookie_unspecified->IsSetPermittedInContext( + url, options, + CookieAccessParams(CookieAccessSemantics::LEGACY, + false /* delegate_treats_url_as_trustworthy */)), + MatchesCookieAccessResult(_, CookieEffectiveSameSite::NO_RESTRICTION, _, + false)); +} + +TEST(CanonicalCookieTest, IsSetPermitted_AllowedToAccessSecureCookies) { + GURL url("https://www.example.com/test"); + GURL insecure_url("http://www.example.com/test"); + GURL localhost_url("http://localhost/test"); + base::Time current_time = base::Time::Now(); + CookieOptions options; + + for (bool secure : {false, true}) { + for (CookieSameSite same_site : { + CookieSameSite::UNSPECIFIED, + CookieSameSite::NO_RESTRICTION, + CookieSameSite::LAX_MODE, + CookieSameSite::STRICT_MODE, + }) { + auto cookie = CanonicalCookie::CreateUnsafeCookieForTesting( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), secure, false /*httponly*/, same_site, + COOKIE_PRIORITY_DEFAULT, false); + + for (bool delegate_treats_url_as_trustworthy : {false, true}) { + for (CookieAccessSemantics access_semantics : { + CookieAccessSemantics::UNKNOWN, + CookieAccessSemantics::LEGACY, + CookieAccessSemantics::NONLEGACY, + }) { + EXPECT_THAT( + cookie->IsSetPermittedInContext( + url, options, + CookieAccessParams(access_semantics, + delegate_treats_url_as_trustworthy)), + MatchesCookieAccessResult(_, _, _, true)); + EXPECT_THAT( + cookie->IsSetPermittedInContext( + insecure_url, options, + CookieAccessParams(access_semantics, + delegate_treats_url_as_trustworthy)), + MatchesCookieAccessResult(_, _, _, + delegate_treats_url_as_trustworthy)); + EXPECT_THAT( + cookie->IsSetPermittedInContext( + localhost_url, options, + CookieAccessParams(access_semantics, + delegate_treats_url_as_trustworthy)), + MatchesCookieAccessResult(_, _, _, true)); + } + } + } + } } } // namespace net
diff --git a/net/cookies/cookie_access_result.cc b/net/cookies/cookie_access_result.cc index d6182543..faa89ca1 100644 --- a/net/cookies/cookie_access_result.cc +++ b/net/cookies/cookie_access_result.cc
@@ -11,10 +11,13 @@ CookieAccessResult::CookieAccessResult( CookieEffectiveSameSite effective_same_site, CookieInclusionStatus status, - CookieAccessSemantics access_semantics) + CookieAccessSemantics access_semantics, + bool is_allowed_to_access_secure_cookies) : status(status), effective_same_site(effective_same_site), - access_semantics(access_semantics) {} + access_semantics(access_semantics), + is_allowed_to_access_secure_cookies(is_allowed_to_access_secure_cookies) { +} CookieAccessResult::CookieAccessResult(CookieInclusionStatus status) : status(status) {}
diff --git a/net/cookies/cookie_access_result.h b/net/cookies/cookie_access_result.h index 7e5aa208..0c99a19 100644 --- a/net/cookies/cookie_access_result.h +++ b/net/cookies/cookie_access_result.h
@@ -5,6 +5,8 @@ #ifndef NET_COOKIES_COOKIE_ACCESS_RESULT_H_ #define NET_COOKIES_COOKIE_ACCESS_RESULT_H_ +#include <ostream> + #include "net/base/net_export.h" #include "net/cookies/cookie_constants.h" #include "net/cookies/cookie_inclusion_status.h" @@ -18,7 +20,8 @@ CookieAccessResult(); CookieAccessResult(CookieEffectiveSameSite effective_same_site, CookieInclusionStatus status, - CookieAccessSemantics access_semantics); + CookieAccessSemantics access_semantics, + bool is_allowed_to_access_secure_cookie); explicit CookieAccessResult(CookieInclusionStatus status); @@ -34,8 +37,21 @@ CookieEffectiveSameSite effective_same_site = CookieEffectiveSameSite::UNDEFINED; CookieAccessSemantics access_semantics = CookieAccessSemantics::UNKNOWN; + // Whether access to Secure cookies should be allowed. This is expected to be + // set based on the scheme of the source URL. + bool is_allowed_to_access_secure_cookies = false; }; +// Provided to allow gtest to create more helpful error messages, instead of +// printing hex. +inline void PrintTo(const CookieAccessResult& car, std::ostream* os) { + *os << "{ { "; + PrintTo(car.status, os); + *os << " }, " << static_cast<int>(car.effective_same_site) << ", " + << static_cast<int>(car.access_semantics) << ", " + << car.is_allowed_to_access_secure_cookies << " }"; +} + } // namespace net #endif // NET_COOKIES_COOKIE_ACCESS_RESULT_H_
diff --git a/net/cookies/cookie_inclusion_status.h b/net/cookies/cookie_inclusion_status.h index 59f64971..ebbf732 100644 --- a/net/cookies/cookie_inclusion_status.h +++ b/net/cookies/cookie_inclusion_status.h
@@ -292,6 +292,12 @@ return os << status.GetDebugString(); } +// Provided to allow gtest to create more helpful error messages, instead of +// printing hex. +inline void PrintTo(const CookieInclusionStatus& cis, std::ostream* os) { + *os << cis; +} + } // namespace net #endif // NET_COOKIES_COOKIE_INCLUSION_STATUS_H_
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index 8629273..dd6f8ad 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -1190,37 +1190,6 @@ bool delegate_treats_url_as_trustworthy = cookie_access_delegate() && cookie_access_delegate()->ShouldTreatUrlAsTrustworthy(source_url); - CookieAccessScheme access_scheme = - cookie_util::ProvisionalAccessScheme(source_url); - if (access_scheme == CookieAccessScheme::kNonCryptographic && - delegate_treats_url_as_trustworthy) { - access_scheme = CookieAccessScheme::kTrustworthy; - } - - bool allowed_to_set_secure_cookie = false; - switch (access_scheme) { - case CookieAccessScheme::kNonCryptographic: - if (cc->IsSecure()) { - access_result.status.AddExclusionReason( - CookieInclusionStatus::EXCLUDE_SECURE_ONLY); - } - break; - - case CookieAccessScheme::kCryptographic: - // All cool! - allowed_to_set_secure_cookie = true; - break; - - case CookieAccessScheme::kTrustworthy: - allowed_to_set_secure_cookie = true; - if (cc->IsSecure()) { - // OK, but want people aware of this. - access_result.status.AddWarningReason( - CookieInclusionStatus:: - WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC); - } - break; - } if (!IsCookieableScheme(source_url.scheme())) { access_result.status.AddExclusionReason( @@ -1230,7 +1199,7 @@ const std::string key(GetKey(cc->Domain())); cc->IsSetPermittedInContext( - options, + source_url, options, CookieAccessParams(GetAccessSemanticsForCookie(*cc), delegate_treats_url_as_trustworthy), &access_result); @@ -1248,8 +1217,9 @@ // deletes an existing cookie, so any ExclusionReasons in |status| that would // prevent such deletion should be finalized beforehand. MaybeDeleteEquivalentCookieAndUpdateStatus( - key, *cc, allowed_to_set_secure_cookie, options.exclude_httponly(), - already_expired, &creation_date_to_inherit, &access_result.status); + key, *cc, access_result.is_allowed_to_access_secure_cookies, + options.exclude_httponly(), already_expired, &creation_date_to_inherit, + &access_result.status); if (access_result.status.HasExclusionReason( CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE) || @@ -1427,11 +1397,13 @@ store_->DeleteCookie(*cc); } change_dispatcher_.DispatchChange( - CookieChangeInfo(*cc, - CookieAccessResult(CookieEffectiveSameSite::UNDEFINED, - CookieInclusionStatus(), - GetAccessSemanticsForCookie(*cc)), - mapping.cause), + CookieChangeInfo( + *cc, + CookieAccessResult(CookieEffectiveSameSite::UNDEFINED, + CookieInclusionStatus(), + GetAccessSemanticsForCookie(*cc), + true /* is_allowed_to_access_secure_cookies */), + mapping.cause), mapping.notify); // If this is the last cookie in |cookies_| with this key, decrement the
diff --git a/net/url_request/test_url_fetcher_factory.cc b/net/url_request/test_url_fetcher_factory.cc index 4a203b9..aeffb23 100644 --- a/net/url_request/test_url_fetcher_factory.cc +++ b/net/url_request/test_url_fetcher_factory.cc
@@ -107,14 +107,13 @@ void TestURLFetcher::SetReferrerPolicy(ReferrerPolicy referrer_policy) {} -void TestURLFetcher::SetExtraRequestHeaders( - const std::string& extra_request_headers) { +void TestURLFetcher::ClearExtraRequestHeaders() { fake_extra_request_headers_.Clear(); - fake_extra_request_headers_.AddHeadersFromString(extra_request_headers); } -void TestURLFetcher::AddExtraRequestHeader(const std::string& header_line) { - fake_extra_request_headers_.AddHeaderFromString(header_line); +void TestURLFetcher::AddExtraRequestHeader(const std::string& name, + const std::string& value) { + fake_extra_request_headers_.SetHeader(name, value); } void TestURLFetcher::SetRequestContext(
diff --git a/net/url_request/test_url_fetcher_factory.h b/net/url_request/test_url_fetcher_factory.h index fa873375..b886249 100644 --- a/net/url_request/test_url_fetcher_factory.h +++ b/net/url_request/test_url_fetcher_factory.h
@@ -116,9 +116,9 @@ void SetAllowCredentials(bool allow_credentials) override {} void SetReferrer(const std::string& referrer) override; void SetReferrerPolicy(ReferrerPolicy referrer_policy) override; - void SetExtraRequestHeaders( - const std::string& extra_request_headers) override; - void AddExtraRequestHeader(const std::string& header_line) override; + void ClearExtraRequestHeaders() override; + void AddExtraRequestHeader(const std::string& name, + const std::string& value) override; void SetRequestContext( URLRequestContextGetter* request_context_getter) override; void SetInitiator(const base::Optional<url::Origin>& initiator) override;
diff --git a/net/url_request/url_fetcher.h b/net/url_request/url_fetcher.h index cbdce6a..9a8bead 100644 --- a/net/url_request/url_fetcher.h +++ b/net/url_request/url_fetcher.h
@@ -207,16 +207,15 @@ // The referrer policy may only be changed before Start() is called. virtual void SetReferrerPolicy(ReferrerPolicy referrer_policy) = 0; - // Set extra headers on the request. Must be called before the request - // is started. - // This replaces the entire extra request headers. - virtual void SetExtraRequestHeaders( - const std::string& extra_request_headers) = 0; + // Clear all extra headers on the request (if any have been set before). + // Must be called before the request is started. + virtual void ClearExtraRequestHeaders() = 0; - // Add header (with format field-name ":" [ field-value ]) to the request - // headers. Must be called before the request is started. + // Add an extra header to the request headers. Must be called before the + // request is started. // This appends the header to the current extra request headers. - virtual void AddExtraRequestHeader(const std::string& header_line) = 0; + virtual void AddExtraRequestHeader(const std::string& name, + const std::string& value) = 0; // Set the URLRequestContext on the request. Must be called before the // request is started.
diff --git a/net/url_request/url_fetcher_core.cc b/net/url_request/url_fetcher_core.cc index 754dd86..d3e7d8c 100644 --- a/net/url_request/url_fetcher_core.cc +++ b/net/url_request/url_fetcher_core.cc
@@ -231,14 +231,13 @@ referrer_policy_ = referrer_policy; } -void URLFetcherCore::SetExtraRequestHeaders( - const std::string& extra_request_headers) { +void URLFetcherCore::ClearExtraRequestHeaders() { extra_request_headers_.Clear(); - extra_request_headers_.AddHeadersFromString(extra_request_headers); } -void URLFetcherCore::AddExtraRequestHeader(const std::string& header_line) { - extra_request_headers_.AddHeaderFromString(header_line); +void URLFetcherCore::AddExtraRequestHeader(const std::string& name, + const std::string& value) { + extra_request_headers_.SetHeader(name, value); } void URLFetcherCore::SetRequestContext(
diff --git a/net/url_request/url_fetcher_core.h b/net/url_request/url_fetcher_core.h index 6b10769..25c0976 100644 --- a/net/url_request/url_fetcher_core.h +++ b/net/url_request/url_fetcher_core.h
@@ -90,8 +90,8 @@ void SetAllowCredentials(bool allow_credentials); void SetReferrer(const std::string& referrer); void SetReferrerPolicy(ReferrerPolicy referrer_policy); - void SetExtraRequestHeaders(const std::string& extra_request_headers); - void AddExtraRequestHeader(const std::string& header_line); + void ClearExtraRequestHeaders(); + void AddExtraRequestHeader(const std::string& name, const std::string& value); void SetRequestContext(URLRequestContextGetter* request_context_getter); // Set the origin that should be considered as "initiating" the fetch. This // URL
diff --git a/net/url_request/url_fetcher_impl.cc b/net/url_request/url_fetcher_impl.cc index 007488b9..255d2fc 100644 --- a/net/url_request/url_fetcher_impl.cc +++ b/net/url_request/url_fetcher_impl.cc
@@ -75,13 +75,13 @@ return core_->GetLoadFlags(); } -void URLFetcherImpl::SetExtraRequestHeaders( - const std::string& extra_request_headers) { - core_->SetExtraRequestHeaders(extra_request_headers); +void URLFetcherImpl::ClearExtraRequestHeaders() { + core_->ClearExtraRequestHeaders(); } -void URLFetcherImpl::AddExtraRequestHeader(const std::string& header_line) { - core_->AddExtraRequestHeader(header_line); +void URLFetcherImpl::AddExtraRequestHeader(const std::string& name, + const std::string& value) { + core_->AddExtraRequestHeader(name, value); } void URLFetcherImpl::SetRequestContext(
diff --git a/net/url_request/url_fetcher_impl.h b/net/url_request/url_fetcher_impl.h index 9be0ba37..338ad08 100644 --- a/net/url_request/url_fetcher_impl.h +++ b/net/url_request/url_fetcher_impl.h
@@ -55,9 +55,9 @@ int GetLoadFlags() const override; void SetReferrer(const std::string& referrer) override; void SetReferrerPolicy(ReferrerPolicy referrer_policy) override; - void SetExtraRequestHeaders( - const std::string& extra_request_headers) override; - void AddExtraRequestHeader(const std::string& header_line) override; + void ClearExtraRequestHeaders() override; + void AddExtraRequestHeader(const std::string& name, + const std::string& value) override; void SetRequestContext( URLRequestContextGetter* request_context_getter) override; void SetInitiator(const base::Optional<url::Origin>& initiator) override;
diff --git a/net/url_request/url_fetcher_impl_unittest.cc b/net/url_request/url_fetcher_impl_unittest.cc index 042910c..d2bcead 100644 --- a/net/url_request/url_fetcher_impl_unittest.cc +++ b/net/url_request/url_fetcher_impl_unittest.cc
@@ -1431,7 +1431,8 @@ EXPECT_EQ("request1", data); fetcher()->SetRequestContext(second_request_context_getter_.get()); - fetcher()->SetExtraRequestHeaders("test: request2"); + fetcher()->ClearExtraRequestHeaders(); + fetcher()->AddExtraRequestHeader("test", "request2"); fetcher()->Start(); return; } @@ -1454,7 +1455,8 @@ ReuseFetcherDelegate delegate(context_getter); delegate.CreateFetcher(test_server_->GetURL("/echoheader?test"), URLFetcher::GET, context_getter); - delegate.fetcher()->SetExtraRequestHeaders("test: request1"); + delegate.fetcher()->ClearExtraRequestHeaders(); + delegate.fetcher()->AddExtraRequestHeader("test", "request1"); delegate.StartFetcherAndWait(); EXPECT_EQ(OK, delegate.fetcher()->GetError());
diff --git a/ppapi/tests/corb_test_plugin.cc b/ppapi/tests/corb_test_plugin.cc index 15569a8b0..a23597b 100644 --- a/ppapi/tests/corb_test_plugin.cc +++ b/ppapi/tests/corb_test_plugin.cc
@@ -18,7 +18,8 @@ #undef PostMessage #endif -// This is a simple C++ Pepper plugin that enables Plugin Power Saver tests. +// This is a simple C++ Pepper plugin that enables some NetworkService/CORB +// tests (e.g. NetworkServiceRestartBrowserTest.Plugin). class CorbTestInstance : public pp::Instance { public: explicit CorbTestInstance(PP_Instance instance) : pp::Instance(instance) {} @@ -50,6 +51,13 @@ request.SetURL(url); request.SetAllowCrossOriginRequests(true); + // Set the |request_initiator| in the same way as the PDF plugin. + // + // (The PDF plugin is currently the only plugin that depends on relaxing + // `request_initiator_origin_lock` enforcement via + // network::mojom::NetworkService::AddAllowedRequestInitiatorForPlugin.) + request.SetCustomReferrerURL(url); + std::ostringstream msg_builder; std::string response_body; int result = OpenURLRequest(this->pp_instance(), &loader, request,
diff --git a/ppapi/tests/test_url_loader.cc b/ppapi/tests/test_url_loader.cc index 3f87361..5af374e 100644 --- a/ppapi/tests/test_url_loader.cc +++ b/ppapi/tests/test_url_loader.cc
@@ -580,9 +580,9 @@ PASS(); } -// CORB (Cross-Origin Read Blocking) shouldn't apply to plugins with universal -// access (see PepperURLLoaderHost::has_universal_access_) - such plugins may -// have their own CORS-like mechanisms - e.g. crossdomain.xml in Flash). +// CORB (Cross-Origin Read Blocking) should apply, even to plugins with +// universal access like the PDF plugin. +// // This test is quite similar to TestTrustedSameOriginRestriction, but it // explicitly uses a CORB-eligible response (test/json + nosniff) and also // explicitly verifies that the response body was not blocked. @@ -595,14 +595,27 @@ request.SetURL(cross_origin_url); request.SetAllowCrossOriginRequests(true); + // The test code below (similarly to the PDF plugin) sets the referrer - this + // will propagate into network::ResourceRequest::request_initiator and should + // match the NetworkService::AddAllowedRequestInitiatorForPlugin exemption. + // This will pass `request_initiator_origin_lock` verification. + std::string referrer = GetReachableAbsoluteURL(""); + request.SetCustomReferrerURL(referrer); + request.SetHeaders(referrer); + std::string response_body; int32_t rv = OpenTrusted(request, &response_body); if (rv != PP_OK) return ReportError("Trusted CORB-eligible request failed", rv); - // Main verification - if CORB blocked the response, then |response_body| - // would be empty. - ASSERT_EQ("{ \"foo\": \"bar\" }\n", response_body); + // Main verification - CORB should block the response where the + // `request_initiator` is cross-origin wrt the target URL. + // + // Note that this case (and CORB blocking) does never apply to the PDF plugin, + // because the PDF plugin only triggers requests where both + // `request_initiator` and the target URL are based on the URL of the PDF + // document (i.e. they are same-origin wrt each other). + ASSERT_EQ("", response_body); PASS(); } @@ -718,11 +731,15 @@ ASSERT_EQ(PP_OK, OpenTrusted("GET", "Via:\n")); ASSERT_EQ(PP_OK, OpenTrusted("GET", "Sec-foo:\n")); } - // Trusted requests with custom referrer should succeed. + // Trusted requests with custom referrer should succeed. Note that the + // referrer has to be from the same origin as the plugin (this matches the + // behavior of the PDF plugin, which after Flash removal is the only plugin + // that depends on custom referrers). { pp::URLRequestInfo request(instance_); - request.SetCustomReferrerURL("http://www.referer.com/"); - request.SetHeaders("Referer: http://www.referer.com/"); + std::string referrer = GetReachableAbsoluteURL(""); + request.SetCustomReferrerURL(referrer); + request.SetHeaders(referrer); int32_t rv = OpenTrusted(request, NULL); if (rv != PP_OK)
diff --git a/services/data_decoder/ble_scan_parser_impl.cc b/services/data_decoder/ble_scan_parser_impl.cc index 78104c8e..7ca658c 100644 --- a/services/data_decoder/ble_scan_parser_impl.cc +++ b/services/data_decoder/ble_scan_parser_impl.cc
@@ -141,7 +141,8 @@ return std::string(); } - std::string uuid = base::HexEncode(bytes.data(), bytes.size()); + std::vector<uint8_t> reversed(bytes.rbegin(), bytes.rend()); + std::string uuid = base::HexEncode(reversed.data(), reversed.size()); switch (format) { case UuidFormat::kFormat16Bit:
diff --git a/services/data_decoder/ble_scan_parser_impl_unittest.cc b/services/data_decoder/ble_scan_parser_impl_unittest.cc index b5897b89..777fa71 100644 --- a/services/data_decoder/ble_scan_parser_impl_unittest.cc +++ b/services/data_decoder/ble_scan_parser_impl_unittest.cc
@@ -22,7 +22,7 @@ TEST(BleScanParserImplTest, Parse16BitUuid) { const uint8_t kUuid16[] = {0xab, 0xcd}; - const char kExpected[] = "0000ABCD-0000-1000-8000-00805F9B34FB"; + const char kExpected[] = "0000CDAB-0000-1000-8000-00805F9B34FB"; std::string actual = BleScanParserImpl::ParseUuid(kUuid16, UuidFormat::kFormat16Bit); EXPECT_STREQ(kExpected, actual.c_str()); @@ -30,7 +30,7 @@ TEST(BleScanParserImplTest, Parse32BitUuid) { const uint8_t kUuid32[] = {0xab, 0xcd, 0xef, 0x01}; - const char kExpected[] = "ABCDEF01-0000-1000-8000-00805F9B34FB"; + const char kExpected[] = "01EFCDAB-0000-1000-8000-00805F9B34FB"; std::string actual = BleScanParserImpl::ParseUuid(kUuid32, UuidFormat::kFormat32Bit); EXPECT_STREQ(kExpected, actual.c_str()); @@ -39,7 +39,7 @@ TEST(BleScanParserImplTest, Parse128BitUuid) { const uint8_t kUuid128[] = {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}; - const char kExpected[] = "ABCDEF01-2345-6789-ABCD-EF0123456789"; + const char kExpected[] = "89674523-01EF-CDAB-8967-452301EFCDAB"; std::string actual = BleScanParserImpl::ParseUuid(kUuid128, UuidFormat::kFormat128Bit); EXPECT_STREQ(kExpected, actual.c_str()); @@ -47,14 +47,14 @@ TEST(BleScanParserImplTest, Parse16BitServiceUuids) { std::vector<device::BluetoothUUID> expected = { - device::BluetoothUUID("0000ABCD-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("0000EF01-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("00002345-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("00006789-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("0000ABCD-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("0000EF01-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("00002345-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("00006789-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("0000CDAB-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("000001EF-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("00004523-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("00008967-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("0000CDAB-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("000001EF-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("00004523-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("00008967-0000-1000-8000-00805F9B34FB"), }; const uint8_t kUuids[] = {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, @@ -68,10 +68,10 @@ TEST(BleScanParserImplTest, Parse32BitServiceUuids) { std::vector<device::BluetoothUUID> expected = { - device::BluetoothUUID("ABCDEF01-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("23456789-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("ABCDEF01-0000-1000-8000-00805F9B34FB"), - device::BluetoothUUID("23456789-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("01EFCDAB-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("89674523-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("01EFCDAB-0000-1000-8000-00805F9B34FB"), + device::BluetoothUUID("89674523-0000-1000-8000-00805F9B34FB"), }; const uint8_t kUuids[] = {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, @@ -85,8 +85,8 @@ TEST(BleScanParserImplTest, Parse128BitServiceUuids) { std::vector<device::BluetoothUUID> expected = { - device::BluetoothUUID("ABCDEF01-2345-6789-ABCD-EF0123456789"), - device::BluetoothUUID("23456789-ABCD-EF01-ABCD-EF0123456789"), + device::BluetoothUUID("89674523-01EF-CDAB-8967-452301EFCDAB"), + device::BluetoothUUID("89674523-01EF-CDAB-01EF-CDAB89674523"), }; const uint8_t kUuids[] = {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, @@ -123,18 +123,18 @@ // Advertising flag = 0x42 0x02, 0x01, 0x42, // 16-bit service UUIDs 0000abcd-... and 0000ef01-... - 0x05, 0x02, 0xab, 0xcd, 0xef, 0x01, + 0x05, 0x02, 0xcd, 0xab, 0x01, 0xef, // TX power = 0x1b 0x02, 0x0a, 0x1b, // 32-bit service UUIDs abcdef01-... and 23456789-... - 0x09, 0x05, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, + 0x09, 0x05, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, // Local name 'Steve' 0x06, 0x08, 0x53, 0x74, 0x65, 0x76, 0x65, // 128-bit service UUID abcdef01-2345-6789-abcd-ef0123456789 - 0x11, 0x06, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, + 0x11, 0x06, 0x89, 0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x67, + 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, // Service data map 0000dcab-... => { 0xa1, 0xb2, 0xc3, 0xd4, 0xe5 } - 0x08, 0x16, 0xdc, 0xab, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, + 0x08, 0x16, 0xab, 0xdc, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, // Manufacturer data map 0xd00d => { 0x1a, 0x2b, 0x3c, 0x4d } 0x07, 0xff, 0x0d, 0xd0, 0x1a, 0x2b, 0x3c, 0x4d};
diff --git a/services/network/BUILD.gn b/services/network/BUILD.gn index 14d8e68..f06c146d 100644 --- a/services/network/BUILD.gn +++ b/services/network/BUILD.gn
@@ -34,8 +34,6 @@ "crash_keys.h", "crl_set_distributor.cc", "crl_set_distributor.h", - "cross_origin_read_blocking_exception_for_plugin.cc", - "cross_origin_read_blocking_exception_for_plugin.h", "data_pipe_element_reader.cc", "data_pipe_element_reader.h", "dns_config_change_manager.cc",
diff --git a/services/network/cors/cors_url_loader_factory.cc b/services/network/cors/cors_url_loader_factory.cc index 7a332fb..7e4d57cf 100644 --- a/services/network/cors/cors_url_loader_factory.cc +++ b/services/network/cors/cors_url_loader_factory.cc
@@ -20,7 +20,6 @@ #include "services/network/cors/cors_url_loader.h" #include "services/network/cors/preflight_controller.h" #include "services/network/crash_keys.h" -#include "services/network/cross_origin_read_blocking_exception_for_plugin.h" #include "services/network/network_context.h" #include "services/network/network_service.h" #include "services/network/public/cpp/cors/cors.h" @@ -405,7 +404,6 @@ switch (initiator_lock_compatibility) { case InitiatorLockCompatibility::kCompatibleLock: case InitiatorLockCompatibility::kBrowserProcess: - case InitiatorLockCompatibility::kExcludedCorbForPlugin: case InitiatorLockCompatibility::kAllowedRequestInitiatorForPlugin: break; @@ -427,7 +425,12 @@ case InitiatorLockCompatibility::kIncorrectLock: // Requests from the renderer need to always specify a correct initiator. - NOTREACHED(); + NOTREACHED() << "request_initiator_origin_lock_ = " + << request_initiator_origin_lock_.value_or( + url::Origin::Create(GURL("https://no-lock.com"))) + << "; request.request_initiator = " + << request.request_initiator.value_or(url::Origin::Create( + GURL("https://no-initiator.com"))); if (base::FeatureList::IsEnabled( features::kRequestInitiatorSiteLockEnfocement)) { url::debug::ScopedOriginCrashKey initiator_lock_crash_key( @@ -517,12 +520,6 @@ request_initiator_origin_lock, request_initiator); if (result == InitiatorLockCompatibility::kIncorrectLock && - CrossOriginReadBlockingExceptionForPlugin::ShouldAllowForPlugin( - process_id)) { - result = InitiatorLockCompatibility::kExcludedCorbForPlugin; - } - - if (result == InitiatorLockCompatibility::kIncorrectLock && request_initiator.has_value() && context_->network_service()->IsInitiatorAllowedForPlugin( process_id, request_initiator.value())) {
diff --git a/services/network/cross_origin_read_blocking_exception_for_plugin.cc b/services/network/cross_origin_read_blocking_exception_for_plugin.cc deleted file mode 100644 index 53faac4..0000000 --- a/services/network/cross_origin_read_blocking_exception_for_plugin.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <set> - -#include "base/no_destructor.h" -#include "base/stl_util.h" -#include "services/network/cross_origin_read_blocking_exception_for_plugin.h" - -namespace network { - -namespace { - -std::set<int>& GetPluginProxyingProcesses() { - static base::NoDestructor<std::set<int>> set; - return *set; -} - -} // namespace - -// static -void CrossOriginReadBlockingExceptionForPlugin::AddExceptionForPlugin( - int process_id) { - std::set<int>& plugin_proxies = GetPluginProxyingProcesses(); - plugin_proxies.insert(process_id); -} - -// static -bool CrossOriginReadBlockingExceptionForPlugin::ShouldAllowForPlugin( - int process_id) { - std::set<int>& plugin_proxies = GetPluginProxyingProcesses(); - return base::Contains(plugin_proxies, process_id); -} - -// static -void CrossOriginReadBlockingExceptionForPlugin::RemoveExceptionForPlugin( - int process_id) { - std::set<int>& plugin_proxies = GetPluginProxyingProcesses(); - plugin_proxies.erase(process_id); -} - -} // namespace network
diff --git a/services/network/cross_origin_read_blocking_exception_for_plugin.h b/services/network/cross_origin_read_blocking_exception_for_plugin.h deleted file mode 100644 index 8203475..0000000 --- a/services/network/cross_origin_read_blocking_exception_for_plugin.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_NETWORK_CROSS_ORIGIN_READ_BLOCKING_EXCEPTION_FOR_PLUGIN_H_ -#define SERVICES_NETWORK_CROSS_ORIGIN_READ_BLOCKING_EXCEPTION_FOR_PLUGIN_H_ - -#include "base/component_export.h" -#include "base/macros.h" - -namespace network { - -class COMPONENT_EXPORT(NETWORK_SERVICE) - CrossOriginReadBlockingExceptionForPlugin { - public: - // Notifies CORB that |process_id| is proxying requests on behalf of a - // universal-access plugin and therefore CORB should stop blocking requests - // marked as ResourceType::kPluginResource. - // - // TODO(lukasza, laforge): https://crbug.com/702995: Remove the static - // ...ForPlugin methods once Flash support is removed from Chromium (probably - // around 2020 - see https://www.chromium.org/flash-roadmap). - static void AddExceptionForPlugin(int process_id); - - // Returns true if CORB should ignore a request initiated by a universal - // access plugin - i.e. if |process_id| has been previously passed to - // AddExceptionForPlugin. - static bool ShouldAllowForPlugin(int process_id); - - // Reverts AddExceptionForPlugin. - static void RemoveExceptionForPlugin(int process_id); - - DISALLOW_COPY_AND_ASSIGN(CrossOriginReadBlockingExceptionForPlugin); -}; - -} // namespace network - -#endif // SERVICES_NETWORK_CROSS_ORIGIN_READ_BLOCKING_EXCEPTION_FOR_PLUGIN_H_
diff --git a/services/network/network_service.cc b/services/network/network_service.cc index ca51e6e..db223e9 100644 --- a/services/network/network_service.cc +++ b/services/network/network_service.cc
@@ -49,7 +49,6 @@ #include "net/ssl/ssl_key_logger_impl.h" #include "net/url_request/url_request_context.h" #include "services/network/crl_set_distributor.h" -#include "services/network/cross_origin_read_blocking_exception_for_plugin.h" #include "services/network/dns_config_change_manager.h" #include "services/network/first_party_sets/preloaded_first_party_sets.h" #include "services/network/http_auth_cache_copier.h" @@ -690,11 +689,6 @@ } #endif -void NetworkService::AddCorbExceptionForPlugin(int32_t process_id) { - DCHECK_NE(mojom::kBrowserProcessId, process_id); - CrossOriginReadBlockingExceptionForPlugin::AddExceptionForPlugin(process_id); -} - void NetworkService::AddAllowedRequestInitiatorForPlugin( int32_t process_id, const url::Origin& allowed_request_initiator) { @@ -706,9 +700,6 @@ void NetworkService::RemoveSecurityExceptionsForPlugin(int32_t process_id) { DCHECK_NE(mojom::kBrowserProcessId, process_id); - CrossOriginReadBlockingExceptionForPlugin::RemoveExceptionForPlugin( - process_id); - std::map<int, std::set<url::Origin>>& map = plugin_origins_; map.erase(process_id); }
diff --git a/services/network/network_service.h b/services/network/network_service.h index 239319f..2d5b1ab0 100644 --- a/services/network/network_service.h +++ b/services/network/network_service.h
@@ -203,7 +203,6 @@ #if defined(OS_WIN) || defined(OS_MAC) void SetEncryptionKey(const std::string& encryption_key) override; #endif - void AddCorbExceptionForPlugin(int32_t process_id) override; void AddAllowedRequestInitiatorForPlugin( int32_t process_id, const url::Origin& allowed_request_initiator) override;
diff --git a/services/network/public/cpp/cookie_manager_mojom_traits.cc b/services/network/public/cpp/cookie_manager_mojom_traits.cc index 215258c7..1b04ea1 100644 --- a/services/network/public/cpp/cookie_manager_mojom_traits.cc +++ b/services/network/public/cpp/cookie_manager_mojom_traits.cc
@@ -457,7 +457,8 @@ if (!c.ReadAccessSemantics(&access_semantics)) return false; - *out = {effective_same_site, status, access_semantics}; + *out = {effective_same_site, status, access_semantics, + c.is_allowed_to_access_secure_cookies()}; return true; }
diff --git a/services/network/public/cpp/cookie_manager_mojom_traits.h b/services/network/public/cpp/cookie_manager_mojom_traits.h index cde54d9..205c315 100644 --- a/services/network/public/cpp/cookie_manager_mojom_traits.h +++ b/services/network/public/cpp/cookie_manager_mojom_traits.h
@@ -217,6 +217,10 @@ const net::CookieAccessResult& c) { return c.access_semantics; } + static bool is_allowed_to_access_secure_cookies( + const net::CookieAccessResult& c) { + return c.is_allowed_to_access_secure_cookies; + } static bool Read(network::mojom::CookieAccessResultDataView access_result, net::CookieAccessResult* out); };
diff --git a/services/network/public/cpp/cookie_manager_mojom_traits_unittest.cc b/services/network/public/cpp/cookie_manager_mojom_traits_unittest.cc index 22317b6e..8fca0ce 100644 --- a/services/network/public/cpp/cookie_manager_mojom_traits_unittest.cc +++ b/services/network/public/cpp/cookie_manager_mojom_traits_unittest.cc
@@ -118,7 +118,7 @@ invalid, copied)); } -TEST(CookieManagerTraitsTest, Rountrips_CookieAccessResult) { +TEST(CookieManagerTraitsTest, Roundtrips_CookieAccessResult) { net::CookieAccessResult original = net::CookieAccessResult( net::CookieEffectiveSameSite::LAX_MODE, net::CookieInclusionStatus( @@ -126,7 +126,8 @@ EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX, net::CookieInclusionStatus:: WARN_SAMESITE_UNSPECIFIED_CROSS_SITE_CONTEXT), - net::CookieAccessSemantics::LEGACY); + net::CookieAccessSemantics::LEGACY, + true /* is_allowed_to_access_secure_cookies */); net::CookieAccessResult copied; EXPECT_TRUE(mojo::test::SerializeAndDeserialize<mojom::CookieAccessResult>( @@ -139,12 +140,14 @@ EXPECT_TRUE(copied.status.HasExactlyWarningReasonsForTesting( {net::CookieInclusionStatus:: WARN_SAMESITE_UNSPECIFIED_CROSS_SITE_CONTEXT})); + EXPECT_EQ(original.is_allowed_to_access_secure_cookies, + copied.is_allowed_to_access_secure_cookies); } TEST(CookieManagerTraitsTest, Rountrips_CookieWithAccessResult) { net::CanonicalCookie original_cookie( "A", "B", "x.y", "/path", base::Time(), base::Time(), base::Time(), - /* secure = */ true, /* http_only = */ false, + /* secure = */ true, /* httponly = */ false, net::CookieSameSite::NO_RESTRICTION, net::COOKIE_PRIORITY_LOW, false); net::CookieWithAccessResult original = {original_cookie, @@ -172,10 +175,10 @@ EXPECT_EQ(original.access_result.status, copied.access_result.status); } -TEST(CookieManagerTraitsTest, Rountrips_CookieAndLineWithAccessResult) { +TEST(CookieManagerTraitsTest, Roundtrips_CookieAndLineWithAccessResult) { net::CanonicalCookie original_cookie( "A", "B", "x.y", "/path", base::Time(), base::Time(), base::Time(), - /* secure = */ true, /* http_only = */ false, + /* secure = */ true, /* httponly = */ false, net::CookieSameSite::NO_RESTRICTION, net::COOKIE_PRIORITY_LOW, false); net::CookieAndLineWithAccessResult original(original_cookie, "cookie-string", @@ -374,14 +377,15 @@ TEST(CookieManagerTraitsTest, Roundtrips_CookieChangeInfo) { net::CanonicalCookie original_cookie( "A", "B", "x.y", "/path", base::Time(), base::Time(), base::Time(), - /* secure = */ false, /* http_only = */ false, + /* secure = */ false, /* httponly = */ false, net::CookieSameSite::UNSPECIFIED, net::COOKIE_PRIORITY_LOW, false); net::CookieChangeInfo original( original_cookie, net::CookieAccessResult(net::CookieEffectiveSameSite::UNDEFINED, net::CookieInclusionStatus(), - net::CookieAccessSemantics::LEGACY), + net::CookieAccessSemantics::LEGACY, + false /* is_allowed_to_access_secure_cookies */), net::CookieChangeCause::EXPLICIT); net::CookieChangeInfo copied;
diff --git a/services/network/public/cpp/cross_origin_read_blocking_unittest.cc b/services/network/public/cpp/cross_origin_read_blocking_unittest.cc index 3f9f0b5..9ea8144 100644 --- a/services/network/public/cpp/cross_origin_read_blocking_unittest.cc +++ b/services/network/public/cpp/cross_origin_read_blocking_unittest.cc
@@ -366,11 +366,9 @@ }, { // Blocked, because the unit test doesn't make a call to - // CrossOriginReadBlocking::AddExceptionForFlash (simulating a behavior - // of a compromised renderer that only pretends to be hosting Flash). - // - // The regular scenario is covered by integration tests: - // OutOfProcessPPAPITest.URLLoaderTrusted. + // NetworkService::AddAllowedRequestInitiatorForPlugin (simulating a + // behavior of a compromised renderer that only pretends to be hosting + // PDF). "Blocked: Cross-site fetch HTML from Flash without CORS", __LINE__, "http://www.b.com/plugin.html", // target_url
diff --git a/services/network/public/cpp/features.cc b/services/network/public/cpp/features.cc index 62a9602f..0fcc0a9 100644 --- a/services/network/public/cpp/features.cc +++ b/services/network/public/cpp/features.cc
@@ -155,11 +155,7 @@ // See also https://crbug.com/920634 const base::Feature kRequestInitiatorSiteLockEnfocement = { "RequestInitiatorSiteLockEnfocement", -#if defined(OS_ANDROID) - base::FEATURE_DISABLED_BY_DEFAULT}; -#else base::FEATURE_ENABLED_BY_DEFAULT}; -#endif // When the CertVerifierService is enabled, certificate verification will not be // performed in the network service, but will instead be brokered to a separate
diff --git a/services/network/public/cpp/initiator_lock_compatibility.h b/services/network/public/cpp/initiator_lock_compatibility.h index 9275c998..4608fe3 100644 --- a/services/network/public/cpp/initiator_lock_compatibility.h +++ b/services/network/public/cpp/initiator_lock_compatibility.h
@@ -44,9 +44,6 @@ // - HTML Imports (see https://crbug.com/871827#c9). kIncorrectLock = 4, - // Covered by CrossOriginReadBlockingExceptionForPlugin::ShouldAllowForPlugin. - kExcludedCorbForPlugin = 6, - // Covered by AddAllowedRequestInitiatorForPlugin. kAllowedRequestInitiatorForPlugin = 7,
diff --git a/services/network/public/cpp/resource_request.cc b/services/network/public/cpp/resource_request.cc index 7228cd0..355ca24 100644 --- a/services/network/public/cpp/resource_request.cc +++ b/services/network/public/cpp/resource_request.cc
@@ -138,8 +138,7 @@ originated_from_service_worker == request.originated_from_service_worker && skip_service_worker == request.skip_service_worker && - corb_detachable == request.corb_detachable && - corb_excluded == request.corb_excluded && mode == request.mode && + corb_detachable == request.corb_detachable && mode == request.mode && credentials_mode == request.credentials_mode && redirect_mode == request.redirect_mode && fetch_integrity == request.fetch_integrity &&
diff --git a/services/network/public/cpp/resource_request.h b/services/network/public/cpp/resource_request.h index c2574b1..b6a7e435 100644 --- a/services/network/public/cpp/resource_request.h +++ b/services/network/public/cpp/resource_request.h
@@ -118,7 +118,6 @@ bool originated_from_service_worker = false; bool skip_service_worker = false; bool corb_detachable = false; - bool corb_excluded = false; mojom::RequestMode mode = mojom::RequestMode::kNoCors; mojom::CredentialsMode credentials_mode = mojom::CredentialsMode::kInclude; mojom::RedirectMode redirect_mode = mojom::RedirectMode::kFollow;
diff --git a/services/network/public/cpp/url_request_mojom_traits.cc b/services/network/public/cpp/url_request_mojom_traits.cc index 6aeb457..b44e8cf2 100644 --- a/services/network/public/cpp/url_request_mojom_traits.cc +++ b/services/network/public/cpp/url_request_mojom_traits.cc
@@ -239,7 +239,6 @@ out->originated_from_service_worker = data.originated_from_service_worker(); out->skip_service_worker = data.skip_service_worker(); out->corb_detachable = data.corb_detachable(); - out->corb_excluded = data.corb_excluded(); out->destination = data.destination(); out->keepalive = data.keepalive(); out->has_user_gesture = data.has_user_gesture();
diff --git a/services/network/public/cpp/url_request_mojom_traits.h b/services/network/public/cpp/url_request_mojom_traits.h index 51075e7..819cab67 100644 --- a/services/network/public/cpp/url_request_mojom_traits.h +++ b/services/network/public/cpp/url_request_mojom_traits.h
@@ -177,9 +177,6 @@ static bool corb_detachable(const network::ResourceRequest& request) { return request.corb_detachable; } - static bool corb_excluded(const network::ResourceRequest& request) { - return request.corb_excluded; - } static network::mojom::RequestMode mode( const network::ResourceRequest& request) { return request.mode;
diff --git a/services/network/public/mojom/cookie_manager.mojom b/services/network/public/mojom/cookie_manager.mojom index 3c0ec0e..a9e379cf 100644 --- a/services/network/public/mojom/cookie_manager.mojom +++ b/services/network/public/mojom/cookie_manager.mojom
@@ -156,10 +156,12 @@ CookieAccessResult access_result; }; +// See net/cookies/cookie_access_result.{cc,h} for documentation. struct CookieAccessResult { CookieEffectiveSameSite effective_same_site; CookieAccessSemantics access_semantics; CookieInclusionStatus status; + bool is_allowed_to_access_secure_cookies; }; struct CookieWithAccessResult {
diff --git a/services/network/public/mojom/network_service.mojom b/services/network/public/mojom/network_service.mojom index 6e5025c..3e24514 100644 --- a/services/network/public/mojom/network_service.mojom +++ b/services/network/public/mojom/network_service.mojom
@@ -360,15 +360,6 @@ [EnableIf=is_win] SetEncryptionKey(string encryption_key); - // Notifies CORB (Cross-Origin Read Blocking) that |process_id| is proxying - // requests on behalf of a universal-access plugin and therefore CORB should - // stop blocking requests marked as ResourceType::kPluginResource. - // - // TODO(lukasza, laforge): https://crbug.com/702995: Remove the ...ForPlugin - // methods once Flash support is removed from Chromium (probably around 2020 - // - see https://www.chromium.org/flash-roadmap). - AddCorbExceptionForPlugin(int32 process_id); - // Notifies |request_initiator_origin_lock| enforcement code that |process_id| // is proxying requests on behalf of a plugin from // |allowed_request_initiator| origin. @@ -379,7 +370,7 @@ int32 process_id, url.mojom.Origin allowed_request_initiator); - // Reverts AddCorbExceptionForPlugin and AddAllowedRequestInitiatorForPlugin. + // Reverts AddAllowedRequestInitiatorForPlugin. RemoveSecurityExceptionsForPlugin(int32 process_id); // Called when the system is low on memory.
diff --git a/services/network/public/mojom/url_loader.mojom b/services/network/public/mojom/url_loader.mojom index a38d9e98..4d6a1ecb 100644 --- a/services/network/public/mojom/url_loader.mojom +++ b/services/network/public/mojom/url_loader.mojom
@@ -261,11 +261,6 @@ // If true then the request continues even if it's blocked by CORB. bool corb_detachable = false; - // TODO(lukasza): https://crbug.com/846339: Remove the field below and instead - // make plugins use a separate URLoaderFactory. Note requests of this type are - // only excluded if mode is kNoCors. - bool corb_excluded = false; - // https://fetch.spec.whatwg.org/#concept-request-mode // Used mainly by CORS handling (out-of-blink CORS), CORB, Service Worker. // CORS handling needs a proper origin (including a unique opaque origin).
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index 65bb883..3273379d 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -46,7 +46,6 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "services/network/chunked_data_pipe_upload_data_stream.h" -#include "services/network/cross_origin_read_blocking_exception_for_plugin.h" #include "services/network/data_pipe_element_reader.h" #include "services/network/network_usage_accumulator.h" #include "services/network/origin_policy/origin_policy_constants.h" @@ -586,10 +585,6 @@ url_request_->SetUserData(kUserDataKey, std::make_unique<UnownedPointer>(this)); - is_nocors_corb_excluded_request_ = - request.corb_excluded && request.mode == mojom::RequestMode::kNoCors && - CrossOriginReadBlockingExceptionForPlugin::ShouldAllowForPlugin( - factory_params_->process_id); request_mode_ = request.mode; if (request.trusted_params) { @@ -1363,7 +1358,7 @@ // Figure out if we need to sniff (for MIME type detection or for Cross-Origin // Read Blocking / CORB). - if (factory_params_->is_corb_enabled && !is_nocors_corb_excluded_request_) { + if (factory_params_->is_corb_enabled) { CrossOriginReadBlocking::LogAction( CrossOriginReadBlocking::Action::kResponseStarted);
diff --git a/services/network/url_loader.h b/services/network/url_loader.h index 6b2e6d3..600dd2f 100644 --- a/services/network/url_loader.h +++ b/services/network/url_loader.h
@@ -464,11 +464,6 @@ // encoded body size was reported to the client. int64_t reported_total_encoded_bytes_ = 0; - // Indicates whether this request was made by a CORB-excluded request type and - // was not using CORS. Such requests are exempt from blocking, while other - // CORB-excluded requests must be blocked if the CORS check fails. - bool is_nocors_corb_excluded_request_ = false; - mojom::RequestMode request_mode_; bool has_user_activation_;
diff --git a/services/network/url_loader_unittest.cc b/services/network/url_loader_unittest.cc index 7a2dcadc..bc2edbde 100644 --- a/services/network/url_loader_unittest.cc +++ b/services/network/url_loader_unittest.cc
@@ -75,7 +75,6 @@ #include "net/url_request/url_request_job.h" #include "net/url_request/url_request_test_job.h" #include "net/url_request/url_request_test_util.h" -#include "services/network/cross_origin_read_blocking_exception_for_plugin.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/cookie_access_observer.mojom-forward.h" @@ -3637,7 +3636,6 @@ request.resource_type = kResourceType; request.mode = mojom::RequestMode::kCors; request.request_initiator = url::Origin::Create(GURL("http://foo.com/")); - request.corb_excluded = true; base::RunLoop delete_run_loop; mojo::PendingRemote<mojom::URLLoader> loader; @@ -3666,58 +3664,12 @@ // Blocked because this is a cross-origin request made with a CORS request // header, but without a valid CORS response header. - // request.corb_excluded does not apply in that case. ASSERT_EQ(std::string(), body); } -// This simulates plugins with universal access, like Flash. These can make -// cross-origin requests that are not subject to CORB. -TEST_F(URLLoaderTest, CorbExcludedWithNoCors) { - int kResourceType = 1; - ResourceRequest request = - CreateResourceRequest("GET", test_server()->GetURL("/hello.html")); - request.resource_type = kResourceType; - request.mode = mojom::RequestMode::kNoCors; - request.request_initiator = url::Origin::Create(GURL("http://foo.com/")); - request.corb_excluded = true; - - base::RunLoop delete_run_loop; - mojo::PendingRemote<mojom::URLLoader> loader; - std::unique_ptr<URLLoader> url_loader; - mojom::URLLoaderFactoryParams params; - params.process_id = 123; - CrossOriginReadBlockingExceptionForPlugin::AddExceptionForPlugin(123); - url_loader = std::make_unique<URLLoader>( - context(), nullptr /* network_service_client */, - nullptr /* network_context_client */, - DeleteLoaderCallback(&delete_run_loop, &url_loader), - loader.InitWithNewPipeAndPassReceiver(), 0, request, - client()->CreateRemote(), /*reponse_body_use_tracker=*/base::nullopt, - TRAFFIC_ANNOTATION_FOR_TESTS, ¶ms, - /*coep_reporter=*/nullptr, 0 /* request_id */, - 0 /* keepalive_request_size */, resource_scheduler_client(), nullptr, - nullptr /* network_usage_accumulator */, nullptr /* header_client */, - nullptr /* origin_policy_manager */, nullptr /* trust_token_helper */, - nullptr /* origin_access_list */, - mojo::NullRemote() /* cookie_observer */); - - client()->RunUntilResponseBodyArrived(); - std::string body = ReadBody(); - - client()->RunUntilComplete(); - - delete_run_loop.Run(); - - // The request body is allowed through because CORB isn't applied. - ASSERT_NE(std::string(), body); - - CrossOriginReadBlockingExceptionForPlugin::RemoveExceptionForPlugin(123); -} - -// This simulates a renderer that pretends to be proxying requests for Flash -// (when browser didn't actually confirm that Flash is hosted by the given -// process via -// CrossOriginReadBlockingExceptionForPlugin::AddExceptionForPlugin). We should +// This simulates a renderer that _pretends_ to be proxying requests for PDF +// plugin (when browser didn't _actually_ confirm that Flash or PDF are hosted +// by the given process via AddAllowedRequestInitiatorForPlugin). We should // still apply CORB in this case. TEST_F(URLLoaderTest, CorbEffectiveWithNoCorsWhenNoActualPlugin) { int kResourceType = 1; @@ -3726,16 +3678,14 @@ request.resource_type = kResourceType; request.mode = mojom::RequestMode::kNoCors; request.request_initiator = url::Origin::Create(GURL("http://foo.com/")); - request.corb_excluded = true; base::RunLoop delete_run_loop; mojo::PendingRemote<mojom::URLLoader> loader; std::unique_ptr<URLLoader> url_loader; mojom::URLLoaderFactoryParams params; params.process_id = 234; - // No call to - // CrossOriginReadBlockingExceptionForPlugin::AddExceptionForPlugin(123) - - // this is what we primarily want to cover in this test. + // No call to NetworkService::AddAllowedRequestInitiatorForPlugin - this is + // what we primarily want to cover in this test. url_loader = std::make_unique<URLLoader>( context(), nullptr /* network_service_client */, nullptr /* network_context_client */,
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index c23fe20..52bd31b 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -26897,5266 +26897,6 @@ } ] }, - "ios-simulator-coverage-exp": { - "isolated_scripts": [ - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "absl_hardening_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "absl_hardening_tests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/abseil-cpp:absl_hardening_tests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "absl_hardening_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "absl_hardening_tests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/abseil-cpp:absl_hardening_tests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "base_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "boringssl_crypto_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "boringssl_crypto_tests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/boringssl:boringssl_crypto_tests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "boringssl_crypto_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "boringssl_crypto_tests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/boringssl:boringssl_crypto_tests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "boringssl_ssl_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "boringssl_ssl_tests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "boringssl_ssl_tests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "boringssl_ssl_tests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "components_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "crypto_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "crypto_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://crypto:crypto_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "crypto_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "crypto_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://crypto:crypto_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "gfx_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "gfx_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "google_apis_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "google_apis_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://google_apis:google_apis_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "google_apis_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "google_apis_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://google_apis:google_apis_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_chrome_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test:ios_chrome_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_components_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/components:ios_components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_components_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_components_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/components:ios_components_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_net_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_net_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/net:ios_net_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_net_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_net_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/net:ios_net_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_remoting_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_remoting_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://remoting/ios:ios_remoting_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_remoting_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_remoting_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://remoting/ios:ios_remoting_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_testing_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_testing_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/testing:ios_testing_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_testing_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_testing_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/testing:ios_testing_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_inttests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web:ios_web_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_inttests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_inttests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_inttests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ios_web_view_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_view_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web_view:ios_web_view_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "net_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "net_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://net:net_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "net_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "net_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://net:net_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "services_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "services_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://services:services_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "services_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "services_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://services:services_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "skia_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "skia_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "sql_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "sql_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://sql:sql_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "sql_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "sql_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://sql:sql_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone 6s Plus 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s Plus", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone 6s Plus 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone SE (1st generation) 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone SE (1st generation)", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "ui_base_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ui_base_unittests_iPhone SE (1st generation) 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "url_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "url_unittests_iPhone 6s 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://url:url_unittests/" - }, - { - "args": [ - "--platform", - "iPhone 6s", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest" - ], - "isolate_name": "url_unittests", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "url_unittests_iPhone 6s 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://url:url_unittests/" - } - ] - }, "ios-simulator-cronet": { "isolated_scripts": [ { @@ -32251,2186 +26991,6 @@ } ] }, - "ios-simulator-full-configs-coverage-exp": { - "isolated_scripts": [ - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPhone X 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_bookmarks_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_bookmarks_eg2tests_module_iPhone X 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_bookmarks_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_integration_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_integration_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_integration_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPhone X 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_settings_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_settings_eg2tests_module_iPhone X 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_settings_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_signin_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_signin_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_signin_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPhone X 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_smoke_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_smoke_eg2tests_module_iPhone X 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_ui_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_ui_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 5 - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_ui_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPhone X 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_chrome_web_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_chrome_web_eg2tests_module_iPhone X 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/chrome/test/earl_grey2:ios_chrome_web_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPhone X 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone X", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_showcase_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_showcase_eg2tests_module_iPhone X 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/showcase:ios_showcase_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPad Air 2 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPad Air 2", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPad Air 2 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "13.6", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPhone 7 13.6", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - }, - { - "args": [ - "--platform", - "iPhone 7", - "--version", - "14.0", - "--out-dir", - "${ISOLATED_OUTDIR}", - "--xcode-build-version", - "12a7209", - "--xctest", - "--xcode-parallelization" - ], - "isolate_name": "ios_web_shell_eg2tests_module", - "isolate_profile_data": true, - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "ios_web_shell_eg2tests_module_iPhone 7 14.0", - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/mac_toolchain/${platform}", - "location": ".", - "revision": "git_revision:796d2b92cff93fc2059623ce0a66284373ceea0a" - } - ], - "dimension_sets": [ - { - "os": "Mac-10.15" - } - ], - "named_caches": [ - { - "name": "xcode_ios_12a7209", - "path": "Xcode.app" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://ios/web/shell/test:ios_web_shell_eg2tests_module/" - } - ] - }, "ios-simulator-multi-window": { "isolated_scripts": [ {
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 8c7d8f9..b117286d 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -2456,20 +2456,6 @@ 'isolated_scripts': 'ios_code_coverage_tests', }, }, - 'ios-simulator-coverage-exp': { - 'mixins': [ - 'enable_resultdb', - 'isolate_profile_data', - 'mac_10.15', - 'mac_toolchain', - 'out_dir_arg', - 'xcode_12a7209', - 'xctest', - ], - 'test_suites': { - 'isolated_scripts': 'ios_simulator_tests', - }, - }, 'ios-simulator-cronet': { 'mixins': [ 'enable_resultdb', @@ -2483,20 +2469,6 @@ 'isolated_scripts': 'ios_simulator_cronet_tests', } }, - 'ios-simulator-full-configs-coverage-exp': { - 'mixins': [ - 'enable_resultdb', - 'isolate_profile_data', - 'mac_10.15', - 'mac_toolchain', - 'out_dir_arg', - 'xcode_12a7209', - 'xctest', - ], - 'test_suites': { - 'isolated_scripts': 'ios_simulator_full_configs_tests', - }, - }, 'ios-simulator-multi-window': { 'mixins': [ 'enable_resultdb',
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 632f065..04870ef3 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -4491,6 +4491,24 @@ ] } ], + "MuteNotifications": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "MuteNotificationsDuringScreenShare" + ] + } + ] + } + ], "MyChromeEverywhere": [ { "platforms": [ @@ -4614,28 +4632,6 @@ ] } ], - "NavigationPredictorPreconnectSocketCompletionTime": [ - { - "platforms": [ - "android", - "chromeos", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "params": { - "preconnect_socket_completion_time_msec": "3000" - }, - "enable_features": [ - "NavigationPredictorPreconnectSocketCompletionTime" - ] - } - ] - } - ], "NewUsbBackend": [ { "platforms": [
diff --git a/third_party/blink/PRESUBMIT.py b/third_party/blink/PRESUBMIT.py index 1fbbd2bc..7d5e70b 100644 --- a/third_party/blink/PRESUBMIT.py +++ b/third_party/blink/PRESUBMIT.py
@@ -62,8 +62,11 @@ allowed_interfaces = ('services/network/public/mojom/cross_origin_embedder_policy', 'services/network/public/mojom/fetch_api', 'services/network/public/mojom/load_timing_info', + 'services/network/public/mojom/url_loader', + 'services/network/public/mojom/url_loader_factory', 'services/network/public/mojom/url_response_head', 'third_party/blink/public/mojom/blob/serialized_blob', + 'third_party/blink/public/mojom/fetch/fetch_api_request', 'third_party/blink/public/mojom/loader/resource_load_info', 'third_party/blink/public/mojom/loader/resource_load_info_notifier', 'third_party/blink/public/mojom/worker/subresource_loader_updater',
diff --git a/third_party/blink/common/loader/resource_type_util.cc b/third_party/blink/common/loader/resource_type_util.cc index 1ea4c3c..1126c57 100644 --- a/third_party/blink/common/loader/resource_type_util.cc +++ b/third_party/blink/common/loader/resource_type_util.cc
@@ -12,9 +12,12 @@ } bool IsRequestDestinationFrame(network::mojom::RequestDestination destination) { + // kObject and kEmbed can also be destinations for a frame navigation. return destination == network::mojom::RequestDestination::kDocument || destination == network::mojom::RequestDestination::kFrame || - destination == network::mojom::RequestDestination::kIframe; + destination == network::mojom::RequestDestination::kIframe || + destination == network::mojom::RequestDestination::kObject || + destination == network::mojom::RequestDestination::kEmbed; } } // namespace blink
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 146e41c..d585724 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -228,6 +228,8 @@ "platform/web_memory_pressure_listener.h", "platform/web_mixed_content.h", "platform/web_mixed_content_context_type.h", + "platform/web_mojo_url_loader_client.h", + "platform/web_mojo_url_loader_client_observer.h", "platform/web_navigation_body_loader.h", "platform/web_network_state_notifier.h", "platform/web_policy_container.cc",
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index 48625f40..57c73034 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -5507,6 +5507,8 @@ RequestId transportId # WebTransport request URL. string url + # Timestamp. + MonotonicTime timestamp # Request initiator. optional Initiator initiator @@ -5514,6 +5516,8 @@ parameters # WebTransport identifier. RequestId transportId + # Timestamp. + MonotonicTime timestamp experimental type PrivateNetworkRequestPolicy extends string enum
diff --git a/third_party/blink/public/platform/DEPS b/third_party/blink/public/platform/DEPS index 44916f9..11cb84b 100644 --- a/third_party/blink/public/platform/DEPS +++ b/third_party/blink/public/platform/DEPS
@@ -84,3 +84,9 @@ "+third_party/blink/renderer/core", "+third_party/blink/renderer/platform", ] + +specific_include_rules = { + "web_mojo_url_loader_client.h": [ + "+services/network/public/mojom/url_loader.mojom.h", + ] +}
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 358f3c1..e8d559d 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -337,6 +337,12 @@ WebURLResponse* response, bool report_security_info, int request_id) {} + + // Determines whether it is safe to redirect from |from_url| to |to_url|. + virtual bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) { + return false; + } + // Public Suffix List -------------------------------------------------- // May return null on some platforms.
diff --git a/content/renderer/loader/url_loader_client_impl.h b/third_party/blink/public/platform/web_mojo_url_loader_client.h similarity index 68% rename from content/renderer/loader/url_loader_client_impl.h rename to third_party/blink/public/platform/web_mojo_url_loader_client.h index 169b477e..bd0a9d7a 100644 --- a/content/renderer/loader/url_loader_client_impl.h +++ b/third_party/blink/public/platform/web_mojo_url_loader_client.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_LOADER_URL_LOADER_CLIENT_IMPL_H_ -#define CONTENT_RENDERER_LOADER_URL_LOADER_CLIENT_IMPL_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_H_ #include <stdint.h> #include <vector> @@ -12,11 +12,11 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" -#include "content/common/content_export.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/data_pipe.h" #include "services/network/public/mojom/url_loader.mojom.h" +#include "third_party/blink/public/platform/web_common.h" #include "third_party/blink/public/platform/web_url_loader.h" namespace base { @@ -31,33 +31,27 @@ struct URLLoaderCompletionStatus; } // namespace network -namespace content { -class ResourceDispatcher; +namespace blink { +class WebMojoURLLoaderClientObserver; -class CONTENT_EXPORT URLLoaderClientImpl final +// WebMojoURLLoaderClient is an implementation of +// network::mojom::URLLoaderClient to receive messages from a single URLLoader. +// TODO(https://crbug.com/860403): Move this class from blink/public/platform/ +// to blink/renderer/platform/loader/fetch/url_loader/ finally. +class BLINK_PLATFORM_EXPORT WebMojoURLLoaderClient final : public network::mojom::URLLoaderClient { public: - URLLoaderClientImpl(int request_id, - ResourceDispatcher* resource_dispatcher, - scoped_refptr<base::SingleThreadTaskRunner> task_runner, - bool bypass_redirect_checks, - const GURL& request_url); - ~URLLoaderClientImpl() override; + WebMojoURLLoaderClient( + int request_id, + WebMojoURLLoaderClientObserver* url_loader_client_observer, + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + bool bypass_redirect_checks, + const GURL& request_url); + ~WebMojoURLLoaderClient() override; // Set the defer status. If loading is deferred, received messages are not // dispatched to clients until it is set not deferred. - void SetDefersLoading(blink::WebURLLoader::DeferType value); - - // Dispatches the messages received after SetDefersLoading is called. - void FlushDeferredMessages(); - - // Binds this instance to the given URLLoaderClient endpoints so that it can - // start getting the mojo calls from the given loader. This is used only for - // the main resource loading. Otherwise (in regular subresource loading cases) - // |this| is not bound to a client request, but used via ThrottlingURLLoader - // to get client upcalls from the loader. - void Bind( - network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints); + void SetDefersLoading(WebURLLoader::DeferType value); // network::mojom::URLLoaderClient implementation void OnReceiveResponse( @@ -80,8 +74,6 @@ blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache; } - const GURL& last_loaded_url() const { return last_loaded_url_; } - private: class BodyBuffer; class DeferredMessage; @@ -95,6 +87,10 @@ bool NeedsStoringMessage() const; void StoreAndDispatch(std::unique_ptr<DeferredMessage> message); void OnConnectionClosed(); + const GURL& last_loaded_url() const { return last_loaded_url_; } + + // Dispatches the messages received after SetDefersLoading is called. + void FlushDeferredMessages(); std::vector<std::unique_ptr<DeferredMessage>> deferred_messages_; std::unique_ptr<BodyBuffer> body_buffer_; @@ -102,10 +98,10 @@ bool has_received_response_head_ = false; bool has_received_response_body_ = false; bool has_received_complete_ = false; - blink::WebURLLoader::DeferType deferred_state_ = - blink::WebURLLoader::DeferType::kNotDeferred; + WebURLLoader::DeferType deferred_state_ = + WebURLLoader::DeferType::kNotDeferred; int32_t accumulated_transfer_size_diff_during_deferred_ = 0; - ResourceDispatcher* const resource_dispatcher_; + WebMojoURLLoaderClientObserver* const url_loader_client_observer_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; bool bypass_redirect_checks_ = false; GURL last_loaded_url_; @@ -117,9 +113,9 @@ mojo::Receiver<network::mojom::URLLoaderClient> url_loader_client_receiver_{ this}; - base::WeakPtrFactory<URLLoaderClientImpl> weak_factory_{this}; + base::WeakPtrFactory<WebMojoURLLoaderClient> weak_factory_{this}; }; -} // namespace content +} // namespace blink -#endif // CONTENT_RENDERER_LOADER_URL_LOADER_CLIENT_IMPL_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_H_
diff --git a/third_party/blink/public/platform/web_mojo_url_loader_client_observer.h b/third_party/blink/public/platform/web_mojo_url_loader_client_observer.h new file mode 100644 index 0000000..4024c646 --- /dev/null +++ b/third_party/blink/public/platform/web_mojo_url_loader_client_observer.h
@@ -0,0 +1,78 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_OBSERVER_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_OBSERVER_H_ + +#include <stdint.h> + +#include <string> +#include <vector> + +#include "mojo/public/cpp/base/big_buffer.h" +#include "mojo/public/cpp/system/data_pipe.h" +#include "services/network/public/mojom/url_response_head.mojom-forward.h" +#include "third_party/blink/public/platform/web_common.h" + +namespace net { +struct RedirectInfo; +} + +namespace network { +struct URLLoaderCompletionStatus; +} + +namespace blink { + +// This is implemented by content::ResourceDispatcher to observe +// WebMojoURLLoaderClient that receives messages from a single URLLoader. +// This is a transient class used until WebURLLoaderImpl in content/ is moved to +// Blink. +// TODO(https://crbug.com/1110032): Remove this. +class BLINK_PLATFORM_EXPORT WebMojoURLLoaderClientObserver { + public: + // Called when the transfer size is updated. + virtual void OnTransferSizeUpdated(int request_id, + int32_t transfer_size_diff) = 0; + + // Called as upload progress is made. + virtual void OnUploadProgress(int request_id, + int64_t position, + int64_t size) = 0; + + // Called when response headers are available. + virtual void OnReceivedResponse(int request_id, + network::mojom::URLResponseHeadPtr) = 0; + + // Called when metadata generated by the renderer is retrieved from the + // cache. + virtual void OnReceivedCachedMetadata(int request_id, + mojo_base::BigBuffer data) = 0; + + // Called when a redirect occurs. + virtual void OnReceivedRedirect( + int request_id, + const net::RedirectInfo& redirect_info, + network::mojom::URLResponseHeadPtr response_head, + scoped_refptr<base::SingleThreadTaskRunner> task_runner) = 0; + + // Called when the response body becomes available. + virtual void OnStartLoadingResponseBody( + int request_id, + mojo::ScopedDataPipeConsumerHandle body) = 0; + + // Called when the response is complete. + virtual void OnRequestComplete( + int request_id, + const network::URLLoaderCompletionStatus& status) = 0; + + virtual void EvictFromBackForwardCache(int request_id) = 0; + + protected: + virtual ~WebMojoURLLoaderClientObserver() = default; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MOJO_URL_LOADER_CLIENT_OBSERVER_H_
diff --git a/third_party/blink/public/web/web_ax_object.h b/third_party/blink/public/web/web_ax_object.h index 5639e35c..402c393 100644 --- a/third_party/blink/public/web/web_ax_object.h +++ b/third_party/blink/public/web/web_ax_object.h
@@ -62,16 +62,6 @@ struct WebRect; struct WebSize; -class BLINK_EXPORT WebAXSparseAttributeClient { - public: - WebAXSparseAttributeClient() = default; - virtual ~WebAXSparseAttributeClient() = default; - - virtual void AddObjectAttribute(WebAXObjectAttribute, const WebAXObject&) = 0; - virtual void AddObjectVectorAttribute(WebAXObjectVectorAttribute, - const WebVector<WebAXObject>&) = 0; -}; - // A container for passing around a reference to AXObject. class WebAXObject { public: @@ -137,12 +127,6 @@ BLINK_EXPORT WebAXObject ChildAt(unsigned) const; BLINK_EXPORT WebAXObject ParentObject() const; - // Retrieve accessibility attributes that apply to only a small - // fraction of WebAXObjects by passing an implementation of - // WebAXSparseAttributeClient, which will be called with only the attributes - // that apply to this object. - BLINK_EXPORT void GetSparseAXAttributes(WebAXSparseAttributeClient&) const; - // Serialize the properties of this node into |node_data|. // // TODO(crbug.com/1068668): AX onion soup - finish migrating
diff --git a/third_party/blink/public/web/web_local_frame_client.h b/third_party/blink/public/web/web_local_frame_client.h index a298cc7..405d68e 100644 --- a/third_party/blink/public/web/web_local_frame_client.h +++ b/third_party/blink/public/web/web_local_frame_client.h
@@ -46,6 +46,7 @@ #include "third_party/blink/public/common/navigation/triggering_event_info.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" +#include "third_party/blink/public/mojom/devtools/console_message.mojom-forward.h" #include "third_party/blink/public/mojom/frame/blocked_navigation_types.mojom-shared.h" #include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom-shared.h" #include "third_party/blink/public/mojom/frame/lifecycle.mojom-shared.h" @@ -276,8 +277,11 @@ // Console messages ---------------------------------------------------- - // Whether or not we should report a detailed message for the given source. - virtual bool ShouldReportDetailedMessageForSource(const WebString& source) { + // Whether or not we should report a detailed message for the given source and + // severity level. + virtual bool ShouldReportDetailedMessageForSourceAndSeverity( + mojom::ConsoleMessageLevel log_level, + const WebString& source) { return false; }
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index c50405e..67e7d12e 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -65,8 +65,8 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_video_frame_output_callback.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_video_frame_request_callback.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_video_frame_request_callback.h", - "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.cc", - "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_xr_frame_request_callback.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_xr_frame_request_callback.h", ]
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index 70a08f8..f3dd016 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -771,7 +771,7 @@ "//third_party/blink/renderer/modules/webcodecs/video_pixel_format.idl", "//third_party/blink/renderer/modules/webcodecs/video_track_reader.idl", "//third_party/blink/renderer/modules/webcodecs/video_track_writer_parameters.idl", - "//third_party/blink/renderer/modules/webcodecs/web_codecs_error_callback.idl", + "//third_party/blink/renderer/modules/webcodecs/webcodecs_error_callback.idl", "//third_party/blink/renderer/modules/webdatabase/database.idl", "//third_party/blink/renderer/modules/webdatabase/sql_error.idl", "//third_party/blink/renderer/modules/webdatabase/sql_result_set.idl",
diff --git a/third_party/blink/renderer/bindings/modules/v8/generated.gni b/third_party/blink/renderer/bindings/modules/v8/generated.gni index 5e12cb8e..5600b9d 100644 --- a/third_party/blink/renderer/bindings/modules/v8/generated.gni +++ b/third_party/blink/renderer/bindings/modules/v8/generated.gni
@@ -190,8 +190,8 @@ "$bindings_modules_v8_output_dir/v8_video_frame_output_callback.h", "$bindings_modules_v8_output_dir/v8_video_frame_request_callback.cc", "$bindings_modules_v8_output_dir/v8_video_frame_request_callback.h", - "$bindings_modules_v8_output_dir/v8_web_codecs_error_callback.cc", - "$bindings_modules_v8_output_dir/v8_web_codecs_error_callback.h", + "$bindings_modules_v8_output_dir/v8_webcodecs_error_callback.cc", + "$bindings_modules_v8_output_dir/v8_webcodecs_error_callback.h", "$bindings_modules_v8_output_dir/v8_xr_frame_request_callback.cc", "$bindings_modules_v8_output_dir/v8_xr_frame_request_callback.h", ]
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_document.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_document.cc index e1e2209c..5be5a1f 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_document.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_document.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_location.h" #include "third_party/blink/renderer/core/animation/document_animation.h" +#include "third_party/blink/renderer/core/document_transition/document_create_transition.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/fullscreen/document_fullscreen.h" #include "third_party/blink/renderer/core/svg/svg_document_extensions.h"
diff --git a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py index dd1978d..db8096c4 100644 --- a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py +++ b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py
@@ -9,6 +9,7 @@ SPECIAL_TOKENS = [ # This list should be sorted by length. + 'WebCodecs', 'WebSocket', 'String16', 'Float32',
diff --git a/third_party/blink/renderer/core/css/resolver/style_adjuster.cc b/third_party/blink/renderer/core/css/resolver/style_adjuster.cc index 45b2210a7..55c709a2 100644 --- a/third_party/blink/renderer/core/css/resolver/style_adjuster.cc +++ b/third_party/blink/renderer/core/css/resolver/style_adjuster.cc
@@ -599,7 +599,7 @@ TouchAction enforced_by_policy = TouchAction::kNone; if (element->GetDocument().IsVerticalScrollEnforced()) enforced_by_policy = TouchAction::kPanY; - if (base::FeatureList::IsEnabled(::features::kSwipeToMoveCursor) && + if (::features::IsSwipeToMoveCursorEnabled() && IsEditableElement(element, style)) { element_touch_action &= ~TouchAction::kInternalPanXScrolls; }
diff --git a/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc b/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc index 56b6a175..5af052b 100644 --- a/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc +++ b/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc
@@ -178,7 +178,8 @@ TEST_F(StyleAdjusterTest, TouchActionContentEditableArea) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures({::features::kSwipeToMoveCursor}, {}); - ASSERT_TRUE(base::FeatureList::IsEnabled(::features::kSwipeToMoveCursor)); + if (!::features::IsSwipeToMoveCursorEnabled()) + return; GetDocument().SetBaseURLOverride(KURL("http://test.com")); SetBodyInnerHTML(R"HTML( @@ -229,7 +230,8 @@ TEST_F(StyleAdjusterTest, TouchActionNoPanXScrollsWhenNoPanX) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures({::features::kSwipeToMoveCursor}, {}); - ASSERT_TRUE(base::FeatureList::IsEnabled(::features::kSwipeToMoveCursor)); + if (!::features::IsSwipeToMoveCursorEnabled()) + return; GetDocument().SetBaseURLOverride(KURL("http://test.com")); SetBodyInnerHTML(R"HTML(
diff --git a/third_party/blink/renderer/core/frame/ad_tracker.cc b/third_party/blink/renderer/core/frame/ad_tracker.cc index 04ade88..e4b14013 100644 --- a/third_party/blink/renderer/core/frame/ad_tracker.cc +++ b/third_party/blink/renderer/core/frame/ad_tracker.cc
@@ -213,7 +213,9 @@ const FetchInitiatorInfo& initiator_info, bool known_ad) { // Check if the document loading the resource is an ad. - known_ad = known_ad || IsKnownAdExecutionContext(execution_context); + const bool is_ad_execution_context = + IsKnownAdExecutionContext(execution_context); + known_ad = known_ad || is_ad_execution_context; // We skip script checking for stylesheet-initiated resource requests as the // stack may represent the cause of a style recalculation rather than the @@ -232,7 +234,7 @@ // contexts, because any script executed inside an ad context is considered an // ad script by IsKnownAdScript. if (resource_type == ResourceType::kScript && known_ad && - !IsKnownAdExecutionContext(execution_context)) { + !is_ad_execution_context) { AppendToKnownAdScripts(*execution_context, request.Url().GetString()); } @@ -286,7 +288,7 @@ // (e.g., when v8 is executed) but not the entire stack. For a small cost we // can also check the top of the stack (this is much cheaper than getting the // full stack from v8). - return IsKnownAdScript(execution_context, ScriptAtTopOfStack()); + return IsKnownAdScriptForCheckedContext(*execution_context, String()); } bool AdTracker::IsKnownAdScript(ExecutionContext* execution_context, @@ -297,13 +299,25 @@ if (IsKnownAdExecutionContext(execution_context)) return true; - if (url.IsEmpty()) - return false; + return IsKnownAdScriptForCheckedContext(*execution_context, url); +} - auto it = known_ad_scripts_.find(execution_context); +bool AdTracker::IsKnownAdScriptForCheckedContext( + ExecutionContext& execution_context, + const String& url) { + DCHECK(!IsKnownAdExecutionContext(&execution_context)); + auto it = known_ad_scripts_.find(&execution_context); if (it == known_ad_scripts_.end()) return false; - return it->value.Contains(url); + + if (it->value.IsEmpty()) + return false; + + // Delay calling ScriptAtTopOfStack() as much as possible due to its cost. + String script_url = url.IsNull() ? ScriptAtTopOfStack() : url; + if (script_url.IsEmpty()) + return false; + return it->value.Contains(script_url); } // This is a separate function for testing purposes.
diff --git a/third_party/blink/renderer/core/frame/ad_tracker.h b/third_party/blink/renderer/core/frame/ad_tracker.h index 80b471a..22f14a5 100644 --- a/third_party/blink/renderer/core/frame/ad_tracker.h +++ b/third_party/blink/renderer/core/frame/ad_tracker.h
@@ -110,7 +110,8 @@ const String& script_name, int script_id); void DidExecuteScript(); - bool IsKnownAdScript(ExecutionContext* execution_context, const String& url); + bool IsKnownAdScript(ExecutionContext*, const String& url); + bool IsKnownAdScriptForCheckedContext(ExecutionContext&, const String& url); void AppendToKnownAdScripts(ExecutionContext&, const String& url); Member<LocalFrame> local_root_;
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc index 35d3f42..176947119 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
@@ -178,19 +178,18 @@ void ContentSecurityPolicy::SetupSelf(const SecurityOrigin& security_origin) { // Ensure that 'self' processes correctly. self_protocol_ = security_origin.Protocol(); - self_source_ = MakeGarbageCollected<CSPSource>( - this, self_protocol_, security_origin.Host(), + self_source_ = network::mojom::blink::CSPSource::New( + self_protocol_, security_origin.Host(), security_origin.Port() == DefaultPortForProtocol(self_protocol_) - ? CSPSource::kPortUnspecified + ? url::PORT_UNSPECIFIED : security_origin.Port(), - String(), CSPSource::kNoWildcard, CSPSource::kNoWildcard); + "", /*is_host_wildcard=*/false, /*is_port_wildcard=*/false); } void ContentSecurityPolicy::SetupSelf(const ContentSecurityPolicy& other) { self_protocol_ = other.self_protocol_; if (other.self_source_) { - self_source_ = - MakeGarbageCollected<CSPSource>(this, *(other.self_source_.Get())); + self_source_ = other.self_source_.Clone(); } } @@ -294,15 +293,14 @@ visitor->Trace(delegate_); visitor->Trace(policies_); visitor->Trace(console_messages_); - visitor->Trace(self_source_); } void ContentSecurityPolicy::CopyStateFrom(const ContentSecurityPolicy* other) { DCHECK(policies_.IsEmpty()); + SetupSelf(*other); for (const auto& policy : other->policies_) AddAndReportPolicyFromHeaderValue(policy->Header(), policy->HeaderType(), policy->HeaderSource()); - SetupSelf(*other); } void ContentSecurityPolicy::CopyPluginTypesFrom( @@ -435,9 +433,9 @@ // to an execution context. scoped_refptr<const SecurityOrigin> origin = SecurityOrigin::Create(url); self_protocol_ = origin->Protocol(); - self_source_ = MakeGarbageCollected<CSPSource>( - this, self_protocol_, origin->Host(), origin->Port(), String(), - CSPSource::kNoWildcard, CSPSource::kNoWildcard); + self_source_ = network::mojom::blink::CSPSource::New( + self_protocol_, origin->Host(), origin->Port(), "", + /*is_host_wildcard=*/false, /*is_port_wildcard=*/false); } Vector<CSPHeaderAndType> ContentSecurityPolicy::Headers() const { @@ -1478,7 +1476,8 @@ } bool ContentSecurityPolicy::UrlMatchesSelf(const KURL& url) const { - return self_source_->MatchesAsSelf(url); + DCHECK(self_source_); + return CSPSourceMatchesAsSelf(*self_source_, self_protocol_, url); } bool ContentSecurityPolicy::ProtocolEqualsSelf(const String& protocol) const {
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy.h b/third_party/blink/renderer/core/frame/csp/content_security_policy.h index 964f3dba..c91cf35 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy.h +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy.h
@@ -64,7 +64,6 @@ class ContentSecurityPolicyResponseHeaders; class ConsoleMessage; class CSPDirectiveList; -class CSPSource; class DOMWrapperWorld; class Element; class ExecutionContext; @@ -443,7 +442,9 @@ bool ShouldSendCSPHeader(ResourceType) const; - CSPSource* GetSelfSource() const { return self_source_; } + network::mojom::blink::CSPSource* GetSelfSource() const { + return self_source_.get(); + } // Whether the main world's CSP should be bypassed based on the current // javascript world we are in. @@ -595,7 +596,7 @@ String disable_eval_error_message_; mojom::blink::InsecureRequestPolicy insecure_request_policy_; - Member<CSPSource> self_source_; + network::mojom::blink::CSPSourcePtr self_source_; String self_protocol_; bool supports_wasm_eval_ = false;
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc b/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc index ab7d3bc..3872e4c 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc
@@ -26,12 +26,7 @@ LEAK_SANITIZER_DISABLED_SCOPE; g_page_holder = std::make_unique<DummyPageHolder>().release(); - // Set loader sandbox flags and install a new document so the document - // has all possible sandbox flags set on the document already when the - // CSP is bound. scoped_refptr<SharedBuffer> empty_document_data = SharedBuffer::Create(); - g_page_holder->GetFrame().Loader().ForceSandboxFlags( - network::mojom::blink::WebSandboxFlags::kAll); g_page_holder->GetFrame().ForceSynchronousDocumentInstall( "text/html", empty_document_data); return 0;
diff --git a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc index a6ed874..f800145 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
@@ -980,7 +980,7 @@ return false; } if (MixedContentChecker::IsMixedContent( - policy_->GetSelfSource()->GetScheme(), + policy_->GetSelfSource()->scheme, parsed_endpoint)) { policy_->ReportMixedContentReportURI(endpoint); return true; @@ -1431,9 +1431,7 @@ auto policy = network::mojom::blink::ContentSecurityPolicy::New(); policy->self_origin = - policy_->GetSelfSource() - ? policy_->GetSelfSource()->ExposeForNavigationalChecks() - : nullptr; + policy_->GetSelfSource() ? policy_->GetSelfSource()->Clone() : nullptr; policy->use_reporting_api = use_reporting_api_; policy->report_endpoints = report_endpoints_; policy->header = network::mojom::blink::ContentSecurityPolicyHeader::New(
diff --git a/third_party/blink/renderer/core/frame/csp/csp_source.cc b/third_party/blink/renderer/core/frame/csp/csp_source.cc index a1366dfa..fec9276f 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_source.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_source.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/frame/csp/csp_source.h" +#include "services/network/public/mojom/content_security_policy.mojom-blink.h" #include "third_party/blink/public/platform/web_content_security_policy_struct.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" @@ -15,96 +16,28 @@ namespace blink { -constexpr int CSPSource::kPortUnspecified = -1; +namespace { -CSPSource::CSPSource(ContentSecurityPolicy* policy, - const String& scheme, - const String& host, - int port, - const String& path, - WildcardDisposition host_wildcard, - WildcardDisposition port_wildcard) - : policy_(policy), - scheme_(scheme.DeprecatedLower()), - host_(host), - port_(port), - path_(path), - host_wildcard_(host_wildcard), - port_wildcard_(port_wildcard) {} +enum class SchemeMatchingResult { + kNotMatching, + kMatchingUpgrade, + kMatchingExact +}; -CSPSource::CSPSource(ContentSecurityPolicy* policy, const CSPSource& other) - : CSPSource(policy, - other.scheme_, - other.host_, - other.port_, - other.path_, - other.host_wildcard_, - other.port_wildcard_) {} +enum class PortMatchingResult { + kNotMatching, + kMatchingWildcard, + kMatchingUpgrade, + kMatchingExact +}; -bool CSPSource::Matches(const KURL& url, - ResourceRequest::RedirectStatus redirect_status) const { - SchemeMatchingResult schemes_match = SchemeMatches(url.Protocol()); - if (schemes_match == SchemeMatchingResult::kNotMatching) - return false; - if (IsSchemeOnly()) - return true; - bool paths_match = (redirect_status == RedirectStatus::kFollowedRedirect) || - PathMatches(url.GetPath()); - PortMatchingResult ports_match = PortMatches( - url.HasPort() ? url.Port() : kPortUnspecified, url.Protocol()); - - // if either the scheme or the port would require an upgrade (e.g. from http - // to https) then check that both of them can upgrade to ensure that we don't - // run into situations where we only upgrade the port but not the scheme or - // viceversa - if ((RequiresUpgrade(schemes_match) || (RequiresUpgrade(ports_match))) && - (!CanUpgrade(schemes_match) || !CanUpgrade(ports_match))) { - return false; - } - - return HostMatches(url.Host()) && - ports_match != PortMatchingResult::kNotMatching && paths_match; -} - -bool CSPSource::MatchesAsSelf(const KURL& url) { - // https://w3c.github.io/webappsec-csp/#match-url-to-source-expression - // Step 4. - SchemeMatchingResult schemes_match = SchemeMatches(url.Protocol()); - bool hosts_match = HostMatches(url.Host()); - PortMatchingResult ports_match = PortMatches( - url.HasPort() ? url.Port() : kPortUnspecified, url.Protocol()); - - // check if the origin is exactly matching - if (schemes_match == SchemeMatchingResult::kMatchingExact && hosts_match && - (ports_match == PortMatchingResult::kMatchingExact || - ports_match == PortMatchingResult::kMatchingWildcard)) { - return true; - } - - String self_scheme = - (scheme_.IsEmpty() ? policy_->GetSelfProtocol() : scheme_); - - bool ports_match_or_defaults = - (ports_match == PortMatchingResult::kMatchingExact || - ((IsDefaultPortForProtocol(port_, self_scheme) || - port_ == kPortUnspecified) && - (!url.HasPort() || - IsDefaultPortForProtocol(url.Port(), url.Protocol())))); - - if (hosts_match && ports_match_or_defaults && - (url.Protocol() == "https" || url.Protocol() == "wss" || - self_scheme == "http")) { - return true; - } - - return false; -} - -CSPSource::SchemeMatchingResult CSPSource::SchemeMatches( - const String& protocol) const { +SchemeMatchingResult SchemeMatches( + const network::mojom::blink::CSPSource& source, + const String& protocol, + const String& self_protocol) { DCHECK_EQ(protocol, protocol.DeprecatedLower()); const String& scheme = - (scheme_.IsEmpty() ? policy_->GetSelfProtocol() : scheme_); + (source.scheme.IsEmpty() ? self_protocol : source.scheme); if (scheme == protocol) return SchemeMatchingResult::kMatchingExact; @@ -117,98 +50,161 @@ return SchemeMatchingResult::kNotMatching; } -bool CSPSource::HostMatches(const String& host) const { - bool match; - - bool equal_hosts = EqualIgnoringASCIICase(host_, host); - if (host_wildcard_ == kHasWildcard) { - if (host_.IsEmpty()) { +bool HostMatches(const network::mojom::blink::CSPSource& source, + const String& host) { + if (source.is_host_wildcard) { + if (source.host.IsEmpty()) { // host-part = "*" - match = true; - } else { - // host-part = "*." 1*host-char *( "." 1*host-char ) - match = host.EndsWithIgnoringCase(String("." + host_)); + return true; } - } else { - // host-part = 1*host-char *( "." 1*host-char ) - match = equal_hosts; + if (host.EndsWithIgnoringCase(String("." + source.host))) { + // host-part = "*." 1*host-char *( "." 1*host-char ) + return true; + } + return false; } - - return match; + return EqualIgnoringASCIICase(source.host, host); } -bool CSPSource::PathMatches(const String& url_path) const { - if (path_.IsEmpty() || (path_ == "/" && url_path.IsEmpty())) +bool PathMatches(const network::mojom::blink::CSPSource& source, + const String& url_path) { + if (source.path.IsEmpty() || (source.path == "/" && url_path.IsEmpty())) return true; String path = DecodeURLEscapeSequences(url_path, DecodeURLMode::kUTF8OrIsomorphic); - if (path_.EndsWith("/")) - return path.StartsWith(path_); + if (source.path.EndsWith("/")) + return path.StartsWith(source.path); - return path == path_; + return path == source.path; } -CSPSource::PortMatchingResult CSPSource::PortMatches( - int port, - const String& protocol) const { - if (port_wildcard_ == kHasWildcard) +PortMatchingResult PortMatches(const network::mojom::blink::CSPSource& source, + const String& self_protocol, + int port, + const String& protocol) { + if (source.is_port_wildcard) return PortMatchingResult::kMatchingWildcard; - if (port == port_) { - if (port == kPortUnspecified) + if (port == source.port) { + if (port == url::PORT_UNSPECIFIED) return PortMatchingResult::kMatchingWildcard; return PortMatchingResult::kMatchingExact; } bool is_scheme_http; // needed for detecting an upgrade when the port is 0 - is_scheme_http = scheme_.IsEmpty() ? policy_->ProtocolEqualsSelf("http") - : EqualIgnoringASCIICase("http", scheme_); + is_scheme_http = source.scheme.IsEmpty() + ? EqualIgnoringASCIICase("http", self_protocol) + : EqualIgnoringASCIICase("http", source.scheme); - if ((port_ == 80 || - ((port_ == kPortUnspecified || port_ == 443) && is_scheme_http)) && - (port == 443 || - (port == kPortUnspecified && DefaultPortForProtocol(protocol) == 443))) { + if ((source.port == 80 || + ((source.port == url::PORT_UNSPECIFIED || source.port == 443) && + is_scheme_http)) && + (port == 443 || (port == url::PORT_UNSPECIFIED && + DefaultPortForProtocol(protocol) == 443))) { return PortMatchingResult::kMatchingUpgrade; } - if (port == kPortUnspecified) { - if (IsDefaultPortForProtocol(port_, protocol)) + if (port == url::PORT_UNSPECIFIED) { + if (IsDefaultPortForProtocol(source.port, protocol)) return PortMatchingResult::kMatchingExact; - return PortMatchingResult::kNotMatching; } - if (port_ == kPortUnspecified) { + if (source.port == url::PORT_UNSPECIFIED) { if (IsDefaultPortForProtocol(port, protocol)) return PortMatchingResult::kMatchingExact; - return PortMatchingResult::kNotMatching; } return PortMatchingResult::kNotMatching; } -bool CSPSource::IsSchemeOnly() const { - return host_.IsEmpty() && (host_wildcard_ == kNoWildcard); +// Helper inline functions for Port and Scheme MatchingResult enums +bool inline RequiresUpgrade(const PortMatchingResult result) { + return result == PortMatchingResult::kMatchingUpgrade; +} +bool inline RequiresUpgrade(const SchemeMatchingResult result) { + return result == SchemeMatchingResult::kMatchingUpgrade; } -network::mojom::blink::CSPSourcePtr CSPSource::ExposeForNavigationalChecks() - const { - return network::mojom::blink::CSPSource::New( - scheme_ ? scheme_ : "", // scheme - host_ ? host_ : "", // host - port_ == kPortUnspecified ? -1 /* url::PORT_UNSPECIFIED */ - : port_, // port - path_ ? path_ : "", // path - host_wildcard_ == kHasWildcard, // is_host_wildcard - port_wildcard_ == kHasWildcard // is_port_wildcard - ); +bool inline CanUpgrade(const PortMatchingResult result) { + return result == PortMatchingResult::kMatchingUpgrade || + result == PortMatchingResult::kMatchingWildcard; } -void CSPSource::Trace(Visitor* visitor) const { - visitor->Trace(policy_); +bool inline CanUpgrade(const SchemeMatchingResult result) { + return result == SchemeMatchingResult::kMatchingUpgrade; +} + +} // namespace + +bool CSPSourceMatches(const network::mojom::blink::CSPSource& source, + const String& self_protocol, + const KURL& url, + ResourceRequest::RedirectStatus redirect_status) { + SchemeMatchingResult schemes_match = + SchemeMatches(source, url.Protocol(), self_protocol); + if (schemes_match == SchemeMatchingResult::kNotMatching) + return false; + if (CSPSourceIsSchemeOnly(source)) + return true; + bool paths_match = (redirect_status == RedirectStatus::kFollowedRedirect) || + PathMatches(source, url.GetPath()); + PortMatchingResult ports_match = PortMatches( + source, self_protocol, url.HasPort() ? url.Port() : url::PORT_UNSPECIFIED, + url.Protocol()); + + // if either the scheme or the port would require an upgrade (e.g. from http + // to https) then check that both of them can upgrade to ensure that we don't + // run into situations where we only upgrade the port but not the scheme or + // viceversa + if ((RequiresUpgrade(schemes_match) || (RequiresUpgrade(ports_match))) && + (!CanUpgrade(schemes_match) || !CanUpgrade(ports_match))) { + return false; + } + + return HostMatches(source, url.Host()) && + ports_match != PortMatchingResult::kNotMatching && paths_match; +} + +bool CSPSourceMatchesAsSelf(const network::mojom::blink::CSPSource& source, + const String& self_protocol, + const KURL& url) { + // https://w3c.github.io/webappsec-csp/#match-url-to-source-expression + // Step 4. + SchemeMatchingResult schemes_match = + SchemeMatches(source, url.Protocol(), self_protocol); + bool hosts_match = HostMatches(source, url.Host()); + PortMatchingResult ports_match = PortMatches( + source, self_protocol, url.HasPort() ? url.Port() : url::PORT_UNSPECIFIED, + url.Protocol()); + + // check if the origin is exactly matching + if (schemes_match == SchemeMatchingResult::kMatchingExact && hosts_match && + (ports_match == PortMatchingResult::kMatchingExact || + ports_match == PortMatchingResult::kMatchingWildcard)) { + return true; + } + + String self_scheme = + (source.scheme.IsEmpty() ? self_protocol : source.scheme); + + bool ports_match_or_defaults = + (ports_match == PortMatchingResult::kMatchingExact || + ((IsDefaultPortForProtocol(source.port, self_scheme) || + source.port == url::PORT_UNSPECIFIED) && + (!url.HasPort() || + IsDefaultPortForProtocol(url.Port(), url.Protocol())))); + + return hosts_match && ports_match_or_defaults && + (url.Protocol() == "https" || url.Protocol() == "wss" || + self_scheme == "http"); +} + +bool CSPSourceIsSchemeOnly(const network::mojom::blink::CSPSource& source) { + return source.host.IsEmpty() && (!source.is_host_wildcard); } } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/csp/csp_source.h b/third_party/blink/renderer/core/frame/csp/csp_source.h index 856d4cd..2f489b18 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_source.h +++ b/third_party/blink/renderer/core/frame/csp/csp_source.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_CSP_CSP_SOURCE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_CSP_CSP_SOURCE_H_ +#include "services/network/public/mojom/content_security_policy.mojom-blink-forward.h" #include "third_party/blink/public/platform/web_content_security_policy_struct.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" @@ -15,86 +16,22 @@ namespace blink { -class ContentSecurityPolicy; class KURL; -class CORE_EXPORT CSPSource final : public GarbageCollected<CSPSource> { - public: - // Represents the absence of a port. - const static int kPortUnspecified; +CORE_EXPORT +bool CSPSourceIsSchemeOnly(const network::mojom::blink::CSPSource& source); - enum WildcardDisposition { kNoWildcard, kHasWildcard }; +CORE_EXPORT +bool CSPSourceMatches(const network::mojom::blink::CSPSource& source, + const String& self_protocol, + const KURL& url, + ResourceRequest::RedirectStatus = + ResourceRequest::RedirectStatus::kNoRedirect); - // NotMatching is the only negative member, the rest are different types of - // matches. NotMatching should always be 0 to let if statements work nicely - enum class PortMatchingResult { - kNotMatching, - kMatchingWildcard, - kMatchingUpgrade, - kMatchingExact - }; - - enum class SchemeMatchingResult { - kNotMatching, - kMatchingUpgrade, - kMatchingExact - }; - - CSPSource(ContentSecurityPolicy*, - const String& scheme, - const String& host, - int port, - const String& path, - WildcardDisposition host_wildcard, - WildcardDisposition port_wildcard); - CSPSource(ContentSecurityPolicy* policy, const CSPSource& other); - bool IsSchemeOnly() const; - const String& GetScheme() { return scheme_; } - bool Matches(const KURL&, - ResourceRequest::RedirectStatus = - ResourceRequest::RedirectStatus::kNoRedirect) const; - - bool MatchesAsSelf(const KURL&); - - network::mojom::blink::CSPSourcePtr ExposeForNavigationalChecks() const; - - void Trace(Visitor*) const; - - private: - FRIEND_TEST_ALL_PREFIXES(CSPDirectiveListTest, OperativeDirectiveGivenType); - - SchemeMatchingResult SchemeMatches(const String&) const; - bool HostMatches(const String&) const; - bool PathMatches(const String&) const; - // Protocol is necessary to determine default port if it is zero. - PortMatchingResult PortMatches(int port, const String& protocol) const; - - // Helper inline functions for Port and Scheme MatchingResult enums - bool inline RequiresUpgrade(const PortMatchingResult result) const { - return result == PortMatchingResult::kMatchingUpgrade; - } - bool inline RequiresUpgrade(const SchemeMatchingResult result) const { - return result == SchemeMatchingResult::kMatchingUpgrade; - } - - bool inline CanUpgrade(const PortMatchingResult result) const { - return result == PortMatchingResult::kMatchingUpgrade || - result == PortMatchingResult::kMatchingWildcard; - } - - bool inline CanUpgrade(const SchemeMatchingResult result) const { - return result == SchemeMatchingResult::kMatchingUpgrade; - } - - Member<ContentSecurityPolicy> policy_; - String scheme_; - String host_; - int port_; - String path_; - - WildcardDisposition host_wildcard_; - WildcardDisposition port_wildcard_; -}; +CORE_EXPORT +bool CSPSourceMatchesAsSelf(const network::mojom::blink::CSPSource& source, + const String& self_protocol, + const KURL& url); } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/csp/csp_source_test.cc b/third_party/blink/renderer/core/frame/csp/csp_source_test.cc index 4238482..f0bd0b9 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_source_test.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_source_test.cc
@@ -13,425 +13,437 @@ namespace blink { -class CSPSourceTest : public testing::Test { - public: - CSPSourceTest() : csp(MakeGarbageCollected<ContentSecurityPolicy>()) {} - - protected: - Persistent<ContentSecurityPolicy> csp; - struct Source { - String scheme; - String host; - String path; - // port is CSPSource::kPortUnspecified if it was not specified so the - // default port for a given scheme will be used. - const int port; - CSPSource::WildcardDisposition host_wildcard; - CSPSource::WildcardDisposition port_wildcard; - }; - - bool EqualSources(const Source& a, const Source& b) { - return a.scheme == b.scheme && a.host == b.host && a.port == b.port && - a.path == b.path && a.host_wildcard == b.host_wildcard && - a.port_wildcard == b.port_wildcard; - } -}; - -TEST_F(CSPSourceTest, BasicMatching) { +TEST(CSPSourceTest, BasicMatching) { KURL base; - CSPSource source(csp.Get(), "http", "example.com", 8000, "/foo/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); + auto source = network::mojom::blink::CSPSource::New( + "http", "example.com", 8000, "/foo/", false, false); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com:8000/foo/"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com:8000/foo/bar"))); - EXPECT_TRUE(source.Matches(KURL(base, "HTTP://EXAMPLE.com:8000/foo/BAR"))); - - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:8000/bar/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://example.com:8000/bar/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:9000/bar/"))); - EXPECT_FALSE(source.Matches(KURL(base, "HTTP://example.com:8000/FOO/bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "HTTP://example.com:8000/FOO/BAR"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:8000/foo/"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:8000/foo/bar"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "HTTP://EXAMPLE.com:8000/foo/BAR"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:8000/bar/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://example.com:8000/bar/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:9000/bar/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "HTTP://example.com:8000/FOO/bar"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "HTTP://example.com:8000/FOO/BAR"))); } -TEST_F(CSPSourceTest, BasicPathMatching) { +TEST(CSPSourceTest, BasicPathMatching) { KURL base; - CSPSource a(csp.Get(), "http", "example.com", 8000, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); + auto a = network::mojom::blink::CSPSource::New("http", "example.com", 8000, + "/", false, false); - EXPECT_TRUE(a.Matches(KURL(base, "http://example.com:8000"))); - EXPECT_TRUE(a.Matches(KURL(base, "http://example.com:8000/"))); - EXPECT_TRUE(a.Matches(KURL(base, "http://example.com:8000/foo/bar"))); + EXPECT_TRUE(CSPSourceMatches(*a, "", KURL(base, "http://example.com:8000"))); + EXPECT_TRUE(CSPSourceMatches(*a, "", KURL(base, "http://example.com:8000/"))); + EXPECT_TRUE( + CSPSourceMatches(*a, "", KURL(base, "http://example.com:8000/foo/bar"))); - EXPECT_FALSE(a.Matches(KURL(base, "http://example.com:8000path"))); - EXPECT_FALSE(a.Matches(KURL(base, "http://example.com:9000/"))); + EXPECT_FALSE( + CSPSourceMatches(*a, "", KURL(base, "http://example.com:8000path"))); + EXPECT_FALSE( + CSPSourceMatches(*a, "", KURL(base, "http://example.com:9000/"))); - CSPSource b(csp.Get(), "http", "example.com", 8000, "", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(b.Matches(KURL(base, "http://example.com:8000"))); - EXPECT_TRUE(b.Matches(KURL(base, "http://example.com:8000/"))); - EXPECT_TRUE(a.Matches(KURL(base, "http://example.com:8000/foo/bar"))); + auto b = network::mojom::blink::CSPSource::New("http", "example.com", 8000, + "", false, false); + EXPECT_TRUE(CSPSourceMatches(*b, "", KURL(base, "http://example.com:8000"))); + EXPECT_TRUE(CSPSourceMatches(*b, "", KURL(base, "http://example.com:8000/"))); + EXPECT_TRUE( + CSPSourceMatches(*a, "", KURL(base, "http://example.com:8000/foo/bar"))); - EXPECT_FALSE(b.Matches(KURL(base, "http://example.com:8000path"))); - EXPECT_FALSE(b.Matches(KURL(base, "http://example.com:9000/"))); + EXPECT_FALSE( + CSPSourceMatches(*b, "", KURL(base, "http://example.com:8000path"))); + EXPECT_FALSE( + CSPSourceMatches(*b, "", KURL(base, "http://example.com:9000/"))); } -TEST_F(CSPSourceTest, WildcardMatching) { +TEST(CSPSourceTest, WildcardMatching) { KURL base; - CSPSource source(csp.Get(), "http", "example.com", - CSPSource::kPortUnspecified, "/", CSPSource::kHasWildcard, - CSPSource::kHasWildcard); + auto source = network::mojom::blink::CSPSource::New( + "http", "example.com", url::PORT_UNSPECIFIED, "/", true, true); - EXPECT_TRUE(source.Matches(KURL(base, "http://foo.example.com:8000/"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://foo.example.com:8000/foo"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://foo.example.com:9000/foo/"))); - EXPECT_TRUE( - source.Matches(KURL(base, "HTTP://FOO.EXAMPLE.com:8000/foo/BAR"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://foo.example.com:8000/"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://foo.example.com:8000/foo"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://foo.example.com:9000/foo/"))); + EXPECT_TRUE(CSPSourceMatches( + *source, "", KURL(base, "HTTP://FOO.EXAMPLE.com:8000/foo/BAR"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:8000/foo"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:9000/foo/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.foo.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://example.foo.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://example.com:8000/bar/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/foo"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:9000/foo/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://example.foo.com:8000/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://example.foo.com:8000/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://example.com:8000/bar/"))); } -TEST_F(CSPSourceTest, RedirectMatching) { +TEST(CSPSourceTest, RedirectMatching) { KURL base; - CSPSource source(csp.Get(), "http", "example.com", 8000, "/bar/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); + auto source = network::mojom::blink::CSPSource::New( + "http", "example.com", 8000, "/bar/", false, false); EXPECT_TRUE( - source.Matches(KURL(base, "http://example.com:8000/"), - ResourceRequest::RedirectStatus::kFollowedRedirect)); + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/"), + ResourceRequest::RedirectStatus::kFollowedRedirect)); EXPECT_TRUE( - source.Matches(KURL(base, "http://example.com:8000/foo"), - ResourceRequest::RedirectStatus::kFollowedRedirect)); + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/foo"), + ResourceRequest::RedirectStatus::kFollowedRedirect)); // Should not allow upgrade of port or scheme without upgrading both EXPECT_FALSE( - source.Matches(KURL(base, "https://example.com:8000/foo"), - ResourceRequest::RedirectStatus::kFollowedRedirect)); + CSPSourceMatches(*source, "", KURL(base, "https://example.com:8000/foo"), + ResourceRequest::RedirectStatus::kFollowedRedirect)); + EXPECT_FALSE(CSPSourceMatches( + *source, "", KURL(base, "http://not-example.com:8000/foo"), + ResourceRequest::RedirectStatus::kFollowedRedirect)); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://example.com:9000/foo/"), + ResourceRequest::RedirectStatus::kNoRedirect)); +} + +TEST(CSPSourceTest, InsecureSchemeMatchesSecureScheme) { + KURL base; + auto source = network::mojom::blink::CSPSource::New( + "http", "", url::PORT_UNSPECIFIED, "/", false, true); + + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:8000/"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "http://not-example.com:8000/"))); + EXPECT_TRUE(CSPSourceMatches(*source, "", + KURL(base, "https://not-example.com:8000/"))); EXPECT_FALSE( - source.Matches(KURL(base, "http://not-example.com:8000/foo"), - ResourceRequest::RedirectStatus::kFollowedRedirect)); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:9000/foo/"), - ResourceRequest::RedirectStatus::kNoRedirect)); + CSPSourceMatches(*source, "", KURL(base, "ftp://example.com:8000/"))); } -TEST_F(CSPSourceTest, InsecureSchemeMatchesSecureScheme) { +TEST(CSPSourceTest, InsecureHostSchemeMatchesSecureScheme) { KURL base; - CSPSource source(csp.Get(), "http", "", CSPSource::kPortUnspecified, "/", - CSPSource::kNoWildcard, CSPSource::kHasWildcard); + auto source = network::mojom::blink::CSPSource::New( + "http", "example.com", url::PORT_UNSPECIFIED, "/", false, true); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com:8000/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com:8000/"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://not-example.com:8000/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://not-example.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "ftp://example.com:8000/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8000/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://not-example.com:8000/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:8000/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://not-example.com:8000/"))); } -TEST_F(CSPSourceTest, InsecureHostSchemeMatchesSecureScheme) { - KURL base; - CSPSource source(csp.Get(), "http", "example.com", - CSPSource::kPortUnspecified, "/", CSPSource::kNoWildcard, - CSPSource::kHasWildcard); - - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://not-example.com:8000/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com:8000/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://not-example.com:8000/"))); -} - -TEST_F(CSPSourceTest, SchemeIsEmpty) { +TEST(CSPSourceTest, SchemeIsEmpty) { KURL base; // Self scheme is http. { - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf(*SecurityOrigin::CreateFromString("http://a.com/")); - CSPSource source(csp.Get(), "", "a.com", CSPSource::kPortUnspecified, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://a.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://a.com"))); - EXPECT_FALSE(source.Matches(KURL(base, "ftp://a.com"))); + auto source = network::mojom::blink::CSPSource::New( + "", "a.com", url::PORT_UNSPECIFIED, "/", false, false); + EXPECT_TRUE(CSPSourceMatches(*source, "http", KURL(base, "http://a.com"))); + EXPECT_TRUE(CSPSourceMatches(*source, "http", KURL(base, "https://a.com"))); + EXPECT_FALSE(CSPSourceMatches(*source, "http", KURL(base, "ftp://a.com"))); } // Self scheme is https. { - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf(*SecurityOrigin::CreateFromString("https://a.com/")); - CSPSource source(csp.Get(), "", "a.com", CSPSource::kPortUnspecified, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_FALSE(source.Matches(KURL(base, "http://a.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://a.com"))); - EXPECT_FALSE(source.Matches(KURL(base, "ftp://a.com"))); + auto source = network::mojom::blink::CSPSource::New( + "", "a.com", url::PORT_UNSPECIFIED, "/", false, false); + EXPECT_FALSE( + CSPSourceMatches(*source, "https", KURL(base, "http://a.com"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "https", KURL(base, "https://a.com"))); + EXPECT_FALSE(CSPSourceMatches(*source, "https", KURL(base, "ftp://a.com"))); } // Self scheme is not in the http familly. { - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf(*SecurityOrigin::CreateFromString("ftp://a.com/")); - CSPSource source(csp.Get(), "", "a.com", CSPSource::kPortUnspecified, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_FALSE(source.Matches(KURL(base, "http://a.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "ftp://a.com"))); + auto source = network::mojom::blink::CSPSource::New( + "", "a.com", url::PORT_UNSPECIFIED, "/", false, false); + EXPECT_FALSE(CSPSourceMatches(*source, "ftp", KURL(base, "http://a.com"))); + EXPECT_TRUE(CSPSourceMatches(*source, "ftp", KURL(base, "ftp://a.com"))); } // Self scheme is unique { - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf( - *SecurityOrigin::CreateFromString("non-standard-scheme://a.com/")); - CSPSource source(csp.Get(), "", "a.com", CSPSource::kPortUnspecified, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_FALSE(source.Matches(KURL(base, "http://a.com"))); + auto source = network::mojom::blink::CSPSource::New( + "", "a.com", url::PORT_UNSPECIFIED, "/", false, false); + EXPECT_FALSE(CSPSourceMatches(*source, "non-standard-scheme", + KURL(base, "http://a.com"))); // The reason matching fails is because the host is parsed as "" when // using a non standard scheme even though it should be parsed as "a.com" // After adding it to the list of standard schemes it now gets parsed // correctly. This does not matter in practice though because there is // no way to render/load anything like "non-standard-scheme://a.com" - EXPECT_FALSE(source.Matches(KURL(base, "non-standard-scheme://a.com"))); + EXPECT_FALSE(CSPSourceMatches(*source, "non-standard-scheme", + KURL(base, "non-standard-scheme://a.com"))); } } -TEST_F(CSPSourceTest, InsecureHostSchemePortMatchesSecurePort) { +TEST(CSPSourceTest, InsecureHostSchemePortMatchesSecurePort) { KURL base; // source scheme is "http", source port is 80 { - CSPSource source(csp.Get(), "http", "example.com", 80, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com/"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com:80/"))); + auto source = network::mojom::blink::CSPSource::New("http", "example.com", + 80, "/", false, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:80/"))); // Should not allow scheme upgrades unless both port and scheme are upgraded - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:443/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://example.com:80/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:443/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:80/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com:443/"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:443/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:8443/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://example.com:8443/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:8443/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:8443/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://not-example.com/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://not-example.com:80/"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://not-example.com:443/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://not-example.com/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://not-example.com:80/"))); - EXPECT_FALSE(source.Matches(KURL(base, "https://not-example.com:443/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://not-example.com/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://not-example.com:80/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "http://not-example.com:443/"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "https://not-example.com/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://not-example.com:80/"))); + EXPECT_FALSE(CSPSourceMatches(*source, "", + KURL(base, "https://not-example.com:443/"))); } // source scheme is "http", source port is 443 { - CSPSource source(csp.Get(), "http", "example.com", 443, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com/"))); + auto source = network::mojom::blink::CSPSource::New("http", "example.com", + 443, "/", false, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com/"))); } // source scheme is empty { - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf(*SecurityOrigin::CreateFromString("http://example.com")); - CSPSource source(csp.Get(), "", "example.com", 80, "/", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com/"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com:443"))); + auto source = network::mojom::blink::CSPSource::New("", "example.com", 80, + "/", false, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://example.com/"))); + EXPECT_TRUE(CSPSourceMatches(*source, "http", + KURL(base, "https://example.com:443"))); // Should not allow upgrade of port or scheme without upgrading both - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:443"))); + EXPECT_FALSE(CSPSourceMatches(*source, "http", + KURL(base, "http://example.com:443"))); } // source port is empty { - CSPSource source(csp.Get(), "http", "example.com", - CSPSource::kPortUnspecified, "/", CSPSource::kNoWildcard, - CSPSource::kNoWildcard); + auto source = network::mojom::blink::CSPSource::New( + "http", "example.com", url::PORT_UNSPECIFIED, "/", false, false); - EXPECT_TRUE(source.Matches(KURL(base, "http://example.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "https://example.com:443"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:443"))); // Should not allow upgrade of port or scheme without upgrading both - EXPECT_FALSE(source.Matches(KURL(base, "https://example.com:80"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://example.com:443"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "https://example.com:80"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "", KURL(base, "http://example.com:443"))); } } -TEST_F(CSPSourceTest, HostMatches) { +TEST(CSPSourceTest, HostMatches) { KURL base; - Persistent<ContentSecurityPolicy> csp( - MakeGarbageCollected<ContentSecurityPolicy>()); - csp->SetupSelf(*SecurityOrigin::CreateFromString("http://a.com")); // Host is * (source-expression = "http://*") { - CSPSource source(csp.Get(), "http", "", CSPSource::kPortUnspecified, "", - CSPSource::kHasWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://a.com"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://."))); + auto source = network::mojom::blink::CSPSource::New( + "http", "", url::PORT_UNSPECIFIED, "", true, false); + EXPECT_TRUE(CSPSourceMatches(*source, "http", KURL(base, "http://a.com"))); + EXPECT_TRUE(CSPSourceMatches(*source, "http", KURL(base, "http://."))); } // Host is *.foo.bar { - CSPSource source(csp.Get(), "", "foo.bar", CSPSource::kPortUnspecified, "", - CSPSource::kHasWildcard, CSPSource::kNoWildcard); - EXPECT_FALSE(source.Matches(KURL(base, "http://a.com"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://foo.bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://o.bar"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://*.foo.bar"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://sub.foo.bar"))); - EXPECT_TRUE(source.Matches(KURL(base, "http://sub.sub.foo.bar"))); + auto source = network::mojom::blink::CSPSource::New( + "", "foo.bar", url::PORT_UNSPECIFIED, "", true, false); + EXPECT_FALSE(CSPSourceMatches(*source, "http", KURL(base, "http://a.com"))); + EXPECT_FALSE(CSPSourceMatches(*source, "http", KURL(base, "http://bar"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "http", KURL(base, "http://foo.bar"))); + EXPECT_FALSE(CSPSourceMatches(*source, "http", KURL(base, "http://o.bar"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://*.foo.bar"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://sub.foo.bar"))); + EXPECT_TRUE(CSPSourceMatches(*source, "http", + KURL(base, "http://sub.sub.foo.bar"))); // Please see http://crbug.com/692505 - EXPECT_TRUE(source.Matches(KURL(base, "http://.foo.bar"))); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://.foo.bar"))); } // Host is exact. { - CSPSource source(csp.Get(), "", "foo.bar", CSPSource::kPortUnspecified, "", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://foo.bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://sub.foo.bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://bar"))); + auto source = network::mojom::blink::CSPSource::New( + "", "foo.bar", url::PORT_UNSPECIFIED, "", false, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://foo.bar"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "http", KURL(base, "http://sub.foo.bar"))); + EXPECT_FALSE(CSPSourceMatches(*source, "http", KURL(base, "http://bar"))); // Please see http://crbug.com/692505 - EXPECT_FALSE(source.Matches(KURL(base, "http://.foo.bar"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "http", KURL(base, "http://.foo.bar"))); } // Host matching is case-insensitive. { - CSPSource source(csp.Get(), "", "FoO.BaR", CSPSource::kPortUnspecified, "", - CSPSource::kNoWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://foo.bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://sub.foo.bar"))); + auto source = network::mojom::blink::CSPSource::New( + "", "FoO.BaR", url::PORT_UNSPECIFIED, "", false, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://foo.bar"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "http", KURL(base, "http://sub.foo.bar"))); } // Wildcarded host matching is case-insensitive. { - CSPSource source(csp.Get(), "", "FoO.BaR", CSPSource::kPortUnspecified, "", - CSPSource::kHasWildcard, CSPSource::kNoWildcard); - EXPECT_TRUE(source.Matches(KURL(base, "http://sub.foo.bar"))); - EXPECT_FALSE(source.Matches(KURL(base, "http://foo.bar"))); + auto source = network::mojom::blink::CSPSource::New( + "", "FoO.BaR", url::PORT_UNSPECIFIED, "", true, false); + EXPECT_TRUE( + CSPSourceMatches(*source, "http", KURL(base, "http://sub.foo.bar"))); + EXPECT_FALSE( + CSPSourceMatches(*source, "http", KURL(base, "http://foo.bar"))); } } -TEST_F(CSPSourceTest, MatchingAsSelf) { +TEST(CSPSourceTest, MatchingAsSelf) { // Testing Step 4 of // https://w3c.github.io/webappsec-csp/#match-url-to-source-expression + struct Source { + String scheme; + String host; + String path; + int port; + bool host_wildcard; + bool port_wildcard; + }; struct TestCase { const Source self_source; const String& url; bool expected; } cases[] = { // Same origin - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "http://example.com:80/", true}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "https://example.com:443/", true}, - {{"https", "example.com", "", 4545, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 4545, false, false}, "https://example.com:4545/", true}, // Mismatching origin // Mismatching host - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "http://example2.com:80/", false}, // Ports not matching default schemes - {{"http", "example.com", "", 8080, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 8080, false, false}, "https://example.com:443/", false}, - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "wss://example.com:8443/", false}, // Allowed different scheme combinations (4.2.1 and 4.2.2) - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "https://example.com:443/", true}, - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "ws://example.com:80/", true}, - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "wss://example.com:443/", true}, - {{"ws", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"ws", "example.com", "", 80, false, false}, "https://example.com:443/", true}, - {{"wss", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"wss", "example.com", "", 443, false, false}, "https://example.com:443/", true}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "wss://example.com:443/", true}, // Ports not set (aka default) - {{"https", "example.com", "", CSPSource::kPortUnspecified, - CSPSource::kNoWildcard, CSPSource::kNoWildcard}, + {{"https", "example.com", "", url::PORT_UNSPECIFIED, false, false}, "wss://example.com:443/", true}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "wss://example.com/", true}, // Paths are ignored - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "https://example.com:443/some-path-here", true}, - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "ws://example.com:80/some-other-path-here", true}, // Custom schemes - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "custom-scheme://example.com/", false}, - {{"http", "example.com", "", 80, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"http", "example.com", "", 80, false, false}, "custom-scheme://example.com:80/", false}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "custom-scheme://example.com/", false}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "custom-scheme://example.com:443/", false}, - {{"https", "example.com", "", 443, CSPSource::kNoWildcard, - CSPSource::kNoWildcard}, + {{"https", "example.com", "", 443, false, false}, "custom-scheme://example.com/some-path", false}, - {{"http", "example.com", "", CSPSource::kPortUnspecified, - CSPSource::kNoWildcard, CSPSource::kNoWildcard}, + {{"http", "example.com", "", url::PORT_UNSPECIFIED, false, false}, "custom-scheme://example.com/some-path", false}, }; KURL base; for (const auto& test : cases) { - CSPSource* self_source = MakeGarbageCollected<CSPSource>( - csp.Get(), test.self_source.scheme, test.self_source.host, - test.self_source.port, test.self_source.path, - test.self_source.host_wildcard, test.self_source.port_wildcard); - EXPECT_EQ(self_source->MatchesAsSelf(KURL(base, test.url)), test.expected); + auto self_source = network::mojom::blink::CSPSource::New( + test.self_source.scheme, test.self_source.host, test.self_source.port, + test.self_source.path, test.self_source.host_wildcard, + test.self_source.port_wildcard); + EXPECT_EQ(test.expected, + CSPSourceMatchesAsSelf(*self_source, "", KURL(base, test.url))); } }
diff --git a/third_party/blink/renderer/core/frame/csp/source_list_directive.cc b/third_party/blink/renderer/core/frame/csp/source_list_directive.cc index 4d5a2671..3abc948 100644 --- a/third_party/blink/renderer/core/frame/csp/source_list_directive.cc +++ b/third_party/blink/renderer/core/frame/csp/source_list_directive.cc
@@ -160,10 +160,14 @@ const UChar* begin_source = position; SkipWhile<UChar, IsSourceCharacter>(position, end); - String scheme, host, path; - int port = CSPSource::kPortUnspecified; - CSPSource::WildcardDisposition host_wildcard = CSPSource::kNoWildcard; - CSPSource::WildcardDisposition port_wildcard = CSPSource::kNoWildcard; + // We need to initialize all strings, since they can't be null in the mojo + // struct. + String scheme = ""; + String host = ""; + String path = ""; + int port = url::PORT_UNSPECIFIED; + bool host_wildcard = false; + bool port_wildcard = false; if (ParseSource(begin_source, position, &scheme, &host, &port, &path, &host_wildcard, &port_wildcard)) { @@ -175,8 +179,8 @@ if (ContentSecurityPolicy::GetDirectiveType(host) != ContentSecurityPolicy::DirectiveType::kUndefined) policy_->ReportDirectiveAsSourceExpression(directive_name_, host); - list_.push_back(MakeGarbageCollected<CSPSource>( - policy_, scheme, host, port, path, host_wildcard, port_wildcard)); + list_.push_back(network::mojom::blink::CSPSource::New( + scheme, host, port, path, host_wildcard, port_wildcard)); } else { policy_->ReportInvalidSourceExpression( directive_name_, String(begin_source, static_cast<wtf_size_t>( @@ -190,15 +194,14 @@ // source = scheme ":" // / ( [ scheme "://" ] host [ port ] [ path ] ) // / "'self'" -bool SourceListDirective::ParseSource( - const UChar* begin, - const UChar* end, - String* scheme, - String* host, - int* port, - String* path, - CSPSource::WildcardDisposition* host_wildcard, - CSPSource::WildcardDisposition* port_wildcard) { +bool SourceListDirective::ParseSource(const UChar* begin, + const UChar* end, + String* scheme, + String* host, + int* port, + String* path, + bool* host_wildcard, + bool* port_wildcard) { if (begin == end) return false; @@ -339,7 +342,7 @@ if (!ParsePort(begin_port, begin_path, port, port_wildcard)) return false; } else { - *port = CSPSource::kPortUnspecified; + *port = url::PORT_UNSPECIFIED; } if (begin_path != end) { @@ -480,14 +483,13 @@ // host-char = ALPHA / DIGIT / "-" // // static -bool SourceListDirective::ParseHost( - const UChar* begin, - const UChar* end, - String* host, - CSPSource::WildcardDisposition* host_wildcard) { +bool SourceListDirective::ParseHost(const UChar* begin, + const UChar* end, + String* host, + bool* host_wildcard) { DCHECK(begin <= end); DCHECK(host->IsEmpty()); - DCHECK(*host_wildcard == CSPSource::kNoWildcard); + DCHECK(!*host_wildcard); if (begin == end) return false; @@ -496,7 +498,7 @@ // Parse "*" or [ "*." ]. if (SkipExactly<UChar>(position, end, '*')) { - *host_wildcard = CSPSource::kHasWildcard; + *host_wildcard = true; if (position == end) { // "*" @@ -553,14 +555,13 @@ // port = ":" ( 1*DIGIT / "*" ) // -bool SourceListDirective::ParsePort( - const UChar* begin, - const UChar* end, - int* port, - CSPSource::WildcardDisposition* port_wildcard) { +bool SourceListDirective::ParsePort(const UChar* begin, + const UChar* end, + int* port, + bool* port_wildcard) { DCHECK(begin <= end); - DCHECK_EQ(*port, CSPSource::kPortUnspecified); - DCHECK(*port_wildcard == CSPSource::kNoWildcard); + DCHECK_EQ(*port, url::PORT_UNSPECIFIED); + DCHECK(!*port_wildcard); if (!SkipExactly<UChar>(begin, end, ':')) NOTREACHED(); @@ -569,8 +570,8 @@ return false; if (end - begin == 1 && *begin == '*') { - *port = CSPSource::kPortUnspecified; - *port_wildcard = CSPSource::kHasWildcard; + *port = url::PORT_UNSPECIFIED; + *port_wildcard = true; return true; } @@ -636,9 +637,11 @@ bool SourceListDirective::HasSourceMatchInList( const KURL& url, ResourceRequest::RedirectStatus redirect_status) const { - for (wtf_size_t i = 0; i < list_.size(); ++i) { - if (list_[i]->Matches(url, redirect_status)) + for (const auto& source : list_) { + if (CSPSourceMatches(*source, policy_->GetSelfProtocol(), url, + redirect_status)) { return true; + } } return false; @@ -661,7 +664,7 @@ SourceListDirective::ExposeForNavigationalChecks() const { WTF::Vector<network::mojom::blink::CSPSourcePtr> sources; for (const auto& source : list_) - sources.push_back(source->ExposeForNavigationalChecks()); + sources.push_back(source.Clone()); // We do not need nonces and hashes for navigational checks WTF::Vector<WTF::String> nonces; @@ -675,7 +678,6 @@ void SourceListDirective::Trace(Visitor* visitor) const { visitor->Trace(policy_); - visitor->Trace(list_); CSPDirective::Trace(visitor); }
diff --git a/third_party/blink/renderer/core/frame/csp/source_list_directive.h b/third_party/blink/renderer/core/frame/csp/source_list_directive.h index 37f0dec..511977d 100644 --- a/third_party/blink/renderer/core/frame/csp/source_list_directive.h +++ b/third_party/blink/renderer/core/frame/csp/source_list_directive.h
@@ -71,17 +71,17 @@ String* host, int* port, String* path, - CSPSource::WildcardDisposition*, - CSPSource::WildcardDisposition*); + bool* is_host_wildcard, + bool* is_port_wildcard); bool ParseScheme(const UChar* begin, const UChar* end, String* scheme); static bool ParseHost(const UChar* begin, const UChar* end, String* host, - CSPSource::WildcardDisposition*); + bool* is_host_wildcard); bool ParsePort(const UChar* begin, const UChar* end, int* port, - CSPSource::WildcardDisposition*); + bool* is_port_wildcard); bool ParsePath(const UChar* begin, const UChar* end, String* path); bool ParseNonce(const UChar* begin, const UChar* end, String* nonce); bool ParseHash(const UChar* begin, @@ -105,7 +105,7 @@ bool HasSourceMatchInList(const KURL&, ResourceRequest::RedirectStatus) const; Member<ContentSecurityPolicy> policy_; - HeapVector<Member<CSPSource>> list_; + WTF::Vector<network::mojom::blink::CSPSourcePtr> list_; String directive_name_; bool allow_self_; bool allow_star_;
diff --git a/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc b/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc index b3d195b..aa5cf2e5 100644 --- a/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc +++ b/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc
@@ -26,8 +26,8 @@ String host; const int port; String path; - CSPSource::WildcardDisposition host_wildcard; - CSPSource::WildcardDisposition port_wildcard; + bool host_wildcard; + bool port_wildcard; }; void SetUp() override { @@ -430,7 +430,7 @@ for (const auto& test : cases) { String host; - CSPSource::WildcardDisposition disposition = CSPSource::kNoWildcard; + bool disposition = false; Vector<UChar> characters; test.sources.AppendTo(characters); const UChar* start = characters.data();
diff --git a/third_party/blink/renderer/core/frame/frame.h b/third_party/blink/renderer/core/frame/frame.h index 3fa70bc..f1dd729 100644 --- a/third_party/blink/renderer/core/frame/frame.h +++ b/third_party/blink/renderer/core/frame/frame.h
@@ -32,6 +32,7 @@ #include "base/i18n/rtl.h" #include "base/optional.h" #include "base/unguessable_token.h" +#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h" #include "third_party/blink/public/common/feature_policy/document_policy_features.h" #include "third_party/blink/public/common/feature_policy/feature_policy_features.h" #include "third_party/blink/public/common/frame/user_activation_state.h" @@ -253,6 +254,23 @@ return navigation_rate_limiter_; } + // Called to get the opener's sandbox flags if any. This works with disowned + // openers, i.e., even if WebFrame::Opener() is nullptr, + network::mojom::blink::WebSandboxFlags OpenerSandboxFlags() const { + return opener_sandbox_flags_; + } + + // Sets the opener's sandbox_flags for the main frame. Once a non-empty + // |opener_feature_state| is set, it can no longer be modified (due to the + // fact that the original opener which passed down the FeatureState cannot be + // modified either). + void SetOpenerSandboxFlags(network::mojom::blink::WebSandboxFlags flags) { + DCHECK(IsMainFrame()); + DCHECK_EQ(network::mojom::blink::WebSandboxFlags::kNone, + opener_sandbox_flags_); + opener_sandbox_flags_ = flags; + } + const DocumentPolicyFeatureState& GetRequiredDocumentPolicy() const { return required_document_policy_; } @@ -427,6 +445,10 @@ NavigationRateLimiter navigation_rate_limiter_; + // Sandbox flags inherited from an opener. It is always empty for child + // frames. + network::mojom::blink::WebSandboxFlags opener_sandbox_flags_; + // The required document policy for any subframes of this frame. // Note: current frame's document policy might not conform to // |required_document_policy_| here, as the Require-Document-Policy HTTP
diff --git a/third_party/blink/renderer/core/frame/frame_console.cc b/third_party/blink/renderer/core/frame/frame_console.cc index 2e8f77d8..0ae6585 100644 --- a/third_party/blink/renderer/core/frame/frame_console.cc +++ b/third_party/blink/renderer/core/frame/frame_console.cc
@@ -76,8 +76,9 @@ if (source == mojom::ConsoleMessageSource::kConsoleApi) { if (!frame_->GetPage()) return; - if (frame_->GetChromeClient().ShouldReportDetailedMessageForSource(*frame_, - url)) { + if (frame_->GetChromeClient() + .ShouldReportDetailedMessageForSourceAndSeverity(*frame_, level, + url)) { std::unique_ptr<SourceLocation> full_location = SourceLocation::CaptureWithFullStackTrace(); if (!full_location->IsUnknown()) @@ -85,8 +86,9 @@ } } else { if (!location->IsUnknown() && - frame_->GetChromeClient().ShouldReportDetailedMessageForSource(*frame_, - url)) + frame_->GetChromeClient() + .ShouldReportDetailedMessageForSourceAndSeverity(*frame_, level, + url)) stack_trace = location->ToString(); }
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index cfb4362..cb9e536 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -2111,15 +2111,6 @@ // this state can no longer be accurately calculated. CHECK(!IsDetached()); - // TODO(https://crbug.com/838348): Sadly, there are situations where Blink may - // attempt to detach a main frame twice due to a bug. That rewinds - // FrameLifecycle from kDetached to kDetaching, but GetPage() will already be - // null. Early returning false in that case is "safe enough", as the frame has - // already been detached, so any detach work gated on IsProvisional() has - // already been done. - if (!GetPage()) - return false; - if (IsMainFrame()) { return GetPage()->MainFrame() != this; }
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc index c7caa0e7..d3cc400 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc
@@ -744,6 +744,18 @@ navigation_info->frame_policy = owner ? owner->GetFramePolicy() : FramePolicy(); + // owner->GetFramePolicy() above only contains the sandbox flags defined by + // the <iframe> element. It doesn't take into account inheritance from the + // parent or the opener. This is not a problem in the general case, because + // this attribute is simply dropped! It matter only for the "fake" navigation + // to the "fake" initial empty document. It is: + // RenderFrameImpl::CommitInitialEmptyDocument(). + // This one doesn't go toward the browser process, it commits synchronously. + // The sandbox flags must be defined. They correspond to the one already in + // use for the 'real' initial empty document. + navigation_info->frame_policy.sandbox_flags = + web_frame_->GetFrame()->Loader().PendingEffectiveSandboxFlags(); + navigation_info->href_translate = href_translate; web_frame_->Client()->BeginNavigation(std::move(navigation_info));
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 76be566..0249ba14 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -461,8 +461,18 @@ return !lifecycle_updates_throttled_; } -void LocalFrameView::SetLifecycleUpdatesThrottledForTesting(bool throttled) { - lifecycle_updates_throttled_ = throttled; +void LocalFrameView::SetLifecycleUpdatesThrottledForTesting() { + if (lifecycle_updates_throttled_) + return; + + lifecycle_updates_throttled_ = true; + // In real world we never set lifecycle_updates_throttled_ to true after + // StartLifecycleUpdates(). For testing, we need to schedule updates for the + // change. + ScheduleAnimation(); + // We may record fewer pre-composited layers under the frame. + if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + SetPaintArtifactCompositorNeedsUpdate(); } void LocalFrameView::InvalidateRect(const IntRect& rect) { @@ -1525,6 +1535,9 @@ if (!RuntimeEnabledFeatures::CompositedSelectionUpdateEnabled()) return; + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + return; + TRACE_EVENT0("blink", "LocalFrameView::updateCompositedSelectionIfNeeded"); Page* page = GetFrame().GetPage(); @@ -4556,6 +4569,8 @@ if (GetFrame().GetDocument()->IsInitialEmptyDocument()) return; lifecycle_updates_throttled_ = false; + RenderThrottlingStatusChanged(); + // TODO(wangxianzhu): The following call seems unnecessary. if (auto* owner = GetLayoutEmbeddedContent()) owner->SetShouldCheckForPaintInvalidation(); @@ -4567,9 +4582,6 @@ kMarkOnlyThis); } - ScheduleAnimation(); - SetIntersectionObservationState(kRequired); - // Non-main-frame lifecycle and commit deferral are controlled by their // main frame. if (!GetFrame().IsMainFrame())
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.h b/third_party/blink/renderer/core/frame/local_frame_view.h index 299ff19..cecd7699 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.h +++ b/third_party/blink/renderer/core/frame/local_frame_view.h
@@ -167,7 +167,7 @@ void UpdateLayout(); bool DidFirstLayout() const; bool LifecycleUpdatesActive() const; - void SetLifecycleUpdatesThrottledForTesting(bool throttled = true); + void SetLifecycleUpdatesThrottledForTesting(); void ScheduleRelayout(); void ScheduleRelayoutOfSubtree(LayoutObject*); bool LayoutPending() const; @@ -624,21 +624,6 @@ void BeginLifecycleUpdates(); - // Records a timestamp in PaintTiming when the frame is first not - // render-throttled (since it last was throttled if applicable). - void MarkFirstEligibleToPaint(); - - // Resets the optional timestamp in PaintTiming to null to indicate - // that the frame is now render-throttled, unless the frame already has - // a first contentful paint. This is a necessary workaround, as when - // constructing the frame, HTMLConstructionSite::InsertHTMLBodyElement - // initiates a call via Document::WillInsertBody to begin lifecycle - // updates, and hence |lifecycle_updates_throttled_| is set to false, which - // can cause the frame to be briefly unthrottled and receive a paint - // eligibility timestamp, even if the frame is throttled shortly thereafter - // and not actually painted. - void MarkIneligibleToPaint(); - // Shorthands of LayoutView's corresponding methods. void SetNeedsPaintPropertyUpdate(); @@ -993,6 +978,21 @@ // StyleEngine instead of the base background color. bool ShouldUseColorAdjustBackground() const; + // Records a timestamp in PaintTiming when the frame is first not + // render-throttled (since it last was throttled if applicable). + void MarkFirstEligibleToPaint(); + + // Resets the optional timestamp in PaintTiming to null to indicate + // that the frame is now render-throttled, unless the frame already has + // a first contentful paint. This is a necessary workaround, as when + // constructing the frame, HTMLConstructionSite::InsertHTMLBodyElement + // initiates a call via Document::WillInsertBody to begin lifecycle + // updates, and hence |lifecycle_updates_throttled_| is set to false, which + // can cause the frame to be briefly unthrottled and receive a paint + // eligibility timestamp, even if the frame is throttled shortly thereafter + // and not actually painted. + void MarkIneligibleToPaint(); + LayoutSize size_; typedef HashSet<scoped_refptr<LayoutEmbeddedObject>> EmbeddedObjectSet;
diff --git a/third_party/blink/renderer/core/frame/local_frame_view_test.cc b/third_party/blink/renderer/core/frame/local_frame_view_test.cc index f4d780e..0a66941 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view_test.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view_test.cc
@@ -414,24 +414,20 @@ // Mainframes are unthrottled by default. EXPECT_FALSE(GetDocument().View()->ShouldThrottleRenderingForTest()); EXPECT_FALSE(parent_timing.FirstEligibleToPaint().is_null()); - - GetDocument().View()->MarkFirstEligibleToPaint(); - EXPECT_FALSE(parent_timing.FirstEligibleToPaint().is_null()); - // Subframes are throttled when first loaded. EXPECT_TRUE(ChildDocument().View()->ShouldThrottleRenderingForTest()); - // Toggle paint elgibility to true. + // Unthrottling the subframe should enable paint eligibility. ChildDocument().OverrideIsInitialEmptyDocument(); ChildDocument().View()->BeginLifecycleUpdates(); - ChildDocument().View()->MarkFirstEligibleToPaint(); EXPECT_FALSE(ChildDocument().View()->ShouldThrottleRenderingForTest()); + UpdateAllLifecyclePhasesForTest(); EXPECT_FALSE(child_timing.FirstEligibleToPaint().is_null()); - // Toggle paint elgibility to false. - ChildDocument().View()->SetLifecycleUpdatesThrottledForTesting(true); - ChildDocument().View()->MarkIneligibleToPaint(); + // Throttling the subframe should disable paint eligibility. + ChildDocument().View()->SetLifecycleUpdatesThrottledForTesting(); EXPECT_TRUE(ChildDocument().View()->ShouldThrottleRenderingForTest()); + UpdateAllLifecyclePhasesForTest(); EXPECT_TRUE(child_timing.FirstEligibleToPaint().is_null()); }
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index eab0ecf..7a11478 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -1985,7 +1985,20 @@ previous_sibling_frame, insert_type, GetFrameToken(), window_agent_factory, interface_registry_, std::move(policy_container))); frame_->Tree().SetName(name); - frame_->Loader().ForceSandboxFlags(sandbox_flags); + + // See sandbox inheritance: content/browser/renderer_host/sandbox_flags.md + // + // New documents are either: + // 1. The initial empty document: + // a. In a new iframe. + // b. In a new popup. + // 2. A document replacing the previous, one via a navigation. + // + // This is about 1.b. This is used to define sandbox flags for the initial + // empty document in a new popup. + if (frame_->IsMainFrame()) + frame_->SetOpenerSandboxFlags(sandbox_flags); + Frame* opener_frame = opener ? ToCoreFrame(*opener) : nullptr; // We must call init() after frame_ is assigned because it is referenced
diff --git a/third_party/blink/renderer/core/html/link_web_bundle.cc b/third_party/blink/renderer/core/html/link_web_bundle.cc index 18f3b30f..cfd0125 100644 --- a/third_party/blink/renderer/core/html/link_web_bundle.cc +++ b/third_party/blink/renderer/core/html/link_web_bundle.cc
@@ -211,6 +211,8 @@ return false; if (!owner_ || !owner_->ValidResourceUrls().Contains(url)) return false; + if (url.Protocol() == "urn") + return true; DCHECK(bundle_loader_); if (!bundle_loader_->GetSecurityOrigin()->IsSameOriginWith( SecurityOrigin::Create(url).get())) { @@ -255,10 +257,10 @@ !url.Pass().IsEmpty()) return KURL(); - // For now, we allow only http: and https: schemes in Web Bundle URLs. + // For now, we allow only http:, https: and urn: schemes in Web Bundle URLs. // TODO(crbug.com/966753): Revisit this once // https://github.com/WICG/webpackage/issues/468 is resolved. - if (!url.ProtocolIsInHTTPFamily()) + if (!url.ProtocolIsInHTTPFamily() && !url.ProtocolIs("urn")) return KURL(); return url;
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index b98dd210..44af3840 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -1684,7 +1684,8 @@ if (!current_stack_trace) { GetFrontend()->webTransportCreated( IdentifiersFactory::SubresourceRequestId(transport_id), - UrlWithoutFragment(request_url).GetString()); + UrlWithoutFragment(request_url).GetString(), + base::TimeTicks::Now().since_origin().InSecondsF()); return; } @@ -1695,12 +1696,15 @@ initiator_object->setStack(std::move(current_stack_trace)); GetFrontend()->webTransportCreated( IdentifiersFactory::SubresourceRequestId(transport_id), - UrlWithoutFragment(request_url).GetString(), std::move(initiator_object)); + UrlWithoutFragment(request_url).GetString(), + base::TimeTicks::Now().since_origin().InSecondsF(), + std::move(initiator_object)); } void InspectorNetworkAgent::WebTransportClosed(uint64_t transport_id) { GetFrontend()->webTransportClosed( - IdentifiersFactory::SubresourceRequestId(transport_id)); + IdentifiersFactory::SubresourceRequestId(transport_id), + base::TimeTicks::Now().since_origin().InSecondsF()); } Response InspectorNetworkAgent::enable(Maybe<int> total_buffer_size,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc index b57ee3c..e40f668 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -642,10 +642,6 @@ allow_discard_start_margin = true; } while (column_break_token); - // TODO(mstensho): Nested column balancing. - if (container_builder_.DidBreakSelf()) - break; - if (!balance_columns) { if (result->ColumnSpanner()) { // We always have to balance columns preceding a spanner, so if we @@ -688,23 +684,22 @@ if (actual_column_count <= forced_break_count + 1) break; - // TODO(mstensho): Handle this situation also when we're inside another - // balanced multicol container, rather than bailing (which we do now, to - // avoid infinite loops). If we exhaust the inner column-count in such - // cases, that piece of information may have to be propagated to the outer - // multicol, and instead stretch there (not here). We have no such mechanism - // in place yet. - if (ConstraintSpace().IsInsideBalancedColumns()) - break; - LayoutUnit new_column_block_size = StretchColumnBlockSize(minimal_space_shortage, column_size.block_size); // Give up if we cannot get taller columns. The multicol container may have // a specified block-size preventing taller columns, for instance. DCHECK_GE(new_column_block_size, column_size.block_size); - if (new_column_block_size <= column_size.block_size) + if (new_column_block_size <= column_size.block_size) { + if (ConstraintSpace().IsInsideBalancedColumns()) { + // If we're doing nested column balancing, propagate any space shortage + // to the outer multicol container, so that the outer multicol container + // can attempt to stretch, so that this inner one may fit as well. + if (!container_builder_.IsInitialColumnBalancingPass()) + container_builder_.PropagateSpaceShortage(minimal_space_shortage); + } break; + } // Remove column fragments and re-attempt layout with taller columns. new_columns.clear();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc index 07fb7588..c87efc2 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
@@ -639,38 +639,20 @@ builder->SetBreakAppeal(appeal_inside); return true; } - } else { - bool need_break; - if (refuse_break_before) { - need_break = false; - } else if (child.IsMonolithic()) { - // If the monolithic piece of content (e.g. a line, or block-level - // replaced content) doesn't fit, we need a break. - need_break = fragment.BlockSize() > space_left; - } else { - // If the block-offset is past the fragmentainer boundary (or exactly at - // the boundary), no part of the fragment is going to fit in the current - // fragmentainer. Fragments may be pushed past the fragmentainer boundary - // by margins. We shouldn't break before a zero-size block that's exactly - // at a fragmentainer boundary, though. - need_break = space_left < LayoutUnit() || - (space_left == LayoutUnit() && fragment.BlockSize()); + } else if (refuse_break_before || fragment.BlockSize() <= space_left) { + // The child either fits, or we are not allowed to break. So we can move + // past this breakpoint. + if (child.IsBlock() && builder) { + // We're tentatively not going to break before or inside this child, but + // we'll check the appeal of breaking there anyway. It may be the best + // breakpoint we'll ever find. (Note that we only do this for block + // children, since, when it comes to inline layout, we first need to lay + // out all the line boxes, so that we know what do to in order to honor + // orphans and widows, if at all possible.) + UpdateEarlyBreakAtBlockChild(space, To<NGBlockNode>(child), layout_result, + appeal_before, builder); } - - if (!need_break) { - if (child.IsBlock() && builder) { - // If this doesn't happen, though, we're tentatively not going to break - // before or inside this child, but we'll check the appeal of breaking - // there anyway. It may be the best breakpoint we'll ever find. (Note - // that we only do this for block children, since, when it comes to - // inline layout, we first need to lay out all the line boxes, so that - // we know what do to in order to honor orphans and widows, if at all - // possible.) - UpdateEarlyBreakAtBlockChild(space, To<NGBlockNode>(child), - layout_result, appeal_before, builder); - } - return true; - } + return true; } // We don't want to break inside, so we should attempt to break before.
diff --git a/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc b/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc index c6d76a50..40f6c2ab 100644 --- a/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc +++ b/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc
@@ -129,16 +129,6 @@ ts << " [" << name << "=\"" << value << "\"]"; } -static void WriteQuotedSVGResource(WTF::TextStream& ts, - const char* name, - const StyleSVGResource* value, - TreeScope& tree_scope) { - DCHECK(value); - AtomicString id = SVGURIReference::FragmentIdentifierFromIRIString( - value->Url(), tree_scope); - WriteNameAndQuotedValue(ts, name, id); -} - template <typename ValueType> static void WriteIfNotDefault(WTF::TextStream& ts, const char* name, @@ -711,6 +701,22 @@ WriteResources(ts, shape, indent); } +static void WriteSVGResourceReferencePrefix( + WTF::TextStream& ts, + const char* resource_name, + const LayoutSVGResourceContainer* resource_object, + const AtomicString& url, + const TreeScope& tree_scope, + int indent) { + AtomicString id = + SVGURIReference::FragmentIdentifierFromIRIString(url, tree_scope); + WriteIndent(ts, indent); + ts << " "; + WriteNameAndQuotedValue(ts, resource_name, id); + ts << " "; + WriteStandardPrefix(ts, *resource_object, 0); +} + void WriteResources(WTF::TextStream& ts, const LayoutObject& object, int indent) { @@ -722,12 +728,9 @@ const ComputedStyle& style = object.StyleRef(); TreeScope& tree_scope = object.GetDocument(); if (LayoutSVGResourceMasker* masker = resources->Masker()) { - WriteIndent(ts, indent); - ts << " "; - WriteQuotedSVGResource(ts, "masker", style.SvgStyle().MaskerResource(), - tree_scope); - ts << " "; - WriteStandardPrefix(ts, *masker, 0); + WriteSVGResourceReferencePrefix(ts, "masker", masker, + style.SvgStyle().MaskerResource()->Url(), + tree_scope, indent); ts << " " << masker->ResourceBoundingBox(reference_box, 1) << "\n"; } if (LayoutSVGResourceClipper* clipper = resources->Clipper()) { @@ -735,13 +738,8 @@ DCHECK_EQ(style.ClipPath()->GetType(), ClipPathOperation::REFERENCE); const ReferenceClipPathOperation& clip_path_reference = To<ReferenceClipPathOperation>(*style.ClipPath()); - AtomicString id = SVGURIReference::FragmentIdentifierFromIRIString( - clip_path_reference.Url(), tree_scope); - WriteIndent(ts, indent); - ts << " "; - WriteNameAndQuotedValue(ts, "clipPath", id); - ts << " "; - WriteStandardPrefix(ts, *clipper, 0); + WriteSVGResourceReferencePrefix( + ts, "clipPath", clipper, clip_path_reference.Url(), tree_scope, indent); ts << " " << clipper->ResourceBoundingBox(reference_box) << "\n"; } if (LayoutSVGResourceFilter* filter = GetFilterResourceForSVG(style)) { @@ -751,13 +749,9 @@ DCHECK_EQ(filter_operation.GetType(), FilterOperation::REFERENCE); const auto& reference_filter_operation = To<ReferenceFilterOperation>(filter_operation); - AtomicString id = SVGURIReference::FragmentIdentifierFromIRIString( - reference_filter_operation.Url(), tree_scope); - WriteIndent(ts, indent); - ts << " "; - WriteNameAndQuotedValue(ts, "filter", id); - ts << " "; - WriteStandardPrefix(ts, *filter, 0); + WriteSVGResourceReferencePrefix(ts, "filter", filter, + reference_filter_operation.Url(), + tree_scope, indent); ts << " " << filter->ResourceBoundingBox(reference_box) << "\n"; } }
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index 7d5e731..6ff7e612 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -1441,9 +1441,15 @@ } network::mojom::blink::WebSandboxFlags DocumentLoader::CalculateSandboxFlags() { - auto sandbox_flags = GetFrameLoader().GetForcedSandboxFlags() | - content_security_policy_->GetSandboxMask() | - frame_policy_.sandbox_flags; + // The snapshot of the FramePolicy taken, when the navigation started. This + // contains the sandbox of the parent/opener and also the sandbox of the + // iframe element owning this new document. + auto sandbox_flags = frame_policy_.sandbox_flags; + + // The new document's response can further restrict sandbox using the + // Content-Security-Policy: sandbox directive: + sandbox_flags |= content_security_policy_->GetSandboxMask(); + if (archive_) { // The URL of a Document loaded from a MHTML archive is controlled by // the Content-Location header. This would allow UXSS, since
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index 5781624..eb98cad 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -118,8 +118,10 @@ const SkBitmap& drag_image, const gfx::Point& drag_image_offset) override {} bool AcceptsLoadDrops() const override { return true; } - bool ShouldReportDetailedMessageForSource(LocalFrame&, - const String&) override { + bool ShouldReportDetailedMessageForSourceAndSeverity( + LocalFrame&, + mojom::blink::ConsoleMessageLevel, + const String&) override { return false; } void AddMessageToConsole(LocalFrame*,
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index ab66bd3..b1c40377 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -216,14 +216,6 @@ FrameLoader::FrameLoader(LocalFrame* frame) : frame_(frame), progress_tracker_(MakeGarbageCollected<ProgressTracker>(frame)), - // Frames need to inherit the sandbox flags of their parent frame. - // These can be fixed at construction time, because the only actions that - // trigger a sandbox flags change in the parent will necessarily detach - // this frame. - forced_sandbox_flags_( - frame_->Tree().Parent() - ? frame_->Tree().Parent()->GetSecurityContext()->GetSandboxFlags() - : network::mojom::blink::WebSandboxFlags::kNone), dispatching_did_clear_window_object_in_main_world_(false), virtual_time_pauser_( frame_->GetFrameScheduler()->CreateWebScopedVirtualTimePauser( @@ -249,10 +241,13 @@ void FrameLoader::Init() { ScriptForbiddenScope forbid_scripts; + // Load the initial empty document: auto navigation_params = std::make_unique<WebNavigationParams>(); navigation_params->url = KURL(g_empty_string); navigation_params->frame_policy = frame_->Owner() ? frame_->Owner()->GetFramePolicy() : FramePolicy(); + navigation_params->frame_policy->sandbox_flags = + PendingEffectiveSandboxFlags(); DocumentLoader* new_document_loader = Client()->CreateDocumentLoader( frame_, kWebNavigationTypeOther, CreateCSPForInitialEmptyDocument(), @@ -1552,11 +1547,6 @@ // The frame might be detached at this point. } -void FrameLoader::ForceSandboxFlags( - network::mojom::blink::WebSandboxFlags flags) { - forced_sandbox_flags_ |= flags; -} - void FrameLoader::DispatchDidClearDocumentOfWindowObject() { if (state_ == State::kUninitialized) return; @@ -1593,10 +1583,12 @@ network::mojom::blink::WebSandboxFlags FrameLoader::PendingEffectiveSandboxFlags() const { - network::mojom::blink::WebSandboxFlags flags = forced_sandbox_flags_; - if (FrameOwner* frame_owner = frame_->Owner()) - flags |= frame_owner->GetFramePolicy().sandbox_flags; - return flags; + if (Frame* parent = frame_->Tree().Parent()) { + return parent->GetSecurityContext()->GetSandboxFlags() | + frame_->Owner()->GetFramePolicy().sandbox_flags; + } else { + return frame_->OpenerSandboxFlags(); + } } void FrameLoader::ModifyRequestForCSP(
diff --git a/third_party/blink/renderer/core/loader/frame_loader.h b/third_party/blink/renderer/core/loader/frame_loader.h index 9b5291f..ee969d3 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.h +++ b/third_party/blink/renderer/core/loader/frame_loader.h
@@ -145,16 +145,11 @@ void DispatchDocumentElementAvailable(); void RunScriptsAtDocumentElementAvailable(); - // The following sandbox flags will be forced, regardless of changes to the - // sandbox attribute of any parent frames. - void ForceSandboxFlags(network::mojom::blink::WebSandboxFlags flags); - - network::mojom::blink::WebSandboxFlags GetForcedSandboxFlags() const { - return forced_sandbox_flags_; - } - - // Includes the collection of forced, inherited, and FrameOwner's sandbox - // flags. + // See content/browser/renderer_host/sandbox_flags.md + // This contains the sandbox flags to commit for new documents. + // - For main documents, it contains the sandbox inherited from the opener. + // - For nested documents, it contains the sandbox flags inherited from the + // parent and the one defined in the <iframe>'s sandbox attribute. network::mojom::blink::WebSandboxFlags PendingEffectiveSandboxFlags() const; // Modifying itself is done based on |fetch_client_settings_object|. @@ -298,8 +293,6 @@ }; std::unique_ptr<ClientNavigationState> client_navigation_; - network::mojom::blink::WebSandboxFlags forced_sandbox_flags_; - // The state is set to kInitialized when Init() completes, and kDetached // during teardown in Detach(). enum class State { kUninitialized, kInitialized, kDetached };
diff --git a/third_party/blink/renderer/core/page/chrome_client.h b/third_party/blink/renderer/core/page/chrome_client.h index e3b0814..01012f8 100644 --- a/third_party/blink/renderer/core/page/chrome_client.h +++ b/third_party/blink/renderer/core/page/chrome_client.h
@@ -263,8 +263,10 @@ virtual void SetOverscrollBehavior(LocalFrame& main_frame, const cc::OverscrollBehavior&) = 0; - virtual bool ShouldReportDetailedMessageForSource(LocalFrame&, - const String& source) = 0; + virtual bool ShouldReportDetailedMessageForSourceAndSeverity( + LocalFrame&, + mojom::blink::ConsoleMessageLevel log_level, + const String& source) = 0; virtual void AddMessageToConsole(LocalFrame*, mojom::ConsoleMessageSource, mojom::ConsoleMessageLevel,
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.cc b/third_party/blink/renderer/core/page/chrome_client_impl.cc index b98a5aa6..14f694c9 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.cc +++ b/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -311,13 +311,15 @@ user_gesture); } -bool ChromeClientImpl::ShouldReportDetailedMessageForSource( +bool ChromeClientImpl::ShouldReportDetailedMessageForSourceAndSeverity( LocalFrame& local_frame, + mojom::blink::ConsoleMessageLevel log_level, const String& url) { WebLocalFrameImpl* webframe = WebLocalFrameImpl::FromFrame(local_frame.LocalFrameRoot()); return webframe && webframe->Client() && - webframe->Client()->ShouldReportDetailedMessageForSource(url); + webframe->Client()->ShouldReportDetailedMessageForSourceAndSeverity( + log_level, url); } void ChromeClientImpl::AddMessageToConsole(LocalFrame* local_frame,
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.h b/third_party/blink/renderer/core/page/chrome_client_impl.h index b510904..dcc67df 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.h +++ b/third_party/blink/renderer/core/page/chrome_client_impl.h
@@ -107,8 +107,10 @@ ScrollGranularity granularity, CompositorElementId scrollable_area_element_id, WebInputEvent::Type injected_type) override; - bool ShouldReportDetailedMessageForSource(LocalFrame&, - const String&) override; + bool ShouldReportDetailedMessageForSourceAndSeverity( + LocalFrame&, + mojom::blink::ConsoleMessageLevel log_level, + const String&) override; void AddMessageToConsole(LocalFrame*, mojom::ConsoleMessageSource, mojom::ConsoleMessageLevel,
diff --git a/third_party/blink/renderer/core/page/page.cc b/third_party/blink/renderer/core/page/page.cc index dce0028..86c0ff8a 100644 --- a/third_party/blink/renderer/core/page/page.cc +++ b/third_party/blink/renderer/core/page/page.cc
@@ -955,7 +955,15 @@ void Page::WillBeDestroyed() { Frame* main_frame = main_frame_; - main_frame->Detach(FrameDetachType::kRemove); + // TODO(https://crbug.com/838348): Sadly, there are situations where Blink may + // attempt to detach a main frame twice due to a bug. That rewinds + // FrameLifecycle from kDetached to kDetaching, but GetPage() will already be + // null. Since Detach() has already happened, just skip the actual Detach() + // call to try to limit the side effects of this bug on the rest of frame + // detach. + if (main_frame->GetPage()) { + main_frame->Detach(FrameDetachType::kRemove); + } DCHECK(AllPages().Contains(this)); AllPages().erase(this);
diff --git a/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc b/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc index 6524611d..9fef5ab1 100644 --- a/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/scrolling_test.cc
@@ -668,7 +668,8 @@ TEST_P(ScrollingTest, touchActionEditableElement) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures({::features::kSwipeToMoveCursor}, {}); - ASSERT_TRUE(base::FeatureList::IsEnabled(::features::kSwipeToMoveCursor)); + if (!::features::IsSwipeToMoveCursorEnabled()) + return; // Long text that will overflow in y-direction. LoadHTML(R"HTML( <style>
diff --git a/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc index e965574..c488115 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h" +#include "cc/input/layer_selection_bound.h" #include "third_party/blink/renderer/core/editing/editor.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/editing/markers/composition_marker.h" @@ -151,10 +152,18 @@ const NGInlineCursor& cursor) { return cursor.Current() .GetLayoutObject() + ->GetFrame() + ->Selection() + .ComputeLayoutSelectionStatus(cursor); +} + +SelectionState ComputeSelectionState(const NGInlineCursor& cursor) { + return cursor.Current() + .GetLayoutObject() ->GetDocument() .GetFrame() ->Selection() - .ComputeLayoutSelectionStatus(cursor); + .ComputeLayoutSelectionStateForCursor(cursor.Current()); } // TODO(yosin): Remove |ComputeLocalRect| once the transition to @@ -363,20 +372,21 @@ public: explicit SelectionPaintState(const NGInlineCursor& containing_block) : selection_status_(ComputeLayoutSelectionStatus(containing_block)), + state_(ComputeSelectionState(containing_block)), containing_block_(containing_block) {} const LayoutSelectionStatus& Status() const { return selection_status_; } const TextPaintStyle& GetSelectionStyle() const { return selection_style_; } + SelectionState State() const { return state_; } + bool ShouldPaintSelectedTextOnly() const { return paint_selected_text_only_; } bool ShouldPaintSelectedTextSeparately() const { return paint_selected_text_separately_; } - bool IsSelectionRectComputed() const { return selection_rect_.has_value(); } - void ComputeSelectionStyle(const Document& document, const ComputedStyle& style, Node* node, @@ -391,10 +401,11 @@ } PhysicalRect ComputeSelectionRect(const PhysicalOffset& box_offset) { - DCHECK(!selection_rect_); - selection_rect_ = - ComputeLocalSelectionRectForText(containing_block_, selection_status_); - selection_rect_->offset += box_offset; + if (!selection_rect_) { + selection_rect_ = ComputeLocalSelectionRectForText(containing_block_, + selection_status_); + selection_rect_->offset += box_offset; + } return *selection_rect_; } @@ -445,14 +456,85 @@ } private: - LayoutSelectionStatus selection_status_; + const LayoutSelectionStatus selection_status_; TextPaintStyle selection_style_; + const SelectionState state_; base::Optional<PhysicalRect> selection_rect_; const NGInlineCursor& containing_block_; bool paint_selected_text_only_; bool paint_selected_text_separately_; }; +template <typename Cursor> +class SelectionBoundsRecorder { + STACK_ALLOCATED(); + + public: + SelectionBoundsRecorder(const Cursor& cursor, + SelectionPaintState& selection, + PaintController& paint_controller, + const PhysicalOffset& box_rect_offset) + : cursor_(cursor), + selection_(selection), + paint_controller_(paint_controller), + box_rect_offset_(box_rect_offset) {} + + ~SelectionBoundsRecorder(); + + private: + const Cursor& cursor_; + SelectionPaintState& selection_; + PaintController& paint_controller_; + const PhysicalOffset& box_rect_offset_; +}; + +template <> +SelectionBoundsRecorder<NGInlineCursor>::~SelectionBoundsRecorder() { + DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled()); + + const FrameSelection& frame_selection = + cursor_.Current().GetLayoutObject()->GetFrame()->Selection(); + if (!frame_selection.IsHandleVisible() || frame_selection.IsHidden()) + return; + + SelectionState state = selection_.State(); + if (state == SelectionState::kInside || state == SelectionState::kNone) + return; + + // TODO(crbug.com/1065049) Handle RTL (i.e. IsTextDirectionRTL) to adjust + // the type and edges appropriately (i.e. the right edge of the selection rect + // should be used for start's edges). + base::Optional<PaintedSelectionBound> start; + base::Optional<PaintedSelectionBound> end; + auto selection_rect = + PixelSnappedIntRect(selection_.ComputeSelectionRect(box_rect_offset_)); + if (state == SelectionState::kStart || + state == SelectionState::kStartAndEnd) { + start.emplace(); + start->type = gfx::SelectionBound::Type::LEFT; + start->edge_start = selection_rect.MinXMinYCorner(); + start->edge_end = selection_rect.MinXMaxYCorner(); + // TODO(crbug.com/1065049) Handle the case where selection within input + // text is clipped out. + start->hidden = false; + } + + if (state == SelectionState::kStartAndEnd || state == SelectionState::kEnd) { + end.emplace(); + end->type = gfx::SelectionBound::Type::RIGHT; + end->edge_start = selection_rect.MaxXMinYCorner(); + end->edge_end = selection_rect.MaxXMaxYCorner(); + end->hidden = false; + } + + paint_controller_.RecordSelection(start, end); +} + +template <> +SelectionBoundsRecorder<NGTextPainterCursor>::~SelectionBoundsRecorder() { + NOTREACHED(); +} + // Check if text-emphasis and ruby annotation text are on different sides. // See InlineTextBox::GetEmphasisMarkPosition(). // @@ -563,12 +645,26 @@ // only in BoxPainterBase::PaintFillLayer, which is already within a // DrawingRecorder. base::Optional<DrawingRecorder> recorder; + const auto& display_item_client = + AsDisplayItemClient(cursor_, selection.has_value()); + + // Ensure the selection bounds are recorded on the paint chunk regardless of + // whether the diplay item that contains the actual selection painting is + // reused. + base::Optional<SelectionBoundsRecorder<Cursor>> selection_recorder; + if (UNLIKELY(RuntimeEnabledFeatures::CompositeAfterPaintEnabled() && + selection && paint_info.phase == PaintPhase::kForeground && + !is_printing)) { + selection_recorder.emplace(cursor_, *selection, + paint_info.context.GetPaintController(), + box_rect.offset); + } + if (paint_info.phase != PaintPhase::kTextClip) { - const auto& display_item_client = - AsDisplayItemClient(cursor_, selection.has_value()); if (DrawingRecorder::UseCachedDrawingIfPossible( - paint_info.context, display_item_client, paint_info.phase)) + paint_info.context, display_item_client, paint_info.phase)) { return; + } recorder.emplace(paint_info.context, display_item_client, paint_info.phase, visual_rect); } @@ -707,8 +803,7 @@ if (UNLIKELY(selection && (selection->ShouldPaintSelectedTextOnly() || selection->ShouldPaintSelectedTextSeparately()))) { // Paint only the text that is selected. - if (!selection->IsSelectionRectComputed()) - selection->ComputeSelectionRect(box_rect.offset); + selection->ComputeSelectionRect(box_rect.offset); if (rotation) selection->MapSelectionRectIntoRotatedSpace(*rotation); selection->PaintSelectedText(text_painter, length, text_style, node_id);
diff --git a/third_party/blink/renderer/core/scheduler_integration_tests/frame_throttling_test.cc b/third_party/blink/renderer/core/scheduler_integration_tests/frame_throttling_test.cc index 0123339d..73b6d681 100644 --- a/third_party/blink/renderer/core/scheduler_integration_tests/frame_throttling_test.cc +++ b/third_party/blink/renderer/core/scheduler_integration_tests/frame_throttling_test.cc
@@ -298,8 +298,7 @@ auto* root_frame = LocalFrameRoot().GetFrame(); auto* root_frame_view = root_frame->View(); root_frame_view->SetNeedsLayout(); - root_frame_view->ScheduleAnimation(); - root_frame_view->SetLifecycleUpdatesThrottledForTesting(true); + root_frame_view->SetLifecycleUpdatesThrottledForTesting(); ASSERT_TRUE(root_frame->IsLocalRoot()); ASSERT_TRUE(root_frame_view->ShouldThrottleRenderingForTest()); @@ -1681,6 +1680,41 @@ GetDocument().View()->RootCcLayer()->children().size()); } +TEST_P(FrameThrottlingTest, GraphicsLayerCollectionLifecycleThrottling) { + // GraphicsLayers are not created with CompositeAfterPaint. + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + return; + + SimRequest main_resource("https://example.com/", "text/html"); + SimRequest frame_resource("https://example.com/iframe.html", "text/html"); + + LoadURL("https://example.com/"); + // The frame is initially throttled. + main_resource.Complete( + "<iframe id='frame' sandbox src='iframe.html'></iframe>"); + frame_resource.Complete( + "<div id='div' style='will-change: transform'>Foo</div>"); + + CompositeFrame(); + auto layer_count = GetDocument().View()->RootCcLayer()->children().size(); + auto* frame_element = + To<HTMLIFrameElement>(GetDocument().getElementById("frame")); + auto* frame_document = frame_element->contentDocument(); + frame_document->View()->SetLifecycleUpdatesThrottledForTesting(); + + CompositeFrame(); + // We no longer collect the graphics layers of the iframe and the composited + // content. + EXPECT_GT(layer_count, + GetDocument().View()->RootCcLayer()->children().size()); + + frame_document->View()->BeginLifecycleUpdates(); + CompositeFrame(); + // Now we should collect all graphics layers again. + EXPECT_EQ(layer_count, + GetDocument().View()->RootCcLayer()->children().size()); +} + TEST_P(FrameThrottlingTest, NestedFramesInRemoteFrameHiddenAndShown) { InitializeRemote(); @@ -1775,8 +1809,7 @@ auto* frame_element = To<HTMLIFrameElement>(GetDocument().getElementById("frame")); auto* frame_document = frame_element->contentDocument(); - frame_document->View()->SetLifecycleUpdatesThrottledForTesting(true); - GetDocument().View()->ScheduleAnimation(); + frame_document->View()->SetLifecycleUpdatesThrottledForTesting(); EXPECT_TRUE(frame_document->View()->ShouldThrottleRenderingForTest()); commands = CompositeFrame();
diff --git a/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc b/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc index 3826889..bc2a919 100644 --- a/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc +++ b/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc
@@ -316,10 +316,10 @@ // stream.[[reader]].[[forAuthorCode]]). ReadableStreamGenericReader* reader = stream->reader_; return StreamPromiseResolver::CreateResolved( - script_state, ReadableStream::CreateReadResult( - script_state, chunk, false, - static_cast<ReadableStreamDefaultReader*>(reader) - ->for_author_code_)); + script_state, + ReadableStream::CreateReadResult( + script_state, chunk, false, + To<ReadableStreamDefaultReader>(reader)->for_author_code_)); } // 3. Let pendingPromise be ! ReadableStreamAddReadRequest(stream).
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc index da29529..b21e05d 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc
@@ -18,7 +18,9 @@ TrustedTypePolicy::TrustedTypePolicy(const String& policy_name, TrustedTypePolicyOptions* policy_options) - : name_(policy_name), policy_options_(policy_options) {} + : name_(policy_name), policy_options_(policy_options) { + DCHECK(policy_options_); +} TrustedHTML* TrustedTypePolicy::createHTML(ScriptState* script_state, const String& input,
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc index 582a14d0..638295dc 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc
@@ -28,6 +28,14 @@ TrustedTypePolicy* TrustedTypePolicyFactory::createPolicy( const String& policy_name, + ExceptionState& exception_state) { + return createPolicy(policy_name, + MakeGarbageCollected<TrustedTypePolicyOptions>(), + exception_state); +} + +TrustedTypePolicy* TrustedTypePolicyFactory::createPolicy( + const String& policy_name, const TrustedTypePolicyOptions* policy_options, ExceptionState& exception_state) { if (RuntimeEnabledFeatures::TrustedTypeBeforePolicyCreationEventEnabled()) {
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h index 82cd9c256..22aa22542 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h
@@ -31,6 +31,7 @@ explicit TrustedTypePolicyFactory(ExecutionContext*); // TrustedTypePolicyFactory.idl + TrustedTypePolicy* createPolicy(const String&, ExceptionState&); TrustedTypePolicy* createPolicy(const String&, const TrustedTypePolicyOptions*, ExceptionState&);
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl index 7465e550..7de315d8 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl
@@ -8,7 +8,7 @@ Exposed=(Window, Worker), RuntimeEnabled=TrustedDOMTypes ] interface TrustedTypePolicyFactory : EventTarget { - [RaisesException] TrustedTypePolicy createPolicy(DOMString policyName, TrustedTypePolicyOptions policyOptions); + [RaisesException] TrustedTypePolicy createPolicy(DOMString policyName, optional TrustedTypePolicyOptions policyOptions); // All the policy object names that have been created [CallWith=ScriptState] boolean isHTML(any checkedObject); [CallWith=ScriptState] boolean isScript(any checkedObject);
diff --git a/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc b/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc index 09230fa..8f36750fe 100644 --- a/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc +++ b/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc
@@ -264,32 +264,6 @@ EXPECT_EQ(0U, ax_cell2->AriaRowIndex()); } -class SparseAttributeAdapter : public AXSparseAttributeClient { - STACK_ALLOCATED(); - - public: - SparseAttributeAdapter() = default; - ~SparseAttributeAdapter() = default; - - HeapHashMap<AXObjectAttribute, Member<AXObject>> object_attributes; - HeapHashMap<AXObjectVectorAttribute, Member<HeapVector<Member<AXObject>>>> - object_vector_attributes; - - private: - void AddObjectAttribute(AXObjectAttribute attribute, - AXObject& value) override { - ASSERT_TRUE(object_attributes.find(attribute) == object_attributes.end()); - object_attributes.insert(attribute, &value); - } - - void AddObjectVectorAttribute(AXObjectVectorAttribute attribute, - HeapVector<Member<AXObject>>* value) override { - ASSERT_TRUE(object_vector_attributes.find(attribute) == - object_vector_attributes.end()); - object_vector_attributes.insert(attribute, value); - } -}; - TEST_F(AccessibilityObjectModelTest, SparseAttributes) { SimRequest main_resource("https://example.com/", "text/html"); LoadURL("https://example.com/"); @@ -313,9 +287,6 @@ auto* cache = AXObjectCache(); ASSERT_NE(nullptr, cache); auto* ax_target = cache->GetOrCreate(target); - SparseAttributeAdapter sparse_attributes; - ax_target->GetSparseAXAttributes(sparse_attributes); - ui::AXNodeData node_data; ax_target->Serialize(&node_data, ui::kAXModeComplete); @@ -323,18 +294,20 @@ ax::mojom::blink::StringAttribute::kKeyShortcuts)); ASSERT_EQ("Widget", node_data.GetStringAttribute( ax::mojom::blink::StringAttribute::kRoleDescription)); + auto* active_descendant_target = + cache->ObjectFromAXID(node_data.GetIntAttribute( + ax::mojom::blink::IntAttribute::kActivedescendantId)); + ASSERT_NE(nullptr, active_descendant_target); ASSERT_EQ(ax::mojom::Role::kListBoxOption, - sparse_attributes.object_attributes - .at(AXObjectAttribute::kAriaActiveDescendant) - ->RoleValue()); - ASSERT_EQ(ax::mojom::Role::kContentInfo, - (*sparse_attributes.object_vector_attributes.at( - AXObjectVectorAttribute::kAriaDetails))[0] - ->RoleValue()); - ASSERT_EQ(ax::mojom::Role::kArticle, - sparse_attributes.object_attributes - .at(AXObjectAttribute::kAriaErrorMessage) - ->RoleValue()); + active_descendant_target->RoleValue()); + auto* aria_details_target = + cache->ObjectFromAXID(node_data.GetIntListAttribute( + ax::mojom::blink::IntListAttribute::kDetailsIds)[0]); + ASSERT_EQ(ax::mojom::Role::kContentInfo, aria_details_target->RoleValue()); + auto* error_message_target = cache->ObjectFromAXID(node_data.GetIntAttribute( + ax::mojom::blink::IntAttribute::kErrormessageId)); + ASSERT_NE(nullptr, error_message_target); + ASSERT_EQ(ax::mojom::Role::kArticle, error_message_target->RoleValue()); target->accessibleNode()->setKeyShortcuts("Ctrl+L"); target->accessibleNode()->setRoleDescription("Object"); @@ -348,25 +321,26 @@ target->accessibleNode()->setErrorMessage( GetDocument().getElementById("error2")->accessibleNode()); - SparseAttributeAdapter sparse_attributes2; - ax_target->GetSparseAXAttributes(sparse_attributes2); + ui::AXNodeData node_data2; + ax_target->Serialize(&node_data2, ui::kAXModeComplete); ASSERT_EQ("Ctrl+K", node_data.GetStringAttribute( ax::mojom::blink::StringAttribute::kKeyShortcuts)); ASSERT_EQ("Widget", node_data.GetStringAttribute( ax::mojom::blink::StringAttribute::kRoleDescription)); + auto* active_descendant_target2 = + cache->ObjectFromAXID(node_data2.GetIntAttribute( + ax::mojom::blink::IntAttribute::kActivedescendantId)); ASSERT_EQ(ax::mojom::Role::kListBoxOption, - sparse_attributes2.object_attributes - .at(AXObjectAttribute::kAriaActiveDescendant) - ->RoleValue()); - ASSERT_EQ(ax::mojom::Role::kContentInfo, - (*sparse_attributes2.object_vector_attributes.at( - AXObjectVectorAttribute::kAriaDetails))[0] - ->RoleValue()); - ASSERT_EQ(ax::mojom::Role::kArticle, - sparse_attributes2.object_attributes - .at(AXObjectAttribute::kAriaErrorMessage) - ->RoleValue()); + active_descendant_target2->RoleValue()); + auto* aria_details_target2 = + cache->ObjectFromAXID(node_data2.GetIntListAttribute( + ax::mojom::blink::IntListAttribute::kDetailsIds)[0]); + ASSERT_EQ(ax::mojom::Role::kContentInfo, aria_details_target2->RoleValue()); + auto* error_message_target2 = cache->ObjectFromAXID(node_data.GetIntAttribute( + ax::mojom::blink::IntAttribute::kErrormessageId)); + ASSERT_NE(nullptr, error_message_target2); + ASSERT_EQ(ax::mojom::Role::kArticle, error_message_target2->RoleValue()); } TEST_F(AccessibilityObjectModelTest, LabeledBy) {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index 061cd391..1e4c6b53 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -3080,6 +3080,14 @@ return AXObject::TextOffsetInFormattingContext(offset); } + // TODO(crbug.com/1149171): NGInlineOffsetMappingBuilder does not properly + // compute offset mappings for empty LayoutText objects. Other text objects + // (such as some list markers) are not affected. + if (const LayoutText* layout_text = DynamicTo<LayoutText>(layout_obj)) { + if (layout_text->GetText().IsEmpty()) + return AXObject::TextOffsetInFormattingContext(offset); + } + LayoutBlockFlow* formatting_context = NGOffsetMapping::GetInlineFormattingContextOf(*layout_obj); if (!formatting_context || formatting_context == layout_obj)
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 7a93697..fd6c8aa 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -734,47 +734,6 @@ return element->ExistingAccessibleNode(); } -void AXObject::GetSparseAXAttributes( - AXSparseAttributeClient& sparse_attribute_client) const { - AXSparseAttributeAOMPropertyClient property_client(*ax_object_cache_, - sparse_attribute_client); - AccessibleNode* accessible_node = GetAccessibleNode(); - - // Virtual nodes for AOM are still tied to the AXTree. - if (accessible_node && IsVirtualObject()) - accessible_node->GetAllAOMProperties(&property_client); - - Element* element = GetElement(); - if (!element) - return; - - AXSparseAttributeSetterMap& ax_sparse_attribute_setter_map = - GetSparseAttributeSetterMap(); - AttributeCollection attributes = element->AttributesWithoutUpdate(); - HashSet<QualifiedName> set_attributes; - for (const Attribute& attr : attributes) { - set_attributes.insert(attr.GetName()); - - AXSparseAttributeSetter* setter = - ax_sparse_attribute_setter_map.at(attr.GetName()); - if (setter) - setter->Run(*this, sparse_attribute_client, attr.Value()); - } - if (!element->DidAttachInternals()) - return; - const auto& internals_attributes = - element->EnsureElementInternals().GetAttributes(); - for (const QualifiedName& attr : internals_attributes.Keys()) { - if (set_attributes.Contains(attr)) - continue; - AXSparseAttributeSetter* setter = ax_sparse_attribute_setter_map.at(attr); - if (setter) { - setter->Run(*this, sparse_attribute_client, - internals_attributes.at(attr)); - } - } -} - void AXObject::Serialize(ui::AXNodeData* node_data, ui::AXMode accessibility_mode) { AccessibilityExpanded expanded = IsExpanded(); @@ -933,7 +892,7 @@ SerializeStyleAttributes(node_data); } - SerializePartialSparseAttributes(node_data); + SerializeSparseAttributes(node_data); if (Element* element = this->GetElement()) { if (const AtomicString& class_name = element->GetClassAttribute()) { @@ -1118,7 +1077,7 @@ } } -void AXObject::SerializePartialSparseAttributes(ui::AXNodeData* node_data) { +void AXObject::SerializeSparseAttributes(ui::AXNodeData* node_data) { if (IsVirtualObject()) { AccessibleNode* accessible_node = GetAccessibleNode(); if (accessible_node) { @@ -1132,7 +1091,7 @@ if (!element) return; - TempSetterMap& setter_map = GetTempSetterMap(); + AXSparseAttributeSetterMap& setter_map = GetAXSparseAttributeSetterMap(); AttributeCollection attributes = element->AttributesWithoutUpdate(); HashSet<QualifiedName> set_attributes; for (const Attribute& attr : attributes) {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index ec93198a..4b52e757 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -80,13 +80,6 @@ enum class AOMRelationProperty; enum class AOMRelationListProperty; -class AXSparseAttributeClient { - public: - virtual void AddObjectAttribute(AXObjectAttribute, AXObject&) = 0; - virtual void AddObjectVectorAttribute(AXObjectVectorAttribute, - HeapVector<Member<AXObject>>*) = 0; -}; - class IgnoredReason { DISALLOW_NEW(); @@ -395,8 +388,6 @@ void TokenVectorFromAttribute(Vector<String>&, const QualifiedName&) const; - void GetSparseAXAttributes(AXSparseAttributeClient&) const; - // Serialize the properties of this node into |node_data|. // // TODO(crbug.com/1068668): AX onion soup - finish migrating @@ -1322,9 +1313,8 @@ void UpdateCachedAttributeValuesIfNeeded() const; // Helpers for serialization. - // TODO(meredithl): Serialize all sparse/table attributes and rename. - void SerializePartialSparseAttributes(ui::AXNodeData* node_data); void SerializeStyleAttributes(ui::AXNodeData* node_data); + void SerializeSparseAttributes(ui::AXNodeData* node_data); void SerializeTableAttributes(ui::AXNodeData* node_data); private:
diff --git a/third_party/blink/renderer/modules/accessibility/ax_position.cc b/third_party/blink/renderer/modules/accessibility/ax_position.cc index 90dbe5c..17268a2b 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_position.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_position.cc
@@ -441,6 +441,14 @@ if (!is_atomic_inline_level && !layout_object->IsText()) return container_object_->ComputedName().length(); + // TODO(crbug.com/1149171): NGInlineOffsetMappingBuilder does not properly + // compute offset mappings for empty LayoutText objects. Other text objects + // (such as some list markers) are not affected. + if (const LayoutText* layout_text = DynamicTo<LayoutText>(layout_object)) { + if (layout_text->GetText().IsEmpty()) + return container_object_->ComputedName().length(); + } + LayoutBlockFlow* formatting_context = NGOffsetMapping::GetInlineFormattingContextOf(*layout_object); const NGOffsetMapping* container_offset_mapping =
diff --git a/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc b/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc index 1b159247..8ed095ac 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc
@@ -34,233 +34,126 @@ node_data->AddStringAttribute(attribute, value.Utf8()); } -class ObjectAttributeSetter : public AXSparseAttributeSetter { - public: - ObjectAttributeSetter(AXObjectAttribute attribute) : attribute_(attribute) {} +void SetObjectAttribute(ax::mojom::blink::IntAttribute attribute, + QualifiedName qualified_name, + AXObject* object, + ui::AXNodeData* node_data, + const AtomicString& value) { + Element* element = object->GetElement(); + if (!element) + return; - private: - AXObjectAttribute attribute_; + Element* target = element->GetElementAttribute(qualified_name); - QualifiedName GetAttributeQualifiedName() { - switch (attribute_) { - case AXObjectAttribute::kAriaActiveDescendant: - return html_names::kAriaActivedescendantAttr; - case AXObjectAttribute::kAriaErrorMessage: - return html_names::kAriaErrormessageAttr; - default: - NOTREACHED(); - } - return g_null_name; + if (!target) + return; + + AXObject* ax_target = object->AXObjectCache().GetOrCreate(target); + if (attribute == ax::mojom::blink::IntAttribute::kActivedescendantId && + !ax_target->IsVisible()) { + return; } - void Run(const AXObject& obj, - AXSparseAttributeClient& attribute_map, - const AtomicString& value) override { - if (value.IsNull()) - return; - - Element* element = obj.GetElement(); - if (!element) - return; - const QualifiedName& q_name = GetAttributeQualifiedName(); - Element* target = element->GetElementAttribute(q_name); - if (!target) - return; - AXObject* ax_target = obj.AXObjectCache().GetOrCreate(target); - if (ax_target) - attribute_map.AddObjectAttribute(attribute_, *ax_target); - } -}; - -class ObjectVectorAttributeSetter : public AXSparseAttributeSetter { - public: - ObjectVectorAttributeSetter(AXObjectVectorAttribute attribute) - : attribute_(attribute) {} - - private: - AXObjectVectorAttribute attribute_; - - QualifiedName GetAttributeQualifiedName() { - switch (attribute_) { - case AXObjectVectorAttribute::kAriaControls: - return html_names::kAriaControlsAttr; - case AXObjectVectorAttribute::kAriaDetails: - return html_names::kAriaDetailsAttr; - case AXObjectVectorAttribute::kAriaFlowTo: - return html_names::kAriaFlowtoAttr; - default: - NOTREACHED(); - } - return g_null_name; - } - - void Run(const AXObject& obj, - AXSparseAttributeClient& attribute_map, - const AtomicString& value) override { - Element* element = obj.GetElement(); - if (!element) - return; - - base::Optional<HeapVector<Member<Element>>> attr_associated_elements = - element->GetElementArrayAttribute(GetAttributeQualifiedName()); - if (!attr_associated_elements) - return; - HeapVector<Member<AXObject>>* objects = - MakeGarbageCollected<HeapVector<Member<AXObject>>>(); - for (const auto& associated_element : attr_associated_elements.value()) { - AXObject* ax_element = - obj.AXObjectCache().GetOrCreate(associated_element); - if (!ax_element) - continue; - if (AXObject* parent = ax_element->ParentObject()) - parent->UpdateChildrenIfNecessary(); - if (!ax_element->AccessibilityIsIgnored()) - objects->push_back(ax_element); - } - attribute_map.AddObjectVectorAttribute(attribute_, objects); - } -}; - -AXSparseAttributeSetterMap& GetSparseAttributeSetterMap() { - // Use a map from attribute name to properties of that attribute. - // That way we only need to iterate over the list of attributes once, - // rather than calling getAttribute() once for each possible obscure - // accessibility attribute. - DEFINE_STATIC_LOCAL(AXSparseAttributeSetterMap, - ax_sparse_attribute_setter_map, ()); - if (ax_sparse_attribute_setter_map.IsEmpty()) { - ax_sparse_attribute_setter_map.Set( - html_names::kAriaActivedescendantAttr, - new ObjectAttributeSetter(AXObjectAttribute::kAriaActiveDescendant)); - ax_sparse_attribute_setter_map.Set( - html_names::kAriaControlsAttr, - new ObjectVectorAttributeSetter( - AXObjectVectorAttribute::kAriaControls)); - ax_sparse_attribute_setter_map.Set( - html_names::kAriaFlowtoAttr, - new ObjectVectorAttributeSetter(AXObjectVectorAttribute::kAriaFlowTo)); - ax_sparse_attribute_setter_map.Set( - html_names::kAriaDetailsAttr, - new ObjectVectorAttributeSetter(AXObjectVectorAttribute::kAriaDetails)); - ax_sparse_attribute_setter_map.Set( - html_names::kAriaErrormessageAttr, - new ObjectAttributeSetter(AXObjectAttribute::kAriaErrorMessage)); - } - return ax_sparse_attribute_setter_map; + node_data->AddIntAttribute(attribute, ax_target->AXObjectID()); } -// TODO(meredithl): move the rest of the sparse attributes to this map. -TempSetterMap& GetTempSetterMap() { - DEFINE_STATIC_LOCAL(TempSetterMap, temp_setter_map, ()); - if (temp_setter_map.IsEmpty()) { - temp_setter_map.Set( +void SetIntListAttribute(ax::mojom::blink::IntListAttribute attribute, + QualifiedName qualified_name, + AXObject* object, + ui::AXNodeData* node_data, + const AtomicString& value) { + Element* element = object->GetElement(); + if (!element) + return; + base::Optional<HeapVector<Member<Element>>> attr_associated_elements = + element->GetElementArrayAttribute(qualified_name); + if (!attr_associated_elements) + return; + std::vector<int32_t> ax_ids; + + for (const auto& associated_element : attr_associated_elements.value()) { + AXObject* ax_element = + object->AXObjectCache().GetOrCreate(associated_element); + if (!ax_element) + continue; + if (AXObject* parent = ax_element->ParentObject()) + parent->UpdateChildrenIfNecessary(); + if (!ax_element->AccessibilityIsIgnored()) + ax_ids.push_back(ax_element->AXObjectID()); + } + node_data->AddIntListAttribute(attribute, ax_ids); +} + +AXSparseAttributeSetterMap& GetAXSparseAttributeSetterMap() { + DEFINE_STATIC_LOCAL(AXSparseAttributeSetterMap, ax_sparse_setter_map, ()); + if (ax_sparse_setter_map.IsEmpty()) { + ax_sparse_setter_map.Set( + html_names::kAriaActivedescendantAttr, + WTF::BindRepeating(&SetObjectAttribute, + ax::mojom::blink::IntAttribute::kActivedescendantId, + html_names::kAriaActivedescendantAttr)); + ax_sparse_setter_map.Set( html_names::kAriaBusyAttr, WTF::BindRepeating(&SetBoolAttribute, ax::mojom::blink::BoolAttribute::kBusy)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaColcountAttr, WTF::BindRepeating(&SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaColumnCount)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaColindexAttr, WTF::BindRepeating( &SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaCellColumnIndex)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaColspanAttr, WTF::BindRepeating( &SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaCellColumnSpan)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( + html_names::kAriaControlsAttr, + WTF::BindRepeating(&SetIntListAttribute, + ax::mojom::blink::IntListAttribute::kControlsIds, + html_names::kAriaControlsAttr)); + ax_sparse_setter_map.Set( + html_names::kAriaErrormessageAttr, + WTF::BindRepeating(&SetObjectAttribute, + ax::mojom::blink::IntAttribute::kErrormessageId, + html_names::kAriaErrormessageAttr)); + ax_sparse_setter_map.Set( + html_names::kAriaDetailsAttr, + WTF::BindRepeating(&SetIntListAttribute, + ax::mojom::blink::IntListAttribute::kDetailsIds, + html_names::kAriaDetailsAttr)); + ax_sparse_setter_map.Set( + html_names::kAriaFlowtoAttr, + WTF::BindRepeating(&SetIntListAttribute, + ax::mojom::blink::IntListAttribute::kFlowtoIds, + html_names::kAriaFlowtoAttr)); + ax_sparse_setter_map.Set( html_names::kAriaRowcountAttr, WTF::BindRepeating(&SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaRowCount)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaRowindexAttr, WTF::BindRepeating(&SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaCellRowIndex)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaRowspanAttr, WTF::BindRepeating(&SetIntAttribute, ax::mojom::blink::IntAttribute::kAriaCellRowSpan)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaRoledescriptionAttr, WTF::BindRepeating( &SetStringAttribute, ax::mojom::blink::StringAttribute::kRoleDescription)); - temp_setter_map.Set( + ax_sparse_setter_map.Set( html_names::kAriaKeyshortcutsAttr, WTF::BindRepeating(&SetStringAttribute, ax::mojom::blink::StringAttribute::kKeyShortcuts)); } - return temp_setter_map; -} - -void AXSparseAttributeAOMPropertyClient::AddStringProperty( - AOMStringProperty property, - const String& value) {} - -void AXSparseAttributeAOMPropertyClient::AddBooleanProperty( - AOMBooleanProperty property, - bool value) {} - -void AXSparseAttributeAOMPropertyClient::AddFloatProperty( - AOMFloatProperty property, - float value) {} - -void AXSparseAttributeAOMPropertyClient::AddRelationProperty( - AOMRelationProperty property, - const AccessibleNode& value) { - AXObjectAttribute attribute; - switch (property) { - case AOMRelationProperty::kActiveDescendant: - attribute = AXObjectAttribute::kAriaActiveDescendant; - break; - case AOMRelationProperty::kErrorMessage: - attribute = AXObjectAttribute::kAriaErrorMessage; - break; - default: - return; - } - - Element* target_element = value.element(); - AXObject* target_obj = ax_object_cache_->GetOrCreate(target_element); - if (target_element) - sparse_attribute_client_.AddObjectAttribute(attribute, *target_obj); -} - -void AXSparseAttributeAOMPropertyClient::AddRelationListProperty( - AOMRelationListProperty property, - const AccessibleNodeList& relations) { - AXObjectVectorAttribute attribute; - switch (property) { - case AOMRelationListProperty::kControls: - attribute = AXObjectVectorAttribute::kAriaControls; - break; - case AOMRelationListProperty::kDetails: - attribute = AXObjectVectorAttribute::kAriaDetails; - break; - case AOMRelationListProperty::kFlowTo: - attribute = AXObjectVectorAttribute::kAriaFlowTo; - break; - default: - return; - } - - HeapVector<Member<AXObject>>* objects = - MakeGarbageCollected<HeapVector<Member<AXObject>>>(); - for (unsigned i = 0; i < relations.length(); ++i) { - AccessibleNode* accessible_node = relations.item(i); - if (accessible_node) { - Element* element = accessible_node->element(); - AXObject* ax_element = ax_object_cache_->GetOrCreate(element); - if (ax_element && !ax_element->AccessibilityIsIgnored()) - objects->push_back(ax_element); - } - } - - sparse_attribute_client_.AddObjectVectorAttribute(attribute, objects); + return ax_sparse_setter_map; } void AXNodeDataAOMPropertyClient::AddStringProperty(AOMStringProperty property, @@ -298,10 +191,57 @@ void AXNodeDataAOMPropertyClient::AddRelationProperty( AOMRelationProperty property, - const AccessibleNode& value) {} + const AccessibleNode& value) { + ax::mojom::blink::IntAttribute attribute; + switch (property) { + case AOMRelationProperty::kActiveDescendant: + attribute = ax::mojom::blink::IntAttribute::kActivedescendantId; + break; + case AOMRelationProperty::kErrorMessage: + attribute = ax::mojom::blink::IntAttribute::kErrormessageId; + break; + default: + return; + } + + Element* target = value.element(); + AXObject* ax_target = ax_object_cache_->GetOrCreate(target); + if (!target) + return; + + node_data_.AddIntAttribute(attribute, ax_target->AXObjectID()); +} void AXNodeDataAOMPropertyClient::AddRelationListProperty( AOMRelationListProperty property, - const AccessibleNodeList& relations) {} + const AccessibleNodeList& relations) { + ax::mojom::blink::IntListAttribute attribute; + switch (property) { + case AOMRelationListProperty::kControls: + attribute = ax::mojom::blink::IntListAttribute::kControlsIds; + break; + case AOMRelationListProperty::kDetails: + attribute = ax::mojom::blink::IntListAttribute::kDetailsIds; + break; + case AOMRelationListProperty::kFlowTo: + attribute = ax::mojom::blink::IntListAttribute::kFlowtoIds; + break; + default: + return; + } + + std::vector<int32_t> ax_ids; + for (unsigned i = 0; i < relations.length(); ++i) { + AccessibleNode* accessible_node = relations.item(i); + if (accessible_node) { + Element* element = accessible_node->element(); + AXObject* ax_element = ax_object_cache_->GetOrCreate(element); + if (ax_element && !ax_element->AccessibilityIsIgnored()) + ax_ids.push_back(ax_element->AXObjectID()); + } + } + + node_data_.AddIntListAttribute(attribute, ax_ids); +} } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.h b/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.h index 50150c1..cdc0b9f5 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.h +++ b/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.h
@@ -13,63 +13,20 @@ namespace blink { -class AXSparseAttributeSetter { - USING_FAST_MALLOC(AXSparseAttributeSetter); - - public: - virtual void Run(const AXObject&, - AXSparseAttributeClient&, - const AtomicString& value) = 0; -}; - -using AXSparseAttributeSetterMap = - HashMap<QualifiedName, AXSparseAttributeSetter*>; - -// A map from attribute name to a AXSparseAttributeSetter that -// calls AXSparseAttributeClient when that attribute's value -// changes. +// A map from attribute name to a callback that sets the |value| for that +// attribute on an AXNodeData. // // That way we only need to iterate over the list of attributes once, // rather than calling getAttribute() once for each possible obscure // accessibility attribute. -// TODO(meredithl): Migrate this to the temp setter for crbug/1068668 -AXSparseAttributeSetterMap& GetSparseAttributeSetterMap(); -// A map from attribute name to a callback that sets the |value| for that -// attribute on an AXNodeData. This is designed to replace the above sparse -// attribute setter. This name is temporary, the above name of -// AXSparseAttributeSetterMap will be used once all sparse attributes are -// migrated. using AXSparseSetterFunc = base::RepeatingCallback<void(AXObject* ax_object, ui::AXNodeData* node_data, const AtomicString& value)>; -using TempSetterMap = HashMap<QualifiedName, AXSparseSetterFunc>; +using AXSparseAttributeSetterMap = HashMap<QualifiedName, AXSparseSetterFunc>; -TempSetterMap& GetTempSetterMap(); - -// An implementation of AOMPropertyClient that calls -// AXSparseAttributeClient for an AOM property. -class AXSparseAttributeAOMPropertyClient : public AOMPropertyClient { - public: - AXSparseAttributeAOMPropertyClient( - AXObjectCacheImpl& ax_object_cache, - AXSparseAttributeClient& sparse_attribute_client) - : ax_object_cache_(ax_object_cache), - sparse_attribute_client_(sparse_attribute_client) {} - - void AddStringProperty(AOMStringProperty, const String& value) override; - void AddBooleanProperty(AOMBooleanProperty, bool value) override; - void AddFloatProperty(AOMFloatProperty, float value) override; - void AddRelationProperty(AOMRelationProperty, - const AccessibleNode& value) override; - void AddRelationListProperty(AOMRelationListProperty, - const AccessibleNodeList& relations) override; - - private: - Persistent<AXObjectCacheImpl> ax_object_cache_; - AXSparseAttributeClient& sparse_attribute_client_; -}; +AXSparseAttributeSetterMap& GetAXSparseAttributeSetterMap(); class AXNodeDataAOMPropertyClient : public AOMPropertyClient { public:
diff --git a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc index 99b6722..3077091 100644 --- a/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc +++ b/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
@@ -378,59 +378,6 @@ return CreateProperty(key, std::move(node_list_value)); } -class SparseAttributeAXPropertyAdapter - : public GarbageCollected<SparseAttributeAXPropertyAdapter>, - public AXSparseAttributeClient { - public: - SparseAttributeAXPropertyAdapter(AXObject& ax_object, - protocol::Array<AXProperty>& properties) - : ax_object_(&ax_object), properties_(properties) {} - - void Trace(Visitor* visitor) const { visitor->Trace(ax_object_); } - - private: - Member<AXObject> ax_object_; - protocol::Array<AXProperty>& properties_; - - void AddObjectAttribute(AXObjectAttribute attribute, - AXObject& object) override { - switch (attribute) { - case AXObjectAttribute::kAriaActiveDescendant: - properties_.emplace_back( - CreateProperty(AXPropertyNameEnum::Activedescendant, - CreateRelatedNodeListValue(object))); - break; - case AXObjectAttribute::kAriaErrorMessage: - properties_.emplace_back( - CreateProperty(AXPropertyNameEnum::Errormessage, - CreateRelatedNodeListValue(object))); - break; - } - } - - void AddObjectVectorAttribute( - AXObjectVectorAttribute attribute, - HeapVector<Member<AXObject>>* objects) override { - switch (attribute) { - case AXObjectVectorAttribute::kAriaControls: - properties_.emplace_back(CreateRelatedNodeListProperty( - AXPropertyNameEnum::Controls, *objects, - html_names::kAriaControlsAttr, *ax_object_)); - break; - case AXObjectVectorAttribute::kAriaDetails: - properties_.emplace_back(CreateRelatedNodeListProperty( - AXPropertyNameEnum::Details, *objects, html_names::kAriaDetailsAttr, - *ax_object_)); - break; - case AXObjectVectorAttribute::kAriaFlowTo: - properties_.emplace_back(CreateRelatedNodeListProperty( - AXPropertyNameEnum::Flowto, *objects, html_names::kAriaFlowtoAttr, - *ax_object_)); - break; - } - } -}; - void FillRelationships(AXObject& ax_object, protocol::Array<AXProperty>& properties) { AXObject::AXObjectVector results; @@ -451,11 +398,19 @@ results.clear(); } +void GetObjectsFromAXIDs(const AXObjectCacheImpl& cache, + const std::vector<int32_t>& ax_ids, + AXObject::AXObjectVector* ax_objects) { + for (const auto& ax_id : ax_ids) { + AXObject* ax_object = cache.ObjectFromAXID(ax_id); + if (!ax_object) + continue; + ax_objects->push_back(ax_object); + } +} + void FillSparseAttributes(AXObject& ax_object, protocol::Array<AXProperty>& properties) { - SparseAttributeAXPropertyAdapter adapter(ax_object, properties); - ax_object.GetSparseAXAttributes(adapter); - ui::AXNodeData node_data; ax_object.Serialize(&node_data, ui::kAXModeComplete); @@ -486,6 +441,58 @@ CreateValue(WTF::String(role_description.c_str()), AXValueTypeEnum::String))); } + + if (node_data.HasIntAttribute( + ax::mojom::blink::IntAttribute::kActivedescendantId)) { + AXObject* target = + ax_object.AXObjectCache().ObjectFromAXID(node_data.GetIntAttribute( + ax::mojom::blink::IntAttribute::kActivedescendantId)); + properties.emplace_back( + CreateProperty(AXPropertyNameEnum::Activedescendant, + CreateRelatedNodeListValue(*target))); + } + + if (node_data.HasIntAttribute( + ax::mojom::blink::IntAttribute::kErrormessageId)) { + AXObject* target = + ax_object.AXObjectCache().ObjectFromAXID(node_data.GetIntAttribute( + ax::mojom::blink::IntAttribute::kErrormessageId)); + properties.emplace_back(CreateProperty( + AXPropertyNameEnum::Errormessage, CreateRelatedNodeListValue(*target))); + } + + if (node_data.HasIntListAttribute( + ax::mojom::blink::IntListAttribute::kControlsIds)) { + const auto ax_ids = node_data.GetIntListAttribute( + ax::mojom::blink::IntListAttribute::kControlsIds); + AXObject::AXObjectVector ax_objects; + GetObjectsFromAXIDs(ax_object.AXObjectCache(), ax_ids, &ax_objects); + properties.emplace_back(CreateRelatedNodeListProperty( + AXPropertyNameEnum::Controls, ax_objects, html_names::kAriaControlsAttr, + ax_object)); + } + + if (node_data.HasIntListAttribute( + ax::mojom::blink::IntListAttribute::kDetailsIds)) { + const auto ax_ids = node_data.GetIntListAttribute( + ax::mojom::blink::IntListAttribute::kDetailsIds); + AXObject::AXObjectVector ax_objects; + GetObjectsFromAXIDs(ax_object.AXObjectCache(), ax_ids, &ax_objects); + properties.emplace_back( + CreateRelatedNodeListProperty(AXPropertyNameEnum::Details, ax_objects, + html_names::kAriaDetailsAttr, ax_object)); + } + + if (node_data.HasIntListAttribute( + ax::mojom::blink::IntListAttribute::kFlowtoIds)) { + const auto ax_ids = node_data.GetIntListAttribute( + ax::mojom::blink::IntListAttribute::kFlowtoIds); + AXObject::AXObjectVector ax_objects; + GetObjectsFromAXIDs(ax_object.AXObjectCache(), ax_ids, &ax_objects); + properties.emplace_back( + CreateRelatedNodeListProperty(AXPropertyNameEnum::Flowto, ax_objects, + html_names::kAriaFlowtoAttr, ax_object)); + } return; } @@ -686,8 +693,8 @@ FillWidgetProperties(ax_object, *(properties.get())); FillWidgetStates(ax_object, *(properties.get())); FillRelationships(ax_object, *(properties.get())); + FillSparseAttributes(ax_object, *(properties.get())); - FillSparseAttributes(ax_object, *properties); AXObject::NameSources name_sources; String computed_name = ax_object.GetName(&name_sources); if (!name_sources.IsEmpty()) {
diff --git a/third_party/blink/renderer/modules/exported/web_ax_object.cc b/third_party/blink/renderer/modules/exported/web_ax_object.cc index 9156033..2c0f8eba 100644 --- a/third_party/blink/renderer/modules/exported/web_ax_object.cc +++ b/third_party/blink/renderer/modules/exported/web_ax_object.cc
@@ -86,31 +86,6 @@ } } // namespace -class WebAXSparseAttributeClientAdapter : public AXSparseAttributeClient { - public: - explicit WebAXSparseAttributeClientAdapter( - WebAXSparseAttributeClient& attribute_map) - : attribute_map_(attribute_map) {} - virtual ~WebAXSparseAttributeClientAdapter() = default; - - private: - WebAXSparseAttributeClient& attribute_map_; - - void AddObjectAttribute(AXObjectAttribute attribute, - AXObject& value) override { - attribute_map_.AddObjectAttribute( - static_cast<WebAXObjectAttribute>(attribute), WebAXObject(&value)); - } - - void AddObjectVectorAttribute(AXObjectVectorAttribute attribute, - HeapVector<Member<AXObject>>* value) override { - WebVector<WebAXObject> result(value->size()); - std::copy(value->begin(), value->end(), result.begin()); - attribute_map_.AddObjectVectorAttribute( - static_cast<WebAXObjectVectorAttribute>(attribute), result); - } -}; - // A utility class which uses the lifetime of this object to signify when // AXObjCache or AXObjectCacheImpl handles programmatic actions. class ScopedActionAnnotator { @@ -257,15 +232,6 @@ return WebAXObject(private_->ParentObjectIncludedInTree()); } -void WebAXObject::GetSparseAXAttributes( - WebAXSparseAttributeClient& client) const { - if (IsDetached()) - return; - - WebAXSparseAttributeClientAdapter adapter(client); - private_->GetSparseAXAttributes(adapter); -} - void WebAXObject::Serialize(ui::AXNodeData* node_data, ui::AXMode accessibility_mode) const { if (IsDetached())
diff --git a/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc b/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc index 2623ec5..5583b8f 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc
@@ -106,8 +106,13 @@ DCHECK(!params_.IsEmpty()); DCHECK(params_.NewLocal(isolate)->IsObject()); - // Copies |param_value_map| to the internal |params_| object; - CopyParamValueMapToObject(isolate, context, param_value_map, params_); + // Copies |param_value_map| to the internal |params_| object. This operation + // could fail if the getter of parameterDescriptors is overridden by user code + // and returns incompatible data. (crbug.com/1151069) + if (!CopyParamValueMapToObject(isolate, context, param_value_map, params_)) { + SetErrorState(AudioWorkletProcessorErrorState::kProcessError); + return false; + } // Performs the user-defined AudioWorkletProcessor.process() function. v8::TryCatch try_catch(isolate); @@ -443,6 +448,7 @@ break; } } + DCHECK(array_size == 1 || array_size == param_float_array->size()); v8::Local<v8::ArrayBuffer> array_buffer = v8::ArrayBuffer::New(isolate, array_size * sizeof(float)); @@ -481,18 +487,23 @@ v8::Local<v8::Value> param_array_value; if (!params_object->Get(context, V8String(isolate, param_name)) - .ToLocal(¶m_array_value)) { + .ToLocal(¶m_array_value) || + !param_array_value->IsFloat32Array()) { return false; } - DCHECK(param_array_value->IsFloat32Array()); + v8::Local<v8::Float32Array> float32_array = param_array_value.As<v8::Float32Array>(); + size_t array_length = float32_array->Length(); - // The Float32Array is either 1 or 128 frames, but it always should be - // less than equal to the size of the given AudioFloatArray. - DCHECK_LE(float32_array->Length(), param_array->size()); + // The |float32_array| is neither 1 nor 128 frames, or the array buffer is + // trasnferred/detached, do not proceed. + if ((array_length != 1 && array_length != param_array->size()) || + float32_array->Buffer()->ByteLength() == 0) + return false; + memcpy(float32_array->Buffer()->GetContents().Data(), param_array->Data(), - float32_array->Length() * sizeof(float)); + array_length * sizeof(float)); } return true;
diff --git a/third_party/blink/renderer/modules/webcodecs/audio_decoder.h b/third_party/blink/renderer/modules/webcodecs/audio_decoder.h index d929a9c3..b701dfa5 100644 --- a/third_party/blink/renderer/modules/webcodecs/audio_decoder.h +++ b/third_party/blink/renderer/modules/webcodecs/audio_decoder.h
@@ -13,7 +13,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_frame_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webcodecs/codec_config_eval.h" #include "third_party/blink/renderer/modules/webcodecs/decoder_template.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/audio_decoder_fuzzer.cc b/third_party/blink/renderer/modules/webcodecs/audio_decoder_fuzzer.cc index 8ff45de8..20a26a9f2 100644 --- a/third_party/blink/renderer/modules/webcodecs/audio_decoder_fuzzer.cc +++ b/third_party/blink/renderer/modules/webcodecs/audio_decoder_fuzzer.cc
@@ -8,7 +8,7 @@ #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_decoder_config.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_decoder_init.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_frame_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/decoder_template.h b/third_party/blink/renderer/modules/webcodecs/decoder_template.h index 422b3370e..e9eb721 100644 --- a/third_party/blink/renderer/modules/webcodecs/decoder_template.h +++ b/third_party/blink/renderer/modules/webcodecs/decoder_template.h
@@ -15,7 +15,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_codec_state.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webcodecs/codec_config_eval.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/idls.gni b/third_party/blink/renderer/modules/webcodecs/idls.gni index cb6206f7..5be7bd5 100644 --- a/third_party/blink/renderer/modules/webcodecs/idls.gni +++ b/third_party/blink/renderer/modules/webcodecs/idls.gni
@@ -19,7 +19,7 @@ "audio_frame_output_callback.idl", "video_encoder_output_callback.idl", "video_frame_output_callback.idl", - "web_codecs_error_callback.idl", + "webcodecs_error_callback.idl", ] modules_dictionary_idl_files = [
diff --git a/third_party/blink/renderer/modules/webcodecs/video_decoder.h b/third_party/blink/renderer/modules/webcodecs/video_decoder.h index 87b2ce2..49f9f8d5 100644 --- a/third_party/blink/renderer/modules/webcodecs/video_decoder.h +++ b/third_party/blink/renderer/modules/webcodecs/video_decoder.h
@@ -15,7 +15,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_frame_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webcodecs/codec_config_eval.h" #include "third_party/blink/renderer/modules/webcodecs/decoder_template.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/video_decoder_fuzzer.cc b/third_party/blink/renderer/modules/webcodecs/video_decoder_fuzzer.cc index 73f1b31..6dac5d0 100644 --- a/third_party/blink/renderer/modules/webcodecs/video_decoder_fuzzer.cc +++ b/third_party/blink/renderer/modules/webcodecs/video_decoder_fuzzer.cc
@@ -8,7 +8,7 @@ #include "third_party/blink/renderer/bindings/modules/v8/v8_video_decoder_config.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_decoder_init.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_frame_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/video_encoder.h b/third_party/blink/renderer/modules/webcodecs/video_encoder.h index aea03eb..e6fed8b 100644 --- a/third_party/blink/renderer/modules/webcodecs/video_encoder.h +++ b/third_party/blink/renderer/modules/webcodecs/video_encoder.h
@@ -17,7 +17,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_codec_state.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_encoder_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webcodecs/codec_logger.h" #include "third_party/blink/renderer/modules/webcodecs/video_frame.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/video_encoder_fuzzer.cc b/third_party/blink/renderer/modules/webcodecs/video_encoder_fuzzer.cc index 81397979..264585ea 100644 --- a/third_party/blink/renderer/modules/webcodecs/video_encoder_fuzzer.cc +++ b/third_party/blink/renderer/modules/webcodecs/video_encoder_fuzzer.cc
@@ -9,7 +9,7 @@ #include "third_party/blink/renderer/bindings/modules/v8/v8_video_decoder_config.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_encoder_init.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_video_encoder_output_callback.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_web_codecs_error_callback.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
diff --git a/third_party/blink/renderer/modules/webcodecs/web_codecs_error_callback.idl b/third_party/blink/renderer/modules/webcodecs/webcodecs_error_callback.idl similarity index 100% rename from third_party/blink/renderer/modules/webcodecs/web_codecs_error_callback.idl rename to third_party/blink/renderer/modules/webcodecs/webcodecs_error_callback.idl
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_device.cc b/third_party/blink/renderer/modules/webgpu/gpu_device.cc index 7eddd23..aca84eb 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_device.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu_device.cc
@@ -149,6 +149,33 @@ } } +void GPUDevice::OnCreateReadyRenderPipelineCallback( + ScriptPromiseResolver* resolver, + WGPUCreateReadyPipelineStatus status, + WGPURenderPipeline render_pipeline, + const char* message) { + switch (status) { + case WGPUCreateReadyPipelineStatus_Success: { + resolver->Resolve( + MakeGarbageCollected<GPURenderPipeline>(this, render_pipeline)); + break; + } + + case WGPUCreateReadyPipelineStatus_Error: + case WGPUCreateReadyPipelineStatus_DeviceLost: + case WGPUCreateReadyPipelineStatus_DeviceDestroyed: + case WGPUCreateReadyPipelineStatus_Unknown: { + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kOperationError, message)); + break; + } + + default: { + NOTREACHED(); + } + } +} + void GPUDevice::OnCreateReadyComputePipelineCallback( ScriptPromiseResolver* resolver, WGPUCreateReadyPipelineStatus status, @@ -239,6 +266,36 @@ return GPUComputePipeline::Create(this, descriptor); } +ScriptPromise GPUDevice::createReadyRenderPipeline( + ScriptState* script_state, + const GPURenderPipelineDescriptor* descriptor) { + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + ScriptPromise promise = resolver->Promise(); + + OwnedRenderPipelineDescriptor dawn_desc_info; + v8::Isolate* isolate = script_state->GetIsolate(); + ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, + "GPUVertexStateDescriptor"); + ConvertToDawnType(isolate, descriptor, &dawn_desc_info, exception_state); + if (exception_state.HadException()) { + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kOperationError, + "Error in parsing GPURenderPipelineDescriptor")); + } else { + auto* callback = + BindDawnCallback(&GPUDevice::OnCreateReadyRenderPipelineCallback, + WrapPersistent(this), WrapPersistent(resolver)); + GetProcs().deviceCreateReadyRenderPipeline( + GetHandle(), &dawn_desc_info.dawn_desc, callback->UnboundCallback(), + callback->AsUserdata()); + } + + // WebGPU guarantees that promises are resolved in finite time so we need to + // ensure commands are flushed. + EnsureFlush(); + return promise; +} + ScriptPromise GPUDevice::createReadyComputePipeline( ScriptState* script_state, const GPUComputePipelineDescriptor* descriptor) {
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_device.h b/third_party/blink/renderer/modules/webgpu/gpu_device.h index a459ac18..e875a6a 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_device.h +++ b/third_party/blink/renderer/modules/webgpu/gpu_device.h
@@ -92,6 +92,9 @@ const GPURenderPipelineDescriptor* descriptor); GPUComputePipeline* createComputePipeline( const GPUComputePipelineDescriptor* descriptor); + ScriptPromise createReadyRenderPipeline( + ScriptState* script_state, + const GPURenderPipelineDescriptor* descriptor); ScriptPromise createReadyComputePipeline( ScriptState* script_state, const GPUComputePipelineDescriptor* descriptor); @@ -126,6 +129,10 @@ WGPUErrorType type, const char* message); + void OnCreateReadyRenderPipelineCallback(ScriptPromiseResolver* resolver, + WGPUCreateReadyPipelineStatus status, + WGPURenderPipeline render_pipeline, + const char* message); void OnCreateReadyComputePipelineCallback( ScriptPromiseResolver* resolver, WGPUCreateReadyPipelineStatus status,
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_device.idl b/third_party/blink/renderer/modules/webgpu/gpu_device.idl index a31ad253..4ae0cb8a 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_device.idl +++ b/third_party/blink/renderer/modules/webgpu/gpu_device.idl
@@ -25,6 +25,7 @@ [CallWith=ScriptState] GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor); GPUComputePipeline createComputePipeline(GPUComputePipelineDescriptor descriptor); + [CallWith=ScriptState] Promise<GPURenderPipeline?> createReadyRenderPipeline(GPURenderPipelineDescriptor descriptor); [CallWith=ScriptState] Promise<GPUComputePipeline?> createReadyComputePipeline(GPUComputePipelineDescriptor descriptor); GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {});
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc index 8d33f86..c067713 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
@@ -14,7 +14,6 @@ #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_attribute_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_buffer_layout_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_state_descriptor.h" -#include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h" #include "third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout.h" #include "third_party/blink/renderer/modules/webgpu/gpu_device.h" #include "third_party/blink/renderer/modules/webgpu/gpu_pipeline_layout.h" @@ -88,22 +87,24 @@ return dawn_desc; } -using WGPUVertexStateInfo = std::tuple<WGPUVertexStateDescriptor, - Vector<WGPUVertexBufferLayoutDescriptor>, - Vector<WGPUVertexAttributeDescriptor>>; - -WGPUVertexStateInfo GPUVertexStateAsWGPUVertexState( +void GPUVertexStateAsWGPUVertexState( v8::Isolate* isolate, const GPUVertexStateDescriptor* descriptor, + WGPUVertexStateDescriptor* dawn_desc, + Vector<WGPUVertexBufferLayoutDescriptor>* dawn_vertex_buffers, + Vector<WGPUVertexAttributeDescriptor>* dawn_vertex_attributes, ExceptionState& exception_state) { - WGPUVertexStateDescriptor dawn_desc = {}; - dawn_desc.indexFormat = - AsDawnEnum<WGPUIndexFormat>(descriptor->indexFormat()); - dawn_desc.vertexBufferCount = 0; - dawn_desc.vertexBuffers = nullptr; + DCHECK(isolate); + DCHECK(descriptor); + DCHECK(dawn_desc); + DCHECK(dawn_vertex_buffers); + DCHECK(dawn_vertex_attributes); - Vector<WGPUVertexBufferLayoutDescriptor> dawn_vertex_buffers; - Vector<WGPUVertexAttributeDescriptor> dawn_vertex_attributes; + *dawn_desc = {}; + dawn_desc->indexFormat = + AsDawnEnum<WGPUIndexFormat>(descriptor->indexFormat()); + dawn_desc->vertexBufferCount = 0; + dawn_desc->vertexBuffers = nullptr; if (descriptor->hasVertexBuffers()) { // TODO(crbug.com/951629): Use a sequence of nullable descriptors. @@ -111,9 +112,7 @@ descriptor->vertexBuffers().V8Value(); if (!vertex_buffers_value->IsArray()) { exception_state.ThrowTypeError("vertexBuffers must be an array"); - - return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), - std::move(dawn_vertex_attributes)); + return; } v8::Local<v8::Context> context = isolate->GetCurrentContext(); @@ -135,7 +134,7 @@ dawn_vertex_buffer.stepMode = WGPUInputStepMode_Vertex; dawn_vertex_buffer.attributeCount = 0; dawn_vertex_buffer.attributes = nullptr; - dawn_vertex_buffers.push_back(dawn_vertex_buffer); + dawn_vertex_buffers->push_back(dawn_vertex_buffer); continue; } @@ -143,8 +142,7 @@ NativeValueTraits<GPUVertexBufferLayoutDescriptor>::NativeValue( isolate, value, exception_state); if (exception_state.HadException()) { - return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), - std::move(dawn_vertex_attributes)); + return; } WGPUVertexBufferLayoutDescriptor dawn_vertex_buffer = {}; @@ -154,7 +152,7 @@ dawn_vertex_buffer.attributeCount = static_cast<uint32_t>(vertex_buffer->attributes().size()); dawn_vertex_buffer.attributes = nullptr; - dawn_vertex_buffers.push_back(dawn_vertex_buffer); + dawn_vertex_buffers->push_back(dawn_vertex_buffer); for (wtf_size_t j = 0; j < vertex_buffer->attributes().size(); ++j) { const GPUVertexAttributeDescriptor* attribute = @@ -164,7 +162,7 @@ dawn_vertex_attribute.offset = attribute->offset(); dawn_vertex_attribute.format = AsDawnEnum<WGPUVertexFormat>(attribute->format()); - dawn_vertex_attributes.push_back(dawn_vertex_attribute); + dawn_vertex_attributes->push_back(dawn_vertex_attribute); } } @@ -172,21 +170,18 @@ // after we stopped appending to the vector so the pointers aren't // invalidated. uint32_t attributeIndex = 0; - for (WGPUVertexBufferLayoutDescriptor& buffer : dawn_vertex_buffers) { + for (WGPUVertexBufferLayoutDescriptor& buffer : *dawn_vertex_buffers) { if (buffer.attributeCount == 0) { continue; } - buffer.attributes = &dawn_vertex_attributes[attributeIndex]; + buffer.attributes = &(*dawn_vertex_attributes)[attributeIndex]; attributeIndex += buffer.attributeCount; } } - dawn_desc.vertexBufferCount = - static_cast<uint32_t>(dawn_vertex_buffers.size()); - dawn_desc.vertexBuffers = dawn_vertex_buffers.data(); - - return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), - std::move(dawn_vertex_attributes)); + dawn_desc->vertexBufferCount = + static_cast<uint32_t>(dawn_vertex_buffers->size()); + dawn_desc->vertexBuffers = dawn_vertex_buffers->data(); } WGPURasterizationStateDescriptor AsDawnType( @@ -206,6 +201,69 @@ } // anonymous namespace +void ConvertToDawnType(v8::Isolate* isolate, + const GPURenderPipelineDescriptor* webgpu_desc, + OwnedRenderPipelineDescriptor* dawn_desc_info, + ExceptionState& exception_state) { + DCHECK(isolate); + DCHECK(webgpu_desc); + DCHECK(dawn_desc_info); + + GPUVertexStateAsWGPUVertexState( + isolate, webgpu_desc->vertexState(), &dawn_desc_info->vertex_state, + &dawn_desc_info->vertex_buffer_layouts, + &dawn_desc_info->vertex_attributes, exception_state); + if (exception_state.HadException()) { + return; + } + dawn_desc_info->dawn_desc.vertexState = &dawn_desc_info->vertex_state; + + if (webgpu_desc->hasLayout()) { + dawn_desc_info->dawn_desc.layout = AsDawnType(webgpu_desc->layout()); + } + + if (webgpu_desc->hasLabel()) { + dawn_desc_info->label = webgpu_desc->label().Utf8(); + dawn_desc_info->dawn_desc.label = dawn_desc_info->label.c_str(); + } + + dawn_desc_info->vertex_stage_info = AsDawnType(webgpu_desc->vertexStage()); + dawn_desc_info->dawn_desc.vertexStage = + std::get<0>(dawn_desc_info->vertex_stage_info); + if (webgpu_desc->hasFragmentStage()) { + dawn_desc_info->fragment_stage_info = + AsDawnType(webgpu_desc->fragmentStage()); + dawn_desc_info->dawn_desc.fragmentStage = + &std::get<0>(dawn_desc_info->fragment_stage_info); + } + + dawn_desc_info->dawn_desc.primitiveTopology = + AsDawnEnum<WGPUPrimitiveTopology>(webgpu_desc->primitiveTopology()); + + dawn_desc_info->rasterization_state = + AsDawnType(webgpu_desc->rasterizationState()); + dawn_desc_info->dawn_desc.rasterizationState = + &dawn_desc_info->rasterization_state; + + dawn_desc_info->dawn_desc.sampleCount = webgpu_desc->sampleCount(); + + if (webgpu_desc->hasDepthStencilState()) { + dawn_desc_info->depth_stencil_state = + AsDawnType(webgpu_desc->depthStencilState()); + dawn_desc_info->dawn_desc.depthStencilState = + &dawn_desc_info->depth_stencil_state; + } + + dawn_desc_info->color_states = AsDawnType(webgpu_desc->colorStates()); + dawn_desc_info->dawn_desc.colorStateCount = + static_cast<uint32_t>(webgpu_desc->colorStates().size()); + dawn_desc_info->dawn_desc.colorStates = dawn_desc_info->color_states.get(); + + dawn_desc_info->dawn_desc.sampleMask = webgpu_desc->sampleMask(); + dawn_desc_info->dawn_desc.alphaToCoverageEnabled = + webgpu_desc->alphaToCoverageEnabled(); +} + // static GPURenderPipeline* GPURenderPipeline::Create( ScriptState* script_state, @@ -214,71 +272,18 @@ DCHECK(device); DCHECK(webgpu_desc); - std::string label; - WGPURenderPipelineDescriptor dawn_desc = {}; - dawn_desc.nextInChain = nullptr; - if (webgpu_desc->hasLayout()) { - dawn_desc.layout = AsDawnType(webgpu_desc->layout()); - } - if (webgpu_desc->hasLabel()) { - label = webgpu_desc->label().Utf8(); - dawn_desc.label = label.c_str(); - } - - OwnedProgrammableStageDescriptor vertex_stage_info = - AsDawnType(webgpu_desc->vertexStage()); - dawn_desc.vertexStage = std::get<0>(vertex_stage_info); - OwnedProgrammableStageDescriptor fragment_stage_info; - if (webgpu_desc->hasFragmentStage()) { - fragment_stage_info = AsDawnType(webgpu_desc->fragmentStage()); - dawn_desc.fragmentStage = &std::get<0>(fragment_stage_info); - } else { - dawn_desc.fragmentStage = nullptr; - } - - dawn_desc.primitiveTopology = - AsDawnEnum<WGPUPrimitiveTopology>(webgpu_desc->primitiveTopology()); - + OwnedRenderPipelineDescriptor dawn_desc_info; v8::Isolate* isolate = script_state->GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, "GPUVertexStateDescriptor"); - WGPUVertexStateInfo vertex_state_info = GPUVertexStateAsWGPUVertexState( - isolate, webgpu_desc->vertexState(), exception_state); - WGPUVertexStateDescriptor dawn_vertex_state = std::get<0>(vertex_state_info); - - dawn_desc.vertexState = &dawn_vertex_state; - + ConvertToDawnType(isolate, webgpu_desc, &dawn_desc_info, exception_state); if (exception_state.HadException()) { return nullptr; } - WGPURasterizationStateDescriptor rasterization_state; - rasterization_state = AsDawnType(webgpu_desc->rasterizationState()); - dawn_desc.rasterizationState = &rasterization_state; - - dawn_desc.sampleCount = webgpu_desc->sampleCount(); - - WGPUDepthStencilStateDescriptor depth_stencil_state = {}; - if (webgpu_desc->hasDepthStencilState()) { - depth_stencil_state = AsDawnType(webgpu_desc->depthStencilState()); - dawn_desc.depthStencilState = &depth_stencil_state; - } else { - dawn_desc.depthStencilState = nullptr; - } - - std::unique_ptr<WGPUColorStateDescriptor[]> color_states = - AsDawnType(webgpu_desc->colorStates()); - dawn_desc.colorStateCount = - static_cast<uint32_t>(webgpu_desc->colorStates().size()); - - dawn_desc.colorStates = color_states.get(); - - dawn_desc.sampleMask = webgpu_desc->sampleMask(); - dawn_desc.alphaToCoverageEnabled = webgpu_desc->alphaToCoverageEnabled(); - return MakeGarbageCollected<GPURenderPipeline>( - device, device->GetProcs().deviceCreateRenderPipeline(device->GetHandle(), - &dawn_desc)); + device, device->GetProcs().deviceCreateRenderPipeline( + device->GetHandle(), &dawn_desc_info.dawn_desc)); } GPURenderPipeline::GPURenderPipeline(GPUDevice* device,
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h index 3f9dbb1..b1fb959 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h +++ b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h
@@ -5,14 +5,47 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGPU_GPU_RENDER_PIPELINE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGPU_GPU_RENDER_PIPELINE_H_ +#include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h" #include "third_party/blink/renderer/modules/webgpu/dawn_object.h" namespace blink { class GPUBindGroupLayout; class GPURenderPipelineDescriptor; +class ExceptionState; class ScriptState; +struct OwnedRenderPipelineDescriptor { + public: + OwnedRenderPipelineDescriptor() : dawn_desc({}) {} + + // This struct should be non-copyable non-movable because it contains + // self-referencing pointers that would be invalidated when moved / copied. + OwnedRenderPipelineDescriptor(const OwnedRenderPipelineDescriptor& desc) = + delete; + OwnedRenderPipelineDescriptor(OwnedRenderPipelineDescriptor&& desc) = delete; + OwnedRenderPipelineDescriptor& operator=( + const OwnedRenderPipelineDescriptor& desc) = delete; + OwnedRenderPipelineDescriptor& operator=( + OwnedRenderPipelineDescriptor&& desc) = delete; + + WGPURenderPipelineDescriptor dawn_desc; + std::string label; + OwnedProgrammableStageDescriptor vertex_stage_info; + OwnedProgrammableStageDescriptor fragment_stage_info; + WGPUVertexStateDescriptor vertex_state; + Vector<WGPUVertexBufferLayoutDescriptor> vertex_buffer_layouts; + Vector<WGPUVertexAttributeDescriptor> vertex_attributes; + WGPURasterizationStateDescriptor rasterization_state; + WGPUDepthStencilStateDescriptor depth_stencil_state; + std::unique_ptr<WGPUColorStateDescriptor[]> color_states; +}; + +void ConvertToDawnType(v8::Isolate* isolate, + const GPURenderPipelineDescriptor* webgpu_desc, + OwnedRenderPipelineDescriptor* dawn_desc_info, + ExceptionState& exception_state); + class GPURenderPipeline : public DawnObject<WGPURenderPipeline> { DEFINE_WRAPPERTYPEINFO();
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 9cc26a7..80956a9 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1043,6 +1043,7 @@ "graphics/paint/hit_test_data.h", "graphics/paint/ignore_paint_timing_scope.cc", "graphics/paint/ignore_paint_timing_scope.h", + "graphics/paint/layer_selection_data.h", "graphics/paint/paint_artifact.cc", "graphics/paint/paint_artifact.h", "graphics/paint/paint_canvas.h", @@ -1064,6 +1065,7 @@ "graphics/paint/paint_record_builder.h", "graphics/paint/paint_recorder.h", "graphics/paint/paint_shader.h", + "graphics/paint/painted_selection_bound.h", "graphics/paint/property_tree_state.cc", "graphics/paint/property_tree_state.h", "graphics/paint/raster_invalidation_tracking.cc",
diff --git a/third_party/blink/renderer/platform/file_metadata.cc b/third_party/blink/renderer/platform/file_metadata.cc index 51d0190..5b7ae7a3 100644 --- a/third_party/blink/renderer/platform/file_metadata.cc +++ b/third_party/blink/renderer/platform/file_metadata.cc
@@ -78,24 +78,6 @@ return true; } -bool GetFileModificationTime(const String& path, - base::Optional<base::Time>& result) { - FileMetadata metadata; - if (!GetFileMetadata(path, metadata)) - return false; - result = metadata.modification_time; - return true; -} - -void RebindFileUtilitiesForTesting() { - auto& host = GetFileUtilitiesHost(); - if (host) { - host.Unbind().reset(); - } - Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( - host.BindNewPipeAndPassReceiver()); -} - bool GetFileMetadata(const String& path, FileMetadata& metadata) { auto& host = GetFileUtilitiesHost(); if (!host) {
diff --git a/third_party/blink/renderer/platform/file_metadata.h b/third_party/blink/renderer/platform/file_metadata.h index 08c52dd..2965473 100644 --- a/third_party/blink/renderer/platform/file_metadata.h +++ b/third_party/blink/renderer/platform/file_metadata.h
@@ -64,14 +64,9 @@ }; PLATFORM_EXPORT bool GetFileSize(const String&, int64_t& result); -PLATFORM_EXPORT bool GetFileModificationTime( - const String&, - base::Optional<base::Time>& result); PLATFORM_EXPORT bool GetFileMetadata(const String&, FileMetadata&); PLATFORM_EXPORT KURL FilePathToURL(const String&); -PLATFORM_EXPORT void RebindFileUtilitiesForTesting(); - inline base::Optional<base::Time> NullableTimeToOptionalTime(base::Time time) { if (time.is_null()) return base::nullopt;
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc index d05e03f..b3117c6 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
@@ -1150,6 +1150,7 @@ // See if we can de-composite any transforms. DecompositeTransforms(); + cc::LayerSelection layer_selection; const PendingLayer* previous_pending_layer = nullptr; for (auto& pending_layer : pending_layers_) { const auto& property_state = pending_layer.property_tree_state; @@ -1171,7 +1172,8 @@ pending_layer, new_content_layer_clients, new_scroll_hit_test_layers, new_scrollbar_layers); - UpdateLayerProperties(*layer, pending_layer, &property_tree_manager); + UpdateLayerProperties(*layer, pending_layer, layer_selection, + &property_tree_manager); layer->SetLayerTreeHost(root_layer_->layer_tree_host()); @@ -1233,6 +1235,9 @@ previous_pending_layer = &pending_layer; } + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + root_layer_->layer_tree_host()->RegisterSelection(layer_selection); + property_tree_manager.Finalize(); content_layer_clients_.swap(new_content_layer_clients); scroll_hit_test_layers_.swap(new_scroll_hit_test_layers); @@ -1274,6 +1279,7 @@ void PaintArtifactCompositor::UpdateLayerProperties( cc::Layer& layer, const PendingLayer& pending_layer, + cc::LayerSelection& layer_selection, PropertyTreeManager* property_tree_manager) { // Properties of foreign layers are managed by their owners. if (pending_layer.compositing_type == PendingLayer::kForeignLayer) @@ -1286,7 +1292,8 @@ .GetPaintArtifactShared()); } PaintChunksToCcLayer::UpdateLayerProperties( - layer, pending_layer.property_tree_state, chunks, property_tree_manager); + layer, pending_layer.property_tree_state, chunks, layer_selection, + property_tree_manager); } void PaintArtifactCompositor::UpdateRepaintedLayerProperties() const { @@ -1299,8 +1306,9 @@ continue; DCHECK(pending_layer.graphics_layer); if (pending_layer.graphics_layer->Repainted()) { + cc::LayerSelection layer_selection; UpdateLayerProperties(pending_layer.graphics_layer->CcLayer(), - pending_layer); + pending_layer, layer_selection); } }
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h index ec84fdf..81ca77a 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" +#include "cc/input/layer_selection_bound.h" #include "cc/layers/content_layer_client.h" #include "cc/layers/layer_collections.h" #include "cc/layers/picture_layer.h" @@ -281,6 +282,7 @@ static void UpdateLayerProperties(cc::Layer&, const PendingLayer&, + cc::LayerSelection& layer_selection, PropertyTreeManager* = nullptr); void DecompositeTransforms();
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc index 13951f8..60210f2 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -7,6 +7,7 @@ #include "base/containers/adapters.h" #include "base/numerics/safe_conversions.h" #include "cc/base/features.h" +#include "cc/input/layer_selection_bound.h" #include "cc/layers/layer.h" #include "cc/paint/display_item_list.h" #include "cc/paint/paint_op_buffer.h" @@ -985,14 +986,75 @@ layer.SetNonFastScrollableRegion(std::move(non_fast_scrollable_region)); } +static gfx::Point MapSelectionBoundPoint(const IntPoint& point, + const PropertyTreeState& layer_state, + const PropertyTreeState& chunk_state, + const FloatPoint& layer_offset) { + FloatPoint mapped_point = + GeometryMapper::SourceToDestinationProjection(chunk_state.Transform(), + layer_state.Transform()) + .MapPoint(FloatPoint(point)); + + mapped_point.MoveBy(-layer_offset); + gfx::Point out_point(RoundedIntPoint(mapped_point)); + return out_point; +} + +static cc::LayerSelectionBound +ConvertPaintedSelectionBoundToLayerSelectionBound( + const PaintedSelectionBound& bound, + const PropertyTreeState& layer_state, + const PropertyTreeState& chunk_state, + const FloatPoint& layer_offset) { + cc::LayerSelectionBound layer_bound; + layer_bound.type = bound.type; + layer_bound.hidden = bound.hidden; + layer_bound.edge_start = MapSelectionBoundPoint(bound.edge_start, layer_state, + chunk_state, layer_offset); + layer_bound.edge_end = MapSelectionBoundPoint(bound.edge_end, layer_state, + chunk_state, layer_offset); + return layer_bound; +} + +static void UpdateLayerSelection(cc::Layer& layer, + const PropertyTreeState& layer_state, + const PaintChunkSubset& chunks, + cc::LayerSelection& layer_selection) { + gfx::Vector2dF cc_layer_offset = layer.offset_to_transform_parent(); + FloatPoint layer_offset(cc_layer_offset.x(), cc_layer_offset.y()); + for (const auto& chunk : chunks) { + if (!chunk.layer_selection_data) + continue; + + auto chunk_state = chunk.properties.GetPropertyTreeState().Unalias(); + if (chunk.layer_selection_data->start) { + const PaintedSelectionBound& bound = + chunk.layer_selection_data->start.value(); + layer_selection.start = ConvertPaintedSelectionBoundToLayerSelectionBound( + bound, layer_state, chunk_state, layer_offset); + layer_selection.start.layer_id = layer.id(); + } + + if (chunk.layer_selection_data->end) { + const PaintedSelectionBound& bound = + chunk.layer_selection_data->end.value(); + layer_selection.end = ConvertPaintedSelectionBoundToLayerSelectionBound( + bound, layer_state, chunk_state, layer_offset); + layer_selection.end.layer_id = layer.id(); + } + } +} + void PaintChunksToCcLayer::UpdateLayerProperties( cc::Layer& layer, const PropertyTreeState& layer_state, const PaintChunkSubset& chunks, + cc::LayerSelection& layer_selection, PropertyTreeManager* property_tree_manager) { UpdateBackgroundColor(layer, layer_state.Effect(), chunks); UpdateTouchActionWheelEventHandlerAndNonFastScrollableRegions( layer, layer_state, chunks, property_tree_manager); + UpdateLayerSelection(layer, layer_state, chunks, layer_selection); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.h b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.h index 5b311bb..4c95969 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.h +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_COMPOSITING_PAINT_CHUNKS_TO_CC_LAYER_H_ #include "base/memory/scoped_refptr.h" +#include "cc/input/layer_selection_bound.h" #include "cc/paint/display_item_list.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/platform_export.h" @@ -75,6 +76,7 @@ static void UpdateLayerProperties(cc::Layer& layer, const PropertyTreeState& layer_state, const PaintChunkSubset&, + cc::LayerSelection& layer_selection, PropertyTreeManager* = nullptr); };
diff --git a/third_party/blink/renderer/platform/graphics/paint/layer_selection_data.h b/third_party/blink/renderer/platform/graphics/paint/layer_selection_data.h new file mode 100644 index 0000000..7bc878f --- /dev/null +++ b/third_party/blink/renderer/platform/graphics/paint/layer_selection_data.h
@@ -0,0 +1,29 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_LAYER_SELECTION_DATA_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_LAYER_SELECTION_DATA_H_ + +#include "third_party/blink/renderer/platform/platform_export.h" + +#include "base/optional.h" +#include "third_party/blink/renderer/platform/graphics/paint/painted_selection_bound.h" + +namespace blink { + +// Represents paint-related metadata about the start and end of a selection. +// The information is stored on a paint chunk - note that the frame's selection +// can start in one paint chunk and end in another, so it's possible for one +// or both of the bounds to be set. The start and end can also be set +// independently by different painters within the same paint chunk. +// In the common case of no selection (or if the selection completely surrounds +// a paint chunk), neither would be set. +struct PLATFORM_EXPORT LayerSelectionData { + base::Optional<PaintedSelectionBound> start; + base::Optional<PaintedSelectionBound> end; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_LAYER_SELECTION_DATA_H_
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc index ef550343..7ad9c06 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc
@@ -20,6 +20,7 @@ IntRect bounds; IntRect drawable_bounds; void* hit_test_data; + void* layer_selection; bool b[2]; };
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h index d12dddb..d9fbc7e4 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item.h" #include "third_party/blink/renderer/platform/graphics/paint/hit_test_data.h" +#include "third_party/blink/renderer/platform/graphics/paint/layer_selection_data.h" #include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h" #include "third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h" #include "third_party/blink/renderer/platform/platform_export.h" @@ -54,6 +55,7 @@ id(other.id), properties(other.properties), hit_test_data(std::move(other.hit_test_data)), + layer_selection_data(std::move(other.layer_selection_data)), bounds(other.bounds), drawable_bounds(other.drawable_bounds), raster_effect_outset(other.raster_effect_outset), @@ -99,6 +101,12 @@ return *hit_test_data; } + LayerSelectionData& EnsureLayerSelectionData() { + if (!layer_selection_data) + layer_selection_data = std::make_unique<LayerSelectionData>(); + return *layer_selection_data; + } + size_t MemoryUsageInBytes() const; String ToString() const; @@ -126,6 +134,7 @@ RefCountedPropertyTreeState properties; std::unique_ptr<HitTestData> hit_test_data; + std::unique_ptr<LayerSelectionData> layer_selection_data; // The following fields depend on the display items in this chunk. // They are updated when a display item is added into the chunk.
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_chunker.cc b/third_party/blink/renderer/platform/graphics/paint/paint_chunker.cc index 2669abf..86ed6b9 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_chunker.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_chunker.cc
@@ -154,6 +154,39 @@ return created_new_chunk; } +void PaintChunker::AddSelectionToCurrentChunk( + base::Optional<PaintedSelectionBound> start, + base::Optional<PaintedSelectionBound> end) { + // We should have painted the selection when calling this method. + DCHECK(chunks_); + DCHECK(!chunks_->IsEmpty()); + + auto& chunk = chunks_->back(); + +#if DCHECK_IS_ON() + if (start) { + IntRect edge_rect(start->edge_start, start->edge_end - start->edge_start); + DCHECK(chunk.bounds.Contains(edge_rect)); + } + + if (end) { + IntRect edge_rect(end->edge_start, end->edge_end - end->edge_start); + DCHECK(chunk.bounds.Contains(edge_rect)); + } +#endif + + LayerSelectionData& selection_data = chunk.EnsureLayerSelectionData(); + if (start) { + DCHECK(!selection_data.start); + selection_data.start = start; + } + + if (end) { + DCHECK(!selection_data.end); + selection_data.end = end; + } +} + void PaintChunker::CreateScrollHitTestChunk( const PaintChunk::Id& id, const TransformPaintPropertyNode* scroll_translation,
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h b/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h index 08ba2df..1ceb470 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/optional.h" +#include "cc/input/layer_selection_bound.h" #include "third_party/blink/renderer/platform/geometry/region.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_artifact.h" @@ -68,6 +69,11 @@ const TransformPaintPropertyNode* scroll_translation, const IntRect&); + // The id will be used when we need to create a new current chunk. + // Otherwise it's ignored. Returns true if a new chunk is added. + void AddSelectionToCurrentChunk(base::Optional<PaintedSelectionBound> start, + base::Optional<PaintedSelectionBound> end); + // Returns true if a new chunk is created. bool ProcessBackgroundColorCandidate(const PaintChunk::Id& id, Color color,
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc index f609678..af34053 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
@@ -79,6 +79,14 @@ CheckNewChunk(); } +void PaintController::RecordSelection( + base::Optional<PaintedSelectionBound> start, + base::Optional<PaintedSelectionBound> end) { + DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled()); + DCHECK(start.has_value() || end.has_value()); + paint_chunker_.AddSelectionToCurrentChunk(start, end); +} + void PaintController::SetPossibleBackgroundColor( const DisplayItemClient& client, Color color,
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller.h b/third_party/blink/renderer/platform/graphics/paint/paint_controller.h index ce9172be..78de6fe 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller.h
@@ -10,6 +10,8 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/optional.h" +#include "cc/input/layer_selection_bound.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/layout_point.h" #include "third_party/blink/renderer/platform/graphics/contiguous_container.h" @@ -109,6 +111,10 @@ DisplayItem::Type, const TransformPaintPropertyNode* scroll_translation, const IntRect&); + + void RecordSelection(base::Optional<PaintedSelectionBound> start, + base::Optional<PaintedSelectionBound> end); + void SetPossibleBackgroundColor(const DisplayItemClient&, Color, uint64_t area);
diff --git a/third_party/blink/renderer/platform/graphics/paint/painted_selection_bound.h b/third_party/blink/renderer/platform/graphics/paint/painted_selection_bound.h new file mode 100644 index 0000000..b881dbb0 --- /dev/null +++ b/third_party/blink/renderer/platform/graphics/paint/painted_selection_bound.h
@@ -0,0 +1,29 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINTED_SELECTION_BOUND_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINTED_SELECTION_BOUND_H_ + +#include "third_party/blink/renderer/platform/platform_export.h" + +#include "third_party/blink/renderer/platform/geometry/float_point.h" +#include "ui/gfx/selection_bound.h" + +namespace blink { + +// Blink's notion of cc::LayerSelectionBound. Note that the points are IntPoints +// to match the painted selection rect, which is always pixel aligned. +// There is also no layer_id as that is determined at composition time. +struct PLATFORM_EXPORT PaintedSelectionBound { + gfx::SelectionBound::Type type; + IntPoint edge_start; + IntPoint edge_end; + // Whether this bound is hidden (clipped out/occluded) within the painted + // content of the layer (as opposed to being outside of the layer's bounds). + bool hidden; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINTED_SELECTION_BOUND_H_
diff --git a/third_party/blink/renderer/platform/loader/BUILD.gn b/third_party/blink/renderer/platform/loader/BUILD.gn index 85cfd35..63be258 100644 --- a/third_party/blink/renderer/platform/loader/BUILD.gn +++ b/third_party/blink/renderer/platform/loader/BUILD.gn
@@ -118,6 +118,7 @@ "fetch/unique_identifier.h", "fetch/url_loader/request_conversion.cc", "fetch/url_loader/request_conversion.h", + "fetch/url_loader/web_mojo_url_loader_client.cc", "fetch/url_loader/worker_main_script_loader.cc", "fetch/url_loader/worker_main_script_loader.h", "fetch/url_loader/worker_main_script_loader_client.h", @@ -195,6 +196,7 @@ "link_header_test.cc", "static_data_navigation_body_loader_test.cc", "subresource_integrity_test.cc", + "web_mojo_url_loader_client_unittest.cc", ] configs += [ "//third_party/blink/renderer/platform:blink_platform_config" ]
diff --git a/third_party/blink/renderer/platform/loader/DEPS b/third_party/blink/renderer/platform/loader/DEPS index 52019c0..3108f95 100644 --- a/third_party/blink/renderer/platform/loader/DEPS +++ b/third_party/blink/renderer/platform/loader/DEPS
@@ -11,6 +11,8 @@ "+components/link_header_util", # for LinkHeader.cpp "+net/base/load_flags.h", "+net/base/net_errors.h", + "+net/traffic_annotation/network_traffic_annotation_test_helper.h", + "+net/url_request/redirect_info.h", "+services/metrics/public", # for UKM API "+services/network/public", # for Fetch API and CORS "+third_party/blink/renderer/platform/bindings/dom_wrapper_world.h",
diff --git a/content/renderer/loader/url_loader_client_impl.cc b/third_party/blink/renderer/platform/loader/fetch/url_loader/web_mojo_url_loader_client.cc similarity index 71% rename from content/renderer/loader/url_loader_client_impl.cc rename to third_party/blink/renderer/platform/loader/fetch/url_loader/web_mojo_url_loader_client.cc index afdfc4f..086fd9a8 100644 --- a/content/renderer/loader/url_loader_client_impl.cc +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/web_mojo_url_loader_client.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/loader/url_loader_client_impl.h" +#include "third_party/blink/public/platform/web_mojo_url_loader_client.h" #include <iterator> @@ -11,34 +11,27 @@ #include "base/feature_list.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" -#include "content/public/common/url_utils.h" -#include "content/public/renderer/content_renderer_client.h" -#include "content/renderer/loader/resource_dispatcher.h" #include "mojo/public/cpp/system/data_pipe_drainer.h" #include "net/url_request/redirect_info.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/platform/web_mojo_url_loader_client_observer.h" -namespace content { +namespace blink { namespace { constexpr size_t kDefaultMaxBufferedBodyBytes = 100 * 1000; -// Determines whether it is safe to redirect from |from_url| to |to_url|. -bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) { - return IsSafeRedirectTarget(from_url, to_url) && - (!GetContentClient()->renderer() || // null in unit tests. - GetContentClient()->renderer()->IsSafeRedirectTarget(to_url)); -} - } // namespace -class URLLoaderClientImpl::DeferredMessage { +class WebMojoURLLoaderClient::DeferredMessage { public: DeferredMessage() = default; - virtual void HandleMessage(ResourceDispatcher* dispatcher, - int request_id) = 0; + virtual void HandleMessage( + WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) = 0; virtual bool IsCompletionMessage() const = 0; virtual ~DeferredMessage() = default; @@ -46,15 +39,17 @@ DISALLOW_COPY_AND_ASSIGN(DeferredMessage); }; -class URLLoaderClientImpl::DeferredOnReceiveResponse final +class WebMojoURLLoaderClient::DeferredOnReceiveResponse final : public DeferredMessage { public: explicit DeferredOnReceiveResponse( network::mojom::URLResponseHeadPtr response_head) : response_head_(std::move(response_head)) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnReceivedResponse(request_id, std::move(response_head_)); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnReceivedResponse(request_id, + std::move(response_head_)); } bool IsCompletionMessage() const override { return false; } @@ -62,7 +57,7 @@ network::mojom::URLResponseHeadPtr response_head_; }; -class URLLoaderClientImpl::DeferredOnReceiveRedirect final +class WebMojoURLLoaderClient::DeferredOnReceiveRedirect final : public DeferredMessage { public: DeferredOnReceiveRedirect( @@ -73,9 +68,10 @@ response_head_(std::move(response_head)), task_runner_(std::move(task_runner)) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnReceivedRedirect(request_id, redirect_info_, - std::move(response_head_), task_runner_); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnReceivedRedirect( + request_id, redirect_info_, std::move(response_head_), task_runner_); } bool IsCompletionMessage() const override { return false; } @@ -85,14 +81,15 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; -class URLLoaderClientImpl::DeferredOnUploadProgress final +class WebMojoURLLoaderClient::DeferredOnUploadProgress final : public DeferredMessage { public: DeferredOnUploadProgress(int64_t current, int64_t total) : current_(current), total_(total) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnUploadProgress(request_id, current_, total_); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnUploadProgress(request_id, current_, total_); } bool IsCompletionMessage() const override { return false; } @@ -101,14 +98,16 @@ const int64_t total_; }; -class URLLoaderClientImpl::DeferredOnReceiveCachedMetadata final +class WebMojoURLLoaderClient::DeferredOnReceiveCachedMetadata final : public DeferredMessage { public: explicit DeferredOnReceiveCachedMetadata(mojo_base::BigBuffer data) : data_(std::move(data)) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnReceivedCachedMetadata(request_id, std::move(data_)); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnReceivedCachedMetadata(request_id, + std::move(data_)); } bool IsCompletionMessage() const override { return false; } @@ -116,15 +115,17 @@ mojo_base::BigBuffer data_; }; -class URLLoaderClientImpl::DeferredOnStartLoadingResponseBody final +class WebMojoURLLoaderClient::DeferredOnStartLoadingResponseBody final : public DeferredMessage { public: explicit DeferredOnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) : body_(std::move(body)) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnStartLoadingResponseBody(request_id, std::move(body_)); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnStartLoadingResponseBody(request_id, + std::move(body_)); } bool IsCompletionMessage() const override { return false; } @@ -132,13 +133,15 @@ mojo::ScopedDataPipeConsumerHandle body_; }; -class URLLoaderClientImpl::DeferredOnComplete final : public DeferredMessage { +class WebMojoURLLoaderClient::DeferredOnComplete final + : public DeferredMessage { public: explicit DeferredOnComplete(const network::URLLoaderCompletionStatus& status) : status_(status) {} - void HandleMessage(ResourceDispatcher* dispatcher, int request_id) override { - dispatcher->OnRequestComplete(request_id, status_); + void HandleMessage(WebMojoURLLoaderClientObserver* url_loader_client_observer, + int request_id) override { + url_loader_client_observer->OnRequestComplete(request_id, status_); } bool IsCompletionMessage() const override { return true; } @@ -146,10 +149,10 @@ const network::URLLoaderCompletionStatus status_; }; -class URLLoaderClientImpl::BodyBuffer final +class WebMojoURLLoaderClient::BodyBuffer final : public mojo::DataPipeDrainer::Client { public: - BodyBuffer(URLLoaderClientImpl* owner, + BodyBuffer(WebMojoURLLoaderClient* owner, mojo::ScopedDataPipeConsumerHandle readable, mojo::ScopedDataPipeProducerHandle writable, scoped_refptr<base::SingleThreadTaskRunner> task_runner) @@ -251,11 +254,11 @@ writable_.reset(); // There might be a deferred OnComplete message waiting for us to finish // draining the response body, so flush the deferred messages in - // the owner URLLoaderClientImpl. + // the owner WebMojoURLLoaderClient. owner_->FlushDeferredMessages(); } - URLLoaderClientImpl* const owner_; + WebMojoURLLoaderClient* const owner_; mojo::ScopedDataPipeProducerHandle writable_; mojo::SimpleWatcher writable_watcher_; std::unique_ptr<mojo::DataPipeDrainer> pipe_drainer_; @@ -268,109 +271,33 @@ bool draining_ = true; }; -URLLoaderClientImpl::URLLoaderClientImpl( +WebMojoURLLoaderClient::WebMojoURLLoaderClient( int request_id, - ResourceDispatcher* resource_dispatcher, + WebMojoURLLoaderClientObserver* url_loader_client_observer, scoped_refptr<base::SingleThreadTaskRunner> task_runner, bool bypass_redirect_checks, const GURL& request_url) : request_id_(request_id), - resource_dispatcher_(resource_dispatcher), + url_loader_client_observer_(url_loader_client_observer), task_runner_(std::move(task_runner)), bypass_redirect_checks_(bypass_redirect_checks), last_loaded_url_(request_url) {} -URLLoaderClientImpl::~URLLoaderClientImpl() = default; +WebMojoURLLoaderClient::~WebMojoURLLoaderClient() = default; -void URLLoaderClientImpl::SetDefersLoading( - blink::WebURLLoader::DeferType value) { +void WebMojoURLLoaderClient::SetDefersLoading(WebURLLoader::DeferType value) { deferred_state_ = value; - if (value == blink::WebURLLoader::DeferType::kNotDeferred) { + if (value == WebURLLoader::DeferType::kNotDeferred) { task_runner_->PostTask( - FROM_HERE, base::BindOnce(&URLLoaderClientImpl::FlushDeferredMessages, - weak_factory_.GetWeakPtr())); + FROM_HERE, + base::BindOnce(&WebMojoURLLoaderClient::FlushDeferredMessages, + weak_factory_.GetWeakPtr())); } } -void URLLoaderClientImpl::FlushDeferredMessages() { - if (deferred_state_ != blink::WebURLLoader::DeferType::kNotDeferred) - return; - std::vector<std::unique_ptr<DeferredMessage>> messages; - messages.swap(deferred_messages_); - bool has_completion_message = false; - base::WeakPtr<URLLoaderClientImpl> weak_this = weak_factory_.GetWeakPtr(); - // First, dispatch all messages excluding the followings: - // - transfer size change - // - completion - // These two types of messages are dispatched later. - for (size_t index = 0; index < messages.size(); ++index) { - if (messages[index]->IsCompletionMessage()) { - // The completion message arrives at the end of the message queue. - DCHECK(!has_completion_message); - DCHECK_EQ(index, messages.size() - 1); - has_completion_message = true; - break; - } - - messages[index]->HandleMessage(resource_dispatcher_, request_id_); - if (!weak_this) - return; - if (deferred_state_ != blink::WebURLLoader::DeferType::kNotDeferred) { - deferred_messages_.insert( - deferred_messages_.begin(), - std::make_move_iterator(messages.begin()) + index + 1, - std::make_move_iterator(messages.end())); - return; - } - } - - // Dispatch the transfer size update. - if (accumulated_transfer_size_diff_during_deferred_ > 0) { - auto transfer_size_diff = accumulated_transfer_size_diff_during_deferred_; - accumulated_transfer_size_diff_during_deferred_ = 0; - resource_dispatcher_->OnTransferSizeUpdated(request_id_, - transfer_size_diff); - if (!weak_this) - return; - if (deferred_state_ != blink::WebURLLoader::DeferType::kNotDeferred) { - if (has_completion_message) { - DCHECK_GT(messages.size(), 0u); - DCHECK(messages.back()->IsCompletionMessage()); - deferred_messages_.emplace_back(std::move(messages.back())); - } - return; - } - } - - // Dispatch the completion message. - if (has_completion_message) { - DCHECK_GT(messages.size(), 0u); - DCHECK(messages.back()->IsCompletionMessage()); - if (body_buffer_ && body_buffer_->active()) { - // If we still have an active body buffer, it means we haven't drained all - // of the contents of the response body yet. We shouldn't dispatch the - // completion message now, so - // put the message back into |deferred_messages_| to be sent later after - // the body buffer is no longer active. - deferred_messages_.emplace_back(std::move(messages.back())); - return; - } - messages.back()->HandleMessage(resource_dispatcher_, request_id_); - } -} - -void URLLoaderClientImpl::Bind( - network::mojom::URLLoaderClientEndpointsPtr endpoints) { - url_loader_.Bind(std::move(endpoints->url_loader), task_runner_); - url_loader_client_receiver_.Bind(std::move(endpoints->url_loader_client), - task_runner_); - url_loader_client_receiver_.set_disconnect_handler(base::BindOnce( - &URLLoaderClientImpl::OnConnectionClosed, weak_factory_.GetWeakPtr())); -} - -void URLLoaderClientImpl::OnReceiveResponse( +void WebMojoURLLoaderClient::OnReceiveResponse( network::mojom::URLResponseHeadPtr response_head) { - TRACE_EVENT1("loading", "URLLoaderClientImpl::OnReceiveResponse", "url", + TRACE_EVENT1("loading", "WebMojoURLLoaderClient::OnReceiveResponse", "url", last_loaded_url_.possibly_invalid_spec()); has_received_response_head_ = true; @@ -380,15 +307,15 @@ StoreAndDispatch( std::make_unique<DeferredOnReceiveResponse>(std::move(response_head))); } else { - resource_dispatcher_->OnReceivedResponse(request_id_, - std::move(response_head)); + url_loader_client_observer_->OnReceivedResponse(request_id_, + std::move(response_head)); } } -void URLLoaderClientImpl::EvictFromBackForwardCache() { - resource_dispatcher_->EvictFromBackForwardCache(request_id_); +void WebMojoURLLoaderClient::EvictFromBackForwardCache() { + url_loader_client_observer_->EvictFromBackForwardCache(request_id_); } -void URLLoaderClientImpl::OnReceiveRedirect( +void WebMojoURLLoaderClient::OnReceiveRedirect( const net::RedirectInfo& redirect_info, network::mojom::URLResponseHeadPtr response_head) { DCHECK(!has_received_response_head_); @@ -402,7 +329,8 @@ return; } if (!bypass_redirect_checks_ && - !IsRedirectSafe(last_loaded_url_, redirect_info.new_url)) { + !Platform::Current()->IsRedirectSafe(last_loaded_url_, + redirect_info.new_url)) { OnComplete(network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT)); return; } @@ -412,12 +340,12 @@ StoreAndDispatch(std::make_unique<DeferredOnReceiveRedirect>( redirect_info, std::move(response_head), task_runner_)); } else { - resource_dispatcher_->OnReceivedRedirect( + url_loader_client_observer_->OnReceivedRedirect( request_id_, redirect_info, std::move(response_head), task_runner_); } } -void URLLoaderClientImpl::OnUploadProgress( +void WebMojoURLLoaderClient::OnUploadProgress( int64_t current_position, int64_t total_size, OnUploadProgressCallback ack_callback) { @@ -425,34 +353,35 @@ StoreAndDispatch(std::make_unique<DeferredOnUploadProgress>( current_position, total_size)); } else { - resource_dispatcher_->OnUploadProgress(request_id_, current_position, - total_size); + url_loader_client_observer_->OnUploadProgress(request_id_, current_position, + total_size); } std::move(ack_callback).Run(); } -void URLLoaderClientImpl::OnReceiveCachedMetadata(mojo_base::BigBuffer data) { +void WebMojoURLLoaderClient::OnReceiveCachedMetadata( + mojo_base::BigBuffer data) { if (NeedsStoringMessage()) { StoreAndDispatch( std::make_unique<DeferredOnReceiveCachedMetadata>(std::move(data))); } else { - resource_dispatcher_->OnReceivedCachedMetadata(request_id_, - std::move(data)); + url_loader_client_observer_->OnReceivedCachedMetadata(request_id_, + std::move(data)); } } -void URLLoaderClientImpl::OnTransferSizeUpdated(int32_t transfer_size_diff) { +void WebMojoURLLoaderClient::OnTransferSizeUpdated(int32_t transfer_size_diff) { if (NeedsStoringMessage()) { accumulated_transfer_size_diff_during_deferred_ += transfer_size_diff; } else { - resource_dispatcher_->OnTransferSizeUpdated(request_id_, - transfer_size_diff); + url_loader_client_observer_->OnTransferSizeUpdated(request_id_, + transfer_size_diff); } } -void URLLoaderClientImpl::OnStartLoadingResponseBody( +void WebMojoURLLoaderClient::OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) { - TRACE_EVENT1("loading", "URLLoaderClientImpl::OnStartLoadingResponseBody", + TRACE_EVENT1("loading", "WebMojoURLLoaderClient::OnStartLoadingResponseBody", "url", last_loaded_url_.possibly_invalid_spec()); DCHECK(has_received_response_head_); @@ -467,8 +396,8 @@ if (!NeedsStoringMessage()) { // Send the message immediately. - resource_dispatcher_->OnStartLoadingResponseBody(request_id_, - std::move(body)); + url_loader_client_observer_->OnStartLoadingResponseBody(request_id_, + std::move(body)); return; } @@ -506,30 +435,30 @@ std::move(new_body_consumer))); } -void URLLoaderClientImpl::OnComplete( +void WebMojoURLLoaderClient::OnComplete( const network::URLLoaderCompletionStatus& status) { has_received_complete_ = true; - // Dispatch completion status to the ResourceDispatcher. + // Dispatch completion status to the WebMojoURLLoaderClientObserver. // Except for errors, there must always be a response's body. DCHECK(has_received_response_body_ || status.error_code != net::OK); if (NeedsStoringMessage()) { StoreAndDispatch(std::make_unique<DeferredOnComplete>(status)); } else { - resource_dispatcher_->OnRequestComplete(request_id_, status); + url_loader_client_observer_->OnRequestComplete(request_id_, status); } } -bool URLLoaderClientImpl::NeedsStoringMessage() const { - return deferred_state_ != blink::WebURLLoader::DeferType::kNotDeferred || +bool WebMojoURLLoaderClient::NeedsStoringMessage() const { + return deferred_state_ != WebURLLoader::DeferType::kNotDeferred || deferred_messages_.size() > 0 || accumulated_transfer_size_diff_during_deferred_ > 0; } -void URLLoaderClientImpl::StoreAndDispatch( +void WebMojoURLLoaderClient::StoreAndDispatch( std::unique_ptr<DeferredMessage> message) { DCHECK(NeedsStoringMessage()); - if (deferred_state_ != blink::WebURLLoader::DeferType::kNotDeferred) { + if (deferred_state_ != WebURLLoader::DeferType::kNotDeferred) { deferred_messages_.push_back(std::move(message)); } else if (deferred_messages_.size() > 0 || accumulated_transfer_size_diff_during_deferred_ > 0) { @@ -540,7 +469,7 @@ } } -void URLLoaderClientImpl::OnConnectionClosed() { +void WebMojoURLLoaderClient::OnConnectionClosed() { // If the connection aborts before the load completes, mark it as aborted. if (!has_received_complete_) { OnComplete(network::URLLoaderCompletionStatus(net::ERR_ABORTED)); @@ -548,4 +477,71 @@ } } -} // namespace content +void WebMojoURLLoaderClient::FlushDeferredMessages() { + if (deferred_state_ != WebURLLoader::DeferType::kNotDeferred) + return; + std::vector<std::unique_ptr<DeferredMessage>> messages; + messages.swap(deferred_messages_); + bool has_completion_message = false; + base::WeakPtr<WebMojoURLLoaderClient> weak_this = weak_factory_.GetWeakPtr(); + // First, dispatch all messages excluding the followings: + // - transfer size change + // - completion + // These two types of messages are dispatched later. + for (size_t index = 0; index < messages.size(); ++index) { + if (messages[index]->IsCompletionMessage()) { + // The completion message arrives at the end of the message queue. + DCHECK(!has_completion_message); + DCHECK_EQ(index, messages.size() - 1); + has_completion_message = true; + break; + } + + messages[index]->HandleMessage(url_loader_client_observer_, request_id_); + if (!weak_this) + return; + if (deferred_state_ != WebURLLoader::DeferType::kNotDeferred) { + deferred_messages_.insert( + deferred_messages_.begin(), + std::make_move_iterator(messages.begin()) + index + 1, + std::make_move_iterator(messages.end())); + return; + } + } + + // Dispatch the transfer size update. + if (accumulated_transfer_size_diff_during_deferred_ > 0) { + auto transfer_size_diff = accumulated_transfer_size_diff_during_deferred_; + accumulated_transfer_size_diff_during_deferred_ = 0; + url_loader_client_observer_->OnTransferSizeUpdated(request_id_, + transfer_size_diff); + if (!weak_this) + return; + if (deferred_state_ != WebURLLoader::DeferType::kNotDeferred) { + if (has_completion_message) { + DCHECK_GT(messages.size(), 0u); + DCHECK(messages.back()->IsCompletionMessage()); + deferred_messages_.emplace_back(std::move(messages.back())); + } + return; + } + } + + // Dispatch the completion message. + if (has_completion_message) { + DCHECK_GT(messages.size(), 0u); + DCHECK(messages.back()->IsCompletionMessage()); + if (body_buffer_ && body_buffer_->active()) { + // If we still have an active body buffer, it means we haven't drained all + // of the contents of the response body yet. We shouldn't dispatch the + // completion message now, so + // put the message back into |deferred_messages_| to be sent later after + // the body buffer is no longer active. + deferred_messages_.emplace_back(std::move(messages.back())); + return; + } + messages.back()->HandleMessage(url_loader_client_observer_, request_id_); + } +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/loader/web_mojo_url_loader_client_unittest.cc b/third_party/blink/renderer/platform/loader/web_mojo_url_loader_client_unittest.cc new file mode 100644 index 0000000..6430d05 --- /dev/null +++ b/third_party/blink/renderer/platform/loader/web_mojo_url_loader_client_unittest.cc
@@ -0,0 +1,891 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/public/platform/web_mojo_url_loader_client.h" + +#include <vector> +#include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/task_environment.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/redirect_info.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/loader/throttling_url_loader.h" +#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" +#include "third_party/blink/public/platform/resource_load_info_notifier_wrapper.h" +#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" +#include "third_party/blink/public/platform/web_mojo_url_loader_client_observer.h" +#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" + +namespace blink { + +namespace { + +constexpr size_t kDataPipeCapacity = 4096; + +class MockWebURLLoaderClientObserver + : public blink::WebMojoURLLoaderClientObserver { + public: + struct Context; + MockWebURLLoaderClientObserver() : context_(new Context()) {} + ~MockWebURLLoaderClientObserver() override = default; + + void OnUploadProgress(int request_id, + int64_t position, + int64_t size) override { + EXPECT_FALSE(context_->complete); + } + + void OnReceivedRedirect( + int request_id, + const net::RedirectInfo& redirect_info, + network::mojom::URLResponseHeadPtr head, + scoped_refptr<base::SingleThreadTaskRunner> task_runner) override { + EXPECT_FALSE(context_->cancelled); + EXPECT_FALSE(context_->complete); + ++context_->seen_redirects; + context_->last_load_timing = head->load_timing; + if (context_->defer_on_redirect) { + context_->url_laoder_client->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferred); + } + } + + void OnReceivedResponse(int request_id, + network::mojom::URLResponseHeadPtr head) override { + EXPECT_FALSE(context_->cancelled); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + context_->received_response = true; + context_->last_load_timing = head->load_timing; + if (context_->cancel_on_receive_response) + context_->cancelled = true; + } + + void OnStartLoadingResponseBody( + int request_id, + mojo::ScopedDataPipeConsumerHandle body) override { + if (context_->cancelled) + return; + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + context_->body_handle = std::move(body); + } + + void OnTransferSizeUpdated(int request_id, int transfer_size_diff) override { + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + if (context_->cancelled) + return; + context_->total_encoded_data_length += transfer_size_diff; + if (context_->defer_on_transfer_size_updated) { + context_->url_laoder_client->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferred); + } + } + + void OnReceivedCachedMetadata(int request_id, + mojo_base::BigBuffer data) override { + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + if (context_->cancelled) + return; + context_->cached_metadata = std::move(data); + } + + void OnRequestComplete( + int request_id, + const network::URLLoaderCompletionStatus& status) override { + if (context_->cancelled) + return; + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + context_->complete = true; + context_->completion_status = status; + } + + void EvictFromBackForwardCache(int request_id) override {} + + Context* context() { return context_.get(); } + + struct Context final { + Context() = default; + ~Context() = default; + Context(const Context&) = delete; + Context& operator=(const Context&) = delete; + + // True if should follow redirects, false if should cancel them. + bool follow_redirects = true; + // True if the request should be deferred on redirects. + bool defer_on_redirect = false; + + // Number of total redirects seen. + int seen_redirects = 0; + + bool cancel_on_receive_response = false; + bool cancel_on_receive_data = false; + bool received_response = false; + + mojo_base::BigBuffer cached_metadata; + // Data received. If downloading to file, remains empty. + std::string data; + + // Mojo's data pipe passed on OnStartLoadingResponseBody. + mojo::ScopedDataPipeConsumerHandle body_handle; + + // Total encoded data length, regardless of whether downloading to a file or + // not. + int total_encoded_data_length = 0; + bool defer_on_transfer_size_updated = false; + + bool complete = false; + bool cancelled = false; + int request_id = -1; + + net::LoadTimingInfo last_load_timing; + network::URLLoaderCompletionStatus completion_status; + WebMojoURLLoaderClient* url_laoder_client; + }; + + private: + std::unique_ptr<Context> context_; +}; + +std::string ReadOneChunk(mojo::ScopedDataPipeConsumerHandle* handle) { + char buffer[kDataPipeCapacity]; + uint32_t read_bytes = kDataPipeCapacity; + MojoResult result = + (*handle)->ReadData(buffer, &read_bytes, MOJO_READ_DATA_FLAG_NONE); + if (result != MOJO_RESULT_OK) + return ""; + return std::string(buffer, read_bytes); +} + +std::string GetRequestPeerContextBody( + MockWebURLLoaderClientObserver::Context* context) { + if (context->body_handle) { + context->data += ReadOneChunk(&context->body_handle); + } + return context->data; +} + +} // namespace + +class WebMojoURLLoaderClientTest : public ::testing::Test, + public network::mojom::URLLoaderFactory, + public ::testing::WithParamInterface<bool> { + protected: + WebMojoURLLoaderClientTest() + : url_loader_client_observer_(new MockWebURLLoaderClientObserver()) { + if (DeferWithBackForwardCacheEnabled()) { + scoped_feature_list_.InitAndEnableFeature( + blink::features::kLoadingTasksUnfreezable); + } + + auto url_loader_factory = + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(this); + auto request = std::make_unique<network::ResourceRequest>(); + auto loading_task_runner = + blink::scheduler::GetSingleThreadTaskRunnerForTesting(); + + client_ = std::make_unique<WebMojoURLLoaderClient>( + request_id_, url_loader_client_observer_.get(), loading_task_runner, + url_loader_factory->BypassRedirectChecks(), request->url); + context_ = url_loader_client_observer_->context(); + context_->url_laoder_client = client_.get(); + url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart( + std::move(url_loader_factory), + std::vector<std::unique_ptr<blink::URLLoaderThrottle>>(), + /*routing_id=*/0, request_id_, /*loader_options=0*/ 0, request.get(), + client_.get(), TRAFFIC_ANNOTATION_FOR_TESTS, + std::move(loading_task_runner), + base::make_optional(std::vector<std::string>())); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(url_loader_client_); + } + + bool DeferWithBackForwardCacheEnabled() { return GetParam(); } + + void TearDown() override { url_loader_client_.reset(); } + + void CreateLoaderAndStart( + mojo::PendingReceiver<network::mojom::URLLoader> receiver, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& url_request, + mojo::PendingRemote<network::mojom::URLLoaderClient> client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) + override { + url_loader_client_.Bind(std::move(client)); + } + + void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) + override { + NOTREACHED(); + } + + static MojoCreateDataPipeOptions DataPipeOptions() { + MojoCreateDataPipeOptions options; + options.struct_size = sizeof(MojoCreateDataPipeOptions); + options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; + options.element_num_bytes = 1; + options.capacity_num_bytes = kDataPipeCapacity; + return options; + } + + class TestPlatform final : public TestingPlatformSupport { + public: + bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) override { + return true; + } + }; + + base::test::SingleThreadTaskEnvironment task_environment_; + ScopedTestingPlatformSupport<TestPlatform> platform_; + base::test::ScopedFeatureList scoped_feature_list_; + std::unique_ptr<ThrottlingURLLoader> url_loader_; + std::unique_ptr<WebMojoURLLoaderClient> client_; + std::unique_ptr<MockWebURLLoaderClientObserver> url_loader_client_observer_; + MockWebURLLoaderClientObserver::Context* context_; + int request_id_ = 0; + mojo::Remote<network::mojom::URLLoaderClient> url_loader_client_; +}; + +TEST_P(WebMojoURLLoaderClientTest, OnReceiveResponse) { + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + + EXPECT_FALSE(context_->received_response); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); +} + +TEST_P(WebMojoURLLoaderClientTest, ResponseBody) { + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + + EXPECT_FALSE(context_->received_response); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + uint32_t size = 5; + MojoResult result = + data_pipe_producer->WriteData("hello", &size, MOJO_WRITE_DATA_FLAG_NONE); + ASSERT_EQ(MOJO_RESULT_OK, result); + EXPECT_EQ(5u, size); + + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, OnReceiveRedirect) { + net::RedirectInfo redirect_info; + + url_loader_client_->OnReceiveRedirect(redirect_info, + network::mojom::URLResponseHead::New()); + + EXPECT_EQ(0, context_->seen_redirects); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, context_->seen_redirects); +} + +TEST_P(WebMojoURLLoaderClientTest, OnReceiveCachedMetadata) { + std::vector<uint8_t> data; + data.push_back('a'); + mojo_base::BigBuffer metadata(data); + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + url_loader_client_->OnReceiveCachedMetadata(std::move(metadata)); + + EXPECT_FALSE(context_->received_response); + EXPECT_EQ(0u, context_->cached_metadata.size()); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + ASSERT_EQ(1u, context_->cached_metadata.size()); + EXPECT_EQ('a', context_->cached_metadata.data()[0]); +} + +TEST_P(WebMojoURLLoaderClientTest, OnTransferSizeUpdated) { + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + url_loader_client_->OnTransferSizeUpdated(4); + url_loader_client_->OnTransferSizeUpdated(4); + + EXPECT_FALSE(context_->received_response); + EXPECT_EQ(0, context_->total_encoded_data_length); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_EQ(8, context_->total_encoded_data_length); +} + +TEST_P(WebMojoURLLoaderClientTest, OnCompleteWithResponseBody) { + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + uint32_t size = 5; + MojoResult result = + data_pipe_producer->WriteData("hello", &size, MOJO_WRITE_DATA_FLAG_NONE); + ASSERT_EQ(MOJO_RESULT_OK, result); + EXPECT_EQ(5u, size); + data_pipe_producer.reset(); + + EXPECT_FALSE(context_->received_response); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->complete); + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(context_->received_response); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + EXPECT_TRUE(context_->complete); +} + +// Due to the lack of ordering guarantee, it is possible that the response body +// bytes arrives after the completion message. URLLoaderClientImpl should +// restore the order. +TEST_P(WebMojoURLLoaderClientTest, OnCompleteShouldBeTheLastMessage) { + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnComplete(status); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + + uint32_t size = 5; + MojoResult result = + data_pipe_producer->WriteData("hello", &size, MOJO_WRITE_DATA_FLAG_NONE); + ASSERT_EQ(MOJO_RESULT_OK, result); + EXPECT_EQ(5u, size); + + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, CancelOnReceiveResponse) { + context_->cancel_on_receive_response = true; + + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_FALSE(context_->cancelled); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_TRUE(context_->cancelled); +} + +TEST_P(WebMojoURLLoaderClientTest, Defer) { + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + data_pipe_producer.reset(); // Empty body. + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); +} + +TEST_P(WebMojoURLLoaderClientTest, DeferWithResponseBody) { + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + std::string msg1 = "hello"; + uint32_t size = msg1.size(); + ASSERT_EQ(MOJO_RESULT_OK, data_pipe_producer->WriteData( + msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg1.size(), size); + data_pipe_producer.reset(); + + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, + DeferredAndDeferredWithBackForwardCacheTransitions) { + if (!DeferWithBackForwardCacheEnabled()) + return; + // Call OnReceiveResponse and OnStartLoadingResponseBody while + // deferred (not for back-forward cache). + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(MOJO_RESULT_OK, + mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); + url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Write data to the response body pipe. + std::string msg1 = "he"; + uint32_t size = msg1.size(); + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg1.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Defer for back-forward cache. + client_->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); + std::string msg2 = "ll"; + size = msg2.size(); + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg2.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg2.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Defer not for back-forward cache again. + client_->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); + std::string msg3 = "o"; + size = msg3.size(); + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg3.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg3.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Stop deferring. + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + + // Write more data to the pipe while not deferred. + std::string msg4 = "world"; + size = msg4.size(); + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg4.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg4.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("helloworld", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, + DeferredWithBackForwardCacheStoppedDeferringBeforeClosing) { + if (!DeferWithBackForwardCacheEnabled()) + return; + // Call OnReceiveResponse, OnStartLoadingResponseBody, OnComplete while + // deferred. + client_->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(MOJO_RESULT_OK, + mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); + url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); + network::URLLoaderCompletionStatus status; + url_loader_client_->OnComplete(status); + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Write data to the response body pipe, but don't close the connection yet. + std::string msg1 = "hello"; + uint32_t size = msg1.size(); + // We expect that the other end of the pipe to be ready to read the data + // immediately. + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg1.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Stop deferring. OnComplete message shouldn't be dispatched yet because + // we're still waiting for the response body pipe to be closed. + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + // When the body is buffered, we'll wait until the pipe is closed before + // sending the OnComplete message. + EXPECT_FALSE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + + // Write more data to the pipe while not deferred. + std::string msg2 = "world"; + size = msg2.size(); + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg2.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg2.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("helloworld", GetRequestPeerContextBody(context_)); + + // Close the response body pipe. + producer_handle.reset(); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + EXPECT_EQ("helloworld", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, DeferBodyWithoutOnComplete) { + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + // Call OnStartLoadingResponseBody while deferred. + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(MOJO_RESULT_OK, + mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); + url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Write data to the response body pipe, but don't close the connection yet. + std::string msg1 = "hello"; + uint32_t size = msg1.size(); + // We expect that the other end of the pipe to be ready to read the data + // immediately. + ASSERT_EQ(MOJO_RESULT_OK, producer_handle->WriteData( + msg1.data(), &size, MOJO_WRITE_DATA_FLAG_NONE)); + EXPECT_EQ(msg1.size(), size); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Stop deferring. + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + + // Close the response body pipe. + producer_handle.reset(); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); +} + +TEST_P(WebMojoURLLoaderClientTest, + DeferredWithBackForwardCacheLongResponseBody) { + if (!DeferWithBackForwardCacheEnabled()) + return; + // Call OnReceiveResponse, OnStartLoadingResponseBody, OnComplete while + // deferred. + client_->SetDefersLoading( + blink::WebURLLoader::DeferType::kDeferredWithBackForwardCache); + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(MOJO_RESULT_OK, + mojo::CreateDataPipe(nullptr, &producer_handle, &consumer_handle)); + url_loader_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); + network::URLLoaderCompletionStatus status; + url_loader_client_->OnComplete(status); + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + + // Write to the response body pipe. It will take several writes. + const uint32_t body_size = 70000; + uint32_t bytes_remaining = body_size; + std::string body(body_size, '*'); + while (bytes_remaining > 0) { + uint32_t start_position = body_size - bytes_remaining; + uint32_t bytes_sent = bytes_remaining; + MojoResult result = producer_handle->WriteData( + body.c_str() + start_position, &bytes_sent, MOJO_WRITE_DATA_FLAG_NONE); + if (result == MOJO_RESULT_SHOULD_WAIT) { + // When we buffer the body the pipe gets drained asynchronously, so it's + // possible to keep writing to the pipe if we wait. + base::RunLoop().RunUntilIdle(); + continue; + } + EXPECT_EQ(MOJO_RESULT_OK, result); + EXPECT_GE(bytes_remaining, bytes_sent); + bytes_remaining -= bytes_sent; + } + // Ensure we've written all that we can write. When buffering is disabled, we + // can only write |body_size| - |bytes_remaining| bytes. + const uint32_t bytes_written = body_size - bytes_remaining; + EXPECT_EQ(body_size, bytes_written); + producer_handle.reset(); + + // Stop deferring. + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + // When the body is buffered, BodyBuffer shouldn't be finished writing to the + // new response body pipe at this point (because nobody is reading it). + EXPECT_FALSE(context_->complete); + + // Calling GetRequestPeerContextBody to read data from the new response body + // pipe will make BodyBuffer write the rest of the body to the pipe. + uint32_t bytes_read = 0; + while (bytes_read < bytes_written) { + bytes_read = GetRequestPeerContextBody(context_).size(); + base::RunLoop().RunUntilIdle(); + } + // Ensure that we've read everything we've written. + EXPECT_EQ(bytes_written, bytes_read); + EXPECT_EQ(body, GetRequestPeerContextBody(context_)); + EXPECT_TRUE(context_->complete); +} + +// As "transfer size update" message is handled specially in the implementation, +// we have a separate test. +TEST_P(WebMojoURLLoaderClientTest, DeferWithTransferSizeUpdated) { + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + uint32_t size = 5; + MojoResult result = + data_pipe_producer->WriteData("hello", &size, MOJO_WRITE_DATA_FLAG_NONE); + ASSERT_EQ(MOJO_RESULT_OK, result); + EXPECT_EQ(5u, size); + data_pipe_producer.reset(); + + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnTransferSizeUpdated(4); + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + EXPECT_EQ(4, context_->total_encoded_data_length); +} + +TEST_P(WebMojoURLLoaderClientTest, SetDeferredDuringFlushingDeferredMessage) { + context_->defer_on_redirect = true; + + net::RedirectInfo redirect_info; + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveRedirect(redirect_info, + network::mojom::URLResponseHead::New()); + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + uint32_t size = 5; + MojoResult result = + data_pipe_producer->WriteData("hello", &size, MOJO_WRITE_DATA_FLAG_NONE); + ASSERT_EQ(MOJO_RESULT_OK, result); + EXPECT_EQ(5u, size); + data_pipe_producer.reset(); + + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + url_loader_client_->OnTransferSizeUpdated(4); + url_loader_client_->OnComplete(status); + + EXPECT_EQ(0, context_->seen_redirects); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(0, context_->seen_redirects); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + EXPECT_EQ(0, context_->seen_redirects); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, context_->seen_redirects); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ("", GetRequestPeerContextBody(context_)); + EXPECT_EQ(0, context_->total_encoded_data_length); + EXPECT_FALSE(context_->cancelled); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1, context_->seen_redirects); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + EXPECT_EQ("hello", GetRequestPeerContextBody(context_)); + EXPECT_EQ(4, context_->total_encoded_data_length); + EXPECT_FALSE(context_->cancelled); +} + +TEST_P(WebMojoURLLoaderClientTest, + SetDeferredDuringFlushingDeferredMessageOnTransferSizeUpdated) { + context_->defer_on_transfer_size_updated = true; + + network::URLLoaderCompletionStatus status; + + url_loader_client_->OnReceiveResponse(network::mojom::URLResponseHead::New()); + MojoCreateDataPipeOptions options = DataPipeOptions(); + mojo::ScopedDataPipeProducerHandle data_pipe_producer; + mojo::ScopedDataPipeConsumerHandle data_pipe_consumer; + EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &data_pipe_producer, + &data_pipe_consumer)); + data_pipe_producer.reset(); // Empty body. + url_loader_client_->OnStartLoadingResponseBody(std::move(data_pipe_consumer)); + + url_loader_client_->OnTransferSizeUpdated(4); + url_loader_client_->OnComplete(status); + + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kDeferred); + + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ(0, context_->total_encoded_data_length); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + EXPECT_FALSE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ(0, context_->total_encoded_data_length); + + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_FALSE(context_->complete); + EXPECT_EQ(4, context_->total_encoded_data_length); + EXPECT_FALSE(context_->cancelled); + + client_->SetDefersLoading(blink::WebURLLoader::DeferType::kNotDeferred); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(context_->received_response); + EXPECT_TRUE(context_->complete); + EXPECT_EQ(4, context_->total_encoded_data_length); + EXPECT_FALSE(context_->cancelled); +} + +INSTANTIATE_TEST_SUITE_P(All, WebMojoURLLoaderClientTest, ::testing::Bool()); + +} // namespace blink
diff --git a/third_party/blink/tools/blinkpy/common/system/executive.py b/third_party/blink/tools/blinkpy/common/system/executive.py index 5b48480..2c31f70 100644 --- a/third_party/blink/tools/blinkpy/common/system/executive.py +++ b/third_party/blink/tools/blinkpy/common/system/executive.py
@@ -329,7 +329,34 @@ ignore_stderr=False, decode_output=True, debug_logging=True): - """Popen wrapper for convenience and to work around python bugs.""" + """Popen wrapper for convenience and to work around python bugs. + + By default, run_command will expect a zero exit code and will return the + program output in that case, or throw a ScriptError if the program has a + non-zero exit code. This behavior can be changed by setting the + appropriate input parameters. + + Args: + args: the program arguments. Passed to Popen. + cwd: the current working directory for the program. Passed to Popen. + env: the environment for the program. Passed to Popen. + input: input to give to the program on stdin. Accepts either a file + handler (will be passed directly) or a string (will be passed + via a pipe). + timeout_seconds: maximum time in seconds to wait for the program to + terminate; on a timeout the process will be killed + error_handler: a custom error handler called with a ScriptError when + the program fails. The default handler raises the error. + return_exit_code: instead of returning the program output, return + the exit code. Setting this makes non-zero exit codes non-fatal + (the error_handler will not be called). + return_stderr: if True, include stderr in the returned output. If + False, stderr will be printed to the console unless ignore_stderr + is also True. + ignore_stderr: squash stderr so it doesn't appear in the console. + decode_output: whether to decode the program output. + debug_logging: whether to log details about program execution. + """ assert isinstance(args, list) or isinstance(args, tuple) start_time = time.time()
diff --git a/third_party/blink/tools/blinkpy/common/system/executive_mock.py b/third_party/blink/tools/blinkpy/common/system/executive_mock.py index e9820aa0..628f0fa 100644 --- a/third_party/blink/tools/blinkpy/common/system/executive_mock.py +++ b/third_party/blink/tools/blinkpy/common/system/executive_mock.py
@@ -148,7 +148,9 @@ if self._exception: raise self._exception # pylint: disable=raising-bad-type if self._should_throw: - raise ScriptError('MOCK ScriptError', output=self._output) + raise ScriptError('MOCK ScriptError', + output=self._output, + exit_code=self._exit_code) if self._run_command_fn: return self._run_command_fn(args)
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/base.py b/third_party/blink/tools/blinkpy/web_tests/port/base.py index 8cd031aa..dd26c7f8 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/base.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/base.py
@@ -46,6 +46,7 @@ from blinkpy.common import read_checksum_from_png from blinkpy.common import path_finder from blinkpy.common.memoized import memoized +from blinkpy.common.system.executive import ScriptError from blinkpy.common.system.path import abspath_to_uri from blinkpy.w3c.wpt_manifest import WPTManifest, MANIFEST_NAME from blinkpy.web_tests.layout_package.bot_test_expectations import BotTestExpectationsFactory @@ -584,15 +585,19 @@ result = None err_str = None try: - exit_code = self._executive.run_command( - command, return_exit_code=True) - if exit_code == 0: - # The images are the same. - result = None - elif exit_code == 1: + output = self._executive.run_command(command) + # Log the output, to enable user debugging of a diff hidden by fuzzy + # expectations. This is useful when tightening fuzzy bounds. + if output: + _log.debug(output) + except ScriptError as error: + if error.exit_code == 1: result = self._filesystem.read_binary_file(diff_filename) + # Log the output, to enable user debugging of the diff. + if error.output: + _log.debug(error.output) else: - err_str = 'Image diff returned an exit code of %s. See http://crbug.com/278596' % exit_code + err_str = 'Image diff returned an exit code of %s. See http://crbug.com/278596' % error.exit_code except OSError as error: err_str = 'error running image diff: %s' % error finally:
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py b/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py index 8528ce7..4c83b03 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py
@@ -31,6 +31,7 @@ import optparse from blinkpy.common import exit_codes +from blinkpy.common.system.executive import ScriptError from blinkpy.common.system.executive_mock import MockExecutive from blinkpy.common.system.log_testing import LoggingTestCase from blinkpy.common.system.system_host import SystemHost @@ -201,7 +202,7 @@ def mock_run_command(args): port.host.filesystem.write_binary_file(args[4], mock_image_diff) - return 1 + raise ScriptError(exit_code=1) # Images are different. port._executive = MockExecutive(run_command_fn=mock_run_command) # pylint: disable=protected-access @@ -223,7 +224,7 @@ def test_diff_image_crashed(self): port = self.make_port() - port._executive = MockExecutive(exit_code=2) # pylint: disable=protected-access + port._executive = MockExecutive(should_throw=True, exit_code=2) # pylint: disable=protected-access self.assertEqual( port.diff_image('EXPECTED', 'ACTUAL'), (None,
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache b/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache index e3823bdd..05f779d 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache +++ b/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache
@@ -16,6 +16,7 @@ crbug.com/1150297 http/tests/navigation/back-during-child-frame-reload.html [ Timeout ] crbug.com/1150297 http/tests/navigation/post-frames-goback1.html [ Timeout ] crbug.com/1150297 http/tests/navigation/postredirect-frames-goback1.html [ Timeout ] +crbug.com/1155125 http/tests/history/replacestate-post-to-get-2.html [ Timeout ] # TODO(peria): Make these tests work with same-site browsing instance swap. crbug.com/1136383 http/tests/inspector-protocol/network/interception-download.js [ Failure ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index b802c48..8e9e803f 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1038,11 +1038,6 @@ crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-inherit-002.xht [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-002.xht [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-005.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-column-rule-001.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-margin-002.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-margin-003.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-margin-004.xht [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-nested-margin-005.xht [ Failure ] crbug.com/1066616 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-overflow-clip-positioned.html [ Failure ] crbug.com/1066616 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-overflow-clip.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-rule-002.xht [ Crash Failure Timeout ] @@ -1078,14 +1073,10 @@ crbug.com/829181 virtual/layout_ng_block_frag/fast/multicol/infinitely-tall-content-in-outer-crash.html [ Skip ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/insane-column-gap.html [ Failure ] crbug.com/1066626 virtual/layout_ng_block_frag/fast/multicol/layers-split-across-columns.html [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/line-too-tall-for-second-outer-row.html [ Failure ] crbug.com/1066626 virtual/layout_ng_block_frag/fast/multicol/mixed-opacity-fixed-test.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/mixed-opacity-test.html [ Crash Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-auto-height-short-first-row.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-short-first-row-extra-tall-line.html [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-short-first-row-unsplittable-block.html [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-uneven-inner-column-height.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-very-tall-inside-short-crash.html [ Skip ] crbug.com/1058792 virtual/layout_ng_block_frag/fast/multicol/nested-with-composited-and-multicol-crash.html [ Crash ] crbug.com/1131125 virtual/layout_ng_block_frag/fast/multicol/nested-with-forced-breaks-in-eariler-rows.html [ Failure ] @@ -1102,8 +1093,6 @@ crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/positioned-split.html [ Failure ] crbug.com/1058792 virtual/layout_ng_block_frag/fast/multicol/span/invalid-spanner-in-transform.html [ Failure Crash ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/outer-column-break-after-inner-spanner-2.html [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/outer-column-break-after-inner-spanner-and-float.html [ Failure ] -crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/outer-column-break-after-inner-spanner.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/preferred-widths-with-column-content.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/spanner-with-margins-between-margins.html [ Failure ] crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/span/trailing-margin-before-spanner.html [ Failure ] @@ -1749,10 +1738,7 @@ crbug.com/1032016 http/tests/devtools/sources/debugger-breakpoints/breakpoints-ui-shifted-breakpoint.js [ Pass Failure Timeout ] # Renaming front_end/protocol to front_end/protocol_client requires a 3-way change. Temporarliy disable web tests that use |Protocol| -crbug.com/1011811 http/tests/devtools/inspector-backend-commands.js [ Pass Failure ] -crbug.com/1011811 http/tests/devtools/report-protocol-errors.js [ Pass Failure ] -crbug.com/1047760 http/tests/devtools/screen-orientation-override.js [ Pass Failure Timeout ] -crbug.com/1011811 http/tests/devtools/elements/styles-1/cached-sync-computed-styles.js [ Pass Failure ] +crbug.com/1047760 http/tests/devtools/screen-orientation-override.js [ Pass Timeout ] # switching to apache-win32: needs triaging. crbug.com/528062 [ Win ] http/tests/css/missing-repaint-after-slow-style-sheet.pl [ Failure ] @@ -1772,6 +1758,7 @@ crbug.com/574283 virtual/threaded-prefer-compositing/fast/scroll-behavior/smooth-scroll/main-thread-scrolling-reason-correctness.html [ Skip ] crbug.com/574283 virtual/threaded-prefer-compositing/fast/scroll-behavior/smooth-scroll/mousewheel-scroll-interrupted.html [ Skip ] +crbug.com/599670 [ Win ] http/tests/devtools/resource-parameters-ipv6.js [ Pass Failure Crash ] crbug.com/472330 fast/borders/border-image-outset-split-inline-vertical-lr.html [ Failure ] crbug.com/472330 fast/writing-mode/box-shadow-vertical-lr.html [ Failure ] crbug.com/472330 fast/writing-mode/box-shadow-vertical-rl.html [ Failure ] @@ -2547,8 +2534,7 @@ crbug.com/958381 [ Mac ] external/wpt/css/CSS2/tables/table-anonymous-objects-206.xht [ Failure ] # ====== New tests from wpt-importer added here ====== -crbug.com/626703 external/wpt/css/css-break/widows-orphans-017.html [ Failure ] -crbug.com/626703 virtual/layout_ng_block_frag/external/wpt/css/css-break/widows-orphans-017.html [ Failure ] +crbug.com/626703 [ Linux ] external/wpt/css/selectors/focus-visible-002.html [ Timeout ] crbug.com/626703 external/wpt/mediacapture-record/MediaRecorder-peerconnection-no-sink.https.html [ Timeout ] crbug.com/626703 external/wpt/mediacapture-record/MediaRecorder-peerconnection.https.html [ Timeout ] crbug.com/626703 [ Win7 ] virtual/plz-dedicated-worker/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] @@ -3193,6 +3179,7 @@ crbug.com/829028 external/wpt/css/css-break/tall-line-in-short-fragmentainer-002.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/trailing-child-margin-000.html [ Failure ] crbug.com/829028 external/wpt/css/css-break/trailing-child-margin-002.html [ Failure ] +crbug.com/1156312 external/wpt/css/css-break/widows-orphans-017.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html [ Failure ] crbug.com/967329 external/wpt/css/css-multicol/columnfill-auto-max-height-001.html [ Failure ] crbug.com/967329 external/wpt/css/css-multicol/columnfill-auto-max-height-002.html [ Failure ] @@ -5851,10 +5838,6 @@ crbug.com/1130020 virtual/scroll-unification/fast/scrolling/scrollbars/scrollbar-mousedown-move-mouseup.html [ Pass Failure Timeout ] crbug.com/1130020 virtual/threaded-prefer-compositing/fast/scrolling/scrollbars/scrollbar-mousedown-move-mouseup.html [ Pass Failure Timeout ] -# Temporarily disable test to allow devtools-frontend changes -crbug.com/1140481 http/tests/devtools/resource-parameters-ipv6.js [ Pass Failure Crash ] -crbug.com/1140481 http/tests/devtools/resource-tree/resource-tree-frame-in-crafted-frame.js [ Pass Failure ] - # Sheriff 2020-11-16 crbug.com/1149734 http/tests/devtools/sources/debugger-ui/debugger-inline-values-frames.js [ Pass Failure Timeout ] crbug.com/1149734 http/tests/devtools/sources/debugger-ui/reveal-execution-line.js [ Pass Failure Timeout ] @@ -5888,7 +5871,6 @@ # Sheriff 2020-12-03 crbug.com/1154940 [ Win7 ] inspector-protocol/overlay/overlay-persistent-overlays-with-emulation.js [ Pass Failure ] -crbug.com/1155125 [ Linux ] http/tests/history/replacestate-post-to-get-2.html [ Pass Timeout ] # Sheriff 2020-12-04 # Failing on Webkit Linux Leak
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 7e86344..744c105 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -6353,13 +6353,6 @@ ] }, "selectors": { - "focus-visible-002-manual.html": [ - "f86082df8b8988e94cc2fb5ca8705b59251d2908", - [ - null, - {} - ] - ], "focus-visible-006-manual.html": [ "974abc0024e3153008e944ff706156efcb9948e2", [ @@ -9786,7 +9779,21 @@ ] ], "serialPort_loopback-manual.https.html": [ - "9e7801d8332f13aff063f6267f645be6ba837529", + "201a2dedba82a30fc5450728a6d9bb6bcdc164a0", + [ + null, + {} + ] + ], + "serialPort_loopback_BreakError-manual.https.html": [ + "22b15316e266e7c69262b96937694c2e016859a6", + [ + null, + {} + ] + ], + "serialPort_loopback_BufferOverrunError-manual.https.html": [ + "e90a5b01613c8a145168cdc0ac5f2094909b2301", [ null, {} @@ -45940,7 +45947,7 @@ ] ], "attachment-local-clipping-color-5.html": [ - "136b704bd699934a0dc206c3847546ee9185a793", + "7b27a040d53cb44f8034e086bcf250f916d50b5b", [ null, [ @@ -45949,23 +45956,7 @@ "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 10 - ], - [ - 0, - 160 - ] - ] - ] - ] - } + {} ] ], "attachment-local-clipping-color-6.html": [ @@ -46034,7 +46025,7 @@ ] ], "attachment-local-clipping-image-5.html": [ - "ddd02dcfaefdd805188b1b9682f2070d6f81a976", + "376c9cd4c0f4dd2d7e1274feb82029ae47d3d0c6", [ null, [ @@ -46043,23 +46034,7 @@ "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 10 - ], - [ - 0, - 160 - ] - ] - ] - ] - } + {} ] ], "attachment-local-clipping-image-6.html": [ @@ -50955,7 +50930,7 @@ ] ], "border-radius-clip-001.html": [ - "008ca7367f20b51c55460f8cffa6f85be83d4988", + "585b62677f4c439deb077a5ab4aba96559366c72", [ null, [ @@ -50964,27 +50939,11 @@ "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 1 - ], - [ - 0, - 1000 - ] - ] - ] - ] - } + {} ] ], "border-radius-clip-002.htm": [ - "759bd5ce4836899512fe8b435a18bd1aad78cfc2", + "e81871ee50c4498c3ed3a63672725e2e395b5281", [ null, [ @@ -50993,23 +50952,7 @@ "==" ] ], - { - "fuzzy": [ - [ - null, - [ - [ - 0, - 70 - ], - [ - 0, - 50 - ] - ] - ] - ] - } + {} ] ], "border-radius-clipping-002.html": [ @@ -83338,6 +83281,19 @@ } }, "css-multicol": { + "abspos-containing-block-outside-spanner.html": [ + "2a9ee38df5f3d7c3758c71764304f37974926b23", + [ + null, + [ + [ + "/css/css-multicol/abspos-containing-block-outside-spanner-ref.html", + "==" + ] + ], + {} + ] + ], "always-balancing-before-column-span.html": [ "a80617b96ef8c4e1061640ac0347c5a5cd96af71", [ @@ -180857,10 +180813,6 @@ "d673be5f4f29bf82619aba6f40ed7e287e902582", [] ], - "OWNERS": [ - "8b137891791fe96927ad78e64b0aad7bded08bdc", - [] - ], "animations": { "background-image-interpolation-expected.txt": [ "0d58012bada5a4860f1ba038b0a33f5d0f977318", @@ -182555,10 +182507,6 @@ "a0e70aa6539e88373bc8615c3f4e1453010e85d5", [] ], - "OWNERS": [ - "8b137891791fe96927ad78e64b0aad7bded08bdc", - [] - ], "blacktext-ref.html": [ "ddfa9100cbef6094375df8b40eeb9673e690d4f7", [] @@ -183565,12 +183513,16 @@ ] }, "css-display": { + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", + [] + ], "META.yml": [ "4e70cb46303c01463675abee7b284da616bc355b", [] ], "OWNERS": [ - "ef891a7266b1502bd00d2a942c69ec55e9db82a9", + "7f2bab2748888967344c729032f6869d665b56b3", [] ], "display-contents-alignment-001-ref.html": [ @@ -183771,12 +183723,16 @@ } }, "css-flexbox": { + "DIR_METADATA": [ + "38ef497cbe0d8246ac84d5ef528f7f043b57f19c", + [] + ], "META.yml": [ "0bcad0b51f759e6ea9a05e2fee919677bc790dd3", [] ], "OWNERS": [ - "3aa83671fd24673d28d03805d7a9e374e65c913a", + "51c6a57df7f416859ec03c427d80be542e6205a4", [] ], "align-content-horiz-001a-expected.txt": [ @@ -185209,12 +185165,16 @@ ] }, "css-font-loading": { + "DIR_METADATA": [ + "38e8f0f1b01185b8f3535088e30932452c6f0590", + [] + ], "META.yml": [ "3ac9b655b0606783334ff91f9fba852df8efdbc1", [] ], "OWNERS": [ - "7376adf647018485f99de8293979278d2aa30230", + "871ef84196f4f4e316c5e6e4488ffd50b18d9074", [] ], "fontface-descriptor-updates-ref.html": [ @@ -185241,12 +185201,16 @@ } }, "css-fonts": { + "DIR_METADATA": [ + "38e8f0f1b01185b8f3535088e30932452c6f0590", + [] + ], "META.yml": [ "e5ea857ec9043a1c61325d73100fddb6da83020c", [] ], "OWNERS": [ - "cf8e2e66cfc50071cfaa6641ee7e3f790b12f979", + "7da8d64f5563025d96a2fed6bd8d03d91a18c0b3", [] ], "README": [ @@ -192315,12 +192279,16 @@ } }, "css-grid": { + "DIR_METADATA": [ + "6c6ae37327498079ba5a2bac120dfab7475d5ddd", + [] + ], "META.yml": [ "e49946f4f7012e2aefbc2fb01573a2e01a903e55", [] ], "OWNERS": [ - "102c483f4e3c81322ad7b03fc7c2a1a89f546c88", + "5e03d9bce08ec1c2c4d3a23b993e8f428c9e68db", [] ], "README.md": [ @@ -192568,20 +192536,8 @@ "df72a88262bb813963704773dd69c055e164e656", [] ], - "grid-self-alignment-non-static-positioned-items-009-expected.txt": [ - "3a100a48575ea7873c6e6b0344c3765be1437d3b", - [] - ], - "grid-self-alignment-non-static-positioned-items-010-expected.txt": [ - "3a100a48575ea7873c6e6b0344c3765be1437d3b", - [] - ], "grid-self-alignment-non-static-positioned-items-011-expected.txt": [ - "e1b6f15191df351804bfa3f04fe87ce7abfd119a", - [] - ], - "grid-self-alignment-non-static-positioned-items-012-expected.txt": [ - "07f4d6483cbc52b04e33d16853f4463e7c55dce5", + "edc3724880efaae821efdccd82b6f190701826c5", [] ], "grid-self-alignment-stretch-input-range-ref.html": [ @@ -194103,12 +194059,16 @@ } }, "css-layout-api": { + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", + [] + ], "META.yml": [ "c85c2d4ccc0b02f3e22ca444952fb7583d96e7c7", [] ], "OWNERS": [ - "ba7fc91b0894b3c593e93f5dd46c3bde247ef5d6", + "fc604d42cea0f99ef1db61fd569808cab264bf83", [] ], "auto-block-size": { @@ -194543,12 +194503,12 @@ } }, "css-logical": { - "META.yml": [ - "cf789d631b1f61c6fee66d29fc5984d155180702", + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", [] ], - "OWNERS": [ - "9b2e5be0a19c48f73b57fe0ad8bbeea81238a1d1", + "META.yml": [ + "cf789d631b1f61c6fee66d29fc5984d155180702", [] ], "animation-001-expected.txt": [ @@ -194643,12 +194603,12 @@ } }, "css-masking": { - "META.yml": [ - "7f92755b092845d3d550568e0572453801451f3d", + "DIR_METADATA": [ + "765407c4db9cfc7cfe2cfba1a9a04d88645b07a2", [] ], - "OWNERS": [ - "5f3e240be54b8b3d8d86991a78652708cbc1a999", + "META.yml": [ + "7f92755b092845d3d550568e0572453801451f3d", [] ], "animations": { @@ -195109,12 +195069,20 @@ } }, "css-multicol": { + "DIR_METADATA": [ + "8b5d8f1f81c2cb00f2c124192da47afc87afa08a", + [] + ], "META.yml": [ "cc95000ec53ea8daef06251ad5a9f20c5b06a281", [] ], "OWNERS": [ - "6a3de9b3a5ce101a9b83f97312ddeb6d7c69274f", + "b28f7fbbdb4bc0d5c2e152d92a33a309de6887a8", + [] + ], + "abspos-containing-block-outside-spanner-ref.html": [ + "a221907f0072087766caf4d4828f07166442e53f", [] ], "balance-grid-container-ref.html": [ @@ -196001,12 +195969,16 @@ } }, "css-namespaces": { + "DIR_METADATA": [ + "a1cb39cdf6ab67bedd521ef32a4454c4993cadeb", + [] + ], "META.yml": [ "b625e16a9cb0837ee9c612fd25737ad011cddc94", [] ], "OWNERS": [ - "73cfd0e3ce53574dad4632879f04d838e708c462", + "54387d37c800d276f31f3575f6d7b787f18a0166", [] ], "README": [ @@ -196733,12 +196705,16 @@ ] }, "css-position": { + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", + [] + ], "META.yml": [ "c1ce1ff602eee4668b9cb5d0168c4372193a8d3a", [] ], "OWNERS": [ - "8f03d3c62fd0cefb11a22b1a4a8d2c06fed97308", + "38ad6be67d76b736803ad22d117a6c01060a4169", [] ], "fixed-z-index-blend-ref.html": [ @@ -196971,12 +196947,16 @@ ] }, "css-properties-values-api": { + "DIR_METADATA": [ + "ea45d267725ae7714f0eefa5345739a68a8816f7", + [] + ], "META.yml": [ "38cd166ca8f45769c269039577aac391ad707e75", [] ], "OWNERS": [ - "c6888c4efaa8228995bbbf329db35cf8eb660651", + "4305d918f2abc780975dc08a236d8c41d7f20b14", [] ], "registered-property-computation-expected.txt": [ @@ -197727,12 +197707,16 @@ } }, "css-scoping": { + "DIR_METADATA": [ + "a1cb39cdf6ab67bedd521ef32a4454c4993cadeb", + [] + ], "META.yml": [ "826341652122a40956ccc74288e23f952f1f40e8", [] ], "OWNERS": [ - "3456394462972a17034768761f1a6b93ee51c11b", + "53463b38f4154029f9fadf7c337119f9828f57b4", [] ], "keyframes-004-expected.txt": [ @@ -213076,12 +213060,16 @@ ] }, "device-memory": { + "DIR_METADATA": [ + "d2c2adf8cb7f8280b2cead447b542343201b5d40", + [] + ], "META.yml": [ "b8dd4761adff3e18b6552d4a8f02abdcd30a3ea6", [] ], "OWNERS": [ - "5dd066fdd04c103dfd70ba06f6aa67d691420924", + "144a162356513962eda1beaade31ac877a93dff2", [] ] }, @@ -213624,12 +213612,12 @@ } }, "dom": { - "META.yml": [ - "6fd5b12664da091fd9ee773b821ad72ee704ee8f", + "DIR_METADATA": [ + "21fc6f356b3a787bbc9a41d2e8d7f464748644ce", [] ], - "OWNERS": [ - "422f9abf5a1182fe9db1615c2c2dd9052819b883", + "META.yml": [ + "6fd5b12664da091fd9ee773b821ad72ee704ee8f", [] ], "collections": { @@ -213702,8 +213690,12 @@ ] }, "scrolling": { + "DIR_METADATA": [ + "4a2c8aa4e0a7aea2acc4c1b62444bb49b4499d3b", + [] + ], "OWNERS": [ - "e7e045164ea50e9f54c23910b7eaf4842b95f434", + "9f9aedfac3433e18800138c0eb8b36cc1319aeb3", [] ], "scroll_support.js": [ @@ -214182,6 +214174,10 @@ } }, "domparsing": { + "DIR_METADATA": [ + "3f57820b0254393752c5e02c4f3a3561946a14ef", + [] + ], "DOMParser-parseFromString-xml-expected.txt": [ "56c0d19a1a3637168e75cffdd2d4e40ac3b114a8", [] @@ -214191,7 +214187,7 @@ [] ], "OWNERS": [ - "5c2ac186c8c9d2c6befccda3e0f1f901e9df885b", + "300e43542d25a391e1562f4c0c0f9b074287cd47", [] ], "XMLSerializer-serializeToString-expected.txt": [ @@ -214238,12 +214234,16 @@ } }, "domxpath": { + "DIR_METADATA": [ + "3f57820b0254393752c5e02c4f3a3561946a14ef", + [] + ], "META.yml": [ "39abd8e7065477f07caca7211f984dddcb7c5f2a", [] ], "OWNERS": [ - "5c2ac186c8c9d2c6befccda3e0f1f901e9df885b", + "300e43542d25a391e1562f4c0c0f9b074287cd47", [] ], "README.md": [ @@ -214278,12 +214278,12 @@ ] }, "editing": { - "META.yml": [ - "f7f2f109d655b517e5da0b3b6b0a0835c9971642", + "DIR_METADATA": [ + "4feb00c40f6afc3d019213ba18b6195afcdc2f2f", [] ], - "OWNERS": [ - "42fc5a29b03d0a9aa2ea33a36996abad64b068ce", + "META.yml": [ + "f7f2f109d655b517e5da0b3b6b0a0835c9971642", [] ], "README": [ @@ -214848,12 +214848,16 @@ } }, "element-timing": { + "DIR_METADATA": [ + "45b72a63be742f08a481cb470863cbaae10e105f", + [] + ], "META.yml": [ "15510df7e5096b5da0b0d216b5d36b478834bf35", [] ], "OWNERS": [ - "40d288d0460188b4e3938554ad0f58d226aa4b71", + "9e3a2546556a896943d73233cb647edca73d9dd4", [] ], "resources": { @@ -214920,12 +214924,16 @@ } }, "encoding": { + "DIR_METADATA": [ + "c8c8e407a09a59c7b47270a870b94ff5e34c857a", + [] + ], "META.yml": [ "a219a492f0b963f19c50c094e9f00cf3cb69d467", [] ], "OWNERS": [ - "0aa698143bb4af9384c0ad9d45d3c18f6588ca50", + "82c8165c34f3df1366bf49099aa5d75b79c59e7e", [] ], "bom-handling.html.headers": [ @@ -215940,12 +215948,16 @@ ] }, "encrypted-media": { + "DIR_METADATA": [ + "a3f1e7a794f0d2b893d17a69b92157172de8becf", + [] + ], "META.yml": [ "b09e3b3c4e860bb92f1bc434c2f13462085f0af2", [] ], "OWNERS": [ - "96cb6024ba8ae9ca8e8307539baf8074393b916f", + "72726ecdaff59482d34f933b036a9e294da187c1", [] ], "README.md": [ @@ -216280,12 +216292,16 @@ } }, "entries-api": { + "DIR_METADATA": [ + "12cf0e36d35303a5936a5a1f0fba87083b219262", + [] + ], "META.yml": [ "69f68452f292a2087ded7e513fd13f1686175a9b", [] ], "OWNERS": [ - "58d13a36345fa4523056f231ca9de83502694b7d", + "67672b06172c4702d7aed216e1e41f444879237e", [] ], "README.md": [ @@ -216352,12 +216368,16 @@ ] }, "event-timing": { + "DIR_METADATA": [ + "45b72a63be742f08a481cb470863cbaae10e105f", + [] + ], "META.yml": [ "aa27fb61c310d91b629ff0d7b19cd01ce469e645", [] ], "OWNERS": [ - "40d288d0460188b4e3938554ad0f58d226aa4b71", + "9e3a2546556a896943d73233cb647edca73d9dd4", [] ], "resources": { @@ -216376,12 +216396,12 @@ } }, "eventsource": { - "META.yml": [ - "92f1036338515da7807fdbde7ab0a26f509cc986", + "DIR_METADATA": [ + "72f55a07bf0614209ec29ccfc63e02435fd01b96", [] ], - "OWNERS": [ - "8263c354debb11010e65383063f506c39841e5ba", + "META.yml": [ + "92f1036338515da7807fdbde7ab0a26f509cc986", [] ], "README.md": [ @@ -216536,12 +216556,16 @@ } }, "feature-policy": { + "DIR_METADATA": [ + "fcc5bce0c43d4db18763d6ea9c4d5dfd07c32b73", + [] + ], "META.yml": [ "5fb6249c67a2c67ce692cd0345ea214feaa8cd95", [] ], "OWNERS": [ - "6385d1242762f7c58592c6e359c7f91304a9492f", + "7f44d1b6e2ffff87a3e265b9ba62518534468d80", [] ], "README.md": [ @@ -216862,12 +216886,16 @@ } }, "fetch": { + "DIR_METADATA": [ + "331a6d13b91d1e6cd3553b926e41ef04c556cddf", + [] + ], "META.yml": [ "43f9dc51cfd31e70601a186a9b91e8f3d7afd462", [] ], "OWNERS": [ - "d6dc1ce4cf0dfdec9db806d1242fa7f368dab4e2", + "0e9d45b77849400abb7b5ffb520a0fa87f4c20a9", [] ], "README.md": [ @@ -217541,8 +217569,12 @@ ] }, "corb": { + "DIR_METADATA": [ + "2c58cd8d17e0442bd6405b3a1fa172b26e8995cf", + [] + ], "OWNERS": [ - "42d5155b66317b0067f81189e31a9168d13ca2f0", + "107fab74861bd2ae970c7e8f4448a79436142716", [] ], "README.md": [ @@ -217693,8 +217725,12 @@ } }, "cross-origin-resource-policy": { + "DIR_METADATA": [ + "2c58cd8d17e0442bd6405b3a1fa172b26e8995cf", + [] + ], "OWNERS": [ - "42d5155b66317b0067f81189e31a9168d13ca2f0", + "107fab74861bd2ae970c7e8f4448a79436142716", [] ], "resources": { @@ -218278,8 +218314,12 @@ } }, "font-access": { + "DIR_METADATA": [ + "d33d12bd3c9caf3e545dfdcc98d67659a78693ff", + [] + ], "OWNERS": [ - "2adf71cfa8c45ac70ca23dd86e57912b2942777c", + "1390e10b6a216a01a3033ec5d8644573fcea1149", [] ], "README.md": [ @@ -219164,12 +219204,16 @@ } }, "fullscreen": { + "DIR_METADATA": [ + "c248719d70d2c1f23e53e7e78c846648a635c1a0", + [] + ], "META.yml": [ "fbdb76390c7ad4390dac7d83004e5721fc62a37d", [] ], "OWNERS": [ - "8a1711365d4f73cac512b38f6a204907dc278bc8", + "212e449935d26b6f59f486c69dd23f6cf5aa48af", [] ], "api": { @@ -219216,12 +219260,16 @@ ] }, "gamepad": { + "DIR_METADATA": [ + "08033218c69115b128f2b08d66971f3ac91b2849", + [] + ], "META.yml": [ "57cb2cd5f08824e128626381b74170e0583fce61", [] ], "OWNERS": [ - "b1d9945efd773f06dbb5302591f2d83fd93f4a03", + "2cf1435129f29a05b4ba130c83f755d6844ce181", [] ], "feature-policy-gamepad.html": [ @@ -219250,12 +219298,16 @@ ] }, "generic-sensor": { + "DIR_METADATA": [ + "fc620d564cf2ffdea9cc43d1cfc0655361356476", + [] + ], "META.yml": [ "bf48f80f8083f0ca13f432d16a7b3b22b3435526", [] ], "OWNERS": [ - "c394fdb9b8bf4d64a3ae8186552076cc4beb0ce3", + "827d3b758d36ddb0acef43595180a846fbd07e5c", [] ], "README.md": [ @@ -219286,12 +219338,16 @@ } }, "geolocation-API": { + "DIR_METADATA": [ + "af86708dbfa87c696d4a4a449733b8f93f8f7e13", + [] + ], "META.yml": [ "fa243042560a8cf081989aa00c27112c7ea67f60", [] ], "OWNERS": [ - "61e58760ad05c2b527c3cb12295ceecc103a3579", + "5c49de21a3b53dfe928d30a36400469d8238bb1d", [] ], "getCurrentPosition_IDL.https-expected.txt": [ @@ -219414,12 +219470,12 @@ ] }, "hr-time": { - "META.yml": [ - "779d5b4af08428c45023fc9d519ab0830d866a87", + "DIR_METADATA": [ + "45b72a63be742f08a481cb470863cbaae10e105f", [] ], - "OWNERS": [ - "f4011d2bf1144bf42ad8d2a194f517d556407835", + "META.yml": [ + "779d5b4af08428c45023fc9d519ab0830d866a87", [] ], "resources": { @@ -219446,12 +219502,12 @@ } }, "html": { - "META.yml": [ - "94b925cc0760b29dc6d0ee7c6fb37ec424da833b", + "DIR_METADATA": [ + "bdebb861fdc50200a6fd292e47a4058151f8c465", [] ], - "OWNERS": [ - "472b0c7cf86c832abc8ad64d18e7c6cad434a1b2", + "META.yml": [ + "94b925cc0760b29dc6d0ee7c6fb37ec424da833b", [] ], "README.md": [ @@ -221089,12 +221145,12 @@ } }, "canvas": { - "META.yml": [ - "0f79f2591292a3b2d82e6d42f22f82368381dc08", + "DIR_METADATA": [ + "866f70300469c2a927d5a4fe6f122ddbdcfc725a", [] ], - "OWNERS": [ - "3b83b67facae74327e940c3784d6c9befdb48789", + "META.yml": [ + "0f79f2591292a3b2d82e6d42f22f82368381dc08", [] ], "element": { @@ -223115,8 +223171,8 @@ "dom": { "documents": { "dom-tree-accessors": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "cross-domain.js": [ @@ -223147,8 +223203,8 @@ }, "elements": { "elements-in-the-dom": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ] }, @@ -223157,8 +223213,8 @@ "94e9a4f1908e4f4eb3216981a91c3c8174902fcb", [] ], - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "custom-attrs-expected.txt": [ @@ -223574,8 +223630,8 @@ }, "editing": { "activation": { - "OWNERS": [ - "261aa8cc139765e5fbf57f7d6c853cff02719506", + "DIR_METADATA": [ + "52a1730ce0172e70cd7c3dac95b3da70d443c891", [] ] }, @@ -226833,8 +226889,8 @@ }, "editing-0": { "contenteditable": { - "OWNERS": [ - "261aa8cc139765e5fbf57f7d6c853cff02719506", + "DIR_METADATA": [ + "52a1730ce0172e70cd7c3dac95b3da70d443c891", [] ], "contenteditable-with-empty-block-ref.html": [ @@ -226843,8 +226899,8 @@ ] }, "making-entire-documents-editable-the-designmode-idl-attribute": { - "OWNERS": [ - "261aa8cc139765e5fbf57f7d6c853cff02719506", + "DIR_METADATA": [ + "52a1730ce0172e70cd7c3dac95b3da70d443c891", [] ], "original-id.json": [ @@ -226857,8 +226913,8 @@ ] }, "spelling-and-grammar-checking": { - "OWNERS": [ - "261aa8cc139765e5fbf57f7d6c853cff02719506", + "DIR_METADATA": [ + "52a1730ce0172e70cd7c3dac95b3da70d443c891", [] ], "references": { @@ -226921,8 +226977,8 @@ "infrastructure": { "common-dom-interfaces": { "collections": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "htmlallcollection-expected.txt": [ @@ -226941,8 +226997,8 @@ }, "conformance-requirements": { "extensibility": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ] } @@ -227237,8 +227293,8 @@ }, "terminology": { "plugins": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "sample.txt": [ @@ -227426,8 +227482,12 @@ }, "interaction": { "focus": { + "DIR_METADATA": [ + "4a2c8aa4e0a7aea2acc4c1b62444bb49b4499d3b", + [] + ], "OWNERS": [ - "f17b1239cde137fe8f8eeba8c0552f8336047e38", + "35449ec5bab7c3e8ac3c61fa50a8207e667eabe2", [] ], "document-level-focus-apis": { @@ -227551,8 +227611,8 @@ ], "requirements-for-implementations": { "other-elements-attributes-and-apis": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "original-id.json": [ @@ -227561,8 +227621,8 @@ ] }, "the-marquee-element-0": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ] } @@ -227577,8 +227637,8 @@ ] }, "the-input-element-as-a-text-entry-widget": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "unrecognized-type-should-fallback-as-text-type-ref.html": [ @@ -227587,8 +227647,8 @@ ] }, "the-select-element-0": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "option-label-ref.html": [ @@ -227597,8 +227657,8 @@ ] }, "the-textarea-element-0": { - "OWNERS": [ - "422c227ea95706b5eaa67c8784b0ce8ac4fca8e1", + "DIR_METADATA": [ + "15104593acde00649ee4cebb518e9f8ec238cbfa", [] ], "textarea-ref.html": [ @@ -227621,8 +227681,8 @@ }, "non-replaced-elements": { "flow-content-0": { - "OWNERS": [ - "9b2e5be0a19c48f73b57fe0ad8bbeea81238a1d1", + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", [] ], "div-align-ref.html": [ @@ -227655,8 +227715,8 @@ ] }, "lists": { - "OWNERS": [ - "9b2e5be0a19c48f73b57fe0ad8bbeea81238a1d1", + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", [] ], "TODO-lists.html": [ @@ -227700,15 +227760,15 @@ "a6fec366db2b8d11401c31cf88ec75e02468144b", [] ], - "OWNERS": [ - "9b2e5be0a19c48f73b57fe0ad8bbeea81238a1d1", + "DIR_METADATA": [ + "85377a77b206fbf1b2892a929462cba04ab6e64a", [] ] } }, "tables": { - "OWNERS": [ - "77c2a59aec02a65d70431e47bbefea2bf59d095a", + "DIR_METADATA": [ + "bd468f81a1a14c030b25277dea36547beb57ca44", [] ], "colgroup_valign-ref.xhtml": [ @@ -255259,6 +255319,10 @@ "be485f03e8b323ff55c98697a267b77a3803af73", [] ], + "invalid-param-array-processor.js": [ + "e4a5dc39ba16b282e254eba84e8038ae59a6471d", + [] + ], "one-pole-processor.js": [ "0bcc43f6f0850f0afc0a596e90f9d626bfd8daed", [] @@ -292663,28 +292727,28 @@ ] ], "grid-self-alignment-non-static-positioned-items-009.html": [ - "ad2f8b1dc34c9021316baf756ad21a884b448f51", + "4136c44b0d9be089b077449a7adfe3eca78642ec", [ null, {} ] ], "grid-self-alignment-non-static-positioned-items-010.html": [ - "856062014d4855db2ca0fc463b65d5ddf2e492ed", + "86dc3257a601da21e43e6151cf64b7bdf9187493", [ null, {} ] ], "grid-self-alignment-non-static-positioned-items-011.html": [ - "f3a8476ddf9153a25879aca8c8e43ab78d9c0cf0", + "d12c1826f73ebeadc5ae0f3298d7dc0b24a6e156", [ null, {} ] ], "grid-self-alignment-non-static-positioned-items-012.html": [ - "0121846f8a17aaa576ccb80590c470ef69216f13", + "003c3bbb378298d3aa3a611aaaa0bd7ef0cdd8e0", [ null, {} @@ -310865,6 +310929,16 @@ } ] ], + "focus-visible-002.html": [ + "19c937a7abbc3ccba91ace6f998de9c5694cb602", + [ + null, + { + "testdriver": true, + "timeout": "long" + } + ] + ], "focus-visible-003.html": [ "4620c1e411492069f085efc08a3647a5eaae6fa6", [ @@ -369937,14 +370011,14 @@ ] ], "selection-not-application-textarea.html": [ - "3116cd93523ff9c70879603078e7070762da37a4", + "e8e82791880e163f513cf64d5df3049e6c7c3b15", [ null, {} ] ], "selection-not-application.html": [ - "a7d7f1c5518551436b6b4845d0ce205cf3721cfc", + "aa98a030a83b8b9506c8e04dc945e022f11073ee", [ null, {} @@ -369958,7 +370032,7 @@ ] ], "selection-start-end.html": [ - "4bcecf234cc042c7d1496f1a814187cdb5386f77", + "919d1a4d658367ef845c584d470db0e98509a584", [ null, {} @@ -430366,6 +430440,13 @@ {} ] ], + "audioworkletprocessor-param-getter-overridden.https.html": [ + "e3fb6e533df8ccaa88564f836239e0c9e9c1d5e4", + [ + null, + {} + ] + ], "audioworkletprocessor-process-frozen-array.https.html": [ "33627204a6f538eba77bd8346952404814e4affa", [
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea.html index 3116cd9..e8e82791 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea.html
@@ -11,8 +11,15 @@ var el = document.createElement("textarea"); assert_equals(el.selectionStart, 0, "initial selectionStart"); assert_equals(el.selectionEnd, 0, "initial selectionEnd"); - assert_equals(el.selectionDirection, "none", "initial selectionDirection"); + // The initial selection direction must be "none" if the platform supports that + // direction, or "forward" otherwise. + assert_in_array(el.selectionDirection, ["none", "forward"]); + const initialDirection = el.selectionDirection; + el.selectionDirection = "none"; + assert_equals(el.selectionDirection, initialDirection); + + el.value = "foo"; el.selectionStart = 1; el.selectionEnd = 1; el.selectionDirection = "forward";
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application.html index a7d7f1c55..aa98a030 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-not-application.html
@@ -63,8 +63,11 @@ }); applicableTypes.forEach(function(type) { - var el = document.createElement("input"); - if (type) el.type = type; + const el = document.createElement("input"); + if (type) { + el.type = type; + } + const initialDirection = el.selectionDirection; test(() => { assert_equals(el.selectionStart, 0); @@ -79,6 +82,11 @@ }, `selectionDirection on an input[type=${type}] returns a value`); test(() => { + el.selectionDirection = "none"; + assert_equals(el.selectionDirection, initialDirection); + }, `assigning selectionDirection "none" on an input[type=${type}] should give the initial direction`); + + test(() => { el.selectionStart = 1; }, `assigning selectionStart on an input[type=${type}] doesn't throw an exception`);
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-start-end.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-start-end.html index 4bcecf23..919d1a4 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-start-end.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/selection-start-end.html
@@ -145,6 +145,31 @@ }, "selectionEnd edge-case values"); test(() => { + for (const el of createTestElements(testValue)) { + el.selectionStart = 200; + assert_equals(el.selectionStart, testValue.length); + el.remove(); + } + }, "selectionStart should be clamped by the current value length"); + + test(() => { + for (const el of createTestElements(testValue)) { + el.selectionStart = 300; + assert_equals(el.selectionEnd, testValue.length); + el.remove(); + } + }, "selectionEnd should be clamped by the current value length"); + + test(() => { + for (const el of createTestElements(testValue)) { + el.setSelectionRange(200, 300); + assert_equals(el.selectionStart, testValue.length); + assert_equals(el.selectionEnd, testValue.length); + el.remove(); + } + }, "setSelectionRange should be clamped by the current value length"); + + test(() => { for (let el of createTestElements(testValue)) { const start = 1; const end = testValue.length - 1;
diff --git a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-DOMWindowTimers-setTimeout-setInterval.tentative.html b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-DOMWindowTimers-setTimeout-setInterval.tentative.html index f36ae94..c247157 100644 --- a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-DOMWindowTimers-setTimeout-setInterval.tentative.html +++ b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-DOMWindowTimers-setTimeout-setInterval.tentative.html
@@ -54,13 +54,12 @@ }); }, "`window.setInterval(null)` throws."); + let policy = window.trustedTypes.createPolicy("default", { createScript: x => "0" }); // After default policy creation string assignment implicitly calls createScript. test(t => { - let policy = window.trustedTypes.createPolicy("default", { createScript: createScriptJS }, true); setTimeout(INPUTS.SCRIPT); setInterval(INPUTS.SCRIPT); }, "`setTimeout(string)`, `setInterval(string)` via default policy (successful Script transformation)."); - // After default policy creation null assignment implicitly calls createScript. test(t => { setTimeout(null);
diff --git a/third_party/blink/web_tests/external/wpt/trusted-types/idlharness.tentative.window-expected.txt b/third_party/blink/web_tests/external/wpt/trusted-types/idlharness.tentative.window-expected.txt deleted file mode 100644 index 585a51b..0000000 --- a/third_party/blink/web_tests/external/wpt/trusted-types/idlharness.tentative.window-expected.txt +++ /dev/null
@@ -1,89 +0,0 @@ -This is a testharness.js-based test. -Found 85 tests; 84 PASS, 1 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS idl_test setup -PASS idl_test validation -PASS TrustedHTML interface: existence and properties of interface object -PASS TrustedHTML interface object length -PASS TrustedHTML interface object name -PASS TrustedHTML interface: existence and properties of interface prototype object -PASS TrustedHTML interface: existence and properties of interface prototype object's "constructor" property -PASS TrustedHTML interface: existence and properties of interface prototype object's @@unscopables property -PASS TrustedHTML interface: stringifier -PASS TrustedHTML must be primary interface of window.trustedTypes.createPolicy("SomeName1", { createHTML: s => s }).createHTML("A string") -PASS Stringification of window.trustedTypes.createPolicy("SomeName1", { createHTML: s => s }).createHTML("A string") -PASS TrustedScript interface: existence and properties of interface object -PASS TrustedScript interface object length -PASS TrustedScript interface object name -PASS TrustedScript interface: existence and properties of interface prototype object -PASS TrustedScript interface: existence and properties of interface prototype object's "constructor" property -PASS TrustedScript interface: existence and properties of interface prototype object's @@unscopables property -PASS TrustedScript interface: stringifier -PASS TrustedScript must be primary interface of window.trustedTypes.createPolicy("SomeName2", { createScript: s => s }).createScript("A string") -PASS Stringification of window.trustedTypes.createPolicy("SomeName2", { createScript: s => s }).createScript("A string") -PASS TrustedScriptURL interface: existence and properties of interface object -PASS TrustedScriptURL interface object length -PASS TrustedScriptURL interface object name -PASS TrustedScriptURL interface: existence and properties of interface prototype object -PASS TrustedScriptURL interface: existence and properties of interface prototype object's "constructor" property -PASS TrustedScriptURL interface: existence and properties of interface prototype object's @@unscopables property -PASS TrustedScriptURL interface: stringifier -PASS TrustedScriptURL must be primary interface of window.trustedTypes.createPolicy("SomeName3", { createScriptURL: s => s }).createScriptURL("A string") -PASS Stringification of window.trustedTypes.createPolicy("SomeName3", { createScriptURL: s => s }).createScriptURL("A string") -PASS TrustedTypePolicyFactory interface: existence and properties of interface object -PASS TrustedTypePolicyFactory interface object length -PASS TrustedTypePolicyFactory interface object name -PASS TrustedTypePolicyFactory interface: existence and properties of interface prototype object -PASS TrustedTypePolicyFactory interface: existence and properties of interface prototype object's "constructor" property -PASS TrustedTypePolicyFactory interface: existence and properties of interface prototype object's @@unscopables property -FAIL TrustedTypePolicyFactory interface: operation createPolicy(DOMString, optional TrustedTypePolicyOptions) assert_equals: property has wrong .length expected 1 but got 2 -PASS TrustedTypePolicyFactory interface: operation isHTML(any) -PASS TrustedTypePolicyFactory interface: operation isScript(any) -PASS TrustedTypePolicyFactory interface: operation isScriptURL(any) -PASS TrustedTypePolicyFactory interface: attribute emptyHTML -PASS TrustedTypePolicyFactory interface: attribute emptyScript -PASS TrustedTypePolicyFactory interface: operation getAttributeType(DOMString, DOMString, optional DOMString, optional DOMString) -PASS TrustedTypePolicyFactory interface: operation getPropertyType(DOMString, DOMString, optional DOMString) -PASS TrustedTypePolicyFactory interface: attribute defaultPolicy -PASS TrustedTypePolicyFactory interface: operation getTypeMapping(optional DOMString) -PASS TrustedTypePolicyFactory interface: attribute onbeforecreatepolicy -PASS TrustedTypePolicyFactory must be primary interface of window.trustedTypes -PASS Stringification of window.trustedTypes -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "createPolicy(DOMString, optional TrustedTypePolicyOptions)" with the proper type -PASS TrustedTypePolicyFactory interface: calling createPolicy(DOMString, optional TrustedTypePolicyOptions) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "isHTML(any)" with the proper type -PASS TrustedTypePolicyFactory interface: calling isHTML(any) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "isScript(any)" with the proper type -PASS TrustedTypePolicyFactory interface: calling isScript(any) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "isScriptURL(any)" with the proper type -PASS TrustedTypePolicyFactory interface: calling isScriptURL(any) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "emptyHTML" with the proper type -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "emptyScript" with the proper type -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "getAttributeType(DOMString, DOMString, optional DOMString, optional DOMString)" with the proper type -PASS TrustedTypePolicyFactory interface: calling getAttributeType(DOMString, DOMString, optional DOMString, optional DOMString) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "getPropertyType(DOMString, DOMString, optional DOMString)" with the proper type -PASS TrustedTypePolicyFactory interface: calling getPropertyType(DOMString, DOMString, optional DOMString) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "defaultPolicy" with the proper type -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "getTypeMapping(optional DOMString)" with the proper type -PASS TrustedTypePolicyFactory interface: calling getTypeMapping(optional DOMString) on window.trustedTypes with too few arguments must throw TypeError -PASS TrustedTypePolicyFactory interface: window.trustedTypes must inherit property "onbeforecreatepolicy" with the proper type -PASS TrustedTypePolicy interface: existence and properties of interface object -PASS TrustedTypePolicy interface object length -PASS TrustedTypePolicy interface object name -PASS TrustedTypePolicy interface: existence and properties of interface prototype object -PASS TrustedTypePolicy interface: existence and properties of interface prototype object's "constructor" property -PASS TrustedTypePolicy interface: existence and properties of interface prototype object's @@unscopables property -PASS TrustedTypePolicy interface: attribute name -PASS TrustedTypePolicy interface: operation createHTML(DOMString) -PASS TrustedTypePolicy interface: operation createScript(DOMString) -PASS TrustedTypePolicy interface: operation createScriptURL(USVString) -PASS TrustedTypePolicy must be primary interface of window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) -PASS Stringification of window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) -PASS TrustedTypePolicy interface: window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) must inherit property "name" with the proper type -PASS TrustedTypePolicy interface: window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) must inherit property "createHTML(DOMString)" with the proper type -PASS TrustedTypePolicy interface: calling createHTML(DOMString) on window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) with too few arguments must throw TypeError -PASS TrustedTypePolicy interface: window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) must inherit property "createScript(DOMString)" with the proper type -PASS TrustedTypePolicy interface: calling createScript(DOMString) on window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) with too few arguments must throw TypeError -PASS TrustedTypePolicy interface: window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) must inherit property "createScriptURL(USVString)" with the proper type -PASS TrustedTypePolicy interface: calling createScriptURL(USVString) on window.trustedTypes.createPolicy("SomeName", { createHTML: s => s }) with too few arguments must throw TypeError -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh b/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh index 8fc28bb..3c8a3ea 100755 --- a/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh
@@ -64,3 +64,9 @@ -primaryURL $wpt_test_http_origin/web-bundle/resources/wbn/resource.js \ -dir nested/ \ -o wbn/nested-main.wbn + +gen-bundle \ + -version b1 \ + -har urn-uuid.har \ + -primaryURL urn:uuid:020111b3-437a-4c5c-ae07-adb6bbffb720 \ + -o wbn/urn-uuid.wbn
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/urn-uuid.har b/third_party/blink/web_tests/external/wpt/web-bundle/resources/urn-uuid.har new file mode 100644 index 0000000..e0cea36 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/urn-uuid.har
@@ -0,0 +1,25 @@ +{ + "log": { + "entries": [ + { + "request": { + "method": "GET", + "url": "urn:uuid:020111b3-437a-4c5c-ae07-adb6bbffb720", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "application/javascript" + } + ], + "content": { + "text": "window.report_result('OK');" + } + } + } + ] + } +}
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/urn-uuid.wbn b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/urn-uuid.wbn new file mode 100644 index 0000000..a4bd3ef --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/urn-uuid.wbn Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/subresource-loading-from-web-bundle.tentative.html b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/subresource-loading-from-web-bundle.tentative.html index c2de0eb..53a9c1b2 100644 --- a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/subresource-loading-from-web-bundle.tentative.html +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/subresource-loading-from-web-bundle.tentative.html
@@ -101,6 +101,16 @@ }, 'Subresource URL must be same-origin with bundle URL'); promise_test(async () => { + const url = 'urn:uuid:020111b3-437a-4c5c-ae07-adb6bbffb720'; + const link = document.createElement('link'); + link.rel = 'webbundle'; + link.href = '../resources/wbn/urn-uuid.wbn'; + link.resources = url; + document.body.appendChild(link); + assert_equals(await loadScriptAndWaitReport(url), 'OK'); + }, 'Subresource loading with urn:uuid: URL'); + + promise_test(async () => { const wbn_url = 'http://web-platform.test:8001/web-bundle/resources/wbn/subresource.wbn?test-resources-update'; const resource_url = 'http://web-platform.test:8001/web-bundle/resources/wbn/submodule.js'; const link = await addLinkAndWaitForLoad(wbn_url);
diff --git a/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-param-getter-overridden.https.html b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-param-getter-overridden.https.html new file mode 100644 index 0000000..e3fb6e5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-param-getter-overridden.https.html
@@ -0,0 +1,59 @@ +<!DOCTYPE html> +<html> + <head> + <title> + Test if AudioWorkletProcessor with invalid parameters array getter + </title> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="/webaudio/resources/audit.js"></script> + </head> + <body> + <script id="layout-test-code"> + let audit = Audit.createTaskRunner(); + + // Arbitrarily determined. Any numbers should work. + let sampleRate = 16000; + let renderLength = 1280; + let context; + let filePath = 'processors/invalid-param-array-processor.js'; + + audit.define('Initializing AudioWorklet and Context', async (task) => { + context = new OfflineAudioContext(1, renderLength, sampleRate); + await context.audioWorklet.addModule(filePath); + task.done(); + }); + + audit.define('Verifying AudioParam in AudioWorkletNode', + async (task, should) => { + let buffer = context.createBuffer(1, 2, context.sampleRate); + buffer.getChannelData(0)[0] = 1; + + let source = new AudioBufferSourceNode(context); + source.buffer = buffer; + source.loop = true; + source.start(); + + let workletNode1 = + new AudioWorkletNode(context, 'invalid-param-array-1'); + let workletNode2 = + new AudioWorkletNode(context, 'invalid-param-array-2'); + workletNode1.connect(workletNode2).connect(context.destination); + + // Manually invoke the param getter. + source.connect(workletNode2.parameters.get('invalidParam')); + + const renderedBuffer = await context.startRendering(); + + // |workletNode2| should be no-op after the parameter getter is + // invoked. Therefore, the rendered result should be silent. + should(renderedBuffer.getChannelData(0), 'The rendered buffer') + .beConstantValueOf(0); + task.done(); + } + ); + + audit.run(); + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/processors/invalid-param-array-processor.js b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/processors/invalid-param-array-processor.js new file mode 100644 index 0000000..e4a5dc3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webaudio/the-audio-api/the-audioworklet-interface/processors/invalid-param-array-processor.js
@@ -0,0 +1,47 @@ +/** + * @class InvalidParamArrayProcessor + * @extends AudioWorkletProcessor + * + * This processor intentionally returns an array with an invalid size when the + * processor's getter is queried. + */ +let singleton = undefined; +let secondFetch = false; +let useDescriptor = false; +let processCounter = 0; + +class InvalidParamArrayProcessor extends AudioWorkletProcessor { + static get parameterDescriptors() { + if (useDescriptor) + return [{name: 'invalidParam'}]; + useDescriptor = true; + return []; + } + + constructor() { + super(); + if (singleton === undefined) + singleton = this; + return singleton; + } + + process(inputs, outputs, parameters) { + const output = outputs[0]; + for (let channel = 0; channel < output.length; ++channel) + output[channel].fill(1); + return false; + } +} + +// This overridden getter is invoked under the hood before process() gets +// called. After this gets called, process() method above will be invalidated, +// and mark the worklet node non-functional. (i.e. in an error state) +Object.defineProperty(Object.prototype, 'invalidParam', {'get': () => { + if (secondFetch) + return new Float32Array(256); + secondFetch = true; + return new Float32Array(128); +}}); + +registerProcessor('invalid-param-array-1', InvalidParamArrayProcessor); +registerProcessor('invalid-param-array-2', InvalidParamArrayProcessor);
diff --git a/third_party/blink/web_tests/fast/alignment/DIR_METADATA b/third_party/blink/web_tests/fast/alignment/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/alignment/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/alignment/OWNERS b/third_party/blink/web_tests/fast/alignment/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/alignment/OWNERS +++ b/third_party/blink/web_tests/fast/alignment/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/autoresize/DIR_METADATA b/third_party/blink/web_tests/fast/autoresize/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/autoresize/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/autoresize/OWNERS b/third_party/blink/web_tests/fast/autoresize/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/autoresize/OWNERS +++ b/third_party/blink/web_tests/fast/autoresize/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/beacon/DIR_METADATA b/third_party/blink/web_tests/fast/beacon/DIR_METADATA new file mode 100644 index 0000000..72f55a07b --- /dev/null +++ b/third_party/blink/web_tests/fast/beacon/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/beacon/OWNERS b/third_party/blink/web_tests/fast/beacon/OWNERS index 8263c35..e69de29 100644 --- a/third_party/blink/web_tests/fast/beacon/OWNERS +++ b/third_party/blink/web_tests/fast/beacon/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network
diff --git a/third_party/blink/web_tests/fast/block/DIR_METADATA b/third_party/blink/web_tests/fast/block/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/block/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/block/OWNERS b/third_party/blink/web_tests/fast/block/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/block/OWNERS +++ b/third_party/blink/web_tests/fast/block/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/borders/DIR_METADATA b/third_party/blink/web_tests/fast/borders/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/borders/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/borders/OWNERS b/third_party/blink/web_tests/fast/borders/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/borders/OWNERS +++ b/third_party/blink/web_tests/fast/borders/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/box-sizing/DIR_METADATA b/third_party/blink/web_tests/fast/box-sizing/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/box-sizing/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/box-sizing/OWNERS b/third_party/blink/web_tests/fast/box-sizing/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/box-sizing/OWNERS +++ b/third_party/blink/web_tests/fast/box-sizing/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/canvas-api/DIR_METADATA b/third_party/blink/web_tests/fast/canvas-api/DIR_METADATA new file mode 100644 index 0000000..469c306 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas-api/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Canvas" +} +team_email: "paint-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/canvas-api/OWNERS b/third_party/blink/web_tests/fast/canvas-api/OWNERS index 14ca7d4e..e69de29 100644 --- a/third_party/blink/web_tests/fast/canvas-api/OWNERS +++ b/third_party/blink/web_tests/fast/canvas-api/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: paint-dev@chromium.org -# COMPONENT: Blink>Canvas
diff --git a/third_party/blink/web_tests/fast/canvas/DIR_METADATA b/third_party/blink/web_tests/fast/canvas/DIR_METADATA new file mode 100644 index 0000000..469c306 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Canvas" +} +team_email: "paint-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/canvas/OWNERS b/third_party/blink/web_tests/fast/canvas/OWNERS index 14ca7d4e..e69de29 100644 --- a/third_party/blink/web_tests/fast/canvas/OWNERS +++ b/third_party/blink/web_tests/fast/canvas/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: paint-dev@chromium.org -# COMPONENT: Blink>Canvas
diff --git a/third_party/blink/web_tests/fast/clip/DIR_METADATA b/third_party/blink/web_tests/fast/clip/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/clip/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/clip/OWNERS b/third_party/blink/web_tests/fast/clip/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/clip/OWNERS +++ b/third_party/blink/web_tests/fast/clip/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/css-generated-content/DIR_METADATA b/third_party/blink/web_tests/fast/css-generated-content/DIR_METADATA new file mode 100644 index 0000000..a1cb39c --- /dev/null +++ b/third_party/blink/web_tests/fast/css-generated-content/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>CSS" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css-generated-content/OWNERS b/third_party/blink/web_tests/fast/css-generated-content/OWNERS index e282c4fb..e69de29 100644 --- a/third_party/blink/web_tests/fast/css-generated-content/OWNERS +++ b/third_party/blink/web_tests/fast/css-generated-content/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>CSS
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/DIR_METADATA b/third_party/blink/web_tests/fast/css-grid-layout/DIR_METADATA new file mode 100644 index 0000000..e0fa458 --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout>Grid" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/OWNERS b/third_party/blink/web_tests/fast/css-grid-layout/OWNERS index 54598e7f..e69de29 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/OWNERS +++ b/third_party/blink/web_tests/fast/css-grid-layout/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout>Grid
diff --git a/third_party/blink/web_tests/fast/css-intrinsic-dimensions/DIR_METADATA b/third_party/blink/web_tests/fast/css-intrinsic-dimensions/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/css-intrinsic-dimensions/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css-intrinsic-dimensions/OWNERS b/third_party/blink/web_tests/fast/css-intrinsic-dimensions/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/css-intrinsic-dimensions/OWNERS +++ b/third_party/blink/web_tests/fast/css-intrinsic-dimensions/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/css/DIR_METADATA b/third_party/blink/web_tests/fast/css/DIR_METADATA new file mode 100644 index 0000000..a1cb39c --- /dev/null +++ b/third_party/blink/web_tests/fast/css/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>CSS" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css/OWNERS b/third_party/blink/web_tests/fast/css/OWNERS index e282c4fb..e69de29 100644 --- a/third_party/blink/web_tests/fast/css/OWNERS +++ b/third_party/blink/web_tests/fast/css/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>CSS
diff --git a/third_party/blink/web_tests/fast/css/containment/DIR_METADATA b/third_party/blink/web_tests/fast/css/containment/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/css/containment/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css/containment/OWNERS b/third_party/blink/web_tests/fast/css/containment/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/css/containment/OWNERS +++ b/third_party/blink/web_tests/fast/css/containment/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/css/content/DIR_METADATA b/third_party/blink/web_tests/fast/css/content/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/css/content/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css/content/OWNERS b/third_party/blink/web_tests/fast/css/content/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/css/content/OWNERS +++ b/third_party/blink/web_tests/fast/css/content/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/css/counters/DIR_METADATA b/third_party/blink/web_tests/fast/css/counters/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/css/counters/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css/counters/OWNERS b/third_party/blink/web_tests/fast/css/counters/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/css/counters/OWNERS +++ b/third_party/blink/web_tests/fast/css/counters/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/css3-text/DIR_METADATA b/third_party/blink/web_tests/fast/css3-text/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/css3-text/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/css3-text/OWNERS b/third_party/blink/web_tests/fast/css3-text/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/css3-text/OWNERS +++ b/third_party/blink/web_tests/fast/css3-text/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/deprecated-flexbox/DIR_METADATA b/third_party/blink/web_tests/fast/deprecated-flexbox/DIR_METADATA new file mode 100644 index 0000000..16e4e2d6f --- /dev/null +++ b/third_party/blink/web_tests/fast/deprecated-flexbox/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout>Flexbox" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/deprecated-flexbox/OWNERS b/third_party/blink/web_tests/fast/deprecated-flexbox/OWNERS index 28a5cc9..e69de29 100644 --- a/third_party/blink/web_tests/fast/deprecated-flexbox/OWNERS +++ b/third_party/blink/web_tests/fast/deprecated-flexbox/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout>Flexbox
diff --git a/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/DIR_METADATA b/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/DIR_METADATA new file mode 100644 index 0000000..a1cb39c --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>CSS" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/OWNERS b/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/OWNERS index e282c4fb..e69de29 100644 --- a/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/OWNERS +++ b/third_party/blink/web_tests/fast/dom/CSSStyleDeclaration/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>CSS
diff --git a/third_party/blink/web_tests/fast/dom/DIR_METADATA b/third_party/blink/web_tests/fast/dom/DIR_METADATA new file mode 100644 index 0000000..1510459 --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/DIR_METADATA
@@ -0,0 +1 @@ +team_email: "dom-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/DIR_METADATA b/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/OWNERS b/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/OWNERS +++ b/third_party/blink/web_tests/fast/dom/Document/CaretRangeFromPoint/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/DIR_METADATA b/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/DIR_METADATA new file mode 100644 index 0000000..c943b93 --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Blink>HTML" +}
diff --git a/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/OWNERS b/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/OWNERS index feb9ef3..e69de29 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/OWNERS +++ b/third_party/blink/web_tests/fast/dom/HTMLDivElement/align/OWNERS
@@ -1 +0,0 @@ -# COMPONENT: Blink>HTML
diff --git a/third_party/blink/web_tests/fast/dom/OWNERS b/third_party/blink/web_tests/fast/dom/OWNERS index 422c227..e69de29 100644 --- a/third_party/blink/web_tests/fast/dom/OWNERS +++ b/third_party/blink/web_tests/fast/dom/OWNERS
@@ -1 +0,0 @@ -# TEAM: dom-dev@chromium.org
diff --git a/third_party/blink/web_tests/fast/dom/elementsFromPoint/DIR_METADATA b/third_party/blink/web_tests/fast/dom/elementsFromPoint/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/elementsFromPoint/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/dom/elementsFromPoint/OWNERS b/third_party/blink/web_tests/fast/dom/elementsFromPoint/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/dom/elementsFromPoint/OWNERS +++ b/third_party/blink/web_tests/fast/dom/elementsFromPoint/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/domurl/DIR_METADATA b/third_party/blink/web_tests/fast/domurl/DIR_METADATA new file mode 100644 index 0000000..72f55a07b --- /dev/null +++ b/third_party/blink/web_tests/fast/domurl/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/domurl/OWNERS b/third_party/blink/web_tests/fast/domurl/OWNERS index 8263c35..e69de29 100644 --- a/third_party/blink/web_tests/fast/domurl/OWNERS +++ b/third_party/blink/web_tests/fast/domurl/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network
diff --git a/third_party/blink/web_tests/fast/encoding/DIR_METADATA b/third_party/blink/web_tests/fast/encoding/DIR_METADATA new file mode 100644 index 0000000..c8c8e407 --- /dev/null +++ b/third_party/blink/web_tests/fast/encoding/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>TextEncoding" +} +team_email: "text-encoding-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/encoding/OWNERS b/third_party/blink/web_tests/fast/encoding/OWNERS index 4858f06..e69de29 100644 --- a/third_party/blink/web_tests/fast/encoding/OWNERS +++ b/third_party/blink/web_tests/fast/encoding/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: text-encoding-dev@chromium.org -# COMPONENT: Blink>TextEncoding
diff --git a/third_party/blink/web_tests/fast/reflections/DIR_METADATA b/third_party/blink/web_tests/fast/reflections/DIR_METADATA new file mode 100644 index 0000000..1c9c5df --- /dev/null +++ b/third_party/blink/web_tests/fast/reflections/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Paint" +} +team_email: "paint-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/reflections/OWNERS b/third_party/blink/web_tests/fast/reflections/OWNERS index 6904c86..e69de29 100644 --- a/third_party/blink/web_tests/fast/reflections/OWNERS +++ b/third_party/blink/web_tests/fast/reflections/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: paint-dev@chromium.org -# COMPONENT: Blink>Paint
diff --git a/third_party/blink/web_tests/fast/replaced/DIR_METADATA b/third_party/blink/web_tests/fast/replaced/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/replaced/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/replaced/OWNERS b/third_party/blink/web_tests/fast/replaced/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/replaced/OWNERS +++ b/third_party/blink/web_tests/fast/replaced/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/scroll-behavior/DIR_METADATA b/third_party/blink/web_tests/fast/scroll-behavior/DIR_METADATA new file mode 100644 index 0000000..8d7b73e --- /dev/null +++ b/third_party/blink/web_tests/fast/scroll-behavior/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Scroll" +} +team_email: "input-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/scroll-behavior/OWNERS b/third_party/blink/web_tests/fast/scroll-behavior/OWNERS index b6c7099b..e69de29 100644 --- a/third_party/blink/web_tests/fast/scroll-behavior/OWNERS +++ b/third_party/blink/web_tests/fast/scroll-behavior/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: input-dev@chromium.org -# COMPONENT: Blink>Scroll
diff --git a/third_party/blink/web_tests/fast/scrolling/DIR_METADATA b/third_party/blink/web_tests/fast/scrolling/DIR_METADATA new file mode 100644 index 0000000..8d7b73e --- /dev/null +++ b/third_party/blink/web_tests/fast/scrolling/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Scroll" +} +team_email: "input-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/scrolling/OWNERS b/third_party/blink/web_tests/fast/scrolling/OWNERS index b6c7099b..e69de29 100644 --- a/third_party/blink/web_tests/fast/scrolling/OWNERS +++ b/third_party/blink/web_tests/fast/scrolling/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: input-dev@chromium.org -# COMPONENT: Blink>Scroll
diff --git a/third_party/blink/web_tests/fast/serviceworker/DIR_METADATA b/third_party/blink/web_tests/fast/serviceworker/DIR_METADATA new file mode 100644 index 0000000..7d8a761e --- /dev/null +++ b/third_party/blink/web_tests/fast/serviceworker/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>ServiceWorker" +} +team_email: "worker-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/serviceworker/OWNERS b/third_party/blink/web_tests/fast/serviceworker/OWNERS index 106deab..e69de29 100644 --- a/third_party/blink/web_tests/fast/serviceworker/OWNERS +++ b/third_party/blink/web_tests/fast/serviceworker/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: worker-dev@chromium.org -# COMPONENT: Blink>ServiceWorker
diff --git a/third_party/blink/web_tests/fast/shapes/DIR_METADATA b/third_party/blink/web_tests/fast/shapes/DIR_METADATA new file mode 100644 index 0000000..d21906d --- /dev/null +++ b/third_party/blink/web_tests/fast/shapes/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/shapes/OWNERS b/third_party/blink/web_tests/fast/shapes/OWNERS index 7c1ec12..e69de29 100644 --- a/third_party/blink/web_tests/fast/shapes/OWNERS +++ b/third_party/blink/web_tests/fast/shapes/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout
diff --git a/third_party/blink/web_tests/fast/spatial-navigation/DIR_METADATA b/third_party/blink/web_tests/fast/spatial-navigation/DIR_METADATA new file mode 100644 index 0000000..1510459 --- /dev/null +++ b/third_party/blink/web_tests/fast/spatial-navigation/DIR_METADATA
@@ -0,0 +1 @@ +team_email: "dom-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/spatial-navigation/OWNERS b/third_party/blink/web_tests/fast/spatial-navigation/OWNERS index 422c227..e69de29 100644 --- a/third_party/blink/web_tests/fast/spatial-navigation/OWNERS +++ b/third_party/blink/web_tests/fast/spatial-navigation/OWNERS
@@ -1 +0,0 @@ -# TEAM: dom-dev@chromium.org
diff --git a/third_party/blink/web_tests/fast/sub-pixel/DIR_METADATA b/third_party/blink/web_tests/fast/sub-pixel/DIR_METADATA new file mode 100644 index 0000000..56b1ae24 --- /dev/null +++ b/third_party/blink/web_tests/fast/sub-pixel/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout>Subpixel" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/sub-pixel/OWNERS b/third_party/blink/web_tests/fast/sub-pixel/OWNERS index 83275e8..e69de29 100644 --- a/third_party/blink/web_tests/fast/sub-pixel/OWNERS +++ b/third_party/blink/web_tests/fast/sub-pixel/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout>Subpixel
diff --git a/third_party/blink/web_tests/fast/table/DIR_METADATA b/third_party/blink/web_tests/fast/table/DIR_METADATA new file mode 100644 index 0000000..49cd596 --- /dev/null +++ b/third_party/blink/web_tests/fast/table/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout>Table" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/table/OWNERS b/third_party/blink/web_tests/fast/table/OWNERS index 8c39d70..e69de29 100644 --- a/third_party/blink/web_tests/fast/table/OWNERS +++ b/third_party/blink/web_tests/fast/table/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout>Table
diff --git a/third_party/blink/web_tests/fast/text-autosizing/DIR_METADATA b/third_party/blink/web_tests/fast/text-autosizing/DIR_METADATA new file mode 100644 index 0000000..14afbed --- /dev/null +++ b/third_party/blink/web_tests/fast/text-autosizing/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>TextAutosize" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/text-autosizing/OWNERS b/third_party/blink/web_tests/fast/text-autosizing/OWNERS index f5afdf9..e69de29 100644 --- a/third_party/blink/web_tests/fast/text-autosizing/OWNERS +++ b/third_party/blink/web_tests/fast/text-autosizing/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>TextAutosize
diff --git a/third_party/blink/web_tests/fast/tokenizer/DIR_METADATA b/third_party/blink/web_tests/fast/tokenizer/DIR_METADATA new file mode 100644 index 0000000..1510459 --- /dev/null +++ b/third_party/blink/web_tests/fast/tokenizer/DIR_METADATA
@@ -0,0 +1 @@ +team_email: "dom-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/tokenizer/OWNERS b/third_party/blink/web_tests/fast/tokenizer/OWNERS index 422c227..e69de29 100644 --- a/third_party/blink/web_tests/fast/tokenizer/OWNERS +++ b/third_party/blink/web_tests/fast/tokenizer/OWNERS
@@ -1 +0,0 @@ -# TEAM: dom-dev@chromium.org
diff --git a/third_party/blink/web_tests/fast/webgl/DIR_METADATA b/third_party/blink/web_tests/fast/webgl/DIR_METADATA new file mode 100644 index 0000000..469c306 --- /dev/null +++ b/third_party/blink/web_tests/fast/webgl/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Canvas" +} +team_email: "paint-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/webgl/OWNERS b/third_party/blink/web_tests/fast/webgl/OWNERS index 14ca7d4e..e69de29 100644 --- a/third_party/blink/web_tests/fast/webgl/OWNERS +++ b/third_party/blink/web_tests/fast/webgl/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: paint-dev@chromium.org -# COMPONENT: Blink>Canvas
diff --git a/third_party/blink/web_tests/fast/workers/DIR_METADATA b/third_party/blink/web_tests/fast/workers/DIR_METADATA new file mode 100644 index 0000000..1201c65 --- /dev/null +++ b/third_party/blink/web_tests/fast/workers/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Workers" +} +team_email: "worker-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/workers/OWNERS b/third_party/blink/web_tests/fast/workers/OWNERS index 51dd60fe..e69de29 100644 --- a/third_party/blink/web_tests/fast/workers/OWNERS +++ b/third_party/blink/web_tests/fast/workers/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: worker-dev@chromium.org -# COMPONENT: Blink>Workers
diff --git a/third_party/blink/web_tests/fast/writing-mode/DIR_METADATA b/third_party/blink/web_tests/fast/writing-mode/DIR_METADATA new file mode 100644 index 0000000..c7d2a56 --- /dev/null +++ b/third_party/blink/web_tests/fast/writing-mode/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Layout>WritingMode" +} +team_email: "layout-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/writing-mode/OWNERS b/third_party/blink/web_tests/fast/writing-mode/OWNERS index 5ee69c13..e69de29 100644 --- a/third_party/blink/web_tests/fast/writing-mode/OWNERS +++ b/third_party/blink/web_tests/fast/writing-mode/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: layout-dev@chromium.org -# COMPONENT: Blink>Layout>WritingMode
diff --git a/third_party/blink/web_tests/fast/xmlhttprequest/DIR_METADATA b/third_party/blink/web_tests/fast/xmlhttprequest/DIR_METADATA new file mode 100644 index 0000000..89a667c --- /dev/null +++ b/third_party/blink/web_tests/fast/xmlhttprequest/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network>XHR" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/fast/xmlhttprequest/OWNERS b/third_party/blink/web_tests/fast/xmlhttprequest/OWNERS index d9e80484..e69de29 100644 --- a/third_party/blink/web_tests/fast/xmlhttprequest/OWNERS +++ b/third_party/blink/web_tests/fast/xmlhttprequest/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network>XHR
diff --git a/third_party/blink/web_tests/fast/xpath/DIR_METADATA b/third_party/blink/web_tests/fast/xpath/DIR_METADATA new file mode 100644 index 0000000..3f57820b --- /dev/null +++ b/third_party/blink/web_tests/fast/xpath/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Blink>XML" +}
diff --git a/third_party/blink/web_tests/fast/xpath/OWNERS b/third_party/blink/web_tests/fast/xpath/OWNERS index 5c2ac18..55fa2fc1 100644 --- a/third_party/blink/web_tests/fast/xpath/OWNERS +++ b/third_party/blink/web_tests/fast/xpath/OWNERS
@@ -1,5 +1,4 @@ # There's no real owners here. If you're familiar with the code please send # a CL to add yourself here. -# COMPONENT: Blink>XML dcheng@chromium.org -palmer@chromium.org +palmer@chromium.org \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/xsl/DIR_METADATA b/third_party/blink/web_tests/fast/xsl/DIR_METADATA new file mode 100644 index 0000000..3f57820b --- /dev/null +++ b/third_party/blink/web_tests/fast/xsl/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Blink>XML" +}
diff --git a/third_party/blink/web_tests/fast/xsl/OWNERS b/third_party/blink/web_tests/fast/xsl/OWNERS index 5c2ac18..55fa2fc1 100644 --- a/third_party/blink/web_tests/fast/xsl/OWNERS +++ b/third_party/blink/web_tests/fast/xsl/OWNERS
@@ -1,5 +1,4 @@ # There's no real owners here. If you're familiar with the code please send # a CL to add yourself here. -# COMPONENT: Blink>XML dcheng@chromium.org -palmer@chromium.org +palmer@chromium.org \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cached-sync-computed-styles.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cached-sync-computed-styles.js index c8ddf3e..ff18823 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cached-sync-computed-styles.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cached-sync-computed-styles.js
@@ -35,7 +35,7 @@ function step1(node) { var callsLeft = 2; nodeId = node.id; - TestRunner.addSniffer(Protocol.SessionRouter.prototype, 'sendMessage', onBackendCall, true); + TestRunner.addSniffer(ProtocolClient.SessionRouter.prototype, 'sendMessage', onBackendCall, true); TestRunner.cssModel.computedStylePromise(nodeId).then(styleCallback); TestRunner.cssModel.computedStylePromise(nodeId).then(styleCallback); function styleCallback() {
diff --git a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands-expected.txt b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands-expected.txt index 2a0c499..a2294ec7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands-expected.txt
@@ -1,7 +1,7 @@ Tests correctness of promisified protocol commands. error: Request Profiler.commandError failed. {"message":"this is the error message"} -commandError: catch result: {"message":"this is the error message"} +commandError: then result: null commandArgs0: then result: undefined error: Protocol Error: Extra 1 arguments in a call to method 'Profiler.commandArgs0'. commandArgs0: then result: null
diff --git a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js index 86b6111..4ea09a8 100644 --- a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js +++ b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js
@@ -5,7 +5,7 @@ (async function() { TestRunner.addResult(`Tests correctness of promisified protocol commands.\n`); - Protocol.test.suppressRequestErrors = false; + ProtocolClient.test.suppressRequestErrors = false; function dumpArgument(name, value) { TestRunner.addResult(name + ' result: ' + (typeof value === 'string' ? value : JSON.stringify(value))); } @@ -47,20 +47,20 @@ }] }; // The protocol definition above is not used, but is left as a reference for commands below. - Protocol.inspectorBackend.registerCommand('Profiler.commandArgs0', [], [], false); - Protocol.inspectorBackend.registerCommand( - 'Profiler.commandArgs1Rets0', [{'name': 'arg1', 'type': 'number', 'optional': false}], [], false); - Protocol.inspectorBackend.registerCommand( - 'Profiler.commandArgs1Rets1', [{'name': 'arg1', 'type': 'object', 'optional': false}], ['arg1'], false); - Protocol.inspectorBackend.registerCommand( + ProtocolClient.inspectorBackend.registerCommand('Profiler.commandArgs0', [], []); + ProtocolClient.inspectorBackend.registerCommand( + 'Profiler.commandArgs1Rets0', [{'name': 'arg1', 'type': 'number', 'optional': false}], []); + ProtocolClient.inspectorBackend.registerCommand( + 'Profiler.commandArgs1Rets1', [{'name': 'arg1', 'type': 'object', 'optional': false}], ['arg1']); + ProtocolClient.inspectorBackend.registerCommand( 'Profiler.commandArgs3Rets3', [ {'name': 'arg1', 'type': 'object', 'optional': false}, {'name': 'arg2', 'type': 'number', 'optional': true}, {'name': 'arg3', 'type': 'string', 'optional': true} ], - ['arg1', 'arg2', 'arg3'], false); - Protocol.inspectorBackend.registerCommand( - 'Profiler.commandError', [{'name': 'error', 'type': 'object', 'optional': false}], [], false); + ['arg1', 'arg2', 'arg3']); + ProtocolClient.inspectorBackend.registerCommand( + 'Profiler.commandError', [{'name': 'error', 'type': 'object', 'optional': false}], []); var sendMessageToBackendOriginal = InspectorFrontendHost.sendMessageToBackend; InspectorFrontendHost.sendMessageToBackend = sendMessageToBackendLoopback;
diff --git a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors-expected.txt b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors-expected.txt index 5d21d66..e418976 100644 --- a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors-expected.txt
@@ -48,7 +48,7 @@ { error : { code : -32602 - data : "nodeId: integer value expected" + data : "Failed to deserialize params - CBOR: map start expected <somewhere>" message : "Invalid parameters" } id : 4 @@ -57,7 +57,7 @@ { error : { code : -32602 - data : "nodeId: integer value expected" + data : "Failed to deserialize params - CBOR: map start expected <somewhere>" message : "Invalid parameters" } id : 5 @@ -66,7 +66,7 @@ { error : { code : -32602 - data : "nodeId: integer value expected" + data : "Failed to deserialize params.nodeId - BINDINGS: mandatory field missing <somewhere>" message : "Invalid parameters" } id : 6 @@ -75,7 +75,7 @@ { error : { code : -32602 - data : "nodeId: integer value expected" + data : "Failed to deserialize params.nodeId - BINDINGS: int32 value expected <somewhere>" message : "Invalid parameters" } id : 7
diff --git a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js index cb6916f..f9dab7c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js +++ b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js
@@ -5,6 +5,12 @@ (async function() { TestRunner.addResult(`Tests that InspectorBackendDispatcher is catching incorrect messages.\n`); + function trimErrorMessage(message) { + if (message.error && message.error.data) { + message.error.data = message.error.data.replace(/at position \d+/, "<somewhere>"); + } + return message; + } var messages = [ 'some wrong string', @@ -30,9 +36,9 @@ var numberOfReports = 0; - Protocol.InspectorBackend.reportProtocolError = function(error, message) { + ProtocolClient.InspectorBackend.reportProtocolError = function(error, message) { if (numberOfReports < messages.length) { - TestRunner.addObject(message); + TestRunner.addObject(trimErrorMessage(message)); TestRunner.addResult('-------------------------------------------------------'); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-parameters-ipv6-expected.txt b/third_party/blink/web_tests/http/tests/devtools/resource-parameters-ipv6-expected.txt index 38c84c44..04d6926e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-parameters-ipv6-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/resource-parameters-ipv6-expected.txt
@@ -8,7 +8,7 @@ cache : { } connection : <string> - pageref : "page_1" + pageref : "page_2" request : { bodySize : <number> cookies : [
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-frame-in-crafted-frame-expected.txt b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-frame-in-crafted-frame-expected.txt index d9b68e8..303b821e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-frame-in-crafted-frame-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-frame-in-crafted-frame-expected.txt
@@ -1,6 +1,7 @@ Tests that frame inside crafted frame doesn't cause 'MainFrameNavigated' event and correctly attaches to frame tree. crbug/259036 FrameAdded id: 2, parentFrameId: 1, isMainFrame: false + FrameNavigated id: 2, parentFrameId: 1, isMainFrame: false FrameAdded id: 3, parentFrameId: 2, isMainFrame: false FrameNavigated id: 3, parentFrameId: 2, isMainFrame: false
diff --git a/third_party/blink/web_tests/http/tests/devtools/screen-orientation-override.js b/third_party/blink/web_tests/http/tests/devtools/screen-orientation-override.js index a0b4d50..4840d7f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/screen-orientation-override.js +++ b/third_party/blink/web_tests/http/tests/devtools/screen-orientation-override.js
@@ -8,7 +8,7 @@ await TestRunner.navigatePromise('resources/screen-orientation-resource.html'); - Protocol.test.suppressRequestErrors = false; + ProtocolClient.test.suppressRequestErrors = false; function addDumpResult(next) { TestRunner.evaluateInPage('dump()', dumpCallback);
diff --git a/third_party/blink/web_tests/http/tests/sendbeacon/DIR_METADATA b/third_party/blink/web_tests/http/tests/sendbeacon/DIR_METADATA new file mode 100644 index 0000000..72f55a07b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/sendbeacon/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/sendbeacon/OWNERS b/third_party/blink/web_tests/http/tests/sendbeacon/OWNERS index 8263c35..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/sendbeacon/OWNERS +++ b/third_party/blink/web_tests/http/tests/sendbeacon/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/DIR_METADATA b/third_party/blink/web_tests/http/tests/serviceworker/DIR_METADATA new file mode 100644 index 0000000..7d8a761e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/serviceworker/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>ServiceWorker" +} +team_email: "worker-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/OWNERS b/third_party/blink/web_tests/http/tests/serviceworker/OWNERS index 106deab..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/serviceworker/OWNERS +++ b/third_party/blink/web_tests/http/tests/serviceworker/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: worker-dev@chromium.org -# COMPONENT: Blink>ServiceWorker
diff --git a/third_party/blink/web_tests/http/tests/streams/DIR_METADATA b/third_party/blink/web_tests/http/tests/streams/DIR_METADATA new file mode 100644 index 0000000..a036f653 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/streams/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network>StreamsAPI" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/streams/OWNERS b/third_party/blink/web_tests/http/tests/streams/OWNERS index b88fce6..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/streams/OWNERS +++ b/third_party/blink/web_tests/http/tests/streams/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network>StreamsAPI
diff --git a/third_party/blink/web_tests/http/tests/svg/DIR_METADATA b/third_party/blink/web_tests/http/tests/svg/DIR_METADATA new file mode 100644 index 0000000..ea801b86 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/svg/DIR_METADATA
@@ -0,0 +1 @@ +team_email: "paint-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/svg/OWNERS b/third_party/blink/web_tests/http/tests/svg/OWNERS index c5acf6a5..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/svg/OWNERS +++ b/third_party/blink/web_tests/http/tests/svg/OWNERS
@@ -1 +0,0 @@ -# TEAM: paint-dev@chromium.org
diff --git a/third_party/blink/web_tests/http/tests/usb/DIR_METADATA b/third_party/blink/web_tests/http/tests/usb/DIR_METADATA new file mode 100644 index 0000000..d8d7bf9 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/usb/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>USB" +} +team_email: "webusb@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/usb/OWNERS b/third_party/blink/web_tests/http/tests/usb/OWNERS index 8dc3166..acf1a9e 100644 --- a/third_party/blink/web_tests/http/tests/usb/OWNERS +++ b/third_party/blink/web_tests/http/tests/usb/OWNERS
@@ -1,4 +1 @@ file://chrome/browser/usb/OWNERS - -# COMPONENT: Blink>USB -# TEAM: webusb@chromium.org
diff --git a/third_party/blink/web_tests/http/tests/websocket/DIR_METADATA b/third_party/blink/web_tests/http/tests/websocket/DIR_METADATA new file mode 100644 index 0000000..60fd6e9 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/websocket/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network>WebSockets" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/websocket/OWNERS b/third_party/blink/web_tests/http/tests/websocket/OWNERS index 09bdfc47..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/websocket/OWNERS +++ b/third_party/blink/web_tests/http/tests/websocket/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network>WebSockets
diff --git a/third_party/blink/web_tests/http/tests/xmlhttprequest/DIR_METADATA b/third_party/blink/web_tests/http/tests/xmlhttprequest/DIR_METADATA new file mode 100644 index 0000000..89a667c --- /dev/null +++ b/third_party/blink/web_tests/http/tests/xmlhttprequest/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>Network>XHR" +} +team_email: "blink-network-dev@chromium.org"
diff --git a/third_party/blink/web_tests/http/tests/xmlhttprequest/OWNERS b/third_party/blink/web_tests/http/tests/xmlhttprequest/OWNERS index d9e80484..e69de29 100644 --- a/third_party/blink/web_tests/http/tests/xmlhttprequest/OWNERS +++ b/third_party/blink/web_tests/http/tests/xmlhttprequest/OWNERS
@@ -1,2 +0,0 @@ -# TEAM: blink-network-dev@chromium.org -# COMPONENT: Blink>Network>XHR
diff --git a/third_party/blink/web_tests/http/tests/xsl/DIR_METADATA b/third_party/blink/web_tests/http/tests/xsl/DIR_METADATA new file mode 100644 index 0000000..3f57820b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/xsl/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Blink>XML" +}
diff --git a/third_party/blink/web_tests/http/tests/xsl/OWNERS b/third_party/blink/web_tests/http/tests/xsl/OWNERS index 5c2ac18..55fa2fc1 100644 --- a/third_party/blink/web_tests/http/tests/xsl/OWNERS +++ b/third_party/blink/web_tests/http/tests/xsl/OWNERS
@@ -1,5 +1,4 @@ # There's no real owners here. If you're familiar with the code please send # a CL to add yourself here. -# COMPONENT: Blink>XML dcheng@chromium.org -palmer@chromium.org +palmer@chromium.org \ No newline at end of file
diff --git a/third_party/blink/web_tests/platform/win/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt b/third_party/blink/web_tests/platform/android/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt similarity index 100% rename from third_party/blink/web_tests/platform/win/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt rename to third_party/blink/web_tests/platform/android/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt
diff --git a/third_party/blink/web_tests/platform/mac-mac-arm11.0/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt b/third_party/blink/web_tests/platform/mac-mac-arm11.0/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt new file mode 100644 index 0000000..c2756963c --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac-arm11.0/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL text field selection for the input textarea assert_equals: updated selectionStart expected 1 but got 0 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt index c2756963c..64bbcdd 100644 --- a/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt +++ b/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/selection-not-application-textarea-expected.txt
@@ -1,4 +1,4 @@ This is a testharness.js-based test. -FAIL text field selection for the input textarea assert_equals: updated selectionStart expected 1 but got 0 +FAIL text field selection for the input textarea assert_equals: final selectionDirection expected "forward" but got "none" Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/plugins/focus-expected.txt b/third_party/blink/web_tests/plugins/focus-expected.txt index c5472ba..653ef8e 100644 --- a/third_party/blink/web_tests/plugins/focus-expected.txt +++ b/third_party/blink/web_tests/plugins/focus-expected.txt
@@ -1,8 +1,3 @@ -CONSOLE MESSAGE: Blink Test Plugin: initializing -CONSOLE MESSAGE: Blink Test Plugin: initializing -CONSOLE MESSAGE: Blink Test Plugin: initializing -CONSOLE MESSAGE: Blink Test Plugin: initializing -CONSOLE MESSAGE: Blink Test Plugin: DidChangeFocus(true) Test for Embed and Object for bug 32292: Unable to focus on embedded plugins such as Flash via javascript focus(). On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/blink/web_tests/plugins/focus.html b/third_party/blink/web_tests/plugins/focus.html index 45a0053..9b8873b 100644 --- a/third_party/blink/web_tests/plugins/focus.html +++ b/third_party/blink/web_tests/plugins/focus.html
@@ -29,6 +29,7 @@ </div> <script> description("Test for Embed and Object for bug 32292: Unable to focus on embedded plugins such as Flash via javascript focus()."); +testRunner.setDumpConsoleMessages(false); var jsTestIsAsync = true; var actualPlugins = document.querySelectorAll('.actualPlugin');
diff --git a/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js b/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js index 5eec2f4..de50a25 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js +++ b/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js
@@ -12,418 +12,19 @@ return { port, fakePort }; } -// Implementation of an UnderlyingSource to create a ReadableStream from a Mojo -// data pipe consumer handle. -class DataPipeSource { - constructor(consumer) { - this.consumer_ = consumer; - } - - async pull(controller) { - let chunk = new ArrayBuffer(64); - let {result, numBytes} = this.consumer_.readData(chunk); - if (result == Mojo.RESULT_OK) { - controller.enqueue(new Uint8Array(chunk, 0, numBytes)); - return; - } else if (result == Mojo.RESULT_FAILED_PRECONDITION) { - controller.close(); - return; - } else if (result == Mojo.RESULT_SHOULD_WAIT) { - await this.readable(); - return this.pull(controller); - } - } - - cancel() { - if (this.watcher_) - this.watcher_.cancel(); - this.consumer_.close(); - } - - readable() { - return new Promise((resolve) => { - this.watcher_ = - this.consumer_.watch({ readable: true, peerClosed: true }, () => { - this.watcher_.cancel(); - this.watcher_ = undefined; - resolve(); - }); - }); - } -} - -// Implementation of an UnderlyingSink to create a WritableStream from a Mojo -// data pipe producer handle. -class DataPipeSink { - constructor(producer) { - this._producer = producer; - } - - async write(chunk, controller) { - while (true) { - let {result, numBytes} = this._producer.writeData(chunk); - if (result == Mojo.RESULT_OK) { - if (numBytes == chunk.byteLength) { - return; - } - chunk = chunk.slice(numBytes); - } else if (result == Mojo.RESULT_FAILED_PRECONDITION) { - throw new DOMException('The pipe is closed.', 'InvalidStateError'); - } else if (result == Mojo.RESULT_SHOULD_WAIT) { - await this.writable(); - } - } - } - - close() { - assert_equals(undefined, this._watcher); - this._producer.close(); - } - - abort(reason) { - if (this._watcher) - this._watcher.cancel(); - this._producer.close(); - } - - writable() { - return new Promise((resolve) => { - this._watcher = - this._producer.watch({ writable: true, peerClosed: true }, () => { - this._watcher.cancel(); - this._watcher = undefined; - resolve(); - }); - }); - } -} - -// Implementation of blink.mojom.SerialPort. -class FakeSerialPort { - constructor() { - this.inputSignals_ = { - dataCarrierDetect: false, - clearToSend: false, - ringIndicator: false, - dataSetReady: false - }; - this.outputSignals_ = { - dataTerminalReady: false, - requestToSend: false, - break: false - }; - } - - open(options, client) { - if (this.binding_ !== undefined) { - // Port already open. - return null; - } - - let portPtr = new device.mojom.SerialPortPtr(); - this.binding_ = new mojo.Binding( - device.mojom.SerialPort, this, mojo.makeRequest(portPtr)); - this.binding_.setConnectionErrorHandler(() => { - this.close(); - }); - - this.options_ = options; - this.client_ = client; - // OS typically sets DTR on open. - this.outputSignals_.dataTerminalReady = true; - - return portPtr; - } - - write(data) { - return this.writer_.write(data); - } - - read() { - return this.reader_.read(); - } - - // Reads from the port until at least |targetLength| is read or the stream is - // closed. The data is returned as a combined Uint8Array. - readWithLength(targetLength) { - return readWithLength(this.reader_, targetLength); - } - - simulateReadError(error) { - this.writer_.close(); - this.writer_.releaseLock(); - this.writer_ = undefined; - this.writable_ = undefined; - this.client_.onReadError(error); - } - - simulateParityError() { - this.simulateReadError(device.mojom.SerialReceiveError.PARITY_ERROR); - } - - simulateDisconnectOnRead() { - this.simulateReadError(device.mojom.SerialReceiveError.DISCONNECTED); - } - - simulateWriteError(error) { - this.reader_.cancel(); - this.reader_ = undefined; - this.readable_ = undefined; - this.client_.onSendError(error); - } - - simulateSystemErrorOnWrite() { - this.simulateWriteError(device.mojom.SerialSendError.SYSTEM_ERROR); - } - - simulateDisconnectOnWrite() { - this.simulateWriteError(device.mojom.SerialSendError.DISCONNECTED); - } - - simulateInputSignals(signals) { - this.inputSignals_ = signals; - } - - get outputSignals() { - return this.outputSignals_; - } - - writable() { - if (this.writable_) - return Promise.resolve(); - - if (!this.writablePromise_) { - this.writablePromise_ = new Promise((resolve) => { - this.writableResolver_ = resolve; - }); - } - - return this.writablePromise_; - } - - readable() { - if (this.readable_) - return Promise.resolve(); - - if (!this.readablePromise_) { - this.readablePromise_ = new Promise((resolve) => { - this.readableResolver_ = resolve; - }); - } - - return this.readablePromise_; - } - - async startWriting(in_stream) { - this.readable_ = new ReadableStream(new DataPipeSource(in_stream)); - this.reader_ = this.readable_.getReader(); - if (this.readableResolver_) { - this.readableResolver_(); - this.readableResolver_ = undefined; - this.readablePromise_ = undefined; - } - } - - async startReading(out_stream) { - this.writable_ = new WritableStream(new DataPipeSink(out_stream)); - this.writer_ = this.writable_.getWriter(); - if (this.writableResolver_) { - this.writableResolver_(); - this.writableResolver_ = undefined; - this.writablePromise_ = undefined; - } - } - - async flush(mode) { - switch (mode) { - case device.mojom.SerialPortFlushMode.kReceive: - this.writer_.abort(); - this.writer_.releaseLock(); - this.writer_ = undefined; - this.writable_ = undefined; - break; - case device.mojom.SerialPortFlushMode.kTransmit: - this.reader_.cancel(); - this.reader_ = undefined; - this.readable_ = undefined; - break; - } - } - - async drain() { - await this.reader_.closed; - } - - async getControlSignals() { - const signals = { - dcd: this.inputSignals_.dataCarrierDetect, - cts: this.inputSignals_.clearToSend, - ri: this.inputSignals_.ringIndicator, - dsr: this.inputSignals_.dataSetReady - }; - return {signals}; - } - - async setControlSignals(signals) { - if (signals.hasDtr) { - this.outputSignals_.dataTerminalReady = signals.dtr; - } - if (signals.hasRts) { - this.outputSignals_.requestToSend = signals.rts; - } - if (signals.hasBrk) { - this.outputSignals_.break = signals.brk; - } - return { success: true }; - } - - async configurePort(options) { - this.options_ = options; - return { success: true }; - } - - async getPortInfo() { - return { - bitrate: this.options_.bitrate, - data_bits: this.options_.data_bits, - parity_bit: this.options_.parity_bit, - stop_bits: this.options_.stop_bits, - cts_flow_control: this.options_.has_cts_flow_control ? - this.options_.cts_flow_control : false - }; - } - - async close() { - // OS typically clears DTR on close. - this.outputSignals_.dataTerminalReady = false; - if (this.writer_) { - this.writer_.close(); - this.writer_.releaseLock(); - this.writer_ = undefined; - } - this.writable_ = undefined; - - if (this.binding_) { - this.binding_.close(); - this.binding_ = undefined; - } - return {}; - } -} - -// Implementation of blink.mojom.SerialService. -class FakeSerialService { - constructor() { - this.interceptor_ = - new MojoInterfaceInterceptor(blink.mojom.SerialService.name); - this.interceptor_.oninterfacerequest = e => this.bind(e.handle); - this.bindingSet_ = new mojo.BindingSet(blink.mojom.SerialService); - this.clients_ = []; - this.nextToken_ = 0; - this.reset(); - } - - start() { - this.interceptor_.start(); - } - - stop() { - this.interceptor_.stop(); - } - - reset() { - this.ports_ = new Map(); - this.selectedPort_ = null; - } - - addPort(info) { - let portInfo = new blink.mojom.SerialPortInfo(); - if (info?.usbVendorId !== undefined) { - portInfo.hasUsbVendorId = true; - portInfo.usbVendorId = info.usbVendorId; - } - if (info?.usbProductId !== undefined) { - portInfo.hasUsbProductId = true; - portInfo.usbProductId = info.usbProductId; - } - - let token = ++this.nextToken_; - portInfo.token = new mojoBase.mojom.UnguessableToken(); - portInfo.token.high = 0; - portInfo.token.low = token; - - let record = { - portInfo: portInfo, - fakePort: new FakeSerialPort(), - }; - this.ports_.set(token, record); - - for (let client of this.clients_) { - client.onPortAdded(portInfo); - } - - return token; - } - - removePort(token) { - let record = this.ports_.get(token); - if (record === undefined) { - return; - } - - this.ports_.delete(token); - - for (let client of this.clients_) { - client.onPortRemoved(record.portInfo); - } - } - - setSelectedPort(token) { - this.selectedPort_ = this.ports_.get(token); - } - - getFakePort(token) { - let record = this.ports_.get(token); - if (record === undefined) - return undefined; - return record.fakePort; - } - - bind(handle) { - this.bindingSet_.addBinding(this, handle); - } - - async setClient(client_remote) { - this.clients_.push(client_remote); - } - - async getPorts() { - return { - ports: Array.from(this.ports_, ([token, record]) => record.portInfo) - }; - } - - async requestPort(filters) { - if (this.selectedPort_) - return { port: this.selectedPort_.portInfo }; - else - return { port: null }; - } - - async openPort(token, options, client) { - let record = this.ports_.get(token.low); - if (record !== undefined) { - return {port: record.fakePort.open(options, client)}; - } else { - return {port: null}; - } - } -} - -let fakeSerialService = new FakeSerialService(); +let fakeSerialService = undefined; function serial_test(func, name, properties) { promise_test(async (test) => { + if (fakeSerialService === undefined) { + await loadMojoResources([ + '/gen/mojo/public/mojom/base/unguessable_token.mojom.js', + '/gen/services/device/public/mojom/serial.mojom.js', + '/gen/third_party/blink/public/mojom/serial/serial.mojom.js', + ]); + await loadScript('resources/fake-serial.js'); + } + fakeSerialService.start(); try { await func(test, fakeSerialService);
diff --git a/third_party/blink/web_tests/wpt_internal/serial/resources/fake-serial.js b/third_party/blink/web_tests/wpt_internal/serial/resources/fake-serial.js new file mode 100644 index 0000000..4e3dfcb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/serial/resources/fake-serial.js
@@ -0,0 +1,409 @@ +// Implementation of an UnderlyingSource to create a ReadableStream from a Mojo +// data pipe consumer handle. +class DataPipeSource { + constructor(consumer) { + this.consumer_ = consumer; + } + + async pull(controller) { + let chunk = new ArrayBuffer(64); + let {result, numBytes} = this.consumer_.readData(chunk); + if (result == Mojo.RESULT_OK) { + controller.enqueue(new Uint8Array(chunk, 0, numBytes)); + return; + } else if (result == Mojo.RESULT_FAILED_PRECONDITION) { + controller.close(); + return; + } else if (result == Mojo.RESULT_SHOULD_WAIT) { + await this.readable(); + return this.pull(controller); + } + } + + cancel() { + if (this.watcher_) + this.watcher_.cancel(); + this.consumer_.close(); + } + + readable() { + return new Promise((resolve) => { + this.watcher_ = + this.consumer_.watch({ readable: true, peerClosed: true }, () => { + this.watcher_.cancel(); + this.watcher_ = undefined; + resolve(); + }); + }); + } +} + +// Implementation of an UnderlyingSink to create a WritableStream from a Mojo +// data pipe producer handle. +class DataPipeSink { + constructor(producer) { + this._producer = producer; + } + + async write(chunk, controller) { + while (true) { + let {result, numBytes} = this._producer.writeData(chunk); + if (result == Mojo.RESULT_OK) { + if (numBytes == chunk.byteLength) { + return; + } + chunk = chunk.slice(numBytes); + } else if (result == Mojo.RESULT_FAILED_PRECONDITION) { + throw new DOMException('The pipe is closed.', 'InvalidStateError'); + } else if (result == Mojo.RESULT_SHOULD_WAIT) { + await this.writable(); + } + } + } + + close() { + assert_equals(undefined, this._watcher); + this._producer.close(); + } + + abort(reason) { + if (this._watcher) + this._watcher.cancel(); + this._producer.close(); + } + + writable() { + return new Promise((resolve) => { + this._watcher = + this._producer.watch({ writable: true, peerClosed: true }, () => { + this._watcher.cancel(); + this._watcher = undefined; + resolve(); + }); + }); + } +} + +// Implementation of blink.mojom.SerialPort. +class FakeSerialPort { + constructor() { + this.inputSignals_ = { + dataCarrierDetect: false, + clearToSend: false, + ringIndicator: false, + dataSetReady: false + }; + this.outputSignals_ = { + dataTerminalReady: false, + requestToSend: false, + break: false + }; + } + + open(options, client) { + if (this.binding_ !== undefined) { + // Port already open. + return null; + } + + let portPtr = new device.mojom.SerialPortPtr(); + this.binding_ = new mojo.Binding( + device.mojom.SerialPort, this, mojo.makeRequest(portPtr)); + this.binding_.setConnectionErrorHandler(() => { + this.close(); + }); + + this.options_ = options; + this.client_ = client; + // OS typically sets DTR on open. + this.outputSignals_.dataTerminalReady = true; + + return portPtr; + } + + write(data) { + return this.writer_.write(data); + } + + read() { + return this.reader_.read(); + } + + // Reads from the port until at least |targetLength| is read or the stream is + // closed. The data is returned as a combined Uint8Array. + readWithLength(targetLength) { + return readWithLength(this.reader_, targetLength); + } + + simulateReadError(error) { + this.writer_.close(); + this.writer_.releaseLock(); + this.writer_ = undefined; + this.writable_ = undefined; + this.client_.onReadError(error); + } + + simulateParityError() { + this.simulateReadError(device.mojom.SerialReceiveError.PARITY_ERROR); + } + + simulateDisconnectOnRead() { + this.simulateReadError(device.mojom.SerialReceiveError.DISCONNECTED); + } + + simulateWriteError(error) { + this.reader_.cancel(); + this.reader_ = undefined; + this.readable_ = undefined; + this.client_.onSendError(error); + } + + simulateSystemErrorOnWrite() { + this.simulateWriteError(device.mojom.SerialSendError.SYSTEM_ERROR); + } + + simulateDisconnectOnWrite() { + this.simulateWriteError(device.mojom.SerialSendError.DISCONNECTED); + } + + simulateInputSignals(signals) { + this.inputSignals_ = signals; + } + + get outputSignals() { + return this.outputSignals_; + } + + writable() { + if (this.writable_) + return Promise.resolve(); + + if (!this.writablePromise_) { + this.writablePromise_ = new Promise((resolve) => { + this.writableResolver_ = resolve; + }); + } + + return this.writablePromise_; + } + + readable() { + if (this.readable_) + return Promise.resolve(); + + if (!this.readablePromise_) { + this.readablePromise_ = new Promise((resolve) => { + this.readableResolver_ = resolve; + }); + } + + return this.readablePromise_; + } + + async startWriting(in_stream) { + this.readable_ = new ReadableStream(new DataPipeSource(in_stream)); + this.reader_ = this.readable_.getReader(); + if (this.readableResolver_) { + this.readableResolver_(); + this.readableResolver_ = undefined; + this.readablePromise_ = undefined; + } + } + + async startReading(out_stream) { + this.writable_ = new WritableStream(new DataPipeSink(out_stream)); + this.writer_ = this.writable_.getWriter(); + if (this.writableResolver_) { + this.writableResolver_(); + this.writableResolver_ = undefined; + this.writablePromise_ = undefined; + } + } + + async flush(mode) { + switch (mode) { + case device.mojom.SerialPortFlushMode.kReceive: + this.writer_.abort(); + this.writer_.releaseLock(); + this.writer_ = undefined; + this.writable_ = undefined; + break; + case device.mojom.SerialPortFlushMode.kTransmit: + this.reader_.cancel(); + this.reader_ = undefined; + this.readable_ = undefined; + break; + } + } + + async drain() { + await this.reader_.closed; + } + + async getControlSignals() { + const signals = { + dcd: this.inputSignals_.dataCarrierDetect, + cts: this.inputSignals_.clearToSend, + ri: this.inputSignals_.ringIndicator, + dsr: this.inputSignals_.dataSetReady + }; + return {signals}; + } + + async setControlSignals(signals) { + if (signals.hasDtr) { + this.outputSignals_.dataTerminalReady = signals.dtr; + } + if (signals.hasRts) { + this.outputSignals_.requestToSend = signals.rts; + } + if (signals.hasBrk) { + this.outputSignals_.break = signals.brk; + } + return { success: true }; + } + + async configurePort(options) { + this.options_ = options; + return { success: true }; + } + + async getPortInfo() { + return { + bitrate: this.options_.bitrate, + data_bits: this.options_.data_bits, + parity_bit: this.options_.parity_bit, + stop_bits: this.options_.stop_bits, + cts_flow_control: this.options_.has_cts_flow_control ? + this.options_.cts_flow_control : false + }; + } + + async close() { + // OS typically clears DTR on close. + this.outputSignals_.dataTerminalReady = false; + if (this.writer_) { + this.writer_.close(); + this.writer_.releaseLock(); + this.writer_ = undefined; + } + this.writable_ = undefined; + + if (this.binding_) { + this.binding_.close(); + this.binding_ = undefined; + } + return {}; + } +} + +// Implementation of blink.mojom.SerialService. +class FakeSerialService { + constructor() { + this.interceptor_ = + new MojoInterfaceInterceptor(blink.mojom.SerialService.name); + this.interceptor_.oninterfacerequest = e => this.bind(e.handle); + this.bindingSet_ = new mojo.BindingSet(blink.mojom.SerialService); + this.clients_ = []; + this.nextToken_ = 0; + this.reset(); + } + + start() { + this.interceptor_.start(); + } + + stop() { + this.interceptor_.stop(); + } + + reset() { + this.ports_ = new Map(); + this.selectedPort_ = null; + } + + addPort(info) { + let portInfo = new blink.mojom.SerialPortInfo(); + if (info?.usbVendorId !== undefined) { + portInfo.hasUsbVendorId = true; + portInfo.usbVendorId = info.usbVendorId; + } + if (info?.usbProductId !== undefined) { + portInfo.hasUsbProductId = true; + portInfo.usbProductId = info.usbProductId; + } + + let token = ++this.nextToken_; + portInfo.token = new mojoBase.mojom.UnguessableToken(); + portInfo.token.high = 0; + portInfo.token.low = token; + + let record = { + portInfo: portInfo, + fakePort: new FakeSerialPort(), + }; + this.ports_.set(token, record); + + for (let client of this.clients_) { + client.onPortAdded(portInfo); + } + + return token; + } + + removePort(token) { + let record = this.ports_.get(token); + if (record === undefined) { + return; + } + + this.ports_.delete(token); + + for (let client of this.clients_) { + client.onPortRemoved(record.portInfo); + } + } + + setSelectedPort(token) { + this.selectedPort_ = this.ports_.get(token); + } + + getFakePort(token) { + let record = this.ports_.get(token); + if (record === undefined) + return undefined; + return record.fakePort; + } + + bind(handle) { + this.bindingSet_.addBinding(this, handle); + } + + async setClient(client_remote) { + this.clients_.push(client_remote); + } + + async getPorts() { + return { + ports: Array.from(this.ports_, ([token, record]) => record.portInfo) + }; + } + + async requestPort(filters) { + if (this.selectedPort_) + return { port: this.selectedPort_.portInfo }; + else + return { port: null }; + } + + async openPort(token, options, client) { + let record = this.ports_.get(token.low); + if (record !== undefined) { + return {port: record.fakePort.open(options, client)}; + } else { + return {port: null}; + } + } +} + +fakeSerialService = new FakeSerialService();
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.any.js similarity index 74% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.any.js index 766b8b2..ec949a9 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_close.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window-expected.txt b/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any-expected.txt similarity index 100% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window-expected.txt rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any-expected.txt
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any.js similarity index 94% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any.js index 80acc69..fa3db6a 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window-expected.txt b/third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any.worker-expected.txt similarity index 100% copy from third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.window-expected.txt copy to third_party/blink/web_tests/wpt_internal/serial/serialPort_events.https.any.worker-expected.txt
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.any.js similarity index 72% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.any.js index d6a5264..2e0df3b 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_getInfo.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.any.js similarity index 83% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.any.js index 30494d3..968697f3 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_getSignals.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.any.js similarity index 82% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.any.js index 267ab53..b20f69d2 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_ondisconnect.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.any.js similarity index 90% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.any.js index 498a11c..ca13877 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_open.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.any.js similarity index 86% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.any.js index 6b2ca96..fd1b08f 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_cancel.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.any.js similarity index 78% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.any.js index 3f1b79d..552567c 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_chain.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.any.js similarity index 62% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.any.js index bc03091..21196f7 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_closeLocked.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.any.js similarity index 71% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.any.js index f5e111e..3532745a 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_disconnect.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_gc.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_gc.https.window.js index c986f62e..480ccff 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_gc.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_gc.https.window.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.any.js similarity index 70% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.any.js index f6721a0..f808751 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_largeRead.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.any.js similarity index 66% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.any.js index f6ee00f..1a12cc2 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_open.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.any.js similarity index 83% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.any.js index b078a3e..7afd494 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_parityError.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.any.js similarity index 72% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.any.js index bb48301..13c6d48 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_pipeThrough.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.any.js similarity index 67% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.any.js index 0c0fb45..b53ea71 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_readable_smallRead.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.any.js similarity index 84% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.any.js index fbc2c2ba..ac20b256 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_setSignals.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.any.js similarity index 96% rename from third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.any.js index c5a3bdd..9728af7d 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serialPort_writable.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts-mojoServiceUnavailable.https.any.js b/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts-mojoServiceUnavailable.https.any.js new file mode 100644 index 0000000..ba2c5285 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts-mojoServiceUnavailable.https.any.js
@@ -0,0 +1,18 @@ +// META: script=/resources/test-only-api.js + +promise_test(async () => { + await loadMojoResources([ + '/gen/mojo/public/mojom/base/unguessable_token.mojom.js', + '/gen/third_party/blink/public/mojom/serial/serial.mojom.js', + ]); + + let interceptor = + new MojoInterfaceInterceptor(blink.mojom.SerialService.name); + interceptor.oninterfacerequest = e => e.handle.close(); + interceptor.start(); + + let ports = await navigator.serial.getPorts(); + assert_equals(ports.length, 0); + + interceptor.stop(); +}, 'getPorts() returns empty list if Mojo service connection fails');
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.any.js b/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.any.js new file mode 100644 index 0000000..03ab5f7 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.any.js
@@ -0,0 +1,25 @@ +// META: script=/resources/test-only-api.js +// META: script=/serial/resources/common.js +// META: script=resources/automation.js + +serial_test(async (t, fake) => { + fake.addPort(); + fake.addPort(); + + let ports = await navigator.serial.getPorts(); + assert_equals(ports.length, 2); + assert_true(ports[0] instanceof SerialPort); + assert_true(ports[1] instanceof SerialPort); +}, 'getPorts() returns the set of configured fake ports'); + +serial_test(async (t, fake) => { + fake.addPort(); + + let portsFirst = await navigator.serial.getPorts(); + assert_equals(portsFirst.length, 1, 'first call returns one port'); + assert_true(portsFirst[0] instanceof SerialPort); + let portsSecond = await navigator.serial.getPorts(); + assert_equals(portsSecond.length, 1, 'second call returns one port'); + assert_true(portsSecond[0] instanceof SerialPort); + assert_true(portsFirst[0] === portsSecond[0]); +}, 'getPorts() returns the same port objects every time');
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.window.js deleted file mode 100644 index fe67e9e..0000000 --- a/third_party/blink/web_tests/wpt_internal/serial/serial_getPorts.https.window.js +++ /dev/null
@@ -1,41 +0,0 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js -// META: script=/serial/resources/common.js -// META: script=resources/automation.js - -promise_test(async () => { - let interceptor = - new MojoInterfaceInterceptor(blink.mojom.SerialService.name); - interceptor.oninterfacerequest = e => e.handle.close(); - interceptor.start(); - - let ports = await navigator.serial.getPorts(); - assert_equals(ports.length, 0); - - interceptor.stop(); -}, 'getPorts() returns empty list if Mojo service connection fails'); - -serial_test(async (t, fake) => { - fake.addPort(); - fake.addPort(); - - let ports = await navigator.serial.getPorts(); - assert_equals(ports.length, 2); - assert_true(ports[0] instanceof SerialPort); - assert_true(ports[1] instanceof SerialPort); -}, 'getPorts() returns the set of configured fake ports'); - -serial_test(async (t, fake) => { - fake.addPort(); - - let portsFirst = await navigator.serial.getPorts(); - assert_equals(portsFirst.length, 1, 'first call returns one port'); - assert_true(portsFirst[0] instanceof SerialPort); - let portsSecond = await navigator.serial.getPorts(); - assert_equals(portsSecond.length, 1, 'second call returns one port'); - assert_true(portsSecond[0] instanceof SerialPort); - assert_true(portsFirst[0] === portsSecond[0]); -}, 'getPorts() returns the same port objects every time');
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.any.js similarity index 76% rename from third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.any.js index 58d8534..e2ff9a0 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_onconnect.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.any.js similarity index 80% rename from third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.window.js rename to third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.any.js index 57fb1e9..583a9ea 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_ondisconnect.https.any.js
@@ -1,8 +1,4 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort-mojoServiceUnavailable.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort-mojoServiceUnavailable.https.window.js new file mode 100644 index 0000000..c3187795 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort-mojoServiceUnavailable.https.window.js
@@ -0,0 +1,24 @@ +// META: script=/resources/testdriver.js +// META: script=/resources/testdriver-vendor.js +// META: script=/resources/test-only-api.js +// META: script=resources/automation.js + +promise_test(async (t) => { + await loadMojoResources([ + '/gen/mojo/public/mojom/base/unguessable_token.mojom.js', + '/gen/third_party/blink/public/mojom/serial/serial.mojom.js', + ]); + + let interceptor = + new MojoInterfaceInterceptor(blink.mojom.SerialService.name); + interceptor.oninterfacerequest = e => e.handle.close(); + interceptor.start(); + + await trustedClick(); + try { + await promise_rejects_dom( + t, 'NotFoundError', navigator.serial.requestPort()); + } finally { + interceptor.stop(); + } +}, 'requestPort() rejects if Mojo service connection fails');
diff --git a/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort.https.window.js b/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort.https.window.js index 083a7352..5b79b8f 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort.https.window.js +++ b/third_party/blink/web_tests/wpt_internal/serial/serial_requestPort.https.window.js
@@ -1,33 +1,14 @@ -// META: script=/resources/testharness.js -// META: script=/resources/testharnessreport.js // META: script=/resources/testdriver.js // META: script=/resources/testdriver-vendor.js -// META: script=/gen/layout_test_data/mojo/public/js/mojo_bindings.js -// META: script=/gen/mojo/public/mojom/base/unguessable_token.mojom.js -// META: script=/gen/third_party/blink/public/mojom/serial/serial.mojom.js +// META: script=/resources/test-only-api.js // META: script=/serial/resources/common.js // META: script=resources/automation.js -promise_test((t) => { +serial_test((t, fake) => { return promise_rejects_dom( t, 'SecurityError', navigator.serial.requestPort()); }, 'requestPort() rejects without a user gesture'); -promise_test(async (t) => { - let interceptor = - new MojoInterfaceInterceptor(blink.mojom.SerialService.name); - interceptor.oninterfacerequest = e => e.handle.close(); - interceptor.start(); - - await trustedClick(); - try { - await promise_rejects_dom( - t, 'NotFoundError', navigator.serial.requestPort()); - } finally { - interceptor.stop(); - } -}, 'requestPort() rejects if Mojo service connection fails'); - serial_test(async (t, fake) => { await trustedClick(); return promise_rejects_dom(
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index 727a7b9..cfc784fe 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Short Name: crashpad URL: https://crashpad.chromium.org/ Version: unknown -Revision: b6f2d06996335c951bfb72f98b5b9e22dc9bc03e +Revision: 83f194ee8544aec1c00683e1cf4e86458f33e035 License: Apache 2.0 License File: crashpad/LICENSE Security Critical: yes
diff --git a/third_party/crashpad/crashpad/DEPS b/third_party/crashpad/crashpad/DEPS index fbff155..db8fd8d 100644 --- a/third_party/crashpad/crashpad/DEPS +++ b/third_party/crashpad/crashpad/DEPS
@@ -28,7 +28,7 @@ '9e121212d42be62a7cce38072f925f8398d11e49', 'crashpad/third_party/edo/edo': { 'url': Var('chromium_git') + '/external/github.com/google/eDistantObject.git@' + - '97121c64019fa0e8bfbc8254e3ccb5572c500746', + '6ffbf833173f53fcd06ecf08670a95cc01c01f72', 'condition': 'checkout_ios', }, 'crashpad/third_party/googletest/googletest': @@ -42,7 +42,7 @@ '7bde79cc274d06451bf65ae82c012a5d3e476b5a', 'crashpad/third_party/mini_chromium/mini_chromium': Var('chromium_git') + '/chromium/mini_chromium@' + - 'cb82d71291f19590d3ee138ba64fcf1e9e0edd84', + 'c748b289b825056985f3dd3b36dc86c766d787ad', 'crashpad/third_party/libfuzzer/src': Var('chromium_git') + '/chromium/llvm-project/compiler-rt/lib/fuzzer.git@' + 'fda403cf93ecb8792cb1d061564d89a6553ca020',
diff --git a/third_party/crashpad/crashpad/build/ios/setup_ios_gn.py b/third_party/crashpad/crashpad/build/ios/setup_ios_gn.py index 5f1829ee..9522ce6 100755 --- a/third_party/crashpad/crashpad/build/ios/setup_ios_gn.py +++ b/third_party/crashpad/crashpad/build/ios/setup_ios_gn.py
@@ -199,7 +199,6 @@ gn_command = [gn_path, '--root=%s' % os.path.realpath(src_path), '-q'] if generate_xcode_project: gn_command.append('--ide=xcode') - gn_command.append('--root-target=gn_all') gn_command.append('--ninja-executable=autoninja') if self._settings.has_section('filters'): target_filters = self._settings.values('filters')
diff --git a/third_party/crashpad/crashpad/snapshot/BUILD.gn b/third_party/crashpad/crashpad/snapshot/BUILD.gn index 6ca9bd4..79f5eeb 100644 --- a/third_party/crashpad/crashpad/snapshot/BUILD.gn +++ b/third_party/crashpad/crashpad/snapshot/BUILD.gn
@@ -368,6 +368,8 @@ "linux/exception_snapshot_linux_test.cc", "linux/process_reader_linux_test.cc", "linux/system_snapshot_linux_test.cc", + "linux/test_modules.cc", + "linux/test_modules.h", "sanitized/process_snapshot_sanitized_test.cc", "sanitized/sanitization_information_test.cc", ]
diff --git a/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous.h b/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous.h index 0c30e1a..90106c9 100644 --- a/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous.h +++ b/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous.h
@@ -41,7 +41,7 @@ //! \brief The difference between the preferred load address in the ELF file //! and the actual loaded address in memory. - LinuxVMOffset load_bias; + VMAddress load_bias; //! \brief The address of the dynamic array for this object. LinuxVMAddress dynamic_array;
diff --git a/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous_test.cc b/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous_test.cc index 3e5722d5..5de6e96a 100644 --- a/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous_test.cc +++ b/third_party/crashpad/crashpad/snapshot/linux/debug_rendezvous_test.cc
@@ -27,6 +27,7 @@ #include "build/build_config.h" #include "gtest/gtest.h" #include "snapshot/elf/elf_image_reader.h" +#include "snapshot/linux/test_modules.h" #include "test/linux/fake_ptrace_connection.h" #include "test/main_arguments.h" #include "test/multiprocess.h" @@ -34,6 +35,7 @@ #include "util/linux/auxiliary_vector.h" #include "util/linux/direct_ptrace_connection.h" #include "util/linux/memory_map.h" +#include "util/numeric/safe_assignment.h" #include "util/process/process_memory_linux.h" #include "util/process/process_memory_range.h" @@ -45,6 +47,20 @@ namespace test { namespace { +void ExpectLoadBias(bool is_64_bit, + VMAddress unsigned_bias, + VMOffset signed_bias) { + if (is_64_bit) { + EXPECT_EQ(unsigned_bias, static_cast<VMAddress>(signed_bias)); + } else { + uint32_t unsigned_bias32; + ASSERT_TRUE(AssignIfInRange(&unsigned_bias32, unsigned_bias)); + + uint32_t casted_bias32 = static_cast<uint32_t>(signed_bias); + EXPECT_EQ(unsigned_bias32, casted_bias32); + } +} + void TestAgainstTarget(PtraceConnection* connection) { // Use ElfImageReader on the main executable which can tell us the debug // address. glibc declares the symbol _r_debug in link.h which we can use to @@ -112,9 +128,11 @@ // Android's loader doesn't set the load bias until Android 4.3 (API 18). if (android_runtime_api >= 18) { - EXPECT_EQ(debug.Executable()->load_bias, exe_reader.GetLoadBias()); + ExpectLoadBias(connection->Is64Bit(), + debug.Executable()->load_bias, + exe_reader.GetLoadBias()); } else { - EXPECT_EQ(debug.Executable()->load_bias, 0); + EXPECT_EQ(debug.Executable()->load_bias, 0u); } for (const DebugRendezvous::LinkEntry& module : debug.Modules()) { @@ -130,7 +148,7 @@ // (API 17). if (is_android_loader && android_runtime_api < 17) { EXPECT_EQ(module.dynamic_array, 0u); - EXPECT_EQ(module.load_bias, 0); + EXPECT_EQ(module.load_bias, 0u); continue; } @@ -170,7 +188,11 @@ const std::string& module_name) { const bool is_vdso_mapping = device == 0 && inode == 0 && mapping_name == "[vdso]"; +#if defined(ARCH_CPU_X86) + static constexpr char kPrefix[] = "linux-gate.so."; +#else static constexpr char kPrefix[] = "linux-vdso.so."; +#endif return is_vdso_mapping == (module_name.empty() || module_name.compare(0, strlen(kPrefix), kPrefix) == 0); @@ -185,9 +207,11 @@ // (API 20) until Android 6.0 (API 23). if (is_android_loader && android_runtime_api > 20 && android_runtime_api < 23) { - EXPECT_EQ(module.load_bias, 0); + EXPECT_EQ(module.load_bias, 0u); } else { - EXPECT_EQ(module.load_bias, module_reader->GetLoadBias()); + ExpectLoadBias(connection->Is64Bit(), + module.load_bias, + static_cast<VMAddress>(module_reader->GetLoadBias())); } CheckedLinuxAddressRange module_range( @@ -196,7 +220,13 @@ } } -TEST(DebugRendezvous, DISABLED_Self) { +TEST(DebugRendezvous, Self) { + const std::string module_name = "test_module.so"; + const std::string module_soname = "test_module_soname"; + ScopedModuleHandle empty_test_module( + LoadTestModule(module_name, module_soname)); + ASSERT_TRUE(empty_test_module.valid()); + FakePtraceConnection connection; ASSERT_TRUE(connection.Initialize(getpid())); @@ -221,7 +251,7 @@ DISALLOW_COPY_AND_ASSIGN(ChildTest); }; -TEST(DebugRendezvous, DISABLED_Child) { +TEST(DebugRendezvous, Child) { ChildTest test; test.Run(); }
diff --git a/third_party/crashpad/crashpad/snapshot/linux/process_reader_linux_test.cc b/third_party/crashpad/crashpad/snapshot/linux/process_reader_linux_test.cc index 98b99e6..c3b8723 100644 --- a/third_party/crashpad/crashpad/snapshot/linux/process_reader_linux_test.cc +++ b/third_party/crashpad/crashpad/snapshot/linux/process_reader_linux_test.cc
@@ -37,6 +37,7 @@ #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "gtest/gtest.h" +#include "snapshot/linux/test_modules.h" #include "test/errors.h" #include "test/linux/fake_ptrace_connection.h" #include "test/linux/get_tls.h" @@ -541,218 +542,6 @@ #endif // !OS_ANDROID || !ARCH_CPU_ARMEL || __ANDROID_API__ >= 21 } -bool WriteTestModule(const base::FilePath& module_path, - const std::string& soname) { -#if defined(ARCH_CPU_64_BITS) - using Ehdr = Elf64_Ehdr; - using Phdr = Elf64_Phdr; - using Shdr = Elf64_Shdr; - using Dyn = Elf64_Dyn; - using Sym = Elf64_Sym; - unsigned char elf_class = ELFCLASS64; -#else - using Ehdr = Elf32_Ehdr; - using Phdr = Elf32_Phdr; - using Shdr = Elf32_Shdr; - using Dyn = Elf32_Dyn; - using Sym = Elf32_Sym; - unsigned char elf_class = ELFCLASS32; -#endif - - struct { - Ehdr ehdr; - struct { - Phdr load1; - Phdr load2; - Phdr dynamic; - } phdr_table; - struct { - Dyn hash; - Dyn strtab; - Dyn symtab; - Dyn strsz; - Dyn syment; - Dyn soname; - Dyn null; - } dynamic_array; - struct { - Elf32_Word nbucket; - Elf32_Word nchain; - Elf32_Word bucket; - Elf32_Word chain; - } hash_table; - char string_table[32]; - struct { - } section_header_string_table; - struct { - Sym und_symbol; - } symbol_table; - struct { - Shdr null; - Shdr dynamic; - Shdr string_table; - Shdr section_header_string_table; - } shdr_table; - } module = {}; - - module.ehdr.e_ident[EI_MAG0] = ELFMAG0; - module.ehdr.e_ident[EI_MAG1] = ELFMAG1; - module.ehdr.e_ident[EI_MAG2] = ELFMAG2; - module.ehdr.e_ident[EI_MAG3] = ELFMAG3; - - module.ehdr.e_ident[EI_CLASS] = elf_class; - -#if defined(ARCH_CPU_LITTLE_ENDIAN) - module.ehdr.e_ident[EI_DATA] = ELFDATA2LSB; -#else - module.ehdr.e_ident[EI_DATA] = ELFDATA2MSB; -#endif // ARCH_CPU_LITTLE_ENDIAN - - module.ehdr.e_ident[EI_VERSION] = EV_CURRENT; - - module.ehdr.e_type = ET_DYN; - -#if defined(ARCH_CPU_X86) - module.ehdr.e_machine = EM_386; -#elif defined(ARCH_CPU_X86_64) - module.ehdr.e_machine = EM_X86_64; -#elif defined(ARCH_CPU_ARMEL) - module.ehdr.e_machine = EM_ARM; -#elif defined(ARCH_CPU_ARM64) - module.ehdr.e_machine = EM_AARCH64; -#elif defined(ARCH_CPU_MIPSEL) || defined(ARCH_CPU_MIPS64EL) - module.ehdr.e_machine = EM_MIPS; -#endif - - module.ehdr.e_version = EV_CURRENT; - module.ehdr.e_ehsize = sizeof(module.ehdr); - - module.ehdr.e_phoff = offsetof(decltype(module), phdr_table); - module.ehdr.e_phnum = sizeof(module.phdr_table) / sizeof(Phdr); - module.ehdr.e_phentsize = sizeof(Phdr); - - module.ehdr.e_shoff = offsetof(decltype(module), shdr_table); - module.ehdr.e_shentsize = sizeof(Shdr); - module.ehdr.e_shnum = sizeof(module.shdr_table) / sizeof(Shdr); - module.ehdr.e_shstrndx = - offsetof(decltype(module.shdr_table), section_header_string_table) / - sizeof(Shdr); - - constexpr size_t load2_vaddr = 0x200000; - - module.phdr_table.load1.p_type = PT_LOAD; - module.phdr_table.load1.p_offset = 0; - module.phdr_table.load1.p_vaddr = 0; - module.phdr_table.load1.p_filesz = offsetof(decltype(module), shdr_table); - module.phdr_table.load1.p_memsz = offsetof(decltype(module), shdr_table); - module.phdr_table.load1.p_flags = PF_R; - module.phdr_table.load1.p_align = load2_vaddr; - - module.phdr_table.load2.p_type = PT_LOAD; - module.phdr_table.load2.p_offset = 0; - module.phdr_table.load2.p_vaddr = load2_vaddr; - module.phdr_table.load2.p_filesz = offsetof(decltype(module), shdr_table); - module.phdr_table.load2.p_memsz = offsetof(decltype(module), shdr_table); - module.phdr_table.load2.p_flags = PF_R | PF_W; - module.phdr_table.load2.p_align = load2_vaddr; - - module.phdr_table.dynamic.p_type = PT_DYNAMIC; - module.phdr_table.dynamic.p_offset = - offsetof(decltype(module), dynamic_array); - module.phdr_table.dynamic.p_vaddr = - load2_vaddr + module.phdr_table.dynamic.p_offset; - module.phdr_table.dynamic.p_filesz = sizeof(module.dynamic_array); - module.phdr_table.dynamic.p_memsz = sizeof(module.dynamic_array); - module.phdr_table.dynamic.p_flags = PF_R | PF_W; - module.phdr_table.dynamic.p_align = 8; - - module.dynamic_array.hash.d_tag = DT_HASH; - module.dynamic_array.hash.d_un.d_ptr = offsetof(decltype(module), hash_table); - module.dynamic_array.strtab.d_tag = DT_STRTAB; - module.dynamic_array.strtab.d_un.d_ptr = - offsetof(decltype(module), string_table); - module.dynamic_array.symtab.d_tag = DT_SYMTAB; - module.dynamic_array.symtab.d_un.d_ptr = - offsetof(decltype(module), symbol_table); - module.dynamic_array.strsz.d_tag = DT_STRSZ; - module.dynamic_array.strsz.d_un.d_val = sizeof(module.string_table); - module.dynamic_array.syment.d_tag = DT_SYMENT; - module.dynamic_array.syment.d_un.d_val = sizeof(Sym); - constexpr size_t kSonameOffset = 1; - module.dynamic_array.soname.d_tag = DT_SONAME; - module.dynamic_array.soname.d_un.d_val = kSonameOffset; - - module.dynamic_array.null.d_tag = DT_NULL; - - module.hash_table.nbucket = 1; - module.hash_table.nchain = 1; - module.hash_table.bucket = 0; - module.hash_table.chain = 0; - - CHECK_GE(sizeof(module.string_table), soname.size() + 2); - module.string_table[0] = '\0'; - memcpy(&module.string_table[kSonameOffset], soname.c_str(), soname.size()); - - module.shdr_table.null.sh_type = SHT_NULL; - - module.shdr_table.dynamic.sh_name = 0; - module.shdr_table.dynamic.sh_type = SHT_DYNAMIC; - module.shdr_table.dynamic.sh_flags = SHF_WRITE | SHF_ALLOC; - module.shdr_table.dynamic.sh_addr = module.phdr_table.dynamic.p_vaddr; - module.shdr_table.dynamic.sh_offset = module.phdr_table.dynamic.p_offset; - module.shdr_table.dynamic.sh_size = module.phdr_table.dynamic.p_filesz; - module.shdr_table.dynamic.sh_link = - offsetof(decltype(module.shdr_table), string_table) / sizeof(Shdr); - - module.shdr_table.string_table.sh_name = 0; - module.shdr_table.string_table.sh_type = SHT_STRTAB; - module.shdr_table.string_table.sh_offset = - offsetof(decltype(module), string_table); - module.shdr_table.string_table.sh_size = sizeof(module.string_table); - - module.shdr_table.section_header_string_table.sh_name = 0; - module.shdr_table.section_header_string_table.sh_type = SHT_STRTAB; - module.shdr_table.section_header_string_table.sh_offset = - offsetof(decltype(module), section_header_string_table); - module.shdr_table.section_header_string_table.sh_size = - sizeof(module.section_header_string_table); - - FileWriter writer; - if (!writer.Open(module_path, - FileWriteMode::kCreateOrFail, - FilePermissions::kWorldReadable)) { - ADD_FAILURE(); - return false; - } - - if (!writer.Write(&module, sizeof(module))) { - ADD_FAILURE(); - return false; - } - - return true; -} - -ScopedModuleHandle LoadTestModule(const std::string& module_name, - const std::string& module_soname) { - base::FilePath module_path( - TestPaths::Executable().DirName().Append(module_name)); - - if (!WriteTestModule(module_path, module_soname)) { - return ScopedModuleHandle(nullptr); - } - EXPECT_TRUE(IsRegularFile(module_path)); - - ScopedModuleHandle handle( - dlopen(module_path.value().c_str(), RTLD_LAZY | RTLD_LOCAL)); - EXPECT_TRUE(handle.valid()) - << "dlopen: " << module_path.value() << " " << dlerror(); - - EXPECT_TRUE(LoggingRemoveFile(module_path)); - - return handle; -} - void ExpectTestModule(ProcessReaderLinux* reader, const std::string& module_name) { for (const auto& module : reader->Modules()) {
diff --git a/third_party/crashpad/crashpad/snapshot/linux/test_modules.cc b/third_party/crashpad/crashpad/snapshot/linux/test_modules.cc new file mode 100644 index 0000000..b2450c20 --- /dev/null +++ b/third_party/crashpad/crashpad/snapshot/linux/test_modules.cc
@@ -0,0 +1,262 @@ +// Copyright 2020 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "snapshot/linux/test_modules.h" + +#include <elf.h> + +#include <limits> + +#include "base/check_op.h" +#include "base/files/file_path.h" +#include "build/build_config.h" +#include "gtest/gtest.h" +#include "test/test_paths.h" +#include "util/file/filesystem.h" +#include "util/file/file_writer.h" + +namespace crashpad { +namespace test { + +bool WriteTestModule(const base::FilePath& module_path, + const std::string& soname) { +#if defined(ARCH_CPU_64_BITS) + using Ehdr = Elf64_Ehdr; + using Phdr = Elf64_Phdr; + using Shdr = Elf64_Shdr; + using Dyn = Elf64_Dyn; + using Sym = Elf64_Sym; + unsigned char elf_class = ELFCLASS64; +#else + using Ehdr = Elf32_Ehdr; + using Phdr = Elf32_Phdr; + using Shdr = Elf32_Shdr; + using Dyn = Elf32_Dyn; + using Sym = Elf32_Sym; + unsigned char elf_class = ELFCLASS32; +#endif + + struct { + Ehdr ehdr; + struct { + Phdr load1; + Phdr load2; + Phdr dynamic; + } phdr_table; + struct { + Dyn hash; + Dyn strtab; + Dyn symtab; + Dyn strsz; + Dyn syment; + Dyn soname; + Dyn null; + } dynamic_array; + struct { + Elf32_Word nbucket; + Elf32_Word nchain; + Elf32_Word bucket; + Elf32_Word chain; + } hash_table; + char string_table[32]; + struct { + } section_header_string_table; + struct { + Sym und_symbol; + } symbol_table; + struct { + Shdr null; + Shdr dynamic; + Shdr string_table; + Shdr section_header_string_table; + } shdr_table; + } module = {}; + + module.ehdr.e_ident[EI_MAG0] = ELFMAG0; + module.ehdr.e_ident[EI_MAG1] = ELFMAG1; + module.ehdr.e_ident[EI_MAG2] = ELFMAG2; + module.ehdr.e_ident[EI_MAG3] = ELFMAG3; + + module.ehdr.e_ident[EI_CLASS] = elf_class; + +#if defined(ARCH_CPU_LITTLE_ENDIAN) + module.ehdr.e_ident[EI_DATA] = ELFDATA2LSB; +#else + module.ehdr.e_ident[EI_DATA] = ELFDATA2MSB; +#endif // ARCH_CPU_LITTLE_ENDIAN + + module.ehdr.e_ident[EI_VERSION] = EV_CURRENT; + + module.ehdr.e_type = ET_DYN; + +#if defined(ARCH_CPU_X86) + module.ehdr.e_machine = EM_386; +#elif defined(ARCH_CPU_X86_64) + module.ehdr.e_machine = EM_X86_64; +#elif defined(ARCH_CPU_ARMEL) + module.ehdr.e_machine = EM_ARM; +#elif defined(ARCH_CPU_ARM64) + module.ehdr.e_machine = EM_AARCH64; +#elif defined(ARCH_CPU_MIPSEL) || defined(ARCH_CPU_MIPS64EL) + module.ehdr.e_machine = EM_MIPS; +#endif + + module.ehdr.e_version = EV_CURRENT; + module.ehdr.e_ehsize = sizeof(module.ehdr); + + module.ehdr.e_phoff = offsetof(decltype(module), phdr_table); + module.ehdr.e_phnum = sizeof(module.phdr_table) / sizeof(Phdr); + module.ehdr.e_phentsize = sizeof(Phdr); + + module.ehdr.e_shoff = offsetof(decltype(module), shdr_table); + module.ehdr.e_shentsize = sizeof(Shdr); + module.ehdr.e_shnum = sizeof(module.shdr_table) / sizeof(Shdr); + module.ehdr.e_shstrndx = + offsetof(decltype(module.shdr_table), section_header_string_table) / + sizeof(Shdr); + + const size_t page_size = getpagesize(); + auto align = [page_size](uintptr_t addr) { + return (addr + page_size - 1) & ~(page_size - 1); + }; + constexpr size_t segment_size = offsetof(decltype(module), shdr_table); + + // This test module covers cases where: + // 1. Multiple segments are mapped from file offset 0. + // 2. Load bias is negative. + + const uintptr_t load2_vaddr = align(std::numeric_limits<uintptr_t>::max() - + align(segment_size) - page_size); + const uintptr_t load1_vaddr = load2_vaddr - align(segment_size); + + module.phdr_table.load1.p_type = PT_LOAD; + module.phdr_table.load1.p_offset = 0; + module.phdr_table.load1.p_vaddr = load1_vaddr; + module.phdr_table.load1.p_filesz = segment_size; + module.phdr_table.load1.p_memsz = segment_size; + module.phdr_table.load1.p_flags = PF_R; + module.phdr_table.load1.p_align = page_size; + + module.phdr_table.load2.p_type = PT_LOAD; + module.phdr_table.load2.p_offset = 0; + module.phdr_table.load2.p_vaddr = load2_vaddr; + module.phdr_table.load2.p_filesz = segment_size; + module.phdr_table.load2.p_memsz = segment_size; + module.phdr_table.load2.p_flags = PF_R | PF_W; + module.phdr_table.load2.p_align = page_size; + + module.phdr_table.dynamic.p_type = PT_DYNAMIC; + module.phdr_table.dynamic.p_offset = + offsetof(decltype(module), dynamic_array); + module.phdr_table.dynamic.p_vaddr = + load2_vaddr + module.phdr_table.dynamic.p_offset; + module.phdr_table.dynamic.p_filesz = sizeof(module.dynamic_array); + module.phdr_table.dynamic.p_memsz = sizeof(module.dynamic_array); + module.phdr_table.dynamic.p_flags = PF_R | PF_W; + module.phdr_table.dynamic.p_align = 8; + + module.dynamic_array.hash.d_tag = DT_HASH; + module.dynamic_array.hash.d_un.d_ptr = + load1_vaddr + offsetof(decltype(module), hash_table); + module.dynamic_array.strtab.d_tag = DT_STRTAB; + module.dynamic_array.strtab.d_un.d_ptr = + load1_vaddr + offsetof(decltype(module), string_table); + module.dynamic_array.symtab.d_tag = DT_SYMTAB; + module.dynamic_array.symtab.d_un.d_ptr = + load1_vaddr + offsetof(decltype(module), symbol_table); + module.dynamic_array.strsz.d_tag = DT_STRSZ; + module.dynamic_array.strsz.d_un.d_val = sizeof(module.string_table); + module.dynamic_array.syment.d_tag = DT_SYMENT; + module.dynamic_array.syment.d_un.d_val = sizeof(Sym); + constexpr size_t kSonameOffset = 1; + module.dynamic_array.soname.d_tag = DT_SONAME; + module.dynamic_array.soname.d_un.d_val = kSonameOffset; + + module.dynamic_array.null.d_tag = DT_NULL; + + module.hash_table.nbucket = 1; + module.hash_table.nchain = 1; + module.hash_table.bucket = 0; + module.hash_table.chain = 0; + + if (sizeof(module.string_table) < soname.size() + 2) { + ADD_FAILURE() << "string table too small"; + return false; + } + module.string_table[0] = '\0'; + memcpy(&module.string_table[kSonameOffset], soname.c_str(), soname.size()); + + module.shdr_table.null.sh_type = SHT_NULL; + + module.shdr_table.dynamic.sh_name = 0; + module.shdr_table.dynamic.sh_type = SHT_DYNAMIC; + module.shdr_table.dynamic.sh_flags = SHF_WRITE | SHF_ALLOC; + module.shdr_table.dynamic.sh_addr = module.phdr_table.dynamic.p_vaddr; + module.shdr_table.dynamic.sh_offset = module.phdr_table.dynamic.p_offset; + module.shdr_table.dynamic.sh_size = module.phdr_table.dynamic.p_filesz; + module.shdr_table.dynamic.sh_link = + offsetof(decltype(module.shdr_table), string_table) / sizeof(Shdr); + + module.shdr_table.string_table.sh_name = 0; + module.shdr_table.string_table.sh_type = SHT_STRTAB; + module.shdr_table.string_table.sh_offset = + offsetof(decltype(module), string_table); + module.shdr_table.string_table.sh_size = sizeof(module.string_table); + + module.shdr_table.section_header_string_table.sh_name = 0; + module.shdr_table.section_header_string_table.sh_type = SHT_STRTAB; + module.shdr_table.section_header_string_table.sh_offset = + offsetof(decltype(module), section_header_string_table); + module.shdr_table.section_header_string_table.sh_size = + sizeof(module.section_header_string_table); + + FileWriter writer; + if (!writer.Open(module_path, + FileWriteMode::kCreateOrFail, + FilePermissions::kWorldReadable)) { + ADD_FAILURE(); + return false; + } + + if (!writer.Write(&module, sizeof(module))) { + ADD_FAILURE(); + LoggingRemoveFile(module_path); + return false; + } + + return true; +} + +ScopedModuleHandle LoadTestModule(const std::string& module_name, + const std::string& module_soname) { + base::FilePath module_path( + TestPaths::Executable().DirName().Append(module_name)); + + if (!WriteTestModule(module_path, module_soname)) { + return ScopedModuleHandle(nullptr); + } + EXPECT_TRUE(IsRegularFile(module_path)); + + ScopedModuleHandle handle( + dlopen(module_path.value().c_str(), RTLD_LAZY | RTLD_LOCAL)); + EXPECT_TRUE(handle.valid()) + << "dlopen: " << module_path.value() << " " << dlerror(); + + EXPECT_TRUE(LoggingRemoveFile(module_path)); + + return handle; +} + +} // namespace test +} // namespace crashpad
diff --git a/third_party/crashpad/crashpad/snapshot/linux/test_modules.h b/third_party/crashpad/crashpad/snapshot/linux/test_modules.h new file mode 100644 index 0000000..b791480a --- /dev/null +++ b/third_party/crashpad/crashpad/snapshot/linux/test_modules.h
@@ -0,0 +1,37 @@ +// Copyright 2020 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_SNAPSHOT_LINUX_TEST_MODULES_H_ +#define CRASHPAD_SNAPSHOT_LINUX_TEST_MODULES_H_ + +#include <string> + +#include "test/scoped_module_handle.h" + +namespace crashpad { +namespace test { + +//! \brief Constructs and loads a test module. +//! +//! \param module_name The filename of the mdoule. +//! \param module_soname The SONAME for the module. +//! \return a handle to the loaded module on success. On failure, the handle +//! will be invalid and a message will be logged. +ScopedModuleHandle LoadTestModule(const std::string& module_name, + const std::string& module_soname); + +} // namespace test +} // namespace crashpad + +#endif // CRASHPAD_SNAPSHOT_LINUX_DEBUG_RENDEZVOUS_H_
diff --git a/third_party/crashpad/crashpad/snapshot/snapshot_test.gyp b/third_party/crashpad/crashpad/snapshot/snapshot_test.gyp index 43de725..a4d4d9e 100644 --- a/third_party/crashpad/crashpad/snapshot/snapshot_test.gyp +++ b/third_party/crashpad/crashpad/snapshot/snapshot_test.gyp
@@ -80,6 +80,8 @@ 'linux/exception_snapshot_linux_test.cc', 'linux/process_reader_linux_test.cc', 'linux/system_snapshot_linux_test.cc', + 'linux/test_modules.cc', + 'linux/test_modules.h', 'mac/cpu_context_mac_test.cc', 'mac/mach_o_image_annotations_reader_test.cc', 'mac/mach_o_image_reader_test.cc',
diff --git a/third_party/crashpad/crashpad/test/fuchsia_crashpad_tests.cmx b/third_party/crashpad/crashpad/test/fuchsia_crashpad_tests.cmx index b25208d8..87004b2 100644 --- a/third_party/crashpad/crashpad/test/fuchsia_crashpad_tests.cmx +++ b/third_party/crashpad/crashpad/test/fuchsia_crashpad_tests.cmx
@@ -7,6 +7,9 @@ } } }, + "include": [ + "sdk/lib/diagnostics/syslog/client.shard.cmx" + ], "program": { "binary": "test/crashpad_tests" },
diff --git a/third_party/crashpad/crashpad/third_party/edo/BUILD.gn b/third_party/crashpad/crashpad/third_party/edo/BUILD.gn index 2b8d5b9..73dca1a 100644 --- a/third_party/crashpad/crashpad/third_party/edo/BUILD.gn +++ b/third_party/crashpad/crashpad/third_party/edo/BUILD.gn
@@ -124,8 +124,8 @@ "edo/Service/Sources/NSKeyedArchiver+EDOAdditions.m", "edo/Service/Sources/NSKeyedUnarchiver+EDOAdditions.h", "edo/Service/Sources/NSKeyedUnarchiver+EDOAdditions.m", - "edo/Service/Sources/NSObject+EDOBlacklistedType.h", - "edo/Service/Sources/NSObject+EDOBlacklistedType.m", + "edo/Service/Sources/NSObject+EDOBlockedType.h", + "edo/Service/Sources/NSObject+EDOBlockedType.m", "edo/Service/Sources/NSObject+EDOParameter.h", "edo/Service/Sources/NSObject+EDOParameter.m", "edo/Service/Sources/NSObject+EDOValue.h",
diff --git a/third_party/crashpad/crashpad/third_party/lss/README.crashpad b/third_party/crashpad/crashpad/third_party/lss/README.crashpad index c036ae0..d1ac991 100644 --- a/third_party/crashpad/crashpad/third_party/lss/README.crashpad +++ b/third_party/crashpad/crashpad/third_party/lss/README.crashpad
@@ -3,7 +3,7 @@ URL: https://chromium.googlesource.com/linux-syscall-support/ Revision: See DEPS License: BSD 3-clause -License File: lss/linux-syscall-support.h +License File: lss/linux_syscall_support.h Security Critical: yes Description:
diff --git a/third_party/crashpad/crashpad/util/linux/ptrace_broker.cc b/third_party/crashpad/crashpad/util/linux/ptrace_broker.cc index b6b5bb13..68621f2 100644 --- a/third_party/crashpad/crashpad/util/linux/ptrace_broker.cc +++ b/third_party/crashpad/crashpad/util/linux/ptrace_broker.cc
@@ -17,6 +17,7 @@ #include <fcntl.h> #include <limits.h> #include <string.h> +#include <sys/mman.h> #include <syscall.h> #include <unistd.h> @@ -24,7 +25,11 @@ #include "base/check_op.h" #include "base/posix/eintr_wrapper.h" +#include "base/process/process_metrics.h" +#include "third_party/lss/lss.h" +#include "util/linux/scoped_ptrace_attach.h" #include "util/misc/memory_sanitizer.h" +#include "util/posix/scoped_mmap.h" namespace crashpad { @@ -52,18 +57,58 @@ } // namespace +class PtraceBroker::AttachmentsArray { + public: + AttachmentsArray() : allocation_(false), attach_count_(0) {} + + ~AttachmentsArray() { + for (size_t index = 0; index < attach_count_; ++index) { + PtraceDetach(Attachments()[index], false); + } + } + + bool Initialize() { + return allocation_.ResetMmap(nullptr, + base::GetPageSize(), + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); + } + + bool Attach(pid_t pid) { + pid_t* attach = AllocateAttachment(); + if (!attach || !PtraceAttach(pid, false)) { + return false; + } + + *attach = pid; + return true; + } + + private: + pid_t* AllocateAttachment() { + if (attach_count_ >= (allocation_.len() / sizeof(pid_t))) { + return nullptr; + } + return &Attachments()[attach_count_++]; + } + + pid_t* Attachments() { return allocation_.addr_as<pid_t*>(); } + + ScopedMmap allocation_; + size_t attach_count_; + + DISALLOW_COPY_AND_ASSIGN(AttachmentsArray); +}; + PtraceBroker::PtraceBroker(int sock, pid_t pid, bool is_64_bit) : ptracer_(is_64_bit, /* can_log= */ false), file_root_(file_root_buffer_), - attachments_(nullptr), - attach_count_(0), - attach_capacity_(0), memory_file_(), sock_(sock), memory_pid_(pid), tried_opening_mem_file_(false) { - AllocateAttachments(); - static constexpr char kProc[] = "/proc/"; size_t root_length = strlen(kProc); memcpy(file_root_buffer_, kProc, root_length); @@ -88,35 +133,12 @@ } int PtraceBroker::Run() { - int result = RunImpl(); - ReleaseAttachments(); - return result; + AttachmentsArray attachments; + attachments.Initialize(); + return RunImpl(&attachments); } -bool PtraceBroker::AllocateAttachments() { - constexpr size_t page_size = 4096; - constexpr size_t alloc_size = - (sizeof(ScopedPtraceAttach) + page_size - 1) & ~(page_size - 1); - void* alloc = sbrk(alloc_size); - if (reinterpret_cast<intptr_t>(alloc) == -1) { - return false; - } - - if (attachments_ == nullptr) { - attachments_ = reinterpret_cast<ScopedPtraceAttach*>(alloc); - } - - attach_capacity_ += alloc_size / sizeof(ScopedPtraceAttach); - return true; -} - -void PtraceBroker::ReleaseAttachments() { - for (size_t index = 0; index < attach_count_; ++index) { - attachments_[index].Reset(); - } -} - -int PtraceBroker::RunImpl() { +int PtraceBroker::RunImpl(AttachmentsArray* attachments) { while (true) { Request request = {}; if (!ReadFileExactly(sock_, &request, sizeof(request))) { @@ -129,25 +151,10 @@ switch (request.type) { case Request::kTypeAttach: { - ScopedPtraceAttach* attach; - ScopedPtraceAttach stack_attach; - bool attach_on_stack = false; - - if (attach_capacity_ > attach_count_ || AllocateAttachments()) { - attach = new (&attachments_[attach_count_]) ScopedPtraceAttach; - } else { - attach = &stack_attach; - attach_on_stack = true; - } - ExceptionHandlerProtocol::Bool status = - ExceptionHandlerProtocol::kBoolFalse; - if (attach->ResetAttach(request.tid)) { - status = ExceptionHandlerProtocol::kBoolTrue; - if (!attach_on_stack) { - ++attach_count_; - } - } + attachments->Attach(request.tid) + ? ExceptionHandlerProtocol::kBoolTrue + : ExceptionHandlerProtocol::kBoolFalse; if (!WriteFile(sock_, &status, sizeof(status))) { return errno; @@ -160,9 +167,6 @@ } } - if (attach_on_stack && status == ExceptionHandlerProtocol::kBoolTrue) { - return RunImpl(); - } continue; }
diff --git a/third_party/crashpad/crashpad/util/linux/ptrace_broker.h b/third_party/crashpad/crashpad/util/linux/ptrace_broker.h index 6a7bfb7..5d90cb2 100644 --- a/third_party/crashpad/crashpad/util/linux/ptrace_broker.h +++ b/third_party/crashpad/crashpad/util/linux/ptrace_broker.h
@@ -24,7 +24,6 @@ #include "util/linux/exception_handler_protocol.h" #include "util/linux/ptrace_connection.h" #include "util/linux/ptracer.h" -#include "util/linux/scoped_ptrace_attach.h" #include "util/linux/thread_info.h" #include "util/misc/address_types.h" @@ -186,16 +185,13 @@ //! This method returns when a PtraceBrokerRequest with type kTypeExit is //! received or an error is encountered on the socket. //! - //! This method calls `sbrk`, which may break other memory management tools, - //! such as `malloc`. - //! //! \return 0 if Run() exited due to an exit request. Otherwise an error code. int Run(); private: - bool AllocateAttachments(); - void ReleaseAttachments(); - int RunImpl(); + class AttachmentsArray; + + int RunImpl(AttachmentsArray*); int SendError(ExceptionHandlerProtocol::Errno err); int SendReadError(ReadError err); int SendOpenResult(OpenResult result); @@ -210,9 +206,6 @@ char file_root_buffer_[32]; Ptracer ptracer_; const char* file_root_; - ScopedPtraceAttach* attachments_; - size_t attach_count_; - size_t attach_capacity_; ScopedFileHandle memory_file_; int sock_; pid_t memory_pid_;
diff --git a/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.cc b/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.cc index 09e3fba..eed83455 100644 --- a/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.cc +++ b/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.cc
@@ -22,6 +22,32 @@ namespace crashpad { +bool PtraceAttach(pid_t pid, bool can_log) { + if (ptrace(PTRACE_ATTACH, pid, nullptr, nullptr) != 0) { + PLOG_IF(ERROR, can_log) << "ptrace"; + return false; + } + + int status; + if (HANDLE_EINTR(waitpid(pid, &status, __WALL)) < 0) { + PLOG_IF(ERROR, can_log) << "waitpid"; + return false; + } + if (!WIFSTOPPED(status)) { + LOG_IF(ERROR, can_log) << "process not stopped"; + return false; + } + return true; +} + +bool PtraceDetach(pid_t pid, bool can_log) { + if (pid >= 0 && ptrace(PTRACE_DETACH, pid, nullptr, nullptr) != 0) { + PLOG_IF(ERROR, can_log) << "ptrace"; + return false; + } + return true; +} + ScopedPtraceAttach::ScopedPtraceAttach() : pid_(-1) {} @@ -30,8 +56,7 @@ } bool ScopedPtraceAttach::Reset() { - if (pid_ >= 0 && ptrace(PTRACE_DETACH, pid_, nullptr, nullptr) != 0) { - PLOG(ERROR) << "ptrace"; + if (!PtraceDetach(pid_, true)) { return false; } pid_ = -1; @@ -41,21 +66,11 @@ bool ScopedPtraceAttach::ResetAttach(pid_t pid) { Reset(); - if (ptrace(PTRACE_ATTACH, pid, nullptr, nullptr) != 0) { - PLOG(ERROR) << "ptrace"; + if (!PtraceAttach(pid, true)) { return false; } - pid_ = pid; - int status; - if (HANDLE_EINTR(waitpid(pid_, &status, __WALL)) < 0) { - PLOG(ERROR) << "waitpid"; - return false; - } - if (!WIFSTOPPED(status)) { - LOG(ERROR) << "process not stopped"; - return false; - } + pid_ = pid; return true; }
diff --git a/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.h b/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.h index a3d9d69..f380d25 100644 --- a/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.h +++ b/third_party/crashpad/crashpad/util/linux/scoped_ptrace_attach.h
@@ -21,6 +21,24 @@ namespace crashpad { +//! \brief Attaches to the process with process ID \a pid and blocks until the +//! target process has stopped by calling `waitpid()`. +//! +//! \param pid The process ID of the process to attach to. +//! \param can_log Whether this function may log messages on failure. +//! \return `true` on success. `false` on failure with a message logged if \a +//! can_log is `true`. +bool PtraceAttach(pid_t pid, bool can_log = true); + +//! \brief Detaches the process with process ID \a pid. The process must +//! already be ptrace attached. +//! +//! \param pid The process ID of the process to detach. +//! \param can_log Whether this function may log messages on failure. +//! \return `true` on success. `false` on failure with a message logged if \a +//! ca_log is `true `true` +bool PtraceDetach(pid_t pid, bool can_log = true); + //! \brief Maintains a `ptrace()` attachment to a process. //! //! On destruction, the process will be detached.
diff --git a/third_party/crashpad/crashpad/util/posix/scoped_mmap.cc b/third_party/crashpad/crashpad/util/posix/scoped_mmap.cc index 0c98ba2..21533d2 100644 --- a/third_party/crashpad/crashpad/util/posix/scoped_mmap.cc +++ b/third_party/crashpad/crashpad/util/posix/scoped_mmap.cc
@@ -22,12 +22,54 @@ #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/numerics/safe_math.h" +#include "base/process/process_metrics.h" +#include "build/build_config.h" + +#if defined(OS_LINUX) +#include "third_party/lss/lss.h" +#endif namespace { -bool Munmap(uintptr_t addr, size_t len) { - if (munmap(reinterpret_cast<void*>(addr), len) != 0) { - PLOG(ERROR) << "munmap"; +#if defined(OS_LINUX) +void* CallMmap(void* addr, + size_t len, + int prot, + int flags, + int fd, + off_t offset) { + return sys_mmap(addr, len, prot, flags, fd, offset); +} + +int CallMunmap(void* addr, size_t len) { + return sys_munmap(addr, len); +} + +int CallMprotect(void* addr, size_t len, int prot) { + return sys_mprotect(addr, len, prot); +} +#else +void* CallMmap(void* addr, + size_t len, + int prot, + int flags, + int fd, + off_t offset) { + return mmap(addr, len, prot, flags, fd, offset); +} + +int CallMunmap(void* addr, size_t len) { + return munmap(addr, len); +} + +int CallMprotect(void* addr, size_t len, int prot) { + return mprotect(addr, len, prot); +} +#endif + +bool LoggingMunmap(uintptr_t addr, size_t len, bool can_log) { + if (CallMunmap(reinterpret_cast<void*>(addr), len) != 0) { + PLOG_IF(ERROR, can_log) << "munmap"; return false; } @@ -35,7 +77,7 @@ } size_t RoundPage(size_t size) { - const size_t kPageMask = base::checked_cast<size_t>(getpagesize()) - 1; + const size_t kPageMask = base::checked_cast<size_t>(base::GetPageSize()) - 1; return (size + kPageMask) & ~kPageMask; } @@ -43,11 +85,12 @@ namespace crashpad { -ScopedMmap::ScopedMmap() {} +ScopedMmap::ScopedMmap(bool can_log) : can_log_(can_log) {} ScopedMmap::~ScopedMmap() { if (is_valid()) { - Munmap(reinterpret_cast<uintptr_t>(addr_), RoundPage(len_)); + LoggingMunmap( + reinterpret_cast<uintptr_t>(addr_), RoundPage(len_), can_log_); } } @@ -63,7 +106,7 @@ DCHECK_EQ(len, 0u); } else { DCHECK_NE(len, 0u); - DCHECK_EQ(new_addr % getpagesize(), 0u); + DCHECK_EQ(new_addr % base::GetPageSize(), 0u); DCHECK((base::CheckedNumeric<uintptr_t>(new_addr) + (new_len_round - 1)) .IsValid()); } @@ -74,11 +117,13 @@ const uintptr_t old_addr = reinterpret_cast<uintptr_t>(addr_); const size_t old_len_round = RoundPage(len_); if (old_addr < new_addr) { - result &= Munmap(old_addr, std::min(old_len_round, new_addr - old_addr)); + result &= LoggingMunmap( + old_addr, std::min(old_len_round, new_addr - old_addr), can_log_); } if (old_addr + old_len_round > new_addr + new_len_round) { uintptr_t unmap_start = std::max(old_addr, new_addr + new_len_round); - result &= Munmap(unmap_start, old_addr + old_len_round - unmap_start); + result &= LoggingMunmap( + unmap_start, old_addr + old_len_round - unmap_start, can_log_); } } @@ -100,9 +145,9 @@ // consider the return value from Reset(). Reset(); - void* new_addr = mmap(addr, len, prot, flags, fd, offset); + void* new_addr = CallMmap(addr, len, prot, flags, fd, offset); if (new_addr == MAP_FAILED) { - PLOG(ERROR) << "mmap"; + PLOG_IF(ERROR, can_log_) << "mmap"; return false; } @@ -113,8 +158,8 @@ } bool ScopedMmap::Mprotect(int prot) { - if (mprotect(addr_, RoundPage(len_), prot) < 0) { - PLOG(ERROR) << "mprotect"; + if (CallMprotect(addr_, RoundPage(len_), prot) < 0) { + PLOG_IF(ERROR, can_log_) << "mprotect"; return false; }
diff --git a/third_party/crashpad/crashpad/util/posix/scoped_mmap.h b/third_party/crashpad/crashpad/util/posix/scoped_mmap.h index b497d94..12f5ceed 100644 --- a/third_party/crashpad/crashpad/util/posix/scoped_mmap.h +++ b/third_party/crashpad/crashpad/util/posix/scoped_mmap.h
@@ -30,7 +30,10 @@ //! will be released by calling `munmap()`. class ScopedMmap { public: - ScopedMmap(); + //! \brief Constructs this object. + //! + //! \param can_log `true` if methods of this class may log messages. + explicit ScopedMmap(bool can_log = true); ~ScopedMmap(); //! \brief Releases the memory-mapped region by calling `munmap()`. @@ -105,6 +108,7 @@ private: void* addr_ = MAP_FAILED; size_t len_ = 0; + bool can_log_; DISALLOW_COPY_AND_ASSIGN(ScopedMmap); };
diff --git a/third_party/google_input_tools/DIR_METADATA b/third_party/google_input_tools/DIR_METADATA index 1d28f0a..ca0e79f 100644 --- a/third_party/google_input_tools/DIR_METADATA +++ b/third_party/google_input_tools/DIR_METADATA
@@ -1,3 +1,3 @@ monorail: { - component: "UI>Input>Text>IME" + component: "OS>Inputs" }
diff --git a/tools/imagediff/image_diff.cc b/tools/imagediff/image_diff.cc index 76e24cb4..45a25b7 100644 --- a/tools/imagediff/image_diff.cc +++ b/tools/imagediff/image_diff.cc
@@ -425,6 +425,11 @@ } } + if (!same) { + printf("Found pixels_different: %d, max_channel_diff: %u\n", + pixels_different, max_channel_diff); + } + if (!fuzzy_diff) { return same; } @@ -436,11 +441,9 @@ // WPT fuzzy matching. This algorithm is equivalent to 'check_pass' in // tools/wptrunner/wptrunner/executors/base.py - fprintf(stderr, "Found pixels_different: %d, max_channel_diff: %u\n", - pixels_different, max_channel_diff); - fprintf(stderr, "Allowed pixels different; %d-%d, channel diff: %u-%u\n", - fuzzy_allowed_pixels_diff[0], fuzzy_allowed_pixels_diff[1], - fuzzy_allowed_max_channel_diff[0], fuzzy_allowed_max_channel_diff[1]); + printf("Allowed pixels_different; %d-%d, max_channel_diff: %u-%u\n", + fuzzy_allowed_pixels_diff[0], fuzzy_allowed_pixels_diff[1], + fuzzy_allowed_max_channel_diff[0], fuzzy_allowed_max_channel_diff[1]); return ((pixels_different == 0 && fuzzy_allowed_pixels_diff[0] == 0) || (max_channel_diff == 0 && fuzzy_allowed_max_channel_diff[0] == 0) ||
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index b26dbb6..ad9fb1a 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -1039,11 +1039,8 @@ 'ios14-beta-simulator': 'ios_simulator_debug_static_rbe_bot_xctest', 'ios14-sdk-simulator': 'ios_simulator_debug_static_rbe_bot_xctest', 'ios-simulator': 'ios_simulator_rbe_code_coverage_partial_instrumentation_xctest', - 'ios-simulator-coverage-exp': 'ios_simulator_rbe_code_coverage_partial_instrumentation_xctest', 'ios-simulator-full-configs': 'ios_simulator_code_coverage_partial_instrumentation_xctest', - 'ios-simulator-full-configs-coverage-exp': 'ios_simulator_rbe_code_coverage_partial_instrumentation_xctest', 'ios-simulator-cronet': 'ios_cronet_xctest', - 'ios-simulator-code-coverage': 'ios_simulator_rbe_code_coverage_partial_instrumentation_xctest', 'ios-simulator-cr-recipe': 'ios_simulator_debug_static_bot_xctest', 'ios-simulator-noncq': 'ios_simulator_debug_static_rbe_bot_xctest', 'ios-simulator-multi-window': 'ios_simulator_debug_static_bot_multi_window_xctest',
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.mac.json b/tools/mb/mb_config_expectations/tryserver.chromium.mac.json index 65a7e791..ba24efff 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.mac.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.mac.json
@@ -250,36 +250,6 @@ "use_goma": true } }, - "ios-simulator-code-coverage": { - "gn_args": { - "coverage_instrumentation_input_file": "//.code-coverage/files_to_instrument.txt", - "enable_run_ios_unittests_with_xctest": true, - "ios_use_goma_rbe": true, - "is_component_build": false, - "is_debug": true, - "symbol_level": 1, - "target_cpu": "x64", - "target_environment": "simulator", - "target_os": "ios", - "use_clang_coverage": true, - "use_goma": true - } - }, - "ios-simulator-coverage-exp": { - "gn_args": { - "coverage_instrumentation_input_file": "//.code-coverage/files_to_instrument.txt", - "enable_run_ios_unittests_with_xctest": true, - "ios_use_goma_rbe": true, - "is_component_build": false, - "is_debug": true, - "symbol_level": 1, - "target_cpu": "x64", - "target_environment": "simulator", - "target_os": "ios", - "use_clang_coverage": true, - "use_goma": true - } - }, "ios-simulator-cr-recipe": { "gn_args": { "enable_run_ios_unittests_with_xctest": true, @@ -332,21 +302,6 @@ "use_goma": true } }, - "ios-simulator-full-configs-coverage-exp": { - "gn_args": { - "coverage_instrumentation_input_file": "//.code-coverage/files_to_instrument.txt", - "enable_run_ios_unittests_with_xctest": true, - "ios_use_goma_rbe": true, - "is_component_build": false, - "is_debug": true, - "symbol_level": 1, - "target_cpu": "x64", - "target_environment": "simulator", - "target_os": "ios", - "use_clang_coverage": true, - "use_goma": true - } - }, "ios-simulator-multi-window": { "gn_args": { "enable_run_ios_unittests_with_xctest": true,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 7c6de95..b170d495 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -12621,6 +12621,7 @@ <int value="31" label="Shop image with Google Lens"/> <int value="32" label="Search Similar Products"/> <int value="33" label="Read later"/> + <int value="34" label="Shop with Google Lens Chip"/> </enum> <enum name="ContextMenuOptionDesktop"> @@ -40922,6 +40923,16 @@ <int value="8" label="Error: early terminated"/> </enum> +<enum name="LensSdkError"> + <int value="1" label="Internal Error"/> + <int value="2" label="Session already started"/> + <int value="3" label="Session not started"/> + <int value="4" label="Query missing payload"/> + <int value="5" label="Query payload missing image"/> + <int value="6" label="Query image failed to resolve"/> + <int value="7" label="Classification error"/> +</enum> + <enum name="LevelDBCorruptionRestoreValue"> <int value="0" label="Database Delete Success"/> <int value="1" label="Database Delete Failure"/> @@ -42801,6 +42812,7 @@ <int value="-1236065190" label="HardwareMediaKeyHandling:disabled"/> <int value="-1235586511" label="enable-datasaver-prompt"/> <int value="-1234740672" label="UsePdfCompositorServiceForPrint:disabled"/> + <int value="-1234518922" label="ChromeLabs:disabled"/> <int value="-1232629319" label="ResamplingScrollEvents:disabled"/> <int value="-1231507397" label="NtpZeroSuggest:enabled"/> <int value="-1230610048" label="SyncWifiConfigurations:disabled"/> @@ -43806,6 +43818,7 @@ <int value="-263645996" label="InteractiveWindowCycleList:enabled"/> <int value="-263150202" label="BundledConnectionHelp:disabled"/> <int value="-262122630" label="ArcEnableDocumentsProviderInFilesApp:enabled"/> + <int value="-261398170" label="ChromeLabs:enabled"/> <int value="-258081634" label="AutofillAssistantDirectActions:disabled"/> <int value="-257478609" label="TextfieldFocusOnTapUp:enabled"/> <int value="-256940675" label="HelpAppSearchServiceIntegration:disabled"/> @@ -64175,6 +64188,8 @@ <int value="6" label="ExcludedCorbForPlugin"> Requests from a renderer process that embeds a plugin (e.g. Flash) that needs to disable CORB and request_initiator_origin_lock enforcement. + + Obsolete - this enum value was removed in Nov 2020 (M89). </int> <int value="7" label="AllowedRequestInitiatorForPlugin"> Requests from a renderer process that embeds a plugin (e.g. PDF) that needs
diff --git a/tools/metrics/histograms/histograms_xml/others/histograms.xml b/tools/metrics/histograms/histograms_xml/others/histograms.xml index 3c139b9..50dc7a9 100644 --- a/tools/metrics/histograms/histograms_xml/others/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/others/histograms.xml
@@ -8140,6 +8140,17 @@ </summary> </histogram> +<histogram name="Lens.ImageClassification.SdkError" enum="LensSdkError" + expires_after="M90"> + <owner>yusuyoutube@google.com</owner> + <owner>benwgold@google.com</owner> + <summary> + Logged the error code when there is a Lens SDK error occurred within the + classification session. The error code is an integer constant defined by the + SDK. Only logged on Android. See http://b/170422682 for more details. + </summary> +</histogram> + <histogram name="LevelDB.ApproximateMemTableMemoryUse" units="bytes" expires_after="2021-01-03"> <owner>nyquist@chromium.org</owner> @@ -11192,7 +11203,7 @@ </summary> </histogram> -<histogram name="PointingStick.Acceleration" enum="BooleanEnabled" +<histogram base="true" name="PointingStick.Acceleration" enum="BooleanEnabled" expires_after="2021-04-01"> <!-- Name completed by histogram_suffixes name="PreferenceChangeType" --> @@ -11206,8 +11217,8 @@ </summary> </histogram> -<histogram name="PointingStick.PointerSensitivity" enum="PointerSensitivity" - expires_after="2021-04-01"> +<histogram base="true" name="PointingStick.PointerSensitivity" + enum="PointerSensitivity" expires_after="2021-04-01"> <!-- Name completed by histogram_suffixes name="PreferenceChangeType" --> <owner>hcutts@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml b/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml index 9bc44831..4e92b75c 100644 --- a/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml
@@ -105,8 +105,8 @@ </histogram> <histogram name="SBClientDownload.DownloadRequestNetError" enum="NetErrorCodes" - expires_after="2021-01-10"> - <owner>vakh@chromium.org</owner> + expires_after="2021-07-10"> + <owner>drubery@chromium.org</owner> <owner>chrome-safebrowsing-alerts@google.com</owner> <owner>mattm@chromium.org</owner> <summary>
diff --git a/tools/perf/benchmark.csv b/tools/perf/benchmark.csv index 13ea4bf..ae8d2ad 100644 --- a/tools/perf/benchmark.csv +++ b/tools/perf/benchmark.csv
@@ -3,6 +3,7 @@ Googlers can view additional information about internal perf infrastructure at,https://goto.google.com/chrome-benchmarking-sheet Benchmark name,Individual owners,Component,Documentation,Tags UNSCHEDULED_blink_perf.service_worker,"shimazu@chromium.org, falken@chromium.org, ting.shao@intel.com",Blink>ServiceWorker,https://bit.ly/blink-perf-benchmarks, +UNSCHEDULED_loading.mbi,blink-isolation-dev@chromium.org,Blink>Internals>Modularization,https://bit.ly/loading-benchmarks,many_agents base_perftests,"skyostil@chromium.org, gab@chromium.org",Internals>SequenceManager,https://chromium.googlesource.com/chromium/src/+/HEAD/base/README.md#performance-testing, blink_perf.accessibility,dmazzoni@chromium.org,Blink>Accessibility,https://bit.ly/blink-perf-benchmarks,all blink_perf.bindings,"jbroman@chromium.org, yukishiino@chromium.org, haraken@chromium.org",Blink>Bindings,https://bit.ly/blink-perf-benchmarks,all
diff --git a/tools/perf/benchmarks/loading.py b/tools/perf/benchmarks/loading.py index a26a945..895198f0 100644 --- a/tools/perf/benchmarks/loading.py +++ b/tools/perf/benchmarks/loading.py
@@ -79,3 +79,27 @@ @classmethod def Name(cls): return 'loading.mobile' + + +@benchmark.Info(emails=['blink-isolation-dev@chromium.org'], + component='Blink>Internals>Modularization', + documentation_url='https://bit.ly/loading-benchmarks') +class LoadingMBI(_LoadingBase): + """ A benchmark measuring loading performance of the sites the MBI team cares + about. """ + # TODO(rmhasan): Remove the SUPPORTED_PLATFORMS lists. + # SUPPORTED_PLATFORMS is deprecated, please put system specifier tags + # from expectations.config in SUPPORTED_PLATFORM_TAGS. + SUPPORTED_PLATFORM_TAGS = [platforms.MOBILE] + SUPPORTED_PLATFORMS = [story.expectations.ALL_MOBILE] + + def CreateStorySet(self, options): + return page_sets.LoadingMobileStorySet( + cache_temperatures=[cache_temperature.ANY], + cache_temperatures_for_pwa=[], + traffic_settings=[traffic_setting.NONE, traffic_setting.REGULAR_3G], + include_tags=['many_agents']) + + @classmethod + def Name(cls): + return 'UNSCHEDULED_loading.mbi'
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 3b42652..ff3a90a5 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -1,16 +1,16 @@ { "trace_processor_shell": { "win": { - "hash": "b8baf0bb54fbc805dd4c5ba04d2b07699a0037d7", - "remote_path": "perfetto_binaries/trace_processor_shell/win/c56ea91f6bd1b910be1ba373b950c04f72595bd9/trace_processor_shell.exe" + "hash": "425a5b1559c4b292b47c05aedccd6e354b191fd6", + "remote_path": "perfetto_binaries/trace_processor_shell/win/3bf9804260028db727c4631798c5babeabaf821c/trace_processor_shell.exe" }, "mac": { - "hash": "11afa62736fe0509113a32ef5bf569455300f172", - "remote_path": "perfetto_binaries/trace_processor_shell/mac/e1502e7972cb2a4bb582d5ae2cc693cc3b7868dc/trace_processor_shell" + "hash": "ccad8ac65998e68e7a4d2aa5d77102b9529f6327", + "remote_path": "perfetto_binaries/trace_processor_shell/mac/3bf9804260028db727c4631798c5babeabaf821c/trace_processor_shell" }, "linux": { - "hash": "80a12d0a00dd8be4514fb96b5bdbb3b5564e99c5", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/48b2aad780bfff59c2cd1a1169cedc68816a017b/trace_processor_shell" + "hash": "7f417b6718505cc8824f912d1cccdc81d556b74d", + "remote_path": "perfetto_binaries/trace_processor_shell/linux/3bf9804260028db727c4631798c5babeabaf821c/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/page_sets/data/loading_mobile.json b/tools/perf/page_sets/data/loading_mobile.json index de293e4..7d4aea0 100644 --- a/tools/perf/page_sets/data/loading_mobile.json +++ b/tools/perf/page_sets/data/loading_mobile.json
@@ -2,302 +2,398 @@ "archives": { "58Pic": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "58Pic_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Amazon": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "AmazonJP": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "AmazonJP_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "Amazon_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "BBC": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "BBC_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "BOLNoticias": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "BOLNoticias_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Baidu": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Baidu_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Bradesco": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Bradesco_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "CNN": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "CNN_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "CNet": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "CNet_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Cricbuzz": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Cricbuzz_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "Dailymotion": { "DEFAULT": "loading_mobile_001.wprgo" - }, + }, "Dailymotion_3g": { "DEFAULT": "loading_mobile_001.wprgo" - }, + }, "Dawn": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Dawn_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "DevOpera": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_cold": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_cold_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_hot": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_hot_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_warm": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "DevOpera_warm_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Dramaq": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Dramaq_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "ESPN": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "ESPN_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Ebay": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Ebay_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "EnquiryIndianRail": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "EnquiryIndianRail_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Facebook": { "DEFAULT": "loading_mobile_002.wprgo" - }, + }, "Facebook_3g": { "DEFAULT": "loading_mobile_002.wprgo" - }, + }, "FlipBoard": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_cold": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_cold_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_hot": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_hot_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_warm": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipBoard_warm_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_cold": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_cold_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_hot": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_hot_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_warm": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FlipKart_warm_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "FranceTVInfo": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "FranceTVInfo_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "G1": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "G1_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GSShop": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GSShop_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleBrazil": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleBrazil_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleIndia": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleIndia_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleIndonesia": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleIndonesia_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleRedirectToGoogleJapan": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "GoogleRedirectToGoogleJapan_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Hongkiat": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Hongkiat_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "IMDB": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "IMDB_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "IndiaTimes": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "IndiaTimes_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "KapanLagi": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "KapanLagi_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Kaskus": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Kaskus_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "LocalMoxie": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "LocalMoxie_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Locanto": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Locanto_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "MSN": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "MSN_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Netflix": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Netflix_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Nicovideo": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Nicovideo_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "NyTimes": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "NyTimes_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "OLX": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "OLX_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "QQNews": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "QQNews_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "Sina": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "Sina_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "SindoNews": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "SindoNews_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "SlideShare": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "SlideShare_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Suumo": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_cold": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_cold_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_hot": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_hot_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_warm": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Suumo_warm_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Thairath": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Thairath_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, + "TheGuardian": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, + "TheGuardian_3g": { + "DEFAULT": "loading_mobile_5e1b45320b.wprgo" + }, "TheStar": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "TheStar_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "TribunNews": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "TribunNews_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Twitter": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Twitter_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "VoiceMemos": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_cold": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_cold_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_hot": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_hot_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_warm": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "VoiceMemos_warm_3g": { "DEFAULT": "loading_mobile_003.wprgo" - }, + }, "Wikipedia": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Wikipedia_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "YahooNews": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "YahooNews_3g": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Youtube": { "DEFAULT": "loading_mobile_000.wprgo" - }, + }, "Youtube_3g": { "DEFAULT": "loading_mobile_000.wprgo" } - }, - "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.", + }, + "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.", "platform_specific": true } \ No newline at end of file
diff --git a/tools/perf/page_sets/data/loading_mobile_5e1b45320b.wprgo.sha1 b/tools/perf/page_sets/data/loading_mobile_5e1b45320b.wprgo.sha1 new file mode 100644 index 0000000..4a4314aa --- /dev/null +++ b/tools/perf/page_sets/data/loading_mobile_5e1b45320b.wprgo.sha1
@@ -0,0 +1 @@ +5e1b45320b4c2b1f798c1ba885128dd407dcccf1 \ No newline at end of file
diff --git a/tools/perf/page_sets/loading_mobile.py b/tools/perf/page_sets/loading_mobile.py index a1d5c7bb..2bd75349 100644 --- a/tools/perf/page_sets/loading_mobile.py +++ b/tools/perf/page_sets/loading_mobile.py
@@ -34,12 +34,18 @@ Design doc: https://docs.google.com/document/d/1QKlZIoURAxZk-brrXsKYZl9O8ieqXht3ogeF9yLNFCI/edit """ - def __init__(self, cache_temperatures=None, cache_temperatures_for_pwa=None, - traffic_settings=None): + def __init__(self, + cache_temperatures=None, + cache_temperatures_for_pwa=None, + traffic_settings=None, + include_tags=None): super(LoadingMobileStorySet, self).__init__( archive_data_file='data/loading_mobile.json', cloud_storage_bucket=story.PARTNER_BUCKET) + if include_tags is None: + include_tags = ['*'] + if cache_temperatures is None: cache_temperatures = [cache_temperature_module.ANY] @@ -49,99 +55,127 @@ if traffic_settings is None: traffic_settings = [traffic_setting_module.NONE] - self.AddStories(['global'], [ - ('https://www.google.com/search?q=flower#q=flower+delivery', - 'GoogleRedirectToGoogleJapan'), - ('https://www.youtube.com/watch?v=MU3YuvNRhVY', 'Youtube'), - # pylint: disable=line-too-long - ('https://www.google.co.in/search?q=%E0%A4%AB%E0%A5%82%E0%A4%B2&rct=j#q=%E0%A4%AB%E0%A5%82%E0%A4%B2+%E0%A4%B5%E0%A4%BF%E0%A4%A4%E0%A4%B0%E0%A4%A3', - 'GoogleIndia'), - ('https://www.google.com.br/search?q=flor#q=Entrega+de+flores&start=10', - 'GoogleBrazil'), - ('https://www.google.co.id/#q=pengiriman+bunga', 'GoogleIndonesia'), - ('https://m.facebook.com/?soft=messages', 'Facebook'), - # pylint: disable=line-too-long - ('http://g1.globo.com/politica/noticia/2016/02/maioria-do-stf-autoriza-fisco-obter-dados-bancarios-sem-decisao-judicial.html', - 'G1'), - # pylint: disable=line-too-long - ('https://m.baidu.com/s?word=%E9%B2%9C%E8%8A%B1%E9%80%9F%E9%80%92&oq=%E9%B2%9C%E8%8A%B1', - 'Baidu'), - # pylint: disable=line-too-long - ('http://news.yahoo.com/were-top-10-most-visited-us-national-parks-105323727.html', - 'YahooNews'), - ('https://en.m.wikipedia.org/wiki/Solo_Foods', 'Wikipedia'), - # pylint: disable=line-too-long - ('http://noticias.bol.uol.com.br/ultimas-noticias/brasil/2016/08/03/tufao-nida-nao-deixa-vitimas-mas-prejuizos-de-us-43-milhoes.htm', - 'BOLNoticias'), - ('http://www.amazon.com/gp/aw/s/ref=is_s/189-8585431-1246432?k=shoes', - 'Amazon'), - # pylint: disable=line-too-long - ('http://m.tribunnews.com/superskor/2016/08/03/ribuan-polisi-dikerahkan-mengawal-bonek', - 'TribunNews'), - ('http://xw.qq.com/news/20160803025029/NEW2016080302502901', 'QQNews'), - # pylint: disable=line-too-long - ('http://m.kaskus.co.id/thread/57a03a3214088d91068b4567/inilah-akibat-bersikap-overprotektif-terhadap-anak/?ref=homelanding&med=hot_thread', - 'Kaskus'), - ('http://www.dailymotion.com/video/x3d1kj5_fallout-4-review_videogames', - 'Dailymotion'), - ('https://mobile.twitter.com/scottjehl/status/760618697727803394', - 'Twitter'), - ('http://m.kapanlagi.com/lirik/artis/anji/kata_siapa/', - 'KapanLagi'), - # pylint: disable=line-too-long - ('http://olx.co.id/iklan/iphone-6s-64-rose-gold-warna-favorite-IDiSdm5.html#5310a118c3;promoted', - 'OLX'), - # pylint: disable=line-too-long - ('http://enquiry.indianrail.gov.in/mntes/MntesServlet?action=MainMenu&subAction=excep&excpType=EC', - 'EnquiryIndianRail'), - # TODO(rnephew): Rerecord this. crbug.com/728882 - # pylint: disable=line-too-long - # ('https://googleblog.blogspot.jp/2016/02/building-safer-web-for-everyone.html', - # 'Blogspot'), - # pylint: disable=line-too-long - # ('http://m.detik.com/finance/read/2016/02/19/151843/3146351/1034/ekspor-tambang-mentah-mau-dibuka-lagi-kalau-sudah-bangun-smelter-bagaimana', - # 'Detik'), - ], cache_temperatures, traffic_settings) + if '*' in include_tags or 'global' in include_tags: + self.AddStories(['global'], [ + ('https://www.google.com/search?q=flower#q=flower+delivery', + 'GoogleRedirectToGoogleJapan'), + ('https://www.youtube.com/watch?v=MU3YuvNRhVY', 'Youtube'), + # pylint: disable=line-too-long + ('https://www.google.co.in/search?q=%E0%A4%AB%E0%A5%82%E0%A4%B2&rct=j#q=%E0%A4%AB%E0%A5%82%E0%A4%B2+%E0%A4%B5%E0%A4%BF%E0%A4%A4%E0%A4%B0%E0%A4%A3', + 'GoogleIndia'), + ('https://www.google.com.br/search?q=flor#q=Entrega+de+flores&start=10', + 'GoogleBrazil'), + ('https://www.google.co.id/#q=pengiriman+bunga', 'GoogleIndonesia'), + ('https://m.facebook.com/?soft=messages', 'Facebook'), + # pylint: disable=line-too-long + ('http://g1.globo.com/politica/noticia/2016/02/maioria-do-stf-autoriza-fisco-obter-dados-bancarios-sem-decisao-judicial.html', + 'G1'), + # pylint: disable=line-too-long + ('https://m.baidu.com/s?word=%E9%B2%9C%E8%8A%B1%E9%80%9F%E9%80%92&oq=%E9%B2%9C%E8%8A%B1', + 'Baidu'), + # pylint: disable=line-too-long + ('http://news.yahoo.com/were-top-10-most-visited-us-national-parks-105323727.html', + 'YahooNews'), + ('https://en.m.wikipedia.org/wiki/Solo_Foods', 'Wikipedia'), + # pylint: disable=line-too-long + ('http://noticias.bol.uol.com.br/ultimas-noticias/brasil/2016/08/03/tufao-nida-nao-deixa-vitimas-mas-prejuizos-de-us-43-milhoes.htm', + 'BOLNoticias'), + ('http://www.amazon.com/gp/aw/s/ref=is_s/189-8585431-1246432?k=shoes', + 'Amazon'), + # pylint: disable=line-too-long + ('http://m.tribunnews.com/superskor/2016/08/03/ribuan-polisi-dikerahkan-mengawal-bonek', + 'TribunNews'), + ('http://xw.qq.com/news/20160803025029/NEW2016080302502901', 'QQNews'), + # pylint: disable=line-too-long + ('http://m.kaskus.co.id/thread/57a03a3214088d91068b4567/inilah-akibat-bersikap-overprotektif-terhadap-anak/?ref=homelanding&med=hot_thread', + 'Kaskus'), + ('http://www.dailymotion.com/video/x3d1kj5_fallout-4-review_videogames', + 'Dailymotion'), + ('https://mobile.twitter.com/scottjehl/status/760618697727803394', + 'Twitter'), + ('http://m.kapanlagi.com/lirik/artis/anji/kata_siapa/', + 'KapanLagi'), + # pylint: disable=line-too-long + ('http://olx.co.id/iklan/iphone-6s-64-rose-gold-warna-favorite-IDiSdm5.html#5310a118c3;promoted', + 'OLX'), + # pylint: disable=line-too-long + ('http://enquiry.indianrail.gov.in/mntes/MntesServlet?action=MainMenu&subAction=excep&excpType=EC', + 'EnquiryIndianRail'), + # TODO(rnephew): Rerecord this. crbug.com/728882 + # pylint: disable=line-too-long + # ('https://googleblog.blogspot.jp/2016/02/building-safer-web-for-everyone.html', + # 'Blogspot'), + # pylint: disable=line-too-long + # ('http://m.detik.com/finance/read/2016/02/19/151843/3146351/1034/ekspor-tambang-mentah-mau-dibuka-lagi-kalau-sudah-bangun-smelter-bagaimana', + # 'Detik'), + ], cache_temperatures, traffic_settings) - self.AddStories(['pwa'], [ - # pylint: disable=line-too-long - ('https://www.flipkart.com/big-wing-casuals/p/itmemeageyfn6m9z?lid=LSTSHOEMEAGURG2PHPW18FTBN&pid=SHOEMEAGURG2PHPW', - 'FlipKart'), - ('https://smp.suumo.jp/mansion/tokyo/sc_104/cond/?moreCond=1', - 'Suumo'), - ('https://voice-memos.appspot.com', 'VoiceMemos'), - ('https://dev.opera.com/', 'DevOpera'), - ('https://flipboard.com/topic/yoga', 'FlipBoard'), - # TODO(rnephew): Record these. crbug.com/728882 - # ('https://wiki-offline.jakearchibald.com/', - # 'WikiOffline'), - # ('https://busrouter.sg', 'BusRouter'), - # ('https://airhorner.com', 'AirHorner'), - ], cache_temperatures_for_pwa, traffic_settings) + if '*' in include_tags or 'pwa' in include_tags: + self.AddStories(['pwa'], [ + # pylint: disable=line-too-long + ('https://www.flipkart.com/big-wing-casuals/p/itmemeageyfn6m9z?lid=LSTSHOEMEAGURG2PHPW18FTBN&pid=SHOEMEAGURG2PHPW', + 'FlipKart'), + ('https://smp.suumo.jp/mansion/tokyo/sc_104/cond/?moreCond=1', + 'Suumo'), + ('https://voice-memos.appspot.com', 'VoiceMemos'), + ('https://dev.opera.com/', 'DevOpera'), + ('https://flipboard.com/topic/yoga', 'FlipBoard'), + # TODO(rnephew): Record these. crbug.com/728882 + # ('https://wiki-offline.jakearchibald.com/', + # 'WikiOffline'), + # ('https://busrouter.sg', 'BusRouter'), + # ('https://airhorner.com', 'AirHorner'), + ], cache_temperatures_for_pwa, traffic_settings) - self.AddStories(['tough_ttfmp'], [ - ('http://www.localmoxie.com', 'LocalMoxie'), - ('http://www.dawn.com', 'Dawn'), - ('http://www.thairath.co.th', 'Thairath'), - ], cache_temperatures, traffic_settings) + if '*' in include_tags or 'tough_ttfmp' in include_tags: + self.AddStories(['tough_ttfmp'], [ + ('http://www.localmoxie.com', 'LocalMoxie'), + ('http://www.dawn.com', 'Dawn'), + ('http://www.thairath.co.th', 'Thairath'), + ], cache_temperatures, traffic_settings) - self.AddStories(['easy_ttfmp'], [ - ('http://www.slideshare.net', 'SlideShare'), - ('http://www.bradesco.com.br', 'Bradesco'), - ('http://www.gsshop.com', 'GSShop'), - ], cache_temperatures, traffic_settings) + if '*' in include_tags or 'easy_ttfmp' in include_tags: + self.AddStories(['easy_ttfmp'], [ + ('http://www.slideshare.net', 'SlideShare'), + ('http://www.bradesco.com.br', 'Bradesco'), + ('http://www.gsshop.com', 'GSShop'), + ], cache_temperatures, traffic_settings) - self.AddStories(['tough_tti'], [ - ('http://www.thestar.com.my', 'TheStar'), - ('http://www.58pic.com', '58Pic'), - ('http://www.hongkiat.com', 'Hongkiat'), - ], cache_temperatures, traffic_settings) + if '*' in include_tags or 'tough_tti' in include_tags: + self.AddStories(['tough_tti'], [ + ('http://www.thestar.com.my', 'TheStar'), + ('http://www.58pic.com', '58Pic'), + ('http://www.hongkiat.com', 'Hongkiat'), + ], cache_temperatures, traffic_settings) - self.AddStories(['easy_tti'], [ - ('http://www.dramaq.com.tw', 'Dramaq'), - ('http://www.locanto.in', 'Locanto'), - ('http://www.francetvinfo.fr', 'FranceTVInfo'), - ], cache_temperatures, traffic_settings) + if '*' in include_tags or 'easy_tti' in include_tags: + self.AddStories(['easy_tti'], [ + ('http://www.dramaq.com.tw', 'Dramaq'), + ('http://www.locanto.in', 'Locanto'), + ('http://www.francetvinfo.fr', 'FranceTVInfo'), + ], cache_temperatures, traffic_settings) + + # The many_agents stories are not added unless explicitly specified to keep + # loading.{mobile,desktop} benchmarks short. + if 'many_agents' in include_tags: + self.AddStories(['many_agents'], [ + ('https://www.amazon.co.jp', 'AmazonJP'), + ('https://www.netflix.com', 'Netflix'), + ('https://sina.com.cn', 'Sina'), + ('https://www.ebay.com', 'Ebay'), + ('https://www.msn.com', 'MSN'), + ('https://www.imdb.com', 'IMDB'), + ('https://www.cnn.com', 'CNN'), + ('https://www.bbc.com', 'BBC'), + ('https://www.espn.com', 'ESPN'), + ('https://www.nytimes.com', 'NyTimes'), + ('https://www.nicovideo.jp', 'Nicovideo'), + ('https://www.cricbuzz.com', 'Cricbuzz'), + ('https://www.theguardian.com', 'TheGuardian'), + ('https://www.cnet.com', 'CNet'), + ('https://www.indiatimes.com', 'IndiaTimes'), + ('https://www.sindonews.com', 'SindoNews'), + ], cache_temperatures, traffic_settings) def GetAbridgedStorySetTagFilter(self): return ABRIDGED.name
diff --git a/ui/base/ime/DIR_METADATA b/ui/base/ime/DIR_METADATA index 40507e1..9f8d081 100644 --- a/ui/base/ime/DIR_METADATA +++ b/ui/base/ime/DIR_METADATA
@@ -7,5 +7,6 @@ # https://source.chromium.org/chromium/infra/infra/+/master:go/src/infra/tools/dirmd/proto/dir_metadata.proto monorail { - component: "UI>Input>Text>IME" -} \ No newline at end of file + component: "OS>Inputs" # for Chrome/Chromium OS only. + # For OSes other than Chrome/Chromium OS, please use "UI>Input>Text>IME". +}
diff --git a/ui/base/ime/chromeos/input_method_util.cc b/ui/base/ime/chromeos/input_method_util.cc index b2aa0147..ac10a8d 100644 --- a/ui/base/ime/chromeos/input_method_util.cc +++ b/ui/base/ime/chromeos/input_method_util.cc
@@ -791,11 +791,6 @@ ResetInputMethods(imes); } -const InputMethodUtil::InputMethodIdToDescriptorMap& -InputMethodUtil::GetIdToDescriptorMapForTesting() { - return id_to_descriptor_; -} - InputMethodDescriptor InputMethodUtil::GetFallbackInputMethodDescriptor() { std::vector<std::string> layouts; layouts.emplace_back("us");
diff --git a/ui/base/ime/chromeos/input_method_util.h b/ui/base/ime/chromeos/input_method_util.h index b43a7b0..4f5330b 100644 --- a/ui/base/ime/chromeos/input_method_util.h +++ b/ui/base/ime/chromeos/input_method_util.h
@@ -160,9 +160,6 @@ InputMethodType type, std::vector<std::string>* out_input_method_ids) const; - // Gets the id to descriptor map for testing. - const InputMethodIdToDescriptorMap& GetIdToDescriptorMapForTesting(); - private: // Converts a string sent from IBus IME engines, which is written in English, // into Chrome's string ID, then pulls internationalized resource string from
diff --git a/ui/base/ime/chromeos/input_method_util_unittest.cc b/ui/base/ime/chromeos/input_method_util_unittest.cc index 9e526d4..72af7cad 100644 --- a/ui/base/ime/chromeos/input_method_util_unittest.cc +++ b/ui/base/ime/chromeos/input_method_util_unittest.cc
@@ -36,7 +36,6 @@ // Change access rights. using InputMethodUtil::GetInputMethodIdsFromLanguageCodeInternal; - using InputMethodUtil::GetIdToDescriptorMapForTesting; }; } // namespace @@ -386,29 +385,6 @@ EXPECT_EQ("fr", language_codes[2]); } -// Test all supported descriptors to detect a typo in input_methods.txt. -TEST_F(InputMethodUtilTest, TestIBusInputMethodText) { - const std::map<std::string, InputMethodDescriptor>& id_to_descriptor = - util_.GetIdToDescriptorMapForTesting(); - for (const auto& it : id_to_descriptor) { - const std::string language_code = it.second.language_codes().at(0); - const base::string16 display_name = - l10n_util::GetDisplayNameForLocale(language_code, "en", false); - // Only two formats, like "fr" (lower case) and "en-US" (lower-upper), are - // allowed. See the text file for details. - EXPECT_TRUE(language_code == "fil" || language_code.length() == 2 || - (language_code.length() == 5 && language_code[2] == '-')) - << "Invalid language code " << language_code; - EXPECT_TRUE(l10n_util::IsValidLocaleSyntax(language_code)) - << "Invalid language code " << language_code; - EXPECT_FALSE(display_name.empty()) - << "Invalid language code " << language_code; - // On error, GetDisplayNameForLocale() returns the |language_code| as-is. - EXPECT_NE(language_code, base::UTF16ToUTF8(display_name)) - << "Invalid language code " << language_code; - } -} - // Test the input method ID migration. TEST_F(InputMethodUtilTest, TestInputMethodIDMigration) { const char* const migration_cases[][2] = {
diff --git a/ui/base/l10n/l10n_util.cc b/ui/base/l10n/l10n_util.cc index abf33789..629a3db 100644 --- a/ui/base/l10n/l10n_util.cc +++ b/ui/base/l10n/l10n_util.cc
@@ -168,7 +168,7 @@ "ny", // Nyanja "oc", // Occitan "om", // Oromo - "or", // Oriya + "or", // Odia (Oriya) "pa", // Punjabi "pl", // Polish "ps", // Pashto @@ -203,7 +203,7 @@ "tr", // Turkish "tt", // Tatar "tw", // Twi - "ug", // Uighur + "ug", // Uyghur "uk", // Ukrainian "ur", // Urdu "uz", // Uzbek
diff --git a/ui/base/ui_base_features.cc b/ui/base/ui_base_features.cc index 6201fe27..e74b6b9b 100644 --- a/ui/base/ui_base_features.cc +++ b/ui/base/ui_base_features.cc
@@ -10,6 +10,10 @@ #include "base/win/windows_version.h" #endif +#if defined(OS_ANDROID) +#include "base/android/build_info.h" +#endif + namespace features { #if defined(OS_WIN) @@ -268,4 +272,16 @@ const base::Feature kSwipeToMoveCursor{"SwipeToMoveCursor", base::FEATURE_DISABLED_BY_DEFAULT}; +bool IsSwipeToMoveCursorEnabled() { + static const bool enabled = + base::FeatureList::IsEnabled(kSwipeToMoveCursor) +#if defined(OS_ANDROID) + && base::android::BuildInfo::GetInstance()->sdk_int() >= + base::android::SDK_VERSION_R; +#else + ; +#endif + return enabled; +} + } // namespace features
diff --git a/ui/base/ui_base_features.h b/ui/base/ui_base_features.h index 72c073d..7166d0a 100644 --- a/ui/base/ui_base_features.h +++ b/ui/base/ui_base_features.h
@@ -147,6 +147,8 @@ COMPONENT_EXPORT(UI_BASE_FEATURES) extern const base::Feature kSwipeToMoveCursor; +COMPONENT_EXPORT(UI_BASE_FEATURES) bool IsSwipeToMoveCursorEnabled(); + } // namespace features #endif // UI_BASE_UI_BASE_FEATURES_H_
diff --git a/ui/file_manager/BUILD.gn b/ui/file_manager/BUILD.gn index 7099db5..6395d12 100644 --- a/ui/file_manager/BUILD.gn +++ b/ui/file_manager/BUILD.gn
@@ -62,7 +62,6 @@ "file_manager/background/js:js_test_gen_html_modules", "file_manager/common/js:js_test_gen_html", "file_manager/common/js:js_test_gen_html_modules", - "file_manager/foreground/elements:js_test_gen_html", "file_manager/foreground/elements:js_test_gen_html_modules", "file_manager/foreground/js:js_test_gen_html", "file_manager/foreground/js:js_test_gen_html_modules",
diff --git a/ui/file_manager/base/tools/modules.py b/ui/file_manager/base/tools/modules.py index 123edf1f..13d93d2 100755 --- a/ui/file_manager/base/tools/modules.py +++ b/ui/file_manager/base/tools/modules.py
@@ -175,7 +175,7 @@ index = last_import_line_index else: file_lines.insert(index + 1, '') - file_lines.insert(index + 1, '// clang-format off') + file_lines.insert(index + 1, '// clang-format on') elif 'import ' not in file_lines[index + 1]: file_lines.insert(index, '') @@ -241,10 +241,6 @@ print 'Unable to find ' + section_first_line return False - # Return False if dependency already found. - if dependency_line in file_lines: - return False - # Find index of `list_name`. Get index of 'sources = [' in case `list_name` # is not defined. rule_index = file_lines.index(section_first_line) @@ -263,8 +259,11 @@ if file_lines[i].endswith(']'): single_line_dependency_list = True - # Jump to the end of the dependency list. + # Go to the end of the dependency list. while not ']' in file_lines[i]: + if dependency_line == file_lines[i]: + # Dependency already found. + return False i += 1 insertion_index = i break @@ -650,14 +649,17 @@ if line.startswith('class '): # Extract class name. class_name = line.split(' ')[1] - # Make sure this class is not used locally. - if get_index_substr(file_lines, 'new ' + class_name) >= 0: - # Export only if the class name is the name of the file. - snake_case_name = ''.join([ - '_' + c.lower() if c.isupper() else c for c in class_name - ]).lstrip('_') - if not snake_case_name + '.js' == js_file_path.split('/')[-1]: - continue + # Export class if this class is used or referred to in another js + # file. + out, _ = subprocess.Popen([ + 'egrep', '-R', '\W{}\W'.format(class_name), '-l', + './ui/file_manager/' + ], + stdout=subprocess.PIPE).communicate() + path = out.rstrip() + if not '\n' in path: + print 'Not exporting ' + class_name + ': local class' + continue file_lines[i] = '/* #export */ ' + line # Export variable in global namespace. elif line.startswith('const ') or line.startswith(
diff --git a/ui/file_manager/file_manager/background/js/trash.js b/ui/file_manager/file_manager/background/js/trash.js index f58833b..897aa4a 100644 --- a/ui/file_manager/file_manager/background/js/trash.js +++ b/ui/file_manager/file_manager/background/js/trash.js
@@ -139,7 +139,8 @@ return trashDirs; } - trashDirs = await TrashDirs.getTrashDirs(entry.filesystem, config); + trashDirs = assert(await TrashDirs.getTrashDirs( + entry.filesystem, config, /*create=*/ true)); // Check and remove old items max once per session. if (this.inProgress_.has(config.id)) { @@ -258,7 +259,8 @@ // Move to last directory in path, making sure dirs are created if needed. let dir = trashEntry.filesEntry.filesystem.root; for (let i = 0; i < parts.length - 1; i++) { - dir = await TrashDirs.getDirectory(dir, parts[i]); + dir = + assert(await TrashDirs.getDirectory(dir, parts[i], /*create=*/ true)); } // Restore filesEntry first, then remove its trash infoEntry.
diff --git a/ui/file_manager/file_manager/common/js/trash.js b/ui/file_manager/file_manager/common/js/trash.js index a2841b63..1c68655 100644 --- a/ui/file_manager/file_manager/common/js/trash.js +++ b/ui/file_manager/file_manager/common/js/trash.js
@@ -76,17 +76,17 @@ } /** - * Promise wrapper for FileSystemDirectoryEntry.getDirectory(). Creates dir if - * it does not exist. + * Promise wrapper for FileSystemDirectoryEntry.getDirectory(). * * @param {!DirectoryEntry} dirEntry current directory. * @param {string} path name of directory within dirEntry. - * @return {!Promise<!DirectoryEntry>} Promise which resolves with - * <dirEntry>/<path>. + * @param {boolean} create if true, directory is created if it does not exist. + * @return {!Promise<?DirectoryEntry>} Promise which resolves with + * <dirEntry>/<path> or null if entry does not exist and create is false. */ - static getDirectory(dirEntry, path) { + static getDirectory(dirEntry, path, create) { return new Promise((resolve, reject) => { - dirEntry.getDirectory(path, {create: true}, resolve, reject); + dirEntry.getDirectory(path, {create}, resolve, () => resolve(null)); }); } @@ -95,19 +95,24 @@ * * @param {!FileSystem} fileSystem File system from volume with trash. * @param {!TrashConfig} config Config specifying trash dir location. - * @return {!Promise<!TrashDirs>} Promise which resolves with trash dirs. + * @param {boolean} create if true, dirs are created if they do not exist. + * @return {!Promise<?TrashDirs>} Promise which resolves with trash dirs, or + * null if dirs do not exist and create is false. */ - static async getTrashDirs(fileSystem, config) { + static async getTrashDirs(fileSystem, config, create) { let trashRoot = fileSystem.root; const parts = config.trashDir.split('/'); for (const part of parts) { if (part) { - trashRoot = await TrashDirs.getDirectory(trashRoot, part); + trashRoot = await TrashDirs.getDirectory(trashRoot, part, create); + if (!trashRoot) { + return null; + } } } - const trashFiles = await TrashDirs.getDirectory(trashRoot, 'files'); - const trashInfo = await TrashDirs.getDirectory(trashRoot, 'info'); - return new TrashDirs(trashFiles, trashInfo); + const files = await TrashDirs.getDirectory(trashRoot, 'files', create); + const info = await TrashDirs.getDirectory(trashRoot, 'info', create); + return files && info ? new TrashDirs(files, info) : null; } } @@ -390,8 +395,12 @@ // Read all of .Trash/files on first call. if (!this.infoReader_) { - const trashDirs = - await TrashDirs.getTrashDirs(this.fileSystem_, this.config_); + const trashDirs = await TrashDirs.getTrashDirs( + this.fileSystem_, this.config_, /*create=*/ false); + // If trash dirs do not yet exist, then return succesful empty read. + if (!trashDirs) { + return success([]); + } // Get all entries in trash/files. const filesReader = trashDirs.files.createReader();
diff --git a/ui/file_manager/file_manager/foreground/elements/BUILD.gn b/ui/file_manager/file_manager/foreground/elements/BUILD.gn index c5ce045c..12058deb 100644 --- a/ui/file_manager/file_manager/foreground/elements/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/elements/BUILD.gn
@@ -6,6 +6,7 @@ import("//third_party/closure_compiler/js_unit_tests.gni") import("//tools/polymer/polymer.gni") import("//ui/file_manager/base/gn/js_test_gen_html.gni") +import("//ui/webui/resources/tools/js_modulizer.gni") visibility = [ "//ui/file_manager/file_manager/foreground/*" ] @@ -25,7 +26,6 @@ ":closure_compile_internal", ":closure_compile_jsmodules", ":js_test_gen_html_modules_type_check_auto", - ":js_test_gen_html_type_check_auto", ] } @@ -57,14 +57,21 @@ deps = [ ":files_format_dialog.m", ":files_icon_button.m", + ":files_message.m", ":files_metadata_box.m", ":files_metadata_entry.m", + ":files_password_dialog.m", ":files_quick_view.m", ":files_ripple.m", ":files_safe_media.m", + ":files_spinner.m", ":files_toast.m", ":files_toggle_ripple.m", ":files_tooltip.m", + ":xf_button.m", + ":xf_circular_progress.m", + ":xf_display_panel.m", + ":xf_panel_item.m", ] } @@ -154,13 +161,25 @@ ] } -js_unittest("files_message_unittest") { +js_unittest("files_message_unittest.m") { deps = [ - ":files_message", - "//ui/webui/resources/js:webui_resource_test", + ":files_message.m", + "//chrome/test/data/webui:chai_assert", + "//ui/webui/resources/js:assert.m", ] } +js_library("files_message.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/files_message.m.js" ] + deps = [ + "//ui/webui/resources/cr_elements/cr_button:cr_button.m", + "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m", + "//ui/webui/resources/js:assert.m", + ] + + extra_deps = [ ":modulize" ] +} + js_library("files_metadata_box") { externs_list = [ "$externs_path/pending_polymer.js" ] } @@ -208,14 +227,28 @@ ] } -js_unittest("files_password_dialog_unittest") { +js_unittest("files_password_dialog_unittest.m") { deps = [ - ":files_password_dialog", - "//ui/file_manager/base/js:test_error_reporting", - "//ui/webui/resources/js:webui_resource_test", + ":files_password_dialog.m", + "//chrome/test/data/webui:chai_assert", + "//ui/file_manager/base/js:test_error_reporting.m", + "//ui/webui/resources/js:assert.m", ] } +js_library("files_password_dialog.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/files_password_dialog.m.js" ] + deps = [ + "//ui/file_manager/file_manager/common/js:async_util.m", + "//ui/webui/resources/cr_elements/cr_button:cr_button.m", + "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m", + "//ui/webui/resources/cr_elements/cr_input:cr_input.m", + "//ui/webui/resources/js:load_time_data.m", + ] + + extra_deps = [ ":modulize" ] +} + js_library("files_quick_view") { deps = [ ":files_metadata_box" ] externs_list = [ @@ -298,6 +331,12 @@ js_library("files_spinner") { } +js_library("files_spinner.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/files_spinner.m.js" ] + + extra_deps = [ ":modulize" ] +} + # TODO(tapted): Move this to //ui/file_manager/base. js_library("files_toast") { visibility += [ "//ui/file_manager/gallery/*" ] @@ -381,21 +420,16 @@ ] } -js_unittest("files_xf_elements_unittest") { +js_unittest("files_xf_elements_unittest.m") { deps = [ - ":xf_display_panel", - "//ui/webui/resources/js:assert", - "//ui/webui/resources/js:webui_resource_test", + ":xf_display_panel.m", + "//chrome/test/data/webui:chai_assert", + "//ui/file_manager/file_manager/common/js:util.m", + "//ui/webui/resources/js:assert.m", + "//ui/webui/resources/js:load_time_data.m", ] -} -js_test_gen_html("js_test_gen_html") { - deps = [ - ":files_message_unittest", - ":files_password_dialog_unittest", - ":files_xf_elements_unittest", - ] - html_import = true + externs_list = [ "$externs_path/file_manager_private.js" ] } js_library("xf_button") { @@ -405,9 +439,26 @@ ] } +js_library("xf_button.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/xf_button.m.js" ] + deps = [ + "//ui/webui/resources/cr_elements/cr_button:cr_button.m", + "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m", + ] + + extra_deps = [ ":modulize" ] +} + js_library("xf_circular_progress") { } +js_library("xf_circular_progress.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/xf_circular_progress.m.js" ] + + deps = [ "//ui/webui/resources/js:assert.m" ] + extra_deps = [ ":modulize" ] +} + js_library("xf_display_panel") { deps = [ ":xf_panel_item", @@ -415,11 +466,36 @@ ] } +js_library("xf_display_panel.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/xf_display_panel.m.js" ] + deps = [ + ":xf_panel_item.m", + "//ui/file_manager/file_manager/common/js:util.m", + ] + + extra_deps = [ ":modulize" ] +} + +js_modulizer("modulize") { + input_files = [ + "files_message.js", + "files_spinner.js", + "files_password_dialog.js", + "xf_button.js", + "xf_circular_progress.js", + "xf_panel_item.js", + "xf_display_panel.js", + ] +} + js_test_gen_html("js_test_gen_html_modules") { is_polymer3 = true deps = [ + ":files_message_unittest.m", + ":files_password_dialog_unittest.m", ":files_toast_unittest.m", ":files_tooltip_unittest.m", + ":files_xf_elements_unittest.m", ] closure_flags = @@ -437,3 +513,15 @@ ":xf_circular_progress", ] } + +js_library("xf_panel_item.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/xf_panel_item.m.js" ] + deps = [ + ":xf_button.m", + ":xf_circular_progress.m", + "//ui/file_manager/file_manager/common/js:util.m", + "//ui/webui/resources/js:assert.m", + ] + + extra_deps = [ ":modulize" ] +}
diff --git a/ui/file_manager/file_manager/foreground/elements/files_message.js b/ui/file_manager/file_manager/foreground/elements/files_message.js index fd9c0c02..aedcc73 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_message.js +++ b/ui/file_manager/file_manager/foreground/elements/files_message.js
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {assert} from 'chrome://resources/js/assert.m.js'; + /** * FilesMessage template. * @const @type {string} @@ -72,7 +74,7 @@ /** * FilesMessage. */ -class FilesMessage extends HTMLElement { +/* #export */ class FilesMessage extends HTMLElement { constructor() { /** * Create element content.
diff --git a/ui/file_manager/file_manager/foreground/elements/files_message_unittest.js b/ui/file_manager/file_manager/foreground/elements/files_message_unittest.m.js similarity index 88% rename from ui/file_manager/file_manager/foreground/elements/files_message_unittest.js rename to ui/file_manager/file_manager/foreground/elements/files_message_unittest.m.js index 0c05347..ccacb32 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_message_unittest.js +++ b/ui/file_manager/file_manager/foreground/elements/files_message_unittest.m.js
@@ -2,22 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * TODO(lucmult): Remove this when converting to JS modules. - * @suppress {checkTypes} - */ -chrome.fileManagerPrivate = { - FormatFileSystemType: { - VFAT: 'vfat', - EXFAT: 'exfat', - NTFS: 'ntfs', - }, -}; +// clang-format off +import {assert} from 'chrome://resources/js/assert.m.js'; +import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://test/chai_assert.js'; + +import {FilesMessage} from './files_message.m.js'; +// clang-format on /** * Adds a FilesMessage element to the page, initially hidden. */ -function setUpPage() { +export function setUpPage() { document.body.innerHTML += '<files-message id="test-files-message" hidden></files-message>'; } @@ -43,7 +38,7 @@ // <files-message> [hidden] controls visual display. assertEquals('none', window.getComputedStyle(message).display); - assertNotEqual(null, message.getAttribute('hidden')); + assertNotEquals(null, message.getAttribute('hidden')); assertTrue(message.hidden); // <files-message> extends HTMLElement and so the setContent() method @@ -53,7 +48,7 @@ }); // <files-message> element should be visually displayed. - assertNotEqual('none', window.getComputedStyle(message).display); + assertNotEquals('none', window.getComputedStyle(message).display); assertEquals(null, message.getAttribute('hidden')); assertFalse(message.hidden); @@ -65,7 +60,7 @@ * setting its content via the element's property setters, and hiding its * sub-elements. */ -async function testFilesMessage(done) { +export async function testFilesMessage(done) { // Setup and return the <files-message> element. /** @type {!FilesMessage|!Element} */ const message = setFilesMessageContent(); @@ -83,11 +78,11 @@ const close = assert(message.shadowRoot.querySelector('#close')); // The sub-elements should be displayed. - assertNotEqual('none', window.getComputedStyle(icon).display); - assertNotEqual('none', window.getComputedStyle(text).display); - assertNotEqual('none', window.getComputedStyle(dismiss).display); - assertNotEqual('none', window.getComputedStyle(action).display); - assertNotEqual('none', window.getComputedStyle(close).display); + assertNotEquals('none', window.getComputedStyle(icon).display); + assertNotEquals('none', window.getComputedStyle(text).display); + assertNotEquals('none', window.getComputedStyle(dismiss).display); + assertNotEquals('none', window.getComputedStyle(action).display); + assertNotEquals('none', window.getComputedStyle(close).display); // To work with screen readers, the icon & text element containing // parent element should have aria role 'alert'. @@ -118,7 +113,7 @@ // Clicking the main element does not emit a visual signal. signal = 'main-element-not-clickable'; - assertNotEqual(null, message.onclick); + assertNotEquals(null, message.onclick); message.click(); assertEquals('main-element-not-clickable', signal); @@ -175,7 +170,7 @@ message.close = {label: 'aria close label'}; assertEquals('aria close label', close.getAttribute('aria-label')); assertEquals('cr:close', close.getAttribute('iron-icon')); - assertNotEqual(null, close.onclick); + assertNotEquals(null, close.onclick); signal = null; close.click(); assertEquals('cr:close', signal); @@ -218,7 +213,7 @@ // Setting null text should display empty text. message.message = null; assertEquals('', text.getAttribute('aria-label')); - assertNotEqual('none', window.getComputedStyle(text).display); + assertNotEquals('none', window.getComputedStyle(text).display); done(); }
diff --git a/ui/file_manager/file_manager/foreground/elements/files_password_dialog.js b/ui/file_manager/file_manager/foreground/elements/files_password_dialog.js index 4b7eca4..4c956d5 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_password_dialog.js +++ b/ui/file_manager/file_manager/foreground/elements/files_password_dialog.js
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +// #import {AsyncUtil} from '../../common/js/async_util.m.js'; + /** * FilesPasswordDialog template. * @const @type {string} @@ -54,7 +57,7 @@ * FilesPasswordDialog.USER_CANCELLED. * @extends HTMLElement */ -class FilesPasswordDialog extends HTMLElement { +/* #export */ class FilesPasswordDialog extends HTMLElement { constructor() { /* * Create element content.
diff --git a/ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.js b/ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.m.js similarity index 89% rename from ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.js rename to ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.m.js index 6096d86..fec6447 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.js +++ b/ui/file_manager/file_manager/foreground/elements/files_password_dialog_unittest.m.js
@@ -2,6 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// clang-format off +import "chrome://resources/cr_elements/cr_button/cr_button.m.js"; +import "chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js"; +import "chrome://resources/cr_elements/cr_input/cr_input.m.js"; + +import {assert} from 'chrome://resources/js/assert.m.js'; +import {assertEquals, assertFalse, assertNotReached} from 'chrome://test/chai_assert.js'; +import {waitUntil} from '../../../base/js/test_error_reporting.m.js'; +import {FilesPasswordDialog} from './files_password_dialog.m.js'; +// clang-format on + /** @type {!FilesPasswordDialog} */ let passwordDialog; /** @type {!CrDialogElement} */ @@ -16,21 +27,9 @@ let unlock; /** - * TODO(lucmult): Remove this when converting to JS modules. - * @suppress {checkTypes} - */ -chrome.fileManagerPrivate = { - FormatFileSystemType: { - VFAT: 'vfat', - EXFAT: 'exfat', - NTFS: 'ntfs', - }, -}; - -/** * Mock LoadTimeData strings. */ -function setUpPage() { +export function setUpPage() { window.loadTimeData.getString = id => { switch (id) { case 'PASSWORD_DIALOG_INVALID': @@ -44,7 +43,7 @@ /** * Adds a FilesPasswordDialog element to the page. */ -function setUp() { +export function setUp() { document.body.innerHTML = `<files-password-dialog id="test-files-password-dialog" hidden> </files-password-dialog>`; @@ -71,7 +70,7 @@ * The askForPassword method should return a promise that is rejected with * FilesPasswordDialog.USER_CANCELLED. */ -async function testSingleArchiveCancelPasswordPrompt(done) { +export async function testSingleArchiveCancelPasswordPrompt(done) { // Check that the dialog is closed. assertFalse(dialog.open); @@ -116,7 +115,7 @@ * method should return a promise that resolves with the expected input * password. */ -async function testUnlockSingleArchive(done) { +export async function testUnlockSingleArchive(done) { // Check that the dialog is closed. assertFalse(dialog.open); @@ -152,7 +151,7 @@ * Tests opening the password dialog with an 'Invalid password' message. This * message is displayed when a wrong password was previously entered. */ -async function testDialogWithWrongPassword(done) { +export async function testDialogWithWrongPassword(done) { // Check that the dialog is closed. assertFalse(dialog.open); @@ -178,7 +177,7 @@ /** * Tests cancel functionality for multiple encrypted archives. */ -async function testCancelMultiplePasswordPrompts(done) { +export async function testCancelMultiplePasswordPrompts(done) { // Check that the dialog is closed. assertFalse(dialog.open); @@ -240,7 +239,7 @@ /** * Tests unlock functionality for multiple encrypted archives. */ -async function testUnlockMultipleArchives(done) { +export async function testUnlockMultipleArchives(done) { // Check that the dialog is closed. assertFalse(dialog.open);
diff --git a/ui/file_manager/file_manager/foreground/elements/files_spinner.js b/ui/file_manager/file_manager/foreground/elements/files_spinner.js index ad428f2..c8013e3 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_spinner.js +++ b/ui/file_manager/file_manager/foreground/elements/files_spinner.js
@@ -63,7 +63,7 @@ /** * FilesSpinner. */ -class FilesSpinner extends HTMLElement { +/* #export */ class FilesSpinner extends HTMLElement { constructor() { super().attachShadow({mode: 'open'}).innerHTML = filesSpinnerTemplate; }
diff --git a/ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.js b/ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.m.js similarity index 94% rename from ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.js rename to ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.m.js index 2e605bce..64d4798 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.js +++ b/ui/file_manager/file_manager/foreground/elements/files_xf_elements_unittest.m.js
@@ -2,17 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * TODO(lucmult): Remove this when converting to JS modules. - * @suppress {checkTypes, constantProperty} - */ -chrome.fileManagerPrivate = { - FormatFileSystemType: { - VFAT: 'vfat', - EXFAT: 'exfat', - NTFS: 'ntfs', - }, -}; +// clang-format off +import {assert} from 'chrome://resources/js/assert.m.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {assertEquals, assertFalse, assertTrue} from 'chrome://test/chai_assert.js'; + +import {util} from '../../common/js/util.m.js'; + +import {DisplayPanel} from './xf_display_panel.m.js'; +// clang-format on /** @type {!DisplayPanel|!Element} */ let displayPanel; @@ -20,7 +18,7 @@ /** * Adds a xf-display-panel element to the test page. */ -function setUp() { +export function setUp() { document.body.innerHTML += '<xf-display-panel id="test-xf-display-panel"></xf-display-panel>'; displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -28,12 +26,12 @@ const enableFilesTransferDetails = true; // Mock LoadTimeData strings for transfer details feature. - window.loadTimeData.data = { + loadTimeData.data = { FILES_TRANSFER_DETAILS_ENABLED: enableFilesTransferDetails }; - window.loadTimeData.getString = id => { - return window.loadTimeData.data_[id] || id; + loadTimeData.getString = id => { + return loadTimeData.data_[id] || id; }; /** @return {boolean} */ @@ -42,7 +40,7 @@ }; } -function tearDown() { +export function tearDown() { displayPanel.removeAllPanelItems(); } @@ -50,7 +48,7 @@ * Tests that adding and removing panels to <xf-display-panel> updates the * aria-hidden attribute. */ -function testDisplayPanelAriaHidden() { +export function testDisplayPanelAriaHidden() { // Starts without any panel so should be hidden; assertEquals(displayPanel.getAttribute('aria-hidden'), 'true'); @@ -77,7 +75,7 @@ assertEquals(displayPanel.getAttribute('aria-hidden'), 'true'); } -async function testDisplayPanelAttachPanel(done) { +export async function testDisplayPanelAttachPanel(done) { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -115,7 +113,7 @@ done(); } -async function testDisplayPanelChangingPanelTypes(done) { +export async function testDisplayPanelChangingPanelTypes(done) { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -210,7 +208,7 @@ done(); } -function testFilesDisplayPanelErrorText() { +export function testFilesDisplayPanelErrorText() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -249,7 +247,7 @@ return option + end; }; -function testFilesDisplayPanelErrorMarker() { +export function testFilesDisplayPanelErrorMarker() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -286,7 +284,7 @@ 'Summary panel error marker property is wrong, should be "hidden"'); } -function testFilesDisplayPanelMixedSummary() { +export function testFilesDisplayPanelMixedSummary() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -346,7 +344,7 @@ assertEquals('success', summaryPanelItem.status); } -function testFilesDisplayPanelMixedProgress() { +export function testFilesDisplayPanelMixedProgress() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -381,7 +379,7 @@ assertEquals('3', summaryPanelItem.progress); } -function testFilesDisplayPanelCircularProgress() { +export function testFilesDisplayPanelCircularProgress() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -401,7 +399,7 @@ assertEquals('4', strokeWidthContainerGroup.getAttribute('stroke-width')); } -async function testFilesDisplayPanelSummaryPanel(done) { +export async function testFilesDisplayPanelSummaryPanel(done) { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -462,7 +460,7 @@ done(); } -function testFilesDisplayPanelTransferDetails() { +export function testFilesDisplayPanelTransferDetails() { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel')); @@ -475,7 +473,7 @@ assertEquals('detailed-panel', progressPanel.getAttribute('detailed-panel')); } -async function testFilesDisplayPanelTransferDetailsSummary(done) { +export async function testFilesDisplayPanelTransferDetailsSummary(done) { // Get the host display panel container element. /** @type {!DisplayPanel|!Element} */ const displayPanel = assert(document.querySelector('#test-xf-display-panel'));
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_button.js b/ui/file_manager/file_manager/foreground/elements/xf_button.js index e5ee9682..55b93eab 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_button.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_button.js
@@ -5,7 +5,7 @@ /** * A button used inside PanelItem with varying display characteristics. */ -class PanelButton extends HTMLElement { +/* #export */ class PanelButton extends HTMLElement { constructor() { super(); this.createElement_();
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_circular_progress.js b/ui/file_manager/file_manager/foreground/elements/xf_circular_progress.js index 1cd4d13..5f6fc98 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_circular_progress.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_circular_progress.js
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {assert} from 'chrome://resources/js/assert.m.js'; + /** * Definition of a circular progress indicator custom element. * The element supports two attributes for control - 'radius' and 'progress'. @@ -11,7 +13,7 @@ * element.setAttribute('progress', '50'); to set progress to half complete * or alternately, set the 'element.progress' JS property for the same result. */ -class CircularProgress extends HTMLElement { +/* #export */ class CircularProgress extends HTMLElement { constructor() { super(); const host = document.createElement('template');
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js b/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js index d54b259b..38e391ff8 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js
@@ -2,11 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {PanelItem} from './xf_panel_item.m.js'; +// #import {util} from '../../common/js/util.m.js'; + /** * A panel to display a collection of PanelItem. * @extends HTMLElement */ -class DisplayPanel extends HTMLElement { +/* #export */ class DisplayPanel extends HTMLElement { constructor() { super(); this.createElement_();
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js index fc45a6d..4a923815 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js
@@ -2,11 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {assert} from 'chrome://resources/js/assert.m.js'; +// #import {util} from '../../common/js/util.m.js'; +// #import {DisplayPanel} from './xf_display_panel.m.js'; +// #import './xf_button.m.js'; +// #import './xf_circular_progress.m.js'; + /** * A panel to display the status or progress of a file operation. * @extends HTMLElement */ -class PanelItem extends HTMLElement { +/* #export */ class PanelItem extends HTMLElement { constructor() { super(); const host = document.createElement('template');
diff --git a/ui/file_manager/integration_tests/file_manager/background.js b/ui/file_manager/integration_tests/file_manager/background.js index becb357..4dadf4b 100644 --- a/ui/file_manager/integration_tests/file_manager/background.js +++ b/ui/file_manager/integration_tests/file_manager/background.js
@@ -62,6 +62,7 @@ */ const BASIC_LOCAL_ENTRY_SET_WITH_HIDDEN = BASIC_LOCAL_ENTRY_SET.concat([ ENTRIES.hiddenFile, + ENTRIES.dotTrash, ]); /**
diff --git a/ui/file_manager/integration_tests/file_manager/context_menu.js b/ui/file_manager/integration_tests/file_manager/context_menu.js index b66c1b1..8d2be347 100644 --- a/ui/file_manager/integration_tests/file_manager/context_menu.js +++ b/ui/file_manager/integration_tests/file_manager/context_menu.js
@@ -578,6 +578,7 @@ ['Downloads', '--', 'Folder'], ['Play files', '--', 'Folder'], ['Linux files', '--', 'Folder'], + ['Trash', '--', 'Folder'], ]; await remoteCall.waitForFiles( appId, expectedRows,
diff --git a/ui/file_manager/integration_tests/file_manager/file_dialog.js b/ui/file_manager/integration_tests/file_manager/file_dialog.js index 12d9d28e..f8c1d0e 100644 --- a/ui/file_manager/integration_tests/file_manager/file_dialog.js +++ b/ui/file_manager/integration_tests/file_manager/file_dialog.js
@@ -783,6 +783,7 @@ ['Play files', '--', 'Folder'], ['Downloads', '--', 'Folder'], ['Linux files', '--', 'Folder'], + ['Trash', '--', 'Folder'], ]; await remoteCall.waitForFiles( appId, expectedRows, {ignoreLastModifiedTime: true});
diff --git a/ui/file_manager/integration_tests/file_manager/file_display.js b/ui/file_manager/integration_tests/file_manager/file_display.js index cd18cdd9..63ae16d 100644 --- a/ui/file_manager/integration_tests/file_manager/file_display.js +++ b/ui/file_manager/integration_tests/file_manager/file_display.js
@@ -516,8 +516,9 @@ await remoteCall.waitForElement(appId, '[volume-type-icon="downloads"]'); const downloadsRow = ['Downloads', '--', 'Folder']; const crostiniRow = ['Linux files', '--', 'Folder']; + const trashRow = ['Trash', '--', 'Folder']; await remoteCall.waitForFiles( - appId, [downloadsRow, crostiniRow], + appId, [downloadsRow, crostiniRow, trashRow], {ignoreFileSize: true, ignoreLastModifiedTime: true}); }; @@ -713,6 +714,7 @@ ['Play files', '--', 'Folder'], ['Downloads', '--', 'Folder'], ['Linux files', '--', 'Folder'], + ['Trash', '--', 'Folder'], ]; await remoteCall.waitForFiles( appId, expectedRows, {ignoreLastModifiedTime: true}); @@ -774,6 +776,7 @@ ['Play files', '--', 'Folder'], ['Downloads', '--', 'Folder'], ['Linux files', '--', 'Folder'], + ['Trash', '--', 'Folder'], ]; await remoteCall.waitForFiles( appId, expectedRows, {ignoreLastModifiedTime: true});
diff --git a/ui/file_manager/integration_tests/file_manager/file_list.js b/ui/file_manager/integration_tests/file_manager/file_list.js index 8c83fc9..9424d6b 100644 --- a/ui/file_manager/integration_tests/file_manager/file_list.js +++ b/ui/file_manager/integration_tests/file_manager/file_list.js
@@ -318,8 +318,6 @@ // Delete item and confirm delete. await remoteCall.waitAndClickElement(appId, '#delete-button'); - await remoteCall.waitAndClickElement( - appId, '.files-confirm-dialog .cr-dialog-ok'); // Wait for completion of file deletion. await remoteCall.waitForElementLost( @@ -342,8 +340,6 @@ await remoteCall.waitAndClickElement( appId, '#file-list [file-name="photos"]'); await remoteCall.waitAndClickElement(appId, '#delete-button'); - await remoteCall.waitAndClickElement( - appId, '.files-confirm-dialog .cr-dialog-ok'); // Wait for file deletion. await remoteCall.waitForElementLost(
diff --git a/ui/file_manager/integration_tests/file_manager/files_tooltip.js b/ui/file_manager/integration_tests/file_manager/files_tooltip.js index 2cfbbf1..0818add 100644 --- a/ui/file_manager/integration_tests/file_manager/files_tooltip.js +++ b/ui/file_manager/integration_tests/file_manager/files_tooltip.js
@@ -269,7 +269,7 @@ */ testcase.filesTooltipHidesOnDeleteDialogClosed = async () => { const appId = await setupAndWaitUntilReady( - RootPath.DOWNLOADS, [ENTRIES.beautiful, ENTRIES.photos], []); + RootPath.DRIVE, [], [ENTRIES.beautiful, ENTRIES.photos]); const fileListItemQuery = '#file-list li[file-name="Beautiful Song.ogg"]'; const okButtonQuery = '.cr-dialog-ok';
diff --git a/ui/file_manager/integration_tests/file_manager/keyboard_operations.js b/ui/file_manager/integration_tests/file_manager/keyboard_operations.js index bfdb68b..7108f874 100644 --- a/ui/file_manager/integration_tests/file_manager/keyboard_operations.js +++ b/ui/file_manager/integration_tests/file_manager/keyboard_operations.js
@@ -102,8 +102,9 @@ * Tests deleting a file from the file list. * * @param {string} path The path to be tested, Downloads or Drive. + * @param {boolean} deleteHasDialog whether delete shows confirmation dialog. */ -async function keyboardDelete(path) { +async function keyboardDelete(path, deleteHasDialog) { const appId = await setupAndWaitUntilReady(path, [ENTRIES.hello], [ENTRIES.hello]); @@ -113,7 +114,9 @@ 'deleteFile failed'); // Run the delete entry confirmation dialog. - await waitAndAcceptDialog(appId); + if (deleteHasDialog) { + await waitAndAcceptDialog(appId); + } // Check: the file list should be empty. await remoteCall.waitForFiles(appId, []); @@ -125,8 +128,9 @@ * * @param {string} path The path to be tested, Downloads or Drive. * @param {string} treeItem The directory tree item selector. + * @param {boolean} deleteHasDialog whether delete shows confirmation dialog. */ -async function keyboardDeleteFolder(path, treeItem) { +async function keyboardDeleteFolder(path, treeItem, deleteHasDialog) { const appId = await setupAndWaitUntilReady(path, [ENTRIES.photos], [ENTRIES.photos]); @@ -142,7 +146,9 @@ 'deleteFile failed'); // Run the delete entry confirmation dialog. - await waitAndAcceptDialog(appId); + if (deleteHasDialog) { + await waitAndAcceptDialog(appId); + } // Check: the file list should be empty. await remoteCall.waitForFiles(appId, []); @@ -289,19 +295,21 @@ }; testcase.keyboardDeleteDownloads = () => { - return keyboardDelete(RootPath.DOWNLOADS); + return keyboardDelete(RootPath.DOWNLOADS, /*deleteHasDialog=*/ false); }; testcase.keyboardDeleteDrive = () => { - return keyboardDelete(RootPath.DRIVE); + return keyboardDelete(RootPath.DRIVE, /*deleteHasDialog=*/ true); }; testcase.keyboardDeleteFolderDownloads = () => { - return keyboardDeleteFolder(RootPath.DOWNLOADS, TREEITEM_DOWNLOADS); + return keyboardDeleteFolder( + RootPath.DOWNLOADS, TREEITEM_DOWNLOADS, /*deleteHasDialog=*/ false); }; testcase.keyboardDeleteFolderDrive = () => { - return keyboardDeleteFolder(RootPath.DRIVE, TREEITEM_DRIVE); + return keyboardDeleteFolder( + RootPath.DRIVE, TREEITEM_DRIVE, /*deleteHasDialog=*/ true); }; testcase.renameFileDownloads = () => { @@ -412,7 +420,7 @@ testcase.keyboardDisableCopyWhenDialogDisplayed = async () => { // Open Files app. const appId = - await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.hello], []); + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.hello]); // Select a file for deletion. chrome.test.assertTrue(
diff --git a/ui/file_manager/integration_tests/file_manager/my_files.js b/ui/file_manager/integration_tests/file_manager/my_files.js index 8d0f4f5..177076c 100644 --- a/ui/file_manager/integration_tests/file_manager/my_files.js +++ b/ui/file_manager/integration_tests/file_manager/my_files.js
@@ -18,8 +18,9 @@ const downloadsRow = ['Downloads', '--', 'Folder']; const playFilesRow = ['Play files', '--', 'Folder']; const crostiniRow = ['Linux files', '--', 'Folder']; + const trashRow = ['Trash', '--', 'Folder']; await remoteCall.waitForFiles( - appId, [downloadsRow, playFilesRow, crostiniRow], + appId, [downloadsRow, playFilesRow, crostiniRow, trashRow], {ignoreFileSize: true, ignoreLastModifiedTime: true}); } @@ -33,6 +34,7 @@ 'Downloads: SubDirectoryItem', 'Linux files: FakeItem', 'Play files: SubDirectoryItem', + 'Trash: SubDirectoryItem', 'Google Drive: DriveVolumeItem', 'My Drive: SubDirectoryItem', 'Shared with me: SubDirectoryItem', @@ -317,9 +319,10 @@ const downloadsRow = ['Downloads', '--', 'Folder']; const playFilesRow = ['Play files', '--', 'Folder']; const crostiniRow = ['Linux files', '--', 'Folder']; + const trashRow = ['Trash', '--', 'Folder']; await remoteCall.waitAndClickElement(appId, myFiles); await remoteCall.waitForFiles( - appId, [downloadsRow, crostiniRow], + appId, [downloadsRow, crostiniRow, trashRow], {ignoreFileSize: true, ignoreLastModifiedTime: true}); // Mount Play files volume. @@ -331,7 +334,7 @@ // Android volume should automatically appear on directory tree and file list. await remoteCall.waitForElement(appId, playFilesTreeItem); await remoteCall.waitForFiles( - appId, [downloadsRow, crostiniRow, playFilesRow], + appId, [downloadsRow, crostiniRow, playFilesRow, trashRow], {ignoreFileSize: true, ignoreLastModifiedTime: true}); // Un-mount Play files volume. @@ -342,7 +345,7 @@ // Check: Play files should disappear from file list. await remoteCall.waitForFiles( - appId, [downloadsRow, crostiniRow], + appId, [downloadsRow, crostiniRow, trashRow], {ignoreFileSize: true, ignoreLastModifiedTime: true}); // Check: Play files should disappear from directory tree.
diff --git a/ui/file_manager/integration_tests/file_manager/quick_view.js b/ui/file_manager/integration_tests/file_manager/quick_view.js index b98da13..9db6ce2 100644 --- a/ui/file_manager/integration_tests/file_manager/quick_view.js +++ b/ui/file_manager/integration_tests/file_manager/quick_view.js
@@ -2711,9 +2711,9 @@ * Tests that the tab-index focus stays within the delete confirm dialog. */ testcase.openQuickViewTabIndexDeleteDialog = async () => { - // Open Files app on Downloads containing ENTRIES.hello. + // Open Files app. const appId = - await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.hello], []); + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.hello]); // Open the file in Quick View. await openQuickView(appId, ENTRIES.hello.nameText); @@ -2756,9 +2756,9 @@ * that Quick View closes when there are no more items to view. */ testcase.openQuickViewAndDeleteSingleSelection = async () => { - // Open Files app on Downloads containing ENTRIES.hello. + // Open Files app. const appId = - await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.hello], []); + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.hello]); // Open the file in Quick View. await openQuickView(appId, ENTRIES.hello.nameText); @@ -2788,9 +2788,9 @@ * deletion. */ testcase.openQuickViewAndDeleteCheckSelection = async () => { - // Open Files app on Downloads containing BASIC_LOCAL_ENTRY_SET. - const appId = await setupAndWaitUntilReady( - RootPath.DOWNLOADS, BASIC_LOCAL_ENTRY_SET, []); + // Open Files app. + const appId = + await setupAndWaitUntilReady(RootPath.DRIVE, [], BASIC_LOCAL_ENTRY_SET); const caller = getCaller(); @@ -2910,16 +2910,12 @@ 'deepQueryAllElements', appId, [audioWebView, ['display']])); }); - // Open the Quick View delete confirm dialog. + // Press delete. const deleteKey = ['#quick-view', 'Delete', false, false, false]; chrome.test.assertTrue( await remoteCall.callRemoteTestUtil('fakeKeyDown', appId, deleteKey), 'Pressing Delete failed.'); - // Click the delete confirm dialog OK button. - const deleteConfirm = ['#quick-view', '.cr-dialog-ok:not([hidden])']; - await remoteCall.waitAndClickElement(appId, deleteConfirm); - // Check: |Beautiful Song.ogg| should have been deleted. await remoteCall.waitForElementLost( appId, '#file-list [file-name="Beautiful Song.ogg"]'); @@ -2947,14 +2943,11 @@ 'deepQueryAllElements', appId, [imageWebView, ['display']])); }); - // Open the Quick View delete confirm dialog. + // Press delete. chrome.test.assertTrue( await remoteCall.callRemoteTestUtil('fakeKeyDown', appId, deleteKey), 'Pressing Delete failed.'); - // Click the delete confirm dialog OK button. - await remoteCall.waitAndClickElement(appId, deleteConfirm); - // Check: |My Desktop Background.png| should have been deleted. await remoteCall.waitForElementLost( appId, '#file-list [file-name="My Desktop Background.png"]'); @@ -2979,10 +2972,6 @@ ['#quick-view', '#delete-button:not([hidden])']; await remoteCall.waitAndClickElement(appId, quickViewDeleteButton); - // Click the delete confirm dialog OK button. - const deleteConfirm = ['#quick-view', '.cr-dialog-ok:not([hidden])']; - await remoteCall.waitAndClickElement(appId, deleteConfirm); - // Check: |hello.txt| should have been deleted. await remoteCall.waitForElementLost( appId, '#file-list [file-name="hello.txt"]'); @@ -3007,6 +2996,7 @@ ['Play files', '--', 'Folder'], ['Downloads', '--', 'Folder'], ['Linux files', '--', 'Folder'], + ['Trash', '--', 'Folder'], ]; await remoteCall.waitForFiles( appId, expectedRows, {ignoreLastModifiedTime: true});
diff --git a/ui/file_manager/integration_tests/file_manager/toolbar.js b/ui/file_manager/integration_tests/file_manager/toolbar.js index 0a624ec..6eed02b 100644 --- a/ui/file_manager/integration_tests/file_manager/toolbar.js +++ b/ui/file_manager/integration_tests/file_manager/toolbar.js
@@ -29,10 +29,9 @@ * dialog. */ testcase.toolbarDeleteButtonKeepFocus = async () => { - const entries = [ENTRIES.desktop]; - // Open Files app. - const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, entries, []); + const appId = + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.desktop]); // Select My Desktop Background.png chrome.test.assertTrue(await remoteCall.callRemoteTestUtil( @@ -87,16 +86,6 @@ chrome.test.assertTrue(await remoteCall.callRemoteTestUtil( 'fakeMouseClick', appId, ['#delete-button'])); - - // Confirm that the confirmation dialog is shown. - await remoteCall.waitForElement(appId, '.cr-dialog-container.shown'); - - // Press delete button. - chrome.test.assertTrue( - !!await remoteCall.callRemoteTestUtil( - 'fakeMouseClick', appId, ['button.cr-dialog-ok']), - 'fakeMouseClick failed'); - // Confirm the file is removed. await remoteCall.waitForFiles( appId, afterDeletion, {ignoreLastModifiedTime: true});
diff --git a/ui/file_manager/integration_tests/file_manager/transfer.js b/ui/file_manager/integration_tests/file_manager/transfer.js index 2540f652..14de9b3 100644 --- a/ui/file_manager/integration_tests/file_manager/transfer.js +++ b/ui/file_manager/integration_tests/file_manager/transfer.js
@@ -304,6 +304,14 @@ sizeText: '--', typeText: 'Folder' }), + new TestEntryInfo({ + type: EntryType.DIRECTORY, + targetPath: 'Trash', + nameText: 'Trash', + lastModifiedTime: '...', + sizeText: '--', + typeText: 'Folder' + }), ] }), }; @@ -904,8 +912,9 @@ chrome.test.assertTrue(await remoteCall.callRemoteTestUtil( 'deleteFile', appId, [entry.nameText])); - // Confirm deletion. - await waitAndAcceptDialog(appId); + // Wait for completion of file deletion. + await remoteCall.waitForElementLost( + appId, `#file-list [file-name="${entry.nameText}"]`); // Paste the file. chrome.test.assertTrue(
diff --git a/ui/file_manager/integration_tests/test_util.js b/ui/file_manager/integration_tests/test_util.js index 7d11e19..759d206 100644 --- a/ui/file_manager/integration_tests/test_util.js +++ b/ui/file_manager/integration_tests/test_util.js
@@ -848,6 +848,15 @@ typeText: 'Folder' }), + dotTrash: new TestEntryInfo({ + type: EntryType.DIRECTORY, + targetPath: '.Trash', + lastModifiedTime: 'Jan 1, 2000, 1:00 AM', + nameText: '.Trash', + sizeText: '--', + typeText: 'Folder' + }), + deeplyBurriedSmallJpeg: new TestEntryInfo({ type: EntryType.FILE, targetPath: 'A/B/C/deep.jpg',
diff --git a/ui/gfx/geometry/resize_utils.cc b/ui/gfx/geometry/resize_utils.cc index cde1838..33de68b 100644 --- a/ui/gfx/geometry/resize_utils.cc +++ b/ui/gfx/geometry/resize_utils.cc
@@ -4,43 +4,32 @@ #include "ui/gfx/geometry/resize_utils.h" -#include <algorithm> - #include "base/check_op.h" +#include "base/numerics/ranges.h" +#include "base/numerics/safe_conversions.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace gfx { +namespace { -void SizeMinMaxToAspectRatio(float aspect_ratio, - Size* min_window_size, - Size* max_window_size) { - DCHECK_GT(aspect_ratio, 0.0f); - - // Calculate the height using the min-width and aspect ratio. - int min_height = min_window_size->width() / aspect_ratio; - if (min_height < min_window_size->height()) { - // The supplied width is too small to honor the min size, so use the height - // to determine the minimum width. - min_window_size->set_width(min_window_size->height() * aspect_ratio); - } else { - min_window_size->set_height(min_height); +// This function decides whether SizeRectToAspectRatio() will adjust the height +// to match the specified width (resizing horizontally) or vice versa (resizing +// vertically). +bool IsResizingHorizontally(ResizeEdge resize_edge) { + switch (resize_edge) { + case ResizeEdge::kLeft: + case ResizeEdge::kRight: + case ResizeEdge::kTopLeft: + case ResizeEdge::kBottomLeft: + return true; + default: + return false; } - - // Calculate the height using the max-width and aspect ratio. - int max_height = max_window_size->width() / aspect_ratio; - if (max_height > max_window_size->height()) { - // The supplied width is too large to honor the max size, so use the height - // to determine the maximum width. - max_window_size->set_width(max_window_size->height() * aspect_ratio); - } else { - max_window_size->set_height(max_height); - } - - DCHECK_GE(max_window_size->width(), min_window_size->width()); - DCHECK_GE(max_window_size->height(), min_window_size->height()); } +} // namespace + void SizeRectToAspectRatio(ResizeEdge resize_edge, float aspect_ratio, const Size& min_window_size, @@ -49,21 +38,39 @@ DCHECK_GT(aspect_ratio, 0.0f); DCHECK_GE(max_window_size.width(), min_window_size.width()); DCHECK_GE(max_window_size.height(), min_window_size.height()); + DCHECK(rect->Contains(Rect(rect->origin(), min_window_size))) + << rect->ToString() << " is smaller than the minimum size " + << min_window_size.ToString(); + DCHECK(Rect(rect->origin(), max_window_size).Contains(*rect)) + << rect->ToString() << " is larger than the maximum size " + << max_window_size.ToString(); - float rect_width = 0.0; - float rect_height = 0.0; - if (resize_edge == ResizeEdge::kLeft || resize_edge == ResizeEdge::kRight || - resize_edge == ResizeEdge::kTopLeft || - resize_edge == ResizeEdge::kBottomLeft) { /* horizontal axis to pivot */ - rect_width = std::min(max_window_size.width(), - std::max(rect->width(), min_window_size.width())); - rect_height = rect_width / aspect_ratio; - } else { /* vertical axis to pivot */ - rect_height = std::min(max_window_size.height(), - std::max(rect->height(), min_window_size.height())); - rect_width = rect_height * aspect_ratio; + Size new_size = rect->size(); + if (IsResizingHorizontally(resize_edge)) { + new_size.set_height(base::ClampRound(new_size.width() / aspect_ratio)); + if (min_window_size.height() > new_size.height() || + new_size.height() > max_window_size.height()) { + new_size.set_height(base::ClampToRange(new_size.height(), + min_window_size.height(), + max_window_size.height())); + new_size.set_width(base::ClampRound(new_size.height() * aspect_ratio)); + } + } else { + new_size.set_width(base::ClampRound(new_size.height() * aspect_ratio)); + if (min_window_size.width() > new_size.width() || + new_size.width() > max_window_size.width()) { + new_size.set_width(base::ClampToRange( + new_size.width(), min_window_size.width(), max_window_size.width())); + new_size.set_height(base::ClampRound(new_size.width() / aspect_ratio)); + } } + // The dimensions might still be outside of the allowed ranges at this point. + // This happens when the aspect ratio makes it impossible to fit |rect| + // within the size limits without letter-/pillarboxing. + new_size.SetToMin(max_window_size); + new_size.SetToMax(min_window_size); + // |rect| bounds before sizing to aspect ratio. int left = rect->x(); int top = rect->y(); @@ -73,29 +80,29 @@ switch (resize_edge) { case ResizeEdge::kRight: case ResizeEdge::kBottom: - right = rect_width + left; - bottom = top + rect_height; + right = new_size.width() + left; + bottom = top + new_size.height(); break; case ResizeEdge::kTop: - right = rect_width + left; - top = bottom - rect_height; + right = new_size.width() + left; + top = bottom - new_size.height(); break; case ResizeEdge::kLeft: case ResizeEdge::kTopLeft: - left = right - rect_width; - top = bottom - rect_height; + left = right - new_size.width(); + top = bottom - new_size.height(); break; case ResizeEdge::kTopRight: - right = left + rect_width; - top = bottom - rect_height; + right = left + new_size.width(); + top = bottom - new_size.height(); break; case ResizeEdge::kBottomLeft: - left = right - rect_width; - bottom = top + rect_height; + left = right - new_size.width(); + bottom = top + new_size.height(); break; case ResizeEdge::kBottomRight: - right = left + rect_width; - bottom = top + rect_height; + right = left + new_size.width(); + bottom = top + new_size.height(); break; }
diff --git a/ui/gfx/geometry/resize_utils.h b/ui/gfx/geometry/resize_utils.h index 44d697a..318a31b 100644 --- a/ui/gfx/geometry/resize_utils.h +++ b/ui/gfx/geometry/resize_utils.h
@@ -23,12 +23,6 @@ kTopRight }; -// Force the min and max window sizes to adhere to the aspect ratio. -// |aspect_ratio| must be valid and is found using width / height. -void GEOMETRY_EXPORT SizeMinMaxToAspectRatio(float aspect_ratio, - Size* min_window_size, - Size* max_window_size); - // Updates |rect| to adhere to the |aspect_ratio| of the window, if it has // been set. |resize_edge| refers to the edge of the window being sized. // |min_window_size| and |max_window_size| are expected to adhere to the
diff --git a/ui/gfx/geometry/resize_utils_unittest.cc b/ui/gfx/geometry/resize_utils_unittest.cc index 6f669f8..bf1e90b 100644 --- a/ui/gfx/geometry/resize_utils_unittest.cc +++ b/ui/gfx/geometry/resize_utils_unittest.cc
@@ -4,6 +4,10 @@ #include "ui/gfx/geometry/resize_utils.h" +#include <string> + +#include "base/strings/strcat.h" +#include "base/strings/string_number_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" @@ -16,132 +20,162 @@ constexpr float kAspectRatioHorizontal = 2.0f; constexpr float kAspectRatioVertical = 0.5f; -const Size kMinSizeSquare = Size(10, 10); -const Size kMaxSizeSquare = Size(50, 50); +constexpr Size kMinSizeHorizontal(20, 10); +constexpr Size kMaxSizeHorizontal(50, 25); -const Size kMinSizeHorizontal = Size(20, 10); -const Size kMaxSizeHorizontal = Size(50, 25); +constexpr Size kMinSizeVertical(10, 20); +constexpr Size kMaxSizeVertical(25, 50); -const Size kMinSizeVertical = Size(10, 20); -const Size kMaxSizeVertical = Size(25, 50); +std::string HitTestToString(ResizeEdge resize_edge) { + switch (resize_edge) { + case ResizeEdge::kTop: + return "top"; + case ResizeEdge::kTopRight: + return "top-righ"; + case ResizeEdge::kRight: + return "right"; + case ResizeEdge::kBottomRight: + return "bottom-right"; + case ResizeEdge::kBottom: + return "bottom"; + case ResizeEdge::kBottomLeft: + return "bottom-left"; + case ResizeEdge::kLeft: + return "left"; + case ResizeEdge::kTopLeft: + return "top-left"; + } +} } // namespace -// Tests resizing of window with a 1:1 aspect ratio. This test also tests the -// 'pivot points' when resizing, i.e. the opposite side or corner of the -// window. -TEST(WindowResizeUtilsTest, SizeToSquareAspectRatio) { - // Size from the top of the window. - // |window_rect| within the bounds of kMinSizeSquare and kMaxSizeSquare. - Rect window_rect(100, 100, 15, 15); - SizeRectToAspectRatio(ResizeEdge::kTop, kAspectRatioSquare, kMinSizeSquare, - kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, 15, 15)); +struct SizingParams { + ResizeEdge resize_edge{}; + float aspect_ratio = 0.0f; + Size min_size; + Size max_size; + Rect input_rect; + Rect expected_output_rect; - // Size from the bottom right corner of the window. - // |window_rect| smaller than kMinSizeSquare. - window_rect.SetRect(100, 100, 5, 5); - SizeRectToAspectRatio(ResizeEdge::kBottomRight, kAspectRatioSquare, - kMinSizeSquare, kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(100, 100, kMinSizeSquare.width(), kMinSizeSquare.height())); + std::string ToString() const { + return base::StrCat({HitTestToString(resize_edge), + " ratio=", base::NumberToString(aspect_ratio), " [", + min_size.ToString(), "..", max_size.ToString(), "] ", + input_rect.ToString(), " -> ", + expected_output_rect.ToString()}); + } +}; - // Size from the top of the window. - // |window_rect| larger than kMaxSizeSquare. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kTop, kAspectRatioSquare, kMinSizeSquare, - kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(100, 150, kMaxSizeSquare.width(), kMaxSizeSquare.height())); +using ResizeUtilsTest = testing::TestWithParam<SizingParams>; - // Size from the bottom of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kBottom, kAspectRatioSquare, kMinSizeSquare, - kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(100, 100, kMaxSizeSquare.width(), kMaxSizeSquare.height())); - - // Size from the left of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kLeft, kAspectRatioSquare, kMinSizeSquare, - kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(150, 150, kMaxSizeSquare.width(), kMaxSizeSquare.height())); - - // Size from the right of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kRight, kAspectRatioSquare, kMinSizeSquare, - kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(100, 100, kMaxSizeSquare.width(), kMaxSizeSquare.height())); - - // Size from the top left corner of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kTopLeft, kAspectRatioSquare, - kMinSizeSquare, kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(150, 150, kMaxSizeSquare.width(), kMaxSizeSquare.height())); - - // Size from the top right corner of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kTopRight, kAspectRatioSquare, - kMinSizeSquare, kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(100, 150, kMaxSizeSquare.width(), kMaxSizeSquare.height())); - - // Size from the bottom left corner of the window. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kBottomLeft, kAspectRatioSquare, - kMinSizeSquare, kMaxSizeSquare, &window_rect); - EXPECT_EQ(window_rect, - Rect(150, 100, kMaxSizeSquare.width(), kMaxSizeSquare.height())); +TEST_P(ResizeUtilsTest, SizeRectToAspectRatio) { + Rect rect = GetParam().input_rect; + SizeRectToAspectRatio(GetParam().resize_edge, GetParam().aspect_ratio, + GetParam().min_size, GetParam().max_size, &rect); + EXPECT_EQ(rect, GetParam().expected_output_rect) << GetParam().ToString(); } -// Tests the aspect ratio of the Rect adheres to the horizontal aspect -// ratio. -TEST(WindowResizeUtilsTest, SizeToHorizontalAspectRatio) { - // |window_rect| within bounds of kMinSizeHorizontal and kMaxSizeHorizontal. - Rect window_rect(100, 100, 20, 10); - SizeRectToAspectRatio(ResizeEdge::kTop, kAspectRatioHorizontal, - kMinSizeHorizontal, kMaxSizeHorizontal, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, 20, 10)); +const SizingParams kSizeRectToSquareAspectRatioTestCases[] = { + // Dragging the top resizer up. + {ResizeEdge::kTop, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 98, 22, 24), Rect(100, 98, 24, 24)}, - // |window_rect| smaller than kMinSizeHorizontal. - window_rect.SetRect(100, 100, 5, 5); - SizeRectToAspectRatio(ResizeEdge::kBottomRight, kAspectRatioHorizontal, - kMinSizeHorizontal, kMaxSizeHorizontal, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, kMinSizeHorizontal.width(), - kMinSizeHorizontal.height())); + // Dragging the bottom resizer down. + {ResizeEdge::kBottom, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 100, 22, 24), Rect(100, 100, 24, 24)}, - // |window_rect| greater than kMaxSizeHorizontal. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kTop, kAspectRatioHorizontal, - kMinSizeHorizontal, kMaxSizeHorizontal, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 175, kMaxSizeHorizontal.width(), - kMaxSizeHorizontal.height())); -} + // Dragging the left resizer right. + {ResizeEdge::kLeft, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(102, 100, 22, 24), Rect(102, 102, 22, 22)}, -// Tests the aspect ratio of the Rect adheres to the vertical aspect ratio. -TEST(WindowResizeUtilsTest, SizeToVerticalAspectRatio) { - // |window_rect| within bounds of kMinSizeVertical and kMaxSizeVertical. - Rect window_rect(100, 100, 10, 20); - SizeRectToAspectRatio(ResizeEdge::kBottomRight, kAspectRatioVertical, - kMinSizeVertical, kMaxSizeVertical, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, 10, 20)); + // Dragging the right resizer left. + {ResizeEdge::kRight, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 100, 22, 24), Rect(100, 100, 22, 22)}, - // |window_rect| smaller than kMinSizeVertical. - window_rect.SetRect(100, 100, 5, 5); - SizeRectToAspectRatio(ResizeEdge::kBottomRight, kAspectRatioVertical, - kMinSizeVertical, kMaxSizeVertical, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, kMinSizeVertical.width(), - kMinSizeVertical.height())); + // Dragging the top-left resizer right. + {ResizeEdge::kTopLeft, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(102, 100, 22, 24), Rect(102, 102, 22, 22)}, - // |window_rect| greater than kMaxSizeVertical. - window_rect.SetRect(100, 100, 100, 100); - SizeRectToAspectRatio(ResizeEdge::kBottomRight, kAspectRatioVertical, - kMinSizeVertical, kMaxSizeVertical, &window_rect); - EXPECT_EQ(window_rect, Rect(100, 100, kMaxSizeVertical.width(), - kMaxSizeVertical.height())); -} + // Dragging the top-right resizer down. + {ResizeEdge::kTopRight, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 102, 24, 22), Rect(100, 102, 22, 22)}, + + // Dragging the bottom-left resizer right. + {ResizeEdge::kBottomLeft, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 102, 22, 24), Rect(100, 102, 22, 22)}, + + // Dragging the bottom-right resizer up. + {ResizeEdge::kBottomRight, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 100, 24, 22), Rect(100, 100, 22, 22)}, + + // Dragging the bottom-right resizer left. + // Rect already as small as `kMinSizeHorizontal` allows. + {ResizeEdge::kBottomRight, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, + Rect(100, 100, kMinSizeHorizontal.width(), kMinSizeHorizontal.width()), + Rect(100, 100, kMinSizeHorizontal.width(), kMinSizeHorizontal.width())}, + + // Dragging the top-left resizer left. + // Rect already as large as `kMaxSizeHorizontal` allows. + {ResizeEdge::kTopLeft, kAspectRatioSquare, kMinSizeHorizontal, + kMaxSizeHorizontal, + Rect(100, 100, kMaxSizeHorizontal.height(), kMaxSizeHorizontal.height()), + Rect(100, 100, kMaxSizeHorizontal.height(), kMaxSizeHorizontal.height())}, +}; + +const SizingParams kSizeRectToHorizontalAspectRatioTestCases[] = { + // Dragging the top resizer down. + {ResizeEdge::kTop, kAspectRatioHorizontal, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(100, 102, 48, 22), Rect(100, 102, 44, 22)}, + + // Dragging the left resizer left. + {ResizeEdge::kLeft, kAspectRatioHorizontal, kMinSizeHorizontal, + kMaxSizeHorizontal, Rect(96, 100, 48, 22), Rect(96, 98, 48, 24)}, + + // Rect already as small as `kMinSizeHorizontal` allows. + {ResizeEdge::kTop, kAspectRatioHorizontal, kMinSizeHorizontal, + kMaxSizeHorizontal, + Rect(100, 100, kMinSizeHorizontal.width(), kMinSizeHorizontal.height()), + Rect(100, 100, kMinSizeHorizontal.width(), kMinSizeHorizontal.height())}, + + // Rect already as large as `kMaxSizeHorizontal` allows. + {ResizeEdge::kTop, kAspectRatioHorizontal, kMinSizeHorizontal, + kMaxSizeHorizontal, + Rect(100, 100, kMaxSizeHorizontal.width(), kMaxSizeHorizontal.height()), + Rect(100, 100, kMaxSizeHorizontal.width(), kMaxSizeHorizontal.height())}, +}; + +const SizingParams kSizeRectToVerticalAspectRatioTestCases[] = { + // Dragging the bottom resizer up. + {ResizeEdge::kBottom, kAspectRatioVertical, kMinSizeVertical, + kMaxSizeVertical, Rect(100, 100, 24, 44), Rect(100, 100, 22, 44)}, + + // Dragging the right resizer right. + {ResizeEdge::kRight, kAspectRatioVertical, kMinSizeVertical, + kMaxSizeVertical, Rect(100, 100, 24, 44), Rect(100, 100, 24, 48)}, + + // Rect already as small as `kMinSizeVertical` allows. + {ResizeEdge::kTop, kAspectRatioVertical, kMinSizeVertical, kMaxSizeVertical, + Rect(100, 100, kMinSizeVertical.width(), kMinSizeVertical.height()), + Rect(100, 100, kMinSizeVertical.width(), kMinSizeVertical.height())}, + + // Rect already as large as `kMaxSizeVertical` allows. + {ResizeEdge::kTop, kAspectRatioVertical, kMinSizeVertical, kMaxSizeVertical, + Rect(100, 100, kMaxSizeVertical.width(), kMaxSizeVertical.height()), + Rect(100, 100, kMaxSizeVertical.width(), kMaxSizeVertical.height())}, +}; + +INSTANTIATE_TEST_SUITE_P( + Square, + ResizeUtilsTest, + testing::ValuesIn(kSizeRectToSquareAspectRatioTestCases)); +INSTANTIATE_TEST_SUITE_P( + Horizontal, + ResizeUtilsTest, + testing::ValuesIn(kSizeRectToHorizontalAspectRatioTestCases)); +INSTANTIATE_TEST_SUITE_P( + Vertical, + ResizeUtilsTest, + testing::ValuesIn(kSizeRectToVerticalAspectRatioTestCases)); } // namespace gfx
diff --git a/ui/ozone/platform/wayland/host/wayland_window_unittest.cc b/ui/ozone/platform/wayland/host/wayland_window_unittest.cc index 07e8515..7b9a7afd 100644 --- a/ui/ozone/platform/wayland/host/wayland_window_unittest.cc +++ b/ui/ozone/platform/wayland/host/wayland_window_unittest.cc
@@ -34,6 +34,7 @@ #include "ui/ozone/platform/wayland/test/mock_pointer.h" #include "ui/ozone/platform/wayland/test/mock_surface.h" #include "ui/ozone/platform/wayland/test/test_keyboard.h" +#include "ui/ozone/platform/wayland/test/test_output.h" #include "ui/ozone/platform/wayland/test/test_region.h" #include "ui/ozone/platform/wayland/test/test_touch.h" #include "ui/ozone/platform/wayland/test/test_wayland_server_thread.h" @@ -1397,6 +1398,45 @@ } } +TEST_P(WaylandWindowTest, ToplevelWindowUpdateBufferScale) { + VerifyAndClearExpectations(); + + // Buffer scale must be 1 when no output has been entered by the window. + EXPECT_EQ(1, window_->buffer_scale()); + + // Creating an output with scale 1. + wl::TestOutput* output1 = server_.CreateAndInitializeOutput(); + output1->SetRect(gfx::Rect(0, 0, 1920, 1080)); + output1->SetScale(1); + Sync(); + + // Creating an output with scale 2. + wl::TestOutput* output2 = server_.CreateAndInitializeOutput(); + output2->SetRect(gfx::Rect(0, 0, 1920, 1080)); + output2->SetScale(2); + Sync(); + + // Send the window to |output1|. + wl::MockSurface* surface = server_.GetObject<wl::MockSurface>( + window_->root_surface()->GetSurfaceId()); + ASSERT_TRUE(surface); + wl_surface_send_enter(surface->resource(), output1->resource()); + Sync(); + + // The window's scale and bounds must remain unchanged. + EXPECT_EQ(1, window_->buffer_scale()); + EXPECT_EQ(gfx::Rect(0, 0, 800, 600), window_->GetBounds()); + + // Simulating drag process from |output1| to |output2|. + wl_surface_send_enter(surface->resource(), output2->resource()); + wl_surface_send_leave(surface->resource(), output1->resource()); + Sync(); + + // The window must change its scale and bounds to keep DIP bounds the same. + EXPECT_EQ(2, window_->buffer_scale()); + EXPECT_EQ(gfx::Rect(0, 0, 1600, 1200), window_->GetBounds()); +} + // Tests WaylandWindow repositions menu windows to be relative to parent window // in a right way. TEST_P(WaylandWindowTest, AdjustPopupBounds) {
diff --git a/ui/strings/ui_strings.grd b/ui/strings/ui_strings.grd index 3140f63..1dba61b 100644 --- a/ui/strings/ui_strings.grd +++ b/ui/strings/ui_strings.grd
@@ -1072,6 +1072,9 @@ <message name="IDS_CLIPBOARD_HISTORY_MENU_TITLE" desc="The title of the clipboard history menu which shows the history of the clipboard data"> Clipboard history </message> + <message name="IDS_CLIPBOARD_HISTORY_DELETE_BUTTON" desc="Accessibility name of the button which functions to delete a clipboard history menu entry"> + Remove from clipboard. + </message> <!-- Strings describing the touch calibration UX --> <message name="IDS_DISPLAY_TOUCH_CALIBRATION_EXIT_LABEL" desc="A message to notify the user about using the escape key to exit the calibration mode.">
diff --git a/ui/strings/ui_strings_grd/IDS_CLIPBOARD_HISTORY_DELETE_BUTTON.png.sha1 b/ui/strings/ui_strings_grd/IDS_CLIPBOARD_HISTORY_DELETE_BUTTON.png.sha1 new file mode 100644 index 0000000..32fdb2f8 --- /dev/null +++ b/ui/strings/ui_strings_grd/IDS_CLIPBOARD_HISTORY_DELETE_BUTTON.png.sha1
@@ -0,0 +1 @@ +174cd4f4630ddd01a62b33f70cfbb2c2aecd2db6 \ No newline at end of file
diff --git a/ui/views/controls/label.cc b/ui/views/controls/label.cc index 46894704..eb06464 100644 --- a/ui/views/controls/label.cc +++ b/ui/views/controls/label.cc
@@ -108,6 +108,19 @@ stored_selection_range_ = gfx::Range::InvalidRange(); } +void Label::SetAccessibleName(const base::string16& name) { + if (name == accessible_name_) + return; + accessible_name_ = name; + OnPropertyChanged(&accessible_name_, kPropertyEffectsNone); + NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged, true); +} + +const base::string16& Label::GetAccessibleName() const { + return accessible_name_.empty() ? full_text_->GetDisplayText() + : accessible_name_; +} + int Label::GetTextContext() const { return text_context_; } @@ -619,7 +632,7 @@ else node_data->role = ax::mojom::Role::kStaticText; - node_data->SetName(full_text_->GetDisplayText()); + node_data->SetName(GetAccessibleName()); } base::string16 Label::GetTooltipText(const gfx::Point& p) const { @@ -1210,6 +1223,7 @@ ADD_PROPERTY_METADATA(bool, HandlesTooltips) ADD_PROPERTY_METADATA(bool, CollapseWhenHidden) ADD_PROPERTY_METADATA(int, MaximumWidth) +ADD_PROPERTY_METADATA(base::string16, AccessibleName) END_METADATA } // namespace views
diff --git a/ui/views/controls/label.h b/ui/views/controls/label.h index 9f5953b..4848b88 100644 --- a/ui/views/controls/label.h +++ b/ui/views/controls/label.h
@@ -90,6 +90,12 @@ const base::string16& GetText() const; virtual void SetText(const base::string16& text); + // Set the accessibility name that will be announced by the screen reader. + // If this function is not called, the screen reader defaults to verbalizing + // the text value. + void SetAccessibleName(const base::string16& name); + const base::string16& GetAccessibleName() const; + // Where the label appears in the UI. Passed in from the constructor. This is // a value from views::style::TextContext or an enum that extends it. int GetTextContext() const; @@ -454,6 +460,9 @@ std::unique_ptr<SelectionController> selection_controller_; + // Accessibility data. + base::string16 accessible_name_; + // Context menu related members. ui::SimpleMenuModel context_menu_contents_; std::unique_ptr<views::MenuRunner> context_menu_runner_;
diff --git a/ui/views/controls/label_unittest.cc b/ui/views/controls/label_unittest.cc index 5d6ab62..4e58e3b 100644 --- a/ui/views/controls/label_unittest.cc +++ b/ui/views/controls/label_unittest.cc
@@ -605,7 +605,9 @@ } TEST_F(LabelTest, Accessibility) { - label()->SetText(ASCIIToUTF16("My special text.")); + const base::string16 accessible_name = ASCIIToUTF16("A11y text."); + + label()->SetText(ASCIIToUTF16("Displayed text.")); ui::AXNodeData node_data; label()->GetAccessibleNodeData(&node_data); @@ -614,6 +616,33 @@ node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); EXPECT_FALSE( node_data.HasIntAttribute(ax::mojom::IntAttribute::kRestriction)); + + // Setting a custom accessible name overrides the displayed text in + // screen reader announcements. + label()->SetAccessibleName(accessible_name); + + label()->GetAccessibleNodeData(&node_data); + EXPECT_EQ(accessible_name, + node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); + EXPECT_NE(label()->GetText(), + node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); + + // Changing the displayed text will not impact the non-empty accessible name. + label()->SetText(ASCIIToUTF16("Different displayed Text.")); + + label()->GetAccessibleNodeData(&node_data); + EXPECT_EQ(accessible_name, + node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); + EXPECT_NE(label()->GetText(), + node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); + + // Clearing the accessible name will cause the screen reader to default to + // verbalizing the displayed text. + label()->SetAccessibleName(ASCIIToUTF16("")); + + label()->GetAccessibleNodeData(&node_data); + EXPECT_EQ(label()->GetText(), + node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); } TEST_F(LabelTest, TextChangeWithoutLayout) {
diff --git a/ui/views/widget/native_widget_mac.mm b/ui/views/widget/native_widget_mac.mm index 4b1cf53..d6793bb7 100644 --- a/ui/views/widget/native_widget_mac.mm +++ b/ui/views/widget/native_widget_mac.mm
@@ -665,7 +665,7 @@ void NativeWidgetMac::SetAspectRatio(const gfx::SizeF& aspect_ratio) { if (!GetNSWindowMojo()) return; - GetNSWindowMojo()->SetContentAspectRatio(aspect_ratio); + GetNSWindowMojo()->SetAspectRatio(aspect_ratio); } void NativeWidgetMac::FlashFrame(bool flash_frame) {
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 46f2701..d3a2fcb 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -930,7 +930,7 @@ if (GetWindowRect(hwnd(), &window_rect)) { gfx::Rect rect(window_rect); - SizeRectToAspectRatio(WMSZ_BOTTOMRIGHT, &rect); + SizeWindowToAspectRatio(WMSZ_BOTTOMRIGHT, &rect); SetBoundsInternal(rect, false); } } @@ -2588,7 +2588,7 @@ return; gfx::Rect window_rect(*rect); - SizeRectToAspectRatio(param, &window_rect); + SizeWindowToAspectRatio(param, &window_rect); // TODO(apacible): Account for window borders as part of the aspect ratio. // https://crbug/869487. @@ -3536,13 +3536,11 @@ ax_system_caret_ = nullptr; } -void HWNDMessageHandler::SizeRectToAspectRatio(UINT param, - gfx::Rect* window_rect) { +void HWNDMessageHandler::SizeWindowToAspectRatio(UINT param, + gfx::Rect* window_rect) { gfx::Size min_window_size; gfx::Size max_window_size; delegate_->GetMinMaxSize(&min_window_size, &max_window_size); - gfx::SizeMinMaxToAspectRatio(aspect_ratio_.value(), &min_window_size, - &max_window_size); min_window_size = delegate_->DIPToScreenSize(min_window_size); max_window_size = delegate_->DIPToScreenSize(max_window_size); gfx::SizeRectToAspectRatio(GetWindowResizeEdge(param), aspect_ratio_.value(),
diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h index 2f5eefa..3d498de 100644 --- a/ui/views/win/hwnd_message_handler.h +++ b/ui/views/win/hwnd_message_handler.h
@@ -607,7 +607,7 @@ // Updates |rect| to adhere to the |aspect_ratio| of the window. |param| // refers to the edge of the window being sized. - void SizeRectToAspectRatio(UINT param, gfx::Rect* rect); + void SizeWindowToAspectRatio(UINT param, gfx::Rect* rect); // Get the cursor position, which may be mocked if running a test POINT GetCursorPos() const;
diff --git a/ui/webui/resources/cr_components/chromeos/network_health/BUILD.gn b/ui/webui/resources/cr_components/chromeos/network_health/BUILD.gn index 18d4cbf3..92d161d0 100644 --- a/ui/webui/resources/cr_components/chromeos/network_health/BUILD.gn +++ b/ui/webui/resources/cr_components/chromeos/network_health/BUILD.gn
@@ -110,6 +110,7 @@ deps = [ ":network_diagnostics_mojo.m", ":network_diagnostics_types.m", + "//third_party/polymer/v3_0/components-chromium/iron-icon:iron-icon", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/js:i18n_behavior.m", ]
diff --git a/ui/webui/resources/cr_components/chromeos/network_health/routine_group.html b/ui/webui/resources/cr_components/chromeos/network_health/routine_group.html index 8a7fbac..bea3d48 100644 --- a/ui/webui/resources/cr_components/chromeos/network_health/routine_group.html +++ b/ui/webui/resources/cr_components/chromeos/network_health/routine_group.html
@@ -1,6 +1,8 @@ <link rel="import" href="../../../html/i18n_behavior.html"> <link rel="import" href="../../../html/polymer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="network_diagnostics_mojo.html"> <link rel="import" href="network_diagnostics_types.html"> @@ -54,6 +56,7 @@ </template> <img class="routine-icon" hidden="[[!showGroupIcon]]" src="[[getGroupIcon_(routines.*)]]"> + <iron-icon icon="[[getArrowIcon_(expanded)]]"></iron-icon> </div> <template is="dom-if" if="[[expanded]]"> <template is="dom-repeat" items="[[routines]]" as="routine"
diff --git a/ui/webui/resources/cr_components/chromeos/network_health/routine_group.js b/ui/webui/resources/cr_components/chromeos/network_health/routine_group.js index 13fafcb6..3e05e74 100644 --- a/ui/webui/resources/cr_components/chromeos/network_health/routine_group.js +++ b/ui/webui/resources/cr_components/chromeos/network_health/routine_group.js
@@ -61,6 +61,15 @@ }, /** + * Returns the correct arrow icon depending on if the routine group is + * expanded. + * @param {boolean} expanded + */ + getArrowIcon_(expanded) { + return expanded ? 'cr:expand-less' : 'cr:expand-more'; + }, + + /** * Helper function to get the icon for a group of routines based on all of * their results. * @param {!PolymerDeepPropertyChange} routines