diff --git a/DEPS b/DEPS index 1289889..a29d440 100644 --- a/DEPS +++ b/DEPS
@@ -280,15 +280,15 @@ # 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': 'b2e4416a6bfcec9f773d1ab25df1ef2ca7f23322', + 'skia_revision': '022cad13a17ab6186c74a7f2bc4c8ada1393a38a', # 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': 'd8914f7033295aa02fa72a73344e84edff87c70a', + 'v8_revision': 'e9a100d0e5eae77791468c1da1c0805dc5442401', # 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': 'da984303fda121cced56dfa07c6890d3b29dc502', + 'angle_revision': '86c735bfe65063bd5fc319809ea3ddb939d65319', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -359,7 +359,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': '8a1afd340d4cefeff093902107269a2483ed5a98', + 'devtools_frontend_revision': 'ce905398178adc4abec56263ae656cf78d0f57f3', # 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. @@ -395,7 +395,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': '0e414c57045668bf6343215a3fc7db6a5a76680b', + 'dawn_revision': 'bd512acad8c9d29e942ff5df0c13024458b09249', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -466,7 +466,7 @@ 'libcxx_revision': 'b1269813eaf5b8ac78e35e45a0f7cc320bd3e7d6', # GN CIPD package version. - 'gn_version': 'git_revision:ecaaf4b9e58a312a1610a37999eeccf58f73e264', + 'gn_version': 'git_revision:03ce92df5f9875bd9929b564be4b612713569aa9', } # Only these hosts are allowed for dependencies in this DEPS file. @@ -780,7 +780,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'fdb05bb379b73a67cea8269e5948b9197a037086', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'f12d519b49ee0aa11027d4640702095500e85250', 'condition': 'checkout_ios', }, @@ -850,7 +850,7 @@ 'packages': [ { 'package': 'chromium/rts/model/linux-amd64', - 'version': 'fnXM6ppirSOMYyWehMZBIfee9f58e4fkTLO0fsRijsIC', + 'version': '_4rp0d4G7gaKcibYjcd7MEGhB_e7VnFe5WJm20wUNusC', }, ], 'dep_type': 'cipd', @@ -861,7 +861,7 @@ 'packages': [ { 'package': 'chromium/rts/model/mac-amd64', - 'version': '098l-jyn-4UGFAQCZ6ocQPSC19o8uX2Yomle7J7kiskC', + 'version': 'XX3g-_Y8esGuqkFEpKpQbdTxBZTxn9a56fjNHm8iuEQC', }, ], 'dep_type': 'cipd', @@ -872,7 +872,7 @@ 'packages': [ { 'package': 'chromium/rts/model/windows-amd64', - 'version': '1njaCIAkuKvrJYbEiGqKK1RtMYAM3Nr_rReKhBTE2aAC', + 'version': 'PGS6ELwFQEAOgpdole1GdZq-ZNLkank5NIcEVNOpd8YC', }, ], 'dep_type': 'cipd', @@ -929,7 +929,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': '4gPri5A_WLHmRIG0GHdvmd3LeWiNvBj1i5IP7kEXAgsC', + 'version': 'LQ9vdgkVWAv1399Rmm15OrPsglaFUcAF8fkDjzH06o4C', }, ], 'condition': 'checkout_android', @@ -983,9 +983,19 @@ 'src/third_party/android_build_tools/lint': { 'packages': [ { - # TODO(wnwen): Switch to chromium/third_party/android_build_tools/lint. - 'package': 'chromium/third_party/android_lint', - 'version': 'f5g1G8eyExIUPHk4lH3xx_xV4pza9WSBaITgmLPgF2cC', + 'package': 'chromium/third_party/android_build_tools/lint', + 'version': 'OkpY7I7TtDs4jihQ9SmckN-GEVBpZ2y9xr4M7TimTqoC', + }, + ], + 'condition': 'checkout_android', + 'dep_type': 'cipd', + }, + + 'src/third_party/android_build_tools/manifest_merger': { + 'packages': [ + { + 'package': 'chromium/third_party/android_build_tools/manifest_merger', + 'version': '0WkAedh1tJB8lzisWJRT80UjpacKLltuV7NqP-0tx9gC', }, ], 'condition': 'checkout_android', @@ -1134,7 +1144,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '2f8c3e725fcce30f9076a337ae5ed256a252c5f2', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'bf3e1a272dd5aee57a9c1dad318498291ebe96ec', 'condition': 'checkout_chromeos', }, @@ -1554,7 +1564,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'dd682e48aa77446c4bec51af0f08421d1a2bac47', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '80dd4d929a592772a530e67c30d9f76bb63f5219', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1605,7 +1615,7 @@ 'packages': [ { 'package': 'chromium/third_party/r8', - 'version': 'iMLEt10uXASDfG2AlATR1fO8xYhBoF24nQvDDXLY6Q8C', + 'version': 'YYmB-DSqgEMUFtrSQw6plpnZygVruQmxrc3Qqeac8ZEC', }, ], 'condition': 'checkout_android', @@ -1685,7 +1695,7 @@ 'dep_type': 'cipd', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@8e318438088194b433410d57c62933eb1770d8f7', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@24ed8b7a6bd7120e29de06dcf7c791a0aee2531c', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1721,10 +1731,10 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'e58ed2132aa47ac110a4cce1763abfa34f4fa34e', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '6c0f3bab40dead9e205a95ef64ad8f912c694a1d', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '1f5f875f89f8af99653b8e5fae1007115747397e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '1c5808145e8b151800b0320b8a7316a09b706488', + Var('webrtc_git') + '/src.git' + '@' + 'f82e8fa911ab3547885f8070b9a951197967c94d', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1797,7 +1807,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@28b82e7e8f39aa2ea2202676cc4c20d62bb23766', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@96b1e592ed122b4c44eaa581d0a412f8a7968cba', 'condition': 'checkout_src_internal', }, @@ -1827,7 +1837,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/help_app/app', - 'version': 'y6WH5M1W1YJZjkVnqvoKiLYFlY0Dc8PC1m_n8Fv6a2MC', + 'version': 'WDzf_mw4eqqsVO64bN84HfCsDushxz0cYt-EtfMrqTMC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal', @@ -1838,7 +1848,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/media_app/app', - 'version': 'ddtGiyriWl2T7dVOXc5ftEX7wbO9I8iWSHgaEHOW7QAC', + 'version': 'DZeJ6sbYACiPjjPN8LkZlj6faYM5y7ABsHKICY-uik4C', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/ash/webui/camera_app_ui/resources/js/custom_toast.ts b/ash/webui/camera_app_ui/resources/js/custom_toast.ts index 7ea7042..1204ab7 100644 --- a/ash/webui/camera_app_ui/resources/js/custom_toast.ts +++ b/ash/webui/camera_app_ui/resources/js/custom_toast.ts
@@ -310,6 +310,7 @@ const timeout = setTimeout(hide, SHOWING_TIMEOUT_MS); showing = {ripple, toast, timeout}; + toast.show(); } /**
diff --git a/ash/webui/camera_app_ui/resources/js/new_feature_toast.ts b/ash/webui/camera_app_ui/resources/js/new_feature_toast.ts deleted file mode 100644 index 6a59372..0000000 --- a/ash/webui/camera_app_ui/resources/js/new_feature_toast.ts +++ /dev/null
@@ -1,228 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import * as animation from './animation.js'; -import {assertExists} from './assert.js'; -import * as dom from './dom.js'; -import {I18nString} from './i18n_string.js'; -import * as loadTimeData from './models/load_time_data.js'; -import * as util from './util.js'; - -/** - * Interval of emerge time between two consecutive ripples in milliseconds. - */ -const RIPPLE_INTERVAL_MS = 5000; - -/** - * Controller for showing ripple effect. - */ -class RippleEffect { - /** - * Initial width of ripple in px. - */ - private readonly width: number; - - /** - * Initial height of ripple in px. - */ - private readonly height: number; - - private readonly cancelHandle: number; - - /** - * @param el Element to show ripple effect on. - */ - constructor(private readonly el: HTMLElement) { - const style = this.el.computedStyleMap(); - - this.width = util.getStyleValueInPx(style, '--ripple-start-width'); - this.height = util.getStyleValueInPx(style, '--ripple-start-height'); - this.cancelHandle = setInterval(() => { - this.addRipple(); - }, RIPPLE_INTERVAL_MS); - - this.addRipple(); - } - - private async addRipple(): Promise<void> { - const rect = this.el.getBoundingClientRect(); - if (rect.width === 0) { - return; - } - const tpl = util.instantiateTemplate('#ripple-template'); - const ripple = dom.getFrom(tpl, '.ripple', HTMLDivElement); - const style = ripple.attributeStyleMap; - style.set('left', CSS.px(rect.left - (this.width - rect.width) / 2)); - style.set('top', CSS.px(rect.top - (this.height - rect.height) / 2)); - style.set('width', CSS.px(this.width)); - style.set('height', CSS.px(this.height)); - document.body.appendChild(tpl); - await animation.play(ripple); - document.body.removeChild(ripple); - } - - /** - * Stops ripple effect. - */ - stop(): void { - clearInterval(this.cancelHandle); - } -} - -/** - * Interval for toast updaing position. - */ -const TOAST_POSITION_UPDATE_MS = 500; - -enum PositionProperty { - BOTTOM = 'bottom', - LEFT = 'left', - RIGHT = 'right', - TOP = 'top', -} - -/** - * Controller for showing new feature toast. - */ -class Toast { - private readonly offsetProperties: Array<{ - elProperty: PositionProperty, - toastProperty: PositionProperty, - offset: number, - }>; - - private readonly toast: HTMLDivElement; - - private readonly cancelHandle: number; - - constructor(private readonly el: HTMLElement) { - /** - * Offset between the position property of toast and the target |el| to - * determine their relative position. - */ - this.offsetProperties = (() => { - const properties = []; - const style = this.el.computedStyleMap(); - - function getPositionProperty(key: string) { - const property = assertExists(style.get(key)).toString(); - return util.assertEnumVariant(PositionProperty, property); - } - - for (const dir of ['x', 'y']) { - const toastProperty = getPositionProperty(`--toast-ref-${dir}`); - const elProperty = getPositionProperty(`--toast-element-ref-${dir}`); - const offset = util.getStyleValueInPx(style, `--toast-offset-${dir}`); - properties.push({elProperty, toastProperty, offset}); - } - return properties; - })(); - - const tpl = util.instantiateTemplate('#new-feature-toast-template'); - this.toast = dom.getFrom(tpl, '#new-feature-toast', HTMLDivElement); - - this.cancelHandle = setInterval(() => { - this.updatePosition(); - }, TOAST_POSITION_UPDATE_MS); - - // Set up i18n texts. - const i18nId = - util.assertEnumVariant(I18nString, el.getAttribute('i18n-new-feature')); - const textEl = dom.getFrom(tpl, '.new-feature-toast-text', HTMLSpanElement); - const text = loadTimeData.getI18nMessage(i18nId); - textEl.textContent = text; - const ariaLabel = - loadTimeData.getI18nMessage(I18nString.NEW_CONTROL_NAVIGATION, text); - this.toast.setAttribute('aria-label', ariaLabel); - - document.body.appendChild(tpl); - this.updatePosition(); - } - - private updatePosition() { - const rect = this.el.getBoundingClientRect(); - const style = this.toast.attributeStyleMap; - if (rect.width === 0) { - style.set('display', 'none'); - return; - } - style.clear(); - for (const {elProperty, toastProperty, offset} of this.offsetProperties) { - let value = rect[elProperty] + offset; - if (toastProperty === PositionProperty.RIGHT) { - value = window.innerWidth - value; - } else if (toastProperty === PositionProperty.BOTTOM) { - value = window.innerHeight - value; - } - style.set(toastProperty, CSS.px(value)); - } - } - - focus(): void { - this.el.setAttribute('aria-owns', 'new-feature-toast'); - this.toast.focus(); - } - - hide(): void { - this.el.removeAttribute('aria-owns'); - clearInterval(this.cancelHandle); - document.body.removeChild(this.toast); - } -} - -let showing: { - ripple: RippleEffect, - toast: Toast, - timeout: number, -}|null = null; - -/** - * Hides the new feature toast. - */ -export function hide(): void { - if (showing === null) { - return; - } - const {ripple, toast, timeout} = showing; - showing = null; - ripple.stop(); - toast.hide(); - clearTimeout(timeout); -} - -/** - * Timeout for showing new feature toast. - */ -const SHOWING_TIMEOUT_MS = 10000; - -/** - * Shows the toast on the given element. - */ -export function show(el: HTMLElement): void { - if (showing !== null) { - hide(); - } - - const ripple = new RippleEffect(el); - const toast = new Toast(el); - const timeout = setTimeout(hide, SHOWING_TIMEOUT_MS); - showing = {ripple, toast, timeout}; -} - -/** - * @return If new feature toast is showing. - */ -export function isShowing(): boolean { - return showing !== null; -} - -/** - * Focuses to new feature toast. - */ -export function focus(): void { - if (showing === null) { - return; - } - showing.toast.focus(); -}
diff --git a/ash/webui/file_manager/file_manager_ui.cc b/ash/webui/file_manager/file_manager_ui.cc index d39e0ce..d20f1a7 100644 --- a/ash/webui/file_manager/file_manager_ui.cc +++ b/ash/webui/file_manager/file_manager_ui.cc
@@ -10,7 +10,9 @@ #include "ash/webui/file_manager/resources/grit/file_manager_swa_resources_map.h" #include "ash/webui/file_manager/url_constants.h" #include "base/check_op.h" +#include "base/logging.h" #include "base/strings/string_util.h" +#include "base/values.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -28,19 +30,26 @@ std::unique_ptr<FileManagerUIDelegate> delegate) : MojoWebDialogUI(web_ui), delegate_(std::move(delegate)) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto* browser_context = web_ui->GetWebContents()->GetBrowserContext(); - auto* trusted_source = CreateTrustedAppDataSource(); - content::WebUIDataSource::Add(browser_context, trusted_source); + // Count the number of active windows. This is done so that we can tell if + // there are any active Files SWA windows. + ++instance_count_; + DCHECK_GT(instance_count_, 0); + DLOG(WARNING) << "Starting FileManagerUI. Open windows: " << instance_count_; + + // Increment the counter each time a window is opened. This is to give a + // unique ID to each window. + ++window_counter_; + + auto* browser_context = web_ui->GetWebContents()->GetBrowserContext(); + auto* trusted_source = CreateTrustedAppDataSource(window_counter_); + content::WebUIDataSource::Add(browser_context, trusted_source); // Add ability to request chrome-untrusted: URLs web_ui->AddRequestableScheme(content::kChromeUIUntrustedScheme); - - ++num_instances_; - DCHECK_GT(num_instances_, 0); - LOG(WARNING) << "Starting FileManagerUI. Open windows: " << num_instances_; } -content::WebUIDataSource* FileManagerUI::CreateTrustedAppDataSource() { +content::WebUIDataSource* FileManagerUI::CreateTrustedAppDataSource( + int window_number) { content::WebUIDataSource* source = content::WebUIDataSource::Create(kChromeUIFileManagerHost); @@ -58,7 +67,9 @@ // Load time data: add files app strings and feature flags. source->EnableReplaceI18nInJS(); - delegate_->PopulateLoadTimeData(source); + base::Value::Dict dict = delegate_->GetLoadTimeData(); + dict.Set("WINDOW_NUMBER", window_number); + source->AddLocalizedStrings(dict); source->UseStringsJs(); // Script security policy. @@ -86,16 +97,16 @@ int FileManagerUI::GetNumInstances() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - return num_instances_; + return instance_count_; } FileManagerUI::~FileManagerUI() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK_GT(num_instances_, 0); - --num_instances_; + DCHECK_GT(instance_count_, 0); + --instance_count_; - LOG(WARNING) << "Stopping FileManagerUI. Open windows: " << num_instances_; + DLOG(WARNING) << "Stopping FileManagerUI. Open windows: " << instance_count_; } void FileManagerUI::BindInterface(
diff --git a/ash/webui/file_manager/file_manager_ui.h b/ash/webui/file_manager/file_manager_ui.h index 2bcf498..f69b276 100644 --- a/ash/webui/file_manager/file_manager_ui.h +++ b/ash/webui/file_manager/file_manager_ui.h
@@ -42,7 +42,7 @@ static int GetNumInstances(); private: - content::WebUIDataSource* CreateTrustedAppDataSource(); + content::WebUIDataSource* CreateTrustedAppDataSource(int window_number); // mojom::PageHandlerFactory: void CreatePageHandler( @@ -54,7 +54,13 @@ mojo::Receiver<mojom::PageHandlerFactory> page_factory_receiver_{this}; std::unique_ptr<FileManagerPageHandler> page_handler_; - static inline int num_instances_ = 0; + // Counts the number of active Files SWA instances. This counter goes up every + // time a new window is opened and down every time a window is closed. + static inline int instance_count_ = 0; + + // Counts the total number of windows opened. Unlike the instance_count_ this + // counter never is decremented. + static inline int window_counter_ = 0; WEB_UI_CONTROLLER_TYPE_DECL(); };
diff --git a/ash/webui/file_manager/file_manager_ui_delegate.h b/ash/webui/file_manager/file_manager_ui_delegate.h index bf56613..40ebb01 100644 --- a/ash/webui/file_manager/file_manager_ui_delegate.h +++ b/ash/webui/file_manager/file_manager_ui_delegate.h
@@ -5,9 +5,7 @@ #ifndef ASH_WEBUI_FILE_MANAGER_FILE_MANAGER_UI_DELEGATE_H_ #define ASH_WEBUI_FILE_MANAGER_FILE_MANAGER_UI_DELEGATE_H_ -namespace content { -class WebUIDataSource; -} // namespace content +#include "base/values.h" namespace ash { @@ -17,7 +15,7 @@ virtual ~FileManagerUIDelegate() = default; // Populates (writes) load time data to the source. - virtual void PopulateLoadTimeData(content::WebUIDataSource*) const = 0; + virtual base::Value::Dict GetLoadTimeData() const = 0; }; } // namespace ash
diff --git a/ash/webui/file_manager/resources/BUILD.gn b/ash/webui/file_manager/resources/BUILD.gn index 4d7eeea..f2b1b8a 100644 --- a/ash/webui/file_manager/resources/BUILD.gn +++ b/ash/webui/file_manager/resources/BUILD.gn
@@ -108,7 +108,7 @@ } optimize_webui("build") { - host = "file_manager" + host = "file-manager" input = rebase_path(preprocess_folder, root_build_dir) js_module_in_files = [
diff --git a/ash/webui/file_manager/resources/main.js b/ash/webui/file_manager/resources/main.js index c20cce9..9015c80 100644 --- a/ash/webui/file_manager/resources/main.js +++ b/ash/webui/file_manager/resources/main.js
@@ -4,12 +4,12 @@ // init_globals.js must be the first loaded module. import './init_globals.js'; +import './strings.m.js'; import 'chrome://file-manager/background/js/metrics_start.js'; import './test_util_swa.js'; import {background} from 'chrome://file-manager/background/js/background.js'; import {VolumeManagerImpl} from 'chrome://file-manager/background/js/volume_manager_impl.js'; -import {promisify} from 'chrome://file-manager/common/js/api.js'; import {GlitchType, reportGlitch} from 'chrome://file-manager/common/js/glitch.js'; import {ScriptLoader} from './script_loader.js'; @@ -21,8 +21,7 @@ class FileManagerApp { async run() { try { - const win = await promisify(chrome.windows.getCurrent); - window.appID = win.id; + window.appID = loadTimeData.getInteger('WINDOW_NUMBER'); } catch (e) { reportGlitch(GlitchType.CAUGHT_EXCEPTION); console.warn('Failed to get the app ID', e);
diff --git a/base/BUILD.gn b/base/BUILD.gn index 6c02515..006315e 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1694,6 +1694,8 @@ "android/task_scheduler/post_task_android.h", "android/task_scheduler/task_runner_android.cc", "android/task_scheduler/task_runner_android.h", + "android/thread_instruction_count.cc", + "android/thread_instruction_count.h", "android/timezone_utils.cc", "android/timezone_utils.h", "android/trace_event_binding.cc",
diff --git a/base/android/java/src/org/chromium/base/FeatureList.java b/base/android/java/src/org/chromium/base/FeatureList.java index 9039f07..c085ec6 100644 --- a/base/android/java/src/org/chromium/base/FeatureList.java +++ b/base/android/java/src/org/chromium/base/FeatureList.java
@@ -151,6 +151,14 @@ } /** + * @param featureName The name of the feature to query. + * @return Whether the feature has a test value configured. + */ + public static boolean hasTestFeature(String featureName) { + return hasTestFeatures() && sTestFeatures.mFeatureFlags.containsKey(featureName); + } + + /** * Returns the test value of the feature with the given name. * * @param featureName The name of the feature to query. @@ -191,8 +199,9 @@ return null; } + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) @NativeMethods - interface Natives { + public interface Natives { boolean isInitialized(); } }
diff --git a/base/android/thread_instruction_count.cc b/base/android/thread_instruction_count.cc new file mode 100644 index 0000000..9d3c32e87 --- /dev/null +++ b/base/android/thread_instruction_count.cc
@@ -0,0 +1,87 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/android/thread_instruction_count.h" + +#include "base/check_op.h" +#include "base/logging.h" +#include "base/no_destructor.h" +#include "base/threading/thread_local_storage.h" + +#include <linux/perf_event.h> +#include <sys/syscall.h> +#include <unistd.h> + +namespace base { +namespace android { + +namespace { + +constexpr int kPerfFdOpenFailed = -1; + +ThreadLocalStorage::Slot& InstructionCounterFdSlot() { + static NoDestructor<ThreadLocalStorage::Slot> fd_slot([](void* fd_ptr) { + int fd = reinterpret_cast<intptr_t>(fd_ptr); + if (fd > 0) + close(fd); + }); + return *fd_slot; +} + +// Opens a new file descriptor that emits the value of +// PERF_COUNT_HW_INSTRUCTIONS in userspace (excluding kernel and hypervisor +// instructions) for the given |thread_id|, or 0 for the calling thread. +// +// Returns kPerfFdOpenFailed if opening the file descriptor failed. +int OpenInstructionCounterFdForThread(int thread_id) { + struct perf_event_attr pe = {0}; + pe.type = PERF_TYPE_HARDWARE; + pe.size = sizeof(struct perf_event_attr); + pe.config = PERF_COUNT_HW_INSTRUCTIONS; + pe.exclude_kernel = 1; + pe.exclude_hv = 1; + + int fd = syscall(__NR_perf_event_open, &pe, thread_id, /* cpu */ -1, + /* group_fd */ -1, /* flags */ 0); + if (fd < 0) { + PLOG(ERROR) << "perf_event_open: omitting instruction counters"; + return kPerfFdOpenFailed; + } + return fd; +} + +// Retrieves the active perf counter FD for the current thread, performing +// lazy-initialization if necessary. +int InstructionCounterFdForCurrentThread() { + auto& slot = InstructionCounterFdSlot(); + int fd = reinterpret_cast<intptr_t>(slot.Get()); + if (fd == 0) { + fd = OpenInstructionCounterFdForThread(0); + slot.Set(reinterpret_cast<void*>(fd)); + } + return fd; +} + +} // namespace + +bool ThreadInstructionCount::IsSupported() { + return InstructionCounterFdForCurrentThread() > 0; +} + +ThreadInstructionCount ThreadInstructionCount::Now() { + DCHECK(IsSupported()); + int fd = InstructionCounterFdForCurrentThread(); + if (fd <= 0) + return ThreadInstructionCount(); + + uint64_t instructions = 0; + ssize_t bytes_read = read(fd, &instructions, sizeof(instructions)); + CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(instructions))) + << "Short reads of small size from kernel memory is not expected. If " + "this fails, use HANDLE_EINTR."; + return ThreadInstructionCount(instructions); +} + +} // namespace android +} // namespace base
diff --git a/base/android/thread_instruction_count.h b/base/android/thread_instruction_count.h new file mode 100644 index 0000000..845d7bd2 --- /dev/null +++ b/base/android/thread_instruction_count.h
@@ -0,0 +1,63 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_ +#define BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_ + +#include <stdint.h> + +#include "base/base_export.h" + +namespace base { +namespace android { + +// Represents the number of instructions that were retired between two samples +// of a thread's performance counters. +class BASE_EXPORT ThreadInstructionDelta { + public: + constexpr ThreadInstructionDelta() : delta_(0) {} + explicit constexpr ThreadInstructionDelta(int64_t delta) : delta_(delta) {} + + constexpr int64_t ToInternalValue() const { return delta_; } + + private: + int64_t delta_; +}; + +// Helper class for reading the current count of instructions retired for the +// current thread via ThreadInstructionCount::Now(). Does *not* count +// instructions retired while running in the kernel. +// +// Limitations: +// * Crashes when used in sandboxed process +// * Works on a userdebug build of Android 12, kernel 4.19. May require extra +// effort to allow on later Android releases and kernel versions. +class BASE_EXPORT ThreadInstructionCount { + public: + // Returns true if the platform supports hardware retired instruction + // counters. May crash in sandboxed processes. + static bool IsSupported(); + + // Returns the number of retired instructions relative to some epoch count, + // or -1 if getting the current instruction count failed / is disabled. + static ThreadInstructionCount Now(); + + constexpr ThreadInstructionCount() : value_(-1) {} + explicit constexpr ThreadInstructionCount(int64_t value) : value_(value) {} + + constexpr ThreadInstructionDelta operator-( + ThreadInstructionCount other) const { + return ThreadInstructionDelta(value_ - other.value_); + } + + constexpr int64_t ToInternalValue() const { return value_; } + + private: + int64_t value_; +}; + +} // namespace android +} // namespace base + +#endif // BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_
diff --git a/base/task/thread_pool/pooled_parallel_task_runner.cc b/base/task/thread_pool/pooled_parallel_task_runner.cc index 00f84bb..4560077 100644 --- a/base/task/thread_pool/pooled_parallel_task_runner.cc +++ b/base/task/thread_pool/pooled_parallel_task_runner.cc
@@ -30,22 +30,10 @@ scoped_refptr<Sequence> sequence = MakeRefCounted<Sequence>( traits_, this, TaskSourceExecutionMode::kParallel); - { - CheckedAutoLock auto_lock(lock_); - sequences_.insert(sequence.get()); - } - return pooled_task_runner_delegate_->PostTaskWithSequence( Task(from_here, std::move(closure), TimeTicks::Now(), delay), std::move(sequence)); } -void PooledParallelTaskRunner::UnregisterSequence(Sequence* sequence) { - DCHECK(sequence); - - CheckedAutoLock auto_lock(lock_); - sequences_.erase(sequence); -} - } // namespace internal } // namespace base
diff --git a/base/task/thread_pool/pooled_parallel_task_runner.h b/base/task/thread_pool/pooled_parallel_task_runner.h index 340ddcf4..c03397c 100644 --- a/base/task/thread_pool/pooled_parallel_task_runner.h +++ b/base/task/thread_pool/pooled_parallel_task_runner.h
@@ -7,19 +7,15 @@ #include "base/base_export.h" #include "base/callback_forward.h" -#include "base/containers/flat_set.h" #include "base/location.h" #include "base/memory/raw_ptr.h" -#include "base/task/common/checked_lock.h" #include "base/task/task_runner.h" #include "base/task/task_traits.h" -#include "base/thread_annotations.h" #include "base/time/time.h" namespace base { namespace internal { -class Sequence; class PooledTaskRunnerDelegate; // A task runner that runs tasks in parallel. @@ -37,21 +33,13 @@ OnceClosure closure, TimeDelta delay) override; - // Removes |sequence| from |sequences_|. - void UnregisterSequence(Sequence* sequence); - private: ~PooledParallelTaskRunner() override; const TaskTraits traits_; - const raw_ptr<PooledTaskRunnerDelegate> pooled_task_runner_delegate_; - - CheckedLock lock_; - - // List of alive Sequences instantiated by this PooledParallelTaskRunner. - // Sequences are added when they are instantiated, and removed when they are - // destroyed. - base::flat_set<Sequence*> sequences_ GUARDED_BY(lock_); + // TODO(crbug.com/1298696): Breaks storage_unittests. + const raw_ptr<PooledTaskRunnerDelegate, DegradeToNoOpWhenMTE> + pooled_task_runner_delegate_; }; } // namespace internal
diff --git a/base/task/thread_pool/pooled_sequenced_task_runner.h b/base/task/thread_pool/pooled_sequenced_task_runner.h index da19a502..74a2e2fc 100644 --- a/base/task/thread_pool/pooled_sequenced_task_runner.h +++ b/base/task/thread_pool/pooled_sequenced_task_runner.h
@@ -56,7 +56,9 @@ private: ~PooledSequencedTaskRunner() override; - const raw_ptr<PooledTaskRunnerDelegate> pooled_task_runner_delegate_; + // TODO(crbug.com/1298696): Breaks base_unittests. + const raw_ptr<PooledTaskRunnerDelegate, DegradeToNoOpWhenMTE> + pooled_task_runner_delegate_; // Sequence for all Tasks posted through this TaskRunner. const scoped_refptr<Sequence> sequence_;
diff --git a/base/task/thread_pool/sequence.cc b/base/task/thread_pool/sequence.cc index ffde049f..052e441 100644 --- a/base/task/thread_pool/sequence.cc +++ b/base/task/thread_pool/sequence.cc
@@ -133,10 +133,6 @@ void Sequence::ReleaseTaskRunner() { if (!task_runner()) return; - if (execution_mode() == TaskSourceExecutionMode::kParallel) { - static_cast<PooledParallelTaskRunner*>(task_runner()) - ->UnregisterSequence(this); - } // No member access after this point, releasing |task_runner()| might delete // |this|. task_runner()->Release();
diff --git a/base/trace_event/memory_infra_background_allowlist.cc b/base/trace_event/memory_infra_background_allowlist.cc index 07d7ed0a..eef5525 100644 --- a/base/trace_event/memory_infra_background_allowlist.cc +++ b/base/trace_event/memory_infra_background_allowlist.cc
@@ -76,7 +76,6 @@ "WebMediaPlayer_MediaThread", "SyncDirectory", "TabRestoreServiceHelper", - "VizProcessContextProvider", nullptr // End of list marker. };
diff --git a/build/android/gyp/merge_manifest.py b/build/android/gyp/merge_manifest.py index 015fa895..f5126c2e 100755 --- a/build/android/gyp/merge_manifest.py +++ b/build/android/gyp/merge_manifest.py
@@ -17,18 +17,6 @@ from util import manifest_utils _MANIFEST_MERGER_MAIN_CLASS = 'com.android.manifmerger.Merger' -_MANIFEST_MERGER_JARS = [ - os.path.join('build-system', 'manifest-merger.jar'), - os.path.join('common', 'common.jar'), - os.path.join('sdk-common', 'sdk-common.jar'), - os.path.join('sdklib', 'sdklib.jar'), - os.path.join('external', 'com', 'google', 'guava', 'guava', '30.1-jre', - 'guava-30.1-jre.jar'), - os.path.join('external', 'kotlin-plugin-ij', 'Kotlin', 'kotlinc', 'lib', - 'kotlin-stdlib.jar'), - os.path.join('external', 'com', 'google', 'code', 'gson', 'gson', '2.8.6', - 'gson-2.8.6.jar'), -] @contextlib.contextmanager @@ -67,21 +55,13 @@ yield patched_manifest.name -def _BuildManifestMergerClasspath(android_sdk_cmdline_tools): - return ':'.join([ - os.path.join(android_sdk_cmdline_tools, 'lib', jar) - for jar in _MANIFEST_MERGER_JARS - ]) - - def main(argv): argv = build_utils.ExpandFileArgs(argv) parser = argparse.ArgumentParser(description=__doc__) build_utils.AddDepfileOption(parser) - parser.add_argument( - '--android-sdk-cmdline-tools', - help='Path to SDK\'s cmdline-tools folder.', - required=True) + parser.add_argument('--manifest-merger-jar', + help='Path to SDK\'s manifest merger jar.', + required=True) parser.add_argument('--root-manifest', help='Root manifest which to merge into', required=True) @@ -106,12 +86,10 @@ help='Treat all warnings as errors.') args = parser.parse_args(argv) - classpath = _BuildManifestMergerClasspath(args.android_sdk_cmdline_tools) - with build_utils.AtomicOutput(args.output) as output: cmd = build_utils.JavaCmd(args.warnings_as_errors) + [ '-cp', - classpath, + args.manifest_merger_jar, _MANIFEST_MERGER_MAIN_CLASS, '--out', output.name, @@ -162,8 +140,7 @@ manifest_utils.AssertPackage(manifest, package) if args.depfile: - inputs = extras + classpath.split(':') - build_utils.WriteDepfile(args.depfile, args.output, inputs=inputs) + build_utils.WriteDepfile(args.depfile, args.output, inputs=extras) if __name__ == '__main__':
diff --git a/build/android/test_runner.py b/build/android/test_runner.py index ed7c295..8245ef72 100755 --- a/build/android/test_runner.py +++ b/build/android/test_runner.py
@@ -1158,8 +1158,7 @@ test_filter_file = os.path.join(os.path.relpath(constants.GetOutDirectory()), _RERUN_FAILED_TESTS_FILE) - arg_list = shlex.split( - wrapper_arg_str.strip('\'')) if wrapper_arg_str else sys.argv + arg_list = shlex.split(wrapper_arg_str) if wrapper_arg_str else sys.argv index = 0 while index < len(arg_list): arg = arg_list[index]
diff --git a/build/config/android/BUILD.gn b/build/config/android/BUILD.gn index 69341ce..90d70cf 100644 --- a/build/config/android/BUILD.gn +++ b/build/config/android/BUILD.gn
@@ -129,6 +129,21 @@ ldflags = [ "-Wl,--pack-dyn-relocs=android" ] } +config("lld_branch_target_hardening") { + # Config opts a shared library into BTI linker hardening. This + # is an opt-in config (rather than default-enabled) to avoid + # interfering with the V8 CFI bots (crbug.com/1334614). + if (current_cpu == "arm64") { + if (arm_control_flow_integrity == "standard") { + # Linking objects without GNU_PROPERTY_AARCH64_FEATURE_1_BTI + # in their .gnu.note section implicitly results in the final + # binary losing Branch Target Identification (BTI) support. + # Issue a warning if this happens. + ldflags = [ "-Wl,-z,force-bti" ] + } + } +} + # Used for instrumented build to generate the orderfile. config("default_orderfile_instrumentation") { if (use_order_profiling) {
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 7d1c897..59e101a6 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -93,6 +93,8 @@ "//third_party/robolectric/lib/android-all-12-robolectric-7732740.jar" _lint_jar_path = "//third_party/android_build_tools/lint/lint.jar" _custom_lint_jar_path = "//third_party/android_build_tools/lint/custom_lint.jar" +_manifest_merger_jar_path = + "//third_party/android_build_tools/manifest_merger/manifest-merger.jar" # Put the bug number in the target name so that false-positives have a hint in # the error message about why non-existent dependencies are there. @@ -1932,6 +1934,7 @@ inputs = [ invoker.build_config, invoker.input_manifest, + _manifest_merger_jar_path, ] outputs = [ invoker.output_manifest ] @@ -1940,9 +1943,8 @@ args = [ "--depfile", rebase_path(depfile, root_build_dir), - "--android-sdk-cmdline-tools", - rebase_path("${public_android_sdk_root}/cmdline-tools/latest", - root_build_dir), + "--manifest-merger-jar", + rebase_path(_manifest_merger_jar_path, root_build_dir), "--root-manifest", rebase_path(invoker.input_manifest, root_build_dir), "--output",
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index d142c527..e14c3cc2 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -8.20220701.3.1 +8.20220704.3.1
diff --git a/build/util/generate_wrapper.py b/build/util/generate_wrapper.py index cbdcd6b..2d1df6b 100755 --- a/build/util/generate_wrapper.py +++ b/build/util/generate_wrapper.py
@@ -106,12 +106,9 @@ return outdir, remaining_args def InsertWrapperScriptArgs(args): - i = 0 - while i < len(args): - if args[i] == '--wrapper-script-args': - args.insert(i + 1, "'%s'" % shlex.join(s for s in sys.argv)) - break - i += 1 + if '--wrapper-script-args' in args: + idx = args.index('--wrapper-script-args') + args.insert(idx + 1, shlex.join(sys.argv)) def FilterIsolatedOutdirBasedArgs(outdir, args): rargs = []
diff --git a/cc/paint/oop_pixeltest.cc b/cc/paint/oop_pixeltest.cc index dc214fd..adc2e71 100644 --- a/cc/paint/oop_pixeltest.cc +++ b/cc/paint/oop_pixeltest.cc
@@ -200,7 +200,8 @@ auto* raster_implementation = raster_context_provider_->RasterInterface(); auto* sii = raster_context_provider_->SharedImageInterface(); uint32_t flags = gpu::SHARED_IMAGE_USAGE_RASTER | - gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION; + gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION | + gpu::SHARED_IMAGE_USAGE_GLES2; gpu::Mailbox mailbox = sii->CreateSharedImage( viz::ResourceFormat::RGBA_8888, gfx::Size(width, height), options.target_color_params.color_space, kTopLeft_GrSurfaceOrigin, @@ -313,7 +314,8 @@ const RasterOptions& options, viz::ResourceFormat image_format) { uint32_t flags = gpu::SHARED_IMAGE_USAGE_RASTER | - gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION; + gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION | + gpu::SHARED_IMAGE_USAGE_GLES2; gpu::Mailbox mailbox = sii->CreateSharedImage( image_format, options.resource_size, options.target_color_params.color_space, kTopLeft_GrSurfaceOrigin,
diff --git a/cc/paint/paint_filter.h b/cc/paint/paint_filter.h index 93a456d..8a82611 100644 --- a/cc/paint/paint_filter.h +++ b/cc/paint/paint_filter.h
@@ -20,7 +20,6 @@ #include "third_party/skia/include/effects/SkImageFilters.h" namespace viz { -class GLRenderer; class SkiaRenderer; class SoftwareRenderer; } // namespace viz @@ -146,7 +145,6 @@ // For cached skia filter access in SkPaint conversions. Mostly used during // raster. friend class PaintFlags; - friend class viz::GLRenderer; friend class viz::SkiaRenderer; friend class viz::SoftwareRenderer;
diff --git a/cc/test/layer_tree_test.cc b/cc/test/layer_tree_test.cc index 4a0c6d43..41b417a 100644 --- a/cc/test/layer_tree_test.cc +++ b/cc/test/layer_tree_test.cc
@@ -417,7 +417,10 @@ } void OnDeferMainFrameUpdatesChanged(bool) override {} - void OnDeferCommitsChanged(bool, PaintHoldingReason) override {} + void OnDeferCommitsChanged( + bool, + PaintHoldingReason, + absl::optional<PaintHoldingCommitTrigger>) override {} void RecordStartOfFrameMetrics() override {} void RecordEndOfFrameMetrics(base::TimeTicks,
diff --git a/cc/test/stub_layer_tree_host_client.h b/cc/test/stub_layer_tree_host_client.h index a5df8c35..8f2950028 100644 --- a/cc/test/stub_layer_tree_host_client.h +++ b/cc/test/stub_layer_tree_host_client.h
@@ -27,7 +27,10 @@ void DidUpdateLayers() override {} void BeginMainFrame(const viz::BeginFrameArgs& args) override {} void OnDeferMainFrameUpdatesChanged(bool) override {} - void OnDeferCommitsChanged(bool, PaintHoldingReason) override {} + void OnDeferCommitsChanged( + bool, + PaintHoldingReason, + absl::optional<PaintHoldingCommitTrigger>) override {} void RecordStartOfFrameMetrics() override {} void RecordEndOfFrameMetrics(base::TimeTicks, ActiveFrameSequenceTrackers) override {}
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index 4512d68..901185e 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -650,10 +650,12 @@ return proxy_->IsDeferringCommits(); } -void LayerTreeHost::OnDeferCommitsChanged(bool defer_status, - PaintHoldingReason reason) { +void LayerTreeHost::OnDeferCommitsChanged( + bool defer_status, + PaintHoldingReason reason, + absl::optional<PaintHoldingCommitTrigger> trigger) { DCHECK(IsMainThread()); - client_->OnDeferCommitsChanged(defer_status, reason); + client_->OnDeferCommitsChanged(defer_status, reason, trigger); } DISABLE_CFI_PERF
diff --git a/cc/trees/layer_tree_host.h b/cc/trees/layer_tree_host.h index 49bba472..1a42b84 100644 --- a/cc/trees/layer_tree_host.h +++ b/cc/trees/layer_tree_host.h
@@ -317,7 +317,9 @@ bool IsDeferringCommits() const; // Notification that the proxy started or stopped deferring commits. - void OnDeferCommitsChanged(bool defer_status, PaintHoldingReason reason); + void OnDeferCommitsChanged(bool defer_status, + PaintHoldingReason reason, + absl::optional<PaintHoldingCommitTrigger> trigger); // Returns whether there are any outstanding ScopedDeferMainFrameUpdate, // though commits may be deferred also when the local_surface_id_from_parent()
diff --git a/cc/trees/layer_tree_host_client.h b/cc/trees/layer_tree_host_client.h index f52db87..63415aa 100644 --- a/cc/trees/layer_tree_host_client.h +++ b/cc/trees/layer_tree_host_client.h
@@ -13,6 +13,7 @@ #include "cc/input/browser_controls_state.h" #include "cc/metrics/event_latency_tracker.h" #include "cc/metrics/frame_sequence_tracker_collection.h" +#include "cc/trees/paint_holding_commit_trigger.h" #include "cc/trees/paint_holding_reason.h" #include "cc/trees/property_tree.h" #include "ui/gfx/geometry/vector2d_f.h" @@ -125,9 +126,13 @@ virtual void OnDeferMainFrameUpdatesChanged(bool) = 0; // Notification that the proxy started or stopped deferring commits. |reason| - // indicates why commits are/were deferred. - virtual void OnDeferCommitsChanged(bool defer_status, - PaintHoldingReason reason) = 0; + // indicates why commits are/were deferred. |trigger| indicates why the commit + // restarted. |trigger| is always provided on restarts, when |defer_status| + // switches to false. + virtual void OnDeferCommitsChanged( + bool defer_status, + PaintHoldingReason reason, + absl::optional<PaintHoldingCommitTrigger> trigger) = 0; // Visual frame-based updates to the state of the LayerTreeHost are expected // to happen only in calls to LayerTreeHostClient::UpdateLayerTreeHost, which
diff --git a/cc/trees/proxy_main.cc b/cc/trees/proxy_main.cc index 4bd11516..e6419e53 100644 --- a/cc/trees/proxy_main.cc +++ b/cc/trees/proxy_main.cc
@@ -606,7 +606,7 @@ commits_restart_time_ = base::TimeTicks::Now() + timeout; // Notify dependent systems that the deferral status has changed. - layer_tree_host_->OnDeferCommitsChanged(true, reason); + layer_tree_host_->OnDeferCommitsChanged(true, reason, absl::nullopt); return true; } @@ -621,7 +621,7 @@ TRACE_ID_LOCAL(this)); // Notify depended systems that the deferral status has changed. - layer_tree_host_->OnDeferCommitsChanged(false, reason); + layer_tree_host_->OnDeferCommitsChanged(false, reason, trigger); } bool ProxyMain::IsDeferringCommits() const {
diff --git a/cc/trees/single_thread_proxy.cc b/cc/trees/single_thread_proxy.cc index 0066ee6..06caf94 100644 --- a/cc/trees/single_thread_proxy.cc +++ b/cc/trees/single_thread_proxy.cc
@@ -366,7 +366,7 @@ commits_restart_time_ = base::TimeTicks::Now() + timeout; // Notify dependent systems that the deferral status has changed. - layer_tree_host_->OnDeferCommitsChanged(true, reason); + layer_tree_host_->OnDeferCommitsChanged(true, reason, absl::nullopt); return true; } @@ -383,7 +383,7 @@ TRACE_ID_LOCAL(this)); // Notify dependent systems that the deferral status has changed. - layer_tree_host_->OnDeferCommitsChanged(false, reason); + layer_tree_host_->OnDeferCommitsChanged(false, reason, trigger); } bool SingleThreadProxy::IsDeferringCommits() const {
diff --git a/chrome/VERSION b/chrome/VERSION index 522efe0..fd3a29a0 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=105 MINOR=0 -BUILD=5160 +BUILD=5162 PATCH=0
diff --git a/chrome/android/chrome_common_shared_library.gni b/chrome/android/chrome_common_shared_library.gni index af086592..995c9469 100644 --- a/chrome/android/chrome_common_shared_library.gni +++ b/chrome/android/chrome_common_shared_library.gni
@@ -81,6 +81,9 @@ deps += [ "//chrome:chrome_android_core" ] } + # Warn if linking code which could implicitly disable BTI on Arm systems + configs += [ "//build/config/android:lld_branch_target_hardening" ] + if (!(defined(invoker.testonly) && invoker.testonly)) { configs -= [ "//build/config/compiler:thinlto_optimize_default" ] configs += [ "//build/config/compiler:thinlto_optimize_max" ]
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTriggerScriptIntegrationTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTriggerScriptIntegrationTest.java index 09d9bf41..9b3fb51 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTriggerScriptIntegrationTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTriggerScriptIntegrationTest.java
@@ -31,7 +31,6 @@ import static org.chromium.chrome.browser.autofill_assistant.ProtoTestUtil.toCssSelector; import android.os.Build.VERSION_CODES; -import android.util.Base64; import androidx.test.espresso.Espresso; import androidx.test.filters.MediumTest; @@ -351,36 +350,6 @@ @Test @MediumTest @EnableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME) - public void base64TriggerScriptsDontRequireMSBB() { - TestThreadUtils.runOnUiThreadBlocking( - () - -> UnifiedConsentServiceBridge.setUrlKeyedAnonymizedDataCollectionEnabled( - Profile.getLastUsedRegularProfile(), false)); - AutofillAssistantPreferencesUtil.setInitialPreferences(true); - - TriggerScriptProto.Builder triggerScript = - TriggerScriptProto - .newBuilder() - /* no trigger condition */ - .setUserInterface(createDefaultTriggerScriptUI("Trigger script", - /* bubbleMessage = */ "", - /* withProgressBar = */ false)); - GetTriggerScriptsResponseProto triggerScripts = GetTriggerScriptsResponseProto.newBuilder() - .addTriggerScripts(triggerScript) - .build(); - byte[] triggerScriptsResponse = triggerScripts.toByteArray(); - String base64Response = Base64.encodeToString(triggerScriptsResponse, /* offset = */ 0, - triggerScriptsResponse.length, Base64.URL_SAFE | Base64.NO_WRAP); - Assert.assertEquals(0, base64Response.length() % 4); - startAutofillAssistantOnTabWithParams( - TEST_PAGE_A, Collections.singletonMap("TRIGGER_SCRIPTS_BASE64", base64Response)); - - waitUntilViewMatchesCondition(withText("Trigger script"), isCompletelyDisplayed()); - } - - @Test - @MediumTest - @EnableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME) public void dontShowOnboardingIfAcceptedInDifferentTab() { TriggerScriptProto.Builder triggerScript = TriggerScriptProto
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java index 2013baa..e2ccbba9 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinator.java
@@ -70,7 +70,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.List; /** * Root coordinator that is responsible for showing start surfaces, like a grid of Tabs, explore @@ -648,11 +647,6 @@ } @VisibleForTesting - public void showTabSelectionEditorForTesting(List<Tab> tabs) { - mStartSurfaceMediator.getSecondaryTasksSurfaceController().showTabSelectionEditor(tabs); - } - - @VisibleForTesting public boolean isMVTilesCleanedUpForTesting() { return mTasksSurface.isMVTilesCleanedUp(); }
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/TasksSurfaceViewBinder.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/TasksSurfaceViewBinder.java index 1c6b6d7..1999531a 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/TasksSurfaceViewBinder.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/TasksSurfaceViewBinder.java
@@ -52,7 +52,7 @@ viewHolder.parentView.addView(viewHolder.tasksSurfaceView, pos); MarginLayoutParams layoutParams = (MarginLayoutParams) viewHolder.tasksSurfaceView.getLayoutParams(); - layoutParams.bottomMargin = model.get(BOTTOM_BAR_HEIGHT); + if (layoutParams != null) layoutParams.bottomMargin = model.get(BOTTOM_BAR_HEIGHT); setTopMargin(viewHolder, model.get(TOP_MARGIN)); }
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/tasks/TasksView.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/tasks/TasksView.java index 9c4a1fa75..932031c4 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/tasks/TasksView.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/tasks/TasksView.java
@@ -42,8 +42,10 @@ import org.chromium.components.content_settings.CookieControlsEnforcement; import org.chromium.ui.base.WindowAndroid; -// The view of the tasks surface. -class TasksView extends CoordinatorLayoutForPointer { +/** + * The view of the tasks surface. Set public for testing. + */ +public class TasksView extends CoordinatorLayoutForPointer { private static final int OMNIBOX_BOTTOM_PADDING_DP = 4; private final Context mContext;
diff --git a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceBackButtonTest.java b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceBackButtonTest.java index 293b120..085c7e5a 100644 --- a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceBackButtonTest.java +++ b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceBackButtonTest.java
@@ -56,9 +56,7 @@ import org.chromium.chrome.browser.layouts.LayoutType; import org.chromium.chrome.browser.native_page.ContextMenuManager; import org.chromium.chrome.browser.suggestions.tile.MostVisitedTilesCarouselLayout; -import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; -import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tasks.tab_management.TabUiTestHelper; import org.chromium.chrome.test.ChromeJUnit4RunnerDelegate; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; @@ -73,7 +71,6 @@ import org.chromium.ui.test.util.UiRestriction; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; @@ -457,22 +454,4 @@ private boolean isInstantReturn() { return mUseInstantStart && mImmediateReturn; } - - private List<Tab> getTabsInCurrentTabModel(TabModel currentTabModel) { - List<Tab> tabs = new ArrayList<>(); - for (int i = 0; i < currentTabModel.getCount(); i++) { - tabs.add(currentTabModel.getTabAt(i)); - } - return tabs; - } - - private boolean isTabGridDialogShown(ChromeTabbedActivity cta) { - View dialogView = cta.findViewById(org.chromium.chrome.tab_ui.R.id.dialog_parent_view); - return dialogView.getVisibility() == View.VISIBLE && dialogView.getAlpha() == 1f; - } - - private boolean isTabGridDialogHidden(ChromeTabbedActivity cta) { - View dialogView = cta.findViewById(org.chromium.chrome.tab_ui.R.id.dialog_parent_view); - return dialogView.getVisibility() == View.GONE; - } }
diff --git a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceMVTilesTest.java b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceMVTilesTest.java index e70e900..15fe2ef 100644 --- a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceMVTilesTest.java +++ b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceMVTilesTest.java
@@ -54,7 +54,6 @@ import org.chromium.chrome.browser.suggestions.SiteSuggestion; import org.chromium.chrome.browser.suggestions.tile.MostVisitedTilesCarouselLayout; import org.chromium.chrome.browser.suggestions.tile.SuggestionsTileView; -import org.chromium.chrome.browser.tab.TabLaunchType; import org.chromium.chrome.browser.tasks.tab_management.TabUiTestHelper; import org.chromium.chrome.browser.ui.messages.snackbar.SnackbarManager; import org.chromium.chrome.test.ChromeJUnit4RunnerDelegate; @@ -171,61 +170,6 @@ assertThat(cta.getTabModelSelector().getCurrentModel().getCount(), equalTo(1)); } - @Test - @MediumTest - @Feature({"StartSurface"}) - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS}) - public void testCleanUpMVTilesAfterHiding() { - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - if (!mImmediateReturn) StartSurfaceTestUtils.pressHomePageButton(cta); - StartSurfaceTestUtils.waitForOverviewVisible( - mLayoutChangedCallbackHelper, mCurrentlyActiveLayout, cta); - StartSurfaceCoordinator startSurfaceCoordinator = - StartSurfaceTestUtils.getStartSurfaceFromUIThread(cta); - TabUiTestHelper.verifyTabModelTabCount(cta, 1, 0); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertFalse(startSurfaceCoordinator.isMVTilesCleanedUpForTesting()); - }); - - StartSurfaceTestUtils.launchFirstMVTile(cta, /* currentTabCount = */ 1); - Assert.assertEquals("The launched tab should have the launch type FROM_START_SURFACE", - TabLaunchType.FROM_START_SURFACE, - cta.getActivityTabProvider().get().getLaunchType()); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertTrue(startSurfaceCoordinator.isMVTilesCleanedUpForTesting()); - }); - } - - @Test - @MediumTest - @Feature({"StartSurface"}) - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS}) - public void testMVTilesInitialized() { - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - if (!mImmediateReturn) StartSurfaceTestUtils.pressHomePageButton(cta); - StartSurfaceTestUtils.waitForOverviewVisible( - mLayoutChangedCallbackHelper, mCurrentlyActiveLayout, cta); - StartSurfaceCoordinator startSurfaceCoordinator = - StartSurfaceTestUtils.getStartSurfaceFromUIThread(cta); - - StartSurfaceTestUtils.launchFirstMVTile(cta, /* currentTabCount = */ 1); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertFalse(startSurfaceCoordinator.isMVTilesInitializedForTesting()); - }); - - TabUiTestHelper.enterTabSwitcher(cta); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertFalse(startSurfaceCoordinator.isMVTilesInitializedForTesting()); - }); - - TestThreadUtils.runOnUiThreadBlocking(() -> cta.getTabCreator(false).launchNTP()); - onViewWaiting(withId(R.id.primary_tasks_surface_view)); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertTrue(startSurfaceCoordinator.isMVTilesInitializedForTesting()); - }); - } - /* MV tiles context menu tests starts. */ @Test @MediumTest
diff --git a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTabSwitcherTest.java b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTabSwitcherTest.java index e2fc48d..6a60a3d 100644 --- a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTabSwitcherTest.java +++ b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTabSwitcherTest.java
@@ -372,32 +372,6 @@ () -> Assert.assertEquals(tab2.getTitle(), title2.getText())); } - @Test - @MediumTest - @Feature({"StartSurface"}) - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS}) - public void testDoNotInitializeSecondaryTasksSurfaceWithoutOpenGridTabSwitcher() { - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - if (!mImmediateReturn) StartSurfaceTestUtils.pressHomePageButton(cta); - StartSurfaceTestUtils.waitForOverviewVisible( - mLayoutChangedCallbackHelper, mCurrentlyActiveLayout, cta); - StartSurfaceCoordinator startSurfaceCoordinator = - StartSurfaceTestUtils.getStartSurfaceFromUIThread(cta); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertTrue(startSurfaceCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); - }); - StartSurfaceTestUtils.launchFirstMVTile(cta, /* currentTabCount = */ 1); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertTrue(startSurfaceCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); - }); - - TabUiTestHelper.enterTabSwitcher(cta); - TestThreadUtils.runOnUiThreadBlocking(() -> { - Assert.assertFalse(startSurfaceCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); - }); - } - /** * @return Whether both features {@link ChromeFeatureList#INSTANT_START} and * {@link ChromeFeatureList#TAB_SWITCHER_ON_RETURN} are enabled.
diff --git a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java index 336b34e..bd9bed3 100644 --- a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java +++ b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java
@@ -46,7 +46,6 @@ import com.google.android.material.appbar.AppBarLayout; -import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; @@ -78,8 +77,6 @@ import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.layouts.LayoutTestUtils; import org.chromium.chrome.browser.layouts.LayoutType; -import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; -import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; import org.chromium.chrome.browser.tasks.ReturnToChromeUtil; @@ -728,31 +725,6 @@ @MediumTest @Feature({"StartSurface"}) // clang-format off - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS + - "/check_sync_before_show_start_at_startup/true"}) - public void testShowStartWithSyncCheck() throws Exception { - // clang-format on - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - StartSurfaceTestUtils.waitForTabModel(cta); - assertEquals(1, cta.getTabModelSelector().getTotalTabCount()); - mActivityTestRule.waitForActivityNativeInitializationComplete(); - Assert.assertFalse(cta.getLayoutManager().isLayoutVisible(LayoutType.TAB_SWITCHER)); - - Assert.assertFalse(ReturnToChromeUtil.isPrimaryAccountSync()); - Assert.assertFalse(ReturnToChromeUtil.shouldShowOverviewPageOnStart(cta, cta.getIntent(), - cta.getTabModelSelector(), cta.getInactivityTrackerForTesting())); - ReturnToChromeUtil.setSyncForTesting(true); - Assert.assertTrue(ReturnToChromeUtil.isPrimaryAccountSync()); - Assert.assertEquals(mImmediateReturn, - ReturnToChromeUtil.shouldShowOverviewPageOnStart(cta, cta.getIntent(), - cta.getTabModelSelector(), cta.getInactivityTrackerForTesting())); - ReturnToChromeUtil.setSyncForTesting(false); - } - - @Test - @MediumTest - @Feature({"StartSurface"}) - // clang-format off @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS}) @DisableIf.Build(sdk_is_greater_than = VERSION_CODES.O_MR1, supported_abis_includes = "x86", message = "Flaky, see crbug.com/1258154") @@ -789,197 +761,6 @@ @MediumTest @Feature({"StartSurface"}) // clang-format off - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS + "/behavioural_targeting/model_mv_tiles" - + "/user_clicks_threshold/1/num_days_user_click_below_threshold/2"}) - public void testStartWithBehaviouralTargeting() throws Exception { - // clang-format on - Assume.assumeTrue(mImmediateReturn); - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - StartSurfaceTestUtils.waitForTabModel(cta); - TabUiTestHelper.verifyTabModelTabCount(cta, 1, 0); - Assert.assertFalse(cta.getLayoutManager().isLayoutVisible(LayoutType.TAB_SWITCHER)); - - SharedPreferencesManager manager = SharedPreferencesManager.getInstance(); - // Verifies that the START_NEXT_SHOW_ON_STARTUP_DECISION_MS has been set. - long nextDecisionTime = - manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); - - manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, - ReturnToChromeUtil.ShowChromeStartSegmentationResult.DONT_SHOW); - - StartSurfaceConfiguration.USER_CLICK_THRESHOLD.setForTesting(1); - int clicksHigherThreshold = StartSurfaceConfiguration.USER_CLICK_THRESHOLD.getValue(); - Assert.assertEquals(1, clicksHigherThreshold); - ReturnToChromeUtil.onMVTileOpened(); - // Verifies that userBehaviourSupported() returns the same result before the next decision - // time arrives. - Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertEquals(nextDecisionTime, - manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP)); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - Assert.assertEquals(1, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); - - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "Startup.Android.ShowChromeStartSegmentationResultComparison")); - - // Verifies if the next decision time past and the clicks of MV tiles is higher than the - // threshold, userBehaviourSupported() returns true. Besides, the next decision time is set - // to NUM_DAYS_KEEP_SHOW_START_AT_STARTUP day's later, and MV tiles count is reset. - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_KEEP_SHOW_START_AT_STARTUP.getValue()); - Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "Startup.Android.ShowChromeStartSegmentationResultComparison", - ReturnToChromeUtil.ShowChromeStartSegmentationResultComparison - .SEGMENTATION_DISABLED_LOGIC_ENABLED)); - - // Verifies if the next decision time past and the clicks of MV tiles is lower than the - // threshold, userBehaviourSupported() returns false. Besides, the next decision time is - // set to NUM_DAYS_USER_CLICK_BELOW_THRESHOLD day's later. - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, - ReturnToChromeUtil.ShowChromeStartSegmentationResult.SHOW); - Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); - Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "Startup.Android.ShowChromeStartSegmentationResultComparison", - ReturnToChromeUtil.ShowChromeStartSegmentationResultComparison - .SEGMENTATION_ENABLED_LOGIC_DISABLED)); - - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("feeds"); - verifyBehaviourTypeRecordedAndChecked(manager); - - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_new_tab"); - verifyBehaviourTypeRecordedAndChecked(manager); - - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_history"); - verifyBehaviourTypeRecordedAndChecked(manager); - - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_recent_tabs"); - verifyBehaviourTypeRecordedAndChecked(manager); - - // Verifies if the key doesn't match the value of - // StartSurfaceConfiguration.BEHAVIOURAL_TARGETING, e.g., the value isn't set, onUIClicked() - // doesn't record or increase the count. - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting(""); - String type = "feeds"; - String key = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type); - ReturnToChromeUtil.onUIClicked(key); - Assert.assertEquals(0, manager.readInt(key, 0)); - - // Verifies the combination case that BEHAVIOURAL_TARGETING is set to "all". - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("all"); - String type1 = "open_history"; - String type2 = "open_recent_tabs"; - String key1 = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type1); - String key2 = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type2); - Assert.assertEquals(0, manager.readInt(key1, 0)); - Assert.assertEquals(0, manager.readInt(key2, 0)); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - - // Increase the count of one key. - ReturnToChromeUtil.onHistoryOpened(); - Assert.assertEquals(1, manager.readInt(key1, 0)); - - // Verifies that userBehaviourSupported() return true due to the count of this key is higher - // or equal to the threshold. - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertEquals(0, manager.readInt(key1, 0)); - Assert.assertEquals(0, manager.readInt(key2, 0)); - Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - - // Resets the decision. - manager.writeBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false); - } - - @Test - @MediumTest - @Feature({"StartSurface"}) - @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS + "/behavioural_targeting/model"}) - public void testStartSegmentationUsage() throws Exception { - Assume.assumeTrue(mImmediateReturn); - ChromeTabbedActivity cta = mActivityTestRule.getActivity(); - StartSurfaceTestUtils.waitForTabModel(cta); - TabUiTestHelper.verifyTabModelTabCount(cta, 1, 0); - Assert.assertFalse(cta.getLayoutManager().isLayoutVisible(LayoutType.TAB_SWITCHER)); - - SharedPreferencesManager manager = SharedPreferencesManager.getInstance(); - // Verifies that the START_NEXT_SHOW_ON_STARTUP_DECISION_MS has been set. - long nextDecisionTime = - manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); - - manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, - ReturnToChromeUtil.ShowChromeStartSegmentationResult.SHOW); - - // Verifies that userBehaviourSupported() returns the same result before the next decision - // time arrives. - Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertEquals(nextDecisionTime, - manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP)); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - - // Verifies if the next decision time past, userBehaviourSupported() returns true. Besides, - // the next decision time is set to NUM_DAYS_KEEP_SHOW_START_AT_STARTUP day's later. - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_KEEP_SHOW_START_AT_STARTUP.getValue()); - - // Verifies if the next decision time past and segmentation says dont show, - // userBehaviourSupported() returns false. Besides, the next decision time is set to - // NUM_DAYS_USER_CLICK_BELOW_THRESHOLD day's later. - manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, - ReturnToChromeUtil.ShowChromeStartSegmentationResult.DONT_SHOW); - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); - - // Verifies that if segmentation stops returning results, then we continue to use the - // previous result. - manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, - ReturnToChromeUtil.ShowChromeStartSegmentationResult.UNINITIALIZED); - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - verifyNextDecisionTimeStampInDays( - manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); - } - - @Test - @MediumTest - @Feature({"StartSurface"}) - // clang-format off @CommandLineFlags.Add({START_SURFACE_TEST_BASE_PARAMS}) public void test_DoNotLoadLastSelectedTabOnStartup() { // clang-format on @@ -1012,49 +793,6 @@ } /** - * Check that the next decision time is within |numOfDays| from now. - * @param numOfDays Number of days to check. - */ - private void verifyNextDecisionTimeStampInDays( - SharedPreferencesManager manager, int numOfDays) { - long approximateTime = - System.currentTimeMillis() + numOfDays * ReturnToChromeUtil.MILLISECONDS_PER_DAY; - long nextDecisionTime = - manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); - - Assert.assertThat("new decision time lower bound", - approximateTime - MILLISECONDS_PER_MINUTE, - Matchers.lessThanOrEqualTo(nextDecisionTime)); - - Assert.assertThat("new decision time upper bound", - approximateTime + MILLISECONDS_PER_MINUTE, - Matchers.greaterThanOrEqualTo(nextDecisionTime)); - } - - private void verifyBehaviourTypeRecordedAndChecked(SharedPreferencesManager manager) { - String key = ReturnToChromeUtil.getBehaviourTypeKeyForTesting( - StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.getValue()); - Assert.assertEquals(0, manager.readInt(key, 0)); - - // Increase the count of the key. - ReturnToChromeUtil.onUIClicked(key); - Assert.assertEquals(1, manager.readInt(key, 0)); - Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - - // Verifies that userBehaviourSupported() return true due to the count of this key is higher - // or equal to the threshold. - manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, - System.currentTimeMillis() - 1); - Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); - Assert.assertEquals(0, manager.readInt(key, 0)); - Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); - - // Resets the decision. - manager.writeBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false); - } - - /** * @return Whether both features {@link ChromeFeatureList#INSTANT_START} and * {@link ChromeFeatureList#TAB_SWITCHER_ON_RETURN} are enabled. */
diff --git a/chrome/android/features/start_surface/junit/DEPS b/chrome/android/features/start_surface/junit/DEPS new file mode 100644 index 0000000..e9f7d81 --- /dev/null +++ b/chrome/android/features/start_surface/junit/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+components/search_engines/android/java/src/org/chromium/components/search_engines/TemplateUrlService.java", +]
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java new file mode 100644 index 0000000..1ae13a6 --- /dev/null +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java
@@ -0,0 +1,350 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.features.start_surface; + +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.content.Intent; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +import org.chromium.base.TimeUtils; +import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.ChromeInactivityTracker; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; +import org.chromium.chrome.browser.preferences.SharedPreferencesManager; +import org.chromium.chrome.browser.tabmodel.TabModelSelector; +import org.chromium.chrome.browser.tasks.ReturnToChromeUtil; +import org.chromium.chrome.test.util.browser.Features; + +/** Tests for {@link StartSurfaceCoordinator}. */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE, shadows = {ShadowRecordHistogram.class}) +@Features.EnableFeatures(ChromeFeatureList.START_SURFACE_ANDROID) +@Features.DisableFeatures({ChromeFeatureList.WEB_FEED, ChromeFeatureList.FEED_INTERACTIVE_REFRESH, + ChromeFeatureList.SHOPPING_LIST}) +public class StartSurfaceCoordinatorUnitTest { + private static final long MILLISECONDS_PER_MINUTE = TimeUtils.SECONDS_PER_MINUTE * 1000; + + @Rule + public StartSurfaceCoordinatorUnitTestRule mTestRule = + new StartSurfaceCoordinatorUnitTestRule(); + @Mock + ChromeInactivityTracker mChromeInactivityTracker; + + StartSurfaceCoordinator mCoordinator; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + ShadowRecordHistogram.reset(); + mCoordinator = mTestRule.getCoordinator(); + } + + @Test + public void testCleanUpMVTilesAfterHiding() { + mCoordinator.setStartSurfaceState(StartSurfaceState.SHOWING_HOMEPAGE); + mCoordinator.showOverview(false); + + Assert.assertFalse(mCoordinator.isMVTilesCleanedUpForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.NOT_SHOWN); + mCoordinator.onHide(); + Assert.assertTrue(mCoordinator.isMVTilesCleanedUpForTesting()); + } + + @Test + public void testMVTilesInitialized() { + mCoordinator.setStartSurfaceState(StartSurfaceState.NOT_SHOWN); + Assert.assertFalse(mCoordinator.isMVTilesInitializedForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.SHOWING_HOMEPAGE); + mCoordinator.showOverview(false); + Assert.assertTrue(mCoordinator.isMVTilesInitializedForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.NOT_SHOWN); + mCoordinator.onHide(); + Assert.assertFalse(mCoordinator.isMVTilesInitializedForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.SHOWN_TABSWITCHER); + Assert.assertFalse(mCoordinator.isMVTilesInitializedForTesting()); + } + + @Test + public void testDoNotInitializeSecondaryTasksSurfaceWithoutOpenGridTabSwitcher() { + mCoordinator.setStartSurfaceState(StartSurfaceState.SHOWING_HOMEPAGE); + mCoordinator.showOverview(false); + Assert.assertTrue(mCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.NOT_SHOWN); + mCoordinator.onHide(); + Assert.assertTrue(mCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); + + mCoordinator.setStartSurfaceState(StartSurfaceState.SHOWN_TABSWITCHER); + Assert.assertFalse(mCoordinator.isSecondaryTasksSurfaceEmptyForTesting()); + } + + @Test + public void testStartWithBehaviouralTargeting() { + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("model_mv_tiles"); + StartSurfaceConfiguration.USER_CLICK_THRESHOLD.setForTesting(1); + StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.setForTesting(2); + + ReturnToChromeUtil.userBehaviourSupported(); + SharedPreferencesManager manager = SharedPreferencesManager.getInstance(); + + // Verifies that the START_NEXT_SHOW_ON_STARTUP_DECISION_MS has been set. + long nextDecisionTime = + manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); + + manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, + ReturnToChromeUtil.ShowChromeStartSegmentationResult.DONT_SHOW); + + StartSurfaceConfiguration.USER_CLICK_THRESHOLD.setForTesting(1); + int clicksHigherThreshold = StartSurfaceConfiguration.USER_CLICK_THRESHOLD.getValue(); + Assert.assertEquals(1, clicksHigherThreshold); + ReturnToChromeUtil.onMVTileOpened(); + // Verifies that userBehaviourSupported() returns the same result before the next decision + // time arrives. + Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertEquals(nextDecisionTime, + manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP)); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + Assert.assertEquals(1, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); + Assert.assertEquals(0, + ShadowRecordHistogram.getHistogramTotalCountForTesting( + "Startup.Android.ShowChromeStartSegmentationResultComparison")); + + // Verifies if the next decision time past and the clicks of MV tiles is higher than the + // threshold, userBehaviourSupported() returns true. Besides, the next decision time is set + // to NUM_DAYS_KEEP_SHOW_START_AT_STARTUP day's later, and MV tiles count is reset. + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_KEEP_SHOW_START_AT_STARTUP.getValue()); + Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); + Assert.assertEquals(1, + ShadowRecordHistogram.getHistogramValueCountForTesting( + "Startup.Android.ShowChromeStartSegmentationResultComparison", + ReturnToChromeUtil.ShowChromeStartSegmentationResultComparison + .SEGMENTATION_DISABLED_LOGIC_ENABLED)); + + // Verifies if the next decision time past and the clicks of MV tiles is lower than the + // threshold, userBehaviourSupported() returns false. Besides, the next decision time is + // set to NUM_DAYS_USER_CLICK_BELOW_THRESHOLD day's later. + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, + ReturnToChromeUtil.ShowChromeStartSegmentationResult.SHOW); + Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); + Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); + Assert.assertEquals(1, + ShadowRecordHistogram.getHistogramValueCountForTesting( + "Startup.Android.ShowChromeStartSegmentationResultComparison", + ReturnToChromeUtil.ShowChromeStartSegmentationResultComparison + .SEGMENTATION_ENABLED_LOGIC_DISABLED)); + + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("feeds"); + verifyBehaviourTypeRecordedAndChecked(manager); + + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_new_tab"); + verifyBehaviourTypeRecordedAndChecked(manager); + + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_history"); + verifyBehaviourTypeRecordedAndChecked(manager); + + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("open_recent_tabs"); + verifyBehaviourTypeRecordedAndChecked(manager); + + // Verifies if the key doesn't match the value of + // StartSurfaceConfiguration.BEHAVIOURAL_TARGETING, e.g., the value isn't set, onUIClicked() + // doesn't record or increase the count. + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting(""); + String type = "feeds"; + String key = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type); + ReturnToChromeUtil.onUIClicked(key); + Assert.assertEquals(0, manager.readInt(key, 0)); + + // Verifies the combination case that BEHAVIOURAL_TARGETING is set to "all". + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("all"); + String type1 = "open_history"; + String type2 = "open_recent_tabs"; + String key1 = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type1); + String key2 = ReturnToChromeUtil.getBehaviourTypeKeyForTesting(type2); + Assert.assertEquals(0, manager.readInt(key1, 0)); + Assert.assertEquals(0, manager.readInt(key2, 0)); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + + // Increase the count of one key. + ReturnToChromeUtil.onHistoryOpened(); + Assert.assertEquals(1, manager.readInt(key1, 0)); + + // Verifies that userBehaviourSupported() return true due to the count of this key is higher + // or equal to the threshold. + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertEquals(0, manager.readInt(key1, 0)); + Assert.assertEquals(0, manager.readInt(key2, 0)); + Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + + // Resets the decision. + manager.writeBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false); + } + + @Test + public void testStartSegmentationUsage() { + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.setForTesting("model"); + + ReturnToChromeUtil.userBehaviourSupported(); + SharedPreferencesManager manager = SharedPreferencesManager.getInstance(); + + // Verifies that the START_NEXT_SHOW_ON_STARTUP_DECISION_MS has been set. + long nextDecisionTime = + manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + Assert.assertEquals(0, manager.readInt(ChromePreferenceKeys.TAP_MV_TILES_COUNT, 0)); + + manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, + ReturnToChromeUtil.ShowChromeStartSegmentationResult.SHOW); + + // Verifies that userBehaviourSupported() returns the same result before the next decision + // time arrives. + Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertEquals(nextDecisionTime, + manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP)); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + + // Verifies if the next decision time past, userBehaviourSupported() returns true. Besides, + // the next decision time is set to NUM_DAYS_KEEP_SHOW_START_AT_STARTUP day's later. + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_KEEP_SHOW_START_AT_STARTUP.getValue()); + + // Verifies if the next decision time past and segmentation says dont show, + // userBehaviourSupported() returns false. Besides, the next decision time is set to + // NUM_DAYS_USER_CLICK_BELOW_THRESHOLD day's later. + manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, + ReturnToChromeUtil.ShowChromeStartSegmentationResult.DONT_SHOW); + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); + + // Verifies that if segmentation stops returning results, then we continue to use the + // previous result. + manager.writeInt(ChromePreferenceKeys.SHOW_START_SEGMENTATION_RESULT, + ReturnToChromeUtil.ShowChromeStartSegmentationResult.UNINITIALIZED); + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertFalse(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + verifyNextDecisionTimeStampInDays( + manager, StartSurfaceConfiguration.NUM_DAYS_USER_CLICK_BELOW_THRESHOLD.getValue()); + } + + @Test + @Features.EnableFeatures( + {ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_SWITCHER_ON_RETURN}) + // clang-format off + public void testShowStartWithSyncCheck() { + // clang-format on + TabModelSelector mTabModelSelector = mTestRule.getTabModelSelector(); + Activity mActivity = mTestRule.getActivity(); + + StartSurfaceConfiguration.CHECK_SYNC_BEFORE_SHOW_START_AT_STARTUP.setForTesting(true); + ReturnToChromeUtil.TAB_SWITCHER_ON_RETURN_MS.setForTesting(0); + when(mTabModelSelector.isTabStateInitialized()).thenReturn(true); + when(mTabModelSelector.getTotalTabCount()).thenReturn(1); + + mActivity.getIntent().setAction(Intent.ACTION_MAIN); + mActivity.getIntent().addCategory(Intent.CATEGORY_LAUNCHER); + when(mChromeInactivityTracker.getLastBackgroundedTimeMs()).thenReturn(10L); + + Assert.assertFalse(ReturnToChromeUtil.isPrimaryAccountSync()); + Assert.assertFalse(ReturnToChromeUtil.shouldShowOverviewPageOnStart( + mActivity, mActivity.getIntent(), mTabModelSelector, mChromeInactivityTracker)); + ReturnToChromeUtil.setSyncForTesting(true); + Assert.assertTrue(ReturnToChromeUtil.isPrimaryAccountSync()); + Assert.assertTrue(ReturnToChromeUtil.shouldShowOverviewPageOnStart( + mActivity, mActivity.getIntent(), mTabModelSelector, mChromeInactivityTracker)); + + ReturnToChromeUtil.setSyncForTesting(false); + } + + /** + * Check that the next decision time is within |numOfDays| from now. + * @param numOfDays Number of days to check. + */ + private void verifyNextDecisionTimeStampInDays( + SharedPreferencesManager manager, int numOfDays) { + long approximateTime = + System.currentTimeMillis() + numOfDays * ReturnToChromeUtil.MILLISECONDS_PER_DAY; + long nextDecisionTime = + manager.readLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + ReturnToChromeUtil.INVALID_DECISION_TIMESTAMP); + + Assert.assertThat("new decision time lower bound", + approximateTime - MILLISECONDS_PER_MINUTE, + Matchers.lessThanOrEqualTo(nextDecisionTime)); + + Assert.assertThat("new decision time upper bound", + approximateTime + MILLISECONDS_PER_MINUTE, + Matchers.greaterThanOrEqualTo(nextDecisionTime)); + } + + private void verifyBehaviourTypeRecordedAndChecked(SharedPreferencesManager manager) { + String key = ReturnToChromeUtil.getBehaviourTypeKeyForTesting( + StartSurfaceConfiguration.BEHAVIOURAL_TARGETING.getValue()); + Assert.assertEquals(0, manager.readInt(key, 0)); + + // Increase the count of the key. + ReturnToChromeUtil.onUIClicked(key); + Assert.assertEquals(1, manager.readInt(key, 0)); + Assert.assertFalse(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + + // Verifies that userBehaviourSupported() return true due to the count of this key is higher + // or equal to the threshold. + manager.writeLong(ChromePreferenceKeys.START_NEXT_SHOW_ON_STARTUP_DECISION_MS, + System.currentTimeMillis() - 1); + Assert.assertTrue(ReturnToChromeUtil.userBehaviourSupported()); + Assert.assertEquals(0, manager.readInt(key, 0)); + Assert.assertTrue(manager.readBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false)); + + // Resets the decision. + manager.writeBoolean(ChromePreferenceKeys.START_SHOW_ON_STARTUP, false); + } +}
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java new file mode 100644 index 0000000..6c3472f --- /dev/null +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java
@@ -0,0 +1,303 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.features.start_surface; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.graphics.Color; +import android.view.ViewGroup; +import android.view.ViewGroup.MarginLayoutParams; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; +import org.mockito.Mockito; +import org.robolectric.Robolectric; + +import org.chromium.base.ActivityState; +import org.chromium.base.ApplicationStatus; +import org.chromium.base.FeatureList; +import org.chromium.base.FeatureListJni; +import org.chromium.base.jank_tracker.DummyJankTracker; +import org.chromium.base.library_loader.LibraryLoader; +import org.chromium.base.supplier.ObservableSupplierImpl; +import org.chromium.base.supplier.OneshotSupplierImpl; +import org.chromium.base.test.util.JniMocker; +import org.chromium.chrome.R; +import org.chromium.chrome.browser.app.tabmodel.ChromeTabModelFilterFactory; +import org.chromium.chrome.browser.back_press.BackPressManager; +import org.chromium.chrome.browser.bookmarks.BookmarkBridge; +import org.chromium.chrome.browser.bookmarks.BookmarkBridgeJni; +import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; +import org.chromium.chrome.browser.feature_engagement.TrackerFactory; +import org.chromium.chrome.browser.feed.FeedServiceBridge; +import org.chromium.chrome.browser.feed.FeedServiceBridgeJni; +import org.chromium.chrome.browser.feed.FeedSurfaceMediator; +import org.chromium.chrome.browser.flags.CachedFeatureFlags; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.fullscreen.BrowserControlsManager; +import org.chromium.chrome.browser.homepage.HomepageManager; +import org.chromium.chrome.browser.init.ActivityLifecycleDispatcherImpl; +import org.chromium.chrome.browser.init.ChromeActivityNativeDelegate; +import org.chromium.chrome.browser.multiwindow.MultiWindowModeStateDispatcherImpl; +import org.chromium.chrome.browser.omnibox.OmniboxStub; +import org.chromium.chrome.browser.omnibox.voice.VoiceRecognitionHandler; +import org.chromium.chrome.browser.preferences.PrefChangeRegistrar; +import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.search_engines.TemplateUrlServiceFactory; +import org.chromium.chrome.browser.share.crow.CrowButtonDelegateImpl; +import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; +import org.chromium.chrome.browser.signin.services.IdentityServicesProviderJni; +import org.chromium.chrome.browser.signin.services.SigninManager; +import org.chromium.chrome.browser.site_settings.CookieControlsServiceBridge; +import org.chromium.chrome.browser.site_settings.CookieControlsServiceBridgeJni; +import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.browser.tabmodel.TabModelFilter; +import org.chromium.chrome.browser.tabmodel.TabModelFilterFactory; +import org.chromium.chrome.browser.tabmodel.TabModelFilterProvider; +import org.chromium.chrome.browser.tabmodel.TabModelSelector; +import org.chromium.chrome.browser.tasks.ReturnToChromeUtil; +import org.chromium.chrome.browser.tasks.tab_management.TabGridDialogView; +import org.chromium.chrome.browser.tasks.tab_management.TabUiThemeProvider; +import org.chromium.chrome.browser.ui.favicon.FaviconHelper; +import org.chromium.chrome.browser.ui.favicon.FaviconHelperJni; +import org.chromium.chrome.browser.ui.messages.snackbar.SnackbarManager; +import org.chromium.chrome.test.util.browser.Features; +import org.chromium.chrome.test.util.browser.offlinepages.FakeOfflinePageBridge; +import org.chromium.chrome.test.util.browser.suggestions.SuggestionsDependenciesRule; +import org.chromium.chrome.test.util.browser.suggestions.mostvisited.FakeMostVisitedSites; +import org.chromium.chrome.test.util.browser.tabmodel.MockTabCreatorManager; +import org.chromium.chrome.test.util.browser.tabmodel.MockTabModel; +import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; +import org.chromium.components.browser_ui.widget.MenuOrKeyboardActionController; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; +import org.chromium.components.feature_engagement.Tracker; +import org.chromium.components.prefs.PrefService; +import org.chromium.components.search_engines.TemplateUrlService; +import org.chromium.components.url_formatter.UrlFormatter; +import org.chromium.components.url_formatter.UrlFormatterJni; +import org.chromium.components.user_prefs.UserPrefs; +import org.chromium.components.user_prefs.UserPrefsJni; +import org.chromium.ui.base.WindowAndroid; +import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogType; +import org.chromium.ui.test.util.modaldialog.FakeModalDialogManager; +import org.chromium.url.GURL; +import org.chromium.url.JUnitTestGURLs; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Custom TestRule for tests using StartSurfaceCoordinator + */ +public class StartSurfaceCoordinatorUnitTestRule implements TestRule { + @Rule + public JniMocker mJniMocker = new JniMocker(); + @Rule + public TestRule mProcessor = new Features.JUnitProcessor(); + @Rule + public SuggestionsDependenciesRule mSuggestionsDeps = new SuggestionsDependenciesRule(); + + private TabModelSelector mTabModelSelector; + private ViewGroup mContainerView; + private TemplateUrlService mTemplateUrlService; + private LibraryLoader mLibraryLoader; + + private Activity mActivity; + private StartSurfaceCoordinator mCoordinator; + + private static class MockTabModelFilterProvider extends TabModelFilterProvider { + public MockTabModelFilterProvider(Activity activity) { + List<TabModel> tabModels = new ArrayList<>(); + tabModels.add(new MockTabModel(false, null)); + MockTabModel tabModel = new MockTabModel(true, null); + tabModel.setAsActiveModelForTesting(); + tabModels.add(tabModel); + + init(new ChromeTabModelFilterFactory(activity), tabModels); + } + + @Override + public void init(TabModelFilterFactory tabModelFilterFactory, List<TabModel> tabModels) { + assert mTabModelFilterList.isEmpty(); + assert tabModels.size() > 0; + + List<TabModelFilter> filters = new ArrayList<>(); + for (int i = 0; i < tabModels.size(); i++) { + filters.add(tabModelFilterFactory.createTabModelFilter(tabModels.get(i))); + } + mTabModelFilterList = Collections.unmodifiableList(filters); + + assert mTabModelFilterList.get(1).isCurrentlySelectedFilter(); + } + } + + @Override + public Statement apply(Statement statement, Description description) { + return new Statement() { + @Override + public void evaluate() { + CachedFeatureFlags.setForTesting(ChromeFeatureList.START_SURFACE_ANDROID, true); + + mTabModelSelector = Mockito.mock(TabModelSelector.class); + mContainerView = Mockito.mock(ViewGroup.class); + mTemplateUrlService = Mockito.mock(TemplateUrlService.class); + mLibraryLoader = Mockito.mock(LibraryLoader.class); + + initJniMocks(); + initViewsMocks(); + + doReturn(new MockTabModelFilterProvider(mActivity)) + .when(mTabModelSelector) + .getTabModelFilterProvider(); + + Assert.assertTrue(ReturnToChromeUtil.isStartSurfaceEnabled(mActivity)); + setUpCoordinator(); + } + }; + } + + public StartSurfaceCoordinator getCoordinator() { + return mCoordinator; + } + + public TabModelSelector getTabModelSelector() { + return mTabModelSelector; + } + + public Activity getActivity() { + return mActivity; + } + + private void initJniMocks() { + Profile profile = Mockito.mock(Profile.class); + PrefService prefService = Mockito.mock(PrefService.class); + Profile.setLastUsedProfileForTesting(profile); + + mSuggestionsDeps.getFactory().offlinePageBridge = new FakeOfflinePageBridge(); + mSuggestionsDeps.getFactory().mostVisitedSites = new FakeMostVisitedSites(); + + FeedSurfaceMediator.setPrefForTest(Mockito.mock(PrefChangeRegistrar.class), prefService); + TrackerFactory.setTrackerForTests(Mockito.mock(Tracker.class)); + + // Mock template url service. + TemplateUrlServiceFactory.setInstanceForTesting(mTemplateUrlService); + when(mTemplateUrlService.doesDefaultSearchEngineHaveLogo()).thenReturn(true); + + // Mock library loader. + when(mLibraryLoader.isInitialized()).thenReturn(false); + LibraryLoader.setLibraryLoaderForTesting(mLibraryLoader); + + UserPrefs.Natives userPrefsJniMock = Mockito.mock(UserPrefs.Natives.class); + Mockito.when(userPrefsJniMock.get(profile)).thenReturn(prefService); + when(userPrefsJniMock.get(profile)).thenReturn(prefService); + mJniMocker.mock(UserPrefsJni.TEST_HOOKS, userPrefsJniMock); + + IdentityServicesProvider.Natives identityServicesProviderJniMock = + Mockito.mock(IdentityServicesProvider.Natives.class); + when(identityServicesProviderJniMock.getSigninManager(any())) + .thenReturn(Mockito.mock(SigninManager.class)); + mJniMocker.mock(IdentityServicesProviderJni.TEST_HOOKS, identityServicesProviderJniMock); + + // Set home page url. + GURL homePageGURL = JUnitTestGURLs.getGURL(JUnitTestGURLs.NTP_URL); + UrlFormatter.Natives urlFormatterJniMock = Mockito.mock(UrlFormatter.Natives.class); + when(urlFormatterJniMock.fixupUrl(HomepageManager.getHomepageUri())) + .thenReturn(homePageGURL); + mJniMocker.mock(UrlFormatterJni.TEST_HOOKS, urlFormatterJniMock); + + mJniMocker.mock(FaviconHelperJni.TEST_HOOKS, Mockito.mock(FaviconHelper.Natives.class)); + mJniMocker.mock(BookmarkBridgeJni.TEST_HOOKS, Mockito.mock(BookmarkBridge.Natives.class)); + mJniMocker.mock( + FeedServiceBridgeJni.TEST_HOOKS, Mockito.mock(FeedServiceBridge.Natives.class)); + mJniMocker.mock(CookieControlsServiceBridgeJni.TEST_HOOKS, + Mockito.mock(CookieControlsServiceBridge.Natives.class)); + mJniMocker.mock(FeatureListJni.TEST_HOOKS, Mockito.mock(FeatureList.Natives.class)); + } + + private void initViewsMocks() { + mActivity = spy(Robolectric.buildActivity(Activity.class).setup().get()); + mActivity.setTheme(org.chromium.chrome.tab_ui.R.style.Theme_BrowserUI_DayNight); + mActivity.setTheme(R.style.ColorOverlay_ChromiumAndroid); + mActivity.setTheme(TabUiThemeProvider.getThemeOverlayStyleResourceId()); + ApplicationStatus.onStateChangeForTesting(mActivity, ActivityState.CREATED); + + when(mContainerView.getContext()).thenReturn(mActivity); + when(mContainerView.getLayoutParams()).thenReturn(new MarginLayoutParams(0, 0)); + + ViewGroup coordinatorView = Mockito.mock(ViewGroup.class); + when(coordinatorView.generateLayoutParams(any())) + .thenReturn(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + when(coordinatorView.findViewById(org.chromium.chrome.tab_ui.R.id.dialog_parent_view)) + .thenReturn(Mockito.mock(TabGridDialogView.class)); + when(mActivity.findViewById(org.chromium.chrome.tab_ui.R.id.coordinator)) + .thenReturn(coordinatorView); + } + + private void setUpCoordinator() { + ScrimCoordinator scrimCoordinator = + new ScrimCoordinator(mActivity, new ScrimCoordinator.SystemUiScrimDelegate() { + @Override + public void setStatusBarScrimFraction(float scrimFraction) { + // Intentional noop + } + + @Override + public void setNavigationBarScrimFraction(float scrimFraction) { + // Intentional noop + } + }, mContainerView, Color.WHITE); + + WindowAndroid windowAndroid = Mockito.mock(WindowAndroid.class); + BrowserControlsManager browserControlsManager = new BrowserControlsManager(mActivity, 0) { + @Override + protected boolean isInVr() { + return false; + } + @Override + protected void rawTopContentOffsetChangedForVr() { + // Intentional noop + } + }; + SnackbarManager snackbarManager = + new SnackbarManager(mActivity, mContainerView, windowAndroid); + TabContentManager tabContentManager = new TabContentManager(mActivity, null, false, null); + + VoiceRecognitionHandler voiceRecognitionHandler = + Mockito.mock(VoiceRecognitionHandler.class); + OmniboxStub omniboxStub = Mockito.mock(OmniboxStub.class); + when(omniboxStub.getVoiceRecognitionHandler()).thenReturn(voiceRecognitionHandler); + when(voiceRecognitionHandler.isVoiceSearchEnabled()).thenReturn(true); + + mCoordinator = new StartSurfaceCoordinator(mActivity, scrimCoordinator, + Mockito.mock(BottomSheetController.class), new OneshotSupplierImpl<>(), + new ObservableSupplierImpl<>(), false, windowAndroid, mContainerView, + new ObservableSupplierImpl<>(), mTabModelSelector, browserControlsManager, + snackbarManager, new ObservableSupplierImpl<>(), + () + -> omniboxStub, + tabContentManager, new FakeModalDialogManager(ModalDialogType.APP), + Mockito.mock(ChromeActivityNativeDelegate.class), + new ActivityLifecycleDispatcherImpl(mActivity), new MockTabCreatorManager(), + Mockito.mock(MenuOrKeyboardActionController.class), + new MultiWindowModeStateDispatcherImpl(mActivity), new DummyJankTracker(), + new ObservableSupplierImpl<>(), new CrowButtonDelegateImpl(), + new BackPressManager()); + + Assert.assertFalse(LibraryLoader.getInstance().isLoaded()); + when(mLibraryLoader.isInitialized()).thenReturn(true); + Assert.assertTrue(ReturnToChromeUtil.isStartSurfaceEnabled(mActivity)); + + mCoordinator.initWithNative(); + } +}
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java index a627b2c5b..e72d37f 100644 --- a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java
@@ -1394,7 +1394,6 @@ @EnableFeatures({ChromeFeatureList.BACK_GESTURE_REFACTOR}) public void testBackPressHandler() { doReturn(false).when(mTabModelSelector).isIncognitoSelected(); - doReturn(false).when(mTabModelSelector).isIncognitoSelected(); doReturn(mVoiceRecognitionHandler).when(mOmniboxStub).getVoiceRecognitionHandler(); doReturn(true).when(mVoiceRecognitionHandler).isVoiceSearchEnabled(); doAnswer((inv) -> mControllerDialogVisibleSupplier.get())
diff --git a/chrome/android/features/start_surface/junit/start_surface_junit_java_sources.gni b/chrome/android/features/start_surface/junit/start_surface_junit_java_sources.gni index f266219..90b2bed4 100644 --- a/chrome/android/features/start_surface/junit/start_surface_junit_java_sources.gni +++ b/chrome/android/features/start_surface/junit/start_surface_junit_java_sources.gni
@@ -4,6 +4,8 @@ start_surface_junit_java_sources = [ "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/SecondaryTasksSurfaceViewBinderUnitTest.java", + "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTest.java", + "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceCoordinatorUnitTestRule.java", "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java", "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/TasksSurfaceViewBinderUnitTest.java", "//chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/tasks/SingleTabSwitcherMediatorUnitTest.java",
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedSurfaceMediator.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedSurfaceMediator.java index b96df6f..97be45e5 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedSurfaceMediator.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedSurfaceMediator.java
@@ -174,8 +174,9 @@ } } - @VisibleForTesting - static void setPrefForTest(PrefChangeRegistrar prefChangeRegistrar, PrefService prefService) { + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public static void setPrefForTest( + PrefChangeRegistrar prefChangeRegistrar, PrefService prefService) { sTestPrefChangeRegistar = prefChangeRegistrar; sPrefServiceForTest = prefService; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java index 2db13da..9643cd68 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java
@@ -1350,8 +1350,9 @@ } } + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) @NativeMethods - interface Natives { + public interface Natives { BookmarkId getBookmarkIdForWebContents(long nativeBookmarkBridge, BookmarkBridge caller, WebContents webContents, boolean onlyEditable); BookmarkItem getBookmarkByID(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/COMMON_METADATA b/chrome/android/java/src/org/chromium/chrome/browser/share/COMMON_METADATA index a9bcd18a..167ca6e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/COMMON_METADATA +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/COMMON_METADATA
@@ -1,3 +1,3 @@ monorail { - component: "UI>Browser>Mobile>Share" + component: "UI>Browser>Sharing" }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/site_settings/CookieControlsServiceBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/site_settings/CookieControlsServiceBridge.java index 2ef3485..c6511bc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/site_settings/CookieControlsServiceBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/site_settings/CookieControlsServiceBridge.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.site_settings; +import androidx.annotation.VisibleForTesting; + import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; import org.chromium.components.content_settings.CookieControlsEnforcement; @@ -77,8 +79,9 @@ mObserver.sendCookieControlsUIChanges(checked, enforcement); } + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) @NativeMethods - interface Natives { + public interface Natives { long init(CookieControlsServiceBridge caller); void destroy(long nativeCookieControlsServiceBridge, CookieControlsServiceBridge caller); void handleCookieControlsToggleChanged(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java index cb06445..ee8996d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java
@@ -74,6 +74,12 @@ import org.chromium.components.external_intents.ExternalNavigationHandler.OverrideUrlLoadingResultType; import org.chromium.components.external_intents.InterceptNavigationDelegateImpl; import org.chromium.components.external_intents.RedirectHandler; +import org.chromium.components.messages.MessageBannerProperties; +import org.chromium.components.messages.MessageDispatcher; +import org.chromium.components.messages.MessageDispatcherProvider; +import org.chromium.components.messages.MessageIdentifier; +import org.chromium.components.messages.MessageStateHandler; +import org.chromium.components.messages.MessagesTestHelper; import org.chromium.content_public.browser.GlobalRenderFrameHostId; import org.chromium.content_public.browser.LifecycleState; import org.chromium.content_public.browser.LoadUrlParams; @@ -85,6 +91,7 @@ import org.chromium.net.test.EmbeddedTestServer; import org.chromium.net.test.util.TestWebServer; import org.chromium.ui.base.PageTransition; +import org.chromium.ui.modelutil.PropertyModel; import org.chromium.url.GURL; import java.util.Arrays; @@ -112,6 +119,8 @@ private static final String BASE_PATH = "/chrome/test/data/android/url_overriding/"; private static final String NAVIGATION_FROM_TIMEOUT_PAGE = BASE_PATH + "navigation_from_timer.html"; + private static final String NAVIGATION_FROM_TIMEOUT_WITH_FALLBACK_PAGE = + BASE_PATH + "navigation_from_timer_with_fallback.html"; private static final String NAVIGATION_FROM_TIMEOUT_PARENT_FRAME_PAGE = BASE_PATH + "navigation_from_timer_parent_frame.html"; private static final String NAVIGATION_FROM_USER_GESTURE_PAGE = @@ -153,6 +162,8 @@ BASE_PATH + "navigation_from_prerender.html"; private static final String NAVIGATION_FROM_FENCED_FRAME = BASE_PATH + "navigation_from_fenced_frame.html"; + private static final String NAVIGATION_FROM_LONG_TIMEOUT = + BASE_PATH + "navigation_from_long_timeout.html"; private static final String OTHER_BROWSER_PACKAGE = "com.other.browser"; private static final String NON_BROWSER_PACKAGE = "not.a.browser"; @@ -311,22 +322,30 @@ }); } - private void loadUrlAndWaitForIntentUrl( + private @OverrideUrlLoadingResultType int loadUrlAndWaitForIntentUrl( final String url, boolean needClick, boolean shouldLaunchExternalIntent) { - loadUrlAndWaitForIntentUrl(url, needClick, false, shouldLaunchExternalIntent, url, true); + return loadUrlAndWaitForIntentUrl( + url, needClick, false, shouldLaunchExternalIntent, url, true); } - private void loadUrlAndWaitForIntentUrl(final String url, boolean needClick, - boolean createsNewTab, final boolean shouldLaunchExternalIntent, + private @OverrideUrlLoadingResultType int loadUrlAndWaitForIntentUrl(final String url, + boolean shouldLaunchExternalIntent, String expectedFinalUrl, + @PageTransition int transition) { + return loadUrlAndWaitForIntentUrl(url, false, false, shouldLaunchExternalIntent, + expectedFinalUrl, true, null, transition); + } + + private @OverrideUrlLoadingResultType int loadUrlAndWaitForIntentUrl(final String url, + boolean needClick, boolean createsNewTab, final boolean shouldLaunchExternalIntent, final String expectedFinalUrl, final boolean shouldFailNavigation) { - loadUrlAndWaitForIntentUrl(url, needClick, createsNewTab, shouldLaunchExternalIntent, - expectedFinalUrl, shouldFailNavigation, null); + return loadUrlAndWaitForIntentUrl(url, needClick, createsNewTab, shouldLaunchExternalIntent, + expectedFinalUrl, shouldFailNavigation, null, PageTransition.LINK); } - private void loadUrlAndWaitForIntentUrl(final String url, boolean needClick, - boolean createsNewTab, final boolean shouldLaunchExternalIntent, - final String expectedFinalUrl, final boolean shouldFailNavigation, - String clickTargetId) { + private @OverrideUrlLoadingResultType int loadUrlAndWaitForIntentUrl(final String url, + boolean needClick, boolean createsNewTab, final boolean shouldLaunchExternalIntent, + final String expectedFinalUrl, final boolean shouldFailNavigation, String clickTargetId, + @PageTransition int transition) { final CallbackHelper finishCallback = new CallbackHelper(); final CallbackHelper failCallback = new CallbackHelper(); final CallbackHelper destroyedCallback = new CallbackHelper(); @@ -345,6 +364,11 @@ Callback<Pair<GURL, OverrideUrlLoadingResult>> resultCallback = (Pair<GURL, OverrideUrlLoadingResult> result) -> { if (result.first.getSpec().equals(url)) return; + // Ignore the NO_OVERRIDE that comes asynchronously after clobbering the tab. + if (lastResultValue.get() == OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB + && result.second.getResultType() == OverrideUrlLoadingResultType.NO_OVERRIDE) { + return; + } lastResultValue.set(result.second.getResultType()); }; @@ -377,7 +401,7 @@ finishCallback.waitForCallback(0, 1, 20, TimeUnit.SECONDS); } catch (TimeoutException ex) { Assert.fail(); - return; + return OverrideUrlLoadingResultType.NO_OVERRIDE; } } @@ -389,7 +413,7 @@ DOMUtils.clickNode(mActivityTestRule.getWebContents(), clickTargetId); } catch (TimeoutException e) { Assert.fail("Failed to click on the target node."); - return; + return OverrideUrlLoadingResultType.NO_OVERRIDE; } } } @@ -399,7 +423,7 @@ failCallback.waitForCallback(0, 1, 20, TimeUnit.SECONDS); } catch (TimeoutException ex) { Assert.fail("Haven't received navigation failure of intents."); - return; + return OverrideUrlLoadingResultType.NO_OVERRIDE; } } @@ -415,7 +439,7 @@ destroyedCallback.waitForCallback(0, 1, 20, TimeUnit.SECONDS); } catch (TimeoutException ex) { Assert.fail("Intercepted new tab wasn't destroyed."); - return; + return OverrideUrlLoadingResultType.NO_OVERRIDE; } } } @@ -429,7 +453,7 @@ finishCallback.waitForCallback(1, 1, 20, TimeUnit.SECONDS); } catch (TimeoutException ex) { Assert.fail("Fallback URL is not loaded"); - return; + return OverrideUrlLoadingResultType.NO_OVERRIDE; } } } @@ -462,6 +486,8 @@ Assert.assertEquals(1 + (hasFallbackUrl ? 1 : 0), finishCallback.getCallCount()); Assert.assertEquals(shouldFailNavigation ? 1 : 0, failCallback.getCallCount()); + + return lastResultValue.get(); } private static InterceptNavigationDelegateImpl getInterceptNavigationDelegate(Tab tab) { @@ -469,6 +495,32 @@ () -> InterceptNavigationDelegateTabHelper.get(tab)); } + private PropertyModel getCurrentExternalNavigationMessage() throws Exception { + return TestThreadUtils.runOnUiThreadBlocking(() -> { + MessageDispatcher messageDispatcher = MessageDispatcherProvider.from( + mActivityTestRule.getActivity().getWindowAndroid()); + List<MessageStateHandler> messages = MessagesTestHelper.getEnqueuedMessages( + messageDispatcher, MessageIdentifier.EXTERNAL_NAVIGATION); + if (messages.isEmpty()) return null; + Assert.assertEquals(1, messages.size()); + return MessagesTestHelper.getCurrentMessage(messages.get(0)); + }); + } + + private void assertMessagePresent() throws Exception { + PackageManager pm = ContextUtils.getApplicationContext().getPackageManager(); + ApplicationInfo selfInfo = ContextUtils.getApplicationContext().getApplicationInfo(); + CharSequence selfLabel = pm.getApplicationLabel(selfInfo); + + PropertyModel message = getCurrentExternalNavigationMessage(); + Assert.assertNotNull(message); + Assert.assertThat(message.get(MessageBannerProperties.TITLE), + Matchers.containsString(selfLabel.toString())); + Assert.assertThat(message.get(MessageBannerProperties.DESCRIPTION).toString(), + Matchers.containsString(selfLabel.toString())); + Assert.assertNotNull(message.get(MessageBannerProperties.ICON)); + } + @Test @SmallTest public void testNavigationFromTimer() { @@ -570,7 +622,9 @@ + Base64.encodeToString(base64FallbackUrl, Base64.URL_SAFE)); // Fallback URL from a subframe will not trigger main or sub frame navigation. - loadUrlAndWaitForIntentUrl(originalUrl, true, false); + @OverrideUrlLoadingResultType + int result = loadUrlAndWaitForIntentUrl(originalUrl, true, false); + Assert.assertEquals(OverrideUrlLoadingResultType.NO_OVERRIDE, result); } @Test @@ -586,7 +640,7 @@ public void testOpenWindowFromLinkUserGesture() { mActivityTestRule.startMainActivityOnBlankPage(); loadUrlAndWaitForIntentUrl(mTestServer.getURL(OPEN_WINDOW_FROM_LINK_USER_GESTURE_PAGE), - true, true, true, null, true, "link"); + true, true, true, null, true, "link", PageTransition.LINK); } @Test @@ -594,7 +648,7 @@ public void testOpenWindowFromSvgUserGesture() { mActivityTestRule.startMainActivityOnBlankPage(); loadUrlAndWaitForIntentUrl(mTestServer.getURL(OPEN_WINDOW_FROM_SVG_USER_GESTURE_PAGE), true, - true, true, null, true, "link"); + true, true, null, true, "link", PageTransition.LINK); } @Test @@ -690,7 +744,8 @@ public void testIntentURIWithFileSchemeDoesNothing() throws TimeoutException { mActivityTestRule.startMainActivityOnBlankPage(); String originalUrl = mTestServer.getURL(NAVIGATION_TO_FILE_SCHEME_FROM_INTENT_URI); - loadUrlAndWaitForIntentUrl(originalUrl, true, true, false, null, true, "scheme_file"); + loadUrlAndWaitForIntentUrl( + originalUrl, true, true, false, null, true, "scheme_file", PageTransition.LINK); } @Test @@ -698,8 +753,8 @@ public void testIntentURIWithMixedCaseFileSchemeDoesNothing() throws TimeoutException { mActivityTestRule.startMainActivityOnBlankPage(); String originalUrl = mTestServer.getURL(NAVIGATION_TO_FILE_SCHEME_FROM_INTENT_URI); - loadUrlAndWaitForIntentUrl( - originalUrl, true, true, false, null, true, "scheme_mixed_case_file"); + loadUrlAndWaitForIntentUrl(originalUrl, true, true, false, null, true, + "scheme_mixed_case_file", PageTransition.LINK); } @Test @@ -707,7 +762,8 @@ public void testIntentURIWithNoSchemeDoesNothing() throws TimeoutException { mActivityTestRule.startMainActivityOnBlankPage(); String originalUrl = mTestServer.getURL(NAVIGATION_TO_FILE_SCHEME_FROM_INTENT_URI); - loadUrlAndWaitForIntentUrl(originalUrl, true, true, false, null, true, "null_scheme"); + loadUrlAndWaitForIntentUrl( + originalUrl, true, true, false, null, true, "null_scheme", PageTransition.LINK); } @Test @@ -715,15 +771,18 @@ public void testIntentURIWithEmptySchemeDoesNothing() throws TimeoutException { mActivityTestRule.startMainActivityOnBlankPage(); String originalUrl = mTestServer.getURL(NAVIGATION_TO_FILE_SCHEME_FROM_INTENT_URI); - loadUrlAndWaitForIntentUrl(originalUrl, true, true, false, null, true, "empty_scheme"); + loadUrlAndWaitForIntentUrl( + originalUrl, true, true, false, null, true, "empty_scheme", PageTransition.LINK); } @Test @LargeTest public void testSubframeLoadCannotLaunchPlayApp() throws TimeoutException { mActivityTestRule.startMainActivityOnBlankPage(); - loadUrlAndWaitForIntentUrl( + @OverrideUrlLoadingResultType + int result = loadUrlAndWaitForIntentUrl( mTestServer.getURL(SUBFRAME_REDIRECT_WITH_PLAY_FALLBACK), false, false); + Assert.assertEquals(OverrideUrlLoadingResultType.NO_OVERRIDE, result); } private void runRedirectToOtherBrowserTest(Instrumentation.ActivityResult chooserResult) { @@ -881,11 +940,16 @@ // Page redirects to intent: URL. finishCallback.waitForCallback(2); + // With RedirectHandler state cleared, this should be treated as a navigation without a - // user gesture, and so should not allow external navigation. - Assert.assertEquals(OverrideUrlLoadingResultType.NO_OVERRIDE, lastResultValue.get()); + // user gesture, which will use a Message to ask the user if they would like to follow the + // external navigation. + Assert.assertEquals( + OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION, lastResultValue.get()); Assert.assertTrue(mLastNavigationHandle.get().getUrl().getSpec().startsWith("intent://")); syncHelper.notifyCalled(); + + Assert.assertNotNull(getCurrentExternalNavigationMessage()); } @Test @@ -1022,4 +1086,51 @@ Criteria.checkThat(monitor.getHits(), Matchers.is(1)); }, 10000L, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } + + @Test + @LargeTest + public void testExternalNavigationMessage() throws Exception { + mActivityTestRule.startMainActivityOnBlankPage(); + + GURL url = new GURL(mTestServer.getURL(NAVIGATION_FROM_LONG_TIMEOUT)); + @OverrideUrlLoadingResultType + int result = loadUrlAndWaitForIntentUrl(url.getSpec(), true, false); + + Assert.assertEquals(OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION, result); + + assertMessagePresent(); + } + + @Test + @LargeTest + public void testRedirectFromBookmark() throws Exception { + mActivityTestRule.startMainActivityOnBlankPage(); + + String url = mTestServer.getURL(NAVIGATION_FROM_TIMEOUT_PAGE); + @OverrideUrlLoadingResultType + int result = loadUrlAndWaitForIntentUrl(url, false, null, PageTransition.AUTO_BOOKMARK); + Assert.assertEquals(OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION, result); + assertMessagePresent(); + } + + @Test + @LargeTest + public void testRedirectFromBookmarkWithFallback() throws Exception { + mActivityTestRule.startMainActivityOnBlankPage(); + + String fallbackUrl = mTestServer.getURL(FALLBACK_LANDING_PATH); + String originalUrl = mTestServer.getURL(NAVIGATION_FROM_TIMEOUT_WITH_FALLBACK_PAGE + + "?replace_text=" + + Base64.encodeToString( + ApiCompatibilityUtils.getBytesUtf8("PARAM_FALLBACK_URL"), Base64.URL_SAFE) + + ":" + + Base64.encodeToString( + ApiCompatibilityUtils.getBytesUtf8(fallbackUrl), Base64.URL_SAFE)); + + @OverrideUrlLoadingResultType + int result = loadUrlAndWaitForIntentUrl( + originalUrl, false, fallbackUrl, PageTransition.AUTO_BOOKMARK); + Assert.assertEquals(OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB, result); + Assert.assertNull(getCurrentExternalNavigationMessage()); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java index 500affd2..7b542cea 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java
@@ -78,15 +78,6 @@ R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed")); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed.Shown")); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed.Shown.BasicCard")); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, @@ -113,13 +104,6 @@ // Wait for the histograms to be logged. Thread.sleep(200); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.UserAborted")); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.UserAborted.Shown")); - // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java index d3dc9ab4..0fec4a7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java
@@ -59,9 +59,6 @@ mBillingAddressId, "" /* serverId */)); } - // Transaction amount from metrics.js is 5$ which falls into the regular transaction category. - private static final int sRegularTransaction = 2; - /** * Expect that the successful checkout funnel metrics are logged during a successful checkout. */ @@ -73,10 +70,6 @@ // Initiate a payment request. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Click the pay button. mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); @@ -87,10 +80,6 @@ mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sRegularTransaction)); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.PAY_CLICKED | Event.RECEIVED_INSTRUMENT_DETAILS | Event.COMPLETED | Event.HAD_INITIAL_FORM_OF_PAYMENT @@ -119,18 +108,10 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Click the pay button. mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getDismissed()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sRegularTransaction)); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.PAY_CLICKED | Event.RECEIVED_INSTRUMENT_DETAILS | Event.COMPLETED | Event.HAD_INITIAL_FORM_OF_PAYMENT @@ -155,10 +136,6 @@ mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Cancel the Payment Request. int callCount = mPaymentRequestTestRule.getDismissed().getCallCount(); TestThreadUtils.runOnUiThreadBlocking( @@ -173,12 +150,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -206,10 +177,6 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Cancel the Payment Request. int callCount = mPaymentRequestTestRule.getDismissed().getCallCount(); TestThreadUtils.runOnUiThreadBlocking((Runnable) () -> { @@ -234,12 +201,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -263,10 +224,6 @@ mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the [X] button. mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); @@ -275,12 +232,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -308,10 +259,6 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the [X] button. mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); @@ -320,12 +267,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -349,10 +290,6 @@ mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the back button. int callCount = mPaymentRequestTestRule.getDismissed().getCallCount(); TestThreadUtils.runOnUiThreadBlocking( @@ -366,12 +303,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -399,10 +330,6 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the back button. int callCount = mPaymentRequestTestRule.getDismissed().getCallCount(); TestThreadUtils.runOnUiThreadBlocking( @@ -416,12 +343,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged(AbortReason.ABORTED_BY_USER); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -446,10 +367,6 @@ mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the back button. ChromeTabUtils.closeCurrentTab(InstrumentationRegistry.getInstrumentation(), mPaymentRequestTestRule.getActivity()); @@ -457,14 +374,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged( AbortReason.MOJO_RENDERER_CLOSING); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - // TODO(crbug.com/1260097): This expectation is no longer valid. Efforts are needed to fix - // the test or the implementation code. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.OTHER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -494,10 +403,6 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Press the back button. ChromeTabUtils.closeCurrentTab(InstrumentationRegistry.getInstrumentation(), mPaymentRequestTestRule.getActivity()); @@ -505,13 +410,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged( AbortReason.MOJO_RENDERER_CLOSING); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - // TODO(crbug.com/1260097): This expectation is no longer valid. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.OTHER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -533,10 +431,6 @@ public void testAbortMetrics_AbortedByMerchant_WithBasicCardEnabled() throws TimeoutException { mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Simulate an abort by the merchant. mPaymentRequestTestRule.clickNodeAndWait("abort", mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains(new String[] {"Abort"}); @@ -544,12 +438,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged( AbortReason.ABORTED_BY_MERCHANT); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.OTHER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -577,10 +465,6 @@ mPaymentRequestTestRule.triggerUIAndWait( "buyWithUrlMethods", mPaymentRequestTestRule.getReadyToPay()); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sRegularTransaction)); - // Simulate an abort by the merchant. mPaymentRequestTestRule.clickNodeAndWait("abort", mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains(new String[] {"Abort"}); @@ -588,12 +472,6 @@ mPaymentRequestTestRule.assertOnlySpecificAbortMetricLogged( AbortReason.ABORTED_BY_MERCHANT); - // Make sure no PaymentRequest.TransactionAmount.Completed is logged since transaction - // got aborted. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.OTHER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING @@ -631,15 +509,6 @@ "PaymentRequest.CheckoutFunnel.NoShow", NotShownReason.NO_MATCHING_PAYMENT_METHOD)); - // Make sure no PaymentRequest.TransactionAmount.[Completed|Triggered] is logged since - // we could not trigger the payment sheet. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Triggered")); - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_GOOGLE | Event.COULD_NOT_SHOW | Event.NEEDS_COMPLETION_PAYMENT; @@ -672,15 +541,6 @@ "PaymentRequest.CheckoutFunnel.NoShow", NotShownReason.NO_SUPPORTED_PAYMENT_METHOD)); - // Make sure no PaymentRequest.TransactionAmount.[Completed|Triggered] is logged since - // we could not trigger the payment sheet. - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Triggered")); - Assert.assertEquals(0, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TransactionAmount.Completed")); - // Make sure the events were logged correctly. int expectedSample = Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_OTHER | Event.COULD_NOT_SHOW | Event.NEEDS_COMPLETION_PAYMENT; @@ -767,15 +627,6 @@ Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed")); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow")); - Assert.assertEquals(1, - RecordHistogram.getHistogramTotalCountForTesting( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow.Google")); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java index f19e88c..c379cfe 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java
@@ -11,7 +11,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; @@ -37,11 +36,6 @@ @Override public void onMainActivityStarted() {} - // The initial total in digital_goods.js is 99.99 while the final total is 1.00. Transaction - // amount metrics must record the final total rather than the initial one. The final total falls - // into the micro transaction category. - private static final int sMicroTransaction = 1; - @Test @MediumTest @Feature({"Payments"}) @@ -57,12 +51,6 @@ mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); mRule.expectResultContains(new String[] {"\"total\":\"1.00\""}); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sMicroTransaction)); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sMicroTransaction)); } @Test @@ -77,12 +65,6 @@ mRule.triggerUIAndWait(mRule.getResultReady()); mRule.expectResultContains(new String[] {"\"total\":\"1.00\""}); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sMicroTransaction)); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sMicroTransaction)); } @Test @@ -101,12 +83,6 @@ mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); mRule.expectResultContains(new String[] {"\"total\":\"1.00\""}); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sMicroTransaction)); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sMicroTransaction)); } @Test @@ -121,12 +97,6 @@ mRule.triggerUIAndWait(mRule.getResultReady()); mRule.expectResultContains(new String[] {"\"total\":\"1.00\""}); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Triggered", sMicroTransaction)); - Assert.assertEquals(1, - RecordHistogram.getHistogramValueCountForTesting( - "PaymentRequest.TransactionAmount.Completed", sMicroTransaction)); } @Test
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index f0371beb..34a1c929 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -4733,6 +4733,16 @@ <message name="IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_PLATFORMKEYS" desc="Permission string for enterprise platform keys permission."> Perform security-related tasks for your organization, such as managing certificates and keys stored on the device </message> + <if expr="is_win"> + <message name="IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_WIN" desc="Permission string for enterprise private reporting permission on Windows."> + Read information about your browser, OS, device, installed software, registry values and files + </message> + </if> + <if expr="is_macosx or is_linux"> + <message name="IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_LINUX_AND_MACOS" desc="Permission string for enterprise private reporting permission on Linux and MacOS."> + Read information about your browser, OS, device, installed software and files + </message> + </if> <message name="IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE" desc="Permission string for enterprise private reporting permission."> Read information about your browser, OS, and device </message>
diff --git a/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_LINUX_AND_MACOS.png.sha1 b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_LINUX_AND_MACOS.png.sha1 new file mode 100644 index 0000000..bd99e78 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_LINUX_AND_MACOS.png.sha1
@@ -0,0 +1 @@ +5842ae8982374d42ec176694398cd99ed39175fa \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_WIN.png.sha1 b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_WIN.png.sha1 new file mode 100644 index 0000000..eee9cc4 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_WIN.png.sha1
@@ -0,0 +1 @@ +58f7f76d652fe9b10d52bbce347d37f89bfe25fb \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 1abb46239..090f84e9 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1988,7 +1988,6 @@ "//chrome/browser/notifications/scheduler/public", "//chrome/browser/password_manager", "//chrome/browser/persisted_state_db:persisted_state_db", - "//chrome/browser/persisted_state_db:persisted_state_db_content_proto", "//chrome/browser/policy:path_parser", "//chrome/browser/privacy_budget", "//chrome/browser/profiles", @@ -2063,6 +2062,7 @@ "//components/cloud_devices/common", "//components/commerce/core:commerce_heuristics_data", "//components/commerce/core:feature_list", + "//components/commerce/core:persisted_state_db_content_proto", "//components/commerce/core:shopping_service", "//components/component_updater", "//components/component_updater:crl_set_remover", @@ -4006,8 +4006,6 @@ "performance_manager/policies/high_efficiency_mode_policy.h", "performance_manager/policies/high_efficiency_mode_policy_helper.cc", "performance_manager/policies/high_efficiency_mode_policy_helper.h", - "performance_manager/policies/high_pmf_discard_policy.cc", - "performance_manager/policies/high_pmf_discard_policy.h", "performance_manager/policies/page_discarding_helper.cc", "performance_manager/policies/page_discarding_helper.h", "performance_manager/policies/urgent_page_discarding_policy.cc", @@ -5119,6 +5117,7 @@ "//chrome/browser/ui/webui/chromeos/crostini_upgrader:mojo_bindings", "//chrome/browser/ui/webui/chromeos/emoji:mojo_bindings", "//chrome/browser/ui/webui/chromeos/launcher_internals:mojo_bindings", + "//chrome/browser/ui/webui/chromeos/manage_mirrorsync:mojo_bindings", "//chrome/browser/ui/webui/chromeos/parent_access:mojo_bindings", "//chrome/browser/ui/webui/chromeos/vm:mojo_bindings", "//chrome/browser/ui/webui/nearby_share:mojom",
diff --git a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfo.java b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfo.java index ff3e9ca..97116e8e2 100644 --- a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfo.java +++ b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfo.java
@@ -28,18 +28,18 @@ // Whether to override the icon information returned to callers. private boolean mUseOldIcons; - public static MergedWebappInfo create( - WebappInfo oldWebappInfo, @Nullable BrowserServicesIntentDataProvider provider) { - return new MergedWebappInfo(oldWebappInfo, provider); + public static MergedWebappInfo create(@NonNull WebappInfo oldWebappInfo, + @Nullable BrowserServicesIntentDataProvider provider) { + return (provider == null) ? null : new MergedWebappInfo(oldWebappInfo, provider); } public static MergedWebappInfo createForTesting( - WebappInfo oldWebappInfo, WebappInfo newWebappInfo) { + @NonNull WebappInfo oldWebappInfo, @NonNull WebappInfo newWebappInfo) { return new MergedWebappInfo(oldWebappInfo, newWebappInfo.getProvider()); } - private MergedWebappInfo( - WebappInfo oldWebappInfo, @Nullable BrowserServicesIntentDataProvider provider) { + private MergedWebappInfo(@NonNull WebappInfo oldWebappInfo, + @NonNull BrowserServicesIntentDataProvider provider) { super(provider); mOldWebappInfo = oldWebappInfo; }
diff --git a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfoTest.java b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfoTest.java index 9b0a574..a02cf6b 100644 --- a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfoTest.java +++ b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/MergedWebappInfoTest.java
@@ -20,93 +20,102 @@ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MergedWebappInfoTest { + private static final String APP_ID = "webapp id"; + private static final String APP_URL = "about:blank"; + private static final String APP_NAME_OLD = "nameOld"; + private static final String APP_NAME_NEW = "nameNew"; + private static final String APP_SHORTNAME_OLD = "shortNameOld"; + private static final String APP_SHORTNAME_NEW = "shortNameNew"; + + @Test + public void testNullProvider() { + Intent intentOld = new Intent(); + intentOld.putExtra(WebappConstants.EXTRA_ID, APP_ID); + intentOld.putExtra(WebappConstants.EXTRA_URL, APP_URL); + intentOld.putExtra(WebappConstants.EXTRA_NAME, APP_NAME_OLD); + intentOld.putExtra(WebappConstants.EXTRA_SHORT_NAME, APP_SHORTNAME_OLD); + intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_ADAPTIVE, false); + intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_GENERATED, false); + WebappInfo oldInfo = createWebappInfo(intentOld); + + // Test for issue https://crbug.com/1341149. Make sure we don't get a valid Merged object if + // provider is null. + Assert.assertEquals(null, MergedWebappInfo.create(oldInfo, /* provider= */ null)); + Assert.assertEquals(null, MergedWebappInfo.create(null, /* provider= */ null)); + } + @Test public void testOverrideValues() { - String id = "webapp id"; - String url = "about:blank"; + Intent intentOld = new Intent(); + intentOld.putExtra(WebappConstants.EXTRA_ID, APP_ID); + intentOld.putExtra(WebappConstants.EXTRA_URL, APP_URL); + intentOld.putExtra(WebappConstants.EXTRA_NAME, APP_NAME_OLD); + intentOld.putExtra(WebappConstants.EXTRA_SHORT_NAME, APP_SHORTNAME_OLD); + intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_ADAPTIVE, false); + intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_GENERATED, false); + WebappInfo oldInfo = createWebappInfo(intentOld); - String nameOld = "nameOld"; - String nameNew = "nameNew"; - String shortNameOld = "shortNameOld"; - String shortNameNew = "shortNameNew"; + Intent intentNew = new Intent(); + intentNew.putExtra(WebappConstants.EXTRA_ID, APP_ID); + intentNew.putExtra(WebappConstants.EXTRA_URL, APP_URL); + intentNew.putExtra(WebappConstants.EXTRA_NAME, APP_NAME_NEW); + intentNew.putExtra(WebappConstants.EXTRA_SHORT_NAME, APP_SHORTNAME_NEW); + intentNew.putExtra(WebappConstants.EXTRA_IS_ICON_ADAPTIVE, true); + intentNew.putExtra(WebappConstants.EXTRA_IS_ICON_GENERATED, true); + MergedWebappInfo newInfo = createMergedWebappInfo(oldInfo, createWebappInfo(intentNew)); - { - Intent intentOld = new Intent(); - intentOld.putExtra(WebappConstants.EXTRA_ID, id); - intentOld.putExtra(WebappConstants.EXTRA_URL, url); - intentOld.putExtra(WebappConstants.EXTRA_NAME, nameOld); - intentOld.putExtra(WebappConstants.EXTRA_SHORT_NAME, shortNameOld); - intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_ADAPTIVE, false); - intentOld.putExtra(WebappConstants.EXTRA_IS_ICON_GENERATED, false); - WebappInfo oldInfo = createWebappInfo(intentOld); + Assert.assertEquals(APP_NAME_OLD, oldInfo.name()); + Assert.assertEquals(APP_NAME_NEW, newInfo.name()); + Assert.assertEquals(APP_SHORTNAME_OLD, oldInfo.shortName()); + Assert.assertEquals(APP_SHORTNAME_NEW, newInfo.shortName()); + Assert.assertTrue(newInfo.icon() != oldInfo.icon()); + Assert.assertTrue(newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); + Assert.assertFalse(oldInfo.isIconAdaptive()); + Assert.assertTrue(newInfo.isIconAdaptive()); + Assert.assertFalse(oldInfo.isIconGenerated()); + Assert.assertTrue(newInfo.isIconGenerated()); - Intent intentNew = new Intent(); - intentNew.putExtra(WebappConstants.EXTRA_ID, id); - intentNew.putExtra(WebappConstants.EXTRA_URL, url); - intentNew.putExtra(WebappConstants.EXTRA_NAME, nameNew); - intentNew.putExtra(WebappConstants.EXTRA_SHORT_NAME, shortNameNew); - intentNew.putExtra(WebappConstants.EXTRA_IS_ICON_ADAPTIVE, true); - intentNew.putExtra(WebappConstants.EXTRA_IS_ICON_GENERATED, true); - MergedWebappInfo newInfo = createMergedWebappInfo(oldInfo, createWebappInfo(intentNew)); + // Make the new WebappInfo pretend old names are still in use. + newInfo.setUseOldName(true); + Assert.assertEquals(APP_NAME_OLD, newInfo.name()); + Assert.assertEquals(APP_SHORTNAME_OLD, newInfo.shortName()); + // But the icon stuff should be unchanged. + Assert.assertTrue(newInfo.icon() != oldInfo.icon()); + Assert.assertTrue(newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); + Assert.assertTrue(newInfo.isIconAdaptive()); + Assert.assertTrue(newInfo.isIconGenerated()); - Assert.assertEquals(nameOld, oldInfo.name()); - Assert.assertEquals(nameNew, newInfo.name()); - Assert.assertEquals(shortNameOld, oldInfo.shortName()); - Assert.assertEquals(shortNameNew, newInfo.shortName()); - Assert.assertTrue(newInfo.icon() != oldInfo.icon()); - Assert.assertTrue( - newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); - Assert.assertFalse(oldInfo.isIconAdaptive()); - Assert.assertTrue(newInfo.isIconAdaptive()); - Assert.assertFalse(oldInfo.isIconGenerated()); - Assert.assertTrue(newInfo.isIconGenerated()); + // Now pretend both the old icons and old names are still in use. + newInfo.setUseOldIcon(true); + Assert.assertEquals(APP_NAME_OLD, newInfo.name()); + Assert.assertEquals(APP_SHORTNAME_OLD, newInfo.shortName()); + Assert.assertTrue(newInfo.icon() == oldInfo.icon()); + Assert.assertEquals(newInfo.iconUrlToMurmur2HashMap(), oldInfo.iconUrlToMurmur2HashMap()); + Assert.assertFalse(newInfo.isIconAdaptive()); + Assert.assertFalse(newInfo.isIconGenerated()); - // Make the new WebappInfo pretend old names are still in use. - newInfo.setUseOldName(true); - Assert.assertEquals(nameOld, newInfo.name()); - Assert.assertEquals(shortNameOld, newInfo.shortName()); - // But the icon stuff should be unchanged. - Assert.assertTrue(newInfo.icon() != oldInfo.icon()); - Assert.assertTrue( - newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); - Assert.assertTrue(newInfo.isIconAdaptive()); - Assert.assertTrue(newInfo.isIconGenerated()); + // Make the new WebappInfo pretend only old icons are still in use. + newInfo.setUseOldName(false); + Assert.assertEquals(APP_NAME_NEW, newInfo.name()); + Assert.assertEquals(APP_SHORTNAME_NEW, newInfo.shortName()); + // But the icon stuff should be changed. + Assert.assertTrue(newInfo.icon() == oldInfo.icon()); + Assert.assertEquals(newInfo.iconUrlToMurmur2HashMap(), oldInfo.iconUrlToMurmur2HashMap()); + Assert.assertFalse(newInfo.isIconAdaptive()); + Assert.assertFalse(newInfo.isIconGenerated()); - // Now pretend both the old icons and old names are still in use. - newInfo.setUseOldIcon(true); - Assert.assertEquals(nameOld, newInfo.name()); - Assert.assertEquals(shortNameOld, newInfo.shortName()); - Assert.assertTrue(newInfo.icon() == oldInfo.icon()); - Assert.assertEquals( - newInfo.iconUrlToMurmur2HashMap(), oldInfo.iconUrlToMurmur2HashMap()); - Assert.assertFalse(newInfo.isIconAdaptive()); - Assert.assertFalse(newInfo.isIconGenerated()); - - // Make the new WebappInfo pretend only old icons are still in use. - newInfo.setUseOldName(false); - Assert.assertEquals(nameNew, newInfo.name()); - Assert.assertEquals(shortNameNew, newInfo.shortName()); - // But the icon stuff should be changed. - Assert.assertTrue(newInfo.icon() == oldInfo.icon()); - Assert.assertEquals( - newInfo.iconUrlToMurmur2HashMap(), oldInfo.iconUrlToMurmur2HashMap()); - Assert.assertFalse(newInfo.isIconAdaptive()); - Assert.assertFalse(newInfo.isIconGenerated()); - - // Now revert back to no override. - newInfo.setUseOldIcon(false); - Assert.assertEquals(nameOld, oldInfo.name()); - Assert.assertEquals(nameNew, newInfo.name()); - Assert.assertEquals(shortNameOld, oldInfo.shortName()); - Assert.assertEquals(shortNameNew, newInfo.shortName()); - Assert.assertTrue(newInfo.icon() != oldInfo.icon()); - Assert.assertTrue( - newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); - Assert.assertFalse(oldInfo.isIconAdaptive()); - Assert.assertTrue(newInfo.isIconAdaptive()); - Assert.assertFalse(oldInfo.isIconGenerated()); - Assert.assertTrue(newInfo.isIconGenerated()); - } + // Now revert back to no override. + newInfo.setUseOldIcon(false); + Assert.assertEquals(APP_NAME_OLD, oldInfo.name()); + Assert.assertEquals(APP_NAME_NEW, newInfo.name()); + Assert.assertEquals(APP_SHORTNAME_OLD, oldInfo.shortName()); + Assert.assertEquals(APP_SHORTNAME_NEW, newInfo.shortName()); + Assert.assertTrue(newInfo.icon() != oldInfo.icon()); + Assert.assertTrue(newInfo.iconUrlToMurmur2HashMap() != oldInfo.iconUrlToMurmur2HashMap()); + Assert.assertFalse(oldInfo.isIconAdaptive()); + Assert.assertTrue(newInfo.isIconAdaptive()); + Assert.assertFalse(oldInfo.isIconGenerated()); + Assert.assertTrue(newInfo.isIconGenerated()); } private WebappInfo createWebappInfo(Intent intent) {
diff --git a/chrome/browser/apps/app_service/app_launch_params.cc b/chrome/browser/apps/app_service/app_launch_params.cc index d87f831a..f346ae9 100644 --- a/chrome/browser/apps/app_service/app_launch_params.cc +++ b/chrome/browser/apps/app_service/app_launch_params.cc
@@ -9,7 +9,7 @@ namespace apps { AppLaunchParams::AppLaunchParams(const std::string& app_id, - apps::mojom::LaunchContainer container, + LaunchContainer container, WindowOpenDisposition disposition, apps::mojom::LaunchSource launch_source, int64_t display_id) @@ -21,7 +21,7 @@ display_id(display_id) {} AppLaunchParams::AppLaunchParams(const std::string& app_id, - apps::mojom::LaunchContainer container, + LaunchContainer container, WindowOpenDisposition disposition, apps::mojom::LaunchSource launch_source, int64_t display_id,
diff --git a/chrome/browser/apps/app_service/app_launch_params.h b/chrome/browser/apps/app_service/app_launch_params.h index 0799a5a..0b211de 100644 --- a/chrome/browser/apps/app_service/app_launch_params.h +++ b/chrome/browser/apps/app_service/app_launch_params.h
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/files/file_path.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -22,13 +23,13 @@ struct AppLaunchParams { AppLaunchParams(const std::string& app_id, - apps::mojom::LaunchContainer container, + LaunchContainer container, WindowOpenDisposition disposition, apps::mojom::LaunchSource launch_source, int64_t display_id = display::kInvalidDisplayId); AppLaunchParams(const std::string& app_id, - apps::mojom::LaunchContainer container, + LaunchContainer container, WindowOpenDisposition disposition, apps::mojom::LaunchSource launch_source, int64_t display_id, @@ -50,7 +51,7 @@ std::string launch_id; // The container type to launch the application in. - apps::mojom::LaunchContainer container; + LaunchContainer container; // If container is TAB, this field controls how the tab is opened. WindowOpenDisposition disposition;
diff --git a/chrome/browser/apps/app_service/app_service_proxy_ash.cc b/chrome/browser/apps/app_service/app_service_proxy_ash.cc index c9a5a40..731660d6 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_ash.cc +++ b/chrome/browser/apps/app_service/app_service_proxy_ash.cc
@@ -569,7 +569,7 @@ Profile* profile, const apps::AppUpdate& update, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { RecordAppLaunchMetrics(profile, update.AppType(), update.AppId(), launch_source, container); }
diff --git a/chrome/browser/apps/app_service/app_service_proxy_ash.h b/chrome/browser/apps/app_service/app_service_proxy_ash.h index 89948b22..85e4bfa 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_ash.h +++ b/chrome/browser/apps/app_service/app_service_proxy_ash.h
@@ -19,6 +19,7 @@ #include "chrome/browser/apps/app_service/publisher_host.h" #include "chrome/browser/apps/app_service/subscriber_crosapi.h" #include "chrome/browser/ash/crosapi/browser_manager.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/icon_types.h" #include "components/services/app_service/public/cpp/instance_registry.h" @@ -198,11 +199,10 @@ void PerformPostLaunchTasks(apps::mojom::LaunchSource launch_source) override; - void RecordAppPlatformMetrics( - Profile* profile, - const apps::AppUpdate& update, - apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container) override; + void RecordAppPlatformMetrics(Profile* profile, + const apps::AppUpdate& update, + apps::mojom::LaunchSource launch_source, + apps::LaunchContainer container) override; void InitAppPlatformMetrics();
diff --git a/chrome/browser/apps/app_service/app_service_proxy_base.cc b/chrome/browser/apps/app_service/app_service_proxy_base.cc index 6b626987..02613c45 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_base.cc +++ b/chrome/browser/apps/app_service/app_service_proxy_base.cc
@@ -20,6 +20,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/web_applications/web_app_id_constants.h" #include "components/services/app_service/app_service_mojom_impl.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_filter.h" @@ -288,9 +289,8 @@ } RecordAppLaunch(update.AppId(), launch_source); - RecordAppPlatformMetrics( - profile_, update, launch_source, - apps::mojom::LaunchContainer::kLaunchContainerNone); + RecordAppPlatformMetrics(profile_, update, launch_source, + apps::LaunchContainer::kLaunchContainerNone); app_service_->Launch(ConvertAppTypeToMojomAppType(update.AppType()), update.AppId(), event_flags, launch_source, @@ -314,9 +314,8 @@ return; } - RecordAppPlatformMetrics( - profile_, update, launch_source, - apps::mojom::LaunchContainer::kLaunchContainerNone); + RecordAppPlatformMetrics(profile_, update, launch_source, + apps::LaunchContainer::kLaunchContainerNone); // TODO(crbug/1117655): File manager records metrics for apps it // launched. So we only record launches from other places. We should @@ -361,9 +360,8 @@ if (launch_source != apps::mojom::LaunchSource::kFromFileManager) { RecordAppLaunch(update.AppId(), launch_source); } - RecordAppPlatformMetrics( - profile_, update, launch_source, - apps::mojom::LaunchContainer::kLaunchContainerNone); + RecordAppPlatformMetrics(profile_, update, launch_source, + apps::LaunchContainer::kLaunchContainerNone); app_service_->LaunchAppWithIntent( ConvertAppTypeToMojomAppType(update.AppType()), update.AppId(), @@ -878,7 +876,7 @@ Profile* profile, const apps::AppUpdate& update, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container) {} + apps::LaunchContainer container) {} void AppServiceProxyBase::PerformPostUninstallTasks( apps::AppType app_type,
diff --git a/chrome/browser/apps/app_service/app_service_proxy_base.h b/chrome/browser/apps/app_service/app_service_proxy_base.h index 0433e90c..7a632de 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_base.h +++ b/chrome/browser/apps/app_service/app_service_proxy_base.h
@@ -21,6 +21,7 @@ #include "chrome/browser/apps/app_service/publishers/app_publisher.h" #include "components/keyed_service/core/keyed_service.h" #include "components/services/app_service/public/cpp/app_capability_access_cache.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/icon_cache.h" @@ -393,7 +394,7 @@ virtual void RecordAppPlatformMetrics(Profile* profile, const apps::AppUpdate& update, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); virtual void PerformPostUninstallTasks( apps::AppType app_type,
diff --git a/chrome/browser/apps/app_service/browser_app_launcher.cc b/chrome/browser/apps/app_service/browser_app_launcher.cc index 8ef3ea7..26a8489e 100644 --- a/chrome/browser/apps/app_service/browser_app_launcher.cc +++ b/chrome/browser/apps/app_service/browser_app_launcher.cc
@@ -26,6 +26,7 @@ #include "components/app_restore/app_launch_info.h" #include "components/app_restore/full_restore_save_handler.h" #include "components/app_restore/full_restore_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/sessions/core/session_id.h" @@ -47,7 +48,7 @@ params.intent); std::string app_id = params.app_id; apps::mojom::LaunchSource launch_source = params.launch_source; - apps::mojom::LaunchContainer container = params.container; + apps::LaunchContainer container = params.container; int restore_id = params.restore_id; // Create the FullRestoreSaveHandler instance before launching the app to
diff --git a/chrome/browser/apps/app_service/launch_utils.cc b/chrome/browser/apps/app_service/launch_utils.cc index 7913d042..f9cedb3 100644 --- a/chrome/browser/apps/app_service/launch_utils.cc +++ b/chrome/browser/apps/app_service/launch_utils.cc
@@ -53,30 +53,30 @@ // we cannot use mojom traits for crosapi::mojom::LaunchParams yet. Move to auto // mapping when the AppService Intent struct is converted to use FilePaths. crosapi::mojom::LaunchContainer ConvertAppServiceToCrosapiLaunchContainer( - apps::mojom::LaunchContainer input) { + apps::LaunchContainer input) { switch (input) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerWindow: return crosapi::mojom::LaunchContainer::kLaunchContainerWindow; - case apps::mojom::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerTab: return crosapi::mojom::LaunchContainer::kLaunchContainerTab; - case apps::mojom::LaunchContainer::kLaunchContainerNone: + case apps::LaunchContainer::kLaunchContainerNone: return crosapi::mojom::LaunchContainer::kLaunchContainerNone; - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: NOTREACHED(); return crosapi::mojom::LaunchContainer::kLaunchContainerNone; } NOTREACHED(); } -apps::mojom::LaunchContainer ConvertCrosapiToAppServiceLaunchContainer( +apps::LaunchContainer ConvertCrosapiToAppServiceLaunchContainer( crosapi::mojom::LaunchContainer input) { switch (input) { case crosapi::mojom::LaunchContainer::kLaunchContainerWindow: - return apps::mojom::LaunchContainer::kLaunchContainerWindow; + return apps::LaunchContainer::kLaunchContainerWindow; case crosapi::mojom::LaunchContainer::kLaunchContainerTab: - return apps::mojom::LaunchContainer::kLaunchContainerTab; + return apps::LaunchContainer::kLaunchContainerTab; case crosapi::mojom::LaunchContainer::kLaunchContainerNone: - return apps::mojom::LaunchContainer::kLaunchContainerNone; + return apps::LaunchContainer::kLaunchContainerNone; } NOTREACHED(); } @@ -126,16 +126,16 @@ NOTREACHED(); } -apps::mojom::LaunchContainer ConvertWindowModeToAppLaunchContainer( +apps::LaunchContainer ConvertWindowModeToAppLaunchContainer( apps::WindowMode window_mode) { switch (window_mode) { case apps::WindowMode::kBrowser: - return apps::mojom::LaunchContainer::kLaunchContainerTab; + return apps::LaunchContainer::kLaunchContainerTab; case apps::WindowMode::kWindow: case apps::WindowMode::kTabbedWindow: - return apps::mojom::LaunchContainer::kLaunchContainerWindow; + return apps::LaunchContainer::kLaunchContainerWindow; case apps::WindowMode::kUnknown: - return apps::mojom::LaunchContainer::kLaunchContainerNone; + return apps::LaunchContainer::kLaunchContainerNone; } } @@ -190,18 +190,18 @@ int event_flags, apps::mojom::LaunchSource launch_source, int64_t display_id, - apps::mojom::LaunchContainer fallback_container) { + apps::LaunchContainer fallback_container) { WindowOpenDisposition raw_disposition = ui::DispositionFromEventFlags(event_flags); - apps::mojom::LaunchContainer container; + apps::LaunchContainer container; WindowOpenDisposition disposition; if (raw_disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB || raw_disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) { - container = apps::mojom::LaunchContainer::kLaunchContainerTab; + container = apps::LaunchContainer::kLaunchContainerTab; disposition = raw_disposition; } else if (raw_disposition == WindowOpenDisposition::NEW_WINDOW) { - container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + container = apps::LaunchContainer::kLaunchContainerWindow; disposition = raw_disposition; } else { // Look at preference to find the right launch container. If no preference @@ -218,7 +218,7 @@ int32_t event_flags, apps::mojom::LaunchSource launch_source, int64_t display_id, - apps::mojom::LaunchContainer fallback_container, + apps::LaunchContainer fallback_container, apps::mojom::IntentPtr&& intent, Profile* profile) { auto params = CreateAppIdLaunchParamsWithEventFlags(
diff --git a/chrome/browser/apps/app_service/launch_utils.h b/chrome/browser/apps/app_service/launch_utils.h index 8d3da55..4b9fb58 100644 --- a/chrome/browser/apps/app_service/launch_utils.h +++ b/chrome/browser/apps/app_service/launch_utils.h
@@ -11,6 +11,7 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/app_service/app_launch_params.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "extensions/common/constants.h" #include "ui/base/window_open_disposition.h" @@ -56,14 +57,14 @@ int event_flags, apps::mojom::LaunchSource source, int64_t display_id, - apps::mojom::LaunchContainer fallback_container); + apps::LaunchContainer fallback_container); apps::AppLaunchParams CreateAppLaunchParamsForIntent( const std::string& app_id, int32_t event_flags, apps::mojom::LaunchSource source, int64_t display_id, - apps::mojom::LaunchContainer fallback_container, + apps::LaunchContainer fallback_container, apps::mojom::IntentPtr&& intent, Profile* profile);
diff --git a/chrome/browser/apps/app_service/launch_utils_unittest.cc b/chrome/browser/apps/app_service/launch_utils_unittest.cc index b834522..7cf035d7 100644 --- a/chrome/browser/apps/app_service/launch_utils_unittest.cc +++ b/chrome/browser/apps/app_service/launch_utils_unittest.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/testing_profile.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "content/public/test/browser_task_environment.h" @@ -21,12 +22,12 @@ class LaunchUtilsTest : public testing::Test { protected: apps::AppLaunchParams CreateLaunchParams( - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, bool preferred_container, int64_t display_id = display::kInvalidDisplayId, - apps::mojom::LaunchContainer fallback_container = - apps::mojom::LaunchContainer::kLaunchContainerNone) { + apps::LaunchContainer fallback_container = + apps::LaunchContainer::kLaunchContainerNone) { return apps::CreateAppIdLaunchParamsWithEventFlags( app_id, apps::GetEventFlags(disposition, preferred_container), apps::mojom::LaunchSource::kFromChromeInternal, display_id, @@ -39,7 +40,7 @@ }; TEST_F(LaunchUtilsTest, WindowContainerAndWindowDisposition) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto container = apps::LaunchContainer::kLaunchContainerWindow; auto disposition = WindowOpenDisposition::NEW_WINDOW; auto params = CreateLaunchParams(container, disposition, false); @@ -48,7 +49,7 @@ } TEST_F(LaunchUtilsTest, TabContainerAndForegoundTabDisposition) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerTab; + auto container = apps::LaunchContainer::kLaunchContainerTab; auto disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; auto params = CreateLaunchParams(container, disposition, false); @@ -57,7 +58,7 @@ } TEST_F(LaunchUtilsTest, TabContainerAndBackgoundTabDisposition) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerTab; + auto container = apps::LaunchContainer::kLaunchContainerTab; auto disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; auto params = CreateLaunchParams(container, disposition, false); @@ -66,10 +67,9 @@ } TEST_F(LaunchUtilsTest, PreferContainerWithTab) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerNone; + auto container = apps::LaunchContainer::kLaunchContainerNone; auto disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; - auto preferred_container = - apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto preferred_container = apps::LaunchContainer::kLaunchContainerWindow; auto params = CreateLaunchParams(container, disposition, true, display::kInvalidDisplayId, preferred_container); @@ -79,10 +79,9 @@ } TEST_F(LaunchUtilsTest, PreferContainerWithWindow) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerNone; + auto container = apps::LaunchContainer::kLaunchContainerNone; auto disposition = WindowOpenDisposition::NEW_WINDOW; - auto preferred_container = - apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto preferred_container = apps::LaunchContainer::kLaunchContainerWindow; auto params = CreateLaunchParams(container, disposition, true, display::kInvalidDisplayId, preferred_container); @@ -100,9 +99,8 @@ auto params = apps::CreateAppLaunchParamsForIntent( app_id, apps::GetEventFlags(disposition, true), apps::mojom::LaunchSource::kFromChromeInternal, - display::kInvalidDisplayId, - apps::mojom::LaunchContainer::kLaunchContainerWindow, std::move(intent), - &profile_); + display::kInvalidDisplayId, apps::LaunchContainer::kLaunchContainerWindow, + std::move(intent), &profile_); EXPECT_EQ(url, params.override_url); } @@ -122,9 +120,8 @@ auto params = apps::CreateAppLaunchParamsForIntent( app_id, apps::GetEventFlags(disposition, true), apps::mojom::LaunchSource::kFromChromeInternal, - display::kInvalidDisplayId, - apps::mojom::LaunchContainer::kLaunchContainerWindow, std::move(intent), - &profile_); + display::kInvalidDisplayId, apps::LaunchContainer::kLaunchContainerWindow, + std::move(intent), &profile_); #if BUILDFLAG(IS_CHROMEOS_ASH) ASSERT_EQ(params.launch_files.size(), 1U); @@ -207,7 +204,7 @@ // Verifies that convert params (with no override url, intent, files) to crosapi // and back works. TEST_F(LaunchUtilsTest, ConvertToCrosapi) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto container = apps::LaunchContainer::kLaunchContainerWindow; auto disposition = WindowOpenDisposition::NEW_WINDOW; const int64_t kDisplayId = 1; auto params = CreateLaunchParams(container, disposition, false, kDisplayId); @@ -224,7 +221,7 @@ // Verifies that convert params with override url to crosapi and back works. TEST_F(LaunchUtilsTest, ConvertToCrosapiUrl) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto container = apps::LaunchContainer::kLaunchContainerWindow; auto disposition = WindowOpenDisposition::NEW_WINDOW; const int64_t kDisplayId = 2; auto params = CreateLaunchParams(container, disposition, false, kDisplayId); @@ -243,7 +240,7 @@ // Verifies that convert params with files to crosapi and back works. TEST_F(LaunchUtilsTest, ConvertToCrosapiFiles) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto container = apps::LaunchContainer::kLaunchContainerWindow; auto disposition = WindowOpenDisposition::NEW_WINDOW; const int64_t kDisplayId = 3; auto params = CreateLaunchParams(container, disposition, false, kDisplayId); @@ -262,7 +259,7 @@ // Verifies that convert params with intent to crosapi and back works. TEST_F(LaunchUtilsTest, ConvertToCrosapiIntent) { - auto container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto container = apps::LaunchContainer::kLaunchContainerWindow; auto disposition = WindowOpenDisposition::NEW_WINDOW; const int64_t kDisplayId = 4; auto params = CreateLaunchParams(container, disposition, false, kDisplayId); @@ -289,7 +286,7 @@ auto converted_params = apps::ConvertCrosapiToLaunchParams(params, &profile_); EXPECT_EQ(params->app_id, converted_params.app_id); - EXPECT_EQ(apps::mojom::LaunchContainer::kLaunchContainerNone, + EXPECT_EQ(apps::LaunchContainer::kLaunchContainerNone, converted_params.container); EXPECT_EQ(WindowOpenDisposition::UNKNOWN, converted_params.disposition); EXPECT_EQ(apps::mojom::LaunchSource::kFromIntentUrl, @@ -330,7 +327,7 @@ apps::ConvertCrosapiToLaunchParams(crosapi_params, &profile_); EXPECT_EQ(converted_params.container, - apps::mojom::LaunchContainer::kLaunchContainerWindow); + apps::LaunchContainer::kLaunchContainerWindow); EXPECT_EQ(converted_params.disposition, WindowOpenDisposition::NEW_FOREGROUND_TAB); EXPECT_EQ(converted_params.launch_source,
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics.cc b/chrome/browser/apps/app_service/metrics/app_platform_metrics.cc index 2b85f3cc..49c1f3bb9 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics.cc +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics.cc
@@ -162,7 +162,7 @@ apps::AppTypeNameV2 GetAppTypeNameV2(Profile* profile, apps::AppType app_type, const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { switch (app_type) { case apps::AppType::kUnknown: return apps::AppTypeNameV2::kUnknown; @@ -173,7 +173,7 @@ case apps::AppType::kCrostini: return apps::AppTypeNameV2::kCrostini; case apps::AppType::kChromeApp: - return container == apps::mojom::LaunchContainer::kLaunchContainerWindow + return container == apps::LaunchContainer::kLaunchContainerWindow ? apps::AppTypeNameV2::kChromeAppWindow : apps::AppTypeNameV2::kChromeAppTab; case apps::AppType::kWeb: { @@ -326,7 +326,7 @@ AppType app_type, const std::string& app_id, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { if (app_type == AppType::kUnknown) { return; } @@ -636,7 +636,7 @@ AppType app_type, const std::string& app_id, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { if (app_type == AppType::kUnknown || !ShouldRecordUkm(profile_)) { return; } @@ -661,9 +661,8 @@ AppType app_type, const std::string& app_id, apps::mojom::UninstallSource uninstall_source) { - AppTypeName app_type_name = - GetAppTypeName(profile_, app_type, app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone); + AppTypeName app_type_name = GetAppTypeName( + profile_, app_type, app_id, apps::LaunchContainer::kLaunchContainerNone); ukm::SourceId source_id = GetSourceId(profile_, app_id); if (source_id == ukm::kInvalidSourceId) { @@ -959,7 +958,7 @@ AppTypeName app_type_name = GetAppTypeName(profile_, update.AppType(), update.AppId(), - apps::mojom::LaunchContainer::kLaunchContainerNone); + apps::LaunchContainer::kLaunchContainerNone); if (app_type_name == AppTypeName::kChromeBrowser || app_type_name == AppTypeName::kUnknown) { @@ -1103,7 +1102,7 @@ InstallTime install_time) { AppTypeName app_type_name = GetAppTypeName(profile_, update.AppType(), update.AppId(), - apps::mojom::LaunchContainer::kLaunchContainerNone); + apps::LaunchContainer::kLaunchContainerNone); ukm::SourceId source_id = GetSourceId(profile_, update.AppId()); if (source_id == ukm::kInvalidSourceId) {
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics.h b/chrome/browser/apps/app_service/metrics/app_platform_metrics.h index 95a75c26..8723cbc0 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics.h +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics.h
@@ -13,6 +13,7 @@ #include "base/unguessable_token.h" #include "chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.h" #include "chrome/browser/apps/app_service/metrics/browser_to_tab_list.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/instance_registry.h" @@ -60,7 +61,7 @@ AppType app_type, const std::string& app_id, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); class AppPlatformMetrics : public apps::AppRegistryCache::Observer, public apps::InstanceRegistry::Observer { @@ -127,7 +128,7 @@ void RecordAppLaunchUkm(AppType app_type, const std::string& app_id, apps::mojom::LaunchSource launch_source, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); // Records UKM when uninstalling an app. void RecordAppUninstallUkm(AppType app_type,
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics_browsertest.cc b/chrome/browser/apps/app_service/metrics/app_platform_metrics_browsertest.cc index 7d254b4d..b11c7e66 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics_browsertest.cc +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics_browsertest.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/web_applications/web_app_install_info.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_test.h" #include "third_party/blink/public/mojom/manifest/display_mode.mojom.h" @@ -46,13 +47,12 @@ } apps::AppTypeName GetWebAppTypeName(const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { return GetAppTypeName(profile(), apps::AppType::kWeb, app_id, container); } - apps::AppTypeName GetSystemWebAppTypeName( - const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::AppTypeName GetSystemWebAppTypeName(const std::string& app_id, + apps::LaunchContainer container) { return GetAppTypeName(profile(), apps::AppType::kSystemWeb, app_id, container); } @@ -67,54 +67,45 @@ apps::AppServiceProxyFactory::GetForProfile(profile()) ->FlushMojoCallsForTesting(); - EXPECT_EQ( - GetWebAppTypeName(system_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetWebAppTypeName(system_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kSystemWeb); - EXPECT_EQ( - GetSystemWebAppTypeName( - system_app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetSystemWebAppTypeName( + system_app_id, apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kSystemWeb); - EXPECT_EQ( - GetWebAppTypeName(system_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetWebAppTypeName(system_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kSystemWeb); - EXPECT_EQ( - GetSystemWebAppTypeName( - system_app_id, apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetSystemWebAppTypeName(system_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kSystemWeb); - EXPECT_EQ( - GetWebAppTypeName(system_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetWebAppTypeName(system_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kSystemWeb); - EXPECT_EQ( - GetSystemWebAppTypeName( - system_app_id, apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kSystemWeb); + EXPECT_EQ(GetSystemWebAppTypeName( + system_app_id, apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kSystemWeb); } IN_PROC_BROWSER_TEST_F(AppPlatformMetricsBrowserTest, UnknownWebApp) { const AppId unknown_app_id = "unknown"; - EXPECT_EQ( - GetWebAppTypeName(unknown_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(unknown_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kChromeBrowser); - EXPECT_EQ( - GetWebAppTypeName(unknown_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(unknown_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kChromeBrowser); - EXPECT_EQ( - GetWebAppTypeName(unknown_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(unknown_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kChromeBrowser); } IN_PROC_BROWSER_TEST_F(AppPlatformMetricsBrowserTest, WindowedWebApps) { @@ -133,38 +124,32 @@ // When container is specified, |user_display_mode| and |display_mode| are // ignored. - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kWeb); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kWeb); - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kChromeBrowser); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kChromeBrowser); // For a web app with no container given, |user_display_mode| kStandalone // leads to |AppTypeName::kWeb|. - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kWeb); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kWeb); } IN_PROC_BROWSER_TEST_F(AppPlatformMetricsBrowserTest, TabbedWebApps) { @@ -183,36 +168,30 @@ // When container is specified, |user_display_mode| and |display_mode| are // ignored. - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kWeb); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow), - apps::AppTypeName::kWeb); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerWindow), + apps::AppTypeName::kWeb); - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kChromeBrowser); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerTab), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerTab), + apps::AppTypeName::kChromeBrowser); // For a web app with no container given, |user_display_mode| kBrowser leads // to |AppTypeName::kChromeBrowser|. - EXPECT_EQ( - GetWebAppTypeName(standalone_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(standalone_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kChromeBrowser); - EXPECT_EQ( - GetWebAppTypeName(browser_app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone), - apps::AppTypeName::kChromeBrowser); + EXPECT_EQ(GetWebAppTypeName(browser_app_id, + apps::LaunchContainer::kLaunchContainerNone), + apps::AppTypeName::kChromeBrowser); }
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc b/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc index ca3ea385..e24adbbe 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc
@@ -41,6 +41,7 @@ #include "components/app_constants/constants.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/instance_registry.h" @@ -2149,8 +2150,7 @@ // TODO(crbug.com/1253250): Register non-mojom apps and use // AppServiceProxy::LaunchAppWithParams to test launching. proxy->BrowserAppLauncher()->LaunchAppWithParamsForTesting( - apps::AppLaunchParams("w2", - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::AppLaunchParams("w2", apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, apps::mojom::LaunchSource::kFromTest)); if (IsLacrosPrimary()) { @@ -2169,8 +2169,7 @@ : AppTypeNameV2::kWebTab); proxy->BrowserAppLauncher()->LaunchAppWithParamsForTesting( - apps::AppLaunchParams("s", - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::AppLaunchParams("s", apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, apps::mojom::LaunchSource::kFromTest)); VerifyAppsLaunchUkm("app://s", AppTypeName::kSystemWeb,
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.cc b/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.cc index 37f36f8a..4f84294 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.cc +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.cc
@@ -27,6 +27,7 @@ #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "components/app_constants/constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/instance_registry.h" #include "components/services/app_service/public/cpp/instance_update.h" #include "components/sync/base/model_type.h" @@ -65,10 +66,9 @@ // Determines what app type a Chrome App should be logged as based on its launch // container and app id. In particular, Chrome apps in tabs are logged as part // of Chrome browser. -apps::AppTypeName GetAppTypeNameForChromeApp( - Profile* profile, - const std::string& app_id, - apps::mojom::LaunchContainer container) { +apps::AppTypeName GetAppTypeNameForChromeApp(Profile* profile, + const std::string& app_id, + apps::LaunchContainer container) { if (app_id == app_constants::kChromeAppId) { return apps::AppTypeName::kChromeBrowser; } @@ -89,18 +89,17 @@ } switch (container) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerWindow: return apps::AppTypeName::kChromeApp; - case apps::mojom::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerTab: return apps::AppTypeName::kChromeBrowser; default: break; } - apps::mojom::LaunchContainer launch_container = - extensions::GetLaunchContainer(extensions::ExtensionPrefs::Get(profile), - extension); - if (launch_container == apps::mojom::LaunchContainer::kLaunchContainerTab) { + apps::LaunchContainer launch_container = extensions::GetLaunchContainer( + extensions::ExtensionPrefs::Get(profile), extension); + if (launch_container == apps::LaunchContainer::kLaunchContainerTab) { return apps::AppTypeName::kChromeBrowser; } @@ -124,7 +123,7 @@ AppTypeName GetAppTypeNameForWebApp(Profile* profile, const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { AppTypeName default_type_name = web_app::IsWebAppsCrosapiEnabled() ? AppTypeName::kStandaloneBrowser : AppTypeName::kChromeBrowser; @@ -149,9 +148,9 @@ } switch (container) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerWindow: return GetWebAppTypeName(); - case apps::mojom::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerTab: return default_type_name; default: break; @@ -164,7 +163,7 @@ AppTypeName GetAppTypeNameForStandaloneBrowserChromeApp( Profile* profile, const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { AppTypeName app_type_name = AppTypeName::kStandaloneBrowser; WindowMode window_mode = WindowMode::kUnknown; AppServiceProxyFactory::GetForProfile(profile)->AppRegistryCache().ForOneApp( @@ -185,12 +184,12 @@ } switch (container) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerWindow: return AppTypeName::kStandaloneBrowserChromeApp; - case apps::mojom::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerTab: return AppTypeName::kStandaloneBrowser; - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: - case apps::mojom::LaunchContainer::kLaunchContainerNone: + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: + case apps::LaunchContainer::kLaunchContainerNone: break; } return window_mode == WindowMode::kWindow || @@ -267,9 +266,8 @@ return AppTypeName::kChromeBrowser; } - if (GetAppTypeNameForWebApp( - profile, app_id, - apps::mojom::LaunchContainer::kLaunchContainerNone) == + if (GetAppTypeNameForWebApp(profile, app_id, + apps::LaunchContainer::kLaunchContainerNone) == AppTypeName::kSystemWeb) { return AppTypeName::kSystemWeb; } @@ -422,7 +420,7 @@ AppTypeName GetAppTypeName(Profile* profile, AppType app_type, const std::string& app_id, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { switch (app_type) { case AppType::kUnknown: return apps::AppTypeName::kUnknown;
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.h b/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.h index b1bcc80..3fc9688 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.h +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics_utils.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_APPS_APP_SERVICE_METRICS_APP_PLATFORM_METRICS_UTILS_H_ #include "base/time/time.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -119,7 +120,7 @@ // Chrome browser. AppTypeName GetAppTypeNameForWebApp(Profile* profile, const std::string& app_id, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); // Determines what app type a chrome app in Lacros should be logged as based on // its launch container and app id. In particular, chrome apps in Lacros tabs @@ -127,7 +128,7 @@ AppTypeName GetAppTypeNameForStandaloneBrowserChromeApp( Profile* profile, const std::string& app_id, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); // Returns false if |window| is a Chrome app window or a standalone web app // window. Otherwise, return true. @@ -188,7 +189,7 @@ AppTypeName GetAppTypeName(Profile* profile, AppType app_type, const std::string& app_id, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); // Gets the app type of a given app_id. Checks multiple sources, not just the // app registry cache, so can identify apps which aren't registered with app
diff --git a/chrome/browser/apps/app_service/publishers/borealis_apps.cc b/chrome/browser/apps/app_service/publishers/borealis_apps.cc index 158ea1cc..50936639 100644 --- a/chrome/browser/apps/app_service/publishers/borealis_apps.cc +++ b/chrome/browser/apps/app_service/publishers/borealis_apps.cc
@@ -178,6 +178,15 @@ anonymous_app_observation_.Observe( &borealis::BorealisService::GetForProfile(profile_)->WindowManager()); + pref_registrar_.Init(profile_->GetPrefs()); + + for (const PermissionInfo& info : permission_infos) { + pref_registrar_.Add( + info.pref_name, + base::BindRepeating(&apps::BorealisApps::OnPermissionChanged, + base::Unretained(this))); + } + // TODO(b/170264723): When uninstalling borealis is completed, ensure that we // remove the apps from the apps service. } @@ -427,6 +436,18 @@ } } +void BorealisApps::OnPermissionChanged() { + apps::mojom::AppPtr mojom_app = apps::mojom::App::New(); + mojom_app->app_type = apps::mojom::AppType::kBorealis; + mojom_app->app_id = borealis::kClientAppId; + PopulatePermissions(mojom_app.get(), profile_); + PublisherBase::Publish(std::move(mojom_app), subscribers_); + + auto app = std::make_unique<App>(AppType::kBorealis, borealis::kClientAppId); + app->permissions = CreatePermissions(profile_); + AppPublisher::Publish(std::move(app)); +} + void BorealisApps::OnAnonymousAppAdded(const std::string& shelf_app_id, const std::string& shelf_app_name) { apps::mojom::AppPtr mojom_app = apps::PublisherBase::MakeApp(
diff --git a/chrome/browser/apps/app_service/publishers/borealis_apps.h b/chrome/browser/apps/app_service/publishers/borealis_apps.h index 4116a8d..4f0392de 100644 --- a/chrome/browser/apps/app_service/publishers/borealis_apps.h +++ b/chrome/browser/apps/app_service/publishers/borealis_apps.h
@@ -15,6 +15,7 @@ #include "chrome/browser/apps/app_service/publishers/app_publisher.h" #include "chrome/browser/ash/borealis/borealis_window_manager.h" #include "chrome/browser/ash/guest_os/guest_os_registry_service.h" +#include "components/prefs/pref_change_registrar.h" #include "components/services/app_service/public/cpp/publisher_base.h" #include "components/services/app_service/public/mojom/app_service.mojom.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -103,6 +104,7 @@ const std::vector<std::string>& updated_apps, const std::vector<std::string>& removed_apps, const std::vector<std::string>& inserted_apps) override; + void OnPermissionChanged(); // borealis::BorealisWindowManager::AnonymousAppObserver overrides. void OnAnonymousAppAdded(const std::string& shelf_app_id, @@ -120,6 +122,8 @@ base::ScopedObservation<borealis::BorealisWindowManager, borealis::BorealisWindowManager::AnonymousAppObserver> anonymous_app_observation_{this}; + + PrefChangeRegistrar pref_registrar_; }; } // namespace apps
diff --git a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps.cc b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps.cc index 19e1029..ee54fab4 100644 --- a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps.cc +++ b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps.cc
@@ -25,6 +25,7 @@ #include "components/app_restore/app_launch_info.h" #include "components/app_restore/features.h" #include "components/app_restore/full_restore_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -187,7 +188,7 @@ if (ShouldSaveToFullRestore(proxy(), app_id)) { auto launch_info = std::make_unique<app_restore::AppLaunchInfo>( - app_id, apps::mojom::LaunchContainer::kLaunchContainerNone, + app_id, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::UNKNOWN, display::kInvalidDisplayId, std::vector<base::FilePath>{}, nullptr); full_restore::SaveAppLaunchInfo(proxy()->profile()->GetPath(), @@ -220,7 +221,7 @@ if (ShouldSaveToFullRestore(proxy(), app_id)) { auto launch_info = std::make_unique<app_restore::AppLaunchInfo>( - app_id, apps::mojom::LaunchContainer::kLaunchContainerNone, + app_id, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::UNKNOWN, display::kInvalidDisplayId, std::vector<base::FilePath>{}, apps::ConvertMojomIntentToIntent(intent)); @@ -249,7 +250,7 @@ if (ShouldSaveToFullRestore(proxy(), app_id)) { auto launch_info = std::make_unique<app_restore::AppLaunchInfo>( - app_id, apps::mojom::LaunchContainer::kLaunchContainerNone, + app_id, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::UNKNOWN, display::kInvalidDisplayId, std::move(file_paths->file_paths), nullptr); full_restore::SaveAppLaunchInfo(proxy()->profile()->GetPath(),
diff --git a/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac.cc b/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac.cc index 6ff822a..d5d3e0b 100644 --- a/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac.cc +++ b/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "chrome/common/chrome_switches.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "net/base/filename_util.h" #include "third_party/blink/public/common/custom_handlers/protocol_handler_utils.h" @@ -219,7 +220,7 @@ ->registrar() .GetAppEffectiveDisplayMode(app_id); - apps::mojom::LaunchContainer launch_container = + apps::LaunchContainer launch_container = web_app::ConvertDisplayModeToAppLaunchContainer(effective_display_mode); apps::mojom::LaunchSource launch_source = apps::mojom::LaunchSource::kFromCommandLine;
diff --git a/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac_unittest.cc b/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac_unittest.cc index 4fe745f..5ebb82380 100644 --- a/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac_unittest.cc +++ b/chrome/browser/apps/app_shim/web_app_shim_manager_delegate_mac_unittest.cc
@@ -141,10 +141,10 @@ const absl::optional<GURL>& url_handler_launch_url, const absl::optional<GURL>& protocol_handler_launch_url, const GURL& override_url) { - apps::AppLaunchParams params( - app_id_, apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromCommandLine); + apps::AppLaunchParams params(app_id_, + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromCommandLine); params.launch_files = launch_files; params.url_handler_launch_url = url_handler_launch_url;
diff --git a/chrome/browser/apps/platform_apps/BUILD.gn b/chrome/browser/apps/platform_apps/BUILD.gn index b3b61dc..1638236 100644 --- a/chrome/browser/apps/platform_apps/BUILD.gn +++ b/chrome/browser/apps/platform_apps/BUILD.gn
@@ -65,6 +65,7 @@ "//components/navigation_interception", "//components/no_state_prefetch/browser", "//components/pref_registry", + "//components/services/app_service/public/cpp:app_types", "//components/services/app_service/public/mojom", "//content/public/browser", "//content/public/common",
diff --git a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_apitest.cc b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_apitest.cc index 890d0014..0278739 100644 --- a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_apitest.cc +++ b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_apitest.cc
@@ -32,6 +32,7 @@ #include "chrome/browser/media_galleries/media_galleries_test_util.h" #include "chrome/common/chrome_paths.h" #include "components/nacl/common/buildflags.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/storage_monitor/storage_info.h" #include "components/storage_monitor/storage_monitor.h" #include "content/public/browser/web_contents.h" @@ -278,7 +279,7 @@ extensions::ResultCatcher catcher; apps::AppLaunchParams params( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); params.command_line = *base::CommandLine::ForCurrentProcess(); apps::AppServiceProxyFactory::GetForProfile(browser()->profile())
diff --git a/chrome/browser/apps/platform_apps/app_browsertest.cc b/chrome/browser/apps/platform_apps/app_browsertest.cc index 88d4fd2f..45d7a53 100644 --- a/chrome/browser/apps/platform_apps/app_browsertest.cc +++ b/chrome/browser/apps/platform_apps/app_browsertest.cc
@@ -46,6 +46,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/host_zoom_map.h" @@ -267,10 +268,10 @@ return false; } - apps::AppLaunchParams params( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromTest); + apps::AppLaunchParams params(extension->id(), + apps::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromTest); params.command_line = command_line; params.current_directory = test_data_dir_; apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) @@ -949,7 +950,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); app_loaded_observer.Wait(); @@ -1100,7 +1101,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); @@ -1125,7 +1126,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); @@ -1166,7 +1167,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); @@ -1194,7 +1195,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
diff --git a/chrome/browser/apps/platform_apps/app_browsertest_util.cc b/chrome/browser/apps/platform_apps/app_browsertest_util.cc index f78d854..9bb5cb9 100644 --- a/chrome/browser/apps/platform_apps/app_browsertest_util.cc +++ b/chrome/browser/apps/platform_apps/app_browsertest_util.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/ui/apps/chrome_app_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/extensions/app_launch_params.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/test/browser_test_utils.h" @@ -161,7 +162,7 @@ apps::AppServiceProxyFactory::GetForProfile(profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); }
diff --git a/chrome/browser/apps/platform_apps/app_window_browsertest.cc b/chrome/browser/apps/platform_apps/app_window_browsertest.cc index b13fb08..f01ee52 100644 --- a/chrome/browser/apps/platform_apps/app_window_browsertest.cc +++ b/chrome/browser/apps/platform_apps/app_window_browsertest.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/test/browser_test.h" @@ -232,7 +233,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest));
diff --git a/chrome/browser/apps/platform_apps/platform_app_launch.cc b/chrome/browser/apps/platform_apps/platform_app_launch.cc index 10f4cd2..b78bfd3 100644 --- a/chrome/browser/apps/platform_apps/platform_app_launch.cc +++ b/chrome/browser/apps/platform_apps/platform_app_launch.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_metrics.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" @@ -38,7 +39,7 @@ bool GetAppLaunchContainer(Profile* profile, const std::string& app_id, const extensions::Extension** out_app, - apps::mojom::LaunchContainer* out_launch_container) { + apps::LaunchContainer* out_launch_container) { const extensions::Extension* app = extensions::ExtensionRegistry::Get(profile)->enabled_extensions().GetByID( app_id); @@ -52,9 +53,8 @@ // Look at preferences to find the right launch container. If no // preference is set, launch as a window. - apps::mojom::LaunchContainer launch_container = - extensions::GetLaunchContainer(extensions::ExtensionPrefs::Get(profile), - app); + apps::LaunchContainer launch_container = extensions::GetLaunchContainer( + extensions::ExtensionPrefs::Get(profile), app); *out_app = app; *out_launch_container = launch_container; @@ -80,12 +80,12 @@ const std::string& app_id, const base::CommandLine& command_line, const base::FilePath& current_directory) { - apps::mojom::LaunchContainer launch_container; + LaunchContainer launch_container; const extensions::Extension* app; if (!GetAppLaunchContainer(profile, app_id, &app, &launch_container)) return false; - if (launch_container == apps::mojom::LaunchContainer::kLaunchContainerTab) + if (launch_container == LaunchContainer::kLaunchContainerTab) return false; RecordCmdLineAppHistogram(app->GetType()); @@ -104,22 +104,22 @@ } bool OpenExtensionApplicationTab(Profile* profile, const std::string& app_id) { - apps::mojom::LaunchContainer launch_container; + apps::LaunchContainer launch_container; const extensions::Extension* app; if (!GetAppLaunchContainer(profile, app_id, &app, &launch_container)) return false; // If the user doesn't want to open a tab, fail. - if (launch_container != apps::mojom::LaunchContainer::kLaunchContainerTab) + if (launch_container != apps::LaunchContainer::kLaunchContainerTab) return false; RecordCmdLineAppHistogram(app->GetType()); content::WebContents* app_tab = ::OpenApplication( - profile, apps::AppLaunchParams( - app_id, apps::mojom::LaunchContainer::kLaunchContainerTab, - WindowOpenDisposition::NEW_FOREGROUND_TAB, - apps::mojom::LaunchSource::kFromCommandLine)); + profile, + apps::AppLaunchParams(app_id, apps::LaunchContainer::kLaunchContainerTab, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + apps::mojom::LaunchSource::kFromCommandLine)); return app_tab != nullptr; } @@ -162,10 +162,10 @@ return false; RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP); - apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromCommandLine); + apps::AppLaunchParams params(app_id, + apps::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromCommandLine); params.command_line = command_line; params.current_directory = current_directory; ::OpenApplicationWithReenablePrompt(profile, std::move(params));
diff --git a/chrome/browser/ash/app_restore/app_launch_handler.cc b/chrome/browser/ash/app_restore/app_launch_handler.cc index d53ac16f..6342934 100644 --- a/chrome/browser/ash/app_restore/app_launch_handler.cc +++ b/chrome/browser/ash/app_restore/app_launch_handler.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/profiles/profile.h" #include "components/app_constants/constants.h" #include "components/app_restore/full_restore_read_handler.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/types_util.h" #include "extensions/browser/extension_registry.h" @@ -248,7 +249,7 @@ apps::AppLaunchParams params( app_id, - static_cast<apps::mojom::LaunchContainer>(it.second->container.value()), + static_cast<apps::LaunchContainer>(it.second->container.value()), static_cast<WindowOpenDisposition>(it.second->disposition.value()), apps::mojom::LaunchSource::kFromFullRestore, it.second->display_id.value(),
diff --git a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc index bc7fdee..8952909 100644 --- a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc +++ b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc
@@ -61,6 +61,7 @@ #include "components/exo/test/shell_surface_builder.h" #include "components/exo/wm_helper_chromeos.h" #include "components/prefs/pref_registry_simple.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -282,7 +283,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); } @@ -362,8 +363,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -391,8 +391,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); CreateAndSaveWindowInfo( @@ -429,8 +428,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -477,8 +475,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -512,8 +509,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -730,8 +726,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -799,8 +794,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -832,8 +826,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<::app_restore::AppLaunchInfo>( - kAppId, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId, kWindowId2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr));
diff --git a/chrome/browser/ash/child_accounts/time_limits/app_time_controller.cc b/chrome/browser/ash/child_accounts/time_limits/app_time_controller.cc index 98f4d1c..edc4f08 100644 --- a/chrome/browser/ash/child_accounts/time_limits/app_time_controller.cc +++ b/chrome/browser/ash/child_accounts/time_limits/app_time_controller.cc
@@ -38,6 +38,7 @@ #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" @@ -175,10 +176,9 @@ if (!extension) return false; - apps::mojom::LaunchContainer launch_container = - extensions::GetLaunchContainer(extensions::ExtensionPrefs::Get(profile), - extension); - return launch_container == apps::mojom::LaunchContainer::kLaunchContainerTab; + apps::LaunchContainer launch_container = extensions::GetLaunchContainer( + extensions::ExtensionPrefs::Get(profile), extension); + return launch_container == apps::LaunchContainer::kLaunchContainerTab; } } // namespace
diff --git a/chrome/browser/ash/crosapi/vpn_extension_observer_ash_browsertest.cc b/chrome/browser/ash/crosapi/vpn_extension_observer_ash_browsertest.cc index 582971a..2c5922f 100644 --- a/chrome/browser/ash/crosapi/vpn_extension_observer_ash_browsertest.cc +++ b/chrome/browser/ash/crosapi/vpn_extension_observer_ash_browsertest.cc
@@ -87,7 +87,9 @@ mojo::Remote<cros_network::mojom::CrosNetworkConfig> cros_network_config_; }; -IN_PROC_BROWSER_TEST_F(VpnExtensionObserverBrowserTest, LoadVpnExtension) { +// TODO(1339457): This test is flaky. +IN_PROC_BROWSER_TEST_F(VpnExtensionObserverBrowserTest, + DISABLED_LoadVpnExtension) { if (!ash_starter_.HasLacrosArgument()) { return; }
diff --git a/chrome/browser/ash/file_manager/file_manager_jstest.cc b/chrome/browser/ash/file_manager/file_manager_jstest.cc index e5fa4ef..bb4fff6c 100644 --- a/chrome/browser/ash/file_manager/file_manager_jstest.cc +++ b/chrome/browser/ash/file_manager/file_manager_jstest.cc
@@ -302,3 +302,7 @@ IN_PROC_BROWSER_TEST_F(FileManagerJsTest, XfBreadcrumbs) { RunTestURL("widgets/xf_breadcrumbs_unittest.js"); } + +IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FileGridTest) { + RunTestURL("foreground/js/ui/file_grid_unittest.js"); +}
diff --git a/chrome/browser/ash/file_manager/file_tasks.cc b/chrome/browser/ash/file_manager/file_tasks.cc index ab0e5000..eb2a1d7 100644 --- a/chrome/browser/ash/file_manager/file_tasks.cc +++ b/chrome/browser/ash/file_manager/file_tasks.cc
@@ -59,6 +59,7 @@ #include "components/drive/drive_api_util.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/file_handler.h" #include "components/services/app_service/public/cpp/file_handler_info.h" @@ -490,10 +491,9 @@ } DCHECK_EQ(task.task_type, TASK_TYPE_ARC_APP); - apps::RecordAppLaunchMetrics( - profile, apps::AppType::kArc, task.app_id, - apps::mojom::LaunchSource::kFromFileManager, - apps::mojom::LaunchContainer::kLaunchContainerWindow); + apps::RecordAppLaunchMetrics(profile, apps::AppType::kArc, task.app_id, + apps::mojom::LaunchSource::kFromFileManager, + apps::LaunchContainer::kLaunchContainerWindow); ExecuteArcTask(profile, task, file_urls, *mime_types, std::move(done)); }
diff --git a/chrome/browser/ash/file_manager/guest_os_file_tasks.cc b/chrome/browser/ash/file_manager/guest_os_file_tasks.cc index 97018f1..ac6d8828 100644 --- a/chrome/browser/ash/file_manager/guest_os_file_tasks.cc +++ b/chrome/browser/ash/file_manager/guest_os_file_tasks.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/ash/plugin_vm/plugin_vm_files.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_util.h" #include "chrome/common/webui_url_constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/browser/entry_info.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_url.h" @@ -283,7 +284,7 @@ apps::RecordAppLaunchMetrics( profile, apps::AppType::kCrostini, task.app_id, apps::mojom::LaunchSource::kFromFileManager, - apps::mojom::LaunchContainer::kLaunchContainerWindow); + apps::LaunchContainer::kLaunchContainerWindow); crostini::LaunchCrostiniApp( profile, task.app_id, display::kInvalidDisplayId, args, base::BindOnce( @@ -307,7 +308,7 @@ apps::RecordAppLaunchMetrics( profile, apps::AppType::kPluginVm, task.app_id, apps::mojom::LaunchSource::kFromFileManager, - apps::mojom::LaunchContainer::kLaunchContainerWindow); + apps::LaunchContainer::kLaunchContainerWindow); DCHECK(plugin_vm::PluginVmFeatures::Get()->IsEnabled(profile)); plugin_vm::LaunchPluginVmApp( profile, task.app_id, args,
diff --git a/chrome/browser/ash/input_method/ui/undo_window.cc b/chrome/browser/ash/input_method/ui/undo_window.cc index c709c786..0c16451 100644 --- a/chrome/browser/ash/input_method/ui/undo_window.cc +++ b/chrome/browser/ash/input_method/ui/undo_window.cc
@@ -8,6 +8,7 @@ #include "ash/public/cpp/style/scoped_light_mode_as_default.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ash/input_method/ui/border_factory.h" +#include "chrome/browser/ash/input_method/ui/colors.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/bubble/bubble_border.h" @@ -26,8 +27,8 @@ constexpr int kPadding = 0; constexpr int kIconSize = 16; // TODO(crbug/1099044): Update and use cros_colors.json5 -constexpr SkColor kButtonHighlightColor = - SkColorSetA(SK_ColorBLACK, 0x0F); // 6% Black. +constexpr cros_styles::ColorName kButtonHighlightColor = + cros_styles::ColorName::kRippleColor; } // namespace @@ -107,7 +108,8 @@ return; undo_button_->SetBackground( - highlighted ? views::CreateSolidBackground(kButtonHighlightColor) + highlighted ? views::CreateSolidBackground( + ResolveSemanticColor(kButtonHighlightColor)) : nullptr); }
diff --git a/chrome/browser/ash/login/demo_mode/demo_session.cc b/chrome/browser/ash/login/demo_mode/demo_session.cc index 92c549c..19851d2 100644 --- a/chrome/browser/ash/login/demo_mode/demo_session.cc +++ b/chrome/browser/ash/login/demo_mode/demo_session.cc
@@ -47,6 +47,7 @@ #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/user_manager/user.h" #include "content/public/browser/browser_thread.h" @@ -646,10 +647,10 @@ Profile* profile = ProfileManager::GetActiveUserProfile(); DCHECK(profile); apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithParams( - apps::AppLaunchParams( - update.AppId(), apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromChromeInternal)); + apps::AppLaunchParams(update.AppId(), + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromChromeInternal)); } void DemoSession::OnAppRegistryCacheWillBeDestroyed(
diff --git a/chrome/browser/ash/system_web_apps/test_support/system_web_app_browsertest_base.cc b/chrome/browser/ash/system_web_apps/test_support/system_web_app_browsertest_base.cc index 078ee220..41d133eb 100644 --- a/chrome/browser/ash/system_web_apps/test_support/system_web_app_browsertest_base.cc +++ b/chrome/browser/ash/system_web_apps/test_support/system_web_app_browsertest_base.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/types_util.h" #include "content/public/test/test_navigation_observer.h" #include "testing/gtest/include/gtest/gtest.h" @@ -65,10 +66,10 @@ GetManager().GetAppIdForSystemApp(system_app_type); CHECK(app_id.has_value()); - return apps::AppLaunchParams( - *app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::CURRENT_TAB, - apps::mojom::LaunchSource::kFromAppListGrid); + return apps::AppLaunchParams(*app_id, + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::CURRENT_TAB, + apps::mojom::LaunchSource::kFromAppListGrid); } content::WebContents* SystemWebAppBrowserTestBase::LaunchApp(
diff --git a/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.cc b/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.cc index 8fbc4745..6ccac98 100644 --- a/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.cc +++ b/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.cc
@@ -4,27 +4,21 @@ #include "chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h" -#include <memory.h> - #include "base/values.h" #include "chrome/browser/ash/file_manager/file_manager_string_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "ui/webui/webui_allowlist.h" ChromeFileManagerUIDelegate::ChromeFileManagerUIDelegate(content::WebUI* web_ui) : web_ui_(web_ui) { DCHECK(web_ui_); } -void ChromeFileManagerUIDelegate::PopulateLoadTimeData( - content::WebUIDataSource* source) const { +base::Value::Dict ChromeFileManagerUIDelegate::GetLoadTimeData() const { base::Value::Dict dict = GetFileManagerStrings(); const std::string locale = g_browser_process->GetApplicationLocale(); AddFileManagerFeatureStrings(locale, Profile::FromWebUI(web_ui_), &dict); - - source->AddLocalizedStrings(dict); + return dict; }
diff --git a/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h b/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h index cd6c2899..8cc9522 100644 --- a/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h +++ b/chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h
@@ -20,8 +20,10 @@ ChromeFileManagerUIDelegate& operator=(const ChromeFileManagerUIDelegate&) = delete; - // FileManagerUIDelegate: - void PopulateLoadTimeData(content::WebUIDataSource*) const override; + // Fetches a map that maps message IDs to actual strings shown to the user. + // Extends the map with properties used by the files app, such as which + // features are enabled. Returns the populated map to the caller. + base::Value::Dict GetLoadTimeData() const override; private: content::WebUI* web_ui_; // Owns |this|.
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 6292b24..4ad1ec7 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -224,8 +224,6 @@ <include name="IDR_VM_APP_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\vm\app.js" type="BINDATA" use_base_dir="false" /> <include name="IDR_VM_MOJOM_WEBUI_JS" file="${root_gen_dir}\mojom-webui\chrome\browser\ui\webui\chromeos\vm\vm.mojom-webui.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_GUEST_OS_DIAGNOSTICS_MOJOM_WEBUI_JS" file="${root_gen_dir}\mojom-webui\chrome\browser\ash\guest_os\guest_os_diagnostics.mojom-webui.js" use_base_dir="false" type="BINDATA" /> - - <include name="IDR_MANAGE_MIRRORSYNC_INDEX_HTML" file="resources\chromeos\manage_mirrorsync\index.html" type="BINDATA" /> </if> <if expr="chromeos_ash and _google_chrome"> <include name="IDR_HELP_MANIFEST" file="resources\help_app\manifest.json" type="BINDATA" />
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index 2026f9a..a58dc02 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -254,6 +254,8 @@ #include "chrome/browser/ui/webui/chromeos/launcher_internals/launcher_internals.mojom.h" #include "chrome/browser/ui/webui/chromeos/launcher_internals/launcher_internals_ui.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom.h" +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" #include "chrome/browser/ui/webui/chromeos/network_ui.h" #include "chrome/browser/ui/webui/chromeos/parent_access/parent_access_ui.h" @@ -1168,6 +1170,12 @@ map); } + if (ash::features::IsDriveFsMirroringEnabled()) { + RegisterWebUIControllerInterfaceBinder< + chromeos::manage_mirrorsync::mojom::PageHandlerFactory, + chromeos::ManageMirrorSyncUI>(map); + } + #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
diff --git a/chrome/browser/chromeos/app_mode/chrome_kiosk_app_launcher.cc b/chrome/browser/chromeos/app_mode/chrome_kiosk_app_launcher.cc index 4c0a466..725a3d39 100644 --- a/chrome/browser/chromeos/app_mode/chrome_kiosk_app_launcher.cc +++ b/chrome/browser/chromeos/app_mode/chrome_kiosk_app_launcher.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/extensions/application_launch.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/disable_reason.h" @@ -91,12 +92,11 @@ SYSLOG(INFO) << "Attempt to launch app."; // Always open the app in a window. - ::OpenApplication( - profile_, - apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromKiosk)); + ::OpenApplication(profile_, apps::AppLaunchParams( + extension->id(), + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromKiosk)); WaitForAppWindow(); }
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc index d9080aa..de84105 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc
@@ -43,6 +43,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h" #include "chrome/common/extensions/api/file_manager_private_internal.h" #include "chrome/common/extensions/extension_constants.h" #include "chromeos/network/network_handler.h" @@ -964,4 +965,13 @@ return RespondNow(NoArguments()); } +ExtensionFunction::ResponseAction +FileManagerPrivateOpenManageSyncSettingsFunction::Run() { + if (ash::features::IsDriveFsMirroringEnabled()) { + chromeos::ManageMirrorSyncDialog::Show( + Profile::FromBrowserContext(browser_context())); + } + return RespondNow(NoArguments()); +} + } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.h b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.h index 36294f2..f47cd9f 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.h
@@ -205,6 +205,19 @@ ResponseAction Run() override; }; +// Implements the chrome.fileManagerPrivate.openManageSyncSettings method. +class FileManagerPrivateOpenManageSyncSettingsFunction + : public ExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("fileManagerPrivate.openManageSyncSettings", + FILEMANAGERPRIVATE_OPENMANAGESYNCSETTINGS) + + protected: + ~FileManagerPrivateOpenManageSyncSettingsFunction() override = default; + + ResponseAction Run() override; +}; + } // namespace extensions #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_MANAGER_PRIVATE_API_DRIVE_H_
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 17407a1d..73237cdd 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -862,7 +862,7 @@ "//components/safe_browsing/core/common:safe_browsing_prefs", "//components/safe_browsing/core/common/proto:csd_proto", "//components/search_engines", - "//components/services/app_service/public/mojom", + "//components/services/app_service/public/cpp:app_types", "//components/services/patch/content", "//components/services/unzip/content", "//components/services/unzip/public/cpp",
diff --git a/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc index 238ec36..3963e956 100644 --- a/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc +++ b/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc
@@ -47,6 +47,7 @@ #include "chrome/common/extensions/extension_metrics.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "components/favicon/core/favicon_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/webapps/browser/install_result_code.h" #include "components/webapps/browser/installable/installable_manager.h" #include "components/webapps/browser/installable/installable_metrics.h" @@ -357,9 +358,9 @@ DCHECK(provider); absl::optional<web_app::UserDisplayMode> display_mode = provider->registrar().GetAppUserDisplayMode(app_id); - auto launch_container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto launch_container = apps::LaunchContainer::kLaunchContainerWindow; if (display_mode == web_app::UserDisplayMode::kBrowser) - launch_container = apps::mojom::LaunchContainer::kLaunchContainerTab; + launch_container = apps::LaunchContainer::kLaunchContainerTab; if (!apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) { // If the profile doesn't have an App Service Proxy available, that means @@ -429,7 +430,7 @@ // returned. // TODO(crbug.com/1003602): Make AppLaunchParams launch container Optional or // add a "default" launch container enum value. - apps::mojom::LaunchContainer launch_container = + apps::LaunchContainer launch_container = GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension); Profile* profile = Profile::FromBrowserContext(context); if (!apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) {
diff --git a/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 3f5385da..1edef20 100644 --- a/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chrome/browser/extensions/api/notifications/notifications_apitest.cc
@@ -27,6 +27,7 @@ #include "chrome/browser/notifications/notifier_state_tracker_factory.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/test/base/interactive_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/test/browser_test.h" #include "extensions/browser/api/test/test_api.h" #include "extensions/browser/app_window/app_window.h" @@ -166,7 +167,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); }
diff --git a/chrome/browser/extensions/browsertest_util.cc b/chrome/browser/extensions/browsertest_util.cc index bdc2c55..5a6de648 100644 --- a/chrome/browser/extensions/browsertest_util.cc +++ b/chrome/browser/extensions/browsertest_util.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_registry.h" @@ -60,7 +61,7 @@ ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( extension_app->id(), - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::CURRENT_TAB, apps::mojom::LaunchSource::kFromTest)));
diff --git a/chrome/browser/extensions/extension_apitest.cc b/chrome/browser/extensions/extension_apitest.cc index 1fa78b39..235aa5e 100644 --- a/chrome/browser/extensions/extension_apitest.cc +++ b/chrome/browser/extensions/extension_apitest.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/common/content_switches.h" #include "extensions/browser/api/test/test_api.h" #include "extensions/browser/extension_registry.h" @@ -148,10 +149,10 @@ if (!url_to_open.is_empty()) { OpenURL(url_to_open, run_options.open_in_incognito); } else if (run_options.launch_as_platform_app) { - apps::AppLaunchParams params( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromTest); + apps::AppLaunchParams params(extension->id(), + apps::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromTest); params.command_line = *base::CommandLine::ForCurrentProcess(); apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher()
diff --git a/chrome/browser/extensions/extension_browsertest.cc b/chrome/browser/extensions/extension_browsertest.cc index ef61d25..bde30815 100644 --- a/chrome/browser/extensions/extension_browsertest.cc +++ b/chrome/browser/extensions/extension_browsertest.cc
@@ -51,6 +51,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/crx_file/crx_verifier.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/sync/model/string_ordinal.h" #include "components/version_info/version_info.h" #include "content/public/browser/navigation_controller.h" @@ -507,7 +508,7 @@ content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); apps::AppLaunchParams params( - app->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + app->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); params.command_line = *base::CommandLine::ForCurrentProcess(); apps::AppServiceProxyFactory::GetForProfile(profile())
diff --git a/chrome/browser/extensions/launch_util.cc b/chrome/browser/extensions/launch_util.cc index 6b6148b..24fac3ef 100644 --- a/chrome/browser/extensions/launch_util.cc +++ b/chrome/browser/extensions/launch_util.cc
@@ -15,7 +15,6 @@ #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "components/pref_registry/pref_registry_syncable.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/pref_names.h" @@ -76,18 +75,18 @@ ExtensionSyncService::Get(context)->SyncExtensionChangeIfNeeded(*extension); } -apps::mojom::LaunchContainer GetLaunchContainer(const ExtensionPrefs* prefs, - const Extension* extension) { - apps::mojom::LaunchContainer manifest_launch_container = +apps::LaunchContainer GetLaunchContainer(const ExtensionPrefs* prefs, + const Extension* extension) { + apps::LaunchContainer manifest_launch_container = AppLaunchInfo::GetLaunchContainer(extension); - absl::optional<apps::mojom::LaunchContainer> result; + absl::optional<apps::LaunchContainer> result; if (manifest_launch_container == - apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated) { + apps::LaunchContainer::kLaunchContainerPanelDeprecated) { result = manifest_launch_container; } else if (manifest_launch_container == - apps::mojom::LaunchContainer::kLaunchContainerTab) { + apps::LaunchContainer::kLaunchContainerTab) { // Look for prefs that indicate the user's choice of launch container. The // app's menu on the NTP provides a UI to set this preference. LaunchType prefs_launch_type = GetLaunchType(prefs, extension); @@ -95,31 +94,31 @@ if (prefs_launch_type == LAUNCH_TYPE_WINDOW) { // If the pref is set to launch a window (or no pref is set, and // window opening is the default), make the container a window. - result = apps::mojom::LaunchContainer::kLaunchContainerWindow; + result = apps::LaunchContainer::kLaunchContainerWindow; #if BUILDFLAG(IS_CHROMEOS_ASH) } else if (prefs_launch_type == LAUNCH_TYPE_FULLSCREEN) { // LAUNCH_TYPE_FULLSCREEN launches in a maximized app window in ash. // For desktop chrome AURA on all platforms we should open the // application in full screen mode in the current tab, on the same // lines as non AURA chrome. - result = apps::mojom::LaunchContainer::kLaunchContainerWindow; + result = apps::LaunchContainer::kLaunchContainerWindow; #endif } else { // All other launch types (tab, pinned, fullscreen) are // implemented as tabs in a window. - result = apps::mojom::LaunchContainer::kLaunchContainerTab; + result = apps::LaunchContainer::kLaunchContainerTab; } } else { // If a new value for app.launch.container is added, logic for it should be - // added here. apps::mojom::LaunchContainer::kLaunchContainerWindow is not + // added here. apps::LaunchContainer::kLaunchContainerWindow is not // present because there is no way to set it in a manifest. - NOTREACHED() << manifest_launch_container; + NOTREACHED() << static_cast<int>(manifest_launch_container); } // All paths should set |result|. if (!result) { DLOG(FATAL) << "Failed to set a launch container."; - result = apps::mojom::LaunchContainer::kLaunchContainerTab; + result = apps::LaunchContainer::kLaunchContainerTab; } return *result; @@ -128,10 +127,10 @@ bool HasPreferredLaunchContainer(const ExtensionPrefs* prefs, const Extension* extension) { int value = -1; - apps::mojom::LaunchContainer manifest_launch_container = + apps::LaunchContainer manifest_launch_container = AppLaunchInfo::GetLaunchContainer(extension); return manifest_launch_container == - apps::mojom::LaunchContainer::kLaunchContainerTab && + apps::LaunchContainer::kLaunchContainerTab && prefs->ReadPrefAsInteger(extension->id(), kPrefLaunchType, &value); }
diff --git a/chrome/browser/extensions/launch_util.h b/chrome/browser/extensions/launch_util.h index 889cb83d..3db52ad 100644 --- a/chrome/browser/extensions/launch_util.h +++ b/chrome/browser/extensions/launch_util.h
@@ -7,7 +7,7 @@ #include <string> -#include "components/services/app_service/public/mojom/types.mojom-forward.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/common/constants.h" namespace content { @@ -39,8 +39,8 @@ // Finds the right launch container based on the launch type. // If |extension|'s prefs do not have a launch type set, then the default // value from GetLaunchType() is used to choose the launch container. -apps::mojom::LaunchContainer GetLaunchContainer(const ExtensionPrefs* prefs, - const Extension* extension); +apps::LaunchContainer GetLaunchContainer(const ExtensionPrefs* prefs, + const Extension* extension); // Returns true if a launch container preference has been specified for // |extension|. GetLaunchContainer() will still return a default value even if
diff --git a/chrome/browser/feed/android/feed_service_bridge.cc b/chrome/browser/feed/android/feed_service_bridge.cc index d32499ae..677e69c 100644 --- a/chrome/browser/feed/android/feed_service_bridge.cc +++ b/chrome/browser/feed/android/feed_service_bridge.cc
@@ -16,7 +16,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/feed/android/jni_headers/FeedServiceBridge_jni.h" #include "chrome/browser/feed/feed_service_factory.h" -#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/feed/core/shared_prefs/pref_names.h" @@ -162,10 +161,7 @@ } bool FeedServiceBridge::IsAutoplayEnabled() { - // For now, disable autoplay if metrics are disabled until we can ensure that - // the autoplay feature does not report metrics. - return base::FeatureList::IsEnabled(kInterestFeedV2Autoplay) && - ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled(); + return base::FeatureList::IsEnabled(kInterestFeedV2Autoplay); } void FeedServiceBridge::ClearAll() {
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index f507a56..c6871aab 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1001,17 +1001,17 @@ { "name": "contextual-triggers-selection-handles", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 104 + "expiry_milestone": 108 }, { "name": "contextual-triggers-selection-menu", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 104 + "expiry_milestone": 108 }, { "name": "contextual-triggers-selection-size", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 104 + "expiry_milestone": 108 }, { "name": "conversion-measurement-debug-mode", @@ -2756,11 +2756,6 @@ "expiry_milestone": -1 }, { - "name": "enable-skia-renderer", - "owners": [ "backer", "kylechar", "penghuang" ], - "expiry_milestone": 100 - }, - { "name": "enable-start-surface", "owners": [ "hanxi", "wychen" ], "expiry_milestone": 115 @@ -2930,6 +2925,11 @@ "expiry_milestone": 105 }, { + "name": "enable-user-policy", + "owners": [ "vincb" ], + "expiry_milestone": 110 + }, + { "name": "enable-vaapi-av1-decode-acceleration", "owners": [ "andrescj", "chromeos-gfx-video@google.com" ], "expiry_milestone": 100 @@ -3118,8 +3118,8 @@ }, { "name": "enable-windows-gaming-input-data-fetcher", - "owners": [ "qiaye@microsoft.com" ], - "expiry_milestone": 92 + "owners": ["gabrielbrito@microsoft.com", "qiaye@microsoft.com" ], + "expiry_milestone": 115 }, { "name": "enable-winrt-geolocation-implementation",
diff --git a/chrome/browser/flags/BUILD.gn b/chrome/browser/flags/BUILD.gn index ab2b46e0..75c9019f 100644 --- a/chrome/browser/flags/BUILD.gn +++ b/chrome/browser/flags/BUILD.gn
@@ -18,6 +18,8 @@ "android/java/src/org/chromium/chrome/browser/flags/FeatureParamUtils.java", "android/java/src/org/chromium/chrome/browser/flags/Flag.java", "android/java/src/org/chromium/chrome/browser/flags/IntCachedFieldTrialParameter.java", + "android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefault.java", + "android/java/src/org/chromium/chrome/browser/flags/PostNativeFlag.java", "android/java/src/org/chromium/chrome/browser/flags/StringCachedFieldTrialParameter.java", "android/java/src/org/chromium/chrome/browser/flags/ValuesOverridden.java", "android/java/src/org/chromium/chrome/browser/flags/ValuesReturned.java", @@ -83,6 +85,9 @@ "android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureListWithProcessorUnitTest.java", "android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureListWithoutProcessorUnitTest.java", "android/java/src/org/chromium/chrome/browser/flags/FeatureParamUtilsUnitTest.java", + "android/java/src/org/chromium/chrome/browser/flags/FlagUnitTest.java", + "android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefaultUnitTest.java", + "android/java/src/org/chromium/chrome/browser/flags/PostNativeFlagUnitTest.java", ] deps = [ ":java",
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/CachedFlag.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/CachedFlag.java index 53f1dc5..fe2281c 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/CachedFlag.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/CachedFlag.java
@@ -15,8 +15,8 @@ public class CachedFlag extends Flag { private final boolean mDefaultValue; - public CachedFlag(String name, boolean defaultValue) { - super(name); + public CachedFlag(String featureName, boolean defaultValue) { + super(featureName); mDefaultValue = defaultValue; }
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/Flag.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/Flag.java index 01f48958e..4b557fc5 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/Flag.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/Flag.java
@@ -10,15 +10,18 @@ * Defines a feature flag for use in Java. * * Duplicate flag definitions are not permitted, so only a single - * instance can be created with a given feature name + * instance can be created with a given feature name. + * + * To create a flag, instantiate a subclass of Flag, either {@link CachedFlag}, + * {@link MutableFlagWithSafeDefault} or {@link PostNativeFlag}. */ public abstract class Flag { private static HashSet<String> sFlagsCreated = new HashSet<>(); protected final String mFeatureName; - Flag(String name) { - assert !sFlagsCreated.contains(name); - mFeatureName = name; + Flag(String featureName) { + assert !sFlagsCreated.contains(featureName); + mFeatureName = featureName; sFlagsCreated.add(mFeatureName); }
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/FlagUnitTest.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/FlagUnitTest.java new file mode 100644 index 0000000..0cef5c35 --- /dev/null +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/FlagUnitTest.java
@@ -0,0 +1,65 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.flags; + +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.FEATURE_A; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.BaseRobolectricTestRunner; + +/** + * Unit Tests for {@link Flag}. + */ +@RunWith(BaseRobolectricTestRunner.class) +public class FlagUnitTest { + @Rule + public final BaseFlagTestRule mBaseFlagTestRule = new BaseFlagTestRule(); + + @Test + public void testDuplicateFeatureFlags_throwsAssertionError() { + new PostNativeFlag(FEATURE_A); + try { + new MutableFlagWithSafeDefault(FEATURE_A, false); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + try { + new CachedFlag(FEATURE_A, false); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + + Flag.resetFlagsForTesting(); + + new MutableFlagWithSafeDefault(FEATURE_A, false); + try { + new PostNativeFlag(FEATURE_A); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + try { + new CachedFlag(FEATURE_A, false); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + + Flag.resetFlagsForTesting(); + + new CachedFlag(FEATURE_A, false); + try { + new MutableFlagWithSafeDefault(FEATURE_A, false); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + try { + new PostNativeFlag(FEATURE_A); + throw new RuntimeException("Duplicate feature"); + } catch (AssertionError e) { + } + } +}
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefault.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefault.java new file mode 100644 index 0000000..58672ba --- /dev/null +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefault.java
@@ -0,0 +1,38 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.flags; + +import org.chromium.base.FeatureList; + +/** + * Flags of this type are un-cached flags that may be called before native, + * but not primarily. They have good default values to use before native is loaded, + * and will switch to using the native value once native is loaded. + * These flags replace code like: + * if (FeatureList.isInitialized() && ChromeFeatureList.isEnabled(featureName)) + * or + * if (!FeatureList.isInitialized() || ChromeFeatureList.isEnabled(featureName)). + */ +public class MutableFlagWithSafeDefault extends Flag { + private final boolean mDefaultValue; + + public MutableFlagWithSafeDefault(String featureName, boolean defaultValue) { + super(featureName); + mDefaultValue = defaultValue; + } + + @Override + public boolean isEnabled() { + if (isFeatureListInitialized(mFeatureName)) { + return ChromeFeatureList.isEnabled(mFeatureName); + } else { + return mDefaultValue; + } + } + + private static boolean isFeatureListInitialized(String featureName) { + return FeatureList.hasTestFeature(featureName) || FeatureList.isNativeInitialized(); + } +}
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefaultUnitTest.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefaultUnitTest.java new file mode 100644 index 0000000..7404792 --- /dev/null +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/MutableFlagWithSafeDefaultUnitTest.java
@@ -0,0 +1,69 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.flags; + +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.A_OFF_B_ON; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.A_ON_B_OFF; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.FEATURE_A; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.FEATURE_B; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.assertIsEnabledMatches; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.FeatureList; +import org.chromium.base.test.BaseRobolectricTestRunner; + +/** + * Unit Tests for {@link MutableFlagWithSafeDefault}. + */ +@RunWith(BaseRobolectricTestRunner.class) +public class MutableFlagWithSafeDefaultUnitTest { + @Rule + public final BaseFlagTestRule mBaseFlagTestRule = new BaseFlagTestRule(); + + @Test(expected = AssertionError.class) + public void testDuplicateFeature_throwsException() { + new MutableFlagWithSafeDefault(FEATURE_A, true); + new MutableFlagWithSafeDefault(FEATURE_A, true); + } + + @Test + public void testNativeInitialized_getsFromChromeFeatureList() { + MutableFlagWithSafeDefault featureA = new MutableFlagWithSafeDefault(FEATURE_A, false); + MutableFlagWithSafeDefault featureB = new MutableFlagWithSafeDefault(FEATURE_B, true); + + // Values from ChromeFeatureList should be used from now on. + FeatureList.setTestFeatures(A_ON_B_OFF); + + // Verify that {@link MutableFlagWithSafeDefault} returns native values. + assertIsEnabledMatches(A_ON_B_OFF, featureA, featureB); + } + + @Test + public void testNativeNotInitialized_useDefault() { + MutableFlagWithSafeDefault featureA = new MutableFlagWithSafeDefault(FEATURE_A, false); + MutableFlagWithSafeDefault featureB = new MutableFlagWithSafeDefault(FEATURE_B, true); + + // Query the flags to make sure the default values are returned. + assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB); + } + + @Test + public void testNativeInitializedUsedDefault_getsFromChromeFeatureList() { + MutableFlagWithSafeDefault featureA = new MutableFlagWithSafeDefault(FEATURE_A, false); + MutableFlagWithSafeDefault featureB = new MutableFlagWithSafeDefault(FEATURE_B, true); + + // Query the flags to make sure the default values are returned. + assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB); + + // Values from ChromeFeatureList should be used from now on. + FeatureList.setTestFeatures(A_ON_B_OFF); + + // Verify that {@link MutableFlagWithSafeDefault} returns native values. + assertIsEnabledMatches(A_ON_B_OFF, featureA, featureB); + } +}
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlag.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlag.java new file mode 100644 index 0000000..6d0d160c --- /dev/null +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlag.java
@@ -0,0 +1,19 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.flags; + +/** + * Flags of this type assume native is loaded and the value can be retrieved directly from native. + */ +public class PostNativeFlag extends Flag { + public PostNativeFlag(String featureName) { + super(featureName); + } + + @Override + public boolean isEnabled() { + return ChromeFeatureList.isEnabled(mFeatureName); + } +}
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlagUnitTest.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlagUnitTest.java new file mode 100644 index 0000000..40f84762 --- /dev/null +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/PostNativeFlagUnitTest.java
@@ -0,0 +1,50 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.flags; + +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.A_OFF_B_ON; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.FEATURE_A; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.FEATURE_B; +import static org.chromium.chrome.browser.flags.BaseFlagTestRule.assertIsEnabledMatches; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.FeatureList; +import org.chromium.base.test.BaseRobolectricTestRunner; + +/** + * Unit Tests for {@link PostNativeFlag}. + */ +@RunWith(BaseRobolectricTestRunner.class) +public class PostNativeFlagUnitTest { + @Rule + public final BaseFlagTestRule mBaseFlagTestRule = new BaseFlagTestRule(); + + @Test(expected = AssertionError.class) + public void testDuplicateFeature_throwsException() { + new PostNativeFlag(FEATURE_A); + new PostNativeFlag(FEATURE_A); + } + + @Test(expected = AssertionError.class) + public void testNativeNotInitialized_throwAssertionError() { + PostNativeFlag featureA = new PostNativeFlag(FEATURE_A); + featureA.isEnabled(); + } + + @Test + public void testNativeInitialized_getsFromChromeFeatureList() { + PostNativeFlag featureA = new PostNativeFlag(FEATURE_A); + PostNativeFlag featureB = new PostNativeFlag(FEATURE_B); + + // Values from ChromeFeatureList should be used from now on. + FeatureList.setTestFeatures(A_OFF_B_ON); + + // Assert {@link MutableFlagWithSafeDefault} uses the values from {@link ChromeFeatureList}. + assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB); + } +}
diff --git a/chrome/browser/media/webrtc/multi_capture_browsertest.cc b/chrome/browser/media/webrtc/multi_capture_browsertest.cc index 9ee43a28..be8c07f 100644 --- a/chrome/browser/media/webrtc/multi_capture_browsertest.cc +++ b/chrome/browser/media/webrtc/multi_capture_browsertest.cc
@@ -77,6 +77,7 @@ current_web_contents->GetBrowserContext(), GURL(""))); } +#if BUILDFLAG(IS_CHROMEOS) IN_PROC_BROWSER_TEST_F(SelectAllScreensTest, SelectAllScreensDisabledWithEmptyPolicy) { initialization_end_checkpoint.Call(); @@ -273,3 +274,4 @@ GURL("https://www.chromium.org")); EXPECT_EQ(multi_capture_allowed, MULTI_CAPTURE_SUPPORTED_ON_PLATFORM); } +#endif // BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/metrics/chrome_metrics_service_accessor.h b/chrome/browser/metrics/chrome_metrics_service_accessor.h index d9a2253..7a10f3f 100644 --- a/chrome/browser/metrics/chrome_metrics_service_accessor.h +++ b/chrome/browser/metrics/chrome_metrics_service_accessor.h
@@ -86,7 +86,6 @@ } namespace feed { -class FeedServiceBridge; class FeedServiceDelegateImpl; class WebFeedSubscriptionCoordinator; } // namespace feed @@ -160,7 +159,6 @@ friend class WebUITabStripFieldTrial; friend class feed::FeedServiceDelegateImpl; friend class browser_sync::DeviceInfoSyncClientImpl; - friend class feed::FeedServiceBridge; friend class feed::WebFeedSubscriptionCoordinator; friend class HttpsFirstModeService; friend class webauthn::authenticator::IsMetricsAndCrashReportingEnabled;
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index 7adba9f..cee1af7 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -385,8 +385,6 @@ EmitTo::kSizeInUkmAndUma, &Memory_Experimental::SetSkia}, {"skia/gpu_resources", "SharedContextState", MetricSize::kLarge, kEffectiveSize, EmitTo::kIgnored, nullptr}, - {"skia/gpu_resources", "VizProcessContextProvider", MetricSize::kLarge, - kEffectiveSize, EmitTo::kIgnored, nullptr}, {"skia/sk_glyph_cache", "Skia.SkGlyphCache", MetricSize::kLarge, kEffectiveSize, EmitTo::kSizeInUkmAndUma, &Memory_Experimental::SetSkia_SkGlyphCache},
diff --git a/chrome/browser/payments/journey_logger_browsertest.cc b/chrome/browser/payments/journey_logger_browsertest.cc index 7d2ca45..75afcb4 100644 --- a/chrome/browser/payments/journey_logger_browsertest.cc +++ b/chrome/browser/payments/journey_logger_browsertest.cc
@@ -167,30 +167,6 @@ } // Make sure the UKM was logged correctly. -IN_PROC_BROWSER_TEST_F(JourneyLoggerTest, UKMTransactionAmountRecorded) { - SetUpForGpay(); - EXPECT_EQ("{\"apiVersion\":1}", - content::EvalJs(GetActiveWebContents(), "testGPay()")); - - auto entries = test_ukm_recorder()->GetEntriesByName( - ukm::builders::PaymentRequest_TransactionAmount::kEntryName); - size_t num_entries = entries.size(); - EXPECT_EQ(2u, num_entries); - for (size_t i = 0; i < num_entries; i++) { - test_ukm_recorder()->ExpectEntrySourceHasUrl(entries[i], main_frame_url()); - EXPECT_EQ(2U, entries[i]->metrics.size()); - test_ukm_recorder()->ExpectEntryMetric( - entries[i], - ukm::builders::PaymentRequest_TransactionAmount::kCompletionStatusName, - i != 0 /* completed */); - test_ukm_recorder()->ExpectEntryMetric( - entries[i], - ukm::builders::PaymentRequest_TransactionAmount::kCategoryName, - static_cast<int64_t>( - JourneyLogger::TransactionSize::kRegularTransaction)); - } -} - IN_PROC_BROWSER_TEST_F(JourneyLoggerTest, UKMCheckoutEventsRecordedForAppOrigin) { GURL merchant_url = https_server()->GetURL("/payment_handler.html");
diff --git a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc index 0a0d7e84d..63d47e3 100644 --- a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc +++ b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/performance_manager/metrics/memory_pressure_metrics.h" #include "chrome/browser/performance_manager/observers/page_load_metrics_observer.h" #include "chrome/browser/performance_manager/policies/background_tab_loading_policy.h" -#include "chrome/browser/performance_manager/policies/high_pmf_discard_policy.h" #include "chrome/browser/performance_manager/policies/policy_features.h" #include "chrome/browser/performance_manager/policies/working_set_trimmer_policy.h" #include "chrome/browser/profiles/profile_manager.h" @@ -111,12 +110,10 @@ #if !BUILDFLAG(IS_ANDROID) graph->PassToGraph(FormInteractionTabHelper::CreateGraphObserver()); - // The PageDiscardingHelper instance is required by the HighPMFDiscardPolicy - // and by UrgentDiscardingFromPerformanceManager. + // The PageDiscardingHelper instance is required by + // UrgentDiscardingFromPerformanceManager. if (base::FeatureList::IsEnabled( - performance_manager::features::kHighPMFDiscardPolicy) || - base::FeatureList::IsEnabled( performance_manager::features:: kUrgentDiscardingFromPerformanceManager)) { graph->PassToGraph(std::make_unique< @@ -139,12 +136,6 @@ performance_manager::policies::BackgroundTabLoadingPolicy>()); } - if (base::FeatureList::IsEnabled( - performance_manager::features::kHighPMFDiscardPolicy)) { - graph->PassToGraph(std::make_unique< - performance_manager::policies::HighPMFDiscardPolicy>()); - } - // The freezing policy isn't enabled on Android yet as it doesn't play well // with the freezing logic already in place in renderers. This logic should be // moved to PerformanceManager, this is tracked in https://crbug.com/1156803.
diff --git a/chrome/browser/performance_manager/policies/high_pmf_discard_policy.cc b/chrome/browser/performance_manager/policies/high_pmf_discard_policy.cc deleted file mode 100644 index 5d8c2cf..0000000 --- a/chrome/browser/performance_manager/policies/high_pmf_discard_policy.cc +++ /dev/null
@@ -1,153 +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 "chrome/browser/performance_manager/policies/high_pmf_discard_policy.h" - -#include "base/bind.h" -#include "base/metrics/field_trial_params.h" -#include "base/metrics/histogram_functions.h" -#include "base/process/process_metrics.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "chrome/browser/performance_manager/policies/page_discarding_helper.h" -#include "chrome/browser/performance_manager/policies/policy_features.h" -#include "components/performance_manager/public/graph/process_node.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" - -#if !BUILDFLAG(IS_LINUX) -#include "base/memory/memory_pressure_monitor.h" -#endif - -namespace performance_manager { -namespace policies { - -namespace { - -// The factor that will be applied to the total amount of RAM to establish the -// PMF limit. -static constexpr base::FeatureParam<double> kRAMRatioPMFLimitFactor{ - &performance_manager::features::kHighPMFDiscardPolicy, - "RAMRatioPMFLimitFactor", 1.5}; - -// The discard strategy to use. -static constexpr base::FeatureParam<int> kDiscardStrategy{ - &performance_manager::features::kHighPMFDiscardPolicy, "DiscardStrategy", - static_cast<int>(features::DiscardStrategy::LRU)}; - -} // namespace - -HighPMFDiscardPolicy::HighPMFDiscardPolicy() = default; -HighPMFDiscardPolicy::~HighPMFDiscardPolicy() = default; - -void HighPMFDiscardPolicy::OnPassedToGraph(Graph* graph) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - graph->AddSystemNodeObserver(this); - graph_ = graph; - - metrics_interest_token_ = performance_manager::ProcessMetricsDecorator:: - RegisterInterestForProcessMetrics(graph_); - - base::SystemMemoryInfoKB mem_info = {}; - if (base::GetSystemMemoryInfo(&mem_info)) - pmf_limit_kb_ = mem_info.total * kRAMRatioPMFLimitFactor.Get(); - - DCHECK(PageDiscardingHelper::GetFromGraph(graph_)) - << "A PageDiscardingHelper instance should be registered against the " - "graph in order to use this policy."; -} - -void HighPMFDiscardPolicy::OnTakenFromGraph(Graph* graph) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - graph->RemoveSystemNodeObserver(this); - metrics_interest_token_.reset(); - graph_ = nullptr; - pmf_limit_kb_ = kInvalidPMFLimitValue; -} - -void HighPMFDiscardPolicy::OnProcessMemoryMetricsAvailable( - const SystemNode* unused) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (pmf_limit_kb_ == kInvalidPMFLimitValue) - return; - - if (discard_attempt_in_progress_) - return; - - int total_pmf_kb = 0; - bool should_discard = false; - auto process_nodes = graph_->GetAllProcessNodes(); - for (const auto* node : process_nodes) { - total_pmf_kb += node->GetPrivateFootprintKb(); - if (total_pmf_kb >= pmf_limit_kb_) { - should_discard = true; - // Do not break so we can compute the total PMF and report it later. - } - } - - // Report metrics when the high-PMF session has ended or after 100 attempts - // (the maximum value for the histograms). - if ((!should_discard && discard_attempts_count_while_pmf_is_high_) || - discard_attempts_count_while_pmf_is_high_ == 100) { - base::UmaHistogramCounts100("Discarding.HighPMFPolicy.DiscardAttemptsCount", - discard_attempts_count_while_pmf_is_high_); - base::UmaHistogramCounts100( - "Discarding.HighPMFPolicy.SuccessfulDiscardsCount", - successful_discards_count_while_pmf_is_high_); - discard_attempts_count_while_pmf_is_high_ = 0; - successful_discards_count_while_pmf_is_high_ = 0; - } - - // Reports the metrics for the previous intervention if necessary. - if (intervention_details_.has_value()) { - base::UmaHistogramBoolean("Discarding.HighPMFPolicy.DiscardSuccess", - intervention_details_->a_tab_has_been_discarded); - - if (intervention_details_->a_tab_has_been_discarded) { - // Report the total PMF delta as an integer as the total PMF might have - // increased. Negative values (increase of memory) are reported as 0 and - // go into the underflow bucket. - base::UmaHistogramCustomCounts( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", - std::max(0, intervention_details_->total_pmf_kb_before_intervention - - total_pmf_kb), - 1, 2000000 /* +2GB */, 50); - } - - intervention_details_.reset(); - } - - if (should_discard) { - discard_attempt_in_progress_ = true; -#if !BUILDFLAG(IS_LINUX) - // Record the memory pressure level before discarding a tab. - content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce([]() { - base::UmaHistogramEnumeration( - "Discarding.HighPMFPolicy.MemoryPressureLevel", - base::MemoryPressureMonitor::Get()->GetCurrentPressureLevel()); - })); -#endif - intervention_details_.emplace( - InterventionDetails{.total_pmf_kb_before_intervention = total_pmf_kb}); - PageDiscardingHelper::GetFromGraph(graph_)->UrgentlyDiscardAPage( - static_cast<features::DiscardStrategy>(kDiscardStrategy.Get()), - base::BindOnce(&HighPMFDiscardPolicy::PostDiscardAttemptCallback, - base::Unretained(this))); - } -} - -void HighPMFDiscardPolicy::PostDiscardAttemptCallback(bool success) { - DCHECK(discard_attempt_in_progress_); - DCHECK(intervention_details_.has_value()); - discard_attempt_in_progress_ = false; - intervention_details_->a_tab_has_been_discarded = success; - ++discard_attempts_count_while_pmf_is_high_; - if (success) - ++successful_discards_count_while_pmf_is_high_; -} - -} // namespace policies -} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/policies/high_pmf_discard_policy.h b/chrome/browser/performance_manager/policies/high_pmf_discard_policy.h deleted file mode 100644 index 36ed7dbe..0000000 --- a/chrome/browser/performance_manager/policies/high_pmf_discard_policy.h +++ /dev/null
@@ -1,77 +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 CHROME_BROWSER_PERFORMANCE_MANAGER_POLICIES_HIGH_PMF_DISCARD_POLICY_H_ -#define CHROME_BROWSER_PERFORMANCE_MANAGER_POLICIES_HIGH_PMF_DISCARD_POLICY_H_ - -#include "base/memory/raw_ptr.h" -#include "base/sequence_checker.h" -#include "components/performance_manager/public/decorators/process_metrics_decorator.h" -#include "components/performance_manager/public/graph/graph.h" -#include "components/performance_manager/public/graph/system_node.h" -#include "third_party/abseil-cpp/absl/types/optional.h" - -namespace performance_manager { - -class Graph; - -namespace policies { - -// The HighPMFDiscardPolicy will discard tabs when Chrome's total PMF exceeds a -// given threshold. -class HighPMFDiscardPolicy : public GraphOwned, - public SystemNode::ObserverDefaultImpl { - public: - HighPMFDiscardPolicy(); - ~HighPMFDiscardPolicy() override; - HighPMFDiscardPolicy(const HighPMFDiscardPolicy& other) = delete; - HighPMFDiscardPolicy& operator=(const HighPMFDiscardPolicy&) = delete; - - // GraphOwned implementation: - void OnPassedToGraph(Graph* graph) override; - void OnTakenFromGraph(Graph* graph) override; - - // SystemNode::ObserverDefaultImpl: - void OnProcessMemoryMetricsAvailable(const SystemNode* system_node) override; - - void set_pmf_limit_for_testing(int pmf_limit_kb) { - pmf_limit_kb_ = pmf_limit_kb; - } - - private: - // Callback called when a discard attempt has completed. - void PostDiscardAttemptCallback(bool success); - - const int kInvalidPMFLimitValue = 0; - - int pmf_limit_kb_ = kInvalidPMFLimitValue; - raw_ptr<Graph> graph_ = nullptr; - - // Indicates whether or not there's a discard attempt in progress. This could - // happen if this attempt doesn't complete between 2 calls to - // OnProcessMemoryMetricsAvailable. - bool discard_attempt_in_progress_ = false; - - // This will contain some details about the current intervention, or will be - // nullopt if there's no intervention in progress. - struct InterventionDetails { - int total_pmf_kb_before_intervention = 0; - bool a_tab_has_been_discarded = false; - }; - absl::optional<InterventionDetails> intervention_details_; - - size_t discard_attempts_count_while_pmf_is_high_ = 0; - size_t successful_discards_count_while_pmf_is_high_ = 0; - - std::unique_ptr< - performance_manager::ProcessMetricsDecorator::ScopedMetricsInterestToken> - metrics_interest_token_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace policies -} // namespace performance_manager - -#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_POLICIES_HIGH_PMF_DISCARD_POLICY_H_
diff --git a/chrome/browser/performance_manager/policies/high_pmf_discard_policy_unittest.cc b/chrome/browser/performance_manager/policies/high_pmf_discard_policy_unittest.cc deleted file mode 100644 index 31053ea9..0000000 --- a/chrome/browser/performance_manager/policies/high_pmf_discard_policy_unittest.cc +++ /dev/null
@@ -1,223 +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 "chrome/browser/performance_manager/policies/high_pmf_discard_policy.h" - -#include "base/bind.h" -#include "base/memory/memory_pressure_listener.h" -#include "base/memory/memory_pressure_monitor.h" -#include "base/memory/raw_ptr.h" -#include "base/test/metrics/histogram_tester.h" -#include "build/build_config.h" -#include "chrome/browser/performance_manager/test_support/page_discarding_utils.h" -#include "components/memory_pressure/fake_memory_pressure_monitor.h" -#include "components/performance_manager/public/decorators/process_metrics_decorator.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace performance_manager { -namespace policies { - -const int kPMFLimitKb = 100 * 1024; - -class HighPMFDiscardPolicyTest - : public testing::GraphTestHarnessWithMockDiscarder { - public: - HighPMFDiscardPolicyTest() = default; - ~HighPMFDiscardPolicyTest() override = default; - HighPMFDiscardPolicyTest(const HighPMFDiscardPolicyTest& other) = delete; - HighPMFDiscardPolicyTest& operator=(const HighPMFDiscardPolicyTest&) = delete; - - void SetUp() override { - testing::GraphTestHarnessWithMockDiscarder::SetUp(); - - // Create the policy and pass it to the graph. - graph()->PassToGraph(std::make_unique<ProcessMetricsDecorator>()); - auto policy = std::make_unique<HighPMFDiscardPolicy>(); - policy_ = policy.get(); - graph()->PassToGraph(std::move(policy)); - - histogram_tester_ = std::make_unique<base::HistogramTester>(); - } - - void TearDown() override { - histogram_tester_.reset(); - graph()->TakeFromGraph(policy_); - testing::GraphTestHarnessWithMockDiscarder::TearDown(); - } - - protected: - HighPMFDiscardPolicy* policy() { return policy_; } - base::HistogramTester* histogram_tester() { return histogram_tester_.get(); } - memory_pressure::test::FakeMemoryPressureMonitor& memory_pressure_monitor() { - return memory_pressure_monitor_; - } - - private: - raw_ptr<HighPMFDiscardPolicy> policy_; - std::unique_ptr<base::HistogramTester> histogram_tester_; - memory_pressure::test::FakeMemoryPressureMonitor memory_pressure_monitor_; -}; - -TEST_F(HighPMFDiscardPolicyTest, EndToEnd) { - policy()->set_pmf_limit_for_testing(kPMFLimitKb); - - process_node()->set_private_footprint_kb(kPMFLimitKb - 1); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - // Make sure that no task get posted to the discarder. - task_env().RunUntilIdle(); - ::testing::Mock::VerifyAndClearExpectations(discarder()); - - // A call to OnProcessMemoryMetricsAvailable should notify the policy that the - // total PMF is too high and a tab should be discarded. - process_node()->set_private_footprint_kb(kPMFLimitKb); - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(true)); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - task_env().RunUntilIdle(); - ::testing::Mock::VerifyAndClearExpectations(discarder()); - - // Lower the PMF of process_node, this is equivalent to discarding a page and - // lowering the total PMF. - process_node()->set_private_footprint_kb(kPMFLimitKb - 1); - // Call OnProcessMemoryMetricsAvailable to record the post discard metrics. - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.DiscardAttemptsCount", 1, 1); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.SuccessfulDiscardsCount", 1, 1); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.DiscardSuccess", true, 1); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", 1, 1); -#if !BUILDFLAG(IS_LINUX) - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.MemoryPressureLevel", - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, 1); -#endif -} - -TEST_F(HighPMFDiscardPolicyTest, Histograms) { - policy()->set_pmf_limit_for_testing(kPMFLimitKb); - process_node()->set_private_footprint_kb(kPMFLimitKb); - - // Pretend that the discard attempt has failed. - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(false)); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - ::testing::Mock::VerifyAndClearExpectations(discarder()); - - // There's been one unsuccessful discard attempt so far. The total PMF is - // still higher than the limit and so the number of discards shouldn't be - // reported. - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(true)); - PageDiscardingHelper::RemovesDiscardAttemptMarkerForTesting(page_node()); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - histogram_tester()->ExpectTotalCount( - "Discarding.HighPMFPolicy.DiscardAttemptsCount", 0); - histogram_tester()->ExpectTotalCount( - "Discarding.HighPMFPolicy.SuccessfulDiscardsCount", 0); - histogram_tester()->ExpectTotalCount( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", 0); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.DiscardSuccess", false, 1); - - // Do a successful discard but leave the total PMF as is. - ::testing::Mock::VerifyAndClearExpectations(discarder()); - - // There's been one unsuccessful discard attempt and one successful one so - // far but the total PMF is still above the limit. - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(true)); - PageDiscardingHelper::RemovesDiscardAttemptMarkerForTesting(page_node()); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - histogram_tester()->ExpectTotalCount( - "Discarding.HighPMFPolicy.DiscardAttemptsCount", 0); - histogram_tester()->ExpectTotalCount( - "Discarding.HighPMFPolicy.SuccessfulDiscardsCount", 0); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", 0, 1); - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.DiscardSuccess", false, 1); - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.DiscardSuccess", true, 1); - - process_node()->set_private_footprint_kb(kPMFLimitKb - 1); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.DiscardAttemptsCount", 3, 1); - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.SuccessfulDiscardsCount", 2, 1); - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", 1, 1); - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.DiscardSuccess", false, 1); - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.DiscardSuccess", true, 2); -} - -TEST_F(HighPMFDiscardPolicyTest, NegativeMemoryReclaimGoesInUnderflowBucket) { - policy()->set_pmf_limit_for_testing(kPMFLimitKb); - process_node()->set_private_footprint_kb(kPMFLimitKb); - - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(true)); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - ::testing::Mock::VerifyAndClearExpectations(discarder()); - process_node()->set_private_footprint_kb( - process_node()->private_footprint_kb() + 1); - - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - - // The total PMF has increased, the memory reclaimed should be reported in the - // underflow bucket. - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab", 0, 1); -} - -#if !BUILDFLAG(IS_LINUX) -TEST_F(HighPMFDiscardPolicyTest, MemoryPressureHistograms) { - policy()->set_pmf_limit_for_testing(kPMFLimitKb); - process_node()->set_private_footprint_kb(kPMFLimitKb); - - EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, - memory_pressure_monitor().GetCurrentPressureLevel()); - - EXPECT_CALL(*discarder(), DiscardPageNodeImpl(page_node())) - .WillOnce(::testing::Return(false)); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - task_env().RunUntilIdle(); - ::testing::Mock::VerifyAndClearExpectations(discarder()); - - histogram_tester()->ExpectUniqueSample( - "Discarding.HighPMFPolicy.MemoryPressureLevel", - - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, 1); - - // Test with MEMORY_PRESSURE_LEVEL_MODERATE. - memory_pressure_monitor().SetAndNotifyMemoryPressure( - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - task_env().RunUntilIdle(); - - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.MemoryPressureLevel", - - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE, 1); - - // Test with MEMORY_PRESSURE_LEVEL_CRITICAL. - memory_pressure_monitor().SetAndNotifyMemoryPressure( - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); - graph()->GetSystemNodeImpl()->OnProcessMemoryMetricsAvailable(); - task_env().RunUntilIdle(); - - histogram_tester()->ExpectBucketCount( - "Discarding.HighPMFPolicy.MemoryPressureLevel", - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL, 1); -} -#endif - -} // namespace policies -} // namespace performance_manager
diff --git a/chrome/browser/persisted_state_db/BUILD.gn b/chrome/browser/persisted_state_db/BUILD.gn index 7732c5c..96d2f41a 100644 --- a/chrome/browser/persisted_state_db/BUILD.gn +++ b/chrome/browser/persisted_state_db/BUILD.gn
@@ -20,8 +20,8 @@ } deps = [ - ":persisted_state_db_content_proto", "//base:base", + "//components/commerce/core:persisted_state_db_content_proto", "//components/keyed_service/content", "//components/leveldb_proto", "//content/public/browser:browser", @@ -40,7 +40,3 @@ ] } } - -proto_library("persisted_state_db_content_proto") { - sources = [ "persisted_state_db_content.proto" ] -}
diff --git a/chrome/browser/persisted_state_db/persisted_state_db.cc b/chrome/browser/persisted_state_db/persisted_state_db.cc index f01aa20..0b279966 100644 --- a/chrome/browser/persisted_state_db/persisted_state_db.cc +++ b/chrome/browser/persisted_state_db/persisted_state_db.cc
@@ -10,9 +10,9 @@ #include "base/android/jni_string.h" #include "base/bind.h" #include "base/callback_helpers.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" #include "chrome/browser/persisted_state_db/profile_proto_db_factory.h" #include "chrome/browser/tab/jni_headers/LevelDBPersistedDataStorage_jni.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" #include "content/public/browser/android/browser_context_handle.h" namespace {
diff --git a/chrome/browser/persisted_state_db/persisted_state_db.h b/chrome/browser/persisted_state_db/persisted_state_db.h index 026e1693..b3bacca1 100644 --- a/chrome/browser/persisted_state_db/persisted_state_db.h +++ b/chrome/browser/persisted_state_db/persisted_state_db.h
@@ -10,7 +10,7 @@ #include "base/memory/weak_ptr.h" #include "base/task/sequenced_task_runner.h" #include "build/build_config.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" #include "components/keyed_service/core/keyed_service.h" #include "components/leveldb_proto/public/proto_database.h"
diff --git a/chrome/browser/persisted_state_db/profile_proto_db.h b/chrome/browser/persisted_state_db/profile_proto_db.h index 39569a4..8e3979e19 100644 --- a/chrome/browser/persisted_state_db/profile_proto_db.h +++ b/chrome/browser/persisted_state_db/profile_proto_db.h
@@ -18,7 +18,7 @@ #include "base/task/sequenced_task_runner.h" #include "base/task/thread_pool.h" #include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" #include "components/keyed_service/core/keyed_service.h" #include "components/leveldb_proto/public/proto_database.h" #include "components/leveldb_proto/public/proto_database_provider.h"
diff --git a/chrome/browser/persisted_state_db/profile_proto_db_factory.cc b/chrome/browser/persisted_state_db/profile_proto_db_factory.cc index ae3de74..10a329b7 100644 --- a/chrome/browser/persisted_state_db/profile_proto_db_factory.cc +++ b/chrome/browser/persisted_state_db/profile_proto_db_factory.cc
@@ -6,7 +6,7 @@ #include "base/no_destructor.h" #include "build/build_config.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" ProfileProtoDBFactory<persisted_state_db::PersistedStateContentProto>* GetPersistedStateProfileProtoDBFactory() {
diff --git a/chrome/browser/persisted_state_db/profile_proto_db_factory_unittest.cc b/chrome/browser/persisted_state_db/profile_proto_db_factory_unittest.cc index fd049320..4b52ef0 100644 --- a/chrome/browser/persisted_state_db/profile_proto_db_factory_unittest.cc +++ b/chrome/browser/persisted_state_db/profile_proto_db_factory_unittest.cc
@@ -7,8 +7,8 @@ #include <memory> #include "base/files/scoped_temp_dir.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" #include "chrome/test/base/testing_profile.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index c847ab7..372c299 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -734,15 +734,9 @@ prefs::kAuthServerAllowlist, base::Value::Type::STRING }, - { key::kGSSAPILibraryName, - prefs::kGSSAPILibraryName, - base::Value::Type::STRING }, { key::kDiskCacheSize, prefs::kDiskCacheSize, base::Value::Type::INTEGER }, - { key::kDevicePolicyRefreshRate, - prefs::kDevicePolicyRefreshRate, - base::Value::Type::INTEGER }, { key::kDefaultBrowserSettingEnabled, prefs::kDefaultBrowserSettingEnabled, base::Value::Type::BOOLEAN }, @@ -845,9 +839,6 @@ { key::kAllowedDomainsForApps, prefs::kAllowedDomainsForApps, base::Value::Type::STRING }, - { key::kGetDisplayMediaSetSelectAllScreensAllowedForUrls, - prefs::kManagedGetDisplayMediaSetSelectAllScreensAllowedForUrls, - base::Value::Type::LIST }, { key::kVariationsRestrictParameter, variations::prefs::kVariationsRestrictParameter, base::Value::Type::STRING }, @@ -1420,6 +1411,12 @@ base::Value::Type::BOOLEAN }, #endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_LINUX) + { key::kGSSAPILibraryName, + prefs::kGSSAPILibraryName, + base::Value::Type::STRING }, +#endif // BUILDFLAG(IS_LINUX) + #if BUILDFLAG(IS_WIN) { key::kChromeCleanupEnabled, prefs::kSwReporterEnabled, @@ -1531,6 +1528,12 @@ { key::kDeviceAttributesAllowedForOrigins, prefs::kDeviceAttributesAllowedForOrigins, base::Value::Type::LIST }, + { key::kDevicePolicyRefreshRate, + prefs::kDevicePolicyRefreshRate, + base::Value::Type::INTEGER }, + { key::kGetDisplayMediaSetSelectAllScreensAllowedForUrls, + prefs::kManagedGetDisplayMediaSetSelectAllScreensAllowedForUrls, + base::Value::Type::LIST }, { key::kLacrosSecondaryProfilesAllowed, prefs::kLacrosSecondaryProfilesAllowed, base::Value::Type::BOOLEAN }, @@ -1966,6 +1969,10 @@ #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_CHROMEOS) + handlers->AddHandler(std::make_unique<IntRangePolicyHandler>( + key::kDeviceChromeVariations, nullptr, + static_cast<int>(variations::RestrictionPolicy::NO_RESTRICTIONS), + static_cast<int>(variations::RestrictionPolicy::ALL), false)); handlers->AddHandler(std::make_unique<extensions::ExtensionListPolicyHandler>( key::kAttestationExtensionAllowlist, prefs::kAttestationExtensionAllowlist, false)); @@ -2311,10 +2318,6 @@ handlers->AddHandler( std::make_unique<extensions::ExtensionSettingsPolicyHandler>( chrome_schema)); - handlers->AddHandler(std::make_unique<IntRangePolicyHandler>( - key::kDeviceChromeVariations, nullptr, - static_cast<int>(variations::RestrictionPolicy::NO_RESTRICTIONS), - static_cast<int>(variations::RestrictionPolicy::ALL), false)); #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \ BUILDFLAG(IS_FUCHSIA)
diff --git a/chrome/browser/policy/policy_prefs_browsertest.cc b/chrome/browser/policy/policy_prefs_browsertest.cc index b6dd759..15d8997 100644 --- a/chrome/browser/policy/policy_prefs_browsertest.cc +++ b/chrome/browser/policy/policy_prefs_browsertest.cc
@@ -19,6 +19,7 @@ #include "base/no_destructor.h" #include "base/path_service.h" #include "base/run_loop.h" +#include "base/sequence_checker_impl.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" @@ -74,6 +75,11 @@ protected: void SetUpInProcessBrowserTestFixture() override { + // Add debug information to understand how `V4Database::weak_factory_on_io_` + // ends up being used from more than one sequence. + // TODO(crbug.com/1341434): Remove after the bug is fixed. + base::SequenceCheckerImpl::EnableStackLogging(); + GetMockPolicyProvider()->SetDefaultReturns( true /* is_initialization_complete_return */, true /* is_first_policy_load_complete_return */);
diff --git a/chrome/browser/policy/test/full_screen_allowed_policy_browsertest.cc b/chrome/browser/policy/test/full_screen_allowed_policy_browsertest.cc index 82d8f97..682b4a1f 100644 --- a/chrome/browser/policy/test/full_screen_allowed_policy_browsertest.cc +++ b/chrome/browser/policy/test/full_screen_allowed_policy_browsertest.cc
@@ -15,6 +15,7 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/app_window/app_window.h" @@ -105,7 +106,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + extension->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
diff --git a/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.cc b/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.cc index d8d879d..10b14eb 100644 --- a/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.cc +++ b/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.cc
@@ -6,8 +6,6 @@ #include <vector> -#include "base/containers/contains.h" -#include "base/containers/fixed_flat_set.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/trace_event/base_tracing.h" @@ -286,20 +284,9 @@ return true; } -bool BaseSearchPrefetchRequest::ShouldBeCancelledOnResultChanges() const { - static constexpr auto CancelableStatus = - base::MakeFixedFlatSet<SearchPrefetchStatus>({ - SearchPrefetchStatus::kInFlight, - SearchPrefetchStatus::kCanBeServed, - SearchPrefetchStatus::kPrerendered, - }); - return base::Contains(CancelableStatus, current_status_); -} - void BaseSearchPrefetchRequest::CancelPrefetch() { DCHECK(current_status_ == SearchPrefetchStatus::kInFlight || - current_status_ == SearchPrefetchStatus::kCanBeServed || - current_status_ == SearchPrefetchStatus::kPrerendered); + current_status_ == SearchPrefetchStatus::kCanBeServed); current_status_ = SearchPrefetchStatus::kRequestCancelled; StopPrefetch(); StopPrerender(); @@ -332,29 +319,20 @@ // reuse the response and will fail for sure, so this does not start // prerendering. return; - case SearchPrefetchStatus::kPrerendered: - case SearchPrefetchStatus::kPrerenderedAndClicked: - // Case 4: Prerender has started and taken the response away. No action is - // needed. - return; case SearchPrefetchStatus::kServed: - case SearchPrefetchStatus::kPrerenderActivated: NOTREACHED(); } - prerender_manager_ = prerender_manager.GetWeakPtr(); - if (!servable_response_code_received_) { + if (servable_response_code_received_) { + // Case 3, 4: This can start prerendering because it has received a + // response. + prerender_manager.StartPrerenderSearchResult(prefetch_search_terms_, + prefetch_url_); + } else { // Case 2: this will start prerendering after it receives a // servable response. - return; + prerender_manager_ = prerender_manager.GetWeakPtr(); } - - // Case 3, 4: This can start prerendering because it has received a - // response. - // TODO(https://crbug.com/1295170): Do not start prerendering if this - // request is about to expire. - prerender_manager.StartPrerenderSearchResult(prefetch_search_terms_, - prefetch_url_); } void BaseSearchPrefetchRequest::ErrorEncountered() { @@ -367,15 +345,9 @@ void BaseSearchPrefetchRequest::OnServableResponseCodeReceived() { servable_response_code_received_ = true; - // TODO(https://crbug.com/1295170): Do not start prerendering if this request - // is about to expire. if (prerender_manager_) { - // Start prerender asynchronously, so that the request can prepare the data - // pipe completely. - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&PrerenderManager::StartPrerenderSearchResult, - prerender_manager_, prefetch_search_terms_, - prefetch_url_)); + prerender_manager_->StartPrerenderSearchResult(prefetch_search_terms_, + prefetch_url_); } } @@ -384,18 +356,6 @@ current_status_ = SearchPrefetchStatus::kCanBeServed; } -void BaseSearchPrefetchRequest::MarkPrefetchAsPrerendered() { - DCHECK(current_status_ == SearchPrefetchStatus::kCanBeServed || - current_status_ == SearchPrefetchStatus::kComplete); - current_status_ = SearchPrefetchStatus::kPrerendered; -} - -void BaseSearchPrefetchRequest::MarkPrefetchAsPrerenderActivated() { - DCHECK(current_status_ == SearchPrefetchStatus::kPrerenderedAndClicked || - current_status_ == SearchPrefetchStatus::kPrerendered); - current_status_ = SearchPrefetchStatus::kPrerenderActivated; -} - void BaseSearchPrefetchRequest::ResetPrerenderUpgrader() { prerender_manager_ = nullptr; } @@ -408,13 +368,8 @@ } void BaseSearchPrefetchRequest::MarkPrefetchAsClicked() { - DCHECK(current_status_ == SearchPrefetchStatus::kCanBeServed || - current_status_ == SearchPrefetchStatus::kPrerendered); - if (current_status_ == SearchPrefetchStatus::kCanBeServed) { - current_status_ = SearchPrefetchStatus::kCanBeServedAndUserClicked; - } else if (current_status_ == SearchPrefetchStatus::kPrerendered) { - current_status_ = SearchPrefetchStatus::kPrerenderedAndClicked; - } + DCHECK(current_status_ == SearchPrefetchStatus::kCanBeServed); + current_status_ = SearchPrefetchStatus::kCanBeServedAndUserClicked; } void BaseSearchPrefetchRequest::MarkPrefetchAsServed() {
diff --git a/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.h b/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.h index 5b154921..c38f13c 100644 --- a/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.h +++ b/chrome/browser/prefetch/search_prefetch/base_search_prefetch_request.h
@@ -16,10 +16,7 @@ class Profile; class SearchPrefetchURLLoader; -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -// Any updates to this class need to be propagated to SearchPrefetchFinalStatus -// in enums.xml. +// Any updates to this class need to be propagated to enums.xml. enum class SearchPrefetchStatus { // The request has not started yet. This status should ideally never be // recorded as Start() should be called on the same stack as creating the @@ -42,23 +39,11 @@ kComplete = 4, // The request hit an error and cannot be served. kRequestFailed = 5, - // The request was cancelled before completion. This is a terminal state. + // The request was cancelled before completion. This is terminal state. kRequestCancelled = 6, - // The request was served to the navigation stack. This is a terminal state. + // The request was served to the navigation stack. This is terminal state. kServed = 7, - // The request was served to the prerender navigation stack. It may move to - // |kPrerenderedAndClicked| when the user navigates to the result in omnibox - // or |kRequestCancelled| if the user closes omnibox. - kPrerendered = 8, - // Similar to |kCanBeServedAndUserClicked|, the request was served to the - // prerender navigation stack, and is marked as being - // clicked by the user. It is expected to move to |kPrerenderActivated| after - // the corresponding prerender is fully activated by the user. - kPrerenderedAndClicked = 9, - // The request was served to the prerender navigation stack, and the prerender - // page is fully activated by the user. This is a terminal state. - kPrerenderActivated = 10, - kMaxValue = kPrerenderActivated, + kMaxValue = kServed, }; // A class representing a prefetch used by the Search Prefetch Service. @@ -94,10 +79,6 @@ // Marks a prefetch as canceled and stops any ongoing fetch. void CancelPrefetch(); - // Returns true if this request should be canceled when the Autocomplete - // suggestion no longer lists this search prefetch. - bool ShouldBeCancelledOnResultChanges() const; - // Called when SearchPrefetchService receives the hint that this prefetch // request can be upgraded to a prerender attempt. void MaybeStartPrerenderSearchResult(PrerenderManager& prerender_manager); @@ -121,17 +102,9 @@ void MarkPrefetchAsClicked(); // Update the status when the request is actually served to the navigation - // stack of a real navigation request. + // stack. void MarkPrefetchAsServed(); - // Updates the status when the request is served to a prerendering navigation - // stack. Note that after this point, this request cannot be served to a real - // navigation anymore. - void MarkPrefetchAsPrerendered(); - - // Updates the status when the prerendering page it is serving was activated. - void MarkPrefetchAsPrerenderActivated(); - // Called when AutocompleteMatches changes. It resets PrerenderUpgrader. // And if the AutocompleteMatches suggests to prerender a search result, // `MaybeStartPrerenderSearchResult` will be called soon.
diff --git a/chrome/browser/prefetch/search_prefetch/search_prefetch_service.cc b/chrome/browser/prefetch/search_prefetch/search_prefetch_service.cc index af8614dd..e6788c2 100644 --- a/chrome/browser/prefetch/search_prefetch/search_prefetch_service.cc +++ b/chrome/browser/prefetch/search_prefetch/search_prefetch_service.cc
@@ -4,15 +4,11 @@ #include "chrome/browser/prefetch/search_prefetch/search_prefetch_service.h" -#include <iterator> -#include <memory> - #include "base/bind.h" #include "base/callback.h" #include "base/containers/contains.h" #include "base/json/values_util.h" #include "base/location.h" -#include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/values.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -84,18 +80,13 @@ struct SearchPrefetchServingReasonRecorder { public: - explicit SearchPrefetchServingReasonRecorder(bool for_prerender) - : for_prerender_(for_prerender) {} + SearchPrefetchServingReasonRecorder() = default; ~SearchPrefetchServingReasonRecorder() { - base::UmaHistogramEnumeration( - for_prerender_ - ? "Omnibox.SearchPrefetch.PrefetchServingReason.Prerender" - : "Omnibox.SearchPrefetch.PrefetchServingReason", - reason_); + UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchPrefetch.PrefetchServingReason", + reason_); } SearchPrefetchServingReason reason_ = SearchPrefetchServingReason::kServed; - const bool for_prerender_ = false; }; void RecordFinalStatus(SearchPrefetchStatus status, bool navigation_prefetch) { @@ -210,8 +201,7 @@ // If the prefetch is for navigation it can replace unservable statuses. if (!navigation_prefetch || status == SearchPrefetchStatus::kCanBeServed || status == SearchPrefetchStatus::kCanBeServedAndUserClicked || - status == SearchPrefetchStatus::kComplete || - status == SearchPrefetchStatus::kPrerendered) { + status == SearchPrefetchStatus::kComplete) { recorder.reason_ = SearchPrefetchEligibilityReason::kAttemptedQueryRecently; return false; @@ -275,9 +265,7 @@ } BaseSearchPrefetchRequest& prefetch = *prefetches_[match_search_terms]; prefetch.RecordClickTime(); - - if (prefetch.current_status() != SearchPrefetchStatus::kCanBeServed && - prefetch.current_status() != SearchPrefetchStatus::kPrerendered) { + if (prefetch.current_status() != SearchPrefetchStatus::kCanBeServed) { return; } prefetch.MarkPrefetchAsClicked(); @@ -287,56 +275,9 @@ const GURL& updated_prerendered_url, const GURL& prerendering_url) { DCHECK(prerender_utils::IsSearchSuggestionPrerenderEnabled()); - - // We do not need this method while running the search prefetch/prerender - // unification experiment. - DCHECK(!SearchPrefetchUpgradeToPrerenderIsEnabled()); AddCacheEntry(updated_prerendered_url, prerendering_url); } -void SearchPrefetchService::OnPrerenderedRequestUsed( - const std::u16string& search_terms, - const GURL& navigation_url) { - DCHECK(SearchPrefetchUpgradeToPrerenderIsEnabled()); - - auto request_it = prefetches_.find(search_terms); - DCHECK(request_it != prefetches_.end()); - if (request_it == prefetches_.end()) { - // TODO(https://crbug.com/1295170): It should be rare but the request can be - // deleted by timer before chrome activates the page. Add some metrics to - // understand the possibility. - return; - } - AddCacheEntry(navigation_url, request_it->second->prefetch_url()); - request_it->second->MarkPrefetchAsPrerenderActivated(); - prefetches_.erase(request_it); -} - -std::unique_ptr<SearchPrefetchURLLoader> -SearchPrefetchService::TakePrerenderFromMemoryCache( - const network::ResourceRequest& tentative_resource_request) { - SearchPrefetchServingReasonRecorder recorder{/*for_prerender=*/true}; - auto iter = - RetrieveSearchTermsInMemoryCache(tentative_resource_request, recorder); - if (iter == prefetches_.end()) { - return nullptr; - } - - // TODO(https://crbug.com/1295170): Do not use the prefetched response if it - // is about to expire. - DCHECK_NE(iter->second->current_status(), - SearchPrefetchStatus::kRequestFailed); - recorder.reason_ = SearchPrefetchServingReason::kPrerendered; - - iter->second->MarkPrefetchAsPrerendered(); - std::unique_ptr<SearchPrefetchURLLoader> response = - iter->second->TakeSearchPrefetchURLLoader(); - return response; - // Do not remove the corresponding entry from `prefetches_` for now, to avoid - // prefetching the same response over again. The entry will be removed on - // prerendering activation or other cases. -} - absl::optional<SearchPrefetchStatus> SearchPrefetchService::GetSearchPrefetchStatusForTesting( std::u16string search_terms) { @@ -349,12 +290,96 @@ SearchPrefetchService::TakePrefetchResponseFromMemoryCache( const network::ResourceRequest& tentative_resource_request) { const GURL& navigation_url = tentative_resource_request.url; - SearchPrefetchServingReasonRecorder recorder(/*for_prerender=*/false); + SearchPrefetchServingReasonRecorder recorder; - auto iter = - RetrieveSearchTermsInMemoryCache(tentative_resource_request, recorder); + auto* template_url_service = + TemplateURLServiceFactory::GetForProfile(profile_); + if (!template_url_service || + !template_url_service->GetDefaultSearchProvider()) { + recorder.reason_ = SearchPrefetchServingReason::kSearchEngineNotValid; + return nullptr; + } + + // The user may have disabled JS since the prefetch occured. + if (!profile_->GetPrefs() || + !profile_->GetPrefs()->GetBoolean(prefs::kWebKitJavascriptEnabled)) { + recorder.reason_ = SearchPrefetchServingReason::kJavascriptDisabled; + return nullptr; + } + + auto* content_settings = + HostContentSettingsMapFactory::GetForProfile(profile_); + if (!content_settings || + content_settings->GetContentSetting(navigation_url, navigation_url, + ContentSettingsType::JAVASCRIPT) == + CONTENT_SETTING_BLOCK) { + recorder.reason_ = SearchPrefetchServingReason::kJavascriptDisabled; + return nullptr; + } + + std::u16string search_terms; + template_url_service->GetDefaultSearchProvider()->ExtractSearchTermsFromURL( + navigation_url, template_url_service->search_terms_data(), &search_terms); + + if (search_terms.length() == 0) { + recorder.reason_ = SearchPrefetchServingReason::kNotDefaultSearchWithTerms; + return nullptr; + } + + const auto& iter = prefetches_.find(search_terms); + if (iter == prefetches_.end()) { - DCHECK_NE(recorder.reason_, SearchPrefetchServingReason::kServed); + recorder.reason_ = SearchPrefetchServingReason::kNoPrefetch; + return nullptr; + } + + // Verify that the URL is the same origin as the prefetch URL. While other + // checks should address this by clearing prefetches on user changes to + // default search, it is paramount to never serve content from one origin to + // another. + if (url::Origin::Create(navigation_url) != + url::Origin::Create(iter->second->prefetch_url())) { + recorder.reason_ = + SearchPrefetchServingReason::kPrefetchWasForDifferentOrigin; + return nullptr; + } + + if (iter->second->current_status() == + SearchPrefetchStatus::kRequestCancelled) { + recorder.reason_ = SearchPrefetchServingReason::kRequestWasCancelled; + return nullptr; + } + + if (iter->second->current_status() == SearchPrefetchStatus::kRequestFailed) { + recorder.reason_ = SearchPrefetchServingReason::kRequestFailed; + return nullptr; + } + + // POST requests are not supported since they are non-idempotent. Only support + // GET. + if (tentative_resource_request.method != + net::HttpRequestHeaders::kGetMethod) { + recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; + return nullptr; + } + + // If the client requests disabling, bypassing, or validating cache, don't + // return a prefetch. + // These are used mostly for reloads and dev tools. + if (tentative_resource_request.load_flags & net::LOAD_BYPASS_CACHE || + tentative_resource_request.load_flags & net::LOAD_DISABLE_CACHE || + tentative_resource_request.load_flags & net::LOAD_VALIDATE_CACHE) { + recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; + return nullptr; + } + + // Link clicks should not be served with a prefetch due to results page nth + // page matching the URL pattern of the DSE. + if (ui::PageTransitionCoreTypeIs( + static_cast<ui::PageTransition>( + tentative_resource_request.transition_type), + ui::PAGE_TRANSITION_LINK)) { + recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; return nullptr; } @@ -373,7 +398,7 @@ if (navigation_url != iter->second->prefetch_url()) AddCacheEntry(navigation_url, iter->second->prefetch_url()); - DeletePrefetch(iter->first); + DeletePrefetch(search_terms); return response; } @@ -437,7 +462,9 @@ const auto& search_terms = kv_pair.first; auto& prefetch_request = kv_pair.second; - if (!prefetch_request->ShouldBeCancelledOnResultChanges()) { + if (prefetch_request->current_status() != SearchPrefetchStatus::kInFlight && + prefetch_request->current_status() != + SearchPrefetchStatus::kCanBeServed) { // Reset all pending prerenders. It will be set soon if service still // wants clients to prerender a SearchTerms. // TODO(https://crbug.com/1295170): Unlike prefetch, which does not @@ -728,108 +755,3 @@ *prerender_manager); } } - -std::map<std::u16string, std::unique_ptr<BaseSearchPrefetchRequest>>::iterator -SearchPrefetchService::RetrieveSearchTermsInMemoryCache( - const network::ResourceRequest& tentative_resource_request, - SearchPrefetchServingReasonRecorder& recorder) { - const GURL& navigation_url = tentative_resource_request.url; - - auto* template_url_service = - TemplateURLServiceFactory::GetForProfile(profile_); - if (!template_url_service || - !template_url_service->GetDefaultSearchProvider()) { - recorder.reason_ = SearchPrefetchServingReason::kSearchEngineNotValid; - return prefetches_.end(); - } - - // The user may have disabled JS since the prefetch occurred. - if (!profile_->GetPrefs() || - !profile_->GetPrefs()->GetBoolean(prefs::kWebKitJavascriptEnabled)) { - recorder.reason_ = SearchPrefetchServingReason::kJavascriptDisabled; - return prefetches_.end(); - } - - auto* content_settings = - HostContentSettingsMapFactory::GetForProfile(profile_); - if (!content_settings || - content_settings->GetContentSetting(navigation_url, navigation_url, - ContentSettingsType::JAVASCRIPT) == - CONTENT_SETTING_BLOCK) { - recorder.reason_ = SearchPrefetchServingReason::kJavascriptDisabled; - return prefetches_.end(); - } - - std::u16string search_terms; - template_url_service->GetDefaultSearchProvider()->ExtractSearchTermsFromURL( - navigation_url, template_url_service->search_terms_data(), &search_terms); - - if (search_terms.length() == 0) { - recorder.reason_ = SearchPrefetchServingReason::kNotDefaultSearchWithTerms; - return prefetches_.end(); - } - - const auto& iter = prefetches_.find(search_terms); - - if (iter == prefetches_.end()) { - recorder.reason_ = SearchPrefetchServingReason::kNoPrefetch; - return prefetches_.end(); - } - - // Verify that the URL is the same origin as the prefetch URL. While other - // checks should address this by clearing prefetches on user changes to - // default search, it is paramount to never serve content from one origin to - // another. - if (url::Origin::Create(navigation_url) != - url::Origin::Create(iter->second->prefetch_url())) { - recorder.reason_ = - SearchPrefetchServingReason::kPrefetchWasForDifferentOrigin; - return prefetches_.end(); - } - - switch (iter->second->current_status()) { - case SearchPrefetchStatus::kRequestCancelled: - recorder.reason_ = SearchPrefetchServingReason::kRequestWasCancelled; - break; - case SearchPrefetchStatus::kRequestFailed: - recorder.reason_ = SearchPrefetchServingReason::kRequestFailed; - break; - case SearchPrefetchStatus::kPrerendered: - recorder.reason_ = SearchPrefetchServingReason::kPrerendered; - break; - default: - break; - } - if (recorder.reason_ != SearchPrefetchServingReason::kServed) - return prefetches_.end(); - - // POST requests are not supported since they are non-idempotent. Only support - // GET. - if (tentative_resource_request.method != - net::HttpRequestHeaders::kGetMethod) { - recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; - return prefetches_.end(); - } - - // If the client requests disabling, bypassing, or validating cache, don't - // return a prefetch. - // These are used mostly for reloads and dev tools. - if (tentative_resource_request.load_flags & net::LOAD_BYPASS_CACHE || - tentative_resource_request.load_flags & net::LOAD_DISABLE_CACHE || - tentative_resource_request.load_flags & net::LOAD_VALIDATE_CACHE) { - recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; - return prefetches_.end(); - } - - // Link clicks should not be served with a prefetch due to results page nth - // page matching the URL pattern of the DSE. - if (ui::PageTransitionCoreTypeIs( - static_cast<ui::PageTransition>( - tentative_resource_request.transition_type), - ui::PAGE_TRANSITION_LINK)) { - recorder.reason_ = SearchPrefetchServingReason::kPostReloadOrLink; - return prefetches_.end(); - } - - return iter; -}
diff --git a/chrome/browser/prefetch/search_prefetch/search_prefetch_service.h b/chrome/browser/prefetch/search_prefetch/search_prefetch_service.h index 1698476..a58c873 100644 --- a/chrome/browser/prefetch/search_prefetch/search_prefetch_service.h +++ b/chrome/browser/prefetch/search_prefetch/search_prefetch_service.h
@@ -40,12 +40,6 @@ struct ResourceRequest; } -namespace { -struct SearchPrefetchServingReasonRecorder; -} - -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. // Any updates to this class need to be propagated to enums.xml. enum class SearchPrefetchEligibilityReason { // The prefetch was started. @@ -70,8 +64,6 @@ kMaxValue = kThrottled, }; -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. // Any updates to this class need to be propagated to enums.xml. enum class SearchPrefetchServingReason { // The prefetch was started. @@ -94,9 +86,7 @@ kNotServedOtherReason = 8, // The navigation was a POST request, reload or link navigation. kPostReloadOrLink = 9, - // A prerender navigation request has taken this response away. - kPrerendered = 10, - kMaxValue = kPrerendered, + kMaxValue = kPostReloadOrLink, }; class SearchPrefetchService : public KeyedService, @@ -148,25 +138,12 @@ // key : The URL displayed on the location bar, The prerendered // page changes the `prerendering_url` by updating some parameters, so it // differs from `prerendering_url`. - // value: The URL sent by the corresponding prefetch request. + // value: The URL sent by a prerendering URL request. // TODO(https://crbug.com/1295170): This is a workaround. Remove this method // after the unification work is done. void AddCacheEntryForPrerender(const GURL& updated_prerendered_url, const GURL& prerendering_url); - // Called by `SearchPrerenderTask` upon prerender activation. - void OnPrerenderedRequestUsed(const std::u16string& search_terms, - const GURL& navigation_url); - - // A prefetch hint can be upgraded to prerender hint. Once the upgrade - // happens, prerendering navigation requests reuse the prefetched response. - // Differing from TakePrefetchResponseFromMemoryCache, this shares a copy of - // the prefetched response without removing the response from MemoryCache, to - // stop this from starting another prefetch attempt after prerender takes the - // response away. - std::unique_ptr<SearchPrefetchURLLoader> TakePrerenderFromMemoryCache( - const network::ResourceRequest& tentative_resource_request); - // Reports the status of a prefetch for a given search term. absl::optional<SearchPrefetchStatus> GetSearchPrefetchStatusForTesting( std::u16string search_terms); @@ -214,12 +191,6 @@ bool LoadFromPrefs(); void SaveToPrefs() const; - // Retrieved the started prefetches by search_terms. - std::map<std::u16string, std::unique_ptr<BaseSearchPrefetchRequest>>::iterator - RetrieveSearchTermsInMemoryCache( - const network::ResourceRequest& tentative_resource_request, - SearchPrefetchServingReasonRecorder& recorder); - // Called when this receives preloadable hints, and iff the // SearchPrefetchUpgradeToPrerender feature is enabled. The feature is running // on the assumption that Prerender is triggered after Prefetch receives
diff --git a/chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.cc b/chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.cc index d14480c2..6af0629 100644 --- a/chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.cc +++ b/chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.cc
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/feature_list.h" #include "base/metrics/histogram_macros.h" -#include "chrome/browser/prefetch/search_prefetch/field_trial_settings.h" #include "chrome/browser/prefetch/search_prefetch/search_prefetch_service.h" #include "chrome/browser/prefetch/search_prefetch/search_prefetch_service_factory.h" #include "chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader.h" @@ -41,24 +40,9 @@ return nullptr; } - // Only intercept primary main frame and prerender main frame requests. + // Only intercept main frame requests. content::RenderFrameHost* main_frame = web_contents->GetPrimaryMainFrame(); - bool is_primary_main_frame_navigation = - main_frame && main_frame->GetFrameTreeNodeId() == frame_tree_node_id; - - // Use the is_outermost_main_frame flag instead of obtaining the - // corresponding RenderFrameHost via the `frame_tree_node_id` and checking - // whether it has no parent frame, since the multipage architecture allows a - // RenderFrameHost to be attached to another node, and we should avoid - // relying on this dependency. - bool can_activate_for_prerender = - SearchPrefetchUpgradeToPrerenderIsEnabled() && - tentative_resource_request.is_outermost_main_frame && - web_contents->IsPrerenderedFrame(frame_tree_node_id); - - // This is not a primary navigation, nor can prerender use the prefetched - // response. - if (!is_primary_main_frame_navigation && !can_activate_for_prerender) { + if (!main_frame || main_frame->GetFrameTreeNodeId() != frame_tree_node_id) { return nullptr; } @@ -72,10 +56,6 @@ if (!service) return nullptr; - if (can_activate_for_prerender) { - return service->TakePrerenderFromMemoryCache(tentative_resource_request); - } - auto loader = service->TakePrefetchResponseFromMemoryCache(tentative_resource_request); if (loader)
diff --git a/chrome/browser/prefetch/search_prefetch/search_preload_unified_browsertest.cc b/chrome/browser/prefetch/search_prefetch/search_preload_unified_browsertest.cc index 934c1dcc..63ca9a6a 100644 --- a/chrome/browser/prefetch/search_prefetch/search_preload_unified_browsertest.cc +++ b/chrome/browser/prefetch/search_prefetch/search_preload_unified_browsertest.cc
@@ -32,7 +32,6 @@ #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/prerender_test_util.h" -#include "content/public/test/test_navigation_observer.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,16 +39,7 @@ #if BUILDFLAG(IS_ANDROID) #include "chrome/test/base/android/android_browser_test.h" #else // BUILDFLAG(IS_ANDROID) -#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/omnibox/browser/autocomplete_controller.h" -#include "components/omnibox/browser/autocomplete_provider.h" -#include "components/omnibox/browser/omnibox_edit_model.h" -#include "components/omnibox/browser/omnibox_view.h" #endif // BUILDFLAG(IS_ANDROID) namespace { @@ -225,17 +215,6 @@ } } - void NavigateToPrerenderedResult(const GURL& expected_prerender_url) { - content::TestNavigationObserver observer(GetActiveWebContents()); - GetActiveWebContents()->OpenURL(content::OpenURLParams( - expected_prerender_url, content::Referrer(), - WindowOpenDisposition::CURRENT_TAB, - ui::PageTransitionFromInt(ui::PAGE_TRANSITION_GENERATED | - ui::PAGE_TRANSITION_FROM_ADDRESS_BAR), - /*is_renderer_initiated=*/false)); - observer.Wait(); - } - content::test::PrerenderTestHelper& prerender_helper() { return prerender_helper_; } @@ -301,21 +280,11 @@ registry_observer.WaitForTrigger(expected_prerender_url); prerender_helper().WaitForPrerenderLoadCompletion(*GetActiveWebContents(), expected_prerender_url); - // Prefetch should be triggered as well. absl::optional<SearchPrefetchStatus> prefetch_status = search_prefetch_service()->GetSearchPrefetchStatusForTesting( base::ASCIIToUTF16(prerender_query)); - EXPECT_EQ(prefetch_status.value(), SearchPrefetchStatus::kPrerendered); - - // No prerender requests went through network, so there should be only one - // request. - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prerender_url)); - content::test::PrerenderHostObserver prerender_observer( - *GetActiveWebContents(), expected_prerender_url); - NavigateToPrerenderedResult(expected_prerender_url); - prerender_observer.WaitForActivation(); - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prerender_url)); + EXPECT_TRUE(prefetch_status.has_value()); } // Tests that the SearchSuggestionService can trigger prerendering if it @@ -330,8 +299,9 @@ std::string search_query_1 = "pre"; std::string prerender_query = "prerender"; - GURL expected_prefetch_url = + GURL expected_prerender_url = GetSearchUrl(prerender_query, /*attach_prefetch_flag=*/true); + content::test::PrerenderHostRegistryObserver registry_observer( *GetActiveWebContents()); @@ -346,25 +316,28 @@ WaitUntilStatusChangesTo( base::ASCIIToUTF16(prerender_query), {SearchPrefetchStatus::kCanBeServed, SearchPrefetchStatus::kComplete}); + std::string search_query_2 = "prer"; ChangeAutocompleteResult(search_query_2, prerender_query, PrerenderHint::kEnabled, PrefetchHint::kEnabled); - // The suggestion service should hint `expected_prefetch_url`, and + // The suggestion service should hint `expected_prerender_url`, and // prerendering for this url should start. - registry_observer.WaitForTrigger(expected_prefetch_url); + registry_observer.WaitForTrigger(expected_prerender_url); prerender_helper().WaitForPrerenderLoadCompletion(*GetActiveWebContents(), - expected_prefetch_url); + expected_prerender_url); - // No prerender requests went through network. - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prefetch_url)); // Activate. - content::test::PrerenderHostObserver prerender_observer( - *GetActiveWebContents(), expected_prefetch_url); - NavigateToPrerenderedResult(expected_prefetch_url); - prerender_observer.WaitForActivation(); - // No prerender requests went through network. - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prefetch_url)); + content::TestActivationManager activation_manager(GetActiveWebContents(), + expected_prerender_url); + GetActiveWebContents()->OpenURL(content::OpenURLParams( + expected_prerender_url, content::Referrer(), + WindowOpenDisposition::CURRENT_TAB, + ui::PageTransitionFromInt(ui::PAGE_TRANSITION_GENERATED | + ui::PAGE_TRANSITION_FROM_ADDRESS_BAR), + /*is_renderer_initiated=*/false)); + activation_manager.WaitForNavigationFinished(); + EXPECT_TRUE(activation_manager.was_activated()); } // Tests that the SearchSuggestionService will not trigger prerender if the @@ -449,140 +422,40 @@ *GetActiveWebContents()); // 1. Type the first query. - std::string search_query_1 = "pre"; - std::string prerender_query_1 = "prerender"; + std::string search_query_1 = "hang"; + std::string prerender_query_1 = "hang_body"; GURL expected_prerender_url = GetSearchUrl(prerender_query_1, /*attach_prefetch_flag=*/true); ChangeAutocompleteResult(search_query_1, prerender_query_1, PrerenderHint::kEnabled, PrefetchHint::kEnabled); - // 2. Prefetch and prerender should be triggered. - registry_observer.WaitForTrigger(expected_prerender_url); - prerender_helper().WaitForPrerenderLoadCompletion(*GetActiveWebContents(), - expected_prerender_url); - EXPECT_TRUE(prerender_manager()->HasSearchResultPagePrerendered()); + // 2. Prefetch should be triggered, and chrome is receiving the response body. absl::optional<SearchPrefetchStatus> prefetch_status = search_prefetch_service()->GetSearchPrefetchStatusForTesting( base::ASCIIToUTF16(prerender_query_1)); EXPECT_TRUE(prefetch_status.has_value()); - EXPECT_EQ(prefetch_status.value(), SearchPrefetchStatus::kPrerendered); - content::test::PrerenderHostObserver prerender_observer( - *GetActiveWebContents(), expected_prerender_url); - histogram_tester.ExpectBucketCount( - "Omnibox.SearchPrefetch.PrefetchServingReason.Prerender", - SearchPrefetchServingReason::kPrerendered, 1); + WaitUntilStatusChangesTo(base::ASCIIToUTF16(prerender_query_1), + {SearchPrefetchStatus::kCanBeServed}); - // 3. Type a different query which results in different suggestions. + // 3. prerendering should be triggered. + registry_observer.WaitForTrigger(expected_prerender_url); + EXPECT_TRUE(prerender_manager()->HasSearchResultPagePrerendered()); + + // 4. Type a different query which results in different suggestions. std::string search_query_2 = "pre"; ChangeAutocompleteResult(search_query_2, search_query_2, PrerenderHint::kDisabled, PrefetchHint::kEnabled); - // 4. The prerender will be destroyed automatically. - prerender_observer.WaitForDestroyed(); -} - -// Tests prerender is cancelled after SearchPrefetchService cancels prefetch -// requests. -IN_PROC_BROWSER_TEST_F(SearchPreloadUnifiedBrowserTest, DoNotRefetchSameTerms) { - base::HistogramTester histogram_tester; - const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html"); - ASSERT_TRUE(GetActiveWebContents()); - ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), kInitialUrl)); - SetUpContext(); - content::test::PrerenderHostRegistryObserver registry_observer( - *GetActiveWebContents()); - - // 1. Type the first query. - std::string search_query_1 = "pre"; - std::string prerender_query = "prerender"; - GURL expected_prerender_url = - GetSearchUrl(prerender_query, /*attach_prefetch_flag=*/true); - ChangeAutocompleteResult(search_query_1, prerender_query, - PrerenderHint::kEnabled, PrefetchHint::kEnabled); - - // 2. Prefetch and prerender should be triggered, and chrome is waiting for - // the body. - registry_observer.WaitForTrigger(expected_prerender_url); - prerender_helper().WaitForPrerenderLoadCompletion(*GetActiveWebContents(), - expected_prerender_url); - EXPECT_TRUE(prerender_manager()->HasSearchResultPagePrerendered()); - absl::optional<SearchPrefetchStatus> prefetch_status = - search_prefetch_service()->GetSearchPrefetchStatusForTesting( - base::ASCIIToUTF16(prerender_query)); - EXPECT_TRUE(prefetch_status.has_value()); - EXPECT_EQ(prefetch_status.value(), SearchPrefetchStatus::kPrerendered); - - // 3. Type a different query which results in the same suggestion. - std::string search_query_2 = "prer"; - ChangeAutocompleteResult(search_query_2, prerender_query, - PrerenderHint::kEnabled, PrefetchHint::kEnabled); - - // 4. Do not prefetch/prerender again. + // 5. The old prefetch should be cancelled. prefetch_status = search_prefetch_service()->GetSearchPrefetchStatusForTesting( - base::ASCIIToUTF16(prerender_query)); + base::ASCIIToUTF16(prerender_query_1)); EXPECT_TRUE(prefetch_status.has_value()); - EXPECT_EQ(prefetch_status.value(), SearchPrefetchStatus::kPrerendered); + WaitUntilStatusChangesTo(base::ASCIIToUTF16(prerender_query_1), + {SearchPrefetchStatus::kRequestCancelled}); - histogram_tester.ExpectBucketCount( - "Omnibox.SearchPrefetch.PrefetchEligibilityReason.SuggestionPrefetch", - SearchPrefetchEligibilityReason::kAttemptedQueryRecently, 1); + // 6. Prerender should be cancelled as well. + EXPECT_FALSE(prerender_manager()->HasSearchResultPagePrerendered()); } -// TODO(https://cubug.com/1282624): This test should run on Android after we're -// able to interact with Android UI. -#if !BUILDFLAG(IS_ANDROID) -IN_PROC_BROWSER_TEST_F(SearchPreloadUnifiedBrowserTest, TriggerAndActivate) { - base::HistogramTester histogram_tester; - const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html"); - ASSERT_TRUE(GetActiveWebContents()); - ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), kInitialUrl)); - SetUpContext(); - content::test::PrerenderHostRegistryObserver registry_observer( - *GetActiveWebContents()); - - // 1. Type the first query. - std::string search_query_1 = "pre"; - std::string prerender_query = "prerender"; - GURL expected_prerender_url = - GetSearchUrl(prerender_query, /*attach_prefetch_flag=*/true); - - // 2. Prepare some context. - AutocompleteInput input( - base::ASCIIToUTF16(prerender_query), metrics::OmniboxEventProto::BLANK, - ChromeAutocompleteSchemeClassifier(browser()->profile())); - LocationBar* location_bar = browser()->window()->GetLocationBar(); - OmniboxView* omnibox = location_bar->GetOmniboxView(); - AutocompleteController* autocomplete_controller = - omnibox->model()->autocomplete_controller(); - - // Prevent the stop timer from killing the hints fetch early. - autocomplete_controller->SetStartStopTimerDurationForTesting( - base::Seconds(10)); - - // 3. Trigger prerender and prefetch. - autocomplete_controller->Start(input); - ui_test_utils::WaitForAutocompleteDone(browser()); - ChangeAutocompleteResult(search_query_1, prerender_query, - PrerenderHint::kEnabled, PrefetchHint::kEnabled); - registry_observer.WaitForTrigger(expected_prerender_url); - prerender_helper().WaitForPrerenderLoadCompletion(*GetActiveWebContents(), - expected_prerender_url); - EXPECT_TRUE(prerender_manager()->HasSearchResultPagePrerendered()); - absl::optional<SearchPrefetchStatus> prefetch_status = - search_prefetch_service()->GetSearchPrefetchStatusForTesting( - base::ASCIIToUTF16(prerender_query)); - EXPECT_TRUE(prefetch_status.has_value()); - EXPECT_EQ(prefetch_status.value(), SearchPrefetchStatus::kPrerendered); - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prerender_url)); - - // 4. Click and activate. - content::test::PrerenderHostObserver prerender_observer( - *GetActiveWebContents(), expected_prerender_url); - omnibox->model()->AcceptInput(WindowOpenDisposition::CURRENT_TAB); - prerender_observer.WaitForActivation(); - EXPECT_EQ(1, prerender_helper().GetRequestCount(expected_prerender_url)); -} -#endif // BUILDFLAG(IS_ANDROID) - } // namespace
diff --git a/chrome/browser/prerender/prerender_manager.cc b/chrome/browser/prerender/prerender_manager.cc index c6d99be3..8af7e4c 100644 --- a/chrome/browser/prerender/prerender_manager.cc +++ b/chrome/browser/prerender/prerender_manager.cc
@@ -152,7 +152,7 @@ return prerendered_search_terms_; } - void OnActivated(content::WebContents& web_contents) const { + void MaybeAppendUrlEntry(content::WebContents& web_contents) const { if (!search_prerender_handle_) { return; } @@ -168,12 +168,6 @@ return; } - if (SearchPrefetchUpgradeToPrerenderIsEnabled()) { - search_prefetch_service->OnPrerenderedRequestUsed( - prerendered_search_terms_, web_contents.GetLastCommittedURL()); - return; - } - // TODO(https://crbug.com/1295170): This rule is hard coded according to // TemplateUrl, which is not good, and can be removed after the unification // work is done. @@ -460,9 +454,10 @@ search_prerender_task_->RecordLifeTimeMetric(); } - if (is_search_destination_match && + if (prerender_utils::ShouldUpdateCacheEntryManually() && + is_search_destination_match && navigation_handle->IsPrerenderedPageActivation()) { - search_prerender_task_->OnActivated(*web_contents()); + search_prerender_task_->MaybeAppendUrlEntry(*web_contents()); } search_prerender_task_.reset();
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index f15777a..4c04f24 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -65,7 +65,6 @@ #include "chrome/browser/permissions/adaptive_quiet_notification_permission_ui_enabler.h" #include "chrome/browser/permissions/last_tab_standing_tracker_factory.h" #include "chrome/browser/permissions/permission_auditing_service_factory.h" -#include "chrome/browser/persisted_state_db/persisted_state_db_content.pb.h" #include "chrome/browser/persisted_state_db/profile_proto_db_factory.h" #include "chrome/browser/plugins/plugin_prefs_factory.h" #include "chrome/browser/policy/cloud/user_cloud_policy_invalidator_factory.h" @@ -118,6 +117,7 @@ #include "chrome/common/chrome_features.h" #include "components/breadcrumbs/core/breadcrumbs_status.h" #include "components/captive_portal/core/buildflags.h" +#include "components/commerce/core/proto/persisted_state_db_content.pb.h" #include "components/optimization_guide/core/optimization_guide_switches.h" #include "components/optimization_guide/machine_learning_tflite_buildflags.h" #include "components/permissions/features.h"
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 9f003cc..11f54d1 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -136,6 +136,7 @@ #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" #include "components/send_tab_to_self/metrics_util.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/browser/spellcheck_host_metrics.h" #include "components/spellcheck/common/spellcheck_common.h" @@ -3331,7 +3332,7 @@ return; apps::AppLaunchParams launch_params( - *app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + *app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::CURRENT_TAB, apps::mojom::LaunchSource::kFromMenu); launch_params.override_url = params_.link_url; apps::AppServiceProxyFactory::GetForProfile(GetProfile())
diff --git a/chrome/browser/renderer_host/chrome_extension_message_filter.cc b/chrome/browser/renderer_host/chrome_extension_message_filter.cc index bfe79a8..6636018 100644 --- a/chrome/browser/renderer_host/chrome_extension_message_filter.cc +++ b/chrome/browser/renderer_host/chrome_extension_message_filter.cc
@@ -195,7 +195,7 @@ extension_id, base::Time::Now(), extensions::Action::ACTION_API_CALL, params.api_call); action->set_args(base::ListValue::From( - base::Value::ToUniquePtrValue(params.arguments.Clone()))); + std::make_unique<base::Value>(params.arguments.Clone()))); if (!params.extra.empty()) { action->mutable_other()->SetString( activity_log_constants::kActionExtra, params.extra); @@ -213,7 +213,7 @@ extension_id, base::Time::Now(), extensions::Action::ACTION_DOM_ACCESS, params.api_call); action->set_args(base::ListValue::From( - base::Value::ToUniquePtrValue(params.arguments.Clone()))); + std::make_unique<base::Value>(params.arguments.Clone()))); action->set_page_url(params.url); action->set_page_title(base::UTF16ToUTF8(params.url_title)); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, @@ -231,7 +231,7 @@ extension_id, base::Time::Now(), extensions::Action::ACTION_API_EVENT, params.api_call); action->set_args(base::ListValue::From( - base::Value::ToUniquePtrValue(params.arguments.Clone()))); + std::make_unique<base::Value>(params.arguments.Clone()))); if (!params.extra.empty()) { action->mutable_other()->SetString(activity_log_constants::kActionExtra, params.extra);
diff --git a/chrome/browser/renderer_host/chrome_extension_message_filter.h b/chrome/browser/renderer_host/chrome_extension_message_filter.h index c02a096a..83c1189 100644 --- a/chrome/browser/renderer_host/chrome_extension_message_filter.h +++ b/chrome/browser/renderer_host/chrome_extension_message_filter.h
@@ -63,9 +63,6 @@ void OnAddAPIActionToExtensionActivityLog( const std::string& extension_id, const ExtensionHostMsg_APIActionOrEvent_Params& params); - void OnAddBlockedCallToExtensionActivityLog( - const std::string& extension_id, - const std::string& function_name); void OnAddDOMActionToExtensionActivityLog( const std::string& extension_id, const ExtensionHostMsg_DOMAction_Params& params);
diff --git a/chrome/browser/resources/chromeos/BUILD.gn b/chrome/browser/resources/chromeos/BUILD.gn index 9e4bd82..de125c9 100644 --- a/chrome/browser/resources/chromeos/BUILD.gn +++ b/chrome/browser/resources/chromeos/BUILD.gn
@@ -22,6 +22,7 @@ "launcher_internals:resources", "login:conditional_resources", "login:unconditional_resources", + "manage_mirrorsync:resources", "multidevice_internals:resources", "network_ui:resources", "notification_tester:resources",
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.html b/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.html index 44871d2..1a5ac204 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.html +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.html
@@ -140,6 +140,10 @@ z-index: -2; } + .hidden { + display: none; + } + #bar { background-color: var(--cros-icon-color-prominent); border-top-left-radius: 2px; @@ -354,59 +358,18 @@ on-transitionstart="onBarTransitionStart"></div> </div> <div class="divider"></div> - <div class="side-padding" id="groups" on-scroll="onEmojiScroll"> - <!-- - history is the "recently used" group and is populated in code, - whereas the other groups are created from the emoji metadata. - --> - - <div data-group="emoji-history"> - <template is="dom-if" - if="[[isHistoryGroupVisible( - categoryHistoryVisibility.emoji, - categoriesHistory.emoji.data.history)]]"> - <emoji-group - data="[[getHistoryEmojis(categoriesHistory.emoji.data.history)]]" - group="Recently used" - preferred="{}" clearable class="group history" - category="emoji"> - </emoji-group> - </template> - </div> - <template is="dom-repeat" items="[[emojiData]]"> - <div data-group$="[[getDataGroupIndex('emoji', index)]]"> - <emoji-group data="[[item.emoji]]" group="[[item.group]]" - preferred="{{categoriesHistory.emoji.data.preference}}" - class="group" category="emoji"> + <template is="dom-repeat" items="[[categoriesGroupElements]]"> + <div data-group$="[[item.groupId]]"> + <emoji-group data="[[item.emoji]]" + group="[[item.name]]" + preferred="[[item.preferences]]" + clearable$="[[item.isHistory]]" + category$="[[item.category]]" + class$="[[getEmojiGroupClassNames(item.isHistory,item.emoji)]]"> </emoji-group> </div> </template> - <div class="category-gap"></div> - <!-- Start of emoticon groups. --> - <template is="dom-if" if="[[v2Enabled]]"> - <div data-group="emoticon-history"> - <template is="dom-if" - if="[[isHistoryGroupVisible( - categoryHistoryVisibility.emoticon, - categoriesHistory.emoticon.data.history)]]"> - <emoji-group - data="[[getHistoryEmojis( - categoriesHistory.emoticon.data.history)]]" - group="Recently used" - preferred="{}" clearable class="group history" - category="emoticon"> - </emoji-group> - </template> - </div> - <template is="dom-repeat" items="[[emoticonData]]"> - <div data-group$="[[getDataGroupIndex('emoticon', index)]]"> - <emoji-group data="[[item.emoji]]" group="[[item.group]]" - class="group" category="emoticon"> - </emoji-group> - </div> - </template> - </template> </div> </div>
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.js b/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.js index 393ac77b..0b506d523 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.js +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_picker.js
@@ -14,9 +14,9 @@ import {Feature} from './emoji_picker.mojom-webui.js'; import {EmojiPickerApiProxy, EmojiPickerApiProxyImpl} from './emoji_picker_api_proxy.js'; import * as events from './events.js'; -import {CATEGORY_METADATA, EMOJI_GROUP_TABS, V2_SUBCATEGORY_TABS} from './metadata_extension.js'; +import {CATEGORY_METADATA, EMOJI_GROUP_TABS, V2_SUBCATEGORY_TABS, V2_TABS_CATEGORY_START_INDEX} from './metadata_extension.js'; import {RecentlyUsedStore} from './store.js'; -import {CategoryData, CategoryEnum, EmojiGroup, EmojiGroupData, EmojiVariants, StoredItem, SubcategoryData} from './types.js'; +import {CategoryData, CategoryEnum, EmojiGroup, EmojiGroupData, EmojiVariants, SubcategoryData, EmojiGroupElement} from './types.js'; const EMOJI_ORDERING_JSON_TEMPLATE = '/emoji_14_0_ordering'; const EMOTICON_ORDERING_JSON_TEMPLATE = '/emoticon_ordering.json'; @@ -42,16 +42,10 @@ /** @type {string} */ /** @private {!Array<!SubcategoryData>} */ emojiGroupTabs: {type: Array}, - /** @private {?EmojiGroupData} */ - emojiData: { - type: Array, - value: () => ([]), - observer: 'onEmojiDataChanged', - }, - /** @private {EmojiGroupData} */ + /** @type {EmojiGroupData} */ categoriesData: {type: Array, value: () => ([])}, - /** @type {?EmojiGroupData} */ - emoticonData: {type: Array, value: () => ([])}, + /** @type {Array<EmojiGroupElement>} */ + categoriesGroupElements: {type: Array, value: () => ([])}, /** @private {Object<CategoryEnum,RecentlyUsedStore>} */ categoriesHistory: {type: Object, value: () => ({})}, /** @private {number} */ @@ -73,8 +67,6 @@ searchExtensionEnabled: {type: Boolean, value: false}, /** @private {boolean} */ incognito: {type: Boolean, value: true}, - /** @private {Object<CategoryEnum,Boolean>} */ - categoryHistoryVisibility: {type: Object, value: () => ({})}, }; } @@ -85,7 +77,6 @@ this.updateIncognitoState(this.incognito); this.emojiGroupTabs = EMOJI_GROUP_TABS; - this.emojiData = []; /** @private {?number} */ this.scrollTimeout = null; @@ -239,23 +230,32 @@ emojiGroup.category = category; }); - // Allow history group to be visible. - this.updateHistoryVisibility(category, true); - - // TODO(b/235418846): Remove the following. - // Update the data variable of the category. - switch (category) { - case CategoryEnum.EMOJI: - this.push('emojiData', ...data); - break; - case CategoryEnum.EMOTICON: - this.push('emoticonData', ...data); - break; - default: - throw new Error(`Unknown category ${category}.`); + // Create recently used emoji group for the category as its first + // group element. + if (V2_TABS_CATEGORY_START_INDEX[category] === + this.categoriesGroupElements.length) { + const historyGroupElement = this.createEmojiGroupElement( + this.getHistoryEmojis(category), {}, true, + V2_TABS_CATEGORY_START_INDEX[category]); + this.push('categoriesGroupElements', historyGroupElement); } + // Convert the emoji group data to elements. + const baseIndex = this.categoriesGroupElements.length; + const categoriesGroupElements = data.map( + (emojiGroup, index) => + this.createEmojiGroupElement( + emojiGroup.emoji, + this.getEmojiGroupPreference(category), + false, + baseIndex + index + ) + ); + + // Update emoji data for other features such as search. this.push('categoriesData', ...data); + // Update group elements for the emoji picker. + this.push('categoriesGroupElements', ...categoriesGroupElements); // If all data is fetched, trigger search index. if (lastPartition) { @@ -620,44 +620,18 @@ } /** - * Sets the visibility of the history group for a category. + * Gets recently used emojis for a category. It gets the history items + * and convert them to emojis. * - * @param {CategoryEnum} category - * @param {boolean} visible If history group needs to be visible or hidden. - */ - updateHistoryVisibility(category, visible) { - // TODO(b/235418846): Remove the func when adding history to emoji groups. - this.set(['categoryHistoryVisibility', category], visible); - } - - /** - * Checks if history group need to be visible in the UI. - * - * @param {?boolean} visible True if the history group is allowed to be - * visible. - * @param {?Array<StoredItem>} historyDataItems Array of history items. - * @returns {?boolean} True if there are history items and group is allowed - * to be visible and False otherwise. - */ - isHistoryGroupVisible(visible, historyDataItems) { - // TODO(b/235418846): Remove the func when adding history to emoji groups. - return visible && historyDataItems && historyDataItems.length > 0; - } - - /** - * Converts history stored items to list of emojis. - * - * @param {!Array<StoredItem>} storedItems List of recently used stored - * items. + * @param {CategoryEnum} category Category of the history. * @return {!Array<EmojiVariants>} List of emojis. */ - getHistoryEmojis(storedItems) { - // TODO(b/235418846): Change the argument to category. - if (!storedItems) { + getHistoryEmojis(category) { + if (this.incognito) { return []; } - return storedItems.map( + return this.categoriesHistory[category].data.history.map( emoji => ({ base: {string: emoji.base, name: emoji.name, keywords: []}, alternates: emoji.alternates @@ -675,15 +649,22 @@ categoryHistoryUpdated(category, historyUpdated = true, preferenceUpdated = true) { - // TODO(b/235418846): Remove the notifications. - // Notify the path that is updated. Manual update is required given - // history storage is outside Polymer but HTML depends on it. - if(historyUpdated) { - this.notifyPath(`categoriesHistory.${category}.data.history`); + // History item is assumed to be the first item of each category. + const historyIndex = V2_TABS_CATEGORY_START_INDEX[category]; + + // If history group is already added, then update it. + if (historyUpdated && + historyIndex < this.categoriesGroupElements.length) { + this.set( + ['categoriesGroupElements', historyIndex, 'emoji'], + this.getHistoryEmojis(category)); } - if(preferenceUpdated) { - this.notifyPath(`categoriesHistory.${category}.data.preference`); - } + + // Note: preference update is not handled because it is an expensive + // operation and adds no value to the current version. + // If needed in the future, its addition requires iterating over all + // categoriesGroupElement of the category and setting their preferences + // here. } /** @@ -694,20 +675,11 @@ */ updateIncognitoState(incognito) { this.incognito = incognito; - - // TODO(b/235418846): Remove the dummy history. - // Set the recently used to a dummy history for incognito state. - // This is used to reduce the complexity for handling of special - // case of empty history when rendering the UI. - // Note: no data must be saved in the dummy history. - const dummyRecentlyUsed = incognito ? - new RecentlyUsedStore('dummy-empty-recently-used') : null; - - // Load the history items for each category. + // Load the history item for each category. for (const category of Object.values(CategoryEnum)) { - this.categoriesHistory[category] = incognito ? - dummyRecentlyUsed : new RecentlyUsedStore(`${category}-recently-used`); - this.categoryHistoryUpdated(category, true, true); + this.categoriesHistory[category] = + incognito ? null : new RecentlyUsedStore(`${category}-recently-used`); + this.categoryHistoryUpdated(category); } } @@ -761,6 +733,56 @@ } /** + * Gets HTML classes for an emoji group element. + * + * @param {boolean} isHistory If group is history. + * @param {Array<EmojiVariants>} emojis List of emojis + * @returns {string} HTML element class attribute. + */ + getEmojiGroupClassNames(isHistory, emojis) { + const baseClassNames = isHistory ? 'group history' : 'group'; + + // Make emoji hidden if it is empty. + // Note: Filtering empty groups in dom-repeat is expensive due to + // re-rendering, so making it hidden is more efficient. + if (!emojis || emojis.length === 0) { + return baseClassNames + ' hidden'; + } + return baseClassNames; + } + + /** + * Create an instance of emoji group element. + * + * @param {Array<EmojiVariants>} emoji List of emojis. + * @param {Object<string,string>} preferences Preferences for emojis. + * @param {boolean} isHistory True if group is for history. + * @param {!number} subcategoryIndex Index of the group in subcategory data. + * @returns {EmojiGroupElement} Instance of emoji group element. + */ + createEmojiGroupElement(emoji, preferences, isHistory, subcategoryIndex) { + const baseDetails = { + 'emoji': emoji, + 'preferences': preferences, + 'isHistory': isHistory, + }; + return /** @type {EmojiGroupElement} */ ( + Object.assign( + {}, baseDetails, V2_SUBCATEGORY_TABS[subcategoryIndex])); + } + + /** + * Gets preferences for an emoji group. + * + * @param {CategoryEnum} category Category of the emoji group. + * @returns {Object<string,string>} Preferences. + */ + getEmojiGroupPreference(category) { + return this.incognito ? [] : + this.categoriesHistory[category].data.preference; + } + + /** * @param {!events.EmojiVariantsShownEvent} ev */ onShowEmojiVariants(ev) { @@ -842,24 +864,6 @@ } /** - * Fires DATA_LOADED_EVENT when emoji data is loaded and the emoji picker - * is ready to use. - */ - onEmojiDataChanged(newValue, oldValue) { - // This is separate from onEmojiDataLoaded because we need to ensure - // Polymer has created the components for the emoji after setting - // this.emojiData. This is an observer, so will run after the component - // tree has been updated. - - // see: - // https://polymer-library.polymer-project.org/3.0/docs/devguide/data-system#property-effects - - if (newValue && newValue.length) { - this.dispatchEvent(events.createCustomEvent(events.EMOJI_DATA_LOADED)); - } - } - - /** * Triggers when category property changes * @param {string} newCategoryName */ @@ -929,20 +933,6 @@ } /** - * Calculate the data group index for different categories - * that matches with the group id from subcategory metadata. - * @param {string} category - * @param {number} offsetIndex - * @returns - */ - getDataGroupIndex(category, offsetIndex) { - // TODO(b/235418846): Remove the func after adding history to emoji groups. - const firstTabByCategory = V2_SUBCATEGORY_TABS.find( - tab => tab.category === category && !tab.groupId.includes('history')); - return parseInt(firstTabByCategory.groupId, 10) + offsetIndex; - } - - /** * @param {string} groupId * @returns {number} * @throws Thrown when no tab with id that matches the given groupId is found.
diff --git a/chrome/browser/resources/chromeos/emoji_picker/metadata_extension.js b/chrome/browser/resources/chromeos/emoji_picker/metadata_extension.js index a85d518a..1271cb0 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/metadata_extension.js +++ b/chrome/browser/resources/chromeos/emoji_picker/metadata_extension.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. +const RECENTLY_USED_NAME = 'Recently used'; + export const CATEGORY_METADATA = [ { name: 'emoji', @@ -25,7 +27,7 @@ // TODO(b/233271528): Remove the list and load it from the input data. export const EMOJI_GROUP_TABS = [ { - name: 'Recently Used', + name: RECENTLY_USED_NAME, icon: 'emoji_picker:schedule', category: 'emoji', groupId: 'emoji-history', @@ -34,7 +36,7 @@ pagination: 1 }, { - name: 'Smileys & Emotion', + name: 'Smileys & Emotions', icon: 'emoji_picker:insert_emoticon', category: 'emoji', groupId: '0', @@ -74,7 +76,7 @@ disabled: false }, { - name: 'Activities', + name: 'Activities & Events', icon: 'emoji_picker:emoji_events', category: 'emoji', groupId: '5', @@ -111,7 +113,7 @@ // TODO(b/233271528): Remove the list and load it from the input data. export const EMOTICON_GROUP_TABS = [ { - name: 'Recently Used', + name: RECENTLY_USED_NAME, icon: 'emoji_picker:schedule', category: 'emoticon', groupId: 'emoticon-history', @@ -192,7 +194,7 @@ pagination: 2 }, { - name: 'Table flipping', + name: 'Table Flipping', category: 'emoticon', groupId: '18', active: false, @@ -244,3 +246,9 @@ // TODO(b/233271528): The concat order must be based on CATEGORY_METADATA. export const V2_SUBCATEGORY_TABS = EMOJI_GROUP_TABS.concat(EMOTICON_GROUP_TABS); + +// TODO(b/233271528): This should be calculated based on concat order. +export const V2_TABS_CATEGORY_START_INDEX = { + 'emoji': 0, + 'emoticon': EMOJI_GROUP_TABS.length, +};
diff --git a/chrome/browser/resources/chromeos/emoji_picker/types.js b/chrome/browser/resources/chromeos/emoji_picker/types.js index 0f73665..729f110 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/types.js +++ b/chrome/browser/resources/chromeos/emoji_picker/types.js
@@ -41,6 +41,14 @@ export let SubcategoryData; /** + * @typedef {{name: string, category: string, emoji: Array<EmojiVariants>, + * groupId: string, activate: boolean, disabled: boolean, + * pagination: ?number, preferences: Object<string,string>, + * isHistory: boolean}} EmojiGroupElement + */ +export let EmojiGroupElement; + +/** * @enum {string} */ export const CategoryEnum = {
diff --git a/chrome/browser/resources/chromeos/manage_mirrorsync/BUILD.gn b/chrome/browser/resources/chromeos/manage_mirrorsync/BUILD.gn new file mode 100644 index 0000000..ee83b2d0 --- /dev/null +++ b/chrome/browser/resources/chromeos/manage_mirrorsync/BUILD.gn
@@ -0,0 +1,67 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//tools/grit/grit_rule.gni") +import("//tools/typescript/ts_library.gni") +import("//ui/webui/resources/tools/generate_grd.gni") + +# Copy all the source files into the gen/ directory. +copy("copy_src") { + sources = [ + "browser_proxy.ts", + "mirrorsync.ts", + ] + outputs = [ "$target_gen_dir/{{source_file_part}}" ] +} + +# Mojo bindings are generated in the corresponding webui folder, copy the JS +# binding outputs to the same gen/ directory as above. +copy("copy_mojo") { + deps = [ "//chrome/browser/ui/webui/chromeos/manage_mirrorsync:mojo_bindings_webui_js" ] + sources = [ "$root_gen_dir/mojom-webui/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom-webui.js" ] + outputs = [ "$target_gen_dir/{{source_file_part}}" ] +} + +ts_library("build_ts") { + root_dir = "$target_gen_dir" + out_dir = "$target_gen_dir/tsc" + in_files = [ + "mirrorsync.ts", + "browser_proxy.ts", + "manage_mirrorsync.mojom-webui.js", + ] + tsconfig_base = "tsconfig_base.json" + extra_deps = [ + ":copy_mojo", + ":copy_src", + ] +} + +resources_grd_file = "$target_gen_dir/resources.grd" + +# Generate a grd file dynamically, this takes static files via `input_files` and +# all the files ran through tsc (via the output manifest_files). +generate_grd("build_grd") { + input_files_base_dir = rebase_path(".", "//") + deps = [ ":build_ts" ] + input_files = [ "index.html" ] + manifest_files = + filter_include(get_target_outputs(":build_ts"), [ "*.manifest" ]) + + grd_prefix = "manage_mirrorsync" + out_grd = resources_grd_file +} + +grit("resources") { + enable_input_discovery_for_gn_analyze = false + source = resources_grd_file + deps = [ ":build_grd" ] + outputs = [ + "grit/manage_mirrorsync_resources.h", + "grit/manage_mirrorsync_resources_map.cc", + "grit/manage_mirrorsync_resources_map.h", + "manage_mirrorsync_resources.pak", + ] + output_dir = "$root_gen_dir/chrome" +}
diff --git a/chrome/browser/resources/chromeos/manage_mirrorsync/browser_proxy.ts b/chrome/browser/resources/chromeos/manage_mirrorsync/browser_proxy.ts new file mode 100644 index 0000000..c9c2c0a --- /dev/null +++ b/chrome/browser/resources/chromeos/manage_mirrorsync/browser_proxy.ts
@@ -0,0 +1,24 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {PageHandlerFactory, PageHandlerRemote} from './manage_mirrorsync.mojom-webui.js'; + +export class BrowserProxy { + handler: PageHandlerRemote = new PageHandlerRemote(); + + constructor() { + const factory = PageHandlerFactory.getRemote(); + factory.createPageHandler(this.handler.$.bindNewPipeAndPassReceiver()); + } + + static getInstance(): BrowserProxy { + return instance || (instance = new BrowserProxy()); + } + + static setInstance(obj: BrowserProxy) { + instance = obj; + } +} + +let instance: BrowserProxy|null = null; \ No newline at end of file
diff --git a/chrome/browser/resources/chromeos/manage_mirrorsync/index.html b/chrome/browser/resources/chromeos/manage_mirrorsync/index.html index e1ee5c567..0a23830d9 100644 --- a/chrome/browser/resources/chromeos/manage_mirrorsync/index.html +++ b/chrome/browser/resources/chromeos/manage_mirrorsync/index.html
@@ -1 +1,2 @@ +<script type="module" src="mirrorsync.js"></script> <h1>Manage MirrorSync</h1> \ No newline at end of file
diff --git a/chrome/browser/resources/chromeos/manage_mirrorsync/mirrorsync.ts b/chrome/browser/resources/chromeos/manage_mirrorsync/mirrorsync.ts new file mode 100644 index 0000000..9e3ef10 --- /dev/null +++ b/chrome/browser/resources/chromeos/manage_mirrorsync/mirrorsync.ts
@@ -0,0 +1,13 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {BrowserProxy} from './browser_proxy.js'; + +async function initialize() { + const proxy = BrowserProxy.getInstance().handler; + /* eslint-disable no-console */ + console.log(await proxy.getSyncingPaths()); +} + +document.addEventListener('DOMContentLoaded', initialize); \ No newline at end of file
diff --git a/chrome/browser/resources/chromeos/manage_mirrorsync/tsconfig_base.json b/chrome/browser/resources/chromeos/manage_mirrorsync/tsconfig_base.json new file mode 100644 index 0000000..675f8cc --- /dev/null +++ b/chrome/browser/resources/chromeos/manage_mirrorsync/tsconfig_base.json
@@ -0,0 +1,8 @@ +{ + "extends": "../../../../../tools/typescript/tsconfig_base.json", + "compilerOptions": { + "allowJs": true, + "inlineSourceMap": true, + "inlineSources": true + } +} \ No newline at end of file
diff --git a/chrome/browser/sync/sync_startup_tracker.cc b/chrome/browser/sync/sync_startup_tracker.cc index bce18f12..8e5783d 100644 --- a/chrome/browser/sync/sync_startup_tracker.cc +++ b/chrome/browser/sync/sync_startup_tracker.cc
@@ -44,12 +44,14 @@ } void SyncStartupTracker::CheckServiceState() { - ServiceStartupState state = is_timed_out_ - ? ServiceStartupState::kTimeout - : GetServiceStartupState(sync_service_); + ServiceStartupState state = GetServiceStartupState(sync_service_); if (state == ServiceStartupState::kPending) { - // Do nothing - still waiting for sync to finish starting up. - return; + if (is_timed_out_) { + state = ServiceStartupState::kTimeout; + } else { + // Do nothing - still waiting for sync to finish starting up. + return; + } } timeout_waiter_.Stop();
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModel.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModel.java index 729e40b..6142a50 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModel.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModel.java
@@ -23,7 +23,7 @@ * EmptyTabModel. */ @VisibleForTesting - protected EmptyTabModel() {} + public EmptyTabModel() {} // "Initialization on demand holder idiom" private static class LazyHolder {
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterProvider.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterProvider.java index 65746b0..eb6c2457 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterProvider.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterProvider.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.tabmodel; +import androidx.annotation.VisibleForTesting; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -14,10 +16,12 @@ * and one for incognito {@link TabModel}. */ public class TabModelFilterProvider implements TabModelSelectorObserver { - private List<TabModelFilter> mTabModelFilterList = Collections.emptyList(); + @VisibleForTesting + public List<TabModelFilter> mTabModelFilterList = Collections.emptyList(); private final List<TabModelObserver> mPendingTabModelObserver = new ArrayList<>(); - TabModelFilterProvider() {} + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public TabModelFilterProvider() {} public void init(TabModelFilterFactory tabModelFilterFactory, List<TabModel> tabModels) { assert mTabModelFilterList.isEmpty();
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b93b7391..659351f 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2769,6 +2769,8 @@ "webui/chromeos/login/wrong_hwid_screen_handler.h", "webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.cc", "webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h", + "webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.cc", + "webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h", "webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.cc", "webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h", "webui/chromeos/multidevice_internals/multidevice_internals_logs_handler.cc", @@ -3122,6 +3124,7 @@ "//chrome/browser/ui/webui/chromeos/audio:mojo_bindings", "//chrome/browser/ui/webui/chromeos/crostini_upgrader:mojo_bindings", "//chrome/browser/ui/webui/chromeos/launcher_internals:mojo_bindings", + "//chrome/browser/ui/webui/chromeos/manage_mirrorsync:mojo_bindings", "//chrome/browser/ui/webui/chromeos/parent_access:mojo_bindings", "//chrome/browser/ui/webui/chromeos/parent_access:proto", "//chrome/browser/ui/webui/chromeos/vm:mojo_bindings",
diff --git a/chrome/browser/ui/android/favicon/java/src/org/chromium/chrome/browser/ui/favicon/FaviconHelper.java b/chrome/browser/ui/android/favicon/java/src/org/chromium/chrome/browser/ui/favicon/FaviconHelper.java index 899884bd2..8b075b3 100644 --- a/chrome/browser/ui/android/favicon/java/src/org/chromium/chrome/browser/ui/favicon/FaviconHelper.java +++ b/chrome/browser/ui/android/favicon/java/src/org/chromium/chrome/browser/ui/favicon/FaviconHelper.java
@@ -16,6 +16,7 @@ import androidx.annotation.ColorInt; import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.annotations.CalledByNative; @@ -216,8 +217,9 @@ urls.toArray(new GURL[0]), desiredSizeInPixel, faviconImageCallback); } + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) @NativeMethods - interface Natives { + public interface Natives { long init(); void destroy(long nativeFaviconHelper); boolean getComposedFaviconImage(long nativeFaviconHelper, Profile profile, GURL[] urls,
diff --git a/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/ConfirmManagedSyncDataDialogTest.java b/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/ConfirmManagedSyncDataDialogTest.java index 633e3cb..2b9c067b 100644 --- a/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/ConfirmManagedSyncDataDialogTest.java +++ b/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/ConfirmManagedSyncDataDialogTest.java
@@ -36,6 +36,7 @@ import org.chromium.base.test.util.ApplicationTestUtils; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.test.util.TestThreadUtils; @@ -101,6 +102,7 @@ @Test @LargeTest + @DisabledTest(message = "https://crbug.com/1341379") public void testDialogIsDismissedAndOnCancelNotCalledWhenRecreated() { showManagedSyncDataDialog(); onView(withText(R.string.sign_in_managed_account))
diff --git a/chrome/browser/ui/ash/desks/desks_client_browsertest.cc b/chrome/browser/ui/ash/desks/desks_client_browsertest.cc index 187d342..aee8bc4 100644 --- a/chrome/browser/ui/ash/desks/desks_client_browsertest.cc +++ b/chrome/browser/ui/ash/desks/desks_client_browsertest.cc
@@ -78,6 +78,7 @@ #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" #include "components/policy/policy_constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/tab_groups/tab_group_color.h" #include "components/tab_groups/tab_group_visual_data.h" @@ -234,7 +235,7 @@ app_type == ash::SystemWebAppType::HELP); web_app::AppId app_id = *web_app::GetAppIdForSystemWebApp(profile, app_type); apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); params.restore_id = app_type == ash::SystemWebAppType::SETTINGS ? kSettingsWindowId @@ -831,7 +832,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<app_restore::AppLaunchInfo>( - extension_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + extension_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr)); @@ -1887,7 +1888,7 @@ ::full_restore::SaveAppLaunchInfo( profile()->GetPath(), std::make_unique<app_restore::AppLaunchInfo>( - extension_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + extension_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId, std::vector<base::FilePath>{}, nullptr));
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc index fc3fcfa..087cea1 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_browsertest.cc
@@ -111,6 +111,7 @@ #include "components/app_constants/constants.h" #include "components/crx_file/id_util.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" @@ -1694,7 +1695,7 @@ EXPECT_TRUE(extension); apps::AppServiceProxyFactory::GetForProfile(profile())->LaunchAppWithParams( apps::AppLaunchParams(extension->id(), - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest));
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index 73af1a6a..f8ce67b 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -89,6 +89,7 @@ #include "components/javascript_dialogs/tab_modal_dialog_manager.h" #include "components/omnibox/common/omnibox_focus_state.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/sessions/core/command_storage_manager_test_helper.h" #include "components/translate/core/browser/language_state.h" #include "components/translate/core/common/language_detection_details.h" @@ -1265,7 +1266,7 @@ ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( extension_app->id(), - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); ASSERT_TRUE(app_window); @@ -1449,7 +1450,7 @@ ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( extension_app->id(), - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); ASSERT_TRUE(app_window);
diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index cb7b5a30..4b2bbcdd 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc
@@ -115,6 +115,7 @@ #include "components/reading_list/core/reading_list_entry.h" #include "components/reading_list/core/reading_list_model.h" #include "components/reading_list/core/reading_list_pref_names.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sessions/core/live_tab_context.h" #include "components/sessions/core/tab_restore_service.h" @@ -687,13 +688,12 @@ if (browser->app_controller()) { const web_app::AppId app_id = browser->app_controller()->app_id(); - auto launch_container = - apps::mojom::LaunchContainer::kLaunchContainerWindow; + auto launch_container = apps::LaunchContainer::kLaunchContainerWindow; auto* provider = web_app::WebAppProvider::GetForWebApps(profile); if (provider && provider->registrar().GetAppEffectiveDisplayMode(app_id) == blink::mojom::DisplayMode::kBrowser) { - launch_container = apps::mojom::LaunchContainer::kLaunchContainerTab; + launch_container = apps::LaunchContainer::kLaunchContainerTab; } apps::AppLaunchParams params = apps::AppLaunchParams( app_id, launch_container, WindowOpenDisposition::NEW_WINDOW,
diff --git a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm index bc0833b9..a999eb7e 100644 --- a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm +++ b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm
@@ -73,7 +73,7 @@ apps::AppServiceProxyFactory::GetForProfile(profile()) ->BrowserAppLauncher() ->LaunchAppWithParams(apps::AppLaunchParams( - app_->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, + app_->id(), apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest)); app_loaded_observer.Wait();
diff --git a/chrome/browser/ui/extensions/app_launch_params.cc b/chrome/browser/ui/extensions/app_launch_params.cc index 83cec31..6c41c464 100644 --- a/chrome/browser/ui/extensions/app_launch_params.cc +++ b/chrome/browser/ui/extensions/app_launch_params.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/extensions/launch_util.h" #include "chrome/browser/profiles/profile.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" @@ -21,7 +22,7 @@ apps::mojom::LaunchSource launch_source) { // Look up the app preference to find out the right launch container. Default // is to launch as a regular tab. - apps::mojom::LaunchContainer container = + apps::LaunchContainer container = extensions::GetLaunchContainer(ExtensionPrefs::Get(profile), extension); return apps::AppLaunchParams(extension->id(), container, disposition, launch_source); @@ -33,7 +34,7 @@ int event_flags, apps::mojom::LaunchSource launch_source, int64_t display_id) { - apps::mojom::LaunchContainer fallback_container = + apps::LaunchContainer fallback_container = extensions::GetLaunchContainer(ExtensionPrefs::Get(profile), extension); return apps::CreateAppIdLaunchParamsWithEventFlags( extension->id(), event_flags, launch_source, display_id,
diff --git a/chrome/browser/ui/extensions/application_launch.cc b/chrome/browser/ui/extensions/application_launch.cc index 6d03b6b..86087bb2 100644 --- a/chrome/browser/ui/extensions/application_launch.cc +++ b/chrome/browser/ui/extensions/application_launch.cc
@@ -164,12 +164,10 @@ return url; } -ui::WindowShowState DetermineWindowShowState( - Profile* profile, - apps::mojom::LaunchContainer container, - const Extension* extension) { - if (!extension || - container != apps::mojom::LaunchContainer::kLaunchContainerWindow) +ui::WindowShowState DetermineWindowShowState(Profile* profile, + apps::LaunchContainer container, + const Extension* extension) { + if (!extension || container != apps::LaunchContainer::kLaunchContainerWindow) return ui::SHOW_STATE_DEFAULT; if (chrome::IsRunningInForcedAppMode()) @@ -332,16 +330,16 @@ prefs->SetLastLaunchTime(extension->id(), base::Time::Now()); switch (params.container) { - case apps::mojom::LaunchContainer::kLaunchContainerNone: { + case apps::LaunchContainer::kLaunchContainerNone: { NOTREACHED(); break; } // Panels are deprecated. Launch a normal window instead. - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: + case apps::LaunchContainer::kLaunchContainerWindow: tab = OpenApplicationWindow(profile, params, url); break; - case apps::mojom::LaunchContainer::kLaunchContainerTab: { + case apps::LaunchContainer::kLaunchContainerTab: { tab = OpenApplicationTab(profile, params, url); break; } @@ -473,7 +471,7 @@ WebContents* OpenAppShortcutWindow(Profile* profile, const GURL& url) { apps::AppLaunchParams launch_params( std::string(), // this is a URL app. No app id. - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromCommandLine); launch_params.override_url = url; @@ -497,18 +495,18 @@ const std::string& app_id, const base::CommandLine& command_line, const base::FilePath& current_directory, - base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> callback) { - apps::mojom::LaunchContainer container; + base::OnceCallback<void(Browser* browser, apps::LaunchContainer container)> + callback) { + apps::LaunchContainer container; if (apps::OpenExtensionApplicationWindow(profile, app_id, command_line, current_directory)) { - container = apps::mojom::LaunchContainer::kLaunchContainerWindow; + container = apps::LaunchContainer::kLaunchContainerWindow; } else if (apps::OpenExtensionApplicationTab(profile, app_id)) { - container = apps::mojom::LaunchContainer::kLaunchContainerTab; + container = apps::LaunchContainer::kLaunchContainerTab; } else { // Open an empty browser window as the app_id is invalid. apps::CreateBrowserWithNewTabPage(profile); - container = apps::mojom::LaunchContainer::kLaunchContainerNone; + container = apps::LaunchContainer::kLaunchContainerNone; } std::move(callback).Run(BrowserList::GetInstance()->GetLastActive(), container);
diff --git a/chrome/browser/ui/extensions/application_launch.h b/chrome/browser/ui/extensions/application_launch.h index 797c0bff..fc1cc036 100644 --- a/chrome/browser/ui/extensions/application_launch.h +++ b/chrome/browser/ui/extensions/application_launch.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_EXTENSIONS_APPLICATION_LAUNCH_H_ #include "chrome/browser/apps/app_service/app_launch_params.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "url/gurl.h" class Browser; @@ -76,8 +77,8 @@ const std::string& app_id, const base::CommandLine& command_line, const base::FilePath& current_directory, - base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> callback); + base::OnceCallback<void(Browser* browser, apps::LaunchContainer container)> + callback); // Shows the browser for |profile| if existent, otherwise attempts to open it. // Returns true if browser window already exists or if it was successfully
diff --git a/chrome/browser/ui/extensions/application_launch_browsertest.cc b/chrome/browser/ui/extensions/application_launch_browsertest.cc index 68d2e012..062c69a 100644 --- a/chrome/browser/ui/extensions/application_launch_browsertest.cc +++ b/chrome/browser/ui/extensions/application_launch_browsertest.cc
@@ -6,6 +6,7 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_test.h" #include "ui/base/base_window.h" @@ -34,7 +35,7 @@ // Create browser2 on display 2. apps::AppLaunchParams params( - "app_id", apps::mojom::LaunchContainer::kLaunchContainerWindow, + "app_id", apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromAppListGrid, display2); Browser* browser2 =
diff --git a/chrome/browser/ui/permission_bubble/permission_bubble_browser_test_util.cc b/chrome/browser/ui/permission_bubble/permission_bubble_browser_test_util.cc index 72b67571..7c8be56 100644 --- a/chrome/browser/ui/permission_bubble/permission_bubble_browser_test_util.cc +++ b/chrome/browser/ui/permission_bubble/permission_bubble_browser_test_util.cc
@@ -17,6 +17,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/permissions/request_type.h" #include "components/permissions/test/mock_permission_request.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" @@ -78,8 +79,7 @@ CHECK(extension); apps::AppLaunchParams params( - extension->id(), - apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated, + extension->id(), apps::LaunchContainer::kLaunchContainerPanelDeprecated, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); content::WebContents* app_contents =
diff --git a/chrome/browser/ui/settings_window_manager_browsertest_chromeos.cc b/chrome/browser/ui/settings_window_manager_browsertest_chromeos.cc index fd4bc53..52f8353 100644 --- a/chrome/browser/ui/settings_window_manager_browsertest_chromeos.cc +++ b/chrome/browser/ui/settings_window_manager_browsertest_chromeos.cc
@@ -25,6 +25,7 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/mixin_based_in_process_browser_test.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" @@ -107,8 +108,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - settings_app_id, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + settings_app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromCommandLine)); web_app::FlushSystemWebAppLaunchesForTesting(browser()->profile());
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index d3e546b..df40a183 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -80,7 +80,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/search_engines/util.h" -#include "components/services/app_service/public/mojom/types.mojom.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/browser_task_traits.h" @@ -522,7 +522,7 @@ web_app::startup::FinalizeWebAppLaunch( LaunchMode::kAsWebAppInWindowByUrl, command_line, is_first_run, chrome::FindBrowserWithWebContents(web_contents), - apps::mojom::LaunchContainer::kLaunchContainerWindow); + apps::LaunchContainer::kLaunchContainerWindow); return true; } }
diff --git a/chrome/browser/ui/startup/web_app_startup_utils.cc b/chrome/browser/ui/startup/web_app_startup_utils.cc index 9ceb3ce..8a7167b 100644 --- a/chrome/browser/ui/startup/web_app_startup_utils.cc +++ b/chrome/browser/ui/startup/web_app_startup_utils.cc
@@ -300,7 +300,7 @@ } } - void OnAppLaunched(Browser* browser, apps::mojom::LaunchContainer container) { + void OnAppLaunched(Browser* browser, apps::LaunchContainer container) { // The finalization step should only occur for the first app launch. if (app_window_has_been_launched_) return; @@ -353,24 +353,24 @@ const base::CommandLine& command_line, chrome::startup::IsFirstRun is_first_run, Browser* browser, - apps::mojom::LaunchContainer container) { + apps::LaunchContainer container) { if (!browser) return; LaunchMode mode; switch (container) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerWindow: DCHECK(browser->is_type_app()); mode = app_launch_mode.value_or(LaunchMode::kAsWebAppInWindowOther); break; - case apps::mojom::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerTab: DCHECK(!browser->is_type_app()); mode = LaunchMode::kAsWebAppInTab; break; - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: NOTREACHED(); [[fallthrough]]; - case apps::mojom::LaunchContainer::kLaunchContainerNone: + case apps::LaunchContainer::kLaunchContainerNone: DCHECK(!browser->is_type_app()); mode = LaunchMode::kUnknownWebApp; break;
diff --git a/chrome/browser/ui/startup/web_app_startup_utils.h b/chrome/browser/ui/startup/web_app_startup_utils.h index c7edae81..471bae00 100644 --- a/chrome/browser/ui/startup/web_app_startup_utils.h +++ b/chrome/browser/ui/startup/web_app_startup_utils.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_UI_STARTUP_WEB_APP_STARTUP_UTILS_H_ #include "chrome/browser/ui/startup/startup_types.h" -#include "components/services/app_service/public/mojom/types.mojom.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" enum class LaunchMode; @@ -34,7 +34,7 @@ const base::CommandLine& command_line, chrome::startup::IsFirstRun is_first_run, Browser* browser, - apps::mojom::LaunchContainer container); + apps::LaunchContainer container); // `callback` will be run after the next `MaybeHandleWebAppLaunch()` invocation // finishes executing.
diff --git a/chrome/browser/ui/views/frame/browser_window_property_manager_browsertest_win.cc b/chrome/browser/ui/views/frame/browser_window_property_manager_browsertest_win.cc index 0de4ef6..8180d17 100644 --- a/chrome/browser/ui/views/frame/browser_window_property_manager_browsertest_win.cc +++ b/chrome/browser/ui/views/frame/browser_window_property_manager_browsertest_win.cc
@@ -205,7 +205,7 @@ apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher() ->LaunchAppWithParams(apps::AppLaunchParams( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerWindow, + extension->id(), apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_FOREGROUND_TAB, apps::mojom::LaunchSource::kFromTest));
diff --git a/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc index 3337945..bea998e0 100644 --- a/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc
@@ -19,9 +19,6 @@ #include "url/gurl.h" namespace payments { -// The transaction amount from defaultDetails in can_make_payment_metrics.js is -// 5$ which falls in regular transaction category. -constexpr uint32_t kRegularTransaction = 2; class PaymentRequestCompletionStatusMetricsTest : public PaymentRequestBrowserTestBase { @@ -64,20 +61,8 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "queryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Complete the Payment Request. PayWithCreditCardAndWait(u"123"); - histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.Completed", - 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.Shown", 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.Shown.BasicCard", 1); - - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Completed", kRegularTransaction, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = @@ -117,9 +102,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant reloads the page. ResetEventWaiter(DialogEvent::DIALOG_CLOSED); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), @@ -130,13 +112,6 @@ histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION, 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.OtherAborted", 1); - - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = @@ -176,9 +151,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant navigates away. ResetEventWaiter(DialogEvent::DIALOG_CLOSED); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), @@ -192,11 +164,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -235,9 +202,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant aborts the Payment Request. ResetEventWaiterForSequence( {DialogEvent::ABORT_CALLED, DialogEvent::DIALOG_CLOSED}); @@ -252,11 +216,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -295,9 +254,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Navigate away. NavigateTo("/payment_request_email_test.html"); @@ -306,16 +262,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); - histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.UserAborted", - 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.UserAborted.Shown", 1); - - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -354,9 +300,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Click on the cancel button. ClickOnCancel(); @@ -365,11 +308,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_USER, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -408,9 +346,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Close the tab containing the Payment Request. ResetEventWaiterForSequence({DialogEvent::DIALOG_CLOSED}); chrome::CloseTab(browser()); @@ -421,11 +356,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_USER, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -464,9 +394,6 @@ ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "noQueryShow();")); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Reload the page containing the Payment Request. ResetEventWaiterForSequence({DialogEvent::DIALOG_CLOSED}); chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB); @@ -477,11 +404,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -527,13 +449,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); - // Make sure no PaymentRequest.TransactionAmount.[Triggered|Completed] is - // logged since transaction got aborted before .show() call. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Triggered", 0); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // There is one sample, because the request was initiated. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -598,19 +513,6 @@ // Navigate away to trigger the log. NavigateTo("a.com", "/payment_request_email_test.html"); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - - histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.Completed", - 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow", 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow.Other", 1); - - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Completed", kRegularTransaction, 1); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -663,9 +565,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant reloads the page. ResetEventWaiter(DialogEvent::DIALOG_CLOSED); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), @@ -676,13 +575,6 @@ histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION, 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.OtherAborted", 1); - - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = @@ -736,9 +628,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant navigates away. ResetEventWaiter(DialogEvent::DIALOG_CLOSED); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), @@ -752,11 +641,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -809,9 +693,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // The merchant aborts the Payment Request. ResetEventWaiterForSequence( {DialogEvent::ABORT_CALLED, DialogEvent::DIALOG_CLOSED}); @@ -826,11 +707,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -883,9 +759,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Navigate away. NavigateTo("/payment_request_email_test.html"); @@ -894,16 +767,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); - histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.UserAborted", - 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.UserAborted.Shown", 1); - - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -956,9 +819,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Click on the cancel button. ClickOnCancel(); @@ -967,11 +827,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_USER, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -1024,9 +879,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Close the tab containing the Payment Request. ResetEventWaiterForSequence({DialogEvent::DIALOG_CLOSED}); chrome::CloseTab(browser()); @@ -1037,11 +889,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_ABORTED_BY_USER, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); @@ -1094,9 +941,6 @@ a_method_name, b_method_name))); WaitForObservedEvent(); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kRegularTransaction, 1); - // Reload the page containing the Payment Request. ResetEventWaiterForSequence({DialogEvent::DIALOG_CLOSED}); chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB); @@ -1107,11 +951,6 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); - // Make sure PaymentRequest.TransactionAmount.Completed is not logged - // since the request got aborted. - histogram_tester.ExpectTotalCount( - "PaymentRequest.TransactionAmount.Completed", 0); - // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events");
diff --git a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc index 0db72c43..3d7248d 100644 --- a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc
@@ -409,13 +409,6 @@ WaitForObservedEvent(); ExpectBodyContains({"bobpay.com"}); - - histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.Completed", - 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow", 1); - histogram_tester.ExpectTotalCount( - "PaymentRequest.TimeToCheckout.Completed.SkippedShow.Other", 1); } }
diff --git a/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc index 45e2fcd..7b02688 100644 --- a/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc
@@ -240,16 +240,6 @@ WaitForObservedEvent(); ExpectBodyContains({R"({"currency":"USD","value":"1.00"})"}); - - // The initial total in digital_goods.js is 99.99 while the final total is - // 1.00. Verify that transaction amount metrics are recorded only once and - // with final total rather than the initial one. The final total falls into - // micro transaction category. - constexpr uint32_t kMicroTransaction = 1; - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kMicroTransaction, 1); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Completed", kMicroTransaction, 1); } IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, Reject) {
diff --git a/chrome/browser/ui/views/webid/account_selection_bubble_view.cc b/chrome/browser/ui/views/webid/account_selection_bubble_view.cc index 674324c..839c896 100644 --- a/chrome/browser/ui/views/webid/account_selection_bubble_view.cc +++ b/chrome/browser/ui/views/webid/account_selection_bubble_view.cc
@@ -291,12 +291,15 @@ SetShowTitle(false); SetShowCloseButton(false); set_close_on_deactivate(false); - SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kVertical, gfx::Insets(), - kTopBottomPadding)); + std::u16string title = l10n_util::GetStringFUTF16( IDS_ACCOUNT_SELECTION_SHEET_TITLE_EXPLICIT, base::UTF8ToUTF16(rp_for_display), idp_for_display_); + SetAccessibleTitle(title); + + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical, gfx::Insets(), + kTopBottomPadding)); bool has_icon = idp_metadata.brand_icon_url.is_valid(); header_view_ = AddChildView(CreateHeaderView(title, has_icon)); AddChildView(std::make_unique<views::Separator>()); @@ -372,11 +375,21 @@ vector_icons::kArrowBackIcon)); views::InstallCircleHighlightPathGenerator(back_button_.get()); back_button_->SetTooltipText(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK)); - back_button_->SetProperty(views::kMarginsKey, - gfx::Insets().set_right(kLeftRightPadding)); - back_button_->SetVisible(false); + int back_button_right_margin = kLeftRightPadding; + if (header_icon_view_) { + // Set the right margin of the back button so that the back button and + // the IDP brand icon have the same width. This ensures that the header + // title does not shift when the user navigates to the consent screen. + back_button_right_margin = + std::max(0, back_button_right_margin + + header_icon_view_->GetPreferredSize().width() - + back_button_->GetPreferredSize().width()); + } + back_button_->SetProperty(views::kMarginsKey, + gfx::Insets().set_right(back_button_right_margin)); + // Add the title. title_label_ = header->AddChildView(std::make_unique<views::Label>( title, views::style::CONTEXT_DIALOG_BODY_TEXT,
diff --git a/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc b/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc index e02b1e5..28ac80a1 100644 --- a/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc +++ b/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc
@@ -66,6 +66,7 @@ #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h" #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include "chrome/common/webui_url_constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/test/test_utils.h" #include "ui/wm/public/activation_change_observer.h" // nogncheck #include "ui/wm/public/activation_client.h" // nogncheck @@ -558,7 +559,7 @@ AppId app_id = GetAppId(profile); auto launch_params = apps::AppLaunchParams( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::CURRENT_TAB, apps::mojom::LaunchSource::kFromAppListGrid); @@ -674,7 +675,7 @@ { auto launch_params = apps::AppLaunchParams( - app_id2, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id2, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::CURRENT_TAB, apps::mojom::LaunchSource::kFromAppListGrid); content::WebContents* web_contents = @@ -686,7 +687,7 @@ { auto launch_params = apps::AppLaunchParams( - app_id1, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id1, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::CURRENT_TAB, apps::mojom::LaunchSource::kFromAppListGrid); content::WebContents* web_contents =
diff --git a/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc b/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc index 627acbe..60fb018 100644 --- a/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc +++ b/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc
@@ -47,6 +47,7 @@ #include "chrome/browser/web_applications/web_app_tab_helper.h" #include "chrome/test/base/ui_test_utils.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "components/webapps/browser/install_result_code.h" #include "components/webapps/browser/installable/installable_metrics.h" @@ -196,7 +197,7 @@ apps::AppServiceProxyFactory::GetForProfile(profile) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, disposition, apps::mojom::LaunchSource::kFromTest)); EXPECT_TRUE(web_contents); Browser* browser = chrome::FindBrowserWithWebContents(web_contents); @@ -222,7 +223,7 @@ apps::AppServiceProxyFactory::GetForProfile(profile) ->BrowserAppLauncher() ->LaunchAppWithParamsForTesting(apps::AppLaunchParams( - app_id, apps::mojom::LaunchContainer::kLaunchContainerTab, + app_id, apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, apps::mojom::LaunchSource::kFromTest)); DCHECK(web_contents);
diff --git a/chrome/browser/ui/web_applications/web_app_browsertest.cc b/chrome/browser/ui/web_applications/web_app_browsertest.cc index 3e7a2824..cd515dcd 100644 --- a/chrome/browser/ui/web_applications/web_app_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_browsertest.cc
@@ -71,6 +71,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sessions/core/tab_restore_service.h" @@ -1471,9 +1472,8 @@ EXPECT_EQ(provider->registrar().GetAppEffectiveDisplayMode(app_id), DisplayMode::kMinimalUi); EXPECT_FALSE(provider->registrar().GetAppLastLaunchTime(app_id).is_null()); - tester.ExpectUniqueSample( - "Extensions.BookmarkAppLaunchContainer", - apps::mojom::LaunchContainer::kLaunchContainerWindow, 1); + tester.ExpectUniqueSample("Extensions.BookmarkAppLaunchContainer", + apps::LaunchContainer::kLaunchContainerWindow, 1); tester.ExpectUniqueSample("Extensions.BookmarkAppLaunchSource", extensions::AppLaunchSource::kSourceReparenting, 1); } @@ -1869,7 +1869,7 @@ const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); BrowserHandler handler(nullptr, std::string());
diff --git a/chrome/browser/ui/web_applications/web_app_controller_browsertest.cc b/chrome/browser/ui/web_applications/web_app_controller_browsertest.cc index e6bc312..abb2cb3 100644 --- a/chrome/browser/ui/web_applications/web_app_controller_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_controller_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" @@ -165,7 +166,7 @@ content::NotificationService::AllSources()); apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); content::WebContents* contents = apps::AppServiceProxyFactory::GetForProfile(profile())
diff --git a/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc b/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc index 9c9e1a5c..9a9cb61f6 100644 --- a/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_engagement_browsertest.cc
@@ -121,10 +121,10 @@ base::HistogramBase::Count windowLaunches, base::HistogramBase::Count tabLaunches) { tester.ExpectBucketCount("Extensions.BookmarkAppLaunchContainer", - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, windowLaunches); tester.ExpectBucketCount("Extensions.BookmarkAppLaunchContainer", - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::LaunchContainer::kLaunchContainerTab, tabLaunches); tester.ExpectTotalCount("Extensions.BookmarkAppLaunchContainer", windowLaunches + tabLaunches); @@ -142,10 +142,10 @@ windowLaunches + tabLaunches); tester.ExpectBucketCount("Extensions.BookmarkAppLaunchContainer", - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, windowLaunches); tester.ExpectBucketCount("Extensions.BookmarkAppLaunchContainer", - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::LaunchContainer::kLaunchContainerTab, tabLaunches); tester.ExpectTotalCount("Extensions.BookmarkAppLaunchContainer", windowLaunches + tabLaunches);
diff --git a/chrome/browser/ui/web_applications/web_app_file_handling_browsertest.cc b/chrome/browser/ui/web_applications/web_app_file_handling_browsertest.cc index 580720f..3a2f3fc0 100644 --- a/chrome/browser/ui/web_applications/web_app_file_handling_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_file_handling_browsertest.cc
@@ -48,6 +48,7 @@ #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_launcher.h" @@ -181,12 +182,11 @@ public: WebAppFileHandlingBrowserTest() : redirect_handle_(*https_server()) {} - void LaunchWithFiles( - const std::string& app_id, - const GURL& expected_launch_url, - const std::vector<base::FilePath>& files, - const apps::mojom::LaunchContainer launch_container = - apps::mojom::LaunchContainer::kLaunchContainerWindow) { + void LaunchWithFiles(const std::string& app_id, + const GURL& expected_launch_url, + const std::vector<base::FilePath>& files, + const apps::LaunchContainer launch_container = + apps::LaunchContainer::kLaunchContainerWindow) { web_contents_ = LaunchApplication( profile(), app_id, expected_launch_url, launch_container, apps::mojom::LaunchSource::kFromFileManager, files); @@ -253,8 +253,8 @@ Profile* profile, const std::string& app_id, const GURL& expected_launch_url, - const apps::mojom::LaunchContainer launch_container = - apps::mojom::LaunchContainer::kLaunchContainerWindow, + const apps::LaunchContainer launch_container = + apps::LaunchContainer::kLaunchContainerWindow, const apps::mojom::LaunchSource launch_source = apps::mojom::LaunchSource::kFromTest, const std::vector<base::FilePath>& files = @@ -314,7 +314,7 @@ InstallFileHandlingPWA(); base::FilePath test_file_path = NewTestFilePath("txt"); LaunchWithFiles(app_id(), GetTextFileHandlerActionURL(), {test_file_path}, - apps::mojom::LaunchContainer::kLaunchContainerTab); + apps::LaunchContainer::kLaunchContainerTab); VerifyPwaDidReceiveFileLaunchParams(true, test_file_path); } @@ -334,16 +334,16 @@ // Test as above in a tab. LaunchWithFiles(app_id(), GetSecureAppURL(), {}, - apps::mojom::LaunchContainer::kLaunchContainerTab); + apps::LaunchContainer::kLaunchContainerTab); LaunchWithFiles(app_id(), GetTextFileHandlerActionURL(), {NewTestFilePath("txt")}, - apps::mojom::LaunchContainer::kLaunchContainerTab); + apps::LaunchContainer::kLaunchContainerTab); LaunchWithFiles(app_id(), GetHTMLFileHandlerActionURL(), {NewTestFilePath("html")}, - apps::mojom::LaunchContainer::kLaunchContainerTab); + apps::LaunchContainer::kLaunchContainerTab); LaunchWithFiles(app_id(), GetCSVFileHandlerActionURL(), {NewTestFilePath("csv")}, - apps::mojom::LaunchContainer::kLaunchContainerTab); + apps::LaunchContainer::kLaunchContainerTab); } // Regression test for crbug.com/1126091
diff --git a/chrome/browser/ui/web_applications/web_app_guest_session_browsertest_chromeos.cc b/chrome/browser/ui/web_applications/web_app_guest_session_browsertest_chromeos.cc index 1b72ee9..aec877f 100644 --- a/chrome/browser/ui/web_applications/web_app_guest_session_browsertest_chromeos.cc +++ b/chrome/browser/ui/web_applications/web_app_guest_session_browsertest_chromeos.cc
@@ -16,6 +16,7 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/account_id/account_id.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/user_manager/user_names.h" #include "content/public/test/browser_test.h" @@ -45,11 +46,10 @@ ->InstallSystemAppsForTesting(); Profile* profile = browser()->profile(); - apps::AppLaunchParams params( - web_app::kOsSettingsAppId, - apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_FOREGROUND_TAB, - apps::mojom::LaunchSource::kFromTest); + apps::AppLaunchParams params(web_app::kOsSettingsAppId, + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + apps::mojom::LaunchSource::kFromTest); content::WebContents* contents = apps::AppServiceProxyFactory::GetForProfile(profile)
diff --git a/chrome/browser/ui/web_applications/web_app_launch_manager.cc b/chrome/browser/ui/web_applications/web_app_launch_manager.cc index 9db250d..3d9ddcf 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_manager.cc +++ b/chrome/browser/ui/web_applications/web_app_launch_manager.cc
@@ -67,8 +67,8 @@ const absl::optional<GURL>& protocol_handler_launch_url, const absl::optional<GURL>& file_launch_url, const std::vector<base::FilePath>& launch_files, - base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> callback) { + base::OnceCallback<void(Browser* browser, apps::LaunchContainer container)> + callback) { if (!provider_) return; @@ -95,7 +95,7 @@ } apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, launch_source); params.command_line = command_line; params.current_directory = current_directory; @@ -126,14 +126,14 @@ void WebAppLaunchManager::LaunchWebApplication( apps::AppLaunchParams&& params, - base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> callback) { - apps::mojom::LaunchContainer container; + base::OnceCallback<void(Browser* browser, apps::LaunchContainer container)> + callback) { + apps::LaunchContainer container; Browser* browser = nullptr; if (provider_->registrar().IsInstalled(params.app_id)) { if (provider_->registrar().GetAppEffectiveDisplayMode(params.app_id) == blink::mojom::DisplayMode::kBrowser) { - params.container = apps::mojom::LaunchContainer::kLaunchContainerTab; + params.container = apps::LaunchContainer::kLaunchContainerTab; params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; } @@ -144,7 +144,7 @@ browser = chrome::FindBrowserWithWebContents(web_contents); } else { // Open an empty browser window as the app_id is invalid. - container = apps::mojom::LaunchContainer::kLaunchContainerNone; + container = apps::LaunchContainer::kLaunchContainerNone; browser = apps::CreateBrowserWithNewTabPage(profile_); } std::move(callback).Run(browser, container);
diff --git a/chrome/browser/ui/web_applications/web_app_launch_manager.h b/chrome/browser/ui/web_applications/web_app_launch_manager.h index 8b7c319..425c5fb 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_manager.h +++ b/chrome/browser/ui/web_applications/web_app_launch_manager.h
@@ -8,7 +8,7 @@ #include "base/callback.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" -#include "components/services/app_service/public/mojom/types.mojom.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" class Browser; @@ -56,8 +56,7 @@ const absl::optional<GURL>& file_launch_url, const std::vector<base::FilePath>& launch_files, base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> - callback); + apps::LaunchContainer container)> callback); static void SetOpenApplicationCallbackForTesting( OpenApplicationCallback callback); @@ -66,8 +65,7 @@ virtual void LaunchWebApplication( apps::AppLaunchParams&& params, base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> - callback); + apps::LaunchContainer container)> callback); const raw_ptr<Profile> profile_; const raw_ptr<WebAppProvider> provider_;
diff --git a/chrome/browser/ui/web_applications/web_app_launch_manager_unittest.cc b/chrome/browser/ui/web_applications/web_app_launch_manager_unittest.cc index c5982d18..3807db4 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_manager_unittest.cc +++ b/chrome/browser/ui/web_applications/web_app_launch_manager_unittest.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/web_applications/web_app_utils.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -31,13 +32,13 @@ MockWebAppLaunchManager& operator=(const MockWebAppLaunchManager&) = delete; ~MockWebAppLaunchManager() override = default; - MOCK_METHOD(void, - LaunchWebApplication, - (apps::AppLaunchParams && params, - base::OnceCallback<void(Browser* browser, - apps::mojom::LaunchContainer container)> - callback), - (override)); + MOCK_METHOD( + void, + LaunchWebApplication, + (apps::AppLaunchParams && params, + base::OnceCallback<void(Browser* browser, + apps::LaunchContainer container)> callback), + (override)); }; #if BUILDFLAG(IS_WIN) @@ -72,10 +73,10 @@ const std::vector<base::FilePath>& launch_files, const absl::optional<GURL>& url_handler_launch_url, const absl::optional<GURL>& protocol_handler_launch_url) { - apps::AppLaunchParams params( - kTestAppId, apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromCommandLine); + apps::AppLaunchParams params(kTestAppId, + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromCommandLine); params.current_directory = base::FilePath(kCurrentDirectory); params.command_line = command_line; @@ -135,7 +136,7 @@ .WillOnce(testing::Invoke( [&](apps::AppLaunchParams&& params, base::OnceCallback<void(Browser * browser, - apps::mojom::LaunchContainer container)> + apps::LaunchContainer container)> callback) { ValidateLaunchParams(params, expected_results); run_loop.Quit(); @@ -167,7 +168,7 @@ .WillOnce(testing::Invoke( [&](apps::AppLaunchParams&& params, base::OnceCallback<void(Browser * browser, - apps::mojom::LaunchContainer container)> + apps::LaunchContainer container)> callback) { ValidateLaunchParams(params, expected_results); run_loop.Quit(); @@ -200,7 +201,7 @@ .WillOnce(testing::Invoke( [&](apps::AppLaunchParams&& params, base::OnceCallback<void(Browser * browser, - apps::mojom::LaunchContainer container)> + apps::LaunchContainer container)> callback) { ValidateLaunchParams(params, expected_results); run_loop.Quit(); @@ -229,7 +230,7 @@ .WillOnce(testing::Invoke( [&](apps::AppLaunchParams&& params, base::OnceCallback<void(Browser * browser, - apps::mojom::LaunchContainer container)> + apps::LaunchContainer container)> callback) { ValidateLaunchParams(params, expected_results); run_loop.Quit();
diff --git a/chrome/browser/ui/web_applications/web_app_launch_process.cc b/chrome/browser/ui/web_applications/web_app_launch_process.cc index 25c2d68..ce43c22 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_process.cc +++ b/chrome/browser/ui/web_applications/web_app_launch_process.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "chrome/browser/web_applications/web_app_tab_helper.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/site_engagement/content/site_engagement_service.h" @@ -248,7 +249,7 @@ } Browser* WebAppLaunchProcess::MaybeFindBrowserForLaunch() const { - if (params_.container == apps::mojom::LaunchContainer::kLaunchContainerTab) { + if (params_.container == apps::LaunchContainer::kLaunchContainerTab) { return chrome::FindTabbedBrowser( &profile_, /*match_original_profiles=*/false, display::Screen::GetScreen()->GetDisplayForNewWindows().id()); @@ -270,7 +271,7 @@ } Browser* WebAppLaunchProcess::CreateBrowserForLaunch() { - if (params_.container == apps::mojom::LaunchContainer::kLaunchContainerTab) { + if (params_.container == apps::LaunchContainer::kLaunchContainerTab) { return Browser::Create(Browser::CreateParams(Browser::TYPE_NORMAL, &profile_, /*user_gesture=*/true));
diff --git a/chrome/browser/ui/web_applications/web_app_launch_utils.cc b/chrome/browser/ui/web_applications/web_app_launch_utils.cc index 8c210f6..e990ac9 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_utils.cc +++ b/chrome/browser/ui/web_applications/web_app_launch_utils.cc
@@ -44,6 +44,7 @@ #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "chrome/browser/web_applications/web_app_tab_helper.h" #include "chrome/browser/web_applications/web_app_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/site_engagement/content/site_engagement_service.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" @@ -176,7 +177,7 @@ } auto launch_url = contents->GetLastCommittedURL(); - RecordMetrics(app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + RecordMetrics(app_id, apps::LaunchContainer::kLaunchContainerWindow, extensions::AppLaunchSource::kSourceReparenting, launch_url, contents); @@ -365,18 +366,17 @@ } void RecordMetrics(const AppId& app_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, extensions::AppLaunchSource launch_source, const GURL& launch_url, content::WebContents* web_contents) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); // TODO(crbug.com/1014328): Populate WebApp metrics instead of Extensions. - if (container == apps::mojom::LaunchContainer::kLaunchContainerTab) { + if (container == apps::LaunchContainer::kLaunchContainerTab) { UMA_HISTOGRAM_ENUMERATION("Extensions.AppTabLaunchType", extensions::LAUNCH_TYPE_REGULAR, 100); - } else if (container == - apps::mojom::LaunchContainer::kLaunchContainerWindow) { + } else if (container == apps::LaunchContainer::kLaunchContainerWindow) { RecordAppWindowLaunch(profile, app_id); } UMA_HISTOGRAM_ENUMERATION("Extensions.BookmarkAppLaunchSource",
diff --git a/chrome/browser/ui/web_applications/web_app_launch_utils.h b/chrome/browser/ui/web_applications/web_app_launch_utils.h index 7f3cc48..27a5e713 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_utils.h +++ b/chrome/browser/ui/web_applications/web_app_launch_utils.h
@@ -10,7 +10,7 @@ #include <string> #include "chrome/browser/web_applications/web_app_id.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/common/constants.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/geometry/rect.h" @@ -81,7 +81,7 @@ void RecordAppWindowLaunch(Profile* profile, const std::string& app_id); void RecordMetrics(const AppId& app_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, extensions::AppLaunchSource launch_source, const GURL& launch_url, content::WebContents* web_contents);
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc index d8a801b..7dd8e92 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc
@@ -121,11 +121,11 @@ switch (extensions::GetLaunchContainer( extensions::ExtensionPrefs::Get(profile), extension)) { - case apps::mojom::LaunchContainer::kLaunchContainerWindow: - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: + case apps::LaunchContainer::kLaunchContainerWindow: + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: return UserDisplayMode::kStandalone; - case apps::mojom::LaunchContainer::kLaunchContainerTab: - case apps::mojom::LaunchContainer::kLaunchContainerNone: + case apps::LaunchContainer::kLaunchContainerTab: + case apps::LaunchContainer::kLaunchContainerNone: return UserDisplayMode::kBrowser; } }
diff --git a/chrome/browser/ui/web_applications/web_app_uninstall_browsertest.cc b/chrome/browser/ui/web_applications/web_app_uninstall_browsertest.cc index fc2288b..43d85ff21 100644 --- a/chrome/browser/ui/web_applications/web_app_uninstall_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_uninstall_browsertest.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/web_applications/web_app_install_finalizer.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sessions/core/tab_restore_service.h" #include "components/webapps/browser/installable/installable_metrics.h" @@ -137,7 +138,7 @@ const AppId app_id = InstallPWA(app_url); apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, + app_id, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, apps::mojom::LaunchSource::kFromTest); UninstallWebApp(app_id);
diff --git a/chrome/browser/ui/web_applications/web_share_target_browsertest.cc b/chrome/browser/ui/web_applications/web_share_target_browsertest.cc index dee5209b..eb0b550 100644 --- a/chrome/browser/ui/web_applications/web_share_target_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_share_target_browsertest.cc
@@ -26,6 +26,7 @@ #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/services/app_service/public/cpp/share_target.h" #include "content/public/browser/web_contents.h" @@ -95,9 +96,8 @@ apps::AppLaunchParams params = apps::CreateAppLaunchParamsForIntent( app_id, /*event_flags=*/0, apps::mojom::LaunchSource::kFromSharesheet, - display::kDefaultDisplayId, - apps::mojom::LaunchContainer::kLaunchContainerWindow, std::move(intent), - profile); + display::kDefaultDisplayId, apps::LaunchContainer::kLaunchContainerWindow, + std::move(intent), profile); content::WebContents* const web_contents = apps::AppServiceProxyFactory::GetForProfile(profile)
diff --git a/chrome/browser/ui/webui/apc_internals/apc_internals_handler.cc b/chrome/browser/ui/webui/apc_internals/apc_internals_handler.cc index a1b698d8..9f2e604 100644 --- a/chrome/browser/ui/webui/apc_internals/apc_internals_handler.cc +++ b/chrome/browser/ui/webui/apc_internals/apc_internals_handler.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/webui/apc_internals/apc_internals_logins_request.h" #include "components/autofill_assistant/browser/switches.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/password_manager/core/browser/password_scripts_fetcher.h" @@ -92,6 +93,7 @@ FireWebUIListener("on-script-fetching-information-received", base::Value(GetPasswordScriptFetcherInformation())); UpdateAutofillAssistantInformation(); + OnRefreshScriptCacheRequested(base::Value::List()); } void APCInternalsHandler::UpdateAutofillAssistantInformation() { @@ -109,7 +111,9 @@ const base::Value::List& args) { if (PasswordScriptsFetcher* scripts_fetcher = GetPasswordScriptsFetcher(); scripts_fetcher) { - scripts_fetcher->PrewarmCache(); + scripts_fetcher->RefreshScriptsIfNecessary( + base::BindOnce(&APCInternalsHandler::OnScriptCacheRequested, + weak_ptr_factory_.GetWeakPtr(), base::Value::List())); } }
diff --git a/chrome/browser/ui/webui/apc_internals/apc_internals_handler.h b/chrome/browser/ui/webui/apc_internals/apc_internals_handler.h index b6ba5b3..ca9b3af 100644 --- a/chrome/browser/ui/webui/apc_internals/apc_internals_handler.h +++ b/chrome/browser/ui/webui/apc_internals/apc_internals_handler.h
@@ -8,11 +8,15 @@ #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" #include "base/values.h" -#include "chrome/browser/ui/webui/apc_internals/apc_internals_logins_request.h" -#include "components/password_manager/core/browser/password_scripts_fetcher.h" -#include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/browser/web_ui_message_handler.h" +class APCInternalsLoginsRequest; + +namespace password_manager { +class PasswordScriptsFetcher; +class PasswordStoreInterface; +} // namespace password_manager + // Provides the WebUI message handling for chrome://apc-internals, the // diagnostics page for Automated Password Change (APC) flows. class APCInternalsHandler : public content::WebUIMessageHandler { @@ -82,6 +86,9 @@ // Represents all Gaia-account-scoped password stores. raw_ptr<password_manager::PasswordStoreInterface> account_password_store_; + + // A factory for weak pointers to the handler. + base::WeakPtrFactory<APCInternalsHandler> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_UI_WEBUI_APC_INTERNALS_APC_INTERNALS_HANDLER_H_
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/BUILD.gn b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/BUILD.gn new file mode 100644 index 0000000..d6e6d4b --- /dev/null +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/BUILD.gn
@@ -0,0 +1,16 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/chromeos/ui_mode.gni") +import("//mojo/public/tools/bindings/mojom.gni") +import("//tools/typescript/ts_library.gni") + +assert(is_chromeos_ash, "Manage MirrorSync dialog is ash-chrome only") + +mojom("mojo_bindings") { + sources = [ "manage_mirrorsync.mojom" ] + + public_deps = [ "//mojo/public/mojom/base" ] + webui_module_path = "/" +}
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/OWNERS b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/OWNERS index 73220a8..e4510da 100644 --- a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/OWNERS +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/OWNERS
@@ -1 +1,4 @@ file://ui/file_manager/OWNERS + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS \ No newline at end of file
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom new file mode 100644 index 0000000..7d68e87 --- /dev/null +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom
@@ -0,0 +1,21 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module chromeos.manage_mirrorsync.mojom; + +import "mojo/public/mojom/base/file_path.mojom"; + +// Lives in the browser process. A renderer uses this to create a page handler +// that enables communication between a renderer and the browser process. +interface PageHandlerFactory { + // Create a page handler to enable communication with the browser process. + CreatePageHandler(pending_receiver<PageHandler> handler); +}; + +// Lives in the browser process. A renderer uses this to invoke methods that +// are implemented in the browser process. +interface PageHandler { + // Returns a list of paths that are enabled for syncing via MirrorSync. + GetSyncingPaths() => (array<mojo_base.mojom.FilePath> paths); +};
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h index fea6ee6c..c4f22bfb 100644 --- a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_dialog.h
@@ -23,11 +23,6 @@ // SystemWebDialogDelegate: void GetDialogSize(gfx::Size* size) const override; - bool ShouldShowCloseButton() const override; - bool ShouldShowDialogTitle() const override; - bool ShouldCloseDialogOnEscape() const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - bool OnDialogCloseRequested() override; void OnDialogShown(content::WebUI* webui) override; void OnCloseContents(content::WebContents* source, bool* out_close_dialog) override;
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.cc b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.cc new file mode 100644 index 0000000..4391c7c --- /dev/null +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.cc
@@ -0,0 +1,28 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h" + +#include <vector> + +#include "base/files/file.h" + +namespace chromeos { + +ManageMirrorSyncPageHandler::ManageMirrorSyncPageHandler( + mojo::PendingReceiver<manage_mirrorsync::mojom::PageHandler> + pending_page_handler) + : receiver_{this, std::move(pending_page_handler)} {} + +ManageMirrorSyncPageHandler::~ManageMirrorSyncPageHandler() = default; + +void ManageMirrorSyncPageHandler::GetSyncingPaths( + GetSyncingPathsCallback callback) { + // TODO(b/237066325): Replace this with a call to the DriveIntegrationService + // to actually get the syncing paths. + std::vector<base::FilePath> placeholder_paths{base::FilePath("/foo/bar")}; + std::move(callback).Run(std::move(placeholder_paths)); +} + +} // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h new file mode 100644 index 0000000..034cdcdad --- /dev/null +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h
@@ -0,0 +1,44 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_MANAGE_MIRRORSYNC_MANAGE_MIRRORSYNC_PAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_MANAGE_MIRRORSYNC_MANAGE_MIRRORSYNC_PAGE_HANDLER_H_ + +#include "base/callback.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" + +namespace chromeos { + +// Handles communication from the chrome://manage-mirrorsync renderer process to +// the browser process exposing various methods for the JS to invoke. +class ManageMirrorSyncPageHandler + : public chromeos::manage_mirrorsync::mojom::PageHandler { + public: + explicit ManageMirrorSyncPageHandler( + mojo::PendingReceiver<chromeos::manage_mirrorsync::mojom::PageHandler> + pending_page_handler); + + ManageMirrorSyncPageHandler(const ManageMirrorSyncPageHandler&) = delete; + ManageMirrorSyncPageHandler& operator=(const ManageMirrorSyncPageHandler&) = + delete; + + ~ManageMirrorSyncPageHandler() override; + + // chromeos::manage_mirrorsync::mojom::PageHandler: + void GetSyncingPaths(GetSyncingPathsCallback callback) override; + + private: + mojo::Receiver<chromeos::manage_mirrorsync::mojom::PageHandler> receiver_; + + base::WeakPtrFactory<ManageMirrorSyncPageHandler> weak_ptr_factory_{this}; +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_MANAGE_MIRRORSYNC_MANAGE_MIRRORSYNC_PAGE_HANDLER_H_
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.cc b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.cc index 9e8e7dc..0fc0551 100644 --- a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.cc +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.cc
@@ -7,7 +7,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/webui_url_constants.h" -#include "chrome/grit/browser_resources.h" +#include "chrome/grit/manage_mirrorsync_resources.h" +#include "chrome/grit/manage_mirrorsync_resources_map.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/webui/mojo_web_ui_controller.h" @@ -18,13 +19,33 @@ content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIManageMirrorSyncHost); auto* profile = Profile::FromWebUI(web_ui); - source->SetDefaultResource(IDR_MANAGE_MIRRORSYNC_INDEX_HTML); + webui::SetupWebUIDataSource(source, + base::make_span(kManageMirrorsyncResources, + kManageMirrorsyncResourcesSize), + IDR_MANAGE_MIRRORSYNC_INDEX_HTML); content::WebUIDataSource::Add(profile, source); } ManageMirrorSyncUI::~ManageMirrorSyncUI() = default; +void ManageMirrorSyncUI::BindInterface( + mojo::PendingReceiver< + chromeos::manage_mirrorsync::mojom::PageHandlerFactory> + pending_receiver) { + if (factory_receiver_.is_bound()) { + factory_receiver_.reset(); + } + factory_receiver_.Bind(std::move(pending_receiver)); +} + +void ManageMirrorSyncUI::CreatePageHandler( + mojo::PendingReceiver<chromeos::manage_mirrorsync::mojom::PageHandler> + receiver) { + page_handler_ = + std::make_unique<ManageMirrorSyncPageHandler>(std::move(receiver)); +} + WEB_UI_CONTROLLER_TYPE_IMPL(ManageMirrorSyncUI) } // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h index 36d0562..3b40276 100644 --- a/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h +++ b/chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_ui.h
@@ -5,12 +5,16 @@ #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_MANAGE_MIRRORSYNC_MANAGE_MIRRORSYNC_UI_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_MANAGE_MIRRORSYNC_MANAGE_MIRRORSYNC_UI_H_ +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync.mojom.h" +#include "chrome/browser/ui/webui/chromeos/manage_mirrorsync/manage_mirrorsync_page_handler.h" #include "ui/web_dialogs/web_dialog_ui.h" namespace chromeos { -// The WebUI for chrome://manage-mirrorsync -class ManageMirrorSyncUI : public ui::MojoWebDialogUI { +// The WebUI for chrome://manage-mirrorsync. +class ManageMirrorSyncUI + : public ui::MojoWebDialogUI, + public chromeos::manage_mirrorsync::mojom::PageHandlerFactory { public: explicit ManageMirrorSyncUI(content::WebUI* web_ui); @@ -19,7 +23,22 @@ ~ManageMirrorSyncUI() override; + // Instantiates implementor of the mojom::PageHandlerFactory + // mojo interface passing the pending receiver that will be internally bound. + void BindInterface(mojo::PendingReceiver< + chromeos::manage_mirrorsync::mojom::PageHandlerFactory> + pending_receiver); + + // chromeos::manage_mirrorsync::mojom::PageHandlerFactory: + void CreatePageHandler( + mojo::PendingReceiver<chromeos::manage_mirrorsync::mojom::PageHandler> + pending_page_handler) override; + private: + std::unique_ptr<ManageMirrorSyncPageHandler> page_handler_; + mojo::Receiver<chromeos::manage_mirrorsync::mojom::PageHandlerFactory> + factory_receiver_{this}; + WEB_UI_CONTROLLER_TYPE_DECL(); };
diff --git a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc index 9fdd558..802300dc 100644 --- a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -81,6 +81,7 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/webapps/browser/install_result_code.h" #include "components/webapps/browser/installable/installable_metrics.h" #include "components/webapps/browser/uninstall_result_code.h" @@ -830,7 +831,7 @@ extensions::Manifest::Type type; GURL full_launch_url; - apps::mojom::LaunchContainer launch_container; + apps::LaunchContainer launch_container; web_app::WebAppRegistrar& registrar = web_app_provider_->registrar(); if (registrar.IsInstalled(extension_id) && @@ -874,8 +875,8 @@ apps::AppLaunchParams params( extension_id, disposition == WindowOpenDisposition::NEW_WINDOW - ? apps::mojom::LaunchContainer::kLaunchContainerWindow - : apps::mojom::LaunchContainer::kLaunchContainerTab, + ? apps::LaunchContainer::kLaunchContainerWindow + : apps::LaunchContainer::kLaunchContainerTab, disposition, apps::mojom::LaunchSource::kFromNewTabPage); params.override_url = override_url; apps::AppServiceProxyFactory::GetForProfile(profile)
diff --git a/chrome/browser/ui/webui/settings/about_handler.cc b/chrome/browser/ui/webui/settings/about_handler.cc index b2ee5511e..cc84f71 100644 --- a/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chrome/browser/ui/webui/settings/about_handler.cc
@@ -378,10 +378,12 @@ policy_registrar_ = std::make_unique<policy::PolicyChangeRegistrar>( g_browser_process->policy_service(), policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())); +#if BUILDFLAG(IS_CHROMEOS) policy_registrar_->Observe( policy::key::kDeviceAutoUpdateDisabled, base::BindRepeating(&AboutHandler::OnDeviceAutoUpdatePolicyChanged, base::Unretained(this))); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) } void AboutHandler::OnJavascriptDisallowed() {
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chrome/browser/ui/webui/settings/site_settings_handler.cc index 9bbfd03..c9efdd1 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -1345,17 +1345,17 @@ ContentSetting setting; CHECK(content_settings::ContentSettingFromString(value, &setting)); - Profile* profile = nullptr; + Profile* target_profile = nullptr; if (incognito) { if (!profile_->HasPrimaryOTRProfile()) return; - profile = profile_->GetPrimaryOTRProfile(/*create_if_needed=*/true); + target_profile = profile_->GetPrimaryOTRProfile(/*create_if_needed=*/true); } else { - profile = profile_; + target_profile = profile_; } HostContentSettingsMap* map = - HostContentSettingsMapFactory::GetForProfile(profile); + HostContentSettingsMapFactory::GetForProfile(target_profile); ContentSettingsPattern primary_pattern = ContentSettingsPattern::FromString(primary_pattern_string); @@ -1368,14 +1368,14 @@ if (setting != CONTENT_SETTING_BLOCK) { GURL url(primary_pattern.ToString()); if (url.is_valid()) { - PermissionDecisionAutoBlockerFactory::GetForProfile(profile_) + PermissionDecisionAutoBlockerFactory::GetForProfile(target_profile) ->RemoveEmbargoAndResetCounts(url, content_type); } } permissions::PermissionUmaUtil::ScopedRevocationReporter scoped_revocation_reporter( - profile, primary_pattern, secondary_pattern, content_type, + target_profile, primary_pattern, secondary_pattern, content_type, permissions::PermissionSourceUI::SITE_SETTINGS); map->SetContentSettingCustomScope(primary_pattern, secondary_pattern,
diff --git a/chrome/browser/ui/webui/signin/turn_sync_on_helper.cc b/chrome/browser/ui/webui/signin/turn_sync_on_helper.cc index a533d2a..a40434d 100644 --- a/chrome/browser/ui/webui/signin/turn_sync_on_helper.cc +++ b/chrome/browser/ui/webui/signin/turn_sync_on_helper.cc
@@ -517,7 +517,7 @@ NOTREACHED(); break; case SyncStartupTracker::ServiceStartupState::kTimeout: - LOG(WARNING) << "Waiting for Sync Service to start timed out."; + DVLOG(1) << "Waiting for Sync Service to start timed out."; [[fallthrough]]; case SyncStartupTracker::ServiceStartupState::kError: case SyncStartupTracker::ServiceStartupState::kComplete:
diff --git a/chrome/browser/web_applications/app_service/BUILD.gn b/chrome/browser/web_applications/app_service/BUILD.gn index d6096354..5d02eb7 100644 --- a/chrome/browser/web_applications/app_service/BUILD.gn +++ b/chrome/browser/web_applications/app_service/BUILD.gn
@@ -22,6 +22,7 @@ deps = [ "//base", "//chrome/browser/ash/system_web_apps", + "//chrome/browser/ash/system_web_apps/types", "//chrome/browser/profiles:profile", "//chrome/browser/ui", "//chrome/browser/web_applications",
diff --git a/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc b/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc index 76995dda..796178f 100644 --- a/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc +++ b/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc
@@ -8,6 +8,8 @@ #include <memory> #include <ostream> #include <set> +#include <tuple> +#include <type_traits> #include <utility> #include "base/bind.h" @@ -18,20 +20,25 @@ #include "base/containers/extend.h" #include "base/containers/flat_map.h" #include "base/containers/flat_set.h" +#include "base/containers/flat_tree.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/metrics/histogram_base.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "base/supports_user_data.h" #include "base/time/time.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/app_service/app_launch_params.h" +#include "chrome/browser/apps/app_service/app_service_proxy_forward.h" #include "chrome/browser/apps/app_service/intent_util.h" #include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/apps/app_service/publishers/app_publisher.h" +#include "chrome/browser/badging/badge_manager.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -44,29 +51,42 @@ #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/web_applications/commands/run_on_os_login_command.h" #include "chrome/browser/web_applications/os_integration/os_integration_manager.h" +#include "chrome/browser/web_applications/os_integration/web_app_file_handler_manager.h" #include "chrome/browser/web_applications/policy/web_app_policy_manager.h" #include "chrome/browser/web_applications/user_display_mode.h" #include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_chromeos_data.h" #include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_install_finalizer.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_sync_bridge.h" -#include "chrome/browser/web_applications/web_app_ui_manager.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "chrome/common/extensions/extension_constants.h" +#include "components/content_settings/core/browser/content_settings_type_set.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/services/app_service/public/cpp/app_types.h" +#include "components/services/app_service/public/cpp/file_handler.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_filter.h" #include "components/services/app_service/public/cpp/intent_util.h" -#include "components/services/app_service/public/cpp/publisher_base.h" #include "components/services/app_service/public/cpp/run_on_os_login_types.h" +#include "components/services/app_service/public/cpp/shortcut.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/browser/clear_site_data_utils.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_user_data.h" #include "content/public/common/content_features.h" +#include "mojo/public/cpp/bindings/struct_ptr.h" +#include "net/cookies/cookie_partition_key.h" #include "ui/base/window_open_disposition.h" #include "ui/display/types/display_constants.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notifier_id.h" #include "url/gurl.h" #include "url/origin.h" @@ -77,7 +97,6 @@ #include "chrome/browser/apps/app_service/metrics/app_service_metrics.h" #include "chrome/browser/badging/badge_manager_factory.h" #include "chrome/browser/notifications/notification_display_service_factory.h" -#include "chrome/common/chrome_switches.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -86,6 +105,7 @@ #include "chrome/browser/ash/file_manager/app_id.h" #include "chrome/browser/ash/login/demo_mode/demo_session.h" #include "chrome/browser/ash/system_web_apps/system_web_app_manager.h" +#include "chrome/browser/ash/system_web_apps/types/system_web_app_delegate.h" #include "chrome/browser/chromeos/arc/arc_web_contents_data.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/full_restore_save_handler.h" @@ -503,6 +523,8 @@ } apps::AppPtr WebAppPublisherHelper::CreateWebApp(const WebApp* web_app) { + DCHECK(!IsShuttingDown()); + apps::Readiness readiness = web_app->is_locally_installed() ? (web_app->is_uninstalling() ? apps::Readiness::kUninstalledByUser @@ -623,123 +645,7 @@ apps::mojom::AppPtr WebAppPublisherHelper::ConvertWebApp( const WebApp* web_app) { - DCHECK(!IsShuttingDown()); - apps::mojom::Readiness readiness = - web_app->is_locally_installed() - ? (web_app->is_uninstalling() - ? apps::mojom::Readiness::kUninstalledByUser - : apps::mojom::Readiness::kReady) - : apps::mojom::Readiness::kDisabledByUser; -#if BUILDFLAG(IS_CHROMEOS) - DCHECK(web_app->chromeos_data().has_value()); - if (web_app->chromeos_data()->is_disabled) - readiness = apps::mojom::Readiness::kDisabledByPolicy; -#endif - - auto install_reason = GetHighestPriorityInstallReason(web_app); - apps::mojom::AppPtr app = apps::PublisherBase::MakeApp( - apps::ConvertAppTypeToMojomAppType(app_type()), web_app->app_id(), - readiness, provider_->registrar().GetAppShortName(web_app->app_id()), - install_reason); - - app->install_source = ConvertInstallSourceToMojom( - provider_->registrar().GetAppInstallSourceForMetrics(web_app->app_id())); - - app->policy_id = GetPolicyId(*web_app); - - // For system web apps (only), the install source is |kSystem|. - DCHECK_EQ(web_app->IsSystemApp(), - app->install_reason == apps::mojom::InstallReason::kSystem); - - app->description = - provider_->registrar().GetAppDescription(web_app->app_id()); - app->additional_search_terms = web_app->additional_search_terms(); - app->last_launch_time = web_app->last_launch_time(); - app->install_time = web_app->install_time(); - - // Web App's publisher_id the start url. - app->publisher_id = web_app->start_url().spec(); - - auto display_mode = registrar().GetAppEffectiveDisplayMode(web_app->app_id()); - app->window_mode = apps::ConvertWindowModeToMojomWindowMode( - ConvertDisplayModeToWindowMode(display_mode)); - - // app->version is left empty here. - PopulateWebAppPermissions(web_app, &app->permissions); - - SetWebAppShowInFields(app, web_app); - - app->allow_uninstall = web_app->CanUserUninstallWebApp() - ? apps::mojom::OptionalBool::kTrue - : apps::mojom::OptionalBool::kFalse; - - // Add the intent filters for PWAs. - base::Extend( - app->intent_filters, - apps_util::CreateWebAppIntentFilters( - web_app->app_id(), registrar().GetAppScope(web_app->app_id()), - registrar().GetAppShareTarget(web_app->app_id()), - provider_->os_integration_manager().GetEnabledFileHandlers( - web_app->app_id()))); - - // These filters are used by the settings page to display would-be-handled - // extensions even when the feature is not enabled for the app, whereas - // `GetEnabledFileHandlers` above only returns the ones that currently are - // enabled. - const apps::FileHandlers* all_file_handlers = - registrar().GetAppFileHandlers(web_app->app_id()); - if (all_file_handlers && !all_file_handlers->empty()) { - std::set<std::string> extensions_set = - apps::GetFileExtensionsFromFileHandlers(*all_file_handlers); - app->intent_filters.push_back(apps_util::CreateFileFilter( - {apps_util::kIntentActionPotentialFileHandler}, - /*mime_types=*/{}, - /*file_extensions=*/ - {extensions_set.begin(), extensions_set.end()})); - } - - if (IsNoteTakingWebApp(*web_app)) - app->intent_filters.push_back(apps_util::CreateNoteTakingFilterMojom()); - - if (IsLockScreenCapable(*web_app)) - app->intent_filters.push_back(apps_util::CreateLockScreenFilterMojom()); - -#if BUILDFLAG(IS_CHROMEOS_ASH) - if (web_app->app_id() == crostini::kCrostiniTerminalSystemAppId) { - app->intent_filters.push_back(apps_util::CreateFileFilter( - {apps_util::kIntentActionView}, - /*mime_types=*/ - {extensions::app_file_handler_util::kMimeTypeInodeDirectory}, - /*file_extensions=*/{})); - } -#endif - - app->icon_key = MakeIconKey(web_app); - - bool paused = IsPaused(web_app->app_id()); - app->paused = paused ? apps::mojom::OptionalBool::kTrue - : apps::mojom::OptionalBool::kFalse; - -#if BUILDFLAG(IS_CHROMEOS) - if (readiness != apps::mojom::Readiness::kReady) { - UpdateAppDisabledMode(app); - } - - app->has_badge = - ShouldShowBadge(web_app->app_id(), - app_notifications_.HasNotification(web_app->app_id())) - ? apps::mojom::OptionalBool::kTrue - : apps::mojom::OptionalBool::kFalse; -#else - app->has_badge = apps::mojom::OptionalBool::kFalse; -#endif - const auto login_mode = registrar().GetAppRunOnOsLoginMode(web_app->app_id()); - app->run_on_os_login = apps::mojom::RunOnOsLogin::New( - apps::ConvertRunOnOsLoginModeToMojomRunOnOsLoginMode( - ConvertOsLoginMode(login_mode.value)), - !login_mode.user_controllable); - - return app; + return apps::ConvertAppToMojomApp(CreateWebApp(web_app)); } apps::AppPtr WebAppPublisherHelper::ConvertUninstalledWebApp( @@ -1124,11 +1030,9 @@ return; } -#if BUILDFLAG(IS_CHROMEOS) if (!IsWebAppsCrosapiEnabled()) { return; } -#endif apps::BrowserAppInstanceTracker* instance_tracker = apps::AppServiceProxyFactory::GetForProfile(profile_)
diff --git a/chrome/browser/web_applications/extensions/BUILD.gn b/chrome/browser/web_applications/extensions/BUILD.gn index 9bc02ed..659631b 100644 --- a/chrome/browser/web_applications/extensions/BUILD.gn +++ b/chrome/browser/web_applications/extensions/BUILD.gn
@@ -36,6 +36,7 @@ "//chrome/browser/web_applications", "//chrome/common", "//components/pref_registry", + "//components/services/app_service/public/cpp:app_types", "//components/services/app_service/public/mojom", "//components/sync/model", "//components/webapps/browser:browser",
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_util.cc b/chrome/browser/web_applications/extensions/bookmark_app_util.cc index 7af7d438..ae63056 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_util.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_util.cc
@@ -61,20 +61,20 @@ LaunchContainerAndType GetLaunchContainerAndTypeFromDisplayMode( web_app::DisplayMode display_mode) { - apps::mojom::LaunchContainer apps_launch_container = + apps::LaunchContainer apps_launch_container = web_app::ConvertDisplayModeToAppLaunchContainer(display_mode); switch (apps_launch_container) { - case apps::mojom::LaunchContainer::kLaunchContainerNone: - return {apps::mojom::LaunchContainer::kLaunchContainerNone, + case apps::LaunchContainer::kLaunchContainerNone: + return {apps::LaunchContainer::kLaunchContainerNone, extensions::LaunchType::LAUNCH_TYPE_DEFAULT}; - case apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated: - return {apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated, + case apps::LaunchContainer::kLaunchContainerPanelDeprecated: + return {apps::LaunchContainer::kLaunchContainerPanelDeprecated, extensions::LaunchType::LAUNCH_TYPE_REGULAR}; - case apps::mojom::LaunchContainer::kLaunchContainerTab: - return {apps::mojom::LaunchContainer::kLaunchContainerTab, + case apps::LaunchContainer::kLaunchContainerTab: + return {apps::LaunchContainer::kLaunchContainerTab, extensions::LaunchType::LAUNCH_TYPE_REGULAR}; - case apps::mojom::LaunchContainer::kLaunchContainerWindow: - return {apps::mojom::LaunchContainer::kLaunchContainerTab, + case apps::LaunchContainer::kLaunchContainerWindow: + return {apps::LaunchContainer::kLaunchContainerTab, display_mode == web_app::DisplayMode::kFullscreen ? extensions::LaunchType::LAUNCH_TYPE_FULLSCREEN : extensions::LaunchType::LAUNCH_TYPE_WINDOW};
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_util.h b/chrome/browser/web_applications/extensions/bookmark_app_util.h index 4390d331..36bd176a 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_util.h +++ b/chrome/browser/web_applications/extensions/bookmark_app_util.h
@@ -7,6 +7,7 @@ #include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_install_info.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/common/constants.h" namespace content { @@ -33,7 +34,7 @@ bool IsInNavigationScopeForLaunchUrl(const GURL& launch_url, const GURL& url); struct LaunchContainerAndType { - apps::mojom::LaunchContainer launch_container; + apps::LaunchContainer launch_container; extensions::LaunchType launch_type; };
diff --git a/chrome/browser/web_applications/web_app_constants.cc b/chrome/browser/web_applications/web_app_constants.cc index 1345856..cc36df79 100644 --- a/chrome/browser/web_applications/web_app_constants.cc +++ b/chrome/browser/web_applications/web_app_constants.cc
@@ -9,7 +9,7 @@ #include "base/compiler_specific.h" #include "chrome/browser/web_applications/user_display_mode.h" #include "chrome/common/chrome_features.h" -#include "components/services/app_service/public/mojom/types.mojom.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "content/public/common/content_features.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -137,19 +137,19 @@ return resolved_display_mode; } -apps::mojom::LaunchContainer ConvertDisplayModeToAppLaunchContainer( +apps::LaunchContainer ConvertDisplayModeToAppLaunchContainer( DisplayMode display_mode) { switch (display_mode) { case DisplayMode::kBrowser: - return apps::mojom::LaunchContainer::kLaunchContainerTab; + return apps::LaunchContainer::kLaunchContainerTab; case DisplayMode::kMinimalUi: case DisplayMode::kStandalone: case DisplayMode::kFullscreen: case DisplayMode::kWindowControlsOverlay: case DisplayMode::kTabbed: - return apps::mojom::LaunchContainer::kLaunchContainerWindow; + return apps::LaunchContainer::kLaunchContainerWindow; case DisplayMode::kUndefined: - return apps::mojom::LaunchContainer::kLaunchContainerNone; + return apps::LaunchContainer::kLaunchContainerNone; } }
diff --git a/chrome/browser/web_applications/web_app_constants.h b/chrome/browser/web_applications/web_app_constants.h index 1b260b6d..41c78363 100644 --- a/chrome/browser/web_applications/web_app_constants.h +++ b/chrome/browser/web_applications/web_app_constants.h
@@ -11,6 +11,7 @@ #include <vector> #include "chrome/browser/web_applications/user_display_mode.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/run_on_os_login_types.h" #include "components/services/app_service/public/mojom/types.mojom-forward.h" #include "third_party/blink/public/common/manifest/manifest.h" @@ -164,7 +165,7 @@ UserDisplayMode user_display_mode, bool is_isolated); -apps::mojom::LaunchContainer ConvertDisplayModeToAppLaunchContainer( +apps::LaunchContainer ConvertDisplayModeToAppLaunchContainer( DisplayMode display_mode); // The operation mode for Run on OS Login.
diff --git a/chrome/browser/web_applications/web_app_icon_manager_browsertest.cc b/chrome/browser/web_applications/web_app_icon_manager_browsertest.cc index 12cc99b..d45d51df 100644 --- a/chrome/browser/web_applications/web_app_icon_manager_browsertest.cc +++ b/chrome/browser/web_applications/web_app_icon_manager_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/web_applications/web_app_install_utils.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/webapps/browser/install_result_code.h" #include "components/webapps/browser/installable/installable_metrics.h" @@ -115,10 +116,10 @@ WebAppBrowserController* controller; { - apps::AppLaunchParams params( - app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromTest); + apps::AppLaunchParams params(app_id, + apps::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromTest); content::WebContents* contents = apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher()
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 2fb6dc81..9c5c6b4 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1656914368-5001a8b9b8044ee35db01ee492cabbd1f395b5b0.profdata +chrome-linux-main-1656978378-52d63b1ea90adacdd3fad89c66d5a0bb99535e1f.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 3e87d7f..a807722 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1656914368-b3c0f85b2f944b6fe9ef2bd7ff7718f75238f9c9.profdata +chrome-mac-arm-main-1656956749-2cc23747b7471debb5a097933912b2a814829eed.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 72fa882..2cf73dd1 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1656914368-9e11ca866685478cd0552483fe965b102fa6ea9a.profdata +chrome-mac-main-1656978378-e5487b3bdfa923bdb0112e79c9fb2a484253a9d2.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index f0674d9..924f38aa 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1656924679-1489720740e0ed53dceee8e75fd004fada5af955.profdata +chrome-win32-main-1656978378-7598a1d5e1abb7b31a9885474b09777419743a9c.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index da4b91a..a2e74e48f 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1656924679-f2572f186d1f9a201ba710fbe839c2e4b1145827.profdata +chrome-win64-main-1656989798-ff1ea13aec751aa8903a31d640534c9047fc9103.profdata
diff --git a/chrome/chrome_paks.gni b/chrome/chrome_paks.gni index 981f263e..ba559fa 100644 --- a/chrome/chrome_paks.gni +++ b/chrome/chrome_paks.gni
@@ -250,6 +250,7 @@ "$root_gen_dir/chrome/internet_config_dialog_resources.pak", "$root_gen_dir/chrome/internet_detail_dialog_resources.pak", "$root_gen_dir/chrome/launcher_internals_resources.pak", + "$root_gen_dir/chrome/manage_mirrorsync_resources.pak", "$root_gen_dir/chrome/multidevice_internals_resources.pak", "$root_gen_dir/chrome/multidevice_setup_resources.pak", "$root_gen_dir/chrome/nearby_internals_resources.pak", @@ -311,6 +312,7 @@ "//chrome/browser/resources/chromeos/launcher_internals:resources", "//chrome/browser/resources/chromeos/login:conditional_resources", "//chrome/browser/resources/chromeos/login:unconditional_resources", + "//chrome/browser/resources/chromeos/manage_mirrorsync:resources", "//chrome/browser/resources/chromeos/multidevice_internals:resources", "//chrome/browser/resources/chromeos/network_ui:resources", "//chrome/browser/resources/chromeos/notification_tester:resources",
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 682ee25e..e2071a72 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -191,6 +191,7 @@ "//components/component_updater", "//components/content_settings/core/common", "//components/crash/core/common", + "//components/device_signals/core/common:features", "//components/dom_distiller/core", "//components/embedder_support/origin_trials", "//components/error_page/common", @@ -218,6 +219,7 @@ "//components/safe_browsing:buildflags", "//components/safe_browsing/core/common", "//components/services/app_service/public/cpp:app_share_target", + "//components/services/app_service/public/cpp:app_types", "//components/services/heap_profiling/public/cpp", "//components/strings", "//components/translate/content/common",
diff --git a/chrome/common/extensions/DEPS b/chrome/common/extensions/DEPS index 6a108e8..13155d7 100644 --- a/chrome/common/extensions/DEPS +++ b/chrome/common/extensions/DEPS
@@ -1,9 +1,9 @@ include_rules = [ "+ash/keyboard/ui/resources", # For virtual keyboard "+components/app_constants/constants.h", + "+components/device_signals/core/common", "+components/policy/core/common", - "+components/services/app_service/public/mojom/types.mojom-shared.h", - "+components/services/app_service/public/mojom/types.mojom-forward.h", + "+components/services/app_service/public/cpp", "+extensions/grit", "+extensions/strings/grit", "+extensions/test",
diff --git a/chrome/common/extensions/api/file_manager_private.idl b/chrome/common/extensions/api/file_manager_private.idl index dfdcf8a..910cc61 100644 --- a/chrome/common/extensions/api/file_manager_private.idl +++ b/chrome/common/extensions/api/file_manager_private.idl
@@ -1724,6 +1724,9 @@ // Tells DriveFS to update its cached pin states of hosted files (once). static void pollDriveHostedFilePinStates(); + + // Opens the dialog to manage the currently syncing folders. + static void openManageSyncSettings(); }; // Events supported by fileManagerPrivate API. These events are broadcasted.
diff --git a/chrome/common/extensions/manifest_handlers/app_launch_info.cc b/chrome/common/extensions/manifest_handlers/app_launch_info.cc index 47c51ba..8b6378a 100644 --- a/chrome/common/extensions/manifest_handlers/app_launch_info.cc +++ b/chrome/common/extensions/manifest_handlers/app_launch_info.cc
@@ -14,7 +14,6 @@ #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/url_constants.h" #include "components/app_constants/constants.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "extensions/common/constants.h" #include "extensions/common/error_utils.h" #include "extensions/common/manifest_constants.h" @@ -62,10 +61,7 @@ } // namespace -AppLaunchInfo::AppLaunchInfo() - : launch_container_(apps::mojom::LaunchContainer::kLaunchContainerTab), - launch_width_(0), - launch_height_(0) {} +AppLaunchInfo::AppLaunchInfo() = default; AppLaunchInfo::~AppLaunchInfo() { } @@ -82,7 +78,7 @@ } // static -apps::mojom::LaunchContainer AppLaunchInfo::GetLaunchContainer( +apps::LaunchContainer AppLaunchInfo::GetLaunchContainer( const Extension* extension) { return GetAppLaunchInfo(extension).launch_container_; } @@ -232,10 +228,9 @@ tmp_launcher_container->GetString(); if (launch_container_string == values::kLaunchContainerPanelDeprecated) { - launch_container_ = - apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated; + launch_container_ = apps::LaunchContainer::kLaunchContainerPanelDeprecated; } else if (launch_container_string == values::kLaunchContainerTab) { - launch_container_ = apps::mojom::LaunchContainer::kLaunchContainerTab; + launch_container_ = apps::LaunchContainer::kLaunchContainerTab; } else { *error = errors::kInvalidLaunchContainer; return false; @@ -245,7 +240,7 @@ // deprecated. bool can_specify_initial_size = launch_container_ == - apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated; + apps::LaunchContainer::kLaunchContainerPanelDeprecated; // Validate the container width if present. if (!ReadLaunchDimension(extension->manifest(),
diff --git a/chrome/common/extensions/manifest_handlers/app_launch_info.h b/chrome/common/extensions/manifest_handlers/app_launch_info.h index a9028b7..2f89e8b2 100644 --- a/chrome/common/extensions/manifest_handlers/app_launch_info.h +++ b/chrome/common/extensions/manifest_handlers/app_launch_info.h
@@ -9,7 +9,7 @@ #include <vector> #include "chrome/common/extensions/extension_constants.h" -#include "components/services/app_service/public/mojom/types.mojom-forward.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/manifest.h" @@ -39,8 +39,7 @@ // users can override the way each app launches. See // ExtensionPrefs::GetLaunchContainer(), which looks at a per-app pref // to decide what container an app will launch in. - static apps::mojom::LaunchContainer GetLaunchContainer( - const Extension* extension); + static apps::LaunchContainer GetLaunchContainer(const Extension* extension); // The default size of the container when launching. Only respected for // containers like panels and windows. @@ -61,10 +60,11 @@ GURL launch_web_url_; - apps::mojom::LaunchContainer launch_container_; + apps::LaunchContainer launch_container_ = + apps::LaunchContainer::kLaunchContainerTab; - int launch_width_; - int launch_height_; + int launch_width_ = 0; + int launch_height_ = 0; }; // Parses all app launch related keys in the manifest.
diff --git a/chrome/common/extensions/manifest_tests/extension_manifests_launch_unittest.cc b/chrome/common/extensions/manifest_tests/extension_manifests_launch_unittest.cc index d995661..6724287 100644 --- a/chrome/common/extensions/manifest_tests/extension_manifests_launch_unittest.cc +++ b/chrome/common/extensions/manifest_tests/extension_manifests_launch_unittest.cc
@@ -6,7 +6,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" @@ -22,15 +22,15 @@ TEST_F(AppLaunchManifestTest, AppLaunchContainer) { scoped_refptr<Extension> extension = LoadAndExpectSuccess("launch_tab.json"); - EXPECT_EQ(apps::mojom::LaunchContainer::kLaunchContainerTab, + EXPECT_EQ(apps::LaunchContainer::kLaunchContainerTab, AppLaunchInfo::GetLaunchContainer(extension.get())); extension = LoadAndExpectSuccess("launch_panel.json"); - EXPECT_EQ(apps::mojom::LaunchContainer::kLaunchContainerPanelDeprecated, + EXPECT_EQ(apps::LaunchContainer::kLaunchContainerPanelDeprecated, AppLaunchInfo::GetLaunchContainer(extension.get())); extension = LoadAndExpectSuccess("launch_default.json"); - EXPECT_EQ(apps::mojom::LaunchContainer::kLaunchContainerTab, + EXPECT_EQ(apps::LaunchContainer::kLaunchContainerTab, AppLaunchInfo::GetLaunchContainer(extension.get())); extension = LoadAndExpectSuccess("launch_width.json");
diff --git a/chrome/common/extensions/manifest_tests/extension_manifests_validapp_unittest.cc b/chrome/common/extensions/manifest_tests/extension_manifests_validapp_unittest.cc index fc6e21d..21bf63a 100644 --- a/chrome/common/extensions/manifest_tests/extension_manifests_validapp_unittest.cc +++ b/chrome/common/extensions/manifest_tests/extension_manifests_validapp_unittest.cc
@@ -8,7 +8,6 @@ #include "base/values.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "testing/gtest/include/gtest/gtest.h" typedef ChromeManifestTest ValidAppManifestTest; @@ -20,7 +19,7 @@ AddPattern(&expected_patterns, "http://www.google.com/mail/*"); AddPattern(&expected_patterns, "http://www.google.com/foobar/*"); EXPECT_EQ(expected_patterns, extension->web_extent()); - EXPECT_EQ(apps::mojom::LaunchContainer::kLaunchContainerTab, + EXPECT_EQ(apps::LaunchContainer::kLaunchContainerTab, extensions::AppLaunchInfo::GetLaunchContainer(extension.get())); EXPECT_EQ(GURL("http://www.google.com/mail/"), extensions::AppLaunchInfo::GetLaunchWebURL(extension.get()));
diff --git a/chrome/common/extensions/permissions/chrome_permission_message_rules.cc b/chrome/common/extensions/permissions/chrome_permission_message_rules.cc index 15d7b4b..6538a7d96 100644 --- a/chrome/common/extensions/permissions/chrome_permission_message_rules.cc +++ b/chrome/common/extensions/permissions/chrome_permission_message_rules.cc
@@ -11,10 +11,12 @@ #include <utility> #include <vector> +#include "base/feature_list.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/grit/generated_resources.h" +#include "components/device_signals/core/common/signals_features.h" #include "ui/base/l10n/l10n_util.h" using extensions::mojom::APIPermissionID; @@ -275,6 +277,20 @@ } }; +int GetEnterpriseReportingPrivatePermissionMessageId() { + if (!base::FeatureList::IsEnabled( + enterprise_signals::features::kNewEvSignalsEnabled)) { + return IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE; + } +#if BUILDFLAG(IS_WIN) + return IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_WIN; +#elif BUILDFLAG(IS_LINUX) or BUILDFLAG(IS_MAC) + return IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE_ENABLED_LINUX_AND_MACOS; +#else + return IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE; +#endif +} + } // namespace ChromePermissionMessageRule::ChromePermissionMessageRule( @@ -696,7 +712,7 @@ {IDS_EXTENSION_PROMPT_WARNING_USERS_PRIVATE, {APIPermissionID::kUsersPrivate}, {}}, - {IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_REPORTING_PRIVATE, + {GetEnterpriseReportingPrivatePermissionMessageId(), {APIPermissionID::kEnterpriseReportingPrivate}, {}}, {IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_HARDWARE_PLATFORM,
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index fbfceb1..6765afa 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -813,7 +813,6 @@ "//chrome/browser/metrics:test_support", "//chrome/browser/payments:browser_tests", "//chrome/browser/persisted_state_db:persisted_state_db", - "//chrome/browser/persisted_state_db:persisted_state_db_content_proto", "//chrome/browser/policy:browser_tests", "//chrome/browser/prerender:browser_tests", "//chrome/browser/privacy_budget:browser_tests", @@ -823,6 +822,7 @@ "//components/browser_ui/widget/android:java", "//components/commerce/core:commerce_heuristics_data", "//components/commerce/core:feature_list", + "//components/commerce/core:persisted_state_db_content_proto", "//components/content_settings/browser:browser", "//components/crash/android:crashpad_main", "//components/infobars/content", @@ -5575,7 +5575,6 @@ "//chrome/browser/notifications:unit_tests", "//chrome/browser/payments:unittests", "//chrome/browser/persisted_state_db:persisted_state_db", - "//chrome/browser/persisted_state_db:persisted_state_db_content_proto", "//chrome/browser/policy:test_support", "//chrome/browser/prerender:unit_tests", "//chrome/browser/privacy_budget:unit_tests", @@ -5630,6 +5629,7 @@ "//components/certificate_transparency:proto", "//components/commerce/core:commerce_heuristics_data", "//components/commerce/core:feature_list", + "//components/commerce/core:persisted_state_db_content_proto", "//components/component_updater:test_support", "//components/content_settings/browser", "//components/content_settings/browser:test_support", @@ -6776,7 +6776,6 @@ # Urgent discarding from performance_manager, high-efficiency mode, and # the High-PMF discard policy aren't supported on Android. "../browser/performance_manager/policies/high_efficiency_mode_policy_unittest.cc", - "../browser/performance_manager/policies/high_pmf_discard_policy_unittest.cc", "../browser/performance_manager/policies/page_discarding_helper_unittest.cc", "../browser/performance_manager/policies/urgent_page_discarding_policy_unittest.cc", ]
diff --git a/chrome/test/data/android/url_overriding/navigation_from_long_timeout.html b/chrome/test/data/android/url_overriding/navigation_from_long_timeout.html new file mode 100644 index 0000000..510361b --- /dev/null +++ b/chrome/test/data/android/url_overriding/navigation_from_long_timeout.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" + content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> + <script> + function waitAndOpenApp() { + window.setTimeout(function () { + window.location.replace( + 'intent://test/#Intent;scheme=externalappscheme;end' + ); + }, 6000); + }; + </script> +</head> +<body style='height:10000px;' onclick='waitAndOpenApp();'> + Click page to open App!! +</body> +</html>
diff --git a/chrome/test/data/android/url_overriding/navigation_from_timer_with_fallback.html b/chrome/test/data/android/url_overriding/navigation_from_timer_with_fallback.html new file mode 100644 index 0000000..a2a8f4cb --- /dev/null +++ b/chrome/test/data/android/url_overriding/navigation_from_timer_with_fallback.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html> +<head> + <script> + function openHello() { + window.location = 'intent://test/#Intent;scheme=externalappscheme;S.browser_fallback_url=PARAM_FALLBACK_URL;end'; + }; + setTimeout(openHello, 2000) + </script> +</head> +<body> + Welcome to Hello. +</body> +</html>
diff --git a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js index 16778ce4..114b3e5 100644 --- a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js +++ b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js
@@ -25,7 +25,8 @@ /** @type {function(...!string): ?HTMLElement} */ let findEmojiFirstButton; /** @type {string} */ - const emoticonGroupSelector = 'emoji-group[category="emoticon"]'; + const emoticonGroupSelector = + 'emoji-group[category="emoticon"]:not(.history)'; /** @type {string} */ const emoticonHistoryGroupSelector = '[data-group="emoticon-history"] > emoji-group[category="emoticon"]'; @@ -117,8 +118,11 @@ }); test('all emoticon groups should be rendered.', () => { + const numEmoticons = emojiPicker.categoriesData.filter( + item => item.category === 'emoticon').length; + assertGT(numEmoticons, 0); assertEquals( - emojiPicker.emoticonData.length, + numEmoticons, emojiPicker.shadowRoot.querySelectorAll( emoticonGroupSelector).length); }); @@ -129,15 +133,28 @@ async () => { const allEmoticonGroups = emojiPicker.shadowRoot.querySelectorAll(emoticonGroupSelector); + + const emoticonData = emojiPicker.categoriesData.filter( + item => item.category === 'emoticon'); + const emoticonGroupElements = + emojiPicker.categoriesGroupElements.filter( + item => item.category === 'emoticon'); + + // The first group element is 'Recently used'. + assertEquals(emoticonGroupElements[0].name, 'Recently used'); + + // Emoticon group elements are created for all data + history. + assertEquals(emoticonGroupElements.length, emoticonData.length + 1); + for (let idx = 0; idx < allEmoticonGroups.length; ++idx) { const group = allEmoticonGroups[idx]; const actualFirstGroupName = group.shadowRoot.querySelector('#heading-left').innerHTML.trim(); - const expectedFirstGroupName = emojiPicker.emoticonData[idx].group; + const expectedFirstGroupName = emoticonGroupElements[idx+1].name; assertEquals(expectedFirstGroupName, actualFirstGroupName); const expectedNumberOfEmoticons = - emojiPicker.emoticonData[idx].emoji.length; + emoticonGroupElements[idx+1].emoji.length; await waitForCondition( () => expectedNumberOfEmoticons === group.shadowRoot.querySelectorAll('.emoji-button').length); @@ -150,10 +167,13 @@ async () => { const firstEmoticonButton = await waitForCondition( () => findEmojiFirstButton(emoticonGroupSelector)); + const emoticonGroupElements = + emojiPicker.categoriesGroupElements.filter( + item => item.category === 'emoticon' && !item.isHistory); const expectedEmoticonString = - emojiPicker.emoticonData[0].emoji[0].base.string; + emoticonGroupElements[0].emoji[0].base.string; const expectedEmoticonName = - emojiPicker.emoticonData[0].emoji[0].base.name; + emoticonGroupElements[0].emoji[0].base.name; const buttonClickPromise = new Promise( (resolve) => emojiPicker.addEventListener(EMOJI_BUTTON_CLICK, (event) => {
diff --git a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_test.js b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_test.js index 2e9faf7..7b2a8c5 100644 --- a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_test.js +++ b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_test.js
@@ -112,7 +112,7 @@ test('recently used should be hidden when empty', () => { const recentlyUsed = findInEmojiPicker('[data-group="emoji-history"] > emoji-group'); - assert(!recentlyUsed); + assert(recentlyUsed.classList.contains('hidden')); }); test( @@ -211,7 +211,7 @@ const recentlyUsed = findInEmojiPicker('[data-group="emoji-history"] > emoji-group'); - assert(!recentlyUsed); + assert(recentlyUsed.classList.contains('hidden')); }); test('recently used should be empty after clearing', async () => { @@ -238,8 +238,9 @@ // Expect no more history. await waitForCondition( - () => findInEmojiPicker('[data-group="emoji-history"] > emoji-group') - .style.display === 'none', + () => findInEmojiPicker( + '[data-group="emoji-history"] > emoji-group') + .classList.contains('hidden'), 'history failed to disappear'); });
diff --git a/chrome/test/ppapi/ppapi_browsertest.cc b/chrome/test/ppapi/ppapi_browsertest.cc index 8c68d18..19301c1 100644 --- a/chrome/test/ppapi/ppapi_browsertest.cc +++ b/chrome/test/ppapi/ppapi_browsertest.cc
@@ -2095,10 +2095,10 @@ const extensions::Extension* extension = LoadExtension(app_dir); ASSERT_TRUE(extension); - apps::AppLaunchParams params( - extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - apps::mojom::LaunchSource::kFromTest); + apps::AppLaunchParams params(extension->id(), + apps::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::LaunchSource::kFromTest); params.command_line = *base::CommandLine::ForCurrentProcess(); apps::AppServiceProxyFactory::GetForProfile(browser()->profile()) ->BrowserAppLauncher()
diff --git a/chromeos/profiles/orderfile.newest.txt b/chromeos/profiles/orderfile.newest.txt index 2c251fe..d5545a2 100644 --- a/chromeos/profiles/orderfile.newest.txt +++ b/chromeos/profiles/orderfile.newest.txt
@@ -1 +1 @@ -chromeos-chrome-orderfile-field-104-5112.9-1656324473-benchmark-104.0.5112.32-r1.orderfile.xz +chromeos-chrome-orderfile-field-104-5112.9-1656324473-benchmark-104.0.5112.33-r1.orderfile.xz
diff --git a/chromeos/tast_control.gni b/chromeos/tast_control.gni index 5974dae..6f881560 100644 --- a/chromeos/tast_control.gni +++ b/chromeos/tast_control.gni
@@ -230,16 +230,6 @@ # https://crbug.com/1335176 "policy.ScreenBrightnessPercent", - # https://crbug.com/1334354 - "arc.Boot.vm", - "arc.ChromeCrash.vm_logged_in", - "arc.Drivefs.vm", - "arc.OptinManaged.vm", - "arc.OptinNetworkError.vm", - "arc.RemovableMedia.vm", - "security.NetworkListenersARC.vm", - "security.SELinuxFilesDataDir.vm", - # b/233264555 "inputs.PhysicalKeyboardEmojiSuggestion", "inputs.PhysicalKeyboardEmojiSuggestion.guest", @@ -276,6 +266,7 @@ "crostini.BasicLxdNext.stable", "crostini.RestartApp", "crostini.RestartApp.stable", + "crostini.RestartApp.clamshell_stable", # http://crbug.com/1335213 "arc.WindowState.clamshell",
diff --git a/components/BUILD.gn b/components/BUILD.gn index f7e06985..581749d 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -898,6 +898,7 @@ "//components/autofill_assistant/browser:proto", "//components/autofill_assistant/browser/devtools:devtools", "//components/autofill_assistant/browser/devtools:gen_devtools_client_api", + "//components/autofill_assistant/browser/public:public", "//components/autofill_assistant/content/common", "//components/autofill_assistant/content/common:mojo_interfaces", "//components/autofill_assistant/content/renderer:browser_tests",
diff --git a/components/app_restore/app_launch_info.cc b/components/app_restore/app_launch_info.cc index 405be97..1e58e862 100644 --- a/components/app_restore/app_launch_info.cc +++ b/components/app_restore/app_launch_info.cc
@@ -10,7 +10,7 @@ AppLaunchInfo::AppLaunchInfo(const std::string& app_id, int32_t window_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, int64_t display_id, std::vector<base::FilePath> launch_files, @@ -27,7 +27,7 @@ : app_id(app_id), window_id(session_id) {} AppLaunchInfo::AppLaunchInfo(const std::string& app_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, int64_t display_id, std::vector<base::FilePath> launch_files,
diff --git a/components/app_restore/app_launch_info.h b/components/app_restore/app_launch_info.h index 79a3130..c37c4f9 100644 --- a/components/app_restore/app_launch_info.h +++ b/components/app_restore/app_launch_info.h
@@ -10,8 +10,8 @@ #include "base/component_export.h" #include "base/files/file_path.h" #include "components/app_restore/tab_group_info.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" -#include "components/services/app_service/public/mojom/types.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/window_open_disposition.h" #include "url/gurl.h" @@ -23,7 +23,7 @@ struct COMPONENT_EXPORT(APP_RESTORE) AppLaunchInfo { AppLaunchInfo(const std::string& app_id, int32_t window_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, int64_t display_id, std::vector<base::FilePath> launch_files, @@ -32,7 +32,7 @@ AppLaunchInfo(const std::string& app_id, int32_t window_id); AppLaunchInfo(const std::string& app_id, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, int64_t display_id, std::vector<base::FilePath> launch_files,
diff --git a/components/app_restore/full_restore_read_and_save_unittest.cc b/components/app_restore/full_restore_read_and_save_unittest.cc index c59c981..afee082 100644 --- a/components/app_restore/full_restore_read_and_save_unittest.cc +++ b/components/app_restore/full_restore_read_and_save_unittest.cc
@@ -23,9 +23,9 @@ #include "components/app_restore/restore_data.h" #include "components/app_restore/window_info.h" #include "components/app_restore/window_properties.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" -#include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/aura_constants.h" @@ -1059,7 +1059,7 @@ // Add a Chrome app launch info. SaveAppLaunchInfo( GetPath(), std::make_unique<app_restore::AppLaunchInfo>( - kAppId, apps::mojom::LaunchContainer::kLaunchContainerNone, + kAppId, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::UNKNOWN, display::kInvalidDisplayId, std::vector<base::FilePath>{}, nullptr)); const LacrosSaveHandler* lacros_save_handler = test_api.GetLacrosSaveHander(); @@ -1121,7 +1121,7 @@ SaveAppLaunchInfo( GetPath(), std::make_unique<app_restore::AppLaunchInfo>( - kAppId, apps::mojom::LaunchContainer::kLaunchContainerNone, + kAppId, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::CURRENT_TAB, display::kInvalidDisplayId, std::vector<base::FilePath>{base::FilePath(kFilePath1), base::FilePath(kFilePath2)},
diff --git a/components/app_restore/restore_data_unittest.cc b/components/app_restore/restore_data_unittest.cc index e79345ced6..e6799f3 100644 --- a/components/app_restore/restore_data_unittest.cc +++ b/components/app_restore/restore_data_unittest.cc
@@ -15,6 +15,7 @@ #include "components/app_restore/app_restore_data.h" #include "components/app_restore/tab_group_info.h" #include "components/app_restore/window_info.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/tab_groups/tab_group_color.h" @@ -161,8 +162,7 @@ void AddAppLaunchInfos() { std::unique_ptr<AppLaunchInfo> app_launch_info1 = std::make_unique<AppLaunchInfo>( - kAppId1, kWindowId1, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + kAppId1, kWindowId1, apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, kDisplayId1, std::vector<base::FilePath>{base::FilePath(kFilePath1), base::FilePath(kFilePath2)}, @@ -170,8 +170,7 @@ std::unique_ptr<AppLaunchInfo> app_launch_info2 = std::make_unique<AppLaunchInfo>( - kAppId1, kWindowId2, - apps::mojom::LaunchContainer::kLaunchContainerTab, + kAppId1, kWindowId2, apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, kDisplayId2, std::vector<base::FilePath>{base::FilePath(kFilePath2)}, MakeIntent(kIntentActionView, kMimeType, kShareText2)); @@ -182,8 +181,7 @@ std::unique_ptr<AppLaunchInfo> app_launch_info3 = std::make_unique<AppLaunchInfo>( - kAppId2, kWindowId3, - apps::mojom::LaunchContainer::kLaunchContainerNone, + kAppId2, kWindowId3, apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_POPUP, kDisplayId2, std::vector<base::FilePath>{base::FilePath(kFilePath1)}, MakeIntent(kIntentActionView, kMimeType, kShareText1)); @@ -239,7 +237,7 @@ } void VerifyAppRestoreData(const std::unique_ptr<AppRestoreData>& data, - apps::mojom::LaunchContainer container, + apps::LaunchContainer container, WindowOpenDisposition disposition, int64_t display_id, std::vector<base::FilePath> file_paths, @@ -394,7 +392,7 @@ VerifyAppRestoreData( app_restore_data_it1->second, - apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::LaunchContainer::kLaunchContainerWindow, WindowOpenDisposition::NEW_WINDOW, kDisplayId2, std::vector<base::FilePath>{base::FilePath(kFilePath1), base::FilePath(kFilePath2)}, @@ -411,7 +409,7 @@ EXPECT_TRUE(app_restore_data_it2 != launch_list_it1->second.end()); VerifyAppRestoreData( app_restore_data_it2->second, - apps::mojom::LaunchContainer::kLaunchContainerTab, + apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, kDisplayId1, std::vector<base::FilePath>{base::FilePath(kFilePath2)}, CreateIntent(kIntentActionView, kMimeType, kShareText2), @@ -431,7 +429,7 @@ EXPECT_EQ(kWindowId3, launch_list_it2->second.begin()->first); VerifyAppRestoreData( launch_list_it2->second.begin()->second, - apps::mojom::LaunchContainer::kLaunchContainerNone, + apps::LaunchContainer::kLaunchContainerNone, WindowOpenDisposition::NEW_POPUP, kDisplayId1, std::vector<base::FilePath>{base::FilePath(kFilePath1)}, CreateIntent(kIntentActionView, kMimeType, kShareText1), @@ -495,8 +493,7 @@ const auto app_restore_data_it4 = launch_list_it1->second.find(kWindowId4); EXPECT_TRUE(app_restore_data_it4 != launch_list_it1->second.end()); VerifyAppRestoreData( - app_restore_data_it4->second, - apps::mojom::LaunchContainer::kLaunchContainerTab, + app_restore_data_it4->second, apps::LaunchContainer::kLaunchContainerTab, WindowOpenDisposition::NEW_FOREGROUND_TAB, kDisplayId1, std::vector<base::FilePath>{base::FilePath(kFilePath2)}, CreateIntent(kIntentActionView, kMimeType, kShareText2), kAppTypeBrower2, @@ -657,9 +654,8 @@ EXPECT_FALSE(app_launch_info->event_flag.has_value()); EXPECT_TRUE(app_launch_info->container.has_value()); - EXPECT_EQ( - static_cast<int>(apps::mojom::LaunchContainer::kLaunchContainerWindow), - app_launch_info->container.value()); + EXPECT_EQ(static_cast<int>(apps::LaunchContainer::kLaunchContainerWindow), + app_launch_info->container.value()); EXPECT_TRUE(app_launch_info->disposition.has_value()); EXPECT_EQ(static_cast<int>(WindowOpenDisposition::NEW_WINDOW),
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index c934b639..a610fead 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -252,6 +252,8 @@ "metrics/form_interactions_counter.h", "metrics/payments/manage_cards_prompt_metrics.cc", "metrics/payments/manage_cards_prompt_metrics.h", + "metrics/payments/offers_metrics.cc", + "metrics/payments/offers_metrics.h", "metrics/payments/save_credit_card_prompt_metrics.cc", "metrics/payments/save_credit_card_prompt_metrics.h", "metrics/payments/virtual_card_enrollment_metrics.cc", @@ -832,6 +834,7 @@ "logging/log_router_unittest.cc", "merchant_promo_code_manager_unittest.cc", "metrics/autofill_metrics_unittest.cc", + "metrics/payments/offers_metrics_unittest.cc", "metrics/shadow_prediction_metrics_unittest.cc", "payments/autofill_offer_manager_unittest.cc", "payments/credit_card_access_manager_unittest.cc",
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.cc b/components/autofill/core/browser/metrics/autofill_metrics.cc index 4b4d57a..be726b1 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics.cc
@@ -2215,21 +2215,6 @@ } // static -void AutofillMetrics::LogStoredOfferMetrics( - const std::vector<std::unique_ptr<AutofillOfferData>>& offers) { - base::UmaHistogramCounts1000("Autofill.Offer.StoredOfferCount", - offers.size()); - - for (const std::unique_ptr<AutofillOfferData>& offer : offers) { - base::UmaHistogramCounts1000( - "Autofill.Offer.StoredOfferRelatedMerchantCount", - offer->GetMerchantOrigins().size()); - base::UmaHistogramCounts1000("Autofill.Offer.StoredOfferRelatedCardCount", - offer->GetEligibleInstrumentIds().size()); - } -} - -// static void AutofillMetrics::LogSyncedOfferDataBeingValid(bool valid) { base::UmaHistogramBoolean("Autofill.Offer.SyncedOfferDataBeingValid", valid); }
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.h b/components/autofill/core/browser/metrics/autofill_metrics.h index cfc7be3e..97b4ba35c 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.h +++ b/components/autofill/core/browser/metrics/autofill_metrics.h
@@ -1715,11 +1715,6 @@ size_t server_card_count_with_card_art_image, base::TimeDelta disused_data_threshold); - // Logs metrics about the offer data associated with a profile. This should be - // called each time a chrome profile is launched. - static void LogStoredOfferMetrics( - const std::vector<std::unique_ptr<AutofillOfferData>>& offers); - // Logs whether the synced autofill offer data is valid. static void LogSyncedOfferDataBeingValid(bool invalid);
diff --git a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc index f90b801a..8123ce3 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc
@@ -3955,31 +3955,6 @@ "Autofill.StoredCreditCardCount.Server.Masked.WithNickname", 2, 1); } -TEST_F(AutofillMetricsTest, LogStoredOfferMetrics) { - std::vector<std::unique_ptr<AutofillOfferData>> offers; - AutofillOfferData offer1 = test::GetCardLinkedOfferData1(); - AutofillOfferData offer2 = test::GetCardLinkedOfferData2(); - offer2.SetEligibleInstrumentIdForTesting({222222, 999999, 888888}); - offer2.SetMerchantOriginForTesting( - {GURL("http://www.example2.com"), GURL("https://www.example3.com/")}); - offers.push_back(std::make_unique<AutofillOfferData>(offer1)); - offers.push_back(std::make_unique<AutofillOfferData>(offer2)); - - base::HistogramTester histogram_tester; - auto SamplesOf = [&histogram_tester](base::StringPiece metric) { - return histogram_tester.GetAllSamples(metric); - }; - AutofillMetrics::LogStoredOfferMetrics(offers); - - // Validate the count metrics. - EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferCount"), - BucketsAre(Bucket(2, 1))); - EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferRelatedMerchantCount"), - BucketsAre(Bucket(1, 1), Bucket(2, 1))); - EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferRelatedCardCount"), - BucketsAre(Bucket(1, 1), Bucket(3, 1))); -} - // Test that we correctly log when Profile Autofill is enabled at startup. TEST_F(AutofillMetricsTest, AutofillProfileIsEnabledAtStartup) { base::HistogramTester histogram_tester;
diff --git a/components/autofill/core/browser/metrics/payments/offers_metrics.cc b/components/autofill/core/browser/metrics/payments/offers_metrics.cc new file mode 100644 index 0000000..28e7d2e --- /dev/null +++ b/components/autofill/core/browser/metrics/payments/offers_metrics.cc
@@ -0,0 +1,50 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/browser/metrics/payments/offers_metrics.h" + +#include <unordered_map> + +#include "base/metrics/histogram_functions.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" + +namespace autofill::autofill_metrics { + +void LogStoredOfferMetrics( + const std::vector<std::unique_ptr<AutofillOfferData>>& offers) { + std::unordered_map<AutofillOfferData::OfferType, int> offer_count; + for (const std::unique_ptr<AutofillOfferData>& offer : offers) { + // This function should only be run when the profile is loaded, which means + // the only offers that should be available are the ones that are stored on + // disk. Since free listing coupons are not stored on disk, we should never + // have any loaded here. + DCHECK_NE(offer->GetOfferType(), + AutofillOfferData::OfferType::FREE_LISTING_COUPON_OFFER); + + offer_count[offer->GetOfferType()]++; + + if (offer->GetOfferType() == + AutofillOfferData::OfferType::GPAY_CARD_LINKED_OFFER) { + base::UmaHistogramCounts1000( + "Autofill.Offer.StoredOfferRelatedMerchantCount", + offer->GetMerchantOrigins().size()); + base::UmaHistogramCounts1000("Autofill.Offer.StoredOfferRelatedCardCount", + offer->GetEligibleInstrumentIds().size()); + } + } + + if (offer_count[AutofillOfferData::OfferType::GPAY_PROMO_CODE_OFFER] > 0) { + base::UmaHistogramCounts1000( + "Autofill.Offer.StoredOfferCount.GPayPromoCodeOffer", + offer_count[AutofillOfferData::OfferType::GPAY_PROMO_CODE_OFFER]); + } + + if (offer_count[AutofillOfferData::OfferType::GPAY_CARD_LINKED_OFFER] > 0) { + base::UmaHistogramCounts1000( + "Autofill.Offer.StoredOfferCount.CardLinkedOffer", + offer_count[AutofillOfferData::OfferType::GPAY_CARD_LINKED_OFFER]); + } +} + +} // namespace autofill::autofill_metrics
diff --git a/components/autofill/core/browser/metrics/payments/offers_metrics.h b/components/autofill/core/browser/metrics/payments/offers_metrics.h new file mode 100644 index 0000000..34c7c6f5 --- /dev/null +++ b/components/autofill/core/browser/metrics/payments/offers_metrics.h
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_OFFERS_METRICS_H_ +#define COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_OFFERS_METRICS_H_ + +#include <memory> +#include <vector> + +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" + +namespace autofill::autofill_metrics { + +// Logs the offer data associated with a profile. This should be called each +// time a Chrome profile is launched. +void LogStoredOfferMetrics( + const std::vector<std::unique_ptr<AutofillOfferData>>& offers); + +} // namespace autofill::autofill_metrics + +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_OFFERS_METRICS_H_
diff --git a/components/autofill/core/browser/metrics/payments/offers_metrics_unittest.cc b/components/autofill/core/browser/metrics/payments/offers_metrics_unittest.cc new file mode 100644 index 0000000..d30bdc9 --- /dev/null +++ b/components/autofill/core/browser/metrics/payments/offers_metrics_unittest.cc
@@ -0,0 +1,56 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <vector> + +#include "base/test/metrics/histogram_tester.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" +#include "components/autofill/core/browser/metrics/autofill_metrics_test_base.h" +#include "components/autofill/core/browser/metrics/payments/offers_metrics.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::base::Bucket; +using ::base::BucketsAre; + +namespace autofill::autofill_metrics { + +class OffersMetricsTest : public metrics::AutofillMetricsBaseTest { + public: + OffersMetricsTest() = default; + ~OffersMetricsTest() override = default; +}; + +TEST_F(OffersMetricsTest, LogStoredOfferMetrics) { + std::vector<std::unique_ptr<AutofillOfferData>> offers; + AutofillOfferData offer1 = test::GetCardLinkedOfferData1(); + AutofillOfferData offer2 = test::GetCardLinkedOfferData2(); + AutofillOfferData offer3 = test::GetPromoCodeOfferData(); + offer2.SetEligibleInstrumentIdForTesting({222222, 999999, 888888}); + offer2.SetMerchantOriginForTesting( + {GURL("http://www.example2.com"), GURL("https://www.example3.com/")}); + offers.push_back(std::make_unique<AutofillOfferData>(offer1)); + offers.push_back(std::make_unique<AutofillOfferData>(offer2)); + offers.push_back(std::make_unique<AutofillOfferData>(offer3)); + + base::HistogramTester histogram_tester; + + autofill_metrics::LogStoredOfferMetrics(offers); + + auto SamplesOf = [&histogram_tester](base::StringPiece metric) { + return histogram_tester.GetAllSamples(metric); + }; + + // Validate the count metrics. + EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferCount.CardLinkedOffer"), + BucketsAre(Bucket(2, 1))); + EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferCount.GPayPromoCodeOffer"), + BucketsAre(Bucket(1, 1))); + EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferRelatedMerchantCount"), + BucketsAre(Bucket(1, 1), Bucket(2, 1))); + EXPECT_THAT(SamplesOf("Autofill.Offer.StoredOfferRelatedCardCount"), + BucketsAre(Bucket(1, 1), Bucket(3, 1))); +} + +} // namespace autofill::autofill_metrics
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 37f3b7a..594176e 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -46,6 +46,7 @@ #include "components/autofill/core/browser/geo/country_names.h" #include "components/autofill/core/browser/geo/phone_number_i18n.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" +#include "components/autofill/core/browser/metrics/payments/offers_metrics.h" #include "components/autofill/core/browser/personal_data_manager_observer.h" #include "components/autofill/core/browser/ui/autofill_image_fetcher.h" #include "components/autofill/core/browser/ui/label_formatter.h" @@ -1885,7 +1886,7 @@ void PersonalDataManager::LogStoredOfferMetrics() const { if (!has_logged_stored_offer_metrics_) { - AutofillMetrics::LogStoredOfferMetrics(autofill_offer_data_); + autofill_metrics::LogStoredOfferMetrics(autofill_offer_data_); // Only log this info once per chrome user profile load. has_logged_stored_offer_metrics_ = true; }
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 5dbd57b3..33790d6 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -267,7 +267,7 @@ // TODO(crbug.com/1098943): Remove once launched. const base::Feature kAutofillEnableSupportForMoreStructureInAddresses{ "AutofillEnableSupportForMoreStructureInAddresses", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Controls if Autofill supports merging subset names. // TODO(crbug.com/1098943): Remove once launched.
diff --git a/components/autofill_assistant/android/public/java/src/org/chromium/components/autofill_assistant/TriggerContext.java b/components/autofill_assistant/android/public/java/src/org/chromium/components/autofill_assistant/TriggerContext.java index d9b6b83..67a026eb 100644 --- a/components/autofill_assistant/android/public/java/src/org/chromium/components/autofill_assistant/TriggerContext.java +++ b/components/autofill_assistant/android/public/java/src/org/chromium/components/autofill_assistant/TriggerContext.java
@@ -104,8 +104,8 @@ /** * Special bool parameter that MUST be present in all intents. It allows the caller to either * request immediate start of autobot (if set to true), or a delayed start using trigger scripts - * (if set to false). If this is set to false, one of the trigger script parameters must be set - * as well (@code{PARAMETER_REQUEST_TRIGGER_SCRIPT} or @code{PARAMETER_TRIGGER_SCRIPTS_BASE64}). + * (if set to false). If this is set to false, the trigger script parameter must be set + * (@code{PARAMETER_REQUEST_TRIGGER_SCRIPT}. */ public static final String PARAMETER_START_IMMEDIATELY = "START_IMMEDIATELY"; @@ -122,13 +122,6 @@ static final String PARAMETER_REQUEST_TRIGGER_SCRIPT = "REQUEST_TRIGGER_SCRIPT"; /** - * Special parameter to allow injecting a base64-encoded GetTriggerScriptsResponseProto. When - * specified, the client will directly use the specified trigger scripts instead of fetching - * them from a remote backend. Takes precedence over PARAMETER_REQUEST_TRIGGER_SCRIPT. - */ - static final String PARAMETER_TRIGGER_SCRIPTS_BASE64 = "TRIGGER_SCRIPTS_BASE64"; - - /** * Identifier used by parameters/or special intent that indicates experiments passed from * the caller. */ @@ -267,14 +260,9 @@ return getBooleanParameter(PARAMETER_REQUEST_TRIGGER_SCRIPT); } - /** Whether the caller specified a base64-encoded trigger scripts response or not. */ - public boolean containsBase64TriggerScripts() { - return !TextUtils.isEmpty(getStringParameter(PARAMETER_TRIGGER_SCRIPTS_BASE64)); - } - /** Whether the caller requested a trigger script to start in any of the supported ways. */ public boolean containsTriggerScript() { - return requestsTriggerScript() || containsBase64TriggerScripts(); + return requestsTriggerScript(); } public void setOnboardingShown(boolean onboardingShown) {
diff --git a/components/autofill_assistant/browser/BUILD.gn b/components/autofill_assistant/browser/BUILD.gn index 068f1cb..88b373d 100644 --- a/components/autofill_assistant/browser/BUILD.gn +++ b/components/autofill_assistant/browser/BUILD.gn
@@ -226,8 +226,6 @@ "protocol_utils.h", "radio_button_controller.cc", "radio_button_controller.h", - "rectf.cc", - "rectf.h", "retry_timer.cc", "retry_timer.h", "save_password_leak_detection_delegate.cc",
diff --git a/components/autofill_assistant/browser/android/ui_controller_android.cc b/components/autofill_assistant/browser/android/ui_controller_android.cc index c328765..6bf279f 100644 --- a/components/autofill_assistant/browser/android/ui_controller_android.cc +++ b/components/autofill_assistant/browser/android/ui_controller_android.cc
@@ -41,7 +41,7 @@ #include "components/autofill_assistant/browser/event_handler.h" #include "components/autofill_assistant/browser/features.h" #include "components/autofill_assistant/browser/metrics.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/user_data.h" #include "components/autofill_assistant/browser/user_data_util.h" #include "components/autofill_assistant/browser/user_model.h"
diff --git a/components/autofill_assistant/browser/element_area.h b/components/autofill_assistant/browser/element_area.h index e925c44..72066365 100644 --- a/components/autofill_assistant/browser/element_area.h +++ b/components/autofill_assistant/browser/element_area.h
@@ -12,7 +12,7 @@ #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "components/autofill_assistant/browser/client_settings.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/selector.h" #include "components/autofill_assistant/browser/web/web_controller.h"
diff --git a/components/autofill_assistant/browser/execution_delegate.h b/components/autofill_assistant/browser/execution_delegate.h index 20a6a6c..bd41d8f 100644 --- a/components/autofill_assistant/browser/execution_delegate.h +++ b/components/autofill_assistant/browser/execution_delegate.h
@@ -7,8 +7,8 @@ #include "components/autofill_assistant/browser/client_settings.h" #include "components/autofill_assistant/browser/event_handler.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/public/runtime_manager_impl.h" -#include "components/autofill_assistant/browser/rectf.h" #include "components/autofill_assistant/browser/state.h" #include "components/autofill_assistant/browser/user_data.h" #include "components/autofill_assistant/browser/viewport_mode.h"
diff --git a/components/autofill_assistant/browser/headless/client_headless.cc b/components/autofill_assistant/browser/headless/client_headless.cc index b4e8e59..94f96d23 100644 --- a/components/autofill_assistant/browser/headless/client_headless.cc +++ b/components/autofill_assistant/browser/headless/client_headless.cc
@@ -72,6 +72,7 @@ /* annotate_dom_model_service= */ common_dependencies_->GetOrCreateAnnotateDomModelService( GetWebContents()->GetBrowserContext())); + controller_->AddObserver(headless_ui_controller_.get()); controller_->Start(url, std::move(trigger_context)); }
diff --git a/components/autofill_assistant/browser/headless/headless_ui_controller.cc b/components/autofill_assistant/browser/headless/headless_ui_controller.cc index 5def234b..bff77466 100644 --- a/components/autofill_assistant/browser/headless/headless_ui_controller.cc +++ b/components/autofill_assistant/browser/headless/headless_ui_controller.cc
@@ -167,4 +167,14 @@ return nullptr; } +void HeadlessUiController::OnTouchableAreaChanged( + const RectF& visual_viewport, + const std::vector<RectF>& touchable_areas, + const std::vector<RectF>& restricted_areas) { + if (action_extension_delegate_) { + action_extension_delegate_->OnTouchableAreaChanged( + visual_viewport, touchable_areas, restricted_areas); + } +} + } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/headless/headless_ui_controller.h b/components/autofill_assistant/browser/headless/headless_ui_controller.h index eae4973e..0ce8364 100644 --- a/components/autofill_assistant/browser/headless/headless_ui_controller.h +++ b/components/autofill_assistant/browser/headless/headless_ui_controller.h
@@ -11,13 +11,14 @@ #include "base/callback_helpers.h" #include "components/autofill_assistant/browser/autofill_assistant_impl.h" -#include "components/autofill_assistant/browser/controller_observer.h" +#include "components/autofill_assistant/browser/empty_controller_observer.h" #include "components/autofill_assistant/browser/execution_delegate.h" #include "components/autofill_assistant/browser/script_executor_ui_delegate.h" namespace autofill_assistant { -class HeadlessUiController : public ScriptExecutorUiDelegate { +class HeadlessUiController : public ScriptExecutorUiDelegate, + public EmptyControllerObserver { public: // The |action_extension_delegate| parameter can be null but if an extension // action is requested it will cause the script to fail. @@ -87,6 +88,12 @@ void OnInterruptStarted() override; void OnInterruptFinished() override; + // Overrides ControllerObserver. + void OnTouchableAreaChanged( + const RectF& visual_viewport, + const std::vector<RectF>& touchable_areas, + const std::vector<RectF>& restricted_areas) override; + private: const raw_ptr<ExternalActionDelegate> action_extension_delegate_; };
diff --git a/components/autofill_assistant/browser/metrics.cc b/components/autofill_assistant/browser/metrics.cc index 288e22a..2c3ce701 100644 --- a/components/autofill_assistant/browser/metrics.cc +++ b/components/autofill_assistant/browser/metrics.cc
@@ -138,7 +138,6 @@ return Metrics::AutofillAssistantStarted::FAILED_NO_INITIAL_URL; case StartupMode::START_REGULAR: return Metrics::AutofillAssistantStarted::OK_IMMEDIATE_START; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: case StartupMode::START_RPC_TRIGGER_SCRIPT: return Metrics::AutofillAssistantStarted::OK_DELAYED_START; } @@ -334,7 +333,6 @@ case StartupMode::MANDATORY_PARAMETERS_MISSING: event = TriggerScriptStarted::MANDATORY_PARAMETER_MISSING; break; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: case StartupMode::START_RPC_TRIGGER_SCRIPT: event = is_first_time_user ? TriggerScriptStarted::FIRST_TIME_USER : TriggerScriptStarted::RETURNING_USER; @@ -735,7 +733,7 @@ out << "DISABLED_PROACTIVE_HELP_SETTING"; break; case Metrics::TriggerScriptFinishedState::BASE64_DECODING_ERROR: - out << "BASE64_DECODING_ERROR"; + out << "BASE64 DECODING ERROR"; break; case Metrics::TriggerScriptFinishedState::BOTTOMSHEET_ONBOARDING_REJECTED: out << "BOTTOMSHEET_ONBOARDING_REJECTED";
diff --git a/components/autofill_assistant/browser/metrics.h b/components/autofill_assistant/browser/metrics.h index cbfb6b5..a83a516 100644 --- a/components/autofill_assistant/browser/metrics.h +++ b/components/autofill_assistant/browser/metrics.h
@@ -343,9 +343,6 @@ // Since Chrome M-88. The proactive help switch was enabled at start, but // then manually disabled in the Chrome settings. DISABLED_PROACTIVE_HELP_SETTING = 23, - // Since Chrome M-88. The client failed to base64-decode the trigger script - // specified in the script parameters. - BASE64_DECODING_ERROR = 24, // The user rejected the bottom sheet onboarding BOTTOMSHEET_ONBOARDING_REJECTED = 25, // Transitioning from CCT to regular tab is currently not supported. @@ -383,6 +380,11 @@ // Since Chrome M-88. The bottom sheet was swipe-dismissed by the user. PROMPT_SWIPE_DISMISSED = 16, + // Note: DEPRECATED since M-105 + // Since Chrome M-88. The client failed to base64-decode the trigger script + // specified in the script parameters. + BASE64_DECODING_ERROR = 24, + kMaxValue = CANCELED };
diff --git a/components/autofill_assistant/browser/public/BUILD.gn b/components/autofill_assistant/browser/public/BUILD.gn index 5dd07d4b..98381d3 100644 --- a/components/autofill_assistant/browser/public/BUILD.gn +++ b/components/autofill_assistant/browser/public/BUILD.gn
@@ -15,6 +15,8 @@ "autofill_assistant_factory.h", "external_action_delegate.h", "headless_script_controller.h", + "rectf.cc", + "rectf.h", "runtime_manager.cc", "runtime_manager.h", "runtime_manager_impl.cc",
diff --git a/components/autofill_assistant/browser/public/external_action_delegate.h b/components/autofill_assistant/browser/public/external_action_delegate.h index 427ef0f..ca09c740 100644 --- a/components/autofill_assistant/browser/public/external_action_delegate.h +++ b/components/autofill_assistant/browser/public/external_action_delegate.h
@@ -7,6 +7,7 @@ #include "base/callback.h" #include "components/autofill_assistant/browser/public/external_action.pb.h" +#include "components/autofill_assistant/browser/public/rectf.h" namespace autofill_assistant { @@ -31,11 +32,30 @@ end_action_callback) = 0; // Called before starting the execution of an interrupt. - virtual void OnInterruptStarted() = 0; + virtual void OnInterruptStarted(){}; // Called after finishing to execute an interrupt, before resuming the // execution of the main script. - virtual void OnInterruptFinished() = 0; + virtual void OnInterruptFinished(){}; + + // Called to notify a change in the configuration of the touchable area. + // + // |visual_viewport| contains the position and size of the visual viewport in + // the layout viewport. It might be empty if not known or the touchable area + // is empty. + // + // |touchable_areas| contains one element per configured rectangle that should + // be visible/touchable, though these can correspond to empty rectangles. + // + // |restricted_areas| contains one element per configured rectangle that + // shouldn't be visible nor touchable. Those rectangles have precedence over + // |touchable_areas|. + // + // All rectangles are expressed in absolute CSS coordinates. + virtual void OnTouchableAreaChanged( + const RectF& visual_viewport, + const std::vector<RectF>& touchable_areas, + const std::vector<RectF>& restricted_areas){}; }; } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/rectf.cc b/components/autofill_assistant/browser/public/rectf.cc similarity index 94% rename from components/autofill_assistant/browser/rectf.cc rename to components/autofill_assistant/browser/public/rectf.cc index 840ca2d3..099004e 100644 --- a/components/autofill_assistant/browser/rectf.cc +++ b/components/autofill_assistant/browser/public/rectf.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 "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" namespace autofill_assistant {
diff --git a/components/autofill_assistant/browser/rectf.h b/components/autofill_assistant/browser/public/rectf.h similarity index 80% rename from components/autofill_assistant/browser/rectf.h rename to components/autofill_assistant/browser/public/rectf.h index 14e0fda..6c4d619e 100644 --- a/components/autofill_assistant/browser/rectf.h +++ b/components/autofill_assistant/browser/public/rectf.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 COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_RECTF_H_ -#define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_RECTF_H_ +#ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_PUBLIC_RECTF_H_ +#define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_PUBLIC_RECTF_H_ #include <ostream> @@ -33,4 +33,4 @@ } // namespace autofill_assistant -#endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_RECTF_H_ +#endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_PUBLIC_RECTF_H_
diff --git a/components/autofill_assistant/browser/script_parameters.cc b/components/autofill_assistant/browser/script_parameters.cc index 2493dde..4f883c43d 100644 --- a/components/autofill_assistant/browser/script_parameters.cc +++ b/components/autofill_assistant/browser/script_parameters.cc
@@ -54,13 +54,6 @@ // TODO(b/151401974): Eliminate duplicate parameter definitions. const char kPasswordChangeUsernameParameterName[] = "PASSWORD_CHANGE_USERNAME"; -// Parameter that contains a base64-encoded GetTriggerScriptsResponseProto -// message. Instructs the client to decode and run this trigger script prior to -// starting the regular flow. Takes precedence over REQUEST_TRIGGER_SCRIPT if -// both are specified. -const char kBase64TriggerScriptsResponseProtoParameterName[] = - "TRIGGER_SCRIPTS_BASE64"; - // Special parameter for instructing the client to request and run a trigger // script from a remote RPC prior to starting the regular flow. const char kRequestTriggerScriptParameterName[] = "REQUEST_TRIGGER_SCRIPT"; @@ -222,11 +215,6 @@ return GetParameter(kPasswordChangeUsernameParameterName); } -absl::optional<std::string> -ScriptParameters::GetBase64TriggerScriptsResponseProto() const { - return GetParameter(kBase64TriggerScriptsResponseProtoParameterName); -} - absl::optional<bool> ScriptParameters::GetRequestsTriggerScript() const { return GetTypedParameter<bool>(parameters_, kRequestTriggerScriptParameterName);
diff --git a/components/autofill_assistant/browser/script_parameters.h b/components/autofill_assistant/browser/script_parameters.h index 189d167d..a6112be 100644 --- a/components/autofill_assistant/browser/script_parameters.h +++ b/components/autofill_assistant/browser/script_parameters.h
@@ -52,7 +52,6 @@ // Getters for specific parameters. absl::optional<std::string> GetOverlayColors() const; absl::optional<std::string> GetPasswordChangeUsername() const; - absl::optional<std::string> GetBase64TriggerScriptsResponseProto() const; absl::optional<bool> GetRequestsTriggerScript() const; absl::optional<bool> GetStartImmediately() const; absl::optional<bool> GetEnabled() const;
diff --git a/components/autofill_assistant/browser/script_parameters_unittest.cc b/components/autofill_assistant/browser/script_parameters_unittest.cc index a335cd6..36e77df 100644 --- a/components/autofill_assistant/browser/script_parameters_unittest.cc +++ b/components/autofill_assistant/browser/script_parameters_unittest.cc
@@ -101,7 +101,6 @@ {"TRIGGER_SCRIPT_EXPERIMENT", "true"}, {"START_IMMEDIATELY", "false"}, {"REQUEST_TRIGGER_SCRIPT", "true"}, - {"TRIGGER_SCRIPTS_BASE64", "abc123"}, {"PASSWORD_CHANGE_USERNAME", "fake_username"}, {"OVERLAY_COLORS", "#123456"}, {"ENABLE_TTS", "true"}, @@ -126,7 +125,6 @@ EXPECT_THAT(parameters.GetTriggerScriptExperiment(), Eq(true)); EXPECT_THAT(parameters.GetStartImmediately(), Eq(false)); EXPECT_THAT(parameters.GetRequestsTriggerScript(), Eq(true)); - EXPECT_THAT(parameters.GetBase64TriggerScriptsResponseProto(), Eq("abc123")); EXPECT_THAT(parameters.GetPasswordChangeUsername(), Eq("fake_username")); EXPECT_THAT(parameters.GetOverlayColors(), Eq("#123456")); EXPECT_THAT(parameters.GetEnableTts(), Eq(true));
diff --git a/components/autofill_assistant/browser/starter.cc b/components/autofill_assistant/browser/starter.cc index 29adcef..10bc943 100644 --- a/components/autofill_assistant/browser/starter.cc +++ b/components/autofill_assistant/browser/starter.cc
@@ -65,19 +65,6 @@ const char kEnabledGroupName[] = "Enabled"; const char kExperimentsSyntheticTrial[] = "AutofillAssistantExperimentsTrial"; -// Creates a service request sender that serves the pre-specified response. -// Creation may fail (return null) if the parameter fails to decode. -std::unique_ptr<ServiceRequestSender> CreateBase64TriggerScriptRequestSender( - const std::string& base64_trigger_script) { - std::string response; - if (!base::Base64UrlDecode(base64_trigger_script, - base::Base64UrlDecodePolicy::IGNORE_PADDING, - &response)) { - return nullptr; - } - return std::make_unique<ServiceRequestSenderLocalImpl>(response); -} - // Creates a service request sender that communicates with a remote endpoint. std::unique_ptr<ServiceRequestSender> CreateRpcTriggerScriptRequestSender( content::BrowserContext* browser_context, @@ -90,12 +77,11 @@ ApiKeyFetcher().GetAPIKey(delegate->GetChannel())); } -// Returns whether |trigger_context| contains either the REQUEST_TRIGGER_SCRIPT -// or the TRIGGER_SCRIPTS_BASE64 script parameter. +// Returns whether |trigger_context| contains the REQUEST_TRIGGER_SCRIPT bool IsTriggerScriptContext(const TriggerContext& trigger_context) { - const auto& script_parameters = trigger_context.GetScriptParameters(); - return script_parameters.GetRequestsTriggerScript() || - script_parameters.GetBase64TriggerScriptsResponseProto(); + return trigger_context.GetScriptParameters() + .GetRequestsTriggerScript() + .value_or(false); } // The heuristic is shared across all instances and initialized on first use. As @@ -409,7 +395,6 @@ switch (startup_mode) { case StartupMode::START_REGULAR: return; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: case StartupMode::START_RPC_TRIGGER_SCRIPT: if (!switched_from_cct_to_tab) { return; @@ -538,7 +523,6 @@ case StartupMode::NO_INITIAL_URL: OnStartDone(/* start_script = */ false); return; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: case StartupMode::START_RPC_TRIGGER_SCRIPT: case StartupMode::START_REGULAR: MaybeInstallFeatureModule(startup_mode); @@ -601,7 +585,6 @@ case StartupMode::START_REGULAR: MaybeShowOnboarding(); return; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: case StartupMode::START_RPC_TRIGGER_SCRIPT: StartTriggerScript(); return; @@ -624,20 +607,7 @@ std::unique_ptr<ServiceRequestSender> service_request_sender = platform_delegate_->GetTriggerScriptRequestSenderToInject(); if (!service_request_sender) { - if (script_parameters.GetBase64TriggerScriptsResponseProto().has_value()) { - service_request_sender = CreateBase64TriggerScriptRequestSender( - script_parameters.GetBase64TriggerScriptsResponseProto().value()); - if (!service_request_sender) { - Metrics::RecordTriggerScriptFinished( - ukm_recorder_, current_ukm_source_id_, - TriggerScriptProto::UNSPECIFIED_TRIGGER_UI_TYPE, - Metrics::TriggerScriptFinishedState::BASE64_DECODING_ERROR); - OnTriggerScriptFinished( - Metrics::TriggerScriptFinishedState::BASE64_DECODING_ERROR, - std::move(pending_trigger_context_), absl::nullopt); - return; - } - } else if (script_parameters.GetRequestsTriggerScript().value_or(false)) { + if (script_parameters.GetRequestsTriggerScript().value_or(false)) { service_request_sender = CreateRpcTriggerScriptRequestSender( web_contents()->GetBrowserContext(), platform_delegate_); } else {
diff --git a/components/autofill_assistant/browser/starter_unittest.cc b/components/autofill_assistant/browser/starter_unittest.cc index b6f3357..1db2da4e 100644 --- a/components/autofill_assistant/browser/starter_unittest.cc +++ b/components/autofill_assistant/browser/starter_unittest.cc
@@ -147,20 +147,6 @@ fake_platform_delegate_.onboarding_accepted_ = true; } - // Returns a base64-encoded trigger script response, as created by - // |CreateTriggerScriptResponseForTest|. - std::string CreateBase64TriggerScriptResponseForTest( - TriggerScriptProto::TriggerUIType trigger_ui_type = - TriggerScriptProto::UNSPECIFIED_TRIGGER_UI_TYPE) { - std::string serialized_get_trigger_scripts_response = - CreateTriggerScriptResponseForTest(trigger_ui_type); - std::string base64_get_trigger_scripts_response; - base::Base64UrlEncode(serialized_get_trigger_scripts_response, - base::Base64UrlEncodePolicy::INCLUDE_PADDING, - &base64_get_trigger_scripts_response); - return base64_get_trigger_scripts_response; - } - // Returns a serialized GetTriggerScriptsResponseProto containing a single // trigger script without any trigger conditions. As such, it will be shown // immediately upon startup. @@ -209,6 +195,33 @@ std::move(mock_trigger_script_service_request_sender); } + // Configures mock_trigger_script_service_request_sender_ with a test response + // and ensures that it is called once. + void SetupRpcTriggerScriptResponseOnce( + const std::string& url, + const std::string& trigger_script_response) { + EXPECT_CALL( + *mock_trigger_script_service_request_sender_, + OnSendRequest(GURL("https://automate-pa.googleapis.com/v1/triggers"), _, + _, RpcType::GET_TRIGGER_SCRIPTS)) + .WillOnce(WithArgs<1, 2>( + [&, url, trigger_script_response]( + const std::string& request_body, + ServiceRequestSender::ResponseCallback& callback) { + GetTriggerScriptsRequestProto request; + ASSERT_TRUE(request.ParseFromString(request_body)); + EXPECT_THAT(request.url(), Eq(GURL(url))); + EXPECT_FALSE(request.client_context().is_in_chrome_triggered()); + std::move(callback).Run(net::HTTP_OK, trigger_script_response, + ServiceRequestSender::ResponseInfo{}); + })); + } + + void SetupRpcTriggerScriptResponseOnce(const std::string& url) { + SetupRpcTriggerScriptResponseOnce(url, + CreateTriggerScriptResponseForTest()); + } + // Each trigger script UI delegate is only good for one trigger script and // must be prepared anew if a test needs to show more than one trigger script. void PrepareTriggerScriptUiDelegate() { @@ -285,7 +298,7 @@ base::flat_map<std::string, std::string> params = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", "abc"}}; + {"REQUEST_TRIGGER_SCRIPT", "true"}}; TriggerContext::Options options; EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); @@ -314,7 +327,7 @@ TEST_F(StarterTest, FailWithoutMandatoryScriptParameter) { // ENABLED is missing from |params|. base::flat_map<std::string, std::string> params = { - {"START_IMMEDIATELY", "false"}, {"TRIGGER_SCRIPTS_BASE64", "abc"}}; + {"START_IMMEDIATELY", "false"}, {"REQUEST_TRIGGER_SCRIPT", "true"}}; TriggerContext::Options options; options.initial_url = kExampleDeeplink; EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); @@ -347,7 +360,7 @@ base::flat_map<std::string, std::string> params = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", "abc"}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"INTENT", "SHOPPING"}, {"EXPERIMENT_IDS", "fake_experiment"}, {"CALLER", "7"}, @@ -496,22 +509,19 @@ std::string serialized_get_trigger_scripts_response; get_trigger_scripts_response.SerializeToString( &serialized_get_trigger_scripts_response); - std::string base64_get_trigger_scripts_response; - base::Base64UrlEncode(serialized_get_trigger_scripts_response, - base::Base64UrlEncodePolicy::INCLUDE_PADDING, - &base64_get_trigger_scripts_response); SetupPlatformDelegateForReturningUser(); - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAutofillAssistantForceFirstTimeUser, "true"); base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", base64_get_trigger_scripts_response}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", "https://www.example.com"}}; + SetupRpcTriggerScriptResponseOnce(kExampleDeeplink, + serialized_get_trigger_scripts_response); EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript(first_time_user_script->user_interface())); starter_->Start(std::make_unique<TriggerContext>( @@ -726,138 +736,19 @@ Metrics::AutofillAssistantExperiment::NO_EXPERIMENT}}}))); } -TEST_F(StarterTest, Base64TriggerScriptFailsForInvalidBase64) { - SetupPlatformDelegateForReturningUser(); - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; - - base::flat_map<std::string, std::string> script_parameters = { - {"ENABLED", "true"}, - {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", "#invalid_hashtag"}, - {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; - EXPECT_CALL(*mock_trigger_script_ui_delegate_, Attach).Times(0); - EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); - - starter_->Start(std::make_unique<TriggerContext>( - std::make_unique<ScriptParameters>(script_parameters), - TriggerContext::Options())); - - EXPECT_THAT(GetUkmTriggerScriptStarted(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptStarted::RETURNING_USER}}}))); - EXPECT_THAT(GetUkmTriggerScriptFinished(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptFinishedState::BASE64_DECODING_ERROR, - TriggerScriptProto::UNSPECIFIED_TRIGGER_UI_TYPE}}}))); - EXPECT_THAT(GetUkmTriggerScriptOnboarding(ukm_recorder_), IsEmpty()); - histogram_tester_.ExpectUniqueSample( - "Android.AutofillAssistant.FeatureModuleInstallation", - Metrics::FeatureModuleInstallation::DFM_ALREADY_INSTALLED, 1u); - EXPECT_THAT(GetUkmRegularScriptOnboarding(ukm_recorder_), IsEmpty()); -} - -TEST_F(StarterTest, Base64TriggerScriptFailsIfProactiveHelpIsDisabled) { - SetupPlatformDelegateForReturningUser(); - fake_platform_delegate_.proactive_help_enabled_ = false; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; - - base::flat_map<std::string, std::string> script_parameters = { - {"ENABLED", "true"}, - {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, - {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; - EXPECT_CALL(*mock_trigger_script_ui_delegate_, Attach).Times(0); - EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); - - starter_->Start(std::make_unique<TriggerContext>( - std::make_unique<ScriptParameters>(script_parameters), - TriggerContext::Options())); - - EXPECT_THAT( - GetUkmTriggerScriptStarted(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptStarted::PROACTIVE_TRIGGERING_DISABLED}}}))); - EXPECT_THAT(GetUkmTriggerScriptFinished(ukm_recorder_), IsEmpty()); - EXPECT_THAT(GetUkmTriggerScriptOnboarding(ukm_recorder_), IsEmpty()); - histogram_tester_.ExpectTotalCount( - "Android.AutofillAssistant.FeatureModuleInstallation", 0u); - EXPECT_THAT(GetUkmRegularScriptOnboarding(ukm_recorder_), IsEmpty()); -} - -TEST_F(StarterTest, Base64TriggerScriptSucceeds) { - SetupPlatformDelegateForFirstTimeUser(); - fake_platform_delegate_.feature_module_installed_ = true; - // Base64 trigger scripts should not require MSBB to be enabled. - fake_platform_delegate_.msbb_enabled_ = false; - // No need to inject a mock request sender for base64 trigger scripts, we can - // use the real one. - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; - - base::flat_map<std::string, std::string> script_parameters = { - {"ENABLED", "true"}, - {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", - CreateBase64TriggerScriptResponseForTest( - TriggerScriptProto::SHOPPING_CART_RETURNING_USER)}, - {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; - TriggerContext::Options options; - options.initial_url = "https://redirect.com/to/www/example/com"; - options.onboarding_shown = false; - EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript) - .WillOnce([&]() { - ASSERT_TRUE(trigger_script_coordinator_ != nullptr); - trigger_script_coordinator_->PerformTriggerScriptAction( - TriggerScriptProto::ACCEPT); - }); - EXPECT_CALL(mock_start_regular_script_callback_, - Run(GURL(kExampleDeeplink), - Pointee(Property(&TriggerContext::GetOnboardingShown, true)), - testing::Ne(absl::nullopt))); - - starter_->Start(std::make_unique<TriggerContext>( - std::make_unique<ScriptParameters>(script_parameters), options)); - - EXPECT_THAT(fake_platform_delegate_.num_show_onboarding_called_, Eq(1)); - EXPECT_THAT(GetUkmTriggerScriptStarted(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptStarted::FIRST_TIME_USER}}}))); - EXPECT_THAT(GetUkmTriggerScriptFinished(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptFinishedState::PROMPT_SUCCEEDED, - TriggerScriptProto::SHOPPING_CART_RETURNING_USER}}}))); - EXPECT_THAT( - GetUkmTriggerScriptOnboarding(ukm_recorder_), - ElementsAreArray(ToHumanReadableMetrics( - {{navigation_ids_[0], - {Metrics::TriggerScriptOnboarding::ONBOARDING_SEEN_AND_ACCEPTED, - TriggerScriptProto::SHOPPING_CART_RETURNING_USER}}}))); - histogram_tester_.ExpectUniqueSample( - "Android.AutofillAssistant.FeatureModuleInstallation", - Metrics::FeatureModuleInstallation::DFM_ALREADY_INSTALLED, 1u); - EXPECT_THAT(GetUkmRegularScriptOnboarding(ukm_recorder_), IsEmpty()); -} - TEST_F(StarterTest, CancelPendingTriggerScriptWhenTransitioningFromCctToTab) { SetupPlatformDelegateForReturningUser(); fake_platform_delegate_.is_custom_tab_ = true; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); + SetupRpcTriggerScriptResponseOnce(kExampleDeeplink); + EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript); starter_->Start(std::make_unique<TriggerContext>( std::make_unique<ScriptParameters>(script_parameters), @@ -881,15 +772,15 @@ TEST_F(StarterTest, CancelPendingTriggerScriptWhenHandlingNewStartupRequest) { SetupPlatformDelegateForReturningUser(); - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; + SetupRpcTriggerScriptResponseOnce(kExampleDeeplink); + EXPECT_CALL(mock_start_regular_script_callback_, Run).Times(0); EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript); starter_->Start(std::make_unique<TriggerContext>( @@ -898,6 +789,7 @@ EXPECT_CALL(*mock_trigger_script_ui_delegate_, HideTriggerScript); PrepareTriggerScriptUiDelegate(); + PrepareTriggerScriptRequestSender(); starter_->Start(std::make_unique<TriggerContext>( std::make_unique<ScriptParameters>(script_parameters), TriggerContext::Options{})); @@ -940,18 +832,18 @@ TEST_F(StarterTest, TriggerScriptStartupFailsIfNavigationDuringOnboarding) { SetupPlatformDelegateForFirstTimeUser(); fake_platform_delegate_.feature_module_installed_ = true; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; // Empty callback to keep the onboarding open indefinitely. fake_platform_delegate_.on_show_onboarding_callback_ = base::DoNothing(); base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", - CreateBase64TriggerScriptResponseForTest( - TriggerScriptProto::SHOPPING_CART_FIRST_TIME_USER)}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; + + SetupRpcTriggerScriptResponseOnce( + kExampleDeeplink, CreateTriggerScriptResponseForTest( + TriggerScriptProto::SHOPPING_CART_FIRST_TIME_USER)); EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript) .WillOnce([&]() { ASSERT_TRUE(trigger_script_coordinator_ != nullptr); @@ -1026,16 +918,14 @@ TEST_F(StarterTest, TriggerScriptAllowsHttpToHttpsRedirect) { SetupPlatformDelegateForFirstTimeUser(); fake_platform_delegate_.feature_module_installed_ = true; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; - - SimulateNavigateToUrl(GURL("http://www.example.com")); base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", "http://www.example.com"}}; + SetupRpcTriggerScriptResponseOnce("http://www.example.com"); + SimulateNavigateToUrl(GURL("http://www.example.com")); EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript).Times(1); EXPECT_CALL(*mock_trigger_script_ui_delegate_, HideTriggerScript).Times(0); starter_->Start(std::make_unique<TriggerContext>( @@ -1281,21 +1171,20 @@ TEST_F(StarterTest, StartTriggerScriptBeforeRedirectRecordsUkmForTargetUrl) { SetupPlatformDelegateForReturningUser(); fake_platform_delegate_.feature_module_installed_ = true; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; TriggerContext::Options options; options.initial_url = "https://redirect.com/to/www/example/com"; + SetupRpcTriggerScriptResponseOnce(kExampleDeeplink); + // Simulate a real flow that starts on some trigger site, which then redirects // to the deeplink. SimulateNavigateToUrl(GURL("https://some-trigger-site.com")); - // Start the flow before the trigger site has had a chance to navigate to the // target domain. This commonly happens due to android intent handling // happening before navigations are started. @@ -1328,7 +1217,7 @@ base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; TriggerContext::Options options; options.initial_url = "https://redirect.com/to/www/example/com"; @@ -1370,13 +1259,11 @@ TEST_F(StarterTest, StartTriggerScriptDuringRedirectRecordsUkmForTargetUrl) { SetupPlatformDelegateForReturningUser(); fake_platform_delegate_.feature_module_installed_ = true; - fake_platform_delegate_.trigger_script_request_sender_for_test_ = nullptr; - mock_trigger_script_service_request_sender_ = nullptr; base::flat_map<std::string, std::string> script_parameters = { {"ENABLED", "true"}, {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", CreateBase64TriggerScriptResponseForTest()}, + {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", kExampleDeeplink}}; TriggerContext::Options options; options.initial_url = "https://redirect.com/to/www/example/com"; @@ -1385,6 +1272,7 @@ // to the deeplink. SimulateNavigateToUrl(GURL("https://some-trigger-site.com")); + SetupRpcTriggerScriptResponseOnce(kExampleDeeplink); // Begin a navigation, then start the flow before the navigation is committed. // UKM should still be recorded for the final URL, not the redirect URL. EXPECT_CALL(*mock_trigger_script_ui_delegate_, ShowTriggerScript);
diff --git a/components/autofill_assistant/browser/startup_util.cc b/components/autofill_assistant/browser/startup_util.cc index 9dea9488..aad8bfb 100644 --- a/components/autofill_assistant/browser/startup_util.cc +++ b/components/autofill_assistant/browser/startup_util.cc
@@ -68,13 +68,9 @@ return StartupMode::START_REGULAR; } - if (!(script_parameters.GetRequestsTriggerScript().value_or(false) || - !script_parameters.GetBase64TriggerScriptsResponseProto() - .value_or(std::string()) - .empty())) { - VLOG(1) - << "Invalid Autofill Assistant intent: START_IMMEDIATELY=false " - "requires either REQUEST_TRIGGER_SCRIPT or TRIGGER_SCRIPTS_BASE64."; + if (!(script_parameters.GetRequestsTriggerScript().value_or(false))) { + VLOG(1) << "Invalid Autofill Assistant intent: START_IMMEDIATELY=false " + "requires REQUEST_TRIGGER_SCRIPT=true."; return StartupMode::MANDATORY_PARAMETERS_MISSING; } @@ -84,12 +80,6 @@ return StartupMode::SETTING_DISABLED; } - if (script_parameters.GetBase64TriggerScriptsResponseProto().has_value()) { - // Base64 trigger scripts do not require further checks, and they take - // precedence over RPC trigger scripts. - return StartupMode::START_BASE64_TRIGGER_SCRIPT; - } - DCHECK(script_parameters.GetRequestsTriggerScript().value_or(false)); if (!options.msbb_setting_enabled) { VLOG(1) << "Invalid Autofill Assistant intent: REQUEST_TRIGGER_SCRIPT "
diff --git a/components/autofill_assistant/browser/startup_util.h b/components/autofill_assistant/browser/startup_util.h index ba9d4828..aa003d2 100644 --- a/components/autofill_assistant/browser/startup_util.h +++ b/components/autofill_assistant/browser/startup_util.h
@@ -27,8 +27,6 @@ // Parameters are ok, a regular script should be started immediately. START_REGULAR, - // Parameters are ok, a base64 trigger script should be started. - START_BASE64_TRIGGER_SCRIPT, // Parameters are ok, a remote trigger script should be started. START_RPC_TRIGGER_SCRIPT };
diff --git a/components/autofill_assistant/browser/startup_util_unittest.cc b/components/autofill_assistant/browser/startup_util_unittest.cc index b269372..edcfc5f 100644 --- a/components/autofill_assistant/browser/startup_util_unittest.cc +++ b/components/autofill_assistant/browser/startup_util_unittest.cc
@@ -35,9 +35,6 @@ case StartupMode::START_REGULAR: out << "START_REGULAR"; break; - case StartupMode::START_BASE64_TRIGGER_SCRIPT: - out << "START_BASE64_TRIGGER_SCRIPT"; - break; case StartupMode::START_RPC_TRIGGER_SCRIPT: out << "START_RPC_TRIGGER_SCRIPT"; break; @@ -74,11 +71,6 @@ {"START_IMMEDIATELY", "false"}, {"REQUEST_TRIGGER_SCRIPT", "true"}, {"ORIGINAL_DEEPLINK", "https://www.example.com"}}; -const base::flat_map<std::string, std::string> kBase64TriggerScript = { - {"ENABLED", "true"}, - {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", "abc"}, - {"ORIGINAL_DEEPLINK", "https://www.example.com"}}; const TriggerContext::Options kDefaultCCTOptions = { std::string(), /* is_cct = */ true, false, false, std::string(), false, @@ -279,68 +271,8 @@ : StartupMode::FEATURE_DISABLED)); } -TEST_P(StartupUtilParametrizedTest, StartBase64TriggerScript) { - // Everything true, DFM already installed. - EXPECT_THAT( - StartupUtil().ChooseStartupModeForIntent( - TriggerContext{ - std::make_unique<ScriptParameters>(kBase64TriggerScript), - kDefaultCCTOptions}, - {.msbb_setting_enabled = true, - .proactive_help_setting_enabled = true, - .feature_module_installed = true}), - MatchingStartupMode(AreFeaturesEnabled({kAutofillAssistant, - kAutofillAssistantProactiveHelp}) - ? StartupMode::START_BASE64_TRIGGER_SCRIPT - : StartupMode::FEATURE_DISABLED)); - - // Everything true, but DFM is not yet installed. - EXPECT_THAT(StartupUtil().ChooseStartupModeForIntent( - TriggerContext{ - std::make_unique<ScriptParameters>(kBase64TriggerScript), - kDefaultCCTOptions}, - {.msbb_setting_enabled = true, - .proactive_help_setting_enabled = true, - .feature_module_installed = false}), - MatchingStartupMode( - AreFeaturesEnabled( - {kAutofillAssistant, kAutofillAssistantProactiveHelp, - kAutofillAssistantLoadDFMForTriggerScripts}) - ? StartupMode::START_BASE64_TRIGGER_SCRIPT - : StartupMode::FEATURE_DISABLED)); - - // MSBB is off, but should not be required by base64 trigger scripts. - EXPECT_THAT( - StartupUtil().ChooseStartupModeForIntent( - TriggerContext{ - std::make_unique<ScriptParameters>(kBase64TriggerScript), - kDefaultCCTOptions}, - {.msbb_setting_enabled = false, - .proactive_help_setting_enabled = true, - .feature_module_installed = true}), - MatchingStartupMode(AreFeaturesEnabled({kAutofillAssistant, - kAutofillAssistantProactiveHelp}) - ? StartupMode::START_BASE64_TRIGGER_SCRIPT - : StartupMode::FEATURE_DISABLED)); - - // Proactive help is off. - EXPECT_THAT( - StartupUtil().ChooseStartupModeForIntent( - TriggerContext{ - std::make_unique<ScriptParameters>(kBase64TriggerScript), - kDefaultCCTOptions}, - {.msbb_setting_enabled = true, - .proactive_help_setting_enabled = false, - .feature_module_installed = true}), - MatchingStartupMode(AreFeaturesEnabled({kAutofillAssistant, - kAutofillAssistantProactiveHelp}) - ? StartupMode::SETTING_DISABLED - : StartupMode::FEATURE_DISABLED)); -} - TEST_P(StartupUtilParametrizedTest, InvalidParameterCombinationsShouldFail) { - // START_IMMEDIATELY=false requires either REQUEST_TRIGGER_SCRIPT or - // TRIGGER_SCRIPTS_BASE64. + // START_IMMEDIATELY=false requires REQUEST_TRIGGER_SCRIPT EXPECT_THAT( StartupUtil().ChooseStartupModeForIntent( TriggerContext{ @@ -377,25 +309,6 @@ ? StartupMode::MANDATORY_PARAMETERS_MISSING : StartupMode::FEATURE_DISABLED)); - // TRIGGER_SCRIPTS_BASE64 must not be empty. - EXPECT_THAT( - StartupUtil().ChooseStartupModeForIntent( - TriggerContext{ - std::make_unique<ScriptParameters>( - base::flat_map<std::string, std::string>{ - {"ENABLED", "true"}, - {"START_IMMEDIATELY", "false"}, - {"TRIGGER_SCRIPTS_BASE64", ""}, - {"ORIGINAL_DEEPLINK", "https://www.example.com"}}), - kDefaultCCTOptions}, - {.msbb_setting_enabled = true, - .proactive_help_setting_enabled = false, - .feature_module_installed = true}), - MatchingStartupMode(AreFeaturesEnabled({kAutofillAssistant, - kAutofillAssistantProactiveHelp}) - ? StartupMode::MANDATORY_PARAMETERS_MISSING - : StartupMode::FEATURE_DISABLED)); - // ORIGINAL_DEEPLINK or initial url must be specified and valid. EXPECT_THAT(StartupUtil().ChooseStartupModeForIntent( TriggerContext{std::make_unique<ScriptParameters>(
diff --git a/components/autofill_assistant/browser/ui_controller.h b/components/autofill_assistant/browser/ui_controller.h index 91099c4..08a4984 100644 --- a/components/autofill_assistant/browser/ui_controller.h +++ b/components/autofill_assistant/browser/ui_controller.h
@@ -170,6 +170,13 @@ void OnInputTextFocusChanged(bool is_text_focused) override; EventHandler* GetEventHandler() override; void DispatchEvent(const EventHandler::EventKey& key) override; + bool SupportsExternalActions() override; + void ExecuteExternalAction( + const external::Action& external_action, + base::OnceCallback<void(ExternalActionDelegate::DomUpdateCallback)> + start_dom_checks_callback, + base::OnceCallback<void(const external::Result& result)> + end_action_callback) override; // Overrides ControllerObserver. void OnError(const std::string& error_message, @@ -181,13 +188,6 @@ void OnStop() override; void OnResetState() override; void OnUiShownChanged(bool shown) override; - bool SupportsExternalActions() override; - void ExecuteExternalAction( - const external::Action& external_action, - base::OnceCallback<void(ExternalActionDelegate::DomUpdateCallback)> - start_dom_checks_callback, - base::OnceCallback<void(const external::Result& result)> - end_action_callback) override; // Overrides AutofillAssistantTtsController::TtsEventDelegate void OnTtsEvent(AutofillAssistantTtsController::TtsEventType event) override;
diff --git a/components/autofill_assistant/browser/ui_delegate.h b/components/autofill_assistant/browser/ui_delegate.h index 51985c7..e3d3137e 100644 --- a/components/autofill_assistant/browser/ui_delegate.h +++ b/components/autofill_assistant/browser/ui_delegate.h
@@ -13,7 +13,7 @@ #include "components/autofill_assistant/browser/client_settings.h" #include "components/autofill_assistant/browser/event_handler.h" #include "components/autofill_assistant/browser/metrics.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/state.h" #include "components/autofill_assistant/browser/tts_button_state.h" #include "components/autofill_assistant/browser/user_action.h"
diff --git a/components/autofill_assistant/browser/web/element_rect_getter.cc b/components/autofill_assistant/browser/web/element_rect_getter.cc index 84e2b6a82..f9525ab0 100644 --- a/components/autofill_assistant/browser/web/element_rect_getter.cc +++ b/components/autofill_assistant/browser/web/element_rect_getter.cc
@@ -10,7 +10,7 @@ #include "components/autofill_assistant/browser/client_status.h" #include "components/autofill_assistant/browser/devtools/devtools/domains/types_runtime.h" #include "components/autofill_assistant/browser/devtools/devtools_client.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/web/element_finder_result.h" #include "components/autofill_assistant/browser/web/web_controller_util.h"
diff --git a/components/autofill_assistant/browser/web/element_rect_getter.h b/components/autofill_assistant/browser/web/element_rect_getter.h index 37ff9afb..b866042 100644 --- a/components/autofill_assistant/browser/web/element_rect_getter.h +++ b/components/autofill_assistant/browser/web/element_rect_getter.h
@@ -9,7 +9,7 @@ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "components/autofill_assistant/browser/devtools/devtools_client.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/web/web_controller_worker.h" namespace autofill_assistant {
diff --git a/components/autofill_assistant/browser/web/web_controller.cc b/components/autofill_assistant/browser/web/web_controller.cc index a387554..c3c0c067 100644 --- a/components/autofill_assistant/browser/web/web_controller.cc +++ b/components/autofill_assistant/browser/web/web_controller.cc
@@ -27,7 +27,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill_assistant/browser/client_status.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/string_conversions_util.h" #include "components/autofill_assistant/browser/user_data_util.h" #include "components/autofill_assistant/browser/web/element.h"
diff --git a/components/autofill_assistant/browser/web/web_controller.h b/components/autofill_assistant/browser/web/web_controller.h index b2fb4d6..f8f0f1e 100644 --- a/components/autofill_assistant/browser/web/web_controller.h +++ b/components/autofill_assistant/browser/web/web_controller.h
@@ -20,7 +20,7 @@ #include "components/autofill_assistant/browser/devtools/devtools/domains/types_network.h" #include "components/autofill_assistant/browser/devtools/devtools/domains/types_runtime.h" #include "components/autofill_assistant/browser/devtools/devtools_client.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/selector.h" #include "components/autofill_assistant/browser/top_padding.h" #include "components/autofill_assistant/browser/user_data.h"
diff --git a/components/autofill_assistant/browser/web/web_controller_browsertest.cc b/components/autofill_assistant/browser/web/web_controller_browsertest.cc index 09e5f825..9c02cb4 100644 --- a/components/autofill_assistant/browser/web/web_controller_browsertest.cc +++ b/components/autofill_assistant/browser/web/web_controller_browsertest.cc
@@ -43,7 +43,7 @@ #include "components/autofill_assistant/browser/fake_script_executor_ui_delegate.h" #include "components/autofill_assistant/browser/mock_script_executor_delegate.h" #include "components/autofill_assistant/browser/model.pb.h" -#include "components/autofill_assistant/browser/rectf.h" +#include "components/autofill_assistant/browser/public/rectf.h" #include "components/autofill_assistant/browser/script.h" #include "components/autofill_assistant/browser/script_executor.h" #include "components/autofill_assistant/browser/selector.h"
diff --git a/components/commerce/core/BUILD.gn b/components/commerce/core/BUILD.gn index dc84038d..a4aa2c2a 100644 --- a/components/commerce/core/BUILD.gn +++ b/components/commerce/core/BUILD.gn
@@ -96,6 +96,11 @@ } } +proto_library("persisted_state_db_content_proto") { + proto_in_dir = "//" + sources = [ "proto/persisted_state_db_content.proto" ] +} + source_set("commerce_heuristics_data") { sources = [ "commerce_heuristics_data.cc",
diff --git a/chrome/browser/persisted_state_db/persisted_state_db_content.proto b/components/commerce/core/proto/persisted_state_db_content.proto similarity index 100% rename from chrome/browser/persisted_state_db/persisted_state_db_content.proto rename to components/commerce/core/proto/persisted_state_db_content.proto
diff --git a/components/components_strings.grd b/components/components_strings.grd index 1a7e174..acaf495 100644 --- a/components/components_strings.grd +++ b/components/components_strings.grd
@@ -345,6 +345,7 @@ </if> <if expr="is_android"> <part file="android_system_error_page_strings.grdp" /> + <part file="external_intents_strings.grdp" /> </if> <if expr="is_ios"> <part file="management_ios_strings.grdp" />
diff --git a/components/external_intents/android/BUILD.gn b/components/external_intents/android/BUILD.gn index 9b3d692..204cafa 100644 --- a/components/external_intents/android/BUILD.gn +++ b/components/external_intents/android/BUILD.gn
@@ -23,7 +23,9 @@ "//base:jni_java", "//build/android:build_java", "//components/embedder_support/android:util_java", + "//components/messages/android:java", "//components/navigation_interception/android:navigation_interception_java", + "//components/strings:components_strings_grd", "//components/url_formatter/android:url_formatter_java", "//components/webapk/android/libs/client:java", "//content/public/android:content_java",
diff --git a/components/external_intents/android/DEPS b/components/external_intents/android/DEPS index 651e42b..bd0285c 100644 --- a/components/external_intents/android/DEPS +++ b/components/external_intents/android/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+components/embedder_support/android", + "+components/messages", "+components/navigation_interception", "+components/webapk/android/libs/client", "+content/public/browser",
diff --git a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java index 0d65bfa..84ecb65 100644 --- a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java +++ b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java
@@ -19,6 +19,7 @@ import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Resources; +import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.StrictMode; import android.os.SystemClock; @@ -52,18 +53,26 @@ import org.chromium.components.embedder_support.util.UrlUtilities; import org.chromium.components.embedder_support.util.UrlUtilitiesJni; import org.chromium.components.external_intents.ExternalNavigationDelegate.IntentToAutofillAllowingAppResult; +import org.chromium.components.messages.MessageBannerProperties; +import org.chromium.components.messages.MessageDispatcher; +import org.chromium.components.messages.MessageDispatcherProvider; +import org.chromium.components.messages.MessageIdentifier; +import org.chromium.components.messages.MessageScopeType; +import org.chromium.components.messages.PrimaryActionClickBehavior; import org.chromium.components.webapk.lib.client.ChromeWebApkHostSignature; import org.chromium.components.webapk.lib.client.WebApkValidator; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.UiThreadTaskTraits; +import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.ContentUrlConstants; import org.chromium.content_public.common.Referrer; import org.chromium.network.mojom.ReferrerPolicy; import org.chromium.ui.base.MimeTypeUtils; import org.chromium.ui.base.PageTransition; import org.chromium.ui.base.WindowAndroid; +import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.permissions.PermissionCallback; import org.chromium.url.GURL; @@ -303,11 +312,11 @@ @OverrideUrlLoadingAsyncActionType int mAsyncActionType; - OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType) { + private OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType) { this(resultType, OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION); } - OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType, + private OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType, @OverrideUrlLoadingAsyncActionType int asyncActionType) { // The async action type should be set only for async actions... assert (asyncActionType == OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION @@ -329,18 +338,37 @@ return mAsyncActionType; } + /** + * Use this result when an asynchronous action needs to be carried out before deciding + * whether to block the external navigation. + */ public static OverrideUrlLoadingResult forAsyncAction( @OverrideUrlLoadingAsyncActionType int asyncActionType) { return new OverrideUrlLoadingResult( OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION, asyncActionType); } + + /** + * Use this result when we would like to block an external navigation without prompting the + * user asking them whether would like to launch an app, or when the navigation does not + * target an app. + */ public static OverrideUrlLoadingResult forNoOverride() { return new OverrideUrlLoadingResult(OverrideUrlLoadingResultType.NO_OVERRIDE); } + + /** + * Use this result when the current external navigation should be blocked and a new + * navigation will be started in the Tab, clobbering the previous one. + */ public static OverrideUrlLoadingResult forClobberingTab() { return new OverrideUrlLoadingResult( OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB); } + + /** + * Use this result when an external app has been launched as a result of the navigation. + */ public static OverrideUrlLoadingResult forExternalIntent() { return new OverrideUrlLoadingResult( OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT); @@ -384,6 +412,7 @@ if (!browserFallbackUrl.isValid() || !UrlUtilities.isHttpOrHttps(browserFallbackUrl)) { browserFallbackUrl = GURL.emptyGURL(); } + targetIntent.removeExtra(EXTRA_BROWSER_FALLBACK_URL); // TODO(https://crbug.com/1096099): Refactor shouldOverrideUrlLoadingInternal, splitting it // up to separate out the notions wanting to fire an external intent vs being able to. @@ -907,8 +936,9 @@ * If the intent can't be resolved, we should fall back to the browserFallbackUrl, or try to * find the app on the market if no fallback is provided. */ - private OverrideUrlLoadingResult handleUnresolvableIntent( - ExternalNavigationParams params, Intent targetIntent, GURL browserFallbackUrl) { + private OverrideUrlLoadingResult handleUnresolvableIntent(ExternalNavigationParams params, + Intent targetIntent, GURL browserFallbackUrl, boolean requiresPromptForExternalIntent) { + if (requiresPromptForExternalIntent) return OverrideUrlLoadingResult.forNoOverride(); // Fallback URL will be handled by the caller of shouldOverrideUrlLoadingInternal. if (!browserFallbackUrl.isEmpty()) return OverrideUrlLoadingResult.forNoOverride(); if (targetIntent.getPackage() != null) { @@ -962,7 +992,9 @@ } private boolean fallBackToHandlingWithInstantApp(ExternalNavigationParams params, - boolean incomingIntentRedirect, QueryIntentActivitiesSupplier resolveInfos) { + boolean incomingIntentRedirect, QueryIntentActivitiesSupplier resolveInfos, + boolean requiresPromptForExternalIntent) { + if (requiresPromptForExternalIntent) return false; if (params.isIncognito()) return false; if (mDelegate.maybeLaunchInstantApp(params.getUrl(), params.getReferrerUrl(), incomingIntentRedirect, isSerpReferrer(), resolveInfos)) { @@ -1441,46 +1473,60 @@ QueryIntentActivitiesSupplier resolvingInfos = new QueryIntentActivitiesSupplier(targetIntent); + boolean requiresPromptForExternalIntent = false; + if (redirectShouldStayInApp(params, isExternalProtocol, targetIntent, resolvingInfos)) { - return OverrideUrlLoadingResult.forNoOverride(); + requiresPromptForExternalIntent = true; } boolean intentMatchesNonDefaultWebApk = intentMatchesNonDefaultWebApk(params, resolvingInfos); if (!preferToShowIntentPicker(params, isExternalProtocol, incomingIntentRedirect, intentMatchesNonDefaultWebApk)) { + requiresPromptForExternalIntent = true; + } + + // Short-circuit expensive quertyIntentActivities calls below since we won't prompt anyways + // for protocols the browser can handle. + if (requiresPromptForExternalIntent && !isExternalProtocol) { return OverrideUrlLoadingResult.forNoOverride(); } // From this point on, we have determined it is safe to launch an External App from a - // fallback URL. - canLaunchExternalFallbackResult.set(true); + // fallback URL (unless we have to prompt). + if (!requiresPromptForExternalIntent) canLaunchExternalFallbackResult.set(true); if (resolvingInfos.get().isEmpty()) { - return handleUnresolvableIntent(params, targetIntent, browserFallbackUrl); + return handleUnresolvableIntent( + params, targetIntent, browserFallbackUrl, requiresPromptForExternalIntent); } if (resolvesToNonExportedActivity(resolvingInfos.get())) { return OverrideUrlLoadingResult.forNoOverride(); } - if (!browserFallbackUrl.isEmpty()) targetIntent.removeExtra(EXTRA_BROWSER_FALLBACK_URL); - boolean hasSpecializedHandler = countSpecializedHandlers(resolvingInfos.get()) > 0; if (!isExternalProtocol && !hasSpecializedHandler && !intentMatchesNonDefaultWebApk) { - if (fallBackToHandlingWithInstantApp(params, incomingIntentRedirect, resolvingInfos)) { + if (fallBackToHandlingWithInstantApp(params, incomingIntentRedirect, resolvingInfos, + requiresPromptForExternalIntent)) { return OverrideUrlLoadingResult.forExternalIntent(); } return fallBackToHandlingInApp(); } - // From this point on we should only have URLs from intent URIs, or URLs for - // apps with specialized handlers (including custom schemes). - if (shouldStayWithinHost(params, resolvingInfos.get(), isExternalProtocol)) { return OverrideUrlLoadingResult.forNoOverride(); } + if (shouldKeepIntentRedirectInApp( + params, incomingIntentRedirect, resolvingInfos.get(), isExternalProtocol)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + if (isAlreadyInTargetWebApk(resolvingInfos, params)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + boolean shouldProxyForInstantApps = mDelegate.handlesInstantAppLaunchingInternally() && isIntentToInstantApp(targetIntent) && isSerpReferrer(); prepareExternalIntent( @@ -1491,14 +1537,7 @@ browserFallbackUrl, shouldProxyForInstantApps); } - if (shouldKeepIntentRedirectInApp( - params, incomingIntentRedirect, resolvingInfos.get(), isExternalProtocol)) { - return OverrideUrlLoadingResult.forNoOverride(); - } - - if (isAlreadyInTargetWebApk(resolvingInfos, params)) { - return OverrideUrlLoadingResult.forNoOverride(); - } else if (launchWebApkIfSoleIntentHandler(resolvingInfos, targetIntent, params)) { + if (launchWebApkIfSoleIntentHandler(resolvingInfos, targetIntent, params)) { return OverrideUrlLoadingResult.forExternalIntent(); } @@ -1514,6 +1553,11 @@ return OverrideUrlLoadingResult.forNoOverride(); } + if (requiresPromptForExternalIntent) { + return maybeAskToLaunchApp(isExternalProtocol, targetIntent, resolvingInfos, + resolveActivity, browserFallbackUrl); + } + return startActivity(targetIntent, shouldProxyForInstantApps, requiresIntentChooser, resolvingInfos, resolveActivity, browserFallbackUrl, intentDataUrl, params.getReferrerUrl()); @@ -2012,6 +2056,82 @@ OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH); } + private OverrideUrlLoadingResult maybeAskToLaunchApp(boolean isExternalProtocol, + Intent targetIntent, QueryIntentActivitiesSupplier resolvingInfos, + ResolveActivitySupplier resolveActivity, GURL browserFallbackUrl) { + // For URLs the browser supports, we shouldn't have reached here. + assert isExternalProtocol; + + // Use the fallback URL if we have it, otherwise we give sites a fingerprinting mechanism + // where they can repeatedly attempt to launch apps without a user gesture until they find + // one the user has installed. + if (!browserFallbackUrl.isEmpty()) return OverrideUrlLoadingResult.forNoOverride(); + + ResolveInfo intentResolveInfo = resolveActivity.get(); + + // No app can resolve the intent, don't prompt. + if (intentResolveInfo == null || intentResolveInfo.activityInfo == null) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + // If the |resolvingInfos| from queryIntentActivities don't contain the result of + // resolveActivity, it means there's no default handler for the intent and it's resolving to + // the ResolverActivity. This means we can't know which app will be launched and can't + // convey that to the user. We also don't want to just allow the chooser dialog to be shown + // when the external navigation was otherwise blocked. In this case, we should just continue + // to block the navigation, and sites hoping to prompt the user when navigation fails should + // make sure to correctly target their app. + if (!resolversSubsetOf(Arrays.asList(intentResolveInfo), resolvingInfos.get())) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + MessageDispatcher messageDispatcher = + MessageDispatcherProvider.from(mDelegate.getWindowAndroid()); + WebContents webContents = mDelegate.getWebContents(); + if (messageDispatcher == null || webContents == null) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + String packageName = intentResolveInfo.activityInfo.packageName; + PackageManager pm = mDelegate.getContext().getPackageManager(); + ApplicationInfo applicationInfo = null; + try { + applicationInfo = pm.getApplicationInfo(packageName, 0); + } catch (NameNotFoundException e) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + Drawable icon = pm.getApplicationLogo(applicationInfo); + if (icon == null) icon = pm.getApplicationIcon(applicationInfo); + CharSequence label = pm.getApplicationLabel(applicationInfo); + + Resources res = mDelegate.getContext().getResources(); + String title = res.getString(R.string.external_navigation_continue_to_title, label); + String description = + res.getString(R.string.external_navigation_continue_to_description, label); + String action = res.getString(R.string.external_navigation_continue_to_action); + + PropertyModel message = + new PropertyModel.Builder(MessageBannerProperties.ALL_KEYS) + .with(MessageBannerProperties.MESSAGE_IDENTIFIER, + MessageIdentifier.EXTERNAL_NAVIGATION) + .with(MessageBannerProperties.TITLE, title) + .with(MessageBannerProperties.DESCRIPTION, description) + .with(MessageBannerProperties.ICON, icon) + .with(MessageBannerProperties.PRIMARY_BUTTON_TEXT, action) + .with(MessageBannerProperties.ICON_TINT_COLOR, + MessageBannerProperties.TINT_NONE) + .with(MessageBannerProperties.ON_PRIMARY_ACTION, + () -> { + startActivity(targetIntent, false); + return PrimaryActionClickBehavior.DISMISS_IMMEDIATELY; + }) + .build(); + messageDispatcher.enqueueMessage(message, webContents, MessageScopeType.NAVIGATION, false); + return OverrideUrlLoadingResult.forAsyncAction( + OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH); + } + /** * Returns the number of specialized intent handlers in {@params infos}. Specialized intent * handlers are intent handlers which handle only a few URLs (e.g. google maps or youtube).
diff --git a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java index ba37b04..327332c 100644 --- a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java +++ b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java
@@ -2693,8 +2693,7 @@ @Override protected OverrideUrlLoadingResult startActivity(Intent intent, boolean proxy, - boolean requiresIntentChooser, - ExternalNavigationHandler.QueryIntentActivitiesSupplier resolvingInfos, + boolean requiresIntentChooser, QueryIntentActivitiesSupplier resolvingInfos, ResolveActivitySupplier resolveActivity, GURL browserFallbackUrl, GURL intentDataUrl, GURL referrerUrl) { mStartActivityIntent = intent;
diff --git a/components/external_intents_strings.grdp b/components/external_intents_strings.grdp new file mode 100644 index 0000000..621096c9 --- /dev/null +++ b/components/external_intents_strings.grdp
@@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<grit-part> + <message name="IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_TITLE" desc="Title for the Continue To App Message." formatter_data="android_java"> + Continue to <ph name="APP_NAME">%1s<ex>Youtube</ex></ph>? + </message> + <message name="IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_DESCRIPTION" desc="Description for the Continue To App Message." formatter_data="android_java"> + This site wants to open the <ph name="APP_NAME">%1s<ex>Youtube</ex></ph> app + </message> + <message name="IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_ACTION" desc="Action for the Continue To App Message." formatter_data="android_java"> + Continue + </message> +</grit-part>
diff --git a/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_ACTION.png.sha1 b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_ACTION.png.sha1 new file mode 100644 index 0000000..a6982454 --- /dev/null +++ b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_ACTION.png.sha1
@@ -0,0 +1 @@ +157f661704da8b36b570c9e9262054cbd7ed564a \ No newline at end of file
diff --git a/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_DESCRIPTION.png.sha1 b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..a6982454 --- /dev/null +++ b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +157f661704da8b36b570c9e9262054cbd7ed564a \ No newline at end of file
diff --git a/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_TITLE.png.sha1 b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_TITLE.png.sha1 new file mode 100644 index 0000000..a6982454 --- /dev/null +++ b/components/external_intents_strings_grdp/IDS_EXTERNAL_NAVIGATION_CONTINUE_TO_TITLE.png.sha1
@@ -0,0 +1 @@ +157f661704da8b36b570c9e9262054cbd7ed564a \ No newline at end of file
diff --git a/components/history/core/browser/expire_history_backend_unittest.cc b/components/history/core/browser/expire_history_backend_unittest.cc index 098823c..58551a1 100644 --- a/components/history/core/browser/expire_history_backend_unittest.cc +++ b/components/history/core/browser/expire_history_backend_unittest.cc
@@ -210,6 +210,7 @@ void NotifyURLsDeleted(DeletionInfo deletion_info) override { urls_deleted_notifications_.push_back(std::move(deletion_info)); } + void NotifyVisitUpdated(const VisitRow& visit) override {} void NotifyVisitDeleted(const VisitRow& visit) override {} };
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index b8acade..8b39b98 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -621,6 +621,7 @@ ? end_ts - visit_row.visit_time : base::Microseconds(0); db_->UpdateVisitRow(visit_row); + NotifyVisitUpdated(visit_row); } } @@ -792,6 +793,7 @@ visit_row.transition = ui::PageTransitionFromInt( visit_row.transition & ~ui::PAGE_TRANSITION_CHAIN_END); db_->UpdateVisitRow(visit_row); + NotifyVisitUpdated(visit_row); } extended_redirect_chain = GetCachedRecentRedirects(request.referrer); @@ -1385,6 +1387,7 @@ if (!db_->UpdateVisitRow(updated_row)) return false; + NotifyVisitUpdated(updated_row); ScheduleCommit(); return true; } @@ -1428,6 +1431,13 @@ return false; } +bool HistoryBackend::GetLastVisitByTime(base::Time visit_time, + VisitRow* visit_row) { + if (db_) + return db_->GetLastRowForVisitByVisitTime(visit_time, visit_row); + return false; +} + QueryURLResult HistoryBackend::QueryURL(const GURL& url, bool want_visits) { QueryURLResult result; result.success = db_ && db_->GetRowForURL(url, &result.row); @@ -1773,21 +1783,34 @@ } VisitRow HistoryBackend::GetRedirectChainStart(VisitRow visit) { + VisitVector redirect_chain = GetRedirectChain(visit); + if (redirect_chain.empty()) + return {}; + return redirect_chain.front(); +} + +VisitVector HistoryBackend::GetRedirectChain(VisitRow visit) { // Iterate up `visit.referring_visit` while `visit.transition` is a redirect. + VisitVector result; + result.push_back(visit); if (db_) { base::flat_set<VisitID> visit_set; while (!(visit.transition & ui::PAGE_TRANSITION_CHAIN_START)) { visit_set.insert(visit.visit_id); // `GetRowForVisit()` should not return false if the DB is correct. - if (!db_->GetRowForVisit(visit.referring_visit, &visit)) + VisitRow referring_visit; + if (!db_->GetRowForVisit(visit.referring_visit, &referring_visit)) return {}; - if (visit_set.count(visit.visit_id)) { + if (visit_set.count(referring_visit.visit_id)) { NOTREACHED() << "Loop in visit redirect chain, giving up"; break; } + result.push_back(referring_visit); + visit = referring_visit; } } - return visit; + std::reverse(result.begin(), result.end()); + return result; } // Observers ------------------------------------------------------------------- @@ -2708,8 +2731,17 @@ delegate_->NotifyURLsDeleted(std::move(deletion_info)); } +void HistoryBackend::NotifyVisitUpdated(const VisitRow& visit) { + for (HistoryBackendObserver& observer : observers_) { + observer.OnVisitUpdated(visit); + } +} + void HistoryBackend::NotifyVisitDeleted(const VisitRow& visit) { tracker_.RemoveVisitById(visit.visit_id); + for (HistoryBackendObserver& observer : observers_) { + observer.OnVisitDeleted(visit); + } } // Deleting --------------------------------------------------------------------
diff --git a/components/history/core/browser/history_backend.h b/components/history/core/browser/history_backend.h index 8ef9788..bdf89556 100644 --- a/components/history/core/browser/history_backend.h +++ b/components/history/core/browser/history_backend.h
@@ -23,7 +23,6 @@ #include "base/gtest_prod_util.h" #include "base/memory/memory_pressure_listener.h" #include "base/observer_list.h" -#include "base/supports_user_data.h" #include "base/task/cancelable_task_tracker.h" #include "base/task/single_thread_task_runner.h" #include "base/time/time.h" @@ -486,18 +485,25 @@ // Get a `Cluster`. Cluster GetCluster(int64_t cluster_id); - // Finds the 1st visit in the redirect chain containing `visit`. Similar to - // `GetRedirectsToSpecificVisit()`, except 1) only returns the 1st visit of - // the redirect chain instead of the entire chain, and 2) ignores referrals. + // Finds the 1st visit in the redirect chain containing `visit`. + // Unlike `GetRedirectsToSpecificVisit()`, this only considers actual + // redirects, not referrals. // May return an invalid `VisitRow` if there's something wrong with the DB. // The caller is responsible for identifying, by looking at `visit_id`, and // handling this case. VisitRow GetRedirectChainStart(VisitRow visit); + // Returns the redirect chain ending in `visit`. (If `visit` is in the middle + // of a redirect chain, returns the start of the chain until `visit`.) + // Unlike `GetRedirectsToSpecificVisit()`, this only considers actual + // redirects, not referrals. + // May return an empty vector if there's something wrong with the DB. + VisitVector GetRedirectChain(VisitRow visit) override; + // Observers ----------------------------------------------------------------- - void AddObserver(HistoryBackendObserver* observer); - void RemoveObserver(HistoryBackendObserver* observer); + void AddObserver(HistoryBackendObserver* observer) override; + void RemoveObserver(HistoryBackendObserver* observer) override; // Generic operations -------------------------------------------------------- @@ -511,7 +517,9 @@ bool GetVisitsForURL(URLID id, VisitVector* visits); // Fetches up to `max_visits` most recent visits for the passed URL. - bool GetMostRecentVisitsForURL(URLID id, int max_visits, VisitVector* visits); + bool GetMostRecentVisitsForURL(URLID id, + int max_visits, + VisitVector* visits) override; // For each element in `urls`, updates the pre-existing URLRow in the database // with the same ID; or ignores the element if no such row exists. Returns the @@ -550,7 +558,12 @@ bool GetURL(const GURL& url, URLRow* url_row); - bool GetURLByID(URLID url_id, URLRow* url_row); + bool GetURLByID(URLID url_id, URLRow* url_row) override; + + // Returns the visit matching a given timestamp. In case of redirects (where + // multiple visits can have the same timestamp), returns the last visit in the + // redirect chain. + bool GetLastVisitByTime(base::Time visit_time, VisitRow* visit_row) override; // Returns the sync controller delegate for syncing typed urls. The returned // delegate is owned by `this` object. @@ -694,7 +707,7 @@ absl::optional<VisitID> originator_referring_visit = absl::nullopt, absl::optional<VisitID> originator_opener_visit = absl::nullopt); - // Returns a redirect chain in `redirects` for the VisitID + // Returns a redirect-or-referral chain in `redirects` for the VisitID // `cur_visit`. `cur_visit` is assumed to be valid. Assumes that // this HistoryBackend object has been Init()ed successfully. void GetRedirectsFromSpecificVisit(VisitID cur_visit, @@ -793,6 +806,7 @@ void NotifyURLsModified(const URLRows& changed_urls, bool is_from_expiration) override; void NotifyURLsDeleted(DeletionInfo deletion_info) override; + void NotifyVisitUpdated(const VisitRow& visit) override; void NotifyVisitDeleted(const VisitRow& visit) override; // Deleting all history ------------------------------------------------------
diff --git a/components/history/core/browser/history_backend_notifier.h b/components/history/core/browser/history_backend_notifier.h index 93d15c27..38d313c2 100644 --- a/components/history/core/browser/history_backend_notifier.h +++ b/components/history/core/browser/history_backend_notifier.h
@@ -44,6 +44,9 @@ // `deletion_info` describes the urls that have been removed from history. virtual void NotifyURLsDeleted(DeletionInfo deletion_info) = 0; + // Called after a visit has been updated. + virtual void NotifyVisitUpdated(const VisitRow& visit) = 0; + // Called after a visit has been deleted. virtual void NotifyVisitDeleted(const VisitRow& visit) = 0; };
diff --git a/components/history/core/browser/history_backend_observer.h b/components/history/core/browser/history_backend_observer.h index c02cf30..eadee7baa 100644 --- a/components/history/core/browser/history_backend_observer.h +++ b/components/history/core/browser/history_backend_observer.h
@@ -53,6 +53,15 @@ bool expired, const URLRows& deleted_rows, const std::set<GURL>& favicon_urls) = 0; + + // Called when a visit is updated. Typically this happens when the visit + // duration is updated, and in some redirect cases when the transition type + // is updated. + virtual void OnVisitUpdated(const VisitRow& visit) = 0; + + // Called when a visit is deleted - usually either due to expiry, or because + // the user explicitly deleted it. + virtual void OnVisitDeleted(const VisitRow& visit) = 0; }; } // namespace history
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index c3c6a7a0..2caf42bf 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -3896,6 +3896,77 @@ } } +TEST_F(HistoryBackendTest, GetRedirectChain) { + const auto add_visit_chain = [&](std::vector<std::string> urls, + base::Time visit_time, + VisitID referring_visit) { + std::vector<VisitID> ids; + for (size_t i = 0; i < urls.size(); i++) { + int transition = ui::PAGE_TRANSITION_TYPED; + if (i == 0) { + transition |= ui::PAGE_TRANSITION_CHAIN_START; + } + if (i == urls.size() - 1) { + transition |= ui::PAGE_TRANSITION_CHAIN_END; + } else { + transition |= ui::PAGE_TRANSITION_SERVER_REDIRECT; + } + auto url_and_visit_id = + backend_->AddPageVisit(GURL(urls[i]), visit_time, referring_visit, + ui::PageTransitionFromInt(transition), false, + SOURCE_BROWSED, false, 0); + ids.push_back(url_and_visit_id.second); + + referring_visit = url_and_visit_id.second; + } + + return ids; + }; + + base::Time time1 = base::Time::Now(); + base::Time time2 = time1 + base::Minutes(1); + base::Time time3 = time2 + base::Minutes(2); + + // Create visits: A single visit (no redirects), and a 2-entry redirect chain + // which further refers to another 3-entry redirect chain. + std::vector<VisitID> chain1_ids = + add_visit_chain({"https://url.com"}, time1, 0); + std::vector<VisitID> chain2_ids = + add_visit_chain({"https://chain2a.com", "https://chain2b.com"}, time2, 0); + std::vector<VisitID> chain3_ids = add_visit_chain( + {"https://chain3a.com", "https://chain3b.com", "https://chain3c.com"}, + time3, chain2_ids.back()); + + ASSERT_EQ(chain1_ids.size(), 1u); + ASSERT_EQ(chain2_ids.size(), 2u); + ASSERT_EQ(chain3_ids.size(), 3u); + + // Querying the redirect chain for the individual visit should just return + // that one visit. + VisitRow visit1; + backend_->db_->GetRowForVisit(chain1_ids.back(), &visit1); + VisitVector chain1 = backend_->GetRedirectChain(visit1); + ASSERT_EQ(chain1.size(), 1u); + EXPECT_EQ(chain1[0].visit_id, chain1_ids[0]); + + // Querying the chains should return the full chains, but only as linked by + // redirects (not by referrals). + VisitRow chain2end; + backend_->db_->GetRowForVisit(chain2_ids.back(), &chain2end); + VisitVector chain2 = backend_->GetRedirectChain(chain2end); + ASSERT_EQ(chain2.size(), 2u); + EXPECT_EQ(chain2[0].visit_id, chain2_ids[0]); + EXPECT_EQ(chain2[1].visit_id, chain2_ids[1]); + + VisitRow chain3end; + backend_->db_->GetRowForVisit(chain3_ids.back(), &chain3end); + VisitVector chain3 = backend_->GetRedirectChain(chain3end); + ASSERT_EQ(chain3.size(), 3u); + EXPECT_EQ(chain3[0].visit_id, chain3_ids[0]); + EXPECT_EQ(chain3[1].visit_id, chain3_ids[1]); + EXPECT_EQ(chain3[2].visit_id, chain3_ids[2]); +} + TEST_F(HistoryBackendTest, GetCluster) { AddAnnotatedVisit(0); AddAnnotatedVisit(1);
diff --git a/components/history/core/browser/sync/history_backend_for_sync.h b/components/history/core/browser/sync/history_backend_for_sync.h index b968ef9..1318543 100644 --- a/components/history/core/browser/sync/history_backend_for_sync.h +++ b/components/history/core/browser/sync/history_backend_for_sync.h
@@ -14,6 +14,8 @@ namespace history { +class HistoryBackendObserver; + // Interface that defines the subset of HistoryBackend that is required by // HistorySyncBridge. This is a separate interface mainly for ease of testing. // Look at HistoryBackend for comments about the individual methods. @@ -21,11 +23,22 @@ public: virtual bool IsExpiredVisitTime(const base::Time& time) const = 0; + virtual bool GetURLByID(URLID url_id, URLRow* url_row) = 0; + virtual bool GetLastVisitByTime(base::Time visit_time, + VisitRow* visit_row) = 0; + virtual bool GetMostRecentVisitsForURL(URLID id, + int max_visits, + VisitVector* visits) = 0; + virtual VisitVector GetRedirectChain(VisitRow visit) = 0; + virtual VisitID AddSyncedVisit(const GURL& url, const std::u16string& title, bool hidden, const VisitRow& visit) = 0; virtual bool UpdateSyncedVisit(const VisitRow& visit) = 0; + + virtual void AddObserver(HistoryBackendObserver* observer) = 0; + virtual void RemoveObserver(HistoryBackendObserver* observer) = 0; }; } // namespace history
diff --git a/components/history/core/browser/sync/history_sync_bridge.cc b/components/history/core/browser/sync/history_sync_bridge.cc index af6d046..8803730 100644 --- a/components/history/core/browser/sync/history_sync_bridge.cc +++ b/components/history/core/browser/sync/history_sync_bridge.cc
@@ -6,6 +6,7 @@ #include "base/auto_reset.h" #include "base/logging.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "components/history/core/browser/sync/history_sync_metadata_database.h" @@ -13,6 +14,7 @@ #include "components/sync/model/metadata_batch.h" #include "components/sync/model/metadata_change_list.h" #include "components/sync/model/model_type_change_processor.h" +#include "components/sync/model/mutable_data_batch.h" #include "components/sync/model/sync_metadata_store_change_list.h" #include "components/sync/protocol/history_specifics.pb.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -24,6 +26,11 @@ constexpr base::TimeDelta kMaxWriteToTheFuture = base::Days(2); +std::string GetStorageKeyFromVisitRow(const VisitRow& row) { + DCHECK(!row.visit_time.is_null()); + return HistorySyncMetadataDatabase::StorageKeyFromVisitTime(row.visit_time); +} + enum class SyncHistoryDatabaseError { // TODO(crbug.com/1318028): Consider introducing separate buckets for // MergeSyncData vs ApplySyncChanges. @@ -31,6 +38,10 @@ kApplySyncChangesWriteMetadata = 2, kOnDatabaseError = 3, kLoadMetadata = 4, + kOnURLVisitedGetVisit = 5, + kOnURLsDeletedReadMetadata = 6, + kOnVisitUpdatedGetURL = 7, + kGetAllDataReadMetadata = 8, }; void RecordDatabaseError(SyncHistoryDatabaseError error) { @@ -112,6 +123,88 @@ return row; } +std::unique_ptr<syncer::EntityData> MakeEntityData( + const std::string& local_cache_guid, + const std::vector<URLRow>& redirect_urls, + const std::vector<VisitRow>& redirect_visits) { + DCHECK(!local_cache_guid.empty()); + DCHECK(!redirect_urls.empty()); + DCHECK_EQ(redirect_urls.size(), redirect_visits.size()); + + auto entity_data = std::make_unique<syncer::EntityData>(); + sync_pb::HistorySpecifics* history = entity_data->specifics.mutable_history(); + + // The first and last visit in the redirect chain are special: The first is + // where the user intended to go (via typing the URL, clicking on a link, etc) + // and the last one is where they actually ended up. + const VisitRow& first_visit = redirect_visits.front(); + const VisitRow& last_visit = redirect_visits.back(); + + // Take the visit time and the originator client ID from the last visit, + // though they should be the same across all visits in the chain anyway. + history->set_visit_time_windows_epoch_micros( + last_visit.visit_time.ToDeltaSinceWindowsEpoch().InMicroseconds()); + + const bool is_local_entity = last_visit.originator_cache_guid.empty(); + history->set_originator_cache_guid( + is_local_entity ? local_cache_guid : last_visit.originator_cache_guid); + + for (size_t i = 0; i < redirect_urls.size(); i++) { + const URLRow& url = redirect_urls[i]; + const VisitRow& visit = redirect_visits[i]; + auto* redirect_entry = history->add_redirect_entries(); + redirect_entry->set_originator_visit_id( + is_local_entity ? visit.visit_id : visit.originator_visit_id); + redirect_entry->set_url(url.url().spec()); + redirect_entry->set_title(base::UTF16ToUTF8(url.title())); + redirect_entry->set_hidden(url.hidden()); + + if (ui::PageTransitionIsRedirect(visit.transition)) { + if (visit.transition & ui::PAGE_TRANSITION_CLIENT_REDIRECT) { + redirect_entry->set_redirect_type( + sync_pb::SyncEnums_PageTransitionRedirectType_CLIENT_REDIRECT); + } else { + // Since we checked ui::PageTransitionIsRedirect(), either the client or + // the server redirect flag must be set. + DCHECK(visit.transition & ui::PAGE_TRANSITION_SERVER_REDIRECT); + redirect_entry->set_redirect_type( + sync_pb::SyncEnums_PageTransitionRedirectType_SERVER_REDIRECT); + } + } + } + + // The transition should be the same across the whole redirect chain, apart + // from redirect-related qualifiers. Take the transition from the first visit. + history->mutable_page_transition()->set_core_transition( + syncer::ToSyncPageTransition(first_visit.transition)); + history->mutable_page_transition()->set_blocked( + (first_visit.transition & ui::PAGE_TRANSITION_BLOCKED) != 0); + history->mutable_page_transition()->set_forward_back( + (first_visit.transition & ui::PAGE_TRANSITION_FORWARD_BACK) != 0); + history->mutable_page_transition()->set_from_address_bar( + (first_visit.transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) != 0); + history->mutable_page_transition()->set_home_page( + (first_visit.transition & ui::PAGE_TRANSITION_HOME_PAGE) != 0); + + // Referring visit and opener visit are taken from the *first* visit in the + // chain, since they only make sense for that one. + history->set_originator_referring_visit_id(first_visit.referring_visit); + history->set_originator_opener_visit_id(first_visit.opener_visit); + + // The final visit is the one where the user actually ended up, so it's the + // only one that can have a (non-zero) visit duration. + history->set_visit_duration_micros( + last_visit.visit_duration.InMicroseconds()); + + // The entity name is used for debugging purposes; choose something that's a + // decent tradeoff between "unique" and "readable". + entity_data->name = + base::StringPrintf("%s-%s", history->originator_cache_guid().c_str(), + redirect_urls.back().url().spec().c_str()); + + return entity_data; +} + enum class SpecificsError { kMissingRequiredFields = 1, kTooOld = 2, @@ -167,6 +260,7 @@ // Note that `sync_metadata_database_` can become null later, in case of // database errors. + history_backend_observation_.Observe(history_backend_.get()); LoadMetadata(); } @@ -265,11 +359,50 @@ void HistorySyncBridge::GetData(StorageKeyList storage_keys, DataCallback callback) { - NOTIMPLEMENTED(); + DCHECK(sequence_checker_.CalledOnValidSequence()); + + auto batch = std::make_unique<syncer::MutableDataBatch>(); + for (const std::string& key : storage_keys) { + base::Time visit_time = + HistorySyncMetadataDatabase::StorageKeyToVisitTime(key); + VisitRow final_visit; + if (!history_backend_->GetLastVisitByTime(visit_time, &final_visit)) { + continue; + } + + // Query the redirect chain that ended in this visit. + std::vector<VisitRow> redirect_visits = + history_backend_->GetRedirectChain(final_visit); + DCHECK(!redirect_visits.empty()); + DCHECK_EQ(redirect_visits.back().visit_id, final_visit.visit_id); + + // Query the corresponding URLs. + std::vector<URLRow> redirect_urls = QueryURLsForVisits(redirect_visits); + + std::unique_ptr<syncer::EntityData> entity_data = + MakeEntityData(GetLocalCacheGuid(), redirect_urls, redirect_visits); + + batch->Put(key, std::move(entity_data)); + } + + std::move(callback).Run(std::move(batch)); } void HistorySyncBridge::GetAllDataForDebugging(DataCallback callback) { - NOTIMPLEMENTED(); + DCHECK(sequence_checker_.CalledOnValidSequence()); + + auto metadata_batch = std::make_unique<syncer::MetadataBatch>(); + if (!sync_metadata_database_->GetAllSyncMetadata(metadata_batch.get())) { + RecordDatabaseError(SyncHistoryDatabaseError::kGetAllDataReadMetadata); + change_processor()->ReportError( + {FROM_HERE, + "Failed reading metadata from HistorySyncMetadataDatabase."}); + } + StorageKeyList storage_keys; + for (const auto& [storage_key, metadata] : metadata_batch->GetAllMetadata()) { + storage_keys.push_back(storage_key); + } + GetData(std::move(storage_keys), std::move(callback)); } std::string HistorySyncBridge::GetClientTag( @@ -294,13 +427,65 @@ ui::PageTransition transition, const URLRow& row, base::Time visit_time) { - NOTIMPLEMENTED(); + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK_GE(row.typed_count(), 0); + + if (processing_syncer_changes_) { + return; // These are changes originating from us, ignore. + } + + if (!change_processor()->IsTrackingMetadata()) { + return; // Sync processor not yet ready, don't sync. + } + + std::vector<VisitRow> visits; + if (!history_backend_->GetMostRecentVisitsForURL(row.id(), /*max_visits=*/1, + &visits)) { + RecordDatabaseError(SyncHistoryDatabaseError::kOnURLVisitedGetVisit); + return; + } + if (visits.size() != 1) { + RecordDatabaseError(SyncHistoryDatabaseError::kOnURLVisitedGetVisit); + return; + } + const VisitRow& visit_row = visits[0]; + + // If this visit is not the end of a redirect chain, ignore it. Note that + // visits that are not part of a redirect chain are considered to be both + // start and end of a chain, so these are *not* ignored here. + if (!(visit_row.transition & ui::PAGE_TRANSITION_CHAIN_END)) { + return; + } + + // Query the redirect chain that ended in this visit. + std::vector<VisitRow> redirect_visits = + history_backend_->GetRedirectChain(visit_row); + DCHECK(!redirect_visits.empty()); + DCHECK_EQ(redirect_visits.back().visit_id, visit_row.visit_id); + + // Query the corresponding URLs. + std::vector<URLRow> redirect_urls = QueryURLsForVisits(redirect_visits); + + std::unique_ptr<syncer::EntityData> entity_data = + MakeEntityData(GetLocalCacheGuid(), redirect_urls, redirect_visits); + + std::unique_ptr<syncer::MetadataChangeList> metadata_change_list = + CreateMetadataChangeList(); + change_processor()->Put(GetStorageKeyFromVisitRow(visit_row), + std::move(entity_data), metadata_change_list.get()); } void HistorySyncBridge::OnURLsModified(HistoryBackend* history_backend, const URLRows& changed_urls, bool is_from_expiration) { - NOTIMPLEMENTED(); + // Not interested: This class is watching visits rather than URLs, so + // modifications are handled in OnVisitUpdated(). + // TODO(crbug.com/1318028): The title *can* get updated without a new visit, + // so watch for and commit such changes. Basically: + // - Get most recent visit for the URL. + // - If it's a local visit, and is tracked (and, maybe, is the end of a + // redirect chain): + // - Build the specifics and Put() it. } void HistorySyncBridge::OnURLsDeleted(HistoryBackend* history_backend, @@ -308,7 +493,97 @@ bool expired, const URLRows& deleted_rows, const std::set<GURL>& favicon_urls) { - NOTIMPLEMENTED(); + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK(sync_metadata_database_); + + if (processing_syncer_changes_) { + return; // These are changes originating from us, ignore. + } + + if (!change_processor()->IsTrackingMetadata()) { + return; // Sync processor not yet ready, don't sync. + } + + // If individual URLs get deleted, we're notified about their removed visits + // via OnVisitDeleted(), so there's nothing to be done here. But if all + // history is cleared, there are no individual notifications, so handle that + // case here. + if (!all_history) { + return; + } + + // No need to send any actual deletions: A HistoryDeleteDirective will take + // care of that. Just untrack all entities and clear their metadata. + auto metadata_batch = std::make_unique<syncer::MetadataBatch>(); + if (!sync_metadata_database_->GetAllSyncMetadata(metadata_batch.get())) { + RecordDatabaseError(SyncHistoryDatabaseError::kOnURLsDeletedReadMetadata); + change_processor()->ReportError( + {FROM_HERE, + "Failed reading metadata from HistorySyncMetadataDatabase."}); + return; + } + for (const auto& [storage_key, metadata] : metadata_batch->GetAllMetadata()) { + sync_metadata_database_->ClearSyncMetadata(syncer::HISTORY, storage_key); + change_processor()->UntrackEntityForStorageKey(storage_key); + } +} + +void HistorySyncBridge::OnVisitUpdated(const VisitRow& visit_row) { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK(sync_metadata_database_); + + if (processing_syncer_changes_) { + return; // These are changes originating from us, ignore. + } + + if (!change_processor()->IsTrackingMetadata()) { + return; // Sync processor not yet ready, don't sync. + } + + // If this visit is not the end of a redirect chain, ignore it. Note that + // visits that are not part of a redirect chain are considered to be both + // start and end of a chain, so these are *not* ignored here. + if (!(visit_row.transition & ui::PAGE_TRANSITION_CHAIN_END)) { + return; + } + + // Query the redirect chain that ended in this visit. + std::vector<VisitRow> redirect_visits = + history_backend_->GetRedirectChain(visit_row); + DCHECK(!redirect_visits.empty()); + DCHECK_EQ(redirect_visits.back().visit_id, visit_row.visit_id); + + // Query the corresponding URLs. + std::vector<URLRow> redirect_urls = QueryURLsForVisits(redirect_visits); + + std::unique_ptr<syncer::EntityData> entity_data = + MakeEntityData(GetLocalCacheGuid(), redirect_urls, redirect_visits); + + std::unique_ptr<syncer::MetadataChangeList> metadata_change_list = + CreateMetadataChangeList(); + change_processor()->Put(GetStorageKeyFromVisitRow(visit_row), + std::move(entity_data), metadata_change_list.get()); +} + +void HistorySyncBridge::OnVisitDeleted(const VisitRow& visit_row) { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK(sync_metadata_database_); + + if (processing_syncer_changes_) { + return; // These are changes originating from us, ignore. + } + + if (!change_processor()->IsTrackingMetadata()) { + return; // Sync processor not yet ready, don't sync. + } + + // No need to send an actual deletion: Either this was an expiry, in which + // no deletion should be sent, or if it's an actual deletion, then a + // HistoryDeleteDirective will take care of that. Just untrack the entity and + // delete its metadata. + std::string storage_key = GetStorageKeyFromVisitRow(visit_row); + sync_metadata_database_->ClearSyncMetadata(syncer::HISTORY, storage_key); + change_processor()->UntrackEntityForStorageKey(storage_key); } void HistorySyncBridge::OnDatabaseError() { @@ -375,4 +650,22 @@ return true; } +std::string HistorySyncBridge::GetLocalCacheGuid() const { + // Before the processor is tracking metadata, the cache GUID isn't known. + DCHECK(change_processor()->IsTrackingMetadata()); + return change_processor()->TrackedCacheGuid(); +} + +std::vector<URLRow> HistorySyncBridge::QueryURLsForVisits( + const std::vector<VisitRow>& visits) { + std::vector<URLRow> urls; + urls.reserve(visits.size()); + for (const VisitRow& visit : visits) { + URLRow url; + history_backend_->GetURLByID(visit.url_id, &url); + urls.push_back(std::move(url)); + } + return urls; +} + } // namespace history
diff --git a/components/history/core/browser/sync/history_sync_bridge.h b/components/history/core/browser/sync/history_sync_bridge.h index 3d61d44b..5fa4900 100644 --- a/components/history/core/browser/sync/history_sync_bridge.h +++ b/components/history/core/browser/sync/history_sync_bridge.h
@@ -8,8 +8,10 @@ #include <memory> #include <set> #include <string> +#include <vector> #include "base/memory/raw_ptr.h" +#include "base/scoped_observation.h" #include "components/history/core/browser/history_backend_observer.h" #include "components/history/core/browser/sync/history_backend_for_sync.h" #include "components/sync/model/model_type_sync_bridge.h" @@ -65,6 +67,8 @@ bool expired, const URLRows& deleted_rows, const std::set<GURL>& favicon_urls) override; + void OnVisitUpdated(const VisitRow& visit_row) override; + void OnVisitDeleted(const VisitRow& visit_row) override; // Called by HistoryBackend when database error is reported through // DatabaseErrorCallback. @@ -84,6 +88,15 @@ // commonly, because no matching entry exists in the backend). bool UpdateEntityInBackend(const sync_pb::HistorySpecifics& specifics); + // Returns the cache GUID of the Sync client on this device. Must only be + // called after `change_processor()->IsTrackingMetadata()` returns true + // (because before that, the cache GUID isn't known). + std::string GetLocalCacheGuid() const; + + // For each entry in `visits`, queries the corresponding URLRow from the + // history backend. + std::vector<URLRow> QueryURLsForVisits(const std::vector<VisitRow>& visits); + // A non-owning pointer to the backend, which we're syncing local changes from // and sync changes to. Never null. const raw_ptr<HistoryBackendForSync> history_backend_; @@ -99,6 +112,11 @@ // HistoryBackend uses SequencedTaskRunner, so this makes sure // HistorySyncBridge is used on the correct sequence. base::SequenceChecker sequence_checker_; + + // Tracks observed history backend, for receiving updates from history + // backend. + base::ScopedObservation<HistoryBackendForSync, HistoryBackendObserver> + history_backend_observation_{this}; }; } // namespace history
diff --git a/components/history/core/browser/sync/history_sync_bridge_unittest.cc b/components/history/core/browser/sync/history_sync_bridge_unittest.cc index e40fd382..0881303 100644 --- a/components/history/core/browser/sync/history_sync_bridge_unittest.cc +++ b/components/history/core/browser/sync/history_sync_bridge_unittest.cc
@@ -12,7 +12,9 @@ #include "components/history/core/browser/sync/history_sync_metadata_database.h" #include "components/history/core/browser/sync/test_history_backend_for_sync.h" #include "components/sync/base/page_transition_conversion.h" +#include "components/sync/model/metadata_batch.h" #include "components/sync/model/metadata_change_list.h" +#include "components/sync/protocol/entity_metadata.pb.h" #include "components/sync/protocol/history_specifics.pb.h" #include "components/sync/test/model/mock_model_type_change_processor.h" #include "sql/database.h" @@ -24,6 +26,7 @@ namespace { +using testing::_; using testing::Return; sync_pb::HistorySpecifics CreateSpecifics( @@ -66,6 +69,16 @@ EXPECT_CALL(*processor(), ModelReadyToSync); bridge_ = std::make_unique<HistorySyncBridge>( &backend_, &metadata_db_, mock_processor_.CreateForwardingProcessor()); + + // Set up the processor to store metadata on Put(). + ON_CALL(*processor(), Put) + .WillByDefault([](const std::string& storage_key, + std::unique_ptr<syncer::EntityData> entity_data, + syncer::MetadataChangeList* metadata_change_list) { + sync_pb::EntityMetadata metadata; + metadata.set_sequence_number(1); + metadata_change_list->UpdateMetadata(storage_key, metadata); + }); } void TearDown() override { @@ -77,6 +90,35 @@ syncer::MockModelTypeChangeProcessor* processor() { return &mock_processor_; } HistorySyncBridge* bridge() { return bridge_.get(); } + std::pair<URLRow, VisitRow> AddVisitToBackendAndAdvanceClock( + const GURL& url, + ui::PageTransition transition) { + // After grabbing the visit time, advance the mock time so that the next + // visit will get a unique time. + base::Time visit_time = base::Time::Now(); + task_environment_.FastForwardBy(base::Seconds(1)); + + URLRow url_row; + const URLRow* existing_url_row = backend()->FindURLRow(url); + if (existing_url_row) { + url_row = *existing_url_row; + } else { + url_row.set_url(url); + url_row.set_title(u"Title"); + url_row.set_id(backend()->AddURL(url_row)); + } + + VisitRow visit_row; + visit_row.url_id = url_row.id(); + visit_row.visit_time = visit_time; + visit_row.transition = + ui::PageTransitionFromInt(transition | ui::PAGE_TRANSITION_CHAIN_START | + ui::PAGE_TRANSITION_CHAIN_END); + visit_row.visit_id = backend()->AddVisit(visit_row); + + return {url_row, visit_row}; + } + syncer::EntityChangeList CreateAddEntityChangeList( const std::vector<sync_pb::HistorySpecifics>& specifics_vector) { syncer::EntityChangeList entity_change_list; @@ -121,6 +163,14 @@ ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); } + syncer::EntityMetadataMap GetAllMetadata() { + auto metadata_batch = std::make_unique<syncer::MetadataBatch>(); + if (!metadata_db_.GetAllSyncMetadata(metadata_batch.get())) { + ADD_FAILURE() << "Failed to read metadata from DB"; + } + return metadata_batch->TakeAllMetadata(); + } + private: base::test::SingleThreadTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; @@ -137,11 +187,8 @@ }; TEST_F(HistorySyncBridgeTest, MergeDoesNotUploadData) { - URLID url_id = backend()->AddURL(URLRow(GURL("https://www.url.com"))); - VisitRow visit; - visit.url_id = url_id; - visit.visit_time = base::Time::Now(); - backend()->AddVisit(visit); + AddVisitToBackendAndAdvanceClock(GURL("https://www.url.com"), + ui::PAGE_TRANSITION_LINK); // The local data should *not* get uploaded to Sync. EXPECT_CALL(*processor(), Put).Times(0); @@ -158,11 +205,7 @@ const GURL local_url("https://local.com"); const GURL remote_url("https://remote.com"); - URLID url_id = backend()->AddURL(URLRow(local_url)); - VisitRow visit; - visit.url_id = url_id; - visit.visit_time = base::Time::Now() - base::Minutes(5); - backend()->AddVisit(visit); + AddVisitToBackendAndAdvanceClock(local_url, ui::PAGE_TRANSITION_LINK); sync_pb::HistorySpecifics remote_entity = CreateSpecifics( base::Time::Now() - base::Minutes(1), remote_cache_guid, remote_url); @@ -242,6 +285,228 @@ EXPECT_EQ(backend()->GetVisits()[0].originator_cache_guid, remote_cache_guid); } +TEST_F(HistorySyncBridgeTest, UploadsNewLocalVisit) { + // Start syncing (with no data yet). + MergeSyncData({}); + + // Visit a URL. + auto [url_row, visit_row] = AddVisitToBackendAndAdvanceClock( + GURL("https://www.url.com"), + ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED | + ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)); + + // Notify the bridge about the visit - it should be sent to the processor. + syncer::EntityData entity; + EXPECT_CALL(*processor(), + Put(HistorySyncMetadataDatabase::StorageKeyFromVisitTime( + visit_row.visit_time), + _, _)) + .WillOnce([&](const std::string& storage_key, + std::unique_ptr<syncer::EntityData> put_entity, + auto* metadata_cl) { entity = std::move(*put_entity); }); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row.transition, url_row, + visit_row.visit_time); + + // Spot check some fields of the resulting entity. + ASSERT_TRUE(entity.specifics.has_history()); + const sync_pb::HistorySpecifics& history = entity.specifics.history(); + EXPECT_EQ(base::Time::FromDeltaSinceWindowsEpoch( + base::Microseconds(history.visit_time_windows_epoch_micros())), + visit_row.visit_time); + EXPECT_EQ(history.originator_cache_guid(), processor()->TrackedCacheGuid()); + ASSERT_EQ(history.redirect_entries_size(), 1); + EXPECT_EQ(history.redirect_entries(0).url(), url_row.url()); + EXPECT_TRUE(ui::PageTransitionCoreTypeIs( + syncer::FromSyncPageTransition( + history.page_transition().core_transition()), + ui::PAGE_TRANSITION_TYPED)); + EXPECT_FALSE(history.page_transition().forward_back()); + EXPECT_TRUE(history.page_transition().from_address_bar()); +} + +TEST_F(HistorySyncBridgeTest, UploadsUpdatedLocalVisit) { + // Start syncing (with no data yet). + MergeSyncData({}); + + // Visit a URL. + auto [url_row, visit_row] = AddVisitToBackendAndAdvanceClock( + GURL("https://www.url.com"), ui::PAGE_TRANSITION_TYPED); + + // Notify the bridge about the visit - it should be sent to the processor. + const std::string storage_key = + HistorySyncMetadataDatabase::StorageKeyFromVisitTime( + visit_row.visit_time); + EXPECT_CALL(*processor(), Put(storage_key, _, _)); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row.transition, url_row, + visit_row.visit_time); + + // Update the visit by adding a duration. This should result in a Put(). + const base::TimeDelta visit_duration = base::Seconds(10); + visit_row.visit_duration = visit_duration; + EXPECT_CALL(*processor(), Put(storage_key, _, _)) + .WillOnce([&](const std::string& storage_key, + std::unique_ptr<syncer::EntityData> entity, + auto* metadata_cl) { + EXPECT_EQ(base::Microseconds( + entity->specifics.history().visit_duration_micros()), + visit_duration); + }); + ASSERT_TRUE(backend()->UpdateVisit(visit_row)); + bridge()->OnVisitUpdated(visit_row); +} + +TEST_F(HistorySyncBridgeTest, UploadsLocalVisitWithRedirects) { + // Start syncing (with no data yet). + MergeSyncData({}); + + // Create a redirect chain with 3 entries. + URLRow url_row1(GURL("https://url1.com")); + URLID url_id1 = backend()->AddURL(url_row1); + url_row1.set_id(url_id1); + URLRow url_row2(GURL("https://url2.com")); + URLID url_id2 = backend()->AddURL(url_row2); + url_row2.set_id(url_id2); + URLRow url_row3(GURL("https://url3.com")); + URLID url_id3 = backend()->AddURL(url_row3); + url_row3.set_id(url_id3); + + const base::Time visit_time = base::Time::Now(); + + VisitRow visit_row1; + visit_row1.url_id = url_id1; + visit_row1.visit_time = visit_time; + visit_row1.transition = ui::PageTransitionFromInt( + ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_CHAIN_START | + ui::PAGE_TRANSITION_CLIENT_REDIRECT); + VisitID visit_id1 = backend()->AddVisit(visit_row1); + VisitRow visit_row2; + visit_row2.referring_visit = visit_id1; + visit_row2.url_id = url_id2; + visit_row2.visit_time = visit_time; + visit_row2.transition = ui::PageTransitionFromInt( + ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_SERVER_REDIRECT); + VisitID visit_id2 = backend()->AddVisit(visit_row2); + VisitRow visit_row3; + visit_row3.referring_visit = visit_id2; + visit_row3.url_id = url_id3; + visit_row3.visit_time = visit_time; + visit_row3.transition = ui::PageTransitionFromInt( + ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_CHAIN_END); + backend()->AddVisit(visit_row3); + + // Notify the bridge about all of the visits - the whole chain should result + // in a single entity being Put(). + syncer::EntityData entity; + EXPECT_CALL( + *processor(), + Put(HistorySyncMetadataDatabase::StorageKeyFromVisitTime(visit_time), _, + _)) + .WillOnce([&](const std::string& storage_key, + std::unique_ptr<syncer::EntityData> put_entity, + auto* metadata_cl) { entity = std::move(*put_entity); }); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row1.transition, url_row1, visit_time); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row2.transition, url_row2, visit_time); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row3.transition, url_row3, visit_time); + + // Check that the resulting entity contains the redirect chain. + ASSERT_TRUE(entity.specifics.has_history()); + const sync_pb::HistorySpecifics& history = entity.specifics.history(); + EXPECT_EQ(base::Time::FromDeltaSinceWindowsEpoch( + base::Microseconds(history.visit_time_windows_epoch_micros())), + visit_time); + EXPECT_EQ(history.originator_cache_guid(), processor()->TrackedCacheGuid()); + ASSERT_EQ(history.redirect_entries_size(), 3); + EXPECT_EQ(history.redirect_entries(0).url(), url_row1.url()); + EXPECT_EQ(history.redirect_entries(1).url(), url_row2.url()); + EXPECT_EQ(history.redirect_entries(2).url(), url_row3.url()); + EXPECT_TRUE(ui::PageTransitionCoreTypeIs( + syncer::FromSyncPageTransition( + history.page_transition().core_transition()), + ui::PAGE_TRANSITION_LINK)); +} + +TEST_F(HistorySyncBridgeTest, UntracksEntityOnIndividualDeletion) { + // Start syncing (with no data yet). + MergeSyncData({}); + + // Visit some URLs. + auto [url_row1, visit_row1] = AddVisitToBackendAndAdvanceClock( + GURL("https://url1.com"), ui::PAGE_TRANSITION_TYPED); + auto [url_row2, visit_row2] = AddVisitToBackendAndAdvanceClock( + GURL("https://url2.com"), ui::PAGE_TRANSITION_LINK); + + // Notify the bridge about the visits - they should be sent to the processor. + syncer::EntityData entity; + EXPECT_CALL(*processor(), Put).Times(2); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row1.transition, url_row1, + visit_row1.visit_time); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row2.transition, url_row2, + visit_row2.visit_time); + ASSERT_EQ(GetAllMetadata().size(), 2u); + + // Now delete the first URL+visit and notify the bridge. This should not + // result in any Put() or Delete() calls to the processor (deletions are + // handled through the separate HISTORY_DELETE_DIRECTIVES data type), but it + // should untrack the deleted entity. + EXPECT_CALL(*processor(), Put).Times(0); + EXPECT_CALL(*processor(), Delete).Times(0); + EXPECT_CALL(*processor(), + UntrackEntityForStorageKey( + HistorySyncMetadataDatabase::StorageKeyFromVisitTime( + visit_row1.visit_time))); + backend()->RemoveURLAndVisits(url_row1.id()); + + bridge()->OnVisitDeleted(visit_row1); + bridge()->OnURLsDeleted(/*history_backend=*/nullptr, /*all_history=*/false, + /*expired=*/false, {url_row1}, /*favicon_urls=*/{}); + // The metadata for the first (deleted) entity should be gone, but the + // metadata for the second entity should still exist. + EXPECT_EQ(GetAllMetadata().size(), 1u); +} + +TEST_F(HistorySyncBridgeTest, UntracksAllEntitiesOnAllHistoryDeletion) { + // Start syncing (with no data yet). + MergeSyncData({}); + + // Add some visits to the DB. + auto [url_row1, visit_row1] = AddVisitToBackendAndAdvanceClock( + GURL("https://url1.com"), ui::PAGE_TRANSITION_TYPED); + auto [url_row2, visit_row2] = AddVisitToBackendAndAdvanceClock( + GURL("https://url2.com"), ui::PAGE_TRANSITION_LINK); + + // Notify the bridge about the visits - they should be sent to the processor. + EXPECT_CALL(*processor(), Put).Times(2); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row1.transition, url_row1, + visit_row1.visit_time); + bridge()->OnURLVisited( + /*history_backend=*/nullptr, visit_row2.transition, url_row2, + visit_row2.visit_time); + ASSERT_EQ(GetAllMetadata().size(), 2u); + + // Now simulate a delete-all-history operation. This should not result in any + // Put() or Delete() calls on the processor (deletions are handled through the + // separate HISTORY_DELETE_DIRECTIVES data type), but it should untrack all + // entities. + EXPECT_CALL(*processor(), Put).Times(0); + EXPECT_CALL(*processor(), Delete).Times(0); + EXPECT_CALL(*processor(), UntrackEntityForStorageKey).Times(2); + backend()->Clear(); + // Deleting all history does *not* result in OnVisitDeleted() calls, and also + // does not include the actual deleted URLs in OnURLsDeleted(). + bridge()->OnURLsDeleted(/*history_backend=*/nullptr, /*all_history=*/true, + /*expired=*/false, /*deleted_rows=*/{}, + /*favicon_urls=*/{}); + EXPECT_TRUE(GetAllMetadata().empty()); +} + } // namespace } // namespace history
diff --git a/components/history/core/browser/sync/test_history_backend_for_sync.cc b/components/history/core/browser/sync/test_history_backend_for_sync.cc index 25fefc1..19ef6c0 100644 --- a/components/history/core/browser/sync/test_history_backend_for_sync.cc +++ b/components/history/core/browser/sync/test_history_backend_for_sync.cc
@@ -4,6 +4,7 @@ #include "components/history/core/browser/sync/test_history_backend_for_sync.h" +#include "base/containers/cxx20_erase_vector.h" #include "testing/gtest/include/gtest/gtest.h" namespace history { @@ -27,18 +28,112 @@ return id; } +bool TestHistoryBackendForSync::UpdateVisit(VisitRow row) { + DCHECK_NE(row.visit_id, 0); + for (VisitRow& visit : visits_) { + if (visit.visit_id == row.visit_id) { + visit = row; + return true; + } + } + return false; +} + +void TestHistoryBackendForSync::RemoveURLAndVisits(URLID url_id) { + base::EraseIf(visits_, [url_id](const VisitRow& visit) { + return visit.url_id == url_id; + }); + base::EraseIf(urls_, + [url_id](const URLRow& url) { return url.id() == url_id; }); +} + +void TestHistoryBackendForSync::Clear() { + urls_.clear(); + visits_.clear(); +} + const std::vector<URLRow>& TestHistoryBackendForSync::GetURLs() const { return urls_; } + const std::vector<VisitRow>& TestHistoryBackendForSync::GetVisits() const { return visits_; } +const URLRow* TestHistoryBackendForSync::FindURLRow(const GURL& url) const { + for (const URLRow& url_row : urls_) { + if (url_row.url() == url) { + return &url_row; + } + } + return nullptr; +} + bool TestHistoryBackendForSync::IsExpiredVisitTime( const base::Time& time) const { return time < base::Time::Now() - kExpiryThreshold; } +bool TestHistoryBackendForSync::GetURLByID(URLID url_id, URLRow* url_row) { + for (const URLRow& row : urls_) { + if (row.id() == url_id) { + *url_row = row; + return true; + } + } + return false; +} + +bool TestHistoryBackendForSync::GetLastVisitByTime(base::Time visit_time, + VisitRow* visit_row) { + *visit_row = VisitRow(); + // If there are multiple matches for `visit_time`, pick the one with the + // largest ID. + for (const VisitRow& candidate : visits_) { + if (candidate.visit_time == visit_time && + candidate.visit_id > visit_row->visit_id) { + *visit_row = candidate; + } + } + return visit_row->visit_id != 0; +} + +bool TestHistoryBackendForSync::GetMostRecentVisitsForURL(URLID id, + int max_visits, + VisitVector* visits) { + // HistorySyncBridge only ever asks for the single most-recent visit. + DCHECK_EQ(max_visits, 1); + + visits->clear(); + for (const VisitRow& candidate : visits_) { + if (candidate.url_id == id) { + if (visits->empty()) { + visits->push_back(candidate); + } else if (candidate.visit_time > (*visits)[0].visit_time || + (candidate.visit_time == (*visits)[0].visit_time && + candidate.visit_id > (*visits)[0].visit_id)) { + (*visits)[0] = candidate; + } + } + } + return !visits->empty(); +} + +VisitVector TestHistoryBackendForSync::GetRedirectChain(VisitRow visit) { + VisitVector result; + result.push_back(visit); + while (!(visit.transition & ui::PAGE_TRANSITION_CHAIN_START)) { + if (!FindVisit(visit.referring_visit, &visit)) { + ADD_FAILURE() << "Data error: referring_visit " << visit.referring_visit + << " not found"; + return {}; + } + result.push_back(visit); + } + std::reverse(result.begin(), result.end()); + return result; +} + VisitID TestHistoryBackendForSync::AddSyncedVisit(const GURL& url, const std::u16string& title, bool hidden, @@ -68,6 +163,25 @@ return false; } +void TestHistoryBackendForSync::AddObserver(HistoryBackendObserver* observer) { + observers_.AddObserver(observer); +} + +void TestHistoryBackendForSync::RemoveObserver( + HistoryBackendObserver* observer) { + observers_.RemoveObserver(observer); +} + +bool TestHistoryBackendForSync::FindVisit(VisitID id, VisitRow* result) { + for (const VisitRow& candidate : visits_) { + if (candidate.visit_id == id) { + *result = candidate; + return true; + } + } + return false; +} + const URLRow& TestHistoryBackendForSync::FindOrAddURL( const GURL& url, const std::u16string& title,
diff --git a/components/history/core/browser/sync/test_history_backend_for_sync.h b/components/history/core/browser/sync/test_history_backend_for_sync.h index 758b573..53b7f82e 100644 --- a/components/history/core/browser/sync/test_history_backend_for_sync.h +++ b/components/history/core/browser/sync/test_history_backend_for_sync.h
@@ -23,21 +23,38 @@ TestHistoryBackendForSync(); ~TestHistoryBackendForSync(); + // Methods to manipulate the contents. These do *not* notify the observers. URLID AddURL(URLRow row); VisitID AddVisit(VisitRow row); + bool UpdateVisit(VisitRow row); + void RemoveURLAndVisits(URLID url_id); + void Clear(); + + // Direct access to the contents. const std::vector<URLRow>& GetURLs() const; const std::vector<VisitRow>& GetVisits() const; + const URLRow* FindURLRow(const GURL& url) const; // HistoryBackendForSync implementation. bool IsExpiredVisitTime(const base::Time& time) const override; + bool GetURLByID(URLID url_id, URLRow* url_row) override; + bool GetLastVisitByTime(base::Time visit_time, VisitRow* visit_row) override; + bool GetMostRecentVisitsForURL(URLID id, + int max_visits, + VisitVector* visits) override; + VisitVector GetRedirectChain(VisitRow visit) override; VisitID AddSyncedVisit(const GURL& url, const std::u16string& title, bool hidden, const VisitRow& visit) override; bool UpdateSyncedVisit(const VisitRow& visit) override; + void AddObserver(HistoryBackendObserver* observer) override; + void RemoveObserver(HistoryBackendObserver* observer) override; private: + bool FindVisit(VisitID id, VisitRow* result); + const URLRow& FindOrAddURL(const GURL& url, const std::u16string& title, bool hidden); @@ -46,6 +63,8 @@ URLID next_url_id_ = 1; std::vector<VisitRow> visits_; VisitID next_visit_id_ = 1; + + base::ObserverList<HistoryBackendObserver, true>::Unchecked observers_; }; } // namespace history
diff --git a/components/history/core/browser/sync/typed_url_sync_bridge.cc b/components/history/core/browser/sync/typed_url_sync_bridge.cc index 3dfc7b74b..585bffc 100644 --- a/components/history/core/browser/sync/typed_url_sync_bridge.cc +++ b/components/history/core/browser/sync/typed_url_sync_bridge.cc
@@ -479,6 +479,10 @@ } } +void TypedURLSyncBridge::OnVisitUpdated(const VisitRow& visit) {} + +void TypedURLSyncBridge::OnVisitDeleted(const VisitRow& visit) {} + void TypedURLSyncBridge::Init() { DCHECK(sequence_checker_.CalledOnValidSequence());
diff --git a/components/history/core/browser/sync/typed_url_sync_bridge.h b/components/history/core/browser/sync/typed_url_sync_bridge.h index c2b6206..f697a69 100644 --- a/components/history/core/browser/sync/typed_url_sync_bridge.h +++ b/components/history/core/browser/sync/typed_url_sync_bridge.h
@@ -67,6 +67,8 @@ bool expired, const std::vector<URLRow>& deleted_rows, const std::set<GURL>& favicon_urls) override; + void OnVisitUpdated(const VisitRow& visit) override; + void OnVisitDeleted(const VisitRow& visit) override; // Must be called after creation and before any operations. void Init();
diff --git a/components/keyed_service/core/dependency_manager.cc b/components/keyed_service/core/dependency_manager.cc index d8409ef..f46f63f 100644 --- a/components/keyed_service/core/dependency_manager.cc +++ b/components/keyed_service/core/dependency_manager.cc
@@ -12,6 +12,8 @@ #include "base/notreached.h" #include "base/supports_user_data.h" #include "components/keyed_service/core/keyed_service_base_factory.h" +#include "components/keyed_service/core/keyed_service_factory.h" +#include "components/keyed_service/core/refcounted_keyed_service_factory.h" #ifndef NDEBUG #include "base/files/file_path.h" @@ -102,6 +104,14 @@ ShutdownFactoriesInOrder(context, destruction_order); MarkContextDead(context); DestroyFactoriesInOrder(context, destruction_order); + + int context_service_count = + KeyedServiceFactory::GetServicesCount(context) + + RefcountedKeyedServiceFactory::GetServicesCount(context); + // At this point all services for a specific context should be destroyed. + // If this is not the case, it means that a service was created but not + // destroyed properly, potentially due to a wrong dependency declaration + DCHECK_EQ(context_service_count, 0); } // static
diff --git a/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java b/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java index 086ce7ae..a14bb25 100644 --- a/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java +++ b/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java
@@ -141,6 +141,8 @@ return "Translate"; case MessageIdentifier.OFFER_NOTIFICATION: return "OfferNotification"; + case MessageIdentifier.EXTERNAL_NAVIGATION: + return "ExternalNavigation"; default: return "Unknown"; }
diff --git a/components/messages/android/message_enums.h b/components/messages/android/message_enums.h index 3624702..0bc4517 100644 --- a/components/messages/android/message_enums.h +++ b/components/messages/android/message_enums.h
@@ -108,6 +108,7 @@ ABOUT_THIS_SITE = 28, TRANSLATE = 29, OFFER_NOTIFICATION = 30, + EXTERNAL_NAVIGATION = 31, // Insert new values before this line. COUNT
diff --git a/components/metrics/clean_exit_beacon.cc b/components/metrics/clean_exit_beacon.cc index d8f2e42..01af8408 100644 --- a/components/metrics/clean_exit_beacon.cc +++ b/components/metrics/clean_exit_beacon.cc
@@ -85,42 +85,64 @@ // Increments kVariationsCrashStreak if |did_previous_session_exit_cleanly| is // false. Also, emits the crash streak to a histogram. // -// Either |beacon_file_contents| or |local_state| is used to retrieve the crash -// streak depending on the client's Extended Variations Safe Mode experiment -// group in the last session. +// If |beacon_file_contents| are given, then the beacon file is used to retrieve +// the crash streak. Otherwise, |local_state| is used. void MaybeIncrementCrashStreak(bool did_previous_session_exit_cleanly, base::Value* beacon_file_contents, PrefService* local_state) { - int num_crashes = - beacon_file_contents - ? beacon_file_contents->FindKey(kVariationsCrashStreak)->GetInt() - : local_state->GetInteger(kVariationsCrashStreak); + int num_crashes; + if (beacon_file_contents) { + absl::optional<int> crash_streak = + beacon_file_contents->GetDict().FindInt(kVariationsCrashStreak); + // Any contents without the key should have been rejected by + // MaybeGetFileContents(). + DCHECK(crash_streak); + num_crashes = crash_streak.value(); + } else { + // TODO(crbug/1341087): Consider not falling back to Local State for clients + // on platforms that support the beacon file. + num_crashes = local_state->GetInteger(kVariationsCrashStreak); + } - // Increment the crash streak if the previous session crashed. Note that the - // streak is not cleared if the previous run didn’t crash. Instead, it’s - // incremented on each crash until Chrome is able to successfully fetch a new - // seed. This way, a seed update that mostly destabilizes Chrome still results - // in a fallback to safe mode. - // - // The crash streak is incremented here rather than in a variations-related - // class for two reasons. First, the crash streak depends on the value of - // kStabilityExitedCleanly. Second, if kVariationsCrashStreak were updated in - // another function, any crash between CleanExitBeacon() and that function - // would cause the crash streak to not be to incremented. A consequence of - // failing to increment the crash streak is that Variations Safe Mode might - // undercount or be completely unaware of repeated crashes early on in - // startup. if (!did_previous_session_exit_cleanly) { + // Increment the crash streak if the previous session crashed. Note that the + // streak is not cleared if the previous run didn’t crash. Instead, it’s + // incremented on each crash until Chrome is able to successfully fetch a + // new seed. This way, a seed update that mostly destabilizes Chrome still + // results in a fallback to Variations Safe Mode. + // + // The crash streak is incremented here rather than in a variations-related + // class for two reasons. First, the crash streak depends on whether Chrome + // exited cleanly in the last session, which is first checked via + // CleanExitBeacon::Initialize(). Second, if the crash streak were updated + // in another function, any crash between beacon initialization and the + // other function might cause the crash streak to not be to incremented. + // "Might" because the updated crash streak also needs to be persisted to + // disk. A consequence of failing to increment the crash streak is that + // Chrome might undercount or be completely unaware of repeated crashes + // early on in startup. ++num_crashes; + // For platforms that use the beacon file, the crash streak is written + // synchronously to disk later on in startup via + // MaybeExtendVariationsSafeMode() and WriteBeaconFile(). The crash streak + // is intentionally not written to the beacon file here. If the beacon file + // indicates that Chrome failed to exit cleanly, then Chrome got at + // least as far as MaybeExtendVariationsSafeMode(), which is during the + // PostEarlyInitialization stage when native code is being synchronously + // executed. Chrome should also be able to reach that point in this session. + // + // For platforms that do not use the beacon file, the crash streak is + // scheduled to be written to disk later on in startup. At the latest, this + // is done when a Local State write is scheduled via WriteBeaconFile(). A + // write is not scheduled here for three reasons. + // + // 1. It is an expensive operation. + // 2. Android WebLayer (one of the two platforms that does not use the + // beacon file) did not appear to benefit from scheduling the write. See + // crbug/1341850 for details. + // 3. Android WebView (the other beacon-file-less platform) has its own + // Variations Safe Mode mechanism and does not need the crash streak. local_state->SetInteger(kVariationsCrashStreak, num_crashes); -#if BUILDFLAG(IS_ANDROID) - // Schedule a Local State write on Android Chrome, WebLayer, and WebView - // only as this write is expensive, and other platforms use the beacon file - // as the source of truth. For other platforms, the crask streak is written - // synchronously to disk later on in startup. See - // MaybeExtendVariationsSafeMode() and WriteBeaconValue(). - local_state->CommitPendingWrite(); -#endif } base::UmaHistogramSparse("Variations.SafeMode.Streak.Crashes", base::clamp(num_crashes, 0, 100)); @@ -140,17 +162,15 @@ // 3. The file is successfully read. // 4. The file contents are in the expected format with the expected info. // -// The file is not expected to exist for clients that have never been in the -// Extended Variations Safe Mode experiment's enabled group. Also, the file may -// not exist for all enabled-group clients because there are some edge cases. -// First, MaybeGetFileContents() is called before clients are assigned to an -// Extended Variations Safe Mode experiment group, so a client that is later -// assigned to the enabled group will not have the file in the first session -// after updating to or installing a Chrome version with the experiment. Second, -// Android Chrome enabled-group clients with repeated background sessions may -// never write a beacon file. Third, it is possible for a user to delete the -// file or to switch groups by resetting their variations state. Finally, -// clients also switch groups when the FieldTrial name is updated. +// The file may not exist for the below reasons: +// +// 1. The file is unsupported on the platform. +// 2. This is the first session after a client updates to or installs a Chrome +// version that uses the beacon file. The beacon file launched on desktop +// and iOS in M102 and on Android Chrome in M103. +// 3. Android Chrome clients with only background sessions may never write a +// beacon file. +// 4. A user may delete the file. std::unique_ptr<base::Value> MaybeGetFileContents( const base::FilePath& beacon_file_path) { if (beacon_file_path.empty()) @@ -271,9 +291,8 @@ : local_state_beacon_value.value_or(true); #if BUILDFLAG(IS_IOS) - // For the time being, this is a no-op to avoid interference with the Extended - // Variations Safe Mode experiment; i.e., ShouldUseUserDefaultsBeacon() always - // returns false. + // TODO(crbug/1231106): For the time being, this is a no-op; i.e., + // ShouldUseUserDefaultsBeacon() always returns false. if (ShouldUseUserDefaultsBeacon()) return backup_beacon_value.value_or(true); #endif // BUILDFLAG(IS_IOS)
diff --git a/components/metrics/clean_exit_beacon.h b/components/metrics/clean_exit_beacon.h index 868e2de..a919f34 100644 --- a/components/metrics/clean_exit_beacon.h +++ b/components/metrics/clean_exit_beacon.h
@@ -55,8 +55,10 @@ // process exited cleanly. class CleanExitBeacon { public: - // Instantiates a CleanExitBeacon whose value is stored in |local_state|'s - // kStabilityExitedCleanly pref. |local_state| must be fully initialized. + // Instantiates a CleanExitBeacon whose value is stored in + // |has_exited_cleanly_|. The value is persisted in the beacon file on + // platforms that support this mechanism and in Local State on platforms that + // don't. // // On Windows, |backup_registry_key| stores a backup of the beacon to verify // that the pref's value corresponds to the registry's. |backup_registry_key| @@ -64,7 +66,7 @@ // mechanism embedded inside CleanExitBeacon. // // |user_data_dir| is the path to the client's user data directory. If empty, - // a separate file will not be used for Variations Safe Mode prefs. + // the beacon file is not used. // // TODO(crbug/1241702): Remove |channel| at the end of the Extended Variations // Safe Mode experiment. |channel| is used to enable the experiment on only @@ -94,14 +96,19 @@ return initial_browser_last_live_timestamp_; } - // Sets the beacon value to |exited_cleanly| and updates the last live - // timestamp. If |is_extended_safe_mode| is true, then the beacon value is - // written to disk synchronously. If false, a write is scheduled, and for - // clients in the Extended Variations Safe Mode experiment, a synchronous - // write is done, too. + // Sets the beacon value to |exited_cleanly| and writes the value to disk if + // the current value (see has_exited_cleanly_) is not already + // |exited_cleanly|. Note that on platforms that do not support the beacon + // file, the write is scheduled, so the value may not be persisted if the + // browser process crashes. // - // Note: |is_extended_safe_mode| should be true only for some clients in the - // Extended Variations Safe Mode experiment. + // Also, updates the last live timestamp. + // + // |is_extended_safe_mode| denotes whether Chrome is about to start watching + // for browser crashes early on in startup as a part of Extended Variations + // Safe Mode, which is supported by most, but not all, platforms. + // + // TODO(crbug/1341125): Consider removing |is_extended_safe_mode|. void WriteBeaconValue(bool exited_cleanly, bool is_extended_safe_mode = false); @@ -147,12 +154,10 @@ private: // Returns true if the previous session exited cleanly. Either Local State // or |beacon_file_contents| is used to get this information. Which is used - // depends on the client's Extended Variations Safe Mode experiment group in - // the previous session. Also, records several metrics. + // depends on the client's platform and the existence of a valid beacon file. + // Also, records several metrics. // // Should be called only once: at startup. - // - // TODO(crbug/1241702): Update this comment when experimentation is over. bool DidPreviousSessionExitCleanly(base::Value* beacon_file_contents); // Writes |exited_cleanly| and the crash streak to the file located at @@ -207,8 +212,8 @@ // unset, Chrome has neither started nor stopped watching for crashes. absl::optional<bool> has_exited_cleanly_ = absl::nullopt; - // Where the clean exit beacon and the variations crash streak may be stored - // for some clients in the Extended Variations Safe Mode experiment. + // Where the clean exit beacon and the variations crash streak are stored on + // platforms that support the beacon file. base::FilePath beacon_file_path_; };
diff --git a/components/page_load_metrics/browser/observers/prerender_page_load_metrics_observer.cc b/components/page_load_metrics/browser/observers/prerender_page_load_metrics_observer.cc index 0722866..917ae1d 100644 --- a/components/page_load_metrics/browser/observers/prerender_page_load_metrics_observer.cc +++ b/components/page_load_metrics/browser/observers/prerender_page_load_metrics_observer.cc
@@ -9,6 +9,7 @@ #include "components/page_load_metrics/browser/observers/core/largest_contentful_paint_handler.h" #include "components/page_load_metrics/browser/page_load_metrics_util.h" #include "content/public/browser/navigation_handle.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_builders.h" @@ -49,11 +50,13 @@ return STOP_OBSERVING; } -// TODO(https://crbug.com/1317494): Audit and use appropriate policy. page_load_metrics::PageLoadMetricsObserver::ObservePolicy PrerenderPageLoadMetricsObserver::OnFencedFramesStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url) { + // TODO(https://crbug.com/1335481): Prerendering pages embedding FencedFrames + // are not supported. So, this class doesn't need forwarding. + DCHECK(!navigation_handle->IsInPrerenderedMainFrame()); return STOP_OBSERVING; } @@ -61,6 +64,10 @@ PrerenderPageLoadMetricsObserver::OnPrerenderStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url) { + // TODO(https://crbug.com/1335481): Prerendering pages embedding FencedFrames + // are not supported. + DCHECK(navigation_handle->GetNavigatingFrameType() != + content::FrameType::kFencedFrameRoot); return CONTINUE_OBSERVING; }
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java b/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java index 4843785..2815e56 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java
@@ -197,18 +197,6 @@ } /** - * Records amount of completed/triggered transactions separated by currency. - * - * @param curreny A string indicating the curreny of the transaction. - * @param value A string indicating the value of the transaction. - * @param completed A boolean indicating whether the transaction has completed or not. - */ - public void recordTransactionAmount(String currency, String value, boolean completed) { - JourneyLoggerJni.get().recordTransactionAmount( - mJourneyLoggerAndroid, JourneyLogger.this, currency, value, completed); - } - - /** * Records that the payment request has entered the given checkout step. * @param step An int indicating the step to be recorded. */ @@ -217,13 +205,6 @@ } /** - * Records the time when request.show() is called. - */ - public void setTriggerTime() { - JourneyLoggerJni.get().setTriggerTime(mJourneyLoggerAndroid, JourneyLogger.this); - } - - /** * Sets the ukm source id of payment app. * @param sourceId A long indicating the ukm source id of the invoked payment app. */ @@ -259,10 +240,7 @@ void setCompleted(long nativeJourneyLoggerAndroid, JourneyLogger caller); void setAborted(long nativeJourneyLoggerAndroid, JourneyLogger caller, int reason); void setNotShown(long nativeJourneyLoggerAndroid, JourneyLogger caller, int reason); - void recordTransactionAmount(long nativeJourneyLoggerAndroid, JourneyLogger caller, - String currency, String value, boolean completed); void recordCheckoutStep(long nativeJourneyLoggerAndroid, JourneyLogger caller, int step); - void setTriggerTime(long nativeJourneyLoggerAndroid, JourneyLogger caller); void setPaymentAppUkmSourceId( long nativeJourneyLoggerAndroid, JourneyLogger caller, long sourceId); }
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java index 5ffc026..93df09ae 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java
@@ -900,8 +900,6 @@ @Nullable private String onShowCalledAndAppsQueriedAndDetailsFinalized() { assert mSpec.getRawTotal() != null; - mJourneyLogger.recordTransactionAmount(mSpec.getRawTotal().amount.currency, - mSpec.getRawTotal().amount.value, false /*completed*/); if (isSecurePaymentConfirmationApplicable()) { assert mBrowserPaymentRequest.getSelectedPaymentApp() != null; assert mSpcAuthnUiController == null; @@ -1197,8 +1195,6 @@ mIsShowCalled = true; mIsShowWaitingForUpdatedDetails = waitForUpdatedDetails; - mJourneyLogger.setTriggerTime(); - if (mIsFinishedQueryingPaymentApps) { PaymentNotShownError notShownError = onShowCalledAndAppsQueried(); if (notShownError != null) { @@ -1406,8 +1402,6 @@ if (result != PaymentComplete.FAIL) { mJourneyLogger.setCompleted(); assert mSpec.getRawTotal() != null; - mJourneyLogger.recordTransactionAmount(mSpec.getRawTotal().amount.currency, - mSpec.getRawTotal().amount.value, true /*completed*/); } mBrowserPaymentRequest.complete(result, this::onCompleteHandled);
diff --git a/components/payments/content/android/journey_logger_android.cc b/components/payments/content/android/journey_logger_android.cc index 0c71ca2..9df6fb1f 100644 --- a/components/payments/content/android/journey_logger_android.cc +++ b/components/payments/content/android/journey_logger_android.cc
@@ -156,17 +156,6 @@ static_cast<JourneyLogger::NotShownReason>(jreason)); } -void JourneyLoggerAndroid::RecordTransactionAmount( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& jcaller, - const base::android::JavaParamRef<jstring>& jcurrency, - const base::android::JavaParamRef<jstring>& jvalue, - jboolean jcompleted) { - journey_logger_.RecordTransactionAmount( - ConvertJavaStringToUTF8(env, jcurrency), - ConvertJavaStringToUTF8(env, jvalue), jcompleted); -} - void JourneyLoggerAndroid::RecordCheckoutStep( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, @@ -175,12 +164,6 @@ static_cast<JourneyLogger::CheckoutFunnelStep>(jstep)); } -void JourneyLoggerAndroid::SetTriggerTime( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& jcaller) { - journey_logger_.SetTriggerTime(); -} - void JourneyLoggerAndroid::SetPaymentAppUkmSourceId( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller,
diff --git a/components/payments/content/android/journey_logger_android.h b/components/payments/content/android/journey_logger_android.h index d9fed17..df8cb9ed 100644 --- a/components/payments/content/android/journey_logger_android.h +++ b/components/payments/content/android/journey_logger_android.h
@@ -73,17 +73,9 @@ void SetNotShown(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, jint jreason); - void RecordTransactionAmount( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& jcaller, - const base::android::JavaParamRef<jstring>& jcurrency, - const base::android::JavaParamRef<jstring>& jvalue, - jboolean jcompleted); void RecordCheckoutStep(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, jint jstep); - void SetTriggerTime(JNIEnv* env, - const base::android::JavaParamRef<jobject>& jcaller); void SetPaymentAppUkmSourceId( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller,
diff --git a/components/payments/content/android/junit/src/org/chromium/components/payments/PaymentRequestServiceTest.java b/components/payments/content/android/junit/src/org/chromium/components/payments/PaymentRequestServiceTest.java index a95c00a..9c45606e 100644 --- a/components/payments/content/android/junit/src/org/chromium/components/payments/PaymentRequestServiceTest.java +++ b/components/payments/content/android/junit/src/org/chromium/components/payments/PaymentRequestServiceTest.java
@@ -254,11 +254,6 @@ .showOrSkipAppSelector(Mockito.anyBoolean(), Mockito.any(), Mockito.anyBoolean()); } - private void verifyJourneyLoggerRecordedTransactionAmount() { - Mockito.verify(mJourneyLogger, Mockito.times(1)) - .recordTransactionAmount(Mockito.eq("CNY"), Mockito.eq("123"), Mockito.eq(false)); - } - private void verifyContinuedShowWithUpdatedDetails(int times) { Mockito.verify(mBrowserPaymentRequest, Mockito.times(times)) .continueShowWithUpdatedDetails(Mockito.any(), Mockito.anyBoolean()); @@ -623,8 +618,6 @@ queryPaymentApps(); Mockito.verify(mBrowserPaymentRequest, Mockito.times(1)) .onShowCalledAndAppsQueriedAndDetailsFinalized(); - - verifyJourneyLoggerRecordedTransactionAmount(); } @Test @@ -640,8 +633,6 @@ updateWith(service); Mockito.verify(mBrowserPaymentRequest, Mockito.times(1)) .onShowCalledAndAppsQueriedAndDetailsFinalized(); - - verifyJourneyLoggerRecordedTransactionAmount(); } @Test @@ -657,8 +648,6 @@ queryPaymentApps(); Mockito.verify(mBrowserPaymentRequest, Mockito.times(1)) .onShowCalledAndAppsQueriedAndDetailsFinalized(); - - verifyJourneyLoggerRecordedTransactionAmount(); } @Test
diff --git a/components/payments/content/payment_request.cc b/components/payments/content/payment_request.cc index 25b7d02..1ee417367 100644 --- a/components/payments/content/payment_request.cc +++ b/components/payments/content/payment_request.cc
@@ -291,7 +291,6 @@ journey_logger_.RecordCheckoutStep( JourneyLogger::CheckoutFunnelStep::kShowCalled); is_show_called_ = true; - journey_logger_.SetTriggerTime(); // A tab can display only one PaymentRequest UI at a time. if (display_manager_) @@ -328,9 +327,6 @@ spec_->AddInitializationObserver(this); } else { DCHECK(spec_->details().total); - journey_logger_.RecordTransactionAmount( - spec_->details().total->amount->currency, - spec_->details().total->amount->value, false /*completed*/); } // If an app store billing payment method is one of the payment methods being @@ -424,9 +420,6 @@ if (is_resolving_promise_passed_into_show_method) { DCHECK(spec_->details().total); - journey_logger_.RecordTransactionAmount( - spec_->details().total->amount->currency, - spec_->details().total->amount->value, false /*completed*/); if (is_requested_methods_supported_invoked_) { if (SatisfiesSkipUIConstraints()) { Pay(); @@ -525,9 +518,6 @@ journey_logger_.SetCompleted(); has_recorded_completion_ = true; DCHECK(spec_->details().total); - journey_logger_.RecordTransactionAmount( - spec_->details().total->amount->currency, - spec_->details().total->amount->value, true /*completed*/); delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted, true);
diff --git a/components/payments/core/journey_logger.cc b/components/payments/core/journey_logger.cc index 8ed3204..48df8cc 100644 --- a/components/payments/core/journey_logger.cc +++ b/components/payments/core/journey_logger.cc
@@ -71,15 +71,6 @@ return seen_true_bit; } -// Records time to checkout for payment requests. The 5-minute max is chosen -// since the payment handler window times out after 5 minutes. -void RecordTimeToCheckoutUmaHistograms(const std::string name, - const base::TimeDelta time_to_checkout) { - UmaHistogramCustomTimes(name, time_to_checkout, - base::Milliseconds(1) /* min */, - base::Minutes(5) /* max */, 100 /*bucket count*/); -} - } // namespace JourneyLogger::JourneyLogger(bool is_incognito, @@ -291,56 +282,6 @@ NOT_SHOWN_REASON_MAX); } -void JourneyLogger::RecordTransactionAmount(std::string currency, - const std::string& value, - bool completed) { - DCHECK(!has_recorded_transaction_amount_[completed]); - has_recorded_transaction_amount_[completed] = true; - double amount = -1; - if (!base::StringToDouble(value, &amount) || amount < 0) - return; - - std::string completion_suffix = completed ? ".Completed" : ".Triggered"; - // The currency should be three upper-case characters between A and Z. - DCHECK(re2::RE2::FullMatch(currency, "^[A-Z]{3}$")); - // A dictionary of 3-letter recorded currency codes and their approximated USD - // conversion rates. Transaction currencies in currency_conversion_rates are - // recorded after conversion. - // Conversion rates last updated on April 9, 2021 - const std::unordered_map<std::string, float> currency_conversion_rates = { - {"USD", 1.0}, {"EUR", 1.19}, {"GBP", 1.37}, {"JPY", 0.0091}, - {"INR", 0.013}, {"CNY", 0.15}, {"CAD", 0.80}, {"RUB", 0.013}, - {"PLN", 0.26}, {"AUD", 0.76}, {"BRL", 0.18}, {"UAH", 0.036}, - {"TWD", 0.035}, {"CZK", 0.046}, {"MXN", 0.050}, {"SGD", 0.75}}; - std::unordered_map<std::string, float>::const_iterator it = - currency_conversion_rates.find(currency); - // transactions with currencies not included in the conversion dictionary are - // not recorded at this point. - if (it == currency_conversion_rates.end()) - return; - - // Approximately convert the transaction amount to USD and map it to one of - // the following categories: 1-zero transactions 2- micro transactions (<= $1) - // 3- regular transactions. - double converted_amount = amount * it->second; - TransactionSize transaction_size = TransactionSize::kRegularTransaction; - if (converted_amount == 0) - transaction_size = TransactionSize::kZeroTransaction; - else if (converted_amount <= 1) - transaction_size = TransactionSize::kMicroTransaction; - base::UmaHistogramEnumeration( - "PaymentRequest.TransactionAmount" + completion_suffix, transaction_size); - - if (payment_request_source_id_ == ukm::kInvalidSourceId) - return; - - // Record the transaction amount in UKM. - ukm::builders::PaymentRequest_TransactionAmount(payment_request_source_id_) - .SetCompletionStatus(completed) - .SetCategory(static_cast<int64_t>(transaction_size)) - .Record(ukm::UkmRecorder::Get()); -} - void JourneyLogger::RecordCheckoutStep(CheckoutFunnelStep step) { base::UmaHistogramEnumeration("PaymentRequest.CheckoutFunnel", step); } @@ -354,7 +295,6 @@ has_recorded_ = true; RecordEventsMetric(completion_status); - RecordTimeToCheckout(completion_status); // Depending on the completion status record kPaymentRequestTriggered and/or // kCompleted checkout steps. @@ -471,76 +411,6 @@ payment_app_source_id_ = ukm::kInvalidSourceId; } -void JourneyLogger::RecordTimeToCheckout( - CompletionStatus completion_status) const { - const base::TimeDelta time_to_checkout = - base::TimeTicks::Now() - trigger_time_; - const std::string histogram_name = "PaymentRequest.TimeToCheckout"; - - // Whether or not the payment sheet was shown shown. - std::string ui_show_suffix; - if (events_ & EVENT_SHOWN) - ui_show_suffix = ".Shown"; - else if (events_ & EVENT_SKIPPED_SHOW) - ui_show_suffix = ".SkippedShow"; - else // User aborted before request.show() - ui_show_suffix = ".BeforeShow"; - - std::string completion_suffix; - switch (completion_status) { - case COMPLETION_STATUS_COMPLETED: { - completion_suffix = ".Completed"; - // Record time to checkout for completed requests separated by payment - // sheet shown status. Requests can complete only after request.show() - // call. - DCHECK_NE(".BeforeShow", ui_show_suffix); - RecordTimeToCheckoutUmaHistograms( - histogram_name + ".Completed" + ui_show_suffix, time_to_checkout); - - // Record time to checkout for completed requests separated by payment - // sheet shown status and selected method. - std::string selected_method_suffix; - if (WasOccurred(Event2::kSelectedCreditCard)) { - selected_method_suffix = ".BasicCard"; - } else if (WasOccurred(Event2::kSelectedGoogle)) { - selected_method_suffix = ".Google"; - } else if (WasOccurred(Event2::kSelectedPlayBilling)) { - selected_method_suffix = ".PlayBilling"; - } else if (WasOccurred(Event2::kSelectedSecurePaymentConfirmation)) { - selected_method_suffix = ".SecurePaymentConfirmation"; - } else { - DCHECK(WasOccurred(Event2::kSelectedOther)); - selected_method_suffix = ".Other"; - } - RecordTimeToCheckoutUmaHistograms(histogram_name + ".Completed" + - ui_show_suffix + - selected_method_suffix, - time_to_checkout); - break; - } - case COMPLETION_STATUS_USER_ABORTED: { - completion_suffix = ".UserAborted"; - // Record time to checkout for requests aborted by user separated by - // payment sheet shown status. - RecordTimeToCheckoutUmaHistograms( - histogram_name + ".UserAborted" + ui_show_suffix, time_to_checkout); - break; - } - case COMPLETION_STATUS_OTHER_ABORTED: - completion_suffix = ".OtherAborted"; - break; - case COMPLETION_STATUS_COULD_NOT_SHOW: - // Do not record checkout duration when payment sheet could not shown. - return; - default: - NOTREACHED(); - } - // Record time to checkout for payment reuqests separated by completion - // status. - RecordTimeToCheckoutUmaHistograms(histogram_name + completion_suffix, - time_to_checkout); -} - bool JourneyLogger::WasOccurred(Event2 event) const { return events2_ & static_cast<int>(event); } @@ -640,10 +510,6 @@ return (events_ & EVENT_SHOWN) > 0 || (events_ & EVENT_SKIPPED_SHOW) > 0; } -void JourneyLogger::SetTriggerTime() { - trigger_time_ = base::TimeTicks::Now(); -} - void JourneyLogger::SetPaymentAppUkmSourceId( ukm::SourceId payment_app_source_id) { payment_app_source_id_ = payment_app_source_id;
diff --git a/components/payments/core/journey_logger.h b/components/payments/core/journey_logger.h index 1031136..d9abbe872 100644 --- a/components/payments/core/journey_logger.h +++ b/components/payments/core/journey_logger.h
@@ -205,18 +205,6 @@ NOT_SHOWN_REASON_MAX = 4, }; - // Transactions fall in one of the following categories after converting to - // USD. - enum class TransactionSize { - // 0$ transactions. - kZeroTransaction = 0, - // Transaction value <= 1$. - kMicroTransaction = 1, - // Transaction value > 1$. - kRegularTransaction = 2, - kMaxValue = kRegularTransaction, - }; - // The categories of the payment methods. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.payments // GENERATED_JAVA_CLASS_NAME_OVERRIDE: PaymentMethodCategory @@ -318,18 +306,9 @@ // reason. void SetNotShown(NotShownReason reason); - // Records the transaction amount after converting to USD separated by - // completion status (complete vs triggered). - void RecordTransactionAmount(std::string currency, - const std::string& value, - bool completed); - // Increments the bucket count for the given checkout step. void RecordCheckoutStep(CheckoutFunnelStep step); - // Records when Payment Request .show is called. - void SetTriggerTime(); - // Sets the UKM source id of the selected app when it gets invoked. void SetPaymentAppUkmSourceId(ukm::SourceId payment_app_source_id); @@ -381,9 +360,6 @@ // Payment Request. void RecordEventsMetric(CompletionStatus completion_status); - // Records the time between request.show() and request completion/abort. - void RecordTimeToCheckout(CompletionStatus completion_status) const; - // Validates the recorded event sequence during the Payment Request. void ValidateEventBits() const; @@ -406,14 +382,6 @@ // The 2.0 version of event_. int events2_; - // Keeps track of whether transaction amounts are recorded or not to catch - // multiple recording. Triggered is the first index and Completed the second. - bool has_recorded_transaction_amount_[2] = {false}; - - // Stores the time that request.show() is called. This is used to record - // checkout duration. - base::TimeTicks trigger_time_; - ukm::SourceId payment_request_source_id_; ukm::SourceId payment_app_source_id_ = ukm::kInvalidSourceId;
diff --git a/components/performance_manager/decorators/process_metrics_decorator.cc b/components/performance_manager/decorators/process_metrics_decorator.cc index 0ff4199..2afac83 100644 --- a/components/performance_manager/decorators/process_metrics_decorator.cc +++ b/components/performance_manager/decorators/process_metrics_decorator.cc
@@ -114,8 +114,7 @@ // fresh data. // TODO(sebmarchand): Measure the performance impact of this. if (base::FeatureList::IsEnabled( - features::kUrgentDiscardingFromPerformanceManager) || - base::FeatureList::IsEnabled(features::kHighPMFDiscardPolicy)) { + features::kUrgentDiscardingFromPerformanceManager)) { refresh_period = kFastRefreshTimerPeriod; } #endif
diff --git a/components/performance_manager/execution_context_priority/boosting_vote_aggregator.h b/components/performance_manager/execution_context_priority/boosting_vote_aggregator.h index 105be2d..ad48bc3 100644 --- a/components/performance_manager/execution_context_priority/boosting_vote_aggregator.h +++ b/components/performance_manager/execution_context_priority/boosting_vote_aggregator.h
@@ -271,8 +271,9 @@ const ExecutionContext* dst() const { return dst_; } private: - raw_ptr<const ExecutionContext> src_ = nullptr; - raw_ptr<const ExecutionContext> dst_ = nullptr; + // TODO(crbug.com/1298696): Breaks component_unittests. + raw_ptr<const ExecutionContext, DegradeToNoOpWhenMTE> src_ = nullptr; + raw_ptr<const ExecutionContext, DegradeToNoOpWhenMTE> dst_ = nullptr; }; using ForwardEdge = Edge<true>; using ReverseEdge = Edge<false>;
diff --git a/components/performance_manager/features.cc b/components/performance_manager/features.cc index 67ce5ff..6b8aa89 100644 --- a/components/performance_manager/features.cc +++ b/components/performance_manager/features.cc
@@ -47,9 +47,6 @@ "BackgroundTabLoadingFromPerformanceManager", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kHighPMFDiscardPolicy{"HighPMFDiscardPolicy", - base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kHighEfficiencyModeAvailable{ "HighEfficiencyModeAvailable", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/performance_manager/graph/page_node_impl_unittest.cc b/components/performance_manager/graph/page_node_impl_unittest.cc index ddc3963e..eb01a7de 100644 --- a/components/performance_manager/graph/page_node_impl_unittest.cc +++ b/components/performance_manager/graph/page_node_impl_unittest.cc
@@ -256,7 +256,8 @@ } private: - raw_ptr<const PageNode> notified_page_node_ = nullptr; + // TODO(crbug.com/1298696): Breaks components_unittests. + raw_ptr<const PageNode, DegradeToNoOpWhenMTE> notified_page_node_ = nullptr; }; using MockObserver = ::testing::StrictMock<LenientMockObserver>;
diff --git a/components/performance_manager/graph/process_node_impl_unittest.cc b/components/performance_manager/graph/process_node_impl_unittest.cc index 67a834c..01b2ecf 100644 --- a/components/performance_manager/graph/process_node_impl_unittest.cc +++ b/components/performance_manager/graph/process_node_impl_unittest.cc
@@ -141,7 +141,9 @@ } private: - raw_ptr<const ProcessNode> notified_process_node_ = nullptr; + // TODO(crbug.com/1298696): Breaks components_unittests. + raw_ptr<const ProcessNode, DegradeToNoOpWhenMTE> notified_process_node_ = + nullptr; }; using MockObserver = ::testing::StrictMock<LenientMockObserver>;
diff --git a/components/performance_manager/public/features.h b/components/performance_manager/public/features.h index 2863748..7b61b00 100644 --- a/components/performance_manager/public/features.h +++ b/components/performance_manager/public/features.h
@@ -53,10 +53,6 @@ DiscardStrategy discard_strategy_; }; -// Feature that controls whether or not tabs should be automatically discarded -// when the total PMF is too high. -extern const base::Feature kHighPMFDiscardPolicy; - // Enable background tab loading of pages (restored via session restore) // directly from Performance Manager rather than via TabLoader. extern const base::Feature kBackgroundTabLoadingFromPerformanceManager;
diff --git a/components/policy/core/common/policy_merger.cc b/components/policy/core/common/policy_merger.cc index 31846f0..97270b1 100644 --- a/components/policy/core/common/policy_merger.cc +++ b/components/policy/core/common/policy_merger.cc
@@ -6,6 +6,8 @@ #include <map> #include <set> +#include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/policy/core/common/policy_merger.h" #include "components/policy/core/common/policy_pref_names.h" #include "components/policy/policy_constants.h" @@ -15,13 +17,14 @@ namespace { -constexpr std::array<const char*, 6> kDictionaryPoliciesToMerge{ +constexpr const char* kDictionaryPoliciesToMerge[] = { +#if BUILDFLAG(IS_CHROMEOS_ASH) + key::kExtensionSettings, key::kDeviceLoginScreenPowerManagement, + key::kKeyPermissions, key::kPowerManagementIdleSettings, + key::kScreenBrightnessPercent, key::kScreenLockDelays, +#else key::kExtensionSettings, - key::kDeviceLoginScreenPowerManagement, - key::kKeyPermissions, - key::kPowerManagementIdleSettings, - key::kScreenBrightnessPercent, - key::kScreenLockDelays, +#endif }; } // namespace @@ -178,8 +181,8 @@ PolicyDictionaryMerger::PolicyDictionaryMerger( base::flat_set<std::string> policies_to_merge) : policies_to_merge_(std::move(policies_to_merge)), - allowed_policies_(kDictionaryPoliciesToMerge.begin(), - kDictionaryPoliciesToMerge.end()) {} + allowed_policies_(std::begin(kDictionaryPoliciesToMerge), + std::end(kDictionaryPoliciesToMerge)) {} PolicyDictionaryMerger::~PolicyDictionaryMerger() = default; void PolicyDictionaryMerger::Merge(PolicyMap* policies) const {
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index 7a664ff4..ea1f259 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -66,8 +66,11 @@ void DowngradeMetricsReportingToRecommendedPolicy(PolicyMap* policies) { // Capture both the Chrome-only and device-level policies on Chrome OS. const std::vector<const char*> metrics_keys = { - policy::key::kMetricsReportingEnabled, - policy::key::kDeviceMetricsReportingEnabled}; + policy::key::kMetricsReportingEnabled, +#if BUILDFLAG(IS_CHROMEOS) + policy::key::kDeviceMetricsReportingEnabled, +#endif + }; for (const char* policy_key : metrics_keys) { PolicyMap::Entry* policy = policies->GetMutable(policy_key); if (policy && policy->level != POLICY_LEVEL_RECOMMENDED &&
diff --git a/components/policy/tools/generate_policy_source.py b/components/policy/tools/generate_policy_source.py index f0f856be..82e886f13 100755 --- a/components/policy/tools/generate_policy_source.py +++ b/components/policy/tools/generate_policy_source.py
@@ -500,7 +500,12 @@ # Returns the policies supported by at least one platform. -def _GetSupportedPolicies(policies): +# Ensure only windows supported policies are returned when building for windows. +# Eventually only supported policies on every platforms will be returned. +def _GetSupportedPolicies(policies, target_platform): + if target_platform == 'win': + return [policy for policy in policies if policy.is_supported] + return [ policy for policy in policies if len(policy.platforms) + len(policy.future_on) > 0 @@ -518,7 +523,7 @@ def _WritePolicyConstantHeader(all_policies, policy_atomic_groups, target_platform, f, risk_tags): - policies = _GetSupportedPolicies(all_policies) + policies = _GetSupportedPolicies(all_policies, target_platform) f.write('''#ifndef COMPONENTS_POLICY_POLICY_CONSTANTS_H_ #define COMPONENTS_POLICY_POLICY_CONSTANTS_H_ @@ -1108,7 +1113,7 @@ def _WritePolicyConstantSource(all_policies, policy_atomic_groups, target_platform, f, risk_tags): - policies = _GetSupportedPolicies(all_policies) + policies = _GetSupportedPolicies(all_policies, target_platform) policy_names = [policy.name for policy in policies] f.write('''#include "components/policy/policy_constants.h"
diff --git a/components/policy/tools/generate_policy_source_test.py b/components/policy/tools/generate_policy_source_test.py index 79da976..5157be9a 100755 --- a/components/policy/tools/generate_policy_source_test.py +++ b/components/policy/tools/generate_policy_source_test.py
@@ -34,7 +34,7 @@ "schema": { "type": "string" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 1, "tags": [], "caption": "ExampleStringPolicy caption", @@ -45,14 +45,16 @@ "schema": { "type": "boolean" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 2, "tags": [], "caption": "ExampleBoolPolicy caption", "desc": "ExampleBoolPolicy desc", }, { - "name": "ExampleBoolMergeMetapolicy", - "type": "main", + "name": + "ExampleBoolMergeMetapolicy", + "type": + "main", "schema": { "type": "boolean" }, @@ -61,13 +63,18 @@ "features": { "metapolicy_type": "merge", }, - "id": 3, + "id": + 3, "tags": [], - "caption": "ExampleBoolMergeMetapolicy caption", - "desc": "ExampleBoolMergeMetapolicy desc", + "caption": + "ExampleBoolMergeMetapolicy caption", + "desc": + "ExampleBoolMergeMetapolicy desc", }, { - "name": "ExampleBoolPrecedenceMetapolicy", - "type": "main", + "name": + "ExampleBoolPrecedenceMetapolicy", + "type": + "main", "schema": { "type": "boolean" }, @@ -76,42 +83,55 @@ "features": { "metapolicy_type": "precedence", }, - "id": 4, + "id": + 4, "tags": [], - "caption": "ExampleBoolPrecedenceMetapolicy caption", - "desc": "ExampleBoolPrecedenceMetapolicy desc", + "caption": + "ExampleBoolPrecedenceMetapolicy caption", + "desc": + "ExampleBoolPrecedenceMetapolicy desc", }, { - "name": "CloudOnlyPolicy", - "type": "main", + "name": + "CloudOnlyPolicy", + "type": + "main", "schema": { "type": "boolean" }, "features": { "cloud_only": True, }, - "supported_on": ["chrome_os:1-", "android:1-"], - "id": 5, + "supported_on": ["chrome_os:1-", "android:1-", "chrome.*:1-"], + "id": + 5, "tags": [], - "caption": "CloudOnlyPolicy caption", - "desc": "CloudOnlyPolicy desc", + "caption": + "CloudOnlyPolicy caption", + "desc": + "CloudOnlyPolicy desc", }, { - "name": "CloudManagementEnrollmentToken", - "type": "string", + "name": + "CloudManagementEnrollmentToken", + "type": + "string", "schema": { "type": "string" }, - "supported_on": ["chrome_os:1-", "android:1-"], - "id": 6, + "supported_on": ["chrome_os:1-", "android:1-", "chrome.*:1-"], + "id": + 6, "tags": [], - "caption": "CloudManagementEnrollmentToken caption", - "desc": "CloudManagementEnrollmentToken desc" + "caption": + "CloudManagementEnrollmentToken caption", + "desc": + "CloudManagementEnrollmentToken desc" }, { "name": "DeprecatedButGenerated", "type": "string", "schema": { "type": "string" }, - "supported_on": ["chrome_os:1-93"], + "supported_on": ["chrome_os:1-93", "android:1-93", "chrome.*:1-93"], "id": 7, "tags": [], "caption": "DeprecatedButGenerated caption", @@ -144,7 +164,7 @@ "schema": { "type": "boolean" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 1015, "tags": [], "caption": "ChunkZeroLastFieldBooleanPolicy caption", @@ -155,7 +175,7 @@ "schema": { "type": "boolean" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 1016, "tags": [], "caption": "ChunkOneFirstFieldBooleanPolicy caption", @@ -166,7 +186,7 @@ "schema": { "type": "boolean" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 1815, "tags": [], "caption": "ChunkOneLastFieldBooleanPolicy caption", @@ -177,7 +197,7 @@ "schema": { "type": "string" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 1816, "tags": [], "caption": "ChunkTwoFirstFieldStringPolicy caption", @@ -188,7 +208,7 @@ "schema": { "type": "string" }, - "supported_on": ["chrome_os:1-"], + "supported_on": ["chrome_os:1-", "chrome.*:1-"], "id": 2615, "tags": [], "caption": "ChunkTwoLastFieldStringPolicy caption", @@ -391,6 +411,7 @@ mocked_file().write.call_args_list) def testWritePolicyConstantSource(self): + self.maxDiff = None output_path = 'mock_policy_constants_cc' for target_platform in self.all_target_platforms:
diff --git a/components/policy/tools/generate_policy_source_test_data.py b/components/policy/tools/generate_policy_source_test_data.py index f358abd..da7957b 100644 --- a/components/policy/tools/generate_policy_source_test_data.py +++ b/components/policy/tools/generate_policy_source_test_data.py
@@ -60,7 +60,7 @@ // // ExampleStringPolicy desc // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ExampleStringPolicyProto { optional PolicyOptions policy_options = 1; optional string ExampleStringPolicy = 2; @@ -70,7 +70,7 @@ // // ExampleBoolPolicy desc // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ExampleBoolPolicyProto { optional PolicyOptions policy_options = 1; optional bool ExampleBoolPolicy = 2; @@ -100,7 +100,7 @@ // // CloudOnlyPolicy desc // -// Supported on: android, chrome_os +// Supported on: android, chrome_os, fuchsia, linux, mac, win message CloudOnlyPolicyProto { optional PolicyOptions policy_options = 1; optional bool CloudOnlyPolicy = 2; @@ -110,7 +110,7 @@ // // CloudManagementEnrollmentToken desc // -// Supported on: android, chrome_os +// Supported on: android, chrome_os, fuchsia, linux, mac, win message CloudManagementEnrollmentTokenProto { optional PolicyOptions policy_options = 1; optional string CloudManagementEnrollmentToken = 2; @@ -120,7 +120,7 @@ // // DeprecatedButGenerated desc // -// Supported on: chrome_os +// Supported on: android, chrome_os, fuchsia, linux, mac, win message DeprecatedButGeneratedProto { optional PolicyOptions policy_options = 1; optional string DeprecatedButGenerated = 2; @@ -150,7 +150,7 @@ // // ChunkZeroLastFieldBooleanPolicy desc. // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ChunkZeroLastFieldBooleanPolicyProto { optional PolicyOptions policy_options = 1; optional bool ChunkZeroLastFieldBooleanPolicy = 2; @@ -160,7 +160,7 @@ // // ChunkOneFirstFieldBooleanPolicy desc. // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ChunkOneFirstFieldBooleanPolicyProto { optional PolicyOptions policy_options = 1; optional bool ChunkOneFirstFieldBooleanPolicy = 2; @@ -170,7 +170,7 @@ // // ChunkOneLastFieldBooleanPolicy desc. // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ChunkOneLastFieldBooleanPolicyProto { optional PolicyOptions policy_options = 1; optional bool ChunkOneLastFieldBooleanPolicy = 2; @@ -180,7 +180,7 @@ // // ChunkTwoFirstFieldStringPolicy desc // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ChunkTwoFirstFieldStringPolicyProto { optional PolicyOptions policy_options = 1; optional string ChunkTwoFirstFieldStringPolicy = 2; @@ -190,7 +190,7 @@ // // ChunkTwoLastFieldStringPolicy desc // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ChunkTwoLastFieldStringPolicyProto { optional PolicyOptions policy_options = 1; optional string ChunkTwoLastFieldStringPolicy = 2; @@ -233,7 +233,7 @@ // // ExampleStringPolicy desc // -// Supported on: chrome_os +// Supported on: chrome_os, fuchsia, linux, mac, win message ExampleStringPolicyProto { optional PolicyOptions policy_options = 1; optional string ExampleStringPolicy = 2;
diff --git a/components/services/app_service/public/cpp/BUILD.gn b/components/services/app_service/public/cpp/BUILD.gn index 745556c..766a893f 100644 --- a/components/services/app_service/public/cpp/BUILD.gn +++ b/components/services/app_service/public/cpp/BUILD.gn
@@ -47,6 +47,8 @@ component("app_types") { output_name = "APP_TYPES" sources = [ + "app_launch_util.cc", + "app_launch_util.h", "app_types.cc", "app_types.h", "features.cc",
diff --git a/components/services/app_service/public/cpp/app_launch_util.cc b/components/services/app_service/public/cpp/app_launch_util.cc new file mode 100644 index 0000000..cc929fc7 --- /dev/null +++ b/components/services/app_service/public/cpp/app_launch_util.cc
@@ -0,0 +1,11 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/services/app_service/public/cpp/app_launch_util.h" + +namespace apps { + +// TODO(crbug.com/1253250): Add function for the non mojom window info struct. + +} // namespace apps
diff --git a/components/services/app_service/public/cpp/app_launch_util.h b/components/services/app_service/public/cpp/app_launch_util.h new file mode 100644 index 0000000..eb9fe7b --- /dev/null +++ b/components/services/app_service/public/cpp/app_launch_util.h
@@ -0,0 +1,29 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_APP_LAUNCH_UTIL_H_ +#define COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_APP_LAUNCH_UTIL_H_ + +#include "components/services/app_service/public/mojom/types.mojom.h" + +namespace apps { + +// Don't remove items or change the order of this enum. It's used in +// histograms and preferences. +enum class LaunchContainer { + kLaunchContainerWindow = 0, + kLaunchContainerPanelDeprecated = 1, + kLaunchContainerTab = 2, + // For platform apps, which don't actually have a container (they just get a + // "onLaunched" event). + kLaunchContainerNone = 3, + + // Add any new values above this one, and update kMaxValue to the highest + // enumerator value. + kMaxValue = kLaunchContainerNone, +}; + +} // namespace apps + +#endif // COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_APP_LAUNCH_UTIL_H_
diff --git a/components/services/app_service/public/mojom/types.mojom b/components/services/app_service/public/mojom/types.mojom index fe129f1..dd01e0e 100644 --- a/components/services/app_service/public/mojom/types.mojom +++ b/components/services/app_service/public/mojom/types.mojom
@@ -487,6 +487,9 @@ // Don't remove items or change the order of this enum. It's used in // histograms and preferences. +// +// This is DEPRECATED. When adding new fields, please use the App +// struct in components/services/app_service/public/cpp/app_launch_util.h. enum LaunchContainer { kLaunchContainerWindow = 0, kLaunchContainerPanelDeprecated = 1,
diff --git a/components/sync/model/client_tag_based_model_type_processor.cc b/components/sync/model/client_tag_based_model_type_processor.cc index 0593528..eda768e 100644 --- a/components/sync/model/client_tag_based_model_type_processor.cc +++ b/components/sync/model/client_tag_based_model_type_processor.cc
@@ -279,7 +279,7 @@ return entity_tracker_ != nullptr; } -std::string ClientTagBasedModelTypeProcessor::TrackedAccountId() { +std::string ClientTagBasedModelTypeProcessor::TrackedAccountId() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Returning non-empty here despite !IsTrackingMetadata() has weird semantics, // e.g. initial updates are being fetched but we haven't received the response @@ -291,7 +291,7 @@ return entity_tracker_->model_type_state().authenticated_account_id(); } -std::string ClientTagBasedModelTypeProcessor::TrackedCacheGuid() { +std::string ClientTagBasedModelTypeProcessor::TrackedCacheGuid() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Returning non-empty here despite !IsTrackingMetadata() has weird semantics, // e.g. initial updates are being fetched but we haven't received the response
diff --git a/components/sync/model/client_tag_based_model_type_processor.h b/components/sync/model/client_tag_based_model_type_processor.h index 779221e..e20f3de 100644 --- a/components/sync/model/client_tag_based_model_type_processor.h +++ b/components/sync/model/client_tag_based_model_type_processor.h
@@ -86,8 +86,8 @@ void OnModelStarting(ModelTypeSyncBridge* bridge) override; void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() const override; - std::string TrackedAccountId() override; - std::string TrackedCacheGuid() override; + std::string TrackedAccountId() const override; + std::string TrackedCacheGuid() const override; void ReportError(const ModelError& error) override; absl::optional<ModelError> GetError() const override; base::WeakPtr<ModelTypeControllerDelegate> GetControllerDelegate() override;
diff --git a/components/sync/model/model_type_change_processor.h b/components/sync/model/model_type_change_processor.h index f40779d..74ceec4f 100644 --- a/components/sync/model/model_type_change_processor.h +++ b/components/sync/model/model_type_change_processor.h
@@ -102,11 +102,11 @@ // Returns the account ID for which metadata is being tracked, or empty if not // tracking metadata. - virtual std::string TrackedAccountId() = 0; + virtual std::string TrackedAccountId() const = 0; // Returns the cache guid for which metadata is being tracked, or empty if not // tracking metadata. - virtual std::string TrackedCacheGuid() = 0; + virtual std::string TrackedCacheGuid() const = 0; // Report an error in the model to sync. Should be called for any persistence // or consistency error the bridge encounters outside of a method that allows
diff --git a/components/sync/test/model/mock_model_type_change_processor.cc b/components/sync/test/model/mock_model_type_change_processor.cc index d2ec23a..391b16b6 100644 --- a/components/sync/test/model/mock_model_type_change_processor.cc +++ b/components/sync/test/model/mock_model_type_change_processor.cc
@@ -76,9 +76,13 @@ return other_->IsTrackingMetadata(); } - std::string TrackedAccountId() override { return other_->TrackedAccountId(); } + std::string TrackedAccountId() const override { + return other_->TrackedAccountId(); + } - std::string TrackedCacheGuid() override { return other_->TrackedCacheGuid(); } + std::string TrackedCacheGuid() const override { + return other_->TrackedCacheGuid(); + } void ReportError(const ModelError& error) override { other_->ReportError(error);
diff --git a/components/sync/test/model/mock_model_type_change_processor.h b/components/sync/test/model/mock_model_type_change_processor.h index d5cdbf29..3fbb49d 100644 --- a/components/sync/test/model/mock_model_type_change_processor.h +++ b/components/sync/test/model/mock_model_type_change_processor.h
@@ -71,8 +71,8 @@ (std::unique_ptr<MetadataBatch> batch), (override)); MOCK_METHOD(bool, IsTrackingMetadata, (), (const override)); - MOCK_METHOD(std::string, TrackedAccountId, (), (override)); - MOCK_METHOD(std::string, TrackedCacheGuid, (), (override)); + MOCK_METHOD(std::string, TrackedAccountId, (), (const override)); + MOCK_METHOD(std::string, TrackedCacheGuid, (), (const override)); MOCK_METHOD(void, ReportError, (const ModelError& error), (override)); MOCK_METHOD(absl::optional<ModelError>, GetError, (), (const override)); MOCK_METHOD(base::WeakPtr<ModelTypeControllerDelegate>,
diff --git a/components/viz/common/resources/resource_format_utils.cc b/components/viz/common/resources/resource_format_utils.cc index 7e93dcb..4108adc0 100644 --- a/components/viz/common/resources/resource_format_utils.cc +++ b/components/viz/common/resources/resource_format_utils.cc
@@ -184,6 +184,54 @@ return false; } +const char* ResourceFormatToString(ResourceFormat format) { + switch (format) { + case ResourceFormat::RGBA_8888: + return "RGBA_8888"; + case ResourceFormat::RGBA_4444: + return "RGBA_4444"; + case ResourceFormat::BGRA_8888: + return "BGRA_8888"; + case ResourceFormat::ALPHA_8: + return "ALPHA_8"; + case ResourceFormat::LUMINANCE_8: + return "LUMINANCE_8"; + case ResourceFormat::RGB_565: + return "RGB_565"; + case ResourceFormat::BGR_565: + return "BGR_565"; + case ResourceFormat::ETC1: + return "ETC1"; + case ResourceFormat::RED_8: + return "RED_8"; + case ResourceFormat::RG_88: + return "RG_88"; + case ResourceFormat::LUMINANCE_F16: + return "LUMINANCE_F16"; + case ResourceFormat::RGBA_F16: + return "RGBA_F16"; + case ResourceFormat::R16_EXT: + return "R16_EXT"; + case ResourceFormat::RG16_EXT: + return "RG16_EXT"; + case ResourceFormat::RGBX_8888: + return "RGBX_8888"; + case ResourceFormat::BGRX_8888: + return "BGRX_8888"; + case ResourceFormat::RGBA_1010102: + return "RGBA_1010102"; + case ResourceFormat::BGRA_1010102: + return "BGRA_1010102"; + case ResourceFormat::YVU_420: + return "YVU_420"; + case ResourceFormat::YUV_420_BIPLANAR: + return "YUV_420_BIPLANAR"; + case ResourceFormat::P010: + return "P010"; + } + NOTREACHED(); +} + unsigned int GLDataType(ResourceFormat format) { DCHECK_LE(format, RESOURCE_FORMAT_MAX); static const GLenum format_gl_data_type[] = {
diff --git a/components/viz/common/resources/resource_format_utils.h b/components/viz/common/resources/resource_format_utils.h index 8d73bfdb..1325c536f 100644 --- a/components/viz/common/resources/resource_format_utils.h +++ b/components/viz/common/resources/resource_format_utils.h
@@ -29,6 +29,8 @@ VIZ_RESOURCE_FORMAT_EXPORT ResourceFormat SkColorTypeToResourceFormat(SkColorType color_type); +VIZ_RESOURCE_FORMAT_EXPORT const char* ResourceFormatToString(ResourceFormat); + // The following functions use unsigned int instead of GLenum, since including // third_party/khronos/GLES2/gl2.h causes redefinition errors as // macros/functions defined in it conflict with macros/functions defined in
diff --git a/components/viz/common/skia_helper.cc b/components/viz/common/skia_helper.cc index 63694eb..4056d86 100644 --- a/components/viz/common/skia_helper.cc +++ b/components/viz/common/skia_helper.cc
@@ -2,62 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/common/skia_helper.h" -#include "base/trace_event/trace_event.h" -#include "cc/base/math_util.h" + #include "third_party/skia/include/effects/SkColorMatrix.h" #include "third_party/skia/include/effects/SkImageFilters.h" #include "third_party/skia/include/effects/SkOverdrawColorFilter.h" -#include "third_party/skia/include/gpu/GrBackendSurface.h" -#include "third_party/skia/include/gpu/GrRecordingContext.h" -#include "ui/gfx/geometry/skia_conversions.h" namespace viz { -sk_sp<SkImage> SkiaHelper::ApplyImageFilter(GrRecordingContext* context, - sk_sp<SkImage> src_image, - const gfx::RectF& src_rect, - const gfx::RectF& dst_rect, - const gfx::Vector2dF& scale, - sk_sp<SkImageFilter> filter, - SkIPoint* offset, - SkIRect* subset, - const gfx::PointF& origin, - bool flush) { - if (!filter) - return nullptr; - - if (!src_image) { - TRACE_EVENT_INSTANT0("viz", - "ApplyImageFilter wrap background texture failed", - TRACE_EVENT_SCOPE_THREAD); - return nullptr; - } - - // Big filters can sometimes fallback to CPU. Therefore, we need - // to disable subnormal floats for performance and security reasons. - cc::ScopedSubnormalFloatDisabler disabler; - SkMatrix local_matrix; - local_matrix.setTranslate(origin.x(), origin.y()); - local_matrix.postScale(scale.x(), scale.y()); - local_matrix.postTranslate(-src_rect.x(), -src_rect.y()); - - SkIRect clip_bounds = gfx::RectFToSkRect(dst_rect).roundOut(); - clip_bounds.offset(-src_rect.x(), -src_rect.y()); - - filter = filter->makeWithLocalMatrix(local_matrix); - SkIRect in_subset = SkIRect::MakeWH(src_rect.width(), src_rect.height()); - - sk_sp<SkImage> image = src_image->makeWithFilter( - context, filter.get(), in_subset, clip_bounds, subset, offset); - if (!image || !image->isTextureBacked()) { - return nullptr; - } - - // Force a flush of the Skia pipeline before we switch back to the compositor - // context. - image->getBackendTexture(flush); - CHECK(image->isTextureBacked()); - return image; -} sk_sp<SkColorFilter> SkiaHelper::MakeOverdrawColorFilter() { static const SkColor colors[SkOverdrawColorFilter::kNumColors] = {
diff --git a/components/viz/common/skia_helper.h b/components/viz/common/skia_helper.h index 7e39962..ad0119f 100644 --- a/components/viz/common/skia_helper.h +++ b/components/viz/common/skia_helper.h
@@ -16,18 +16,6 @@ namespace viz { class VIZ_COMMON_EXPORT SkiaHelper { public: - // |flush| is necessary for GLRenderer but not SkiaRenderer. - static sk_sp<SkImage> ApplyImageFilter(GrRecordingContext* context, - sk_sp<SkImage> src_image, - const gfx::RectF& src_rect, - const gfx::RectF& dst_rect, - const gfx::Vector2dF& scale, - sk_sp<SkImageFilter> filter, - SkIPoint* offset, - SkIRect* subset, - const gfx::PointF& origin, - bool flush); - static sk_sp<SkColorFilter> MakeOverdrawColorFilter(); static sk_sp<SkImageFilter> BuildOpacityFilter(float opacity);
diff --git a/components/viz/service/display/display_compositor_memory_and_task_controller.cc b/components/viz/service/display/display_compositor_memory_and_task_controller.cc index c546d48..9e27e7fb 100644 --- a/components/viz/service/display/display_compositor_memory_and_task_controller.cc +++ b/components/viz/service/display/display_compositor_memory_and_task_controller.cc
@@ -49,9 +49,6 @@ base::Unretained(this), task_executor, image_factory, &event); gpu_task_scheduler_->GetTaskSequence()->ScheduleTask(std::move(callback), {}); event.Wait(); - - // TODO(weiliangc): Move VizProcessContextProvider initialization here to take - // ownership of the shared image interface. } DisplayCompositorMemoryAndTaskController::
diff --git a/components/viz/service/display/display_compositor_memory_and_task_controller.h b/components/viz/service/display/display_compositor_memory_and_task_controller.h index da664cd..555571c5 100644 --- a/components/viz/service/display/display_compositor_memory_and_task_controller.h +++ b/components/viz/service/display/display_compositor_memory_and_task_controller.h
@@ -34,7 +34,7 @@ // For SkiaRenderer. explicit DisplayCompositorMemoryAndTaskController( std::unique_ptr<SkiaOutputSurfaceDependency> skia_dependency); - // For VizProcessContextProvider that uses InProcessCommandBuffer. + // For InProcessCommandBuffer. DisplayCompositorMemoryAndTaskController( gpu::CommandBufferTaskExecutor* task_executor, gpu::ImageFactory* image_factory);
diff --git a/components/viz/service/display/overlay_processor_interface.h b/components/viz/service/display/overlay_processor_interface.h index 2d4c5ff..5b85e90 100644 --- a/components/viz/service/display/overlay_processor_interface.h +++ b/components/viz/service/display/overlay_processor_interface.h
@@ -173,12 +173,11 @@ // Before the overlay refactor to use OverlayProcessorOnGpu, overlay // candidates are stored inside DirectRenderer. Those overlay candidates are - // later sent over to the GPU thread by GLRenderer or SkiaRenderer. This - // helper function will be called by DirectRenderer to take these overlay - // candidates inside overlay processor to avoid sending over DirectRenderer - // implementation. This is overridden by each platform that is ready to send - // overlay candidates inside |OverlayProcessor|. Must be called before - // ScheduleOverlays(). + // later sent over to the GPU thread by SkiaRenderer. This helper function + // will be called by DirectRenderer to take these overlay candidates inside + // overlay processor to avoid sending over DirectRenderer implementation. This + // is overridden by each platform that is ready to send overlay candidates + // inside |OverlayProcessor|. Must be called before ScheduleOverlays(). virtual void TakeOverlayCandidates(CandidateList* candidate_list) {} // TODO(weiliangc): Make it pure virtual after it is implemented by every
diff --git a/components/viz/service/display/renderer_pixeltest.cc b/components/viz/service/display/renderer_pixeltest.cc index 8c8bf7ee..38afb60a 100644 --- a/components/viz/service/display/renderer_pixeltest.cc +++ b/components/viz/service/display/renderer_pixeltest.cc
@@ -898,7 +898,6 @@ testing::ValuesIn(GetRendererTypes()), testing::PrintToStringParamName()); -// Test GLRenderer as well as SkiaRenderer. using GPURendererPixelTest = VizPixelTestWithParam; INSTANTIATE_TEST_SUITE_P(, GPURendererPixelTest, @@ -4229,7 +4228,7 @@ TEST_P(GPURendererPixelTest, TextureQuadBatching) { // This test verifies that multiple texture quads using the same resource // get drawn correctly. It implicitly is trying to test that the - // GLRenderer does the right thing with its draw quad cache. + // renderer does the right thing with its draw quad cache. gfx::Rect rect(this->device_viewport_size_); bool needs_blending = false;
diff --git a/components/viz/service/display/skia_readback_pixeltest.cc b/components/viz/service/display/skia_readback_pixeltest.cc index db740b2..6889e14 100644 --- a/components/viz/service/display/skia_readback_pixeltest.cc +++ b/components/viz/service/display/skia_readback_pixeltest.cc
@@ -402,9 +402,7 @@ } }; -// Test that SkiaRenderer readback works correctly. This test will use the -// default readback implementation for the platform, which is either the legacy -// GLRendererCopier or the new Skia readback API. +// Test that SkiaRenderer RGBA readback works correctly. TEST_P(SkiaReadbackPixelTestRGBA, ExecutesCopyRequest) { // Generates a RenderPass which contains one quad that spans the full output. // The quad has our source image, so the framebuffer should contain the source @@ -469,9 +467,7 @@ } }; -// Test that SkiaRenderer readback works correctly. This test will use the -// default readback implementation for the platform, which is either the legacy -// GLRendererCopier or the new Skia readback API. +// Test that SkiaRenderer NV12 readback works correctly. TEST_P(SkiaReadbackPixelTestNV12, ExecutesCopyRequest) { // Generates a RenderPass which contains one quad that spans the full output. // The quad has our source image, so the framebuffer should contain the source @@ -599,9 +595,7 @@ bool populates_gpu_memory_buffer() const { return std::get<2>(GetParam()); } }; -// Test that SkiaRenderer readback works correctly. This test will use the -// default readback implementation for the platform, which is either the legacy -// GLRendererCopier or the new Skia readback API. +// Test that SkiaRenderer NV12 readback works correctly using existing textures. TEST_P(SkiaReadbackPixelTestNV12WithBlit, ExecutesCopyRequestWithBlit) { const gfx::Rect result_selection = GetRequestArea();
diff --git a/components/viz/service/display_embedder/output_surface_provider_impl.cc b/components/viz/service/display_embedder/output_surface_provider_impl.cc index 3aaccca..c019d729 100644 --- a/components/viz/service/display_embedder/output_surface_provider_impl.cc +++ b/components/viz/service/display_embedder/output_surface_provider_impl.cc
@@ -95,15 +95,14 @@ return std::make_unique<OutputSurfaceUnified>(); #endif - // TODO(penghuang): Merge two output surfaces into one when GLRenderer and - // software compositor is removed. - std::unique_ptr<OutputSurface> output_surface; - if (!gpu_compositing) { - output_surface = std::make_unique<SoftwareOutputSurface>( + return std::make_unique<SoftwareOutputSurface>( CreateSoftwareOutputDeviceForPlatform(surface_handle, display_client)); } else { DCHECK(gpu_dependency); + + std::unique_ptr<OutputSurface> output_surface; + { gpu::ScopedAllowScheduleGpuTask allow_schedule_gpu_task; output_surface = SkiaOutputSurfaceImpl::Create( @@ -129,11 +128,10 @@ #elif !BUILDFLAG(IS_ANDROID) gpu_service_impl_->DisableGpuCompositing(); #endif - return nullptr; } - } - return output_surface; + return output_surface; + } } std::unique_ptr<SoftwareOutputDevice>
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc index e37ce583..4299e06 100644 --- a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc
@@ -306,7 +306,7 @@ dependency_->GetSharedContextState().get(), dependency_->GetMailboxManager(), dependency_->GetSharedImageManager(), dependency_->GetGpuImageFactory(), memory_tracker_.get(), - /*enable_wrapped_sk_image=*/true, /*is_for_display_compositor=*/true), + /*is_for_display_compositor=*/true), shared_image_factory_->RegisterSharedImageBackingFactoryForTesting( &test_backing_factory_); shared_image_representation_factory_ =
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index 5075c120..748baec 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -214,7 +214,6 @@ deps->GetGpuFeatureInfo(), deps->GetSharedContextState().get(), deps->GetMailboxManager(), deps->GetSharedImageManager(), deps->GetGpuImageFactory(), memory_tracker, - /*enable_wrapped_sk_image=*/true, /*is_for_display_compositor=*/true); }
diff --git a/components/viz/test/gl_scaler_test_util.h b/components/viz/test/gl_scaler_test_util.h index 63983c28..6d03739 100644 --- a/components/viz/test/gl_scaler_test_util.h +++ b/components/viz/test/gl_scaler_test_util.h
@@ -25,8 +25,7 @@ namespace viz { -// A collection of utility functions used in the GLScaler and GLRenderer-related -// pixel tests. +// A collection of utility functions used in pixel tests. class GLScalerTestUtil { public: struct ColorBar {
diff --git a/content/browser/renderer_host/compositor_impl_android.h b/content/browser/renderer_host/compositor_impl_android.h index df7ddf8..4a24c7e 100644 --- a/content/browser/renderer_host/compositor_impl_android.h +++ b/content/browser/renderer_host/compositor_impl_android.h
@@ -17,6 +17,7 @@ #include "cc/paint/element_id.h" #include "cc/trees/layer_tree_host_client.h" #include "cc/trees/layer_tree_host_single_thread_client.h" +#include "cc/trees/paint_holding_commit_trigger.h" #include "cc/trees/paint_holding_reason.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/surfaces/frame_sink_id.h" @@ -133,7 +134,10 @@ void DidUpdateLayers() override; void BeginMainFrame(const viz::BeginFrameArgs& args) override; void OnDeferMainFrameUpdatesChanged(bool) override {} - void OnDeferCommitsChanged(bool, cc::PaintHoldingReason) override {} + void OnDeferCommitsChanged( + bool, + cc::PaintHoldingReason, + absl::optional<cc::PaintHoldingCommitTrigger>) override {} void BeginMainFrameNotExpectedSoon() override {} void BeginMainFrameNotExpectedUntil(base::TimeTicks time) override {} void UpdateLayerTreeHost() override;
diff --git a/content/browser/renderer_host/frame_tree.cc b/content/browser/renderer_host/frame_tree.cc index 08d17a6..8135ab7 100644 --- a/content/browser/renderer_host/frame_tree.cc +++ b/content/browser/renderer_host/frame_tree.cc
@@ -203,7 +203,12 @@ blink::FrameOwnerElementType::kNone, blink::FramePolicy())), focused_frame_tree_node_id_(FrameTreeNode::kFrameTreeNodeInvalidId), - load_progress_(0.0) {} + load_progress_(0.0), + fenced_frames_impl_( + blink::features::IsFencedFramesEnabled() + ? absl::optional<blink::features::FencedFramesImplementationType>( + blink::features::kFencedFramesImplementationTypeParam.Get()) + : absl::nullopt) {} FrameTree::~FrameTree() { is_being_destroyed_ = true;
diff --git a/content/browser/renderer_host/frame_tree.h b/content/browser/renderer_host/frame_tree.h index afdbe7db..9ae5299 100644 --- a/content/browser/renderer_host/frame_tree.h +++ b/content/browser/renderer_host/frame_tree.h
@@ -25,6 +25,7 @@ #include "content/common/content_export.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/service_manager/public/mojom/interface_provider.mojom.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom-forward.h" @@ -497,6 +498,22 @@ // each inner FrameTree is attached. void FocusOuterFrameTrees(); + absl::optional<blink::features::FencedFramesImplementationType> + FencedFramesImplementationType() const { + return fenced_frames_impl_; + } + + bool IsFencedFramesMPArchBased() const { + return fenced_frames_impl_.has_value() && + fenced_frames_impl_.value() == + blink::features::FencedFramesImplementationType::kMPArch; + } + bool IsFencedFramesShadowDOMBased() const { + return fenced_frames_impl_.has_value() && + fenced_frames_impl_.value() == + blink::features::FencedFramesImplementationType::kShadowDOM; + } + private: friend class FrameTreeTest; FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest, RemoveFocusedFrame); @@ -555,6 +572,9 @@ // Overall load progress. double load_progress_; + absl::optional<blink::features::FencedFramesImplementationType> + fenced_frames_impl_; + // Whether the initial empty page has been accessed by another page, making it // unsafe to show the pending URL. Usually false unless another window tries // to modify the blank page. Always false after the first commit.
diff --git a/content/browser/renderer_host/frame_tree_node.cc b/content/browser/renderer_host/frame_tree_node.cc index 667dd12..c40caa4 100644 --- a/content/browser/renderer_host/frame_tree_node.cc +++ b/content/browser/renderer_host/frame_tree_node.cc
@@ -721,8 +721,7 @@ // enforced by default. // https://docs.google.com/document/d/1WnIhXOFycoje_sEoZR3Mo0YNSR2Ki7LABIC_HEWFaog bool shadow_dom_fenced_frame_enabled = - blink::features::IsFencedFramesEnabled() && - blink::features::IsFencedFramesShadowDOMBased(); + frame_tree()->IsFencedFramesShadowDOMBased(); // User Activation V2 requires activating all ancestor frames in addition to // the current frame. See @@ -778,8 +777,7 @@ // enforced by default. // https://docs.google.com/document/d/1WnIhXOFycoje_sEoZR3Mo0YNSR2Ki7LABIC_HEWFaog bool shadow_dom_fenced_frame_enabled = - blink::features::IsFencedFramesEnabled() && - blink::features::IsFencedFramesShadowDOMBased(); + frame_tree()->IsFencedFramesShadowDOMBased(); absl::optional<base::UnguessableToken> originator_nonce = fenced_frame_nonce();
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index cbb4266..c8b7a36 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -2036,7 +2036,7 @@ } } else { if (frame_tree_node_->IsFencedFrameRoot() && - blink::features::IsFencedFramesMPArchBased()) { + frame_tree_node_->frame_tree()->IsFencedFramesMPArchBased()) { StartNavigation(); OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_INVALID_URL), @@ -5203,7 +5203,7 @@ // [frame-src] or [fenced-frame-src] if (parent_policies) { bool is_opaque_fenced_frame = - blink::features::IsFencedFramesShadowDOMBased() + frame_tree_node_->frame_tree()->IsFencedFramesShadowDOMBased() ? (frame_tree_node_->IsFencedFrameRoot() && frame_tree_node_->GetFencedFrameMode() == blink::mojom::FencedFrameMode::kOpaqueAds)
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index b775f36..3f177327 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -6667,10 +6667,10 @@ RenderFrameProxyHost* proxy = nullptr; if (IsFencedFrameRoot()) { - // TODO(bokan): This is overy trusting of the renderer. We'll need some way + // TODO(bokan): This is overly trusting of the renderer. We'll need some way // to verify that the browser is the one that initiated this // ScrollFocusedEditable process. - // https://crbug.com/1123606. I&S tracker row 484. + // https://crbug.com/1123606. I&S tracker row 191. if (!params->for_focused_editable) { local_frame_host_receiver_.ReportBadMessage( "ScrollRectToVisibleInParentFrame can only be used for " @@ -6678,9 +6678,8 @@ return; } - proxy = blink::features::IsFencedFramesMPArchBased() - ? GetProxyToOuterDelegate() - : GetProxyToParent(); + proxy = frame_tree_->IsFencedFramesMPArchBased() ? GetProxyToOuterDelegate() + : GetProxyToParent(); } else { proxy = GetProxyToParent(); } @@ -6699,7 +6698,14 @@ DisallowActivationReasonId::kDispatchLoad)) return; - RenderFrameProxyHost* proxy = GetProxyToParent(); + // TODO(bokan): This is overly trusting of the renderer. Ideally we'd check + // that a keyboard event was recently sent. https://crbug.com/1123606. I&S + // tracker row 191. + RenderFrameProxyHost* proxy = + (IsFencedFrameRoot() && frame_tree_->IsFencedFramesMPArchBased()) + ? GetProxyToOuterDelegate() + : GetProxyToParent(); + if (!proxy) { // Only frames with an out-of-process parent frame should be sending this // message. @@ -7479,8 +7485,7 @@ base::UnguessableToken::Create()); return; } - if (!blink::features::IsFencedFramesEnabled() || - !blink::features::IsFencedFramesMPArchBased()) { + if (!frame_tree_->IsFencedFramesMPArchBased()) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_FENCED_FRAME_MOJO_WHEN_DISABLED); std::move(callback).Run(0, blink::mojom::FrameReplicationState::New(),
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index a4318f1..404e744 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -396,6 +396,8 @@ {"WebAppWindowControlsOverlay", features::kWebAppWindowControlsOverlay}, {"WebAuthenticationConditionalUI", features::kWebAuthConditionalUI}, + {"WGIGamepadTriggerRumble", + features::kEnableWindowsGamingInputDataFetcher}, {"WindowOpenNewPopupBehavior", blink::features::kWindowOpenNewPopupBehavior}, // TODO(crbug.com/1185950): Remove this flag when the feature is fully
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 0355b67..5262a910 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -3092,6 +3092,7 @@ "//content/test/gpu/gold_inexact_matching/", "//content/test/gpu/flake_suppressor/", + "//content/test/gpu/unexpected_passes/", "//testing/unexpected_passes_common/", ]
diff --git a/content/test/gpu/run_pytype.py b/content/test/gpu/run_pytype.py index b7783eb2..0ed44bf 100755 --- a/content/test/gpu/run_pytype.py +++ b/content/test/gpu/run_pytype.py
@@ -37,6 +37,7 @@ 'flake_suppressor', 'gold_inexact_matching', 'gpu_tests', + 'unexpected_passes', ] FILES_AND_DIRECTORIES_TO_CHECK = [ os.path.join(GPU_DIR, f) for f in FILES_AND_DIRECTORIES_TO_CHECK
diff --git a/content/test/gpu/unexpected_passes/gpu_builders.py b/content/test/gpu/unexpected_passes/gpu_builders.py index 2f67ae3d..4ae6aed 100644 --- a/content/test/gpu/unexpected_passes/gpu_builders.py +++ b/content/test/gpu/unexpected_passes/gpu_builders.py
@@ -3,6 +3,8 @@ # found in the LICENSE file. """GPU-specific implementation of the unexpected passes' builders module.""" +import typing + from unexpected_passes_common import builders from unexpected_passes_common import constants from unexpected_passes_common import data_types @@ -11,12 +13,13 @@ class GpuBuilders(builders.Builders): - def __init__(self, suite, include_internal_builders): + def __init__(self, suite: str, include_internal_builders: bool): super().__init__(suite, include_internal_builders) self._isolate_names = None self._non_chromium_builders = None - def _BuilderRunsTestOfInterest(self, test_map): + def _BuilderRunsTestOfInterest(self, test_map: typing.Dict[str, typing.Any] + ) -> bool: tests = test_map.get('isolated_scripts', []) for t in tests: if t.get('isolate_name') not in self.GetIsolateNames(): @@ -25,7 +28,7 @@ return True return False - def GetIsolateNames(self): + def GetIsolateNames(self) -> typing.Set[str]: if self._isolate_names is None: self._isolate_names = { 'telemetry_gpu_integration_test', @@ -37,10 +40,10 @@ self._isolate_names.add('telemetry_gpu_integration_test' + suffix) return self._isolate_names - def GetFakeCiBuilders(self): + def GetFakeCiBuilders(self) -> builders.FakeBuildersDict: return {} - def GetNonChromiumBuilders(self): + def GetNonChromiumBuilders(self) -> typing.Set[data_types.BuilderEntry]: if self._non_chromium_builders is None: str_builders = { 'Win V8 FYI Release (NVIDIA)',
diff --git a/content/test/gpu/unexpected_passes/gpu_builders_unittest.py b/content/test/gpu/unexpected_passes/gpu_builders_unittest.py index c70104f..b554e9a 100755 --- a/content/test/gpu/unexpected_passes/gpu_builders_unittest.py +++ b/content/test/gpu/unexpected_passes/gpu_builders_unittest.py
@@ -13,10 +13,10 @@ class BuilderRunsTestOfInterestUnittest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.instance = gpu_builders.GpuBuilders('webgl_conformance', False) - def testMatch(self): + def testMatch(self) -> None: """Tests that a match can be successfully found.""" test_map = { 'isolated_scripts': [ @@ -30,7 +30,7 @@ } self.assertTrue(self.instance._BuilderRunsTestOfInterest(test_map)) - def testNoMatchIsolate(self): + def testNoMatchIsolate(self) -> None: """Tests that a match is not found if the isolate name is not valid.""" test_map = { 'isolated_scripts': [ @@ -44,7 +44,7 @@ } self.assertFalse(self.instance._BuilderRunsTestOfInterest(test_map)) - def testNoMatchSuite(self): + def testNoMatchSuite(self) -> None: """Tests that a match is not found if the suite name is not valid.""" test_map = { 'isolated_scripts': [ @@ -58,7 +58,7 @@ } self.assertFalse(self.instance._BuilderRunsTestOfInterest(test_map)) - def testAndroidSuffixes(self): + def testAndroidSuffixes(self) -> None: """Tests that Android-specific isolates are added.""" isolate_names = self.instance.GetIsolateNames() for isolate in isolate_names: @@ -68,7 +68,7 @@ class GetNonChromiumBuildersUnittest(unittest.TestCase): - def testStringsConvertedToBuilderEntries(self): + def testStringsConvertedToBuilderEntries(self) -> None: """Tests that the easier-to-read strings get converted to BuilderEntry.""" instance = gpu_builders.GpuBuilders('webgl_conformance', False) builder = data_types.BuilderEntry('Win V8 FYI Release (NVIDIA)',
diff --git a/content/test/gpu/unexpected_passes/gpu_expectations.py b/content/test/gpu/unexpected_passes/gpu_expectations.py index 23bd616..7f0fa5a4 100644 --- a/content/test/gpu/unexpected_passes/gpu_expectations.py +++ b/content/test/gpu/unexpected_passes/gpu_expectations.py
@@ -6,6 +6,7 @@ from __future__ import print_function import os +import typing import validate_tag_consistency @@ -17,12 +18,12 @@ class GpuExpectations(expectations.Expectations): - def GetExpectationFilepaths(self): + def GetExpectationFilepaths(self) -> typing.List[str]: filepaths = [] for f in os.listdir(EXPECTATIONS_DIR): if f.endswith('_expectations.txt'): filepaths.append(os.path.join(EXPECTATIONS_DIR, f)) return filepaths - def _GetExpectationFileTagHeader(self, _): + def _GetExpectationFileTagHeader(self, _: str) -> str: return validate_tag_consistency.TAG_HEADER
diff --git a/content/test/gpu/unexpected_passes/gpu_expectations_unittest.py b/content/test/gpu/unexpected_passes/gpu_expectations_unittest.py index 76b9f87..1bbc21ec 100755 --- a/content/test/gpu/unexpected_passes/gpu_expectations_unittest.py +++ b/content/test/gpu/unexpected_passes/gpu_expectations_unittest.py
@@ -11,7 +11,7 @@ class GetExpectationFilepathsUnittest(unittest.TestCase): - def testGetExpectationFilepathsFindsSomething(self): + def testGetExpectationFilepathsFindsSomething(self) -> None: """Tests that the _GetExpectationFilepaths finds something in the dir.""" expectations = gpu_expectations.GpuExpectations() self.assertTrue(len(expectations.GetExpectationFilepaths()) > 0)
diff --git a/content/test/gpu/unexpected_passes/gpu_queries.py b/content/test/gpu/unexpected_passes/gpu_queries.py index c7a4749..88d300a 100644 --- a/content/test/gpu/unexpected_passes/gpu_queries.py +++ b/content/test/gpu/unexpected_passes/gpu_queries.py
@@ -3,8 +3,10 @@ # found in the LICENSE file. """GPU-specific implementation of the unexpected passes' queries module.""" +import typing from unexpected_passes_common import constants +from unexpected_passes_common import data_types from unexpected_passes_common import queries as queries_module RESULTS_SUBQUERY = """\ @@ -182,7 +184,8 @@ class GpuBigQueryQuerier(queries_module.BigQueryQuerier): - def __init__(self, suite, project, num_samples, large_query_mode): + def __init__(self, suite: str, project: str, num_samples: int, + large_query_mode: bool): super().__init__(suite, project, num_samples, large_query_mode) self._check_webgl_version = None @@ -211,12 +214,14 @@ self._suite = TELEMETRY_SUITE_TO_RDB_SUITE_EXCEPTION_MAP.get( self._suite, self._suite + '_integration_test') - def _ShouldSkipOverResult(self, result): + def _ShouldSkipOverResult(self, result: queries_module.QueryResult) -> bool: # Skip over the result if the WebGL version does not match the one we're # looking for. return not self._check_webgl_version(result['typ_tags']) - def _GetQueryGeneratorForBuilder(self, builder): + def _GetQueryGeneratorForBuilder( + self, builder: data_types.BuilderEntry + ) -> typing.Optional[queries_module.BaseQueryGenerator]: if not self._large_query_mode: # Look for all tests that match the given suite. return GpuFixedQueryGenerator( @@ -241,15 +246,18 @@ # Only consider specific test cases that were found to have active # expectations in the above query. Also perform any initial query splitting. - target_num_ids = queries_module.TARGET_RESULTS_PER_QUERY / self._num_samples + target_num_ids = (queries_module.TARGET_RESULTS_PER_QUERY // + self._num_samples) return GpuSplitQueryGenerator(builder, test_ids, target_num_ids) - def _GetRelevantExpectationFilesForQueryResult(self, _): + def _GetRelevantExpectationFilesForQueryResult( + self, + _: queries_module.QueryResult) -> typing.Optional[typing.Iterable[str]]: # Only one expectation file is ever used for the GPU tests, so just use # whichever one we've read in. return None - def _GetSuiteFilterClause(self): + def _GetSuiteFilterClause(self) -> str: """Returns a SQL clause to only include relevant suites. Meant for cases where suites are differentiated by typ tag rather than @@ -264,7 +272,7 @@ return 'AND "%s" IN UNNEST(typ_tags)' % self._webgl_version_tag - def _StripPrefixFromTestId(self, test_id): + def _StripPrefixFromTestId(self, test_id: str) -> str: # GPU test IDs provided by ResultDB are the test name as known by the test # runner prefixed by # "ninja://<target>/gpu_tests.<suite>_integration_test.<class>.", e.g. @@ -274,7 +282,8 @@ assert len(split_id) == 4 return split_id[-1] - def _GetActiveBuilderQuery(self, builder_type, include_internal_builders): + def _GetActiveBuilderQuery(self, builder_type: str, + include_internal_builders: bool) -> str: if include_internal_builders: subquery = ACTIVE_INTERNAL_BUILDER_SUBQUERY.format( builder_project='chrome', builder_type=builder_type) @@ -287,16 +296,17 @@ class GpuFixedQueryGenerator(queries_module.FixedQueryGenerator): - def GetQueries(self): + def GetQueries(self) -> typing.List[str]: return QueryGeneratorImpl(self.GetClauses(), self._builder) class GpuSplitQueryGenerator(queries_module.SplitQueryGenerator): - def GetQueries(self): + def GetQueries(self) -> typing.List[str]: return QueryGeneratorImpl(self.GetClauses(), self._builder) -def QueryGeneratorImpl(test_filter_clauses, builder): +def QueryGeneratorImpl(test_filter_clauses: typing.List[str], + builder: data_types.BuilderEntry) -> typing.List[str]: queries = [] query_template = None if builder.builder_type == constants.BuilderTypes.CI:
diff --git a/content/test/gpu/unexpected_passes/gpu_queries_unittest.py b/content/test/gpu/unexpected_passes/gpu_queries_unittest.py index 175312537..04ad697 100755 --- a/content/test/gpu/unexpected_passes/gpu_queries_unittest.py +++ b/content/test/gpu/unexpected_passes/gpu_queries_unittest.py
@@ -19,7 +19,7 @@ class QueryBuilderUnittest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self._patcher = mock.patch.object(subprocess, 'Popen') self._popen_mock = self._patcher.start() self.addCleanup(self._patcher.stop) @@ -27,7 +27,7 @@ builders.ClearInstance() uu.RegisterGenericBuildersImplementation() - def testWebGlVersion(self): + def testWebGlVersion(self) -> None: """Tests that only results for the correct WebGL version are returned.""" query_results = [ { @@ -87,10 +87,10 @@ data_types.Result('test_name', ['webgl-version-2'], 'Failure', 'step_name', '2345')) - def testSuiteExceptionMap(self): + def testSuiteExceptionMap(self) -> None: """Tests that the suite passed to the query changes for some suites.""" - def assertSuiteInQuery(suite, call_args): + def assertSuiteInQuery(suite: str, call_args: tuple) -> None: query = call_args[0][0][0] s = 'r"gpu_tests\\.%s\\."' % suite self.assertIn(s, query) @@ -128,17 +128,18 @@ class GetQueryGeneratorForBuilderUnittest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self._querier = gpu_uu.CreateGenericGpuQuerier() self._query_patcher = mock.patch.object( self._querier, '_RunBigQueryCommandsForJsonOutput') self._query_mock = self._query_patcher.start() self.addCleanup(self._query_patcher.stop) - def testNoLargeQueryMode(self): + def testNoLargeQueryMode(self) -> None: """Tests that the expected clause is returned in normal mode.""" query_generator = self._querier._GetQueryGeneratorForBuilder( data_types.BuilderEntry('builder', constants.BuilderTypes.CI, False)) + self.assertIsNotNone(query_generator) self.assertEqual(len(query_generator.GetClauses()), 1) self.assertEqual( query_generator.GetClauses()[0], """\ @@ -151,7 +152,7 @@ q = query_generator.GetQueries() self.assertEqual(len(q), 1) - def testLargeQueryModeNoTests(self): + def testLargeQueryModeNoTests(self) -> None: """Tests that a special value is returned if no tests are found.""" querier = gpu_uu.CreateGenericGpuQuerier(large_query_mode=True) with mock.patch.object(querier, @@ -162,7 +163,7 @@ self.assertIsNone(query_generator) query_mock.assert_called_once() - def testLargeQueryModeFoundTests(self): + def testLargeQueryModeFoundTests(self) -> None: """Tests that a clause containing found tests is returned.""" querier = gpu_uu.CreateGenericGpuQuerier(large_query_mode=True) with mock.patch.object(querier, @@ -174,6 +175,7 @@ }] query_generator = querier._GetQueryGeneratorForBuilder( data_types.BuilderEntry('builder', constants.BuilderTypes.CI, False)) + self.assertIsNotNone(query_generator) self.assertEqual(query_generator.GetClauses(), ['AND test_id IN UNNEST(["foo_test", "bar_test"])']) self.assertIsInstance(query_generator, gpu_queries.GpuSplitQueryGenerator) @@ -183,10 +185,10 @@ class GetActiveBuilderQueryUnittest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.querier = gpu_uu.CreateGenericGpuQuerier() - def testPublicCi(self): + def testPublicCi(self) -> None: """Tests that the active query for public CI is as expected.""" expected_query = """\ WITH @@ -207,7 +209,7 @@ self.querier._GetActiveBuilderQuery(constants.BuilderTypes.CI, False), expected_query) - def testInternalCi(self): + def testInternalCi(self) -> None: """Tests that the active query for internal CI is as expected.""" expected_query = """\ WITH @@ -235,7 +237,7 @@ self.querier._GetActiveBuilderQuery(constants.BuilderTypes.CI, True), expected_query) - def testPublicTry(self): + def testPublicTry(self) -> None: """Tests that the active query for public try is as expected.""" expected_query = """\ WITH @@ -256,7 +258,7 @@ self.querier._GetActiveBuilderQuery(constants.BuilderTypes.TRY, False), expected_query) - def testInternalTry(self): + def testInternalTry(self) -> None: """Tests that the active query for internal try is as expected.""" expected_query = """\ WITH @@ -288,7 +290,7 @@ class GeneratedQueryUnittest(unittest.TestCase): maxDiff = None - def testPublicCi(self): + def testPublicCi(self) -> None: """Tests that the generated public CI query is as expected.""" expected_query = """\ WITH @@ -340,7 +342,7 @@ test_filter_clause='tfc'), expected_query) - def testInternalCi(self): + def testInternalCi(self) -> None: """Tests that the generated internal CI query is as expected.""" expected_query = """\ WITH @@ -392,7 +394,7 @@ test_filter_clause='tfc'), expected_query) - def testPublicTry(self): + def testPublicTry(self) -> None: """Tests that the generated public try query is as expected.""" expected_query = """\ WITH @@ -471,7 +473,7 @@ test_filter_clause='tfc'), expected_query) - def testInternalTry(self): + def testInternalTry(self) -> None: """Tests that the generated internal try query is as expected.""" expected_query = """\ WITH @@ -552,7 +554,7 @@ class QueryGeneratorImplUnittest(unittest.TestCase): - def testPublicCi(self): + def testPublicCi(self) -> None: """Tests that public CI builders use the correct query.""" q = gpu_queries.QueryGeneratorImpl(['tfc'], data_types.BuilderEntry( @@ -563,7 +565,7 @@ builder_project='chromium', test_filter_clause='tfc') self.assertEqual(q[0], expected_query) - def testInternalCi(self): + def testInternalCi(self) -> None: """Tests that internal CI builders use the correct query.""" q = gpu_queries.QueryGeneratorImpl(['tfc'], data_types.BuilderEntry( @@ -574,7 +576,7 @@ builder_project='chrome', test_filter_clause='tfc') self.assertEqual(q[0], expected_query) - def testPublicTry(self): + def testPublicTry(self) -> None: """Tests that public try builders use the correct query.""" q = gpu_queries.QueryGeneratorImpl(['tfc'], data_types.BuilderEntry( @@ -585,7 +587,7 @@ builder_project='chromium', test_filter_clause='tfc') self.assertEqual(q[0], expected_query) - def testInternalTry(self): + def testInternalTry(self) -> None: """Tests that internal try builders use the correct query.""" q = gpu_queries.QueryGeneratorImpl(['tfc'], data_types.BuilderEntry( @@ -596,7 +598,7 @@ builder_project='chrome', test_filter_clause='tfc') self.assertEqual(q[0], expected_query) - def testUnknownBuilderType(self): + def testUnknownBuilderType(self) -> None: """Tests that an exception is raised for unknown builder types.""" with self.assertRaises(RuntimeError): gpu_queries.QueryGeneratorImpl(['tfc'], @@ -606,7 +608,7 @@ class GetSuiteFilterClauseUnittest(unittest.TestCase): - def testNonWebGl(self): + def testNonWebGl(self) -> None: """Tests that no filter is returned for non-WebGL suites.""" for suite in [ 'context_lost', @@ -622,7 +624,7 @@ querier = gpu_uu.CreateGenericGpuQuerier(suite=suite) self.assertEqual(querier._GetSuiteFilterClause(), '') - def testWebGl(self): + def testWebGl(self) -> None: """Tests that filters are returned for WebGL suites.""" querier = gpu_uu.CreateGenericGpuQuerier(suite='webgl_conformance1') expected_filter = 'AND "webgl-version-1" IN UNNEST(typ_tags)' @@ -634,7 +636,7 @@ class HelperMethodUnittest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.instance = gpu_uu.CreateGenericGpuQuerier() def testStripPrefixFromTestIdValidId(self): @@ -645,7 +647,7 @@ test_id = prefix + test_name self.assertEqual(self.instance._StripPrefixFromTestId(test_id), test_name) - def testStripPrefixFromTestIdInvalidId(self): + def testStripPrefixFromTestIdInvalidId(self) -> None: test_name = 'conformance/programs/program-handling_html' prefix = ('ninja://chrome/test:telemetry_gpu_integration_test/' 'gpu_testse.webgl_conformance_integration_test.')
diff --git a/content/test/gpu/unexpected_passes/gpu_unittest_utils.py b/content/test/gpu/unexpected_passes/gpu_unittest_utils.py index 3260df2..c1c11aa 100644 --- a/content/test/gpu/unexpected_passes/gpu_unittest_utils.py +++ b/content/test/gpu/unexpected_passes/gpu_unittest_utils.py
@@ -5,11 +5,15 @@ from __future__ import print_function +import typing + from unexpected_passes import gpu_queries from unexpected_passes_common import unittest_utils as uu -def CreateGenericGpuQuerier(*args, **kwargs): - return uu.CreateGenericQuerier(cls=gpu_queries.GpuBigQueryQuerier, - *args, - **kwargs) +def CreateGenericGpuQuerier(*args, **kwargs) -> gpu_queries.GpuBigQueryQuerier: + return typing.cast( + gpu_queries.GpuBigQueryQuerier, + uu.CreateGenericQuerier(cls=gpu_queries.GpuBigQueryQuerier, + *args, + **kwargs))
diff --git a/content/web_test/renderer/gamepad_controller.cc b/content/web_test/renderer/gamepad_controller.cc index db90987..3d1dac5b 100644 --- a/content/web_test/renderer/gamepad_controller.cc +++ b/content/web_test/renderer/gamepad_controller.cc
@@ -66,6 +66,7 @@ void SetAxisCount(int index, int axes); void SetAxisData(int index, int axis, double data); void SetDualRumbleVibrationActuator(int index, bool enabled); + void SetTriggerRumbleVibrationActuator(int index, bool enabled); base::WeakPtr<GamepadController> controller_; }; @@ -116,7 +117,9 @@ .SetMethod("setAxisCount", &GamepadControllerBindings::SetAxisCount) .SetMethod("setAxisData", &GamepadControllerBindings::SetAxisData) .SetMethod("setDualRumbleVibrationActuator", - &GamepadControllerBindings::SetDualRumbleVibrationActuator); + &GamepadControllerBindings::SetDualRumbleVibrationActuator) + .SetMethod("setTriggerRumbleVibrationActuator", + &GamepadControllerBindings::SetTriggerRumbleVibrationActuator); } void GamepadControllerBindings::Connect(int index) { @@ -167,6 +170,13 @@ controller_->SetDualRumbleVibrationActuator(index, enabled); } +void GamepadControllerBindings::SetTriggerRumbleVibrationActuator( + int index, + bool enabled) { + if (controller_) + controller_->SetTriggerRumbleVibrationActuator(index, enabled); +} + GamepadController::MonitorImpl::MonitorImpl( GamepadController* controller, mojo::PendingReceiver<device::mojom::GamepadMonitor> receiver) @@ -423,4 +433,18 @@ gamepads_->seqlock.WriteEnd(); } +void GamepadController::SetTriggerRumbleVibrationActuator(int index, + bool enabled) { + if (index < 0 || index >= static_cast<int>(Gamepads::kItemsLengthCap)) + return; + const int64_t now = CurrentTimeInMicroseconds(); + gamepads_->seqlock.WriteBegin(); + Gamepad& pad = gamepads_->data.items[index]; + pad.vibration_actuator.type = + device::GamepadHapticActuatorType::kTriggerRumble; + pad.vibration_actuator.not_null = enabled; + pad.timestamp = now; + gamepads_->seqlock.WriteEnd(); +} + } // namespace content
diff --git a/content/web_test/renderer/gamepad_controller.h b/content/web_test/renderer/gamepad_controller.h index e1abcec..32b16af6 100644 --- a/content/web_test/renderer/gamepad_controller.h +++ b/content/web_test/renderer/gamepad_controller.h
@@ -80,6 +80,7 @@ void SetAxisCount(int index, int axes); void SetAxisData(int index, int axis, double data); void SetDualRumbleVibrationActuator(int index, bool enabled); + void SetTriggerRumbleVibrationActuator(int index, bool enabled); void OnInterfaceRequest(mojo::ScopedMessagePipeHandle handle);
diff --git a/device/gamepad/abstract_haptic_gamepad.cc b/device/gamepad/abstract_haptic_gamepad.cc index de454ad..3c0c27e1b 100644 --- a/device/gamepad/abstract_haptic_gamepad.cc +++ b/device/gamepad/abstract_haptic_gamepad.cc
@@ -11,6 +11,14 @@ namespace device { namespace { constexpr double kMaxDurationMillis = 5000.0; // 5 seconds + +bool IsValidEffectType(mojom::GamepadHapticEffectType type) { + return type == mojom::GamepadHapticEffectType:: + GamepadHapticEffectTypeDualRumble || + type == mojom::GamepadHapticEffectType:: + GamepadHapticEffectTypeTriggerRumble; +} + } // namespace AbstractHapticGamepad::AbstractHapticGamepad() = default; @@ -44,7 +52,7 @@ void AbstractHapticGamepad::SetZeroVibration() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - SetVibration(0.0, 0.0); + SetVibration(mojom::GamepadEffectParameters::New()); } double AbstractHapticGamepad::GetMaxEffectDurationMillis() { @@ -58,9 +66,8 @@ scoped_refptr<base::SequencedTaskRunner> callback_runner) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!is_shut_down_); - if (type != - mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble) { - // Only dual-rumble effects are supported. + if (!IsValidEffectType(type)) { + // Only dual-rumble and trigger-rumble effects are supported. GamepadDataFetcher::RunVibrationCallback( std::move(callback), std::move(callback_runner), mojom::GamepadHapticsResult::GamepadHapticsResultNotSupported); @@ -85,8 +92,7 @@ playing_effect_callback_ = std::move(callback); callback_runner_ = std::move(callback_runner); - PlayDualRumbleEffect(sequence_id, params->duration, params->start_delay, - params->strong_magnitude, params->weak_magnitude); + PlayVibrationEffect(sequence_id, std::move(params)); } void AbstractHapticGamepad::ResetVibration( @@ -113,27 +119,27 @@ mojom::GamepadHapticsResult::GamepadHapticsResultComplete); } -void AbstractHapticGamepad::PlayDualRumbleEffect(int sequence_id, - double duration, - double start_delay, - double strong_magnitude, - double weak_magnitude) { +void AbstractHapticGamepad::PlayVibrationEffect( + int sequence_id, + mojom::GamepadEffectParametersPtr params) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + double duration = params->duration; + double start_delay = params->start_delay; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&AbstractHapticGamepad::StartVibration, GetWeakPtr(), - sequence_id, duration, strong_magnitude, weak_magnitude), + sequence_id, duration, std::move(params)), base::Milliseconds(start_delay)); } -void AbstractHapticGamepad::StartVibration(int sequence_id, - double duration, - double strong_magnitude, - double weak_magnitude) { +void AbstractHapticGamepad::StartVibration( + int sequence_id, + double duration, + mojom::GamepadEffectParametersPtr params) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (is_shut_down_ || sequence_id != sequence_id_) return; - SetVibration(strong_magnitude, weak_magnitude); + SetVibration(params.Clone()); const double max_duration = GetMaxEffectDurationMillis(); if (duration > max_duration) { @@ -143,8 +149,7 @@ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&AbstractHapticGamepad::StartVibration, GetWeakPtr(), - sequence_id, remaining_duration, strong_magnitude, - weak_magnitude), + sequence_id, remaining_duration, params.Clone()), base::Milliseconds(max_duration)); } else { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
diff --git a/device/gamepad/abstract_haptic_gamepad.h b/device/gamepad/abstract_haptic_gamepad.h index 1c6e3bf2..5b64d0d 100644 --- a/device/gamepad/abstract_haptic_gamepad.h +++ b/device/gamepad/abstract_haptic_gamepad.h
@@ -55,7 +55,7 @@ bool IsShuttingDown() { return is_shutting_down_; } // Set the vibration magnitude for the strong and weak vibration actuators. - virtual void SetVibration(double strong_magnitude, double weak_magnitude) = 0; + virtual void SetVibration(mojom::GamepadEffectParametersPtr params) = 0; // Set the vibration magnitude for both actuators to zero. virtual void SetZeroVibration(); @@ -71,15 +71,11 @@ // are halted and callbacks are issued. virtual void DoShutdown() {} - void PlayDualRumbleEffect(int sequence_id, - double duration, - double start_delay, - double strong_magnitude, - double weak_magnitude); + void PlayVibrationEffect(int sequence_id, + mojom::GamepadEffectParametersPtr params); void StartVibration(int sequence_id, double duration, - double strong_magnitude, - double weak_magnitude); + mojom::GamepadEffectParametersPtr params); void FinishEffect(int sequence_id); bool is_shutting_down_ = false;
diff --git a/device/gamepad/abstract_haptic_gamepad_unittest.cc b/device/gamepad/abstract_haptic_gamepad_unittest.cc index bf95b79..f0c939e0 100644 --- a/device/gamepad/abstract_haptic_gamepad_unittest.cc +++ b/device/gamepad/abstract_haptic_gamepad_unittest.cc
@@ -38,7 +38,7 @@ FakeHapticGamepad() : set_vibration_count_(0), set_zero_vibration_count_(0) {} ~FakeHapticGamepad() override = default; - void SetVibration(double strong_magnitude, double weak_magnitude) override { + void SetVibration(mojom::GamepadEffectParametersPtr params) override { set_vibration_count_++; } @@ -78,8 +78,9 @@ mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) { gamepad_->PlayEffect( type, - mojom::GamepadEffectParameters::New(duration, start_delay, - kStrongMagnitude, kWeakMagnitude), + mojom::GamepadEffectParameters::New( + duration, start_delay, kStrongMagnitude, kWeakMagnitude, + /*left_trigger=*/0, /*right_trigger=*/0), std::move(callback), base::ThreadTaskRunnerHandle::Get()); }
diff --git a/device/gamepad/dualshock4_controller.cc b/device/gamepad/dualshock4_controller.cc index 379716f..cc91cba 100644 --- a/device/gamepad/dualshock4_controller.cc +++ b/device/gamepad/dualshock4_controller.cc
@@ -211,17 +211,17 @@ return true; } -void Dualshock4Controller::SetVibration(double strong_magnitude, - double weak_magnitude) { +void Dualshock4Controller::SetVibration( + mojom::GamepadEffectParametersPtr params) { // Genuine DualShock 4 gamepads use an alternate output report when connected // over Bluetooth. Always send USB-mode reports to SCUF Vantage gamepads. if (bus_type_ == GAMEPAD_BUS_BLUETOOTH && gamepad_id_ != GamepadId::kScufProduct7725) { - SetVibrationBluetooth(strong_magnitude, weak_magnitude); + SetVibrationBluetooth(params->strong_magnitude, params->weak_magnitude); return; } - SetVibrationUsb(strong_magnitude, weak_magnitude); + SetVibrationUsb(params->strong_magnitude, params->weak_magnitude); } void Dualshock4Controller::SetVibrationUsb(double strong_magnitude,
diff --git a/device/gamepad/dualshock4_controller.h b/device/gamepad/dualshock4_controller.h index 7187bd25..df7a9b2 100644 --- a/device/gamepad/dualshock4_controller.h +++ b/device/gamepad/dualshock4_controller.h
@@ -42,7 +42,7 @@ Gamepad* pad); // AbstractHapticGamepad public implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; private:
diff --git a/device/gamepad/dualshock4_controller_unittest.cc b/device/gamepad/dualshock4_controller_unittest.cc index 2b21c8ad..3ae8bbd 100644 --- a/device/gamepad/dualshock4_controller_unittest.cc +++ b/device/gamepad/dualshock4_controller_unittest.cc
@@ -152,8 +152,9 @@ mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) { gamepad->PlayEffect( mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble, - mojom::GamepadEffectParameters::New(kDurationMillis, start_delay, - strong_magnitude, weak_magnitude), + mojom::GamepadEffectParameters::New( + kDurationMillis, start_delay, strong_magnitude, weak_magnitude, + /*left_trigger=*/0, /*right_trigger=*/0), std::move(callback), base::ThreadTaskRunnerHandle::Get()); }
diff --git a/device/gamepad/gamepad_device_linux.cc b/device/gamepad/gamepad_device_linux.cc index 38b9026..28c49b4 100644 --- a/device/gamepad/gamepad_device_linux.cc +++ b/device/gamepad/gamepad_device_linux.cc
@@ -647,28 +647,28 @@ hidraw_fd_.reset(); } -void GamepadDeviceLinux::SetVibration(double strong_magnitude, - double weak_magnitude) { +void GamepadDeviceLinux::SetVibration( + mojom::GamepadEffectParametersPtr params) { DCHECK(polling_runner_->RunsTasksInCurrentSequence()); if (dualshock4_) { - dualshock4_->SetVibration(strong_magnitude, weak_magnitude); + dualshock4_->SetVibration(std::move(params)); return; } if (xbox_hid_) { - xbox_hid_->SetVibration(strong_magnitude, weak_magnitude); + xbox_hid_->SetVibration(std::move(params)); return; } if (hid_haptics_) { - hid_haptics_->SetVibration(strong_magnitude, weak_magnitude); + hid_haptics_->SetVibration(std::move(params)); return; } uint16_t strong_magnitude_scaled = - static_cast<uint16_t>(strong_magnitude * kRumbleMagnitudeMax); + static_cast<uint16_t>(params->strong_magnitude * kRumbleMagnitudeMax); uint16_t weak_magnitude_scaled = - static_cast<uint16_t>(weak_magnitude * kRumbleMagnitudeMax); + static_cast<uint16_t>(params->weak_magnitude * kRumbleMagnitudeMax); // AbstractHapticGamepad will call SetZeroVibration when the effect is // complete, so we don't need to set the duration here except to make sure it
diff --git a/device/gamepad/gamepad_device_linux.h b/device/gamepad/gamepad_device_linux.h index 640b4c1..54e133c 100644 --- a/device/gamepad/gamepad_device_linux.h +++ b/device/gamepad/gamepad_device_linux.h
@@ -94,7 +94,7 @@ void CloseHidrawNode(); // AbstractHapticGamepad public implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; void SetZeroVibration() override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override;
diff --git a/device/gamepad/gamepad_device_mac.h b/device/gamepad/gamepad_device_mac.h index f5149dc..5c20bf7d 100644 --- a/device/gamepad/gamepad_device_mac.h +++ b/device/gamepad/gamepad_device_mac.h
@@ -56,7 +56,7 @@ bool SupportsVibration(); // AbstractHapticGamepad public implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; void SetZeroVibration() override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override;
diff --git a/device/gamepad/gamepad_device_mac.mm b/device/gamepad/gamepad_device_mac.mm index 3ffa1f6..bd8eb9ac 100644 --- a/device/gamepad/gamepad_device_mac.mm +++ b/device/gamepad/gamepad_device_mac.mm
@@ -429,20 +429,19 @@ return dualshock4_ || xbox_hid_ || hid_haptics_ || ff_device_ref_; } -void GamepadDeviceMac::SetVibration(double strong_magnitude, - double weak_magnitude) { +void GamepadDeviceMac::SetVibration(mojom::GamepadEffectParametersPtr params) { if (dualshock4_) { - dualshock4_->SetVibration(strong_magnitude, weak_magnitude); + dualshock4_->SetVibration(std::move(params)); return; } if (xbox_hid_) { - xbox_hid_->SetVibration(strong_magnitude, weak_magnitude); + xbox_hid_->SetVibration(std::move(params)); return; } if (hid_haptics_) { - hid_haptics_->SetVibration(strong_magnitude, weak_magnitude); + hid_haptics_->SetVibration(std::move(params)); return; } @@ -453,9 +452,9 @@ DCHECK(ff_custom_force->rglForceData); ff_custom_force->rglForceData[0] = - static_cast<LONG>(strong_magnitude * kRumbleMagnitudeMax); + static_cast<LONG>(params->strong_magnitude * kRumbleMagnitudeMax); ff_custom_force->rglForceData[1] = - static_cast<LONG>(weak_magnitude * kRumbleMagnitudeMax); + static_cast<LONG>(params->weak_magnitude * kRumbleMagnitudeMax); // Download the effect to the device and start the effect. HRESULT res = FFEffectSetParameters(
diff --git a/device/gamepad/gamepad_platform_data_fetcher.h b/device/gamepad/gamepad_platform_data_fetcher.h index 8570122..0c5ef221 100644 --- a/device/gamepad/gamepad_platform_data_fetcher.h +++ b/device/gamepad/gamepad_platform_data_fetcher.h
@@ -41,16 +41,16 @@ #elif BUILDFLAG(IS_WIN) - manager->AddFactory(new XInputDataFetcherWin::Factory()); - manager->AddFactory(new NintendoDataFetcher::Factory()); - manager->AddFactory(new RawInputDataFetcher::Factory()); - // Windows.Gaming.Input is available in Windows 10.0.10240.0 and later. if (base::FeatureList::IsEnabled( features::kEnableWindowsGamingInputDataFetcher) && base::win::GetVersion() >= base::win::Version::WIN10) { manager->AddFactory(new WgiDataFetcherWin::Factory()); + } else { + manager->AddFactory(new XInputDataFetcherWin::Factory()); } + manager->AddFactory(new NintendoDataFetcher::Factory()); + manager->AddFactory(new RawInputDataFetcher::Factory()); #elif BUILDFLAG(IS_MAC)
diff --git a/device/gamepad/haptic_gamepad_android.cc b/device/gamepad/haptic_gamepad_android.cc index 9577c61..d9807af 100644 --- a/device/gamepad/haptic_gamepad_android.cc +++ b/device/gamepad/haptic_gamepad_android.cc
@@ -13,10 +13,10 @@ HapticGamepadAndroid::~HapticGamepadAndroid() = default; -void HapticGamepadAndroid::SetVibration(double strong_magnitude, - double weak_magnitude) { +void HapticGamepadAndroid::SetVibration( + mojom::GamepadEffectParametersPtr params) { GamepadPlatformDataFetcherAndroid::SetVibration( - device_index_, strong_magnitude, weak_magnitude); + device_index_, params->strong_magnitude, params->weak_magnitude); } void HapticGamepadAndroid::SetZeroVibration() {
diff --git a/device/gamepad/haptic_gamepad_android.h b/device/gamepad/haptic_gamepad_android.h index 480b1a8..e7d7dad 100644 --- a/device/gamepad/haptic_gamepad_android.h +++ b/device/gamepad/haptic_gamepad_android.h
@@ -18,7 +18,7 @@ ~HapticGamepadAndroid() override; // AbstractHapticGamepad implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; void SetZeroVibration() override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override;
diff --git a/device/gamepad/hid_haptic_gamepad.cc b/device/gamepad/hid_haptic_gamepad.cc index 2158d9d..b4aa8f8e 100644 --- a/device/gamepad/hid_haptic_gamepad.cc +++ b/device/gamepad/hid_haptic_gamepad.cc
@@ -105,8 +105,7 @@ writer_.reset(); } -void HidHapticGamepad::SetVibration(double strong_magnitude, - double weak_magnitude) { +void HidHapticGamepad::SetVibration(mojom::GamepadEffectParametersPtr params) { DCHECK(writer_); std::vector<uint8_t> control_report(report_length_bytes_); control_report[0] = report_id_; @@ -114,7 +113,7 @@ // Single channel vibration. Combine both channels into a single magnitude. std::vector<uint8_t> vibration_bytes; double vibration_magnitude = - std::min(strong_magnitude + weak_magnitude, 1.0); + std::min(params->strong_magnitude + params->weak_magnitude, 1.0); MagnitudeToBytes(vibration_magnitude, report_size_bits_, logical_min_, logical_max_, &vibration_bytes); // Vibration magnitude must not overwrite the report ID. @@ -128,9 +127,9 @@ // Dual channel vibration. std::vector<uint8_t> left_bytes; std::vector<uint8_t> right_bytes; - MagnitudeToBytes(strong_magnitude, report_size_bits_, logical_min_, + MagnitudeToBytes(params->strong_magnitude, report_size_bits_, logical_min_, logical_max_, &left_bytes); - MagnitudeToBytes(weak_magnitude, report_size_bits_, logical_min_, + MagnitudeToBytes(params->weak_magnitude, report_size_bits_, logical_min_, logical_max_, &right_bytes); // Vibration magnitude must not overwrite the report ID. DCHECK(report_id_ == 0x00 || strong_offset_bytes_ > 0);
diff --git a/device/gamepad/hid_haptic_gamepad.h b/device/gamepad/hid_haptic_gamepad.h index 19b79b0..426723a 100644 --- a/device/gamepad/hid_haptic_gamepad.h +++ b/device/gamepad/hid_haptic_gamepad.h
@@ -87,7 +87,7 @@ uint16_t product_id); // AbstractHapticGamepad public implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; private:
diff --git a/device/gamepad/hid_haptic_gamepad_unittest.cc b/device/gamepad/hid_haptic_gamepad_unittest.cc index 241190d..924cd71 100644 --- a/device/gamepad/hid_haptic_gamepad_unittest.cc +++ b/device/gamepad/hid_haptic_gamepad_unittest.cc
@@ -98,8 +98,9 @@ mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) { gamepad_->PlayEffect( mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble, - mojom::GamepadEffectParameters::New(kDurationMillis, start_delay, - strong_magnitude, weak_magnitude), + mojom::GamepadEffectParameters::New( + kDurationMillis, start_delay, strong_magnitude, weak_magnitude, + /*left_trigger=*/0, /*right_trigger=*/0), std::move(callback), base::ThreadTaskRunnerHandle::Get()); }
diff --git a/device/gamepad/nintendo_controller.cc b/device/gamepad/nintendo_controller.cc index 78ef425..4339e84 100644 --- a/device/gamepad/nintendo_controller.cc +++ b/device/gamepad/nintendo_controller.cc
@@ -1772,19 +1772,24 @@ device_info_.reset(); } -void NintendoController::SetVibration(double strong_magnitude, - double weak_magnitude) { +void NintendoController::SetVibration( + mojom::GamepadEffectParametersPtr params) { if (is_composite_) { // Split the vibration effect between the left and right subdevices. if (composite_left_ && composite_right_) { - composite_left_->SetVibration(strong_magnitude, 0); - composite_right_->SetVibration(0, weak_magnitude); + composite_left_->SetVibration(mojom::GamepadEffectParameters::New( + params->duration, params->start_delay, params->strong_magnitude, + /*weak_magnitude=*/0, /*left_trigger=*/0, /*right_trigger=*/0)); + composite_right_->SetVibration(mojom::GamepadEffectParameters::New( + params->duration, params->start_delay, /*strong_magnitude=*/0, + params->weak_magnitude, /*left_trigger=*/0, /*right_trigger=*/0)); } } else { - RequestVibration(kVibrationFrequencyStrongRumble, - kVibrationAmplitudeStrongRumbleMax * strong_magnitude, - kVibrationFrequencyWeakRumble, - kVibrationAmplitudeWeakRumbleMax * weak_magnitude); + RequestVibration( + kVibrationFrequencyStrongRumble, + kVibrationAmplitudeStrongRumbleMax * params->strong_magnitude, + kVibrationFrequencyWeakRumble, + kVibrationAmplitudeWeakRumbleMax * params->weak_magnitude); } }
diff --git a/device/gamepad/nintendo_controller.h b/device/gamepad/nintendo_controller.h index a3b72f0..96cdf34 100644 --- a/device/gamepad/nintendo_controller.h +++ b/device/gamepad/nintendo_controller.h
@@ -183,7 +183,7 @@ // AbstractHapticGamepad implementation. void DoShutdown() override; - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; double GetMaxEffectDurationMillis() override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override;
diff --git a/device/gamepad/public/cpp/gamepad.h b/device/gamepad/public/cpp/gamepad.h index 720c9e3..ebb45bf 100644 --- a/device/gamepad/public/cpp/gamepad.h +++ b/device/gamepad/public/cpp/gamepad.h
@@ -36,7 +36,11 @@ double value{0.0}; }; -enum class GamepadHapticActuatorType { kVibration = 0, kDualRumble = 1 }; +enum class GamepadHapticActuatorType { + kVibration = 0, + kDualRumble = 1, + kTriggerRumble = 2 +}; enum class GamepadHapticEffectType { kDualRumble = 0 };
diff --git a/device/gamepad/public/cpp/gamepad_mojom_traits.cc b/device/gamepad/public/cpp/gamepad_mojom_traits.cc index c6e01ca..ebd9a13 100644 --- a/device/gamepad/public/cpp/gamepad_mojom_traits.cc +++ b/device/gamepad/public/cpp/gamepad_mojom_traits.cc
@@ -70,6 +70,9 @@ case device::GamepadHapticActuatorType::kDualRumble: return device::mojom::GamepadHapticActuatorType:: GamepadHapticActuatorTypeDualRumble; + case device::GamepadHapticActuatorType::kTriggerRumble: + return device::mojom::GamepadHapticActuatorType:: + GamepadHapticActuatorTypeTriggerRumble; } NOTREACHED(); @@ -91,6 +94,10 @@ GamepadHapticActuatorTypeDualRumble: *output = device::GamepadHapticActuatorType::kDualRumble; return true; + case device::mojom::GamepadHapticActuatorType:: + GamepadHapticActuatorTypeTriggerRumble: + *output = device::GamepadHapticActuatorType::kTriggerRumble; + return true; } NOTREACHED();
diff --git a/device/gamepad/public/mojom/gamepad.mojom b/device/gamepad/public/mojom/gamepad.mojom index f842d5f..7027d296 100644 --- a/device/gamepad/public/mojom/gamepad.mojom +++ b/device/gamepad/public/mojom/gamepad.mojom
@@ -84,11 +84,13 @@ enum GamepadHapticActuatorType { GamepadHapticActuatorTypeVibration = 0, - GamepadHapticActuatorTypeDualRumble = 1 + GamepadHapticActuatorTypeDualRumble = 1, + GamepadHapticActuatorTypeTriggerRumble = 2 }; enum GamepadHapticEffectType { - GamepadHapticEffectTypeDualRumble = 0 + GamepadHapticEffectTypeDualRumble = 0, + GamepadHapticEffectTypeTriggerRumble = 1 }; struct GamepadHapticActuator { @@ -144,6 +146,8 @@ double start_delay; double strong_magnitude; double weak_magnitude; + double left_trigger; + double right_trigger; }; enum GamepadHapticsResult {
diff --git a/device/gamepad/raw_input_gamepad_device_win.cc b/device/gamepad/raw_input_gamepad_device_win.cc index 7129777..4266c1c02f 100644 --- a/device/gamepad/raw_input_gamepad_device_win.cc +++ b/device/gamepad/raw_input_gamepad_device_win.cc
@@ -209,12 +209,12 @@ return dualshock4_ || hid_haptics_; } -void RawInputGamepadDeviceWin::SetVibration(double strong_magnitude, - double weak_magnitude) { +void RawInputGamepadDeviceWin::SetVibration( + mojom::GamepadEffectParametersPtr params) { if (dualshock4_) - dualshock4_->SetVibration(strong_magnitude, weak_magnitude); + dualshock4_->SetVibration(std::move(params)); else if (hid_haptics_) - hid_haptics_->SetVibration(strong_magnitude, weak_magnitude); + hid_haptics_->SetVibration(std::move(params)); } bool RawInputGamepadDeviceWin::QueryDeviceInfo() {
diff --git a/device/gamepad/raw_input_gamepad_device_win.h b/device/gamepad/raw_input_gamepad_device_win.h index 1b00278..edfa022 100644 --- a/device/gamepad/raw_input_gamepad_device_win.h +++ b/device/gamepad/raw_input_gamepad_device_win.h
@@ -59,7 +59,7 @@ void ReadPadState(Gamepad* pad) const; // AbstractHapticGamepad implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; private:
diff --git a/device/gamepad/wgi_data_fetcher_win.cc b/device/gamepad/wgi_data_fetcher_win.cc index 391577d..ee4af54a 100644 --- a/device/gamepad/wgi_data_fetcher_win.cc +++ b/device/gamepad/wgi_data_fetcher_win.cc
@@ -62,37 +62,44 @@ return raw_game_controller; } -// Check if the gamepad should be added by Windows.Gaming.Input. In the -// situation that a Nintendo or Dualshock4 gamepad is connected, there are -// dedicated data fetchers designed for these gamepads. -// We want to let those data fetchers handle the gamepad input instead. -bool ShouldEnumerateGamepad(const std::u16string& product_name, - ABI::Windows::Gaming::Input::IGamepad* gamepad, - WgiDataFetcherWin::GetActivationFactoryFunction - get_activation_factory_function) { +GamepadId GetGamepadId(const std::u16string& product_name, + ABI::Windows::Gaming::Input::IGamepad* gamepad, + WgiDataFetcherWin::GetActivationFactoryFunction + get_activation_factory_function) { std::string product_name_string = base::UTF16ToUTF8(product_name); HRESULT hr = S_OK; Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IRawGameController> raw_game_controller = GetRawGameController(gamepad, get_activation_factory_function); if (!raw_game_controller) { - return false; + return GamepadId::kUnknownGamepad; } uint16_t vendor_id; hr = raw_game_controller->get_HardwareVendorId(&vendor_id); if (FAILED(hr)) { - return false; + return GamepadId::kUnknownGamepad; } uint16_t product_id; hr = raw_game_controller->get_HardwareProductId(&product_id); if (FAILED(hr)) { + return GamepadId::kUnknownGamepad; + } + + return GamepadIdList::Get().GetGamepadId(product_name_string, vendor_id, + product_id); +} + +// Check if the gamepad should be added by Windows.Gaming.Input. In the +// situation that a Nintendo or Dualshock4 gamepad is connected, there are +// dedicated data fetchers designed for these gamepads. +// We want to let those data fetchers handle the gamepad input instead. +bool ShouldEnumerateGamepad(GamepadId gamepad_id) { + if (gamepad_id == GamepadId::kUnknownGamepad) { return false; } - GamepadId gamepad_id = GamepadIdList::Get().GetGamepadId( - product_name_string, vendor_id, product_id); if (NintendoController::IsNintendoController(gamepad_id)) { // Nintendo devices are handled by the Nintendo data fetcher. return false; @@ -139,6 +146,33 @@ return num_paddles; } +bool HasTriggerRumbleSupport(GamepadId gamepad_id) { + // Xbox One USB + return gamepad_id == GamepadId::kMicrosoftProduct02d1 || + // Xbox One USB 2015 Firmware + gamepad_id == GamepadId::kMicrosoftProduct02dd || + // Xbox One S Bluetooth 2016 Firmware + gamepad_id == GamepadId::kMicrosoftProduct02fd || + // Xbox One S Bluetooth 2021 Firmware + gamepad_id == GamepadId::kMicrosoftProduct0b20 || + // Xbox One S USB + gamepad_id == GamepadId::kMicrosoftProduct02ea || + // Xbox One S Bluetooth + gamepad_id == GamepadId::kMicrosoftProduct02e0 || + // Xbox Series X USB + gamepad_id == GamepadId::kMicrosoftProduct0b12 || + // Xbox Series X Bluetooth + gamepad_id == GamepadId::kMicrosoftProduct0b13 || + // Xbox One Elite USB + gamepad_id == GamepadId::kMicrosoftProduct02e3 || + // Xbox One Elite Series 2 USB + gamepad_id == GamepadId::kMicrosoftProduct0b00 || + // Xbox One Elite Series 2 Bluetooth + gamepad_id == GamepadId::kMicrosoftProduct0b05 || + // Xbox Elite Series 2 Bluetooth 2021 Firmware + gamepad_id == GamepadId::kMicrosoftProduct0b05; +} + } // namespace WgiDataFetcherWin::WgiDataFetcherWin() { @@ -227,8 +261,9 @@ return; const std::u16string display_name = GetGamepadDisplayName(gamepad); - if (!ShouldEnumerateGamepad(display_name, gamepad, - get_activation_factory_function_)) { + GamepadId gamepad_id = + GetGamepadId(display_name, gamepad, get_activation_factory_function_); + if (!ShouldEnumerateGamepad(gamepad_id)) { return; } @@ -240,7 +275,13 @@ Gamepad& pad = state->data; pad.SetID(display_name); pad.connected = true; - pad.vibration_actuator.type = GamepadHapticActuatorType::kDualRumble; + + if (HasTriggerRumbleSupport(gamepad_id)) { + pad.vibration_actuator.type = GamepadHapticActuatorType::kTriggerRumble; + } else { + pad.vibration_actuator.type = GamepadHapticActuatorType::kDualRumble; + } + pad.vibration_actuator.not_null = true; pad.mapping = GamepadMapping::kStandard; devices_[source_id] = std::make_unique<WgiGamepadDevice>(gamepad);
diff --git a/device/gamepad/wgi_data_fetcher_win_unittest.cc b/device/gamepad/wgi_data_fetcher_win_unittest.cc index 6238ce6..f9ebef3 100644 --- a/device/gamepad/wgi_data_fetcher_win_unittest.cc +++ b/device/gamepad/wgi_data_fetcher_win_unittest.cc
@@ -35,8 +35,9 @@ using ::ABI::Windows::Gaming::Input::GamepadReading; -constexpr uint16_t kHardwareProductId = 1; -constexpr uint16_t kHardwareVendorId = 100; +constexpr uint16_t kHardwareVendorId = 0x045e; +constexpr uint16_t kHardwareProductId = 0x028e; +constexpr uint16_t kTriggerRumbleHardwareProductId = 0x0b13; constexpr char kGamepadDisplayName[] = "XBOX_SERIES_X"; constexpr double kErrorTolerance = 1e-5; @@ -145,13 +146,15 @@ } while (buffer->seqlock.ReadRetry(version)); } - void CheckGamepadAdded(PadState* pad_state) { + void CheckGamepadAdded(PadState* pad_state, + GamepadHapticActuatorType actuator_type) { // Check size of connected gamepad list and ensure gamepad state // is initialized correctly. EXPECT_TRUE(pad_state->is_initialized); Gamepad& pad = pad_state->data; EXPECT_TRUE(pad.connected); EXPECT_TRUE(pad.vibration_actuator.not_null); + EXPECT_EQ(pad.vibration_actuator.type, actuator_type); } void CheckGamepadRemoved() { @@ -308,9 +311,9 @@ provider_->PlayVibrationEffectOnce( pad_index, mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble, - mojom::GamepadEffectParameters::New(kDurationMillis, - kZeroStartDelayMillis, - kStrongMagnitude, kWeakMagnitude), + mojom::GamepadEffectParameters::New( + kDurationMillis, kZeroStartDelayMillis, kStrongMagnitude, + kWeakMagnitude, /*left_trigger=*/0, /*right_trigger=*/0), base::BindOnce(&WgiDataFetcherWinTest::HapticsCallback, base::Unretained(this)) .Then(run_loop.QuitClosure())); @@ -349,6 +352,7 @@ EXPECT_TRUE(fetcher().GetGamepadsForTesting().empty()); const auto fake_gamepad = Microsoft::WRL::Make<FakeIGamepad>(); + const auto fake_trigger_rumble_gamepad = Microsoft::WRL::Make<FakeIGamepad>(); auto* fake_gamepad_statics = FakeIGamepadStatics::GetInstance(); // Check that the event handlers were added. @@ -361,21 +365,29 @@ // Corresponding threading simulation is in FakeIGamepadStatics class. fake_gamepad_statics->SimulateGamepadAdded( fake_gamepad, kHardwareProductId, kHardwareVendorId, kGamepadDisplayName); + fake_gamepad_statics->SimulateGamepadAdded( + fake_trigger_rumble_gamepad, kTriggerRumbleHardwareProductId, + kHardwareVendorId, kGamepadDisplayName); - // Wait for the gampad polling thread to handle the gamepad added event. + // Wait for the gampad polling thread to handle the gamepad added events. FlushPollingThread(); - // Assert that the gamepad has been added to the DataFetcher. + // Assert that the gamepads have been added to the DataFetcher. const base::flat_map<int, std::unique_ptr<WgiGamepadDevice>>& gamepads = fetcher().GetGamepadsForTesting(); - ASSERT_EQ(gamepads.size(), 1u); - CheckGamepadAdded(fetcher().GetPadState(gamepads.begin()->first)); + ASSERT_EQ(gamepads.size(), 2u); + auto gamepad_iter = gamepads.begin(); + CheckGamepadAdded(fetcher().GetPadState(gamepad_iter++->first), + GamepadHapticActuatorType::kDualRumble); + CheckGamepadAdded(fetcher().GetPadState(gamepad_iter->first), + GamepadHapticActuatorType::kTriggerRumble); // Simulate the gamepad removing behavior, and make the gamepad-removing // callback return on a different thread, demonstrated the multi-threaded // apartments setting of the GamepadStatics COM API. Corresponding threading // simulation is in FakeIGamepadStatics class. fake_gamepad_statics->SimulateGamepadRemoved(fake_gamepad); + fake_gamepad_statics->SimulateGamepadRemoved(fake_trigger_rumble_gamepad); // Wait for the gampad polling thread to handle the gamepad removed event. FlushPollingThread(); @@ -441,7 +453,7 @@ PadState* pad = fetcher().GetPadState(gamepads.begin()->first); std::u16string display_id(pad->data.id); EXPECT_EQ(kDefaultDisplayName, display_id); - CheckGamepadAdded(pad); + CheckGamepadAdded(pad, GamepadHapticActuatorType::kDualRumble); } TEST_F(WgiDataFetcherWinTest, VerifyGamepadInput) { @@ -517,7 +529,7 @@ EXPECT_EQ(fake_gamepad_vibration.LeftTrigger, 0.0f); EXPECT_EQ(fake_gamepad_vibration.RightTrigger, 0.0f); - // Calling ResetVibration sets the vibration intensity to 0 for both motors. + // Calling ResetVibration sets the vibration intensity to 0 for all motors. SimulateResetVibration(/*pad_index=*/0); EXPECT_EQ(haptics_callback_count_, 2); EXPECT_EQ(haptics_callback_result_,
diff --git a/device/gamepad/wgi_gamepad_device.cc b/device/gamepad/wgi_gamepad_device.cc index e0aa220..3fb3efd 100644 --- a/device/gamepad/wgi_gamepad_device.cc +++ b/device/gamepad/wgi_gamepad_device.cc
@@ -5,6 +5,7 @@ #include "device/gamepad/wgi_gamepad_device.h" #include "base/trace_event/trace_event.h" +#include "device/gamepad/abstract_haptic_gamepad.h" namespace device { @@ -14,12 +15,12 @@ WgiGamepadDevice::~WgiGamepadDevice() = default; -void WgiGamepadDevice::SetVibration(double strong_magnitude, - double weak_magnitude) { +void WgiGamepadDevice::SetVibration(mojom::GamepadEffectParametersPtr params) { ABI::Windows::Gaming::Input::GamepadVibration vibration = { - .LeftMotor = strong_magnitude, - .RightMotor = weak_magnitude, - }; + .LeftMotor = params->strong_magnitude, + .RightMotor = params->weak_magnitude, + .LeftTrigger = params->left_trigger, + .RightTrigger = params->right_trigger}; HRESULT hr = gamepad_->put_Vibration(vibration); DCHECK(SUCCEEDED(hr)); }
diff --git a/device/gamepad/wgi_gamepad_device.h b/device/gamepad/wgi_gamepad_device.h index a2eb0a9..a6b1d0f 100644 --- a/device/gamepad/wgi_gamepad_device.h +++ b/device/gamepad/wgi_gamepad_device.h
@@ -25,7 +25,7 @@ ~WgiGamepadDevice() override; // AbstractHapticGamepad implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad> GetGamepad() {
diff --git a/device/gamepad/xbox_controller_mac.h b/device/gamepad/xbox_controller_mac.h index f86428d..8f37907 100644 --- a/device/gamepad/xbox_controller_mac.h +++ b/device/gamepad/xbox_controller_mac.h
@@ -104,7 +104,7 @@ // AbstractHapticGamepad implementation. void DoShutdown() override; double GetMaxEffectDurationMillis() override; - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; uint32_t location_id() const { return location_id_; }
diff --git a/device/gamepad/xbox_controller_mac.mm b/device/gamepad/xbox_controller_mac.mm index 6436df4..cca9b0d 100644 --- a/device/gamepad/xbox_controller_mac.mm +++ b/device/gamepad/xbox_controller_mac.mm
@@ -332,14 +332,14 @@ return kXboxOneMaxEffectDurationMillis; } -void XboxControllerMac::SetVibration(double strong_magnitude, - double weak_magnitude) { +void XboxControllerMac::SetVibration(mojom::GamepadEffectParametersPtr params) { if (!SupportsVibration()) return; // Clamp magnitudes to [0,1] - strong_magnitude = base::clamp<double>(strong_magnitude, 0.0, 1.0); - weak_magnitude = base::clamp<double>(weak_magnitude, 0.0, 1.0); + double strong_magnitude = + base::clamp<double>(params->strong_magnitude, 0.0, 1.0); + double weak_magnitude = base::clamp<double>(params->weak_magnitude, 0.0, 1.0); if (xinput_type_ == kXInputTypeXbox360) { WriteXbox360Rumble(static_cast<uint8_t>(strong_magnitude * 255.0),
diff --git a/device/gamepad/xbox_hid_controller.cc b/device/gamepad/xbox_hid_controller.cc index 711829e0..6dd76c7 100644 --- a/device/gamepad/xbox_hid_controller.cc +++ b/device/gamepad/xbox_hid_controller.cc
@@ -37,17 +37,16 @@ writer_.reset(); } -void XboxHidController::SetVibration(double strong_magnitude, - double weak_magnitude) { +void XboxHidController::SetVibration(mojom::GamepadEffectParametersPtr params) { DCHECK(writer_); std::array<uint8_t, 9> control_report; control_report.fill(0); control_report[0] = 0x03; // report ID control_report[1] = 0x03; // enable rumble motors, disable trigger haptics control_report[4] = - static_cast<uint8_t>(strong_magnitude * kRumbleMagnitudeMax); + static_cast<uint8_t>(params->strong_magnitude * kRumbleMagnitudeMax); control_report[5] = - static_cast<uint8_t>(weak_magnitude * kRumbleMagnitudeMax); + static_cast<uint8_t>(params->weak_magnitude * kRumbleMagnitudeMax); control_report[6] = 0xff; // duration control_report[7] = 0x00; // start delay control_report[8] = 0x01; // loop count
diff --git a/device/gamepad/xbox_hid_controller.h b/device/gamepad/xbox_hid_controller.h index 51ab9ca..ed616467 100644 --- a/device/gamepad/xbox_hid_controller.h +++ b/device/gamepad/xbox_hid_controller.h
@@ -27,7 +27,7 @@ static bool IsXboxHid(GamepadId gamepad_id); // AbstractHapticGamepad public implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; private:
diff --git a/device/gamepad/xbox_hid_controller_unittest.cc b/device/gamepad/xbox_hid_controller_unittest.cc index ee4d57d..2291c9e 100644 --- a/device/gamepad/xbox_hid_controller_unittest.cc +++ b/device/gamepad/xbox_hid_controller_unittest.cc
@@ -93,8 +93,9 @@ mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) { gamepad_->PlayEffect( mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble, - mojom::GamepadEffectParameters::New(kDurationMillis, start_delay, - strong_magnitude, weak_magnitude), + mojom::GamepadEffectParameters::New( + kDurationMillis, start_delay, strong_magnitude, weak_magnitude, + /*left_trigger=*/0, /*right_trigger=*/0), std::move(callback), base::ThreadTaskRunnerHandle::Get()); }
diff --git a/device/gamepad/xinput_haptic_gamepad_win.cc b/device/gamepad/xinput_haptic_gamepad_win.cc index 8666c31..754f6bc 100644 --- a/device/gamepad/xinput_haptic_gamepad_win.cc +++ b/device/gamepad/xinput_haptic_gamepad_win.cc
@@ -19,15 +19,15 @@ XInputHapticGamepadWin::~XInputHapticGamepadWin() = default; -void XInputHapticGamepadWin::SetVibration(double strong_magnitude, - double weak_magnitude) { +void XInputHapticGamepadWin::SetVibration( + mojom::GamepadEffectParametersPtr params) { if (pad_id_ < 0 || pad_id_ > XUSER_MAX_COUNT || xinput_set_state_ == nullptr) return; XINPUT_VIBRATION vibration; vibration.wLeftMotorSpeed = - static_cast<long>(strong_magnitude * kRumbleMagnitudeMax); + static_cast<long>(params->strong_magnitude * kRumbleMagnitudeMax); vibration.wRightMotorSpeed = - static_cast<long>(weak_magnitude * kRumbleMagnitudeMax); + static_cast<long>(params->weak_magnitude * kRumbleMagnitudeMax); TRACE_EVENT_BEGIN1("GAMEPAD", "XInputSetState", "id", pad_id_); xinput_set_state_(pad_id_, &vibration);
diff --git a/device/gamepad/xinput_haptic_gamepad_win.h b/device/gamepad/xinput_haptic_gamepad_win.h index a290532..c426ca1 100644 --- a/device/gamepad/xinput_haptic_gamepad_win.h +++ b/device/gamepad/xinput_haptic_gamepad_win.h
@@ -22,7 +22,7 @@ ~XInputHapticGamepadWin() override; // AbstractHapticGamepad implementation. - void SetVibration(double strong_magnitude, double weak_magnitude) override; + void SetVibration(mojom::GamepadEffectParametersPtr params) override; base::WeakPtr<AbstractHapticGamepad> GetWeakPtr() override; private:
diff --git a/docs/gpu/sync_token_internals.md b/docs/gpu/sync_token_internals.md index bc272f88..280abc71 100644 --- a/docs/gpu/sync_token_internals.md +++ b/docs/gpu/sync_token_internals.md
@@ -11,7 +11,7 @@ In Chrome, multiple processes, for example browser and renderer, submit work to the GPU process asynchronously in command buffer. However, there are dependencies between the work submitted by different processes, such as -GLRenderer in display compositor in the browser/viz process rendering a tile +SkiaRenderer in the display compositor in the GPU process rendering a tile produced by the raster worker in the renderer process. Sync tokens are used to synchronize the work contained in command buffers
diff --git a/docs/life_of_a_frame.md b/docs/life_of_a_frame.md index 0a8c2085..fbb60e7c 100644 --- a/docs/life_of_a_frame.md +++ b/docs/life_of_a_frame.md
@@ -27,7 +27,7 @@ Rasterization may occur asynchronously on separate threads, or even another process (OOP-R, or out-of-process rasterization). If rasterization cannot be finished before the deadline for activation, the pipeline will not perform the copying from pending tree to the active tree in step [7], and will instead proceed to step [8] with whatever is already in the active tree. ### `[7]` Activation -Activation is the process of pushing layer trees and properties from the pending tree to the active tree (active_tree_). Note that Impl thread can also directly manipulate the activate tree to reflect updates the impl thread makes in step [2]. +Activation is the process of pushing layer trees and properties from the pending tree to the active tree (active_tree_). Note that Impl thread can also directly manipulate the activate tree to reflect updates the impl thread makes in step [2]. ### `[8]` Wait for deadline The deadline for compositor frame submission is provided by the GPU process (Scheduler::BeginImplFrameWithDeadline()). @@ -39,7 +39,7 @@ After each client submitted CompositorFrame (or signalled that it DidNotProduceFrame) the Display Compositor can proceed with the draw. Note that if the DisplayScheduler hits a deadline it will still draw if any client has submitted a new CompositorFrame, even if it's still waiting on a response for other clients. Before the actual draw could happen SurfaceAggregator will recursively walk over compositor frames and replace SurfaceQuads (quads produced by SurfaceLayer) with contents of the embedded compositor frame. This step produces single CompositorFrame in the end that can be drawn by the Display Compositor. ### `[11]` Draw Frame -During draw Display Compositor will go over quads and render passes in the aggregated compositor frame and produce draw commands. For GLRenderer it's gl calls recorded by InProcessCommandBuffer and for SkiaRenderer it's recording of Deferred Display Lists (DDL). +During draw Display Compositor will go over quads and render passes in the aggregated compositor frame and produce draw commands. For SkiaRenderer it's recording of Deferred Display Lists (DDL). ### `[12]` RequestSwap After commands were recorded they will be submitted to the GPU thread to replay along with SwapBuffers request to show the result on screen. @@ -51,7 +51,7 @@ GPU Main Thread does all the GPU work and by the time display compositor is ready to draw it might still be busy doing other tasks (e.g raster for next frame). gpu::Scheduler uses cooperative multi-tasking and can't preempt the current task unless it yields, so the task submitted by the display compositor might have to wait until the current task (and potentially some other high priority tasks) are finished. ### `[15]` GPU draw -Finally tasks that DisplayCompositor posted to GPU Main thread executed and we replay draw commands recorded during Draw Frame [11]. For GLRenderer InProcessCommand buffer will be issuing recorded GL calls, for SkiaRenderer Skia will be replaying DDLs and issue commands to the GPU. This step is when we finally submit the job to the GPU (not GPU thread on CPU). +Finally tasks that DisplayCompositor posted to GPU Main thread executed and we replay draw commands recorded during Draw Frame [11]. For SkiaRenderer Skia will be replaying DDLs and issue commands to the GPU. This step is when we finally submit the job to the GPU (not GPU thread on CPU). ### `[16]` Swap The GPU work has been submitted and we signal that we want to present the result (Submits commands to request displaying framebuffer and/or overlays after drawing new content into them). Depending on the platform this step can be blocking or not and take a substantial amount of time (eg. if we have too many queued swaps sometimes this will just block until the next vblank).
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 4677d4a..9e31564 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1739,6 +1739,7 @@ AUTOTESTPRIVATE_SENDARCOVERLAYCOLOR = 1676, AUTOTESTPRIVATE_ISINPUTMETHODREADYFORTESTING = 1677, AUTOTESTPRIVATE_GETARCAPPKILLS = 1678, + FILEMANAGERPRIVATE_OPENMANAGESYNCSETTINGS = 1679, // Last entry: Add new entries above, then run: // tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index ed22df7..969f3fdc 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h
@@ -75,7 +75,7 @@ IPC_STRUCT_MEMBER(std::string, api_call) // List of arguments. - IPC_STRUCT_MEMBER(base::ListValue, arguments) + IPC_STRUCT_MEMBER(base::Value::List, arguments) // Extra logging information. IPC_STRUCT_MEMBER(std::string, extra)
diff --git a/extensions/renderer/api_activity_logger.cc b/extensions/renderer/api_activity_logger.cc index 6e21ffa0a..74b885cd 100644 --- a/extensions/renderer/api_activity_logger.cc +++ b/extensions/renderer/api_activity_logger.cc
@@ -179,9 +179,7 @@ DCHECK(IsLoggingEnabled()); ExtensionHostMsg_APIActionOrEvent_Params params; params.api_call = call_name; - // TODO(https://crbug.com/1187062): Switch to base::Value::List instead of - // base::ListValue, which is deprecated. - params.arguments.GetList() = std::move(arguments); + params.arguments = std::move(arguments); params.extra = extra; ipc_sender->SendActivityLogIPC(extension_id, call_type, params); }
diff --git a/extensions/renderer/api_activity_logger_unittest.cc b/extensions/renderer/api_activity_logger_unittest.cc index e041199..7167429 100644 --- a/extensions/renderer/api_activity_logger_unittest.cc +++ b/extensions/renderer/api_activity_logger_unittest.cc
@@ -67,9 +67,8 @@ .WillOnce([&](const ExtensionId& extension_id, const ActivityLogCallType, const ExtensionHostMsg_APIActionOrEvent_Params& params) { EXPECT_EQ("someApiMethod", params.api_call); - ASSERT_EQ(1u, params.arguments.GetList().size()); - EXPECT_EQ(base::Value::Type::NONE, - params.arguments.GetList()[0].type()); + ASSERT_EQ(1u, params.arguments.size()); + EXPECT_EQ(base::Value::Type::NONE, params.arguments[0].type()); }); APIActivityLogger::LogAPICall(ipc_sender.get(), context, "someApiMethod",
diff --git a/gpu/command_buffer/client/gl_helper.h b/gpu/command_buffer/client/gl_helper.h index 6be5cd50..246eb06 100644 --- a/gpu/command_buffer/client/gl_helper.h +++ b/gpu/command_buffer/client/gl_helper.h
@@ -420,8 +420,8 @@ // and read back a texture from the GPU into CPU-accessible RAM. A single // readback pipeline can handle multiple outstanding readbacks at the same time. // -// TODO(crbug.com/870036): DEPRECATED. This will be removed soon, in favor of -// I420Converter and readback implementation in GLRendererCopier. +// TODO(crbug.com/870036): DEPRECATED. This will be removed soon in favor of +// I420Converter. class GPU_EXPORT ReadbackYUVInterface { public: ReadbackYUVInterface() {}
diff --git a/gpu/command_buffer/common/shared_image_usage.cc b/gpu/command_buffer/common/shared_image_usage.cc index 118f3fd..9eb520d2b 100644 --- a/gpu/command_buffer/common/shared_image_usage.cc +++ b/gpu/command_buffer/common/shared_image_usage.cc
@@ -9,6 +9,9 @@ namespace gpu { std::string CreateLabelForSharedImageUsage(uint32_t usage) { + if (!usage) + return ""; + std::string label; if (usage & SHARED_IMAGE_USAGE_GLES2) { @@ -56,6 +59,9 @@ if (usage & SHARED_IMAGE_USAGE_MIPMAP) { label += "|Mipmap"; } + if (usage & SHARED_IMAGE_USAGE_CPU_WRITE) { + label += "|CpuWrite"; + } DCHECK(!label.empty());
diff --git a/gpu/command_buffer/service/external_vk_image_backing.cc b/gpu/command_buffer/service/external_vk_image_backing.cc index c019623..76bfc4d 100644 --- a/gpu/command_buffer/service/external_vk_image_backing.cc +++ b/gpu/command_buffer/service/external_vk_image_backing.cc
@@ -507,6 +507,10 @@ } } +SharedImageBackingType ExternalVkImageBacking::GetType() const { + return SharedImageBackingType::kExternalVkImage; +} + void ExternalVkImageBacking::Update(std::unique_ptr<gfx::GpuFence> in_fence) { DCHECK(!in_fence); latest_content_ = kInSharedMemory;
diff --git a/gpu/command_buffer/service/external_vk_image_backing.h b/gpu/command_buffer/service/external_vk_image_backing.h index 04b32ed..d10ab6d 100644 --- a/gpu/command_buffer/service/external_vk_image_backing.h +++ b/gpu/command_buffer/service/external_vk_image_backing.h
@@ -133,6 +133,7 @@ bool is_gl); // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; scoped_refptr<gfx::NativePixmap> GetNativePixmap() override;
diff --git a/gpu/command_buffer/service/raster_decoder_unittest.cc b/gpu/command_buffer/service/raster_decoder_unittest.cc index db24142..96a703b 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest.cc
@@ -233,7 +233,6 @@ shared_image_factory_ = std::make_unique<SharedImageFactory>( GpuPreferences(), workarounds, GpuFeatureInfo(), context_state_.get(), &mailbox_manager_, &shared_image_manager_, nullptr, nullptr, - /*enable_wrapped_sk_image=*/true, /*is_for_display_compositor=*/false); client_texture_mailbox_ =
diff --git a/gpu/command_buffer/service/shared_image_backing.cc b/gpu/command_buffer/service/shared_image_backing.cc index 9dc3515e..b0705ef 100644 --- a/gpu/command_buffer/service/shared_image_backing.cc +++ b/gpu/command_buffer/service/shared_image_backing.cc
@@ -12,6 +12,41 @@ #include "gpu/command_buffer/service/texture_manager.h" namespace gpu { +namespace { + +const char* BackingTypeToString(SharedImageBackingType type) { + switch (type) { + case SharedImageBackingType::kTest: + return "TestBacking"; + case SharedImageBackingType::kExternalVkImage: + return "ExternalVkImageBacking"; + case SharedImageBackingType::kD3D: + return "SharedImageBackingD3D"; + case SharedImageBackingType::kEglImage: + return "SharedImageBackingEglImage"; + case SharedImageBackingType::kAHB: + return "SharedImageBackingAHB"; + case SharedImageBackingType::kAngleVulkan: + return "AngleVulkanBacking"; + case SharedImageBackingType::kGLImage: + return "SharedImageBackingGLImage"; + case SharedImageBackingType::kGLTexture: + return "SharedImageBackingGLTexture"; + case SharedImageBackingType::kOzone: + return "SharedImageBackingOzone"; + case SharedImageBackingType::kRawDraw: + return "SharedImageBackingRawDraw"; + case SharedImageBackingType::kSharedMemory: + return "SharedImageBackingSharedMemory"; + case SharedImageBackingType::kVideo: + return "SharedImageVideo"; + case SharedImageBackingType::kWrappedSkImage: + return "WrappedSkImage"; + } + NOTREACHED(); +}; + +} // namespace SharedImageBacking::SharedImageBacking(const Mailbox& mailbox, viz::ResourceFormat format, @@ -173,6 +208,10 @@ factory_ = nullptr; } +const char* SharedImageBacking::GetName() const { + return BackingTypeToString(GetType()); +} + bool SharedImageBacking::HasAnyRefs() const { AutoLock auto_lock(this);
diff --git a/gpu/command_buffer/service/shared_image_backing.h b/gpu/command_buffer/service/shared_image_backing.h index daa393b..fbf5d74 100644 --- a/gpu/command_buffer/service/shared_image_backing.h +++ b/gpu/command_buffer/service/shared_image_backing.h
@@ -55,6 +55,22 @@ class SharedImageFactory; class VaapiDependenciesFactory; +enum class SharedImageBackingType { + kTest = 0, + kExternalVkImage = 1, + kD3D = 2, + kEglImage = 3, + kAHB = 4, + kAngleVulkan = 5, + kGLImage = 6, + kGLTexture = 7, + kOzone = 8, + kRawDraw = 9, + kSharedMemory = 10, + kVideo = 11, + kWrappedSkImage = 12 +}; + // Represents the actual storage (GL texture, VkImage, GMB) for a SharedImage. // Should not be accessed directly, instead is accessed through a // SharedImageRepresentation. @@ -102,6 +118,11 @@ void RegisterImageFactory(SharedImageFactory* factory); void UnregisterImageFactory(); + // Returns string corresponding to GetType() for logging purposes. + const char* GetName() const; + + virtual SharedImageBackingType GetType() const = 0; + // Returns the initialized / cleared region of the SharedImage. virtual gfx::Rect ClearedRect() const = 0;
diff --git a/gpu/command_buffer/service/shared_image_backing_android.cc b/gpu/command_buffer/service/shared_image_backing_android.cc index 9644b67a..3c46bdae 100644 --- a/gpu/command_buffer/service/shared_image_backing_android.cc +++ b/gpu/command_buffer/service/shared_image_backing_android.cc
@@ -32,7 +32,7 @@ is_thread_safe), write_sync_fd_(std::move(initial_upload_fd)) {} -SharedImageBackingAndroid::~SharedImageBackingAndroid() {} +SharedImageBackingAndroid::~SharedImageBackingAndroid() = default; bool SharedImageBackingAndroid::BeginWrite(base::ScopedFD* fd_to_wait_on) { AutoLock auto_lock(this);
diff --git a/gpu/command_buffer/service/shared_image_backing_d3d.cc b/gpu/command_buffer/service/shared_image_backing_d3d.cc index 4e1058e7..6e4e5a64 100644 --- a/gpu/command_buffer/service/shared_image_backing_d3d.cc +++ b/gpu/command_buffer/service/shared_image_backing_d3d.cc
@@ -441,6 +441,10 @@ return staging_texture_.Get(); } +SharedImageBackingType SharedImageBackingD3D::GetType() const { + return SharedImageBackingType::kD3D; +} + void SharedImageBackingD3D::Update(std::unique_ptr<gfx::GpuFence> in_fence) { DCHECK(!in_fence); if (!shared_memory_handle_.is_null())
diff --git a/gpu/command_buffer/service/shared_image_backing_d3d.h b/gpu/command_buffer/service/shared_image_backing_d3d.h index ae1873e5..d25d735 100644 --- a/gpu/command_buffer/service/shared_image_backing_d3d.h +++ b/gpu/command_buffer/service/shared_image_backing_d3d.h
@@ -104,20 +104,17 @@ ~SharedImageBackingD3D() override; + // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; - bool CopyToGpuMemoryBuffer() override; - bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; - bool PresentSwapChain() override; - std::unique_ptr<SharedImageRepresentationDawn> ProduceDawn( SharedImageManager* manager, MemoryTypeTracker* tracker, WGPUDevice device, WGPUBackendType backend_type) override; - void OnMemoryDump(const std::string& dump_name, base::trace_event::MemoryAllocatorDump* dump, base::trace_event::ProcessMemoryDump* pmd,
diff --git a/gpu/command_buffer/service/shared_image_backing_egl_image.cc b/gpu/command_buffer/service/shared_image_backing_egl_image.cc index fc80df1..829c01f 100644 --- a/gpu/command_buffer/service/shared_image_backing_egl_image.cc +++ b/gpu/command_buffer/service/shared_image_backing_egl_image.cc
@@ -224,6 +224,10 @@ DCHECK(!source_texture_holder_); } +SharedImageBackingType SharedImageBackingEglImage::GetType() const { + return SharedImageBackingType::kEglImage; +} + void SharedImageBackingEglImage::Update( std::unique_ptr<gfx::GpuFence> in_fence) { NOTREACHED();
diff --git a/gpu/command_buffer/service/shared_image_backing_egl_image.h b/gpu/command_buffer/service/shared_image_backing_egl_image.h index b156e9b..4611da3 100644 --- a/gpu/command_buffer/service/shared_image_backing_egl_image.h +++ b/gpu/command_buffer/service/shared_image_backing_egl_image.h
@@ -59,6 +59,8 @@ ~SharedImageBackingEglImage() override; + // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; void MarkForDestruction() override;
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc index 59e4d2dc..f12ca3e 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc
@@ -138,6 +138,8 @@ ~SharedImageBackingAHB() override; + // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; // We never generate LegacyMailboxes in threadsafe mode, so exclude this // function from thread safety analysis. @@ -277,6 +279,10 @@ } } +SharedImageBackingType SharedImageBackingAHB::GetType() const { + return SharedImageBackingType::kAHB; +} + gfx::Rect SharedImageBackingAHB::ClearedRect() const { AutoLock auto_lock(this); // If a |legacy_texture_| exists, defer to that. Once created,
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_angle_vulkan.cc b/gpu/command_buffer/service/shared_image_backing_factory_angle_vulkan.cc index 33206e1f..aabbf84 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_angle_vulkan.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_angle_vulkan.cc
@@ -155,6 +155,10 @@ protected: // SharedImageBacking implementation. + SharedImageBackingType GetType() const override { + return SharedImageBackingType::kAngleVulkan; + } + bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override { NOTREACHED() << "Not supported."; return false;
diff --git a/gpu/command_buffer/service/shared_image_backing_gl_image.cc b/gpu/command_buffer/service/shared_image_backing_gl_image.cc index 7e6f861a..5010e7b5 100644 --- a/gpu/command_buffer/service/shared_image_backing_gl_image.cc +++ b/gpu/command_buffer/service/shared_image_backing_gl_image.cc
@@ -487,6 +487,10 @@ image_->OnMemoryDump(pmd, client_tracing_id, dump_name); } +SharedImageBackingType SharedImageBackingGLImage::GetType() const { + return SharedImageBackingType::kGLImage; +} + gfx::Rect SharedImageBackingGLImage::ClearedRect() const { if (texture_) return texture_->GetLevelClearedRect(texture_->target(), 0);
diff --git a/gpu/command_buffer/service/shared_image_backing_gl_image.h b/gpu/command_buffer/service/shared_image_backing_gl_image.h index 7759861..70721ce 100644 --- a/gpu/command_buffer/service/shared_image_backing_gl_image.h +++ b/gpu/command_buffer/service/shared_image_backing_gl_image.h
@@ -214,6 +214,7 @@ base::trace_event::MemoryAllocatorDump* dump, base::trace_event::ProcessMemoryDump* pmd, uint64_t client_tracing_id) override; + SharedImageBackingType GetType() const override; gfx::Rect ClearedRect() const final; void SetClearedRect(const gfx::Rect& cleared_rect) final; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) final;
diff --git a/gpu/command_buffer/service/shared_image_backing_gl_texture.cc b/gpu/command_buffer/service/shared_image_backing_gl_texture.cc index 58f69f0..840fc72 100644 --- a/gpu/command_buffer/service/shared_image_backing_gl_texture.cc +++ b/gpu/command_buffer/service/shared_image_backing_gl_texture.cc
@@ -138,6 +138,10 @@ } } +SharedImageBackingType SharedImageBackingGLTexture::GetType() const { + return SharedImageBackingType::kGLTexture; +} + gfx::Rect SharedImageBackingGLTexture::ClearedRect() const { if (!IsPassthrough()) return texture_->GetLevelClearedRect(texture_->target(), 0);
diff --git a/gpu/command_buffer/service/shared_image_backing_gl_texture.h b/gpu/command_buffer/service/shared_image_backing_gl_texture.h index 70a0371..67fcfce0 100644 --- a/gpu/command_buffer/service/shared_image_backing_gl_texture.h +++ b/gpu/command_buffer/service/shared_image_backing_gl_texture.h
@@ -46,6 +46,7 @@ base::trace_event::MemoryAllocatorDump* dump, base::trace_event::ProcessMemoryDump* pmd, uint64_t client_tracing_id) override; + SharedImageBackingType GetType() const override; gfx::Rect ClearedRect() const final; void SetClearedRect(const gfx::Rect& cleared_rect) final; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) final;
diff --git a/gpu/command_buffer/service/shared_image_backing_ozone.cc b/gpu/command_buffer/service/shared_image_backing_ozone.cc index 2aec225..d13b27d 100644 --- a/gpu/command_buffer/service/shared_image_backing_ozone.cc +++ b/gpu/command_buffer/service/shared_image_backing_ozone.cc
@@ -130,6 +130,10 @@ SharedImageBackingOzone::~SharedImageBackingOzone() = default; +SharedImageBackingType SharedImageBackingOzone::GetType() const { + return SharedImageBackingType::kOzone; +} + void SharedImageBackingOzone::Update(std::unique_ptr<gfx::GpuFence> in_fence) { if (shared_memory_wrapper_.IsValid()) { DCHECK(!in_fence);
diff --git a/gpu/command_buffer/service/shared_image_backing_ozone.h b/gpu/command_buffer/service/shared_image_backing_ozone.h index e5926cc3..c76cf4f 100644 --- a/gpu/command_buffer/service/shared_image_backing_ozone.h +++ b/gpu/command_buffer/service/shared_image_backing_ozone.h
@@ -58,6 +58,7 @@ ~SharedImageBackingOzone() override; // gpu::SharedImageBacking: + SharedImageBackingType GetType() const override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; scoped_refptr<gfx::NativePixmap> GetNativePixmap() override;
diff --git a/gpu/command_buffer/service/shared_image_backing_raw_draw.cc b/gpu/command_buffer/service/shared_image_backing_raw_draw.cc index 25b8e8b..81e57d8 100644 --- a/gpu/command_buffer/service/shared_image_backing_raw_draw.cc +++ b/gpu/command_buffer/service/shared_image_backing_raw_draw.cc
@@ -128,6 +128,10 @@ DestroyBackendTexture(); } +SharedImageBackingType SharedImageBackingRawDraw::GetType() const { + return SharedImageBackingType::kRawDraw; +} + bool SharedImageBackingRawDraw::ProduceLegacyMailbox( MailboxManager* mailbox_manager) { NOTIMPLEMENTED();
diff --git a/gpu/command_buffer/service/shared_image_backing_raw_draw.h b/gpu/command_buffer/service/shared_image_backing_raw_draw.h index 49df5f6..85fefb8 100644 --- a/gpu/command_buffer/service/shared_image_backing_raw_draw.h +++ b/gpu/command_buffer/service/shared_image_backing_raw_draw.h
@@ -33,6 +33,7 @@ ~SharedImageBackingRawDraw() override; // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; void OnMemoryDump(const std::string& dump_name,
diff --git a/gpu/command_buffer/service/shared_image_backing_shared_memory.cc b/gpu/command_buffer/service/shared_image_backing_shared_memory.cc index 6053d2db..95e0ef7c 100644 --- a/gpu/command_buffer/service/shared_image_backing_shared_memory.cc +++ b/gpu/command_buffer/service/shared_image_backing_shared_memory.cc
@@ -92,6 +92,10 @@ return false; } +SharedImageBackingType SharedImageBackingSharedMemory::GetType() const { + return SharedImageBackingType::kSharedMemory; +} + gfx::Rect SharedImageBackingSharedMemory::ClearedRect() const { NOTREACHED(); return gfx::Rect();
diff --git a/gpu/command_buffer/service/shared_image_backing_shared_memory.h b/gpu/command_buffer/service/shared_image_backing_shared_memory.h index cdeea03..e99749d5 100644 --- a/gpu/command_buffer/service/shared_image_backing_shared_memory.h +++ b/gpu/command_buffer/service/shared_image_backing_shared_memory.h
@@ -36,6 +36,7 @@ // gpu::SharedImageBacking: void Update(std::unique_ptr<gfx::GpuFence> in_fence) override; bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override; + SharedImageBackingType GetType() const override; gfx::Rect ClearedRect() const override; void SetClearedRect(const gfx::Rect& cleared_rect) override; @@ -82,4 +83,4 @@ } // namespace gpu -#endif // GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_BACKING_SHARED_MEMORY_H_ \ No newline at end of file +#endif // GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_BACKING_SHARED_MEMORY_H_
diff --git a/gpu/command_buffer/service/shared_image_factory.cc b/gpu/command_buffer/service/shared_image_factory.cc index 4db9ecb..43987eee 100644 --- a/gpu/command_buffer/service/shared_image_factory.cc +++ b/gpu/command_buffer/service/shared_image_factory.cc
@@ -31,6 +31,8 @@ #include "gpu/command_buffer/service/wrapped_sk_image.h" #include "gpu/config/gpu_preferences.h" #include "ui/base/ui_base_features.h" +#include "ui/gfx/buffer_format_util.h" +#include "ui/gfx/gpu_memory_buffer.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/gl_switches.h" @@ -109,6 +111,21 @@ #endif } +const char* GmbTypeToString(gfx::GpuMemoryBufferType type) { + switch (type) { + case gfx::EMPTY_BUFFER: + return "empty"; + case gfx::SHARED_MEMORY_BUFFER: + return "shared_memory"; + case gfx::IO_SURFACE_BUFFER: + case gfx::NATIVE_PIXMAP: + case gfx::DXGI_SHARED_HANDLE: + case gfx::ANDROID_HARDWARE_BUFFER: + return "platform"; + } + NOTREACHED(); +} + enum DmaBufSupportedType { // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. @@ -214,7 +231,6 @@ SharedImageManager* shared_image_manager, ImageFactory* image_factory, MemoryTracker* memory_tracker, - bool enable_wrapped_sk_image, bool is_for_display_compositor) : mailbox_manager_(mailbox_manager), shared_image_manager_(shared_image_manager), @@ -289,7 +305,7 @@ std::make_unique<SharedImageBackingFactorySharedMemory>(); factories_.push_back(std::move(shared_memory_backing_factory)); - if (enable_wrapped_sk_image && context_state) { + if (context_state) { auto wrapped_sk_image_factory = std::make_unique<raster::WrappedSkImageFactory>(context_state); factories_.push_back(std::move(wrapped_sk_image_factory)); @@ -446,9 +462,14 @@ /*is_pixel_used=*/false); if (!factory) return false; + auto backing = factory->CreateSharedImage( mailbox, format, surface_handle, size, color_space, surface_origin, alpha_type, usage, IsSharedBetweenThreads(usage)); + DVLOG(1) << "CreateSharedImage[" << backing->GetName() + << "] size=" << size.ToString() + << " usage=" << CreateLabelForSharedImageUsage(usage) + << " resource_format=" << viz::ResourceFormatToString(format); return RegisterBacking(std::move(backing), allow_legacy_mailbox); } @@ -481,11 +502,18 @@ } if (!factory) return false; + auto backing = factory->CreateSharedImage(mailbox, format, size, color_space, surface_origin, alpha_type, usage, data); - if (backing) + if (backing) { + DVLOG(1) << "CreateSharedImagePixels[" << backing->GetName() + << "] with pixels size=" << size.ToString() + << " usage=" << CreateLabelForSharedImageUsage(usage) + << " resource_format=" << viz::ResourceFormatToString(format); + backing->OnWriteSucceeded(); + } return RegisterBacking(std::move(backing), allow_legacy_mailbox); } @@ -509,11 +537,20 @@ /*is_pixel_used=*/false, handle.type); if (!factory) return false; + + gfx::GpuMemoryBufferType gmb_type = handle.type; auto backing = factory->CreateSharedImage( mailbox, client_id, std::move(handle), format, plane, surface_handle, size, color_space, surface_origin, alpha_type, usage); - if (backing) + if (backing) { + DVLOG(1) << "CreateSharedImage[" << backing->GetName() + << "] from handle size=" << size.ToString() + << " usage=" << CreateLabelForSharedImageUsage(usage) + << " buffer_format=" << gfx::BufferFormatToString(format) + << " gmb_type=" << GmbTypeToString(gmb_type); + backing->OnWriteSucceeded(); + } return RegisterBacking(std::move(backing), allow_legacy_mailbox); } @@ -728,9 +765,9 @@ } LOG(ERROR) << "Could not find SharedImageBackingFactory with params: usage: " - << usage << ", format: " << format + << CreateLabelForSharedImageUsage(usage) << ", format: " << format << ", share_between_threads: " << share_between_threads - << ", gmb_type: " << gmb_type; + << ", gmb_type: " << GmbTypeToString(gmb_type); return nullptr; }
diff --git a/gpu/command_buffer/service/shared_image_factory.h b/gpu/command_buffer/service/shared_image_factory.h index 4c717ac2..82aabc3 100644 --- a/gpu/command_buffer/service/shared_image_factory.h +++ b/gpu/command_buffer/service/shared_image_factory.h
@@ -55,7 +55,6 @@ SharedImageManager* manager, ImageFactory* image_factory, MemoryTracker* tracker, - bool enable_wrapped_sk_image, bool is_for_display_compositor); ~SharedImageFactory();
diff --git a/gpu/command_buffer/service/shared_image_factory_unittest.cc b/gpu/command_buffer/service/shared_image_factory_unittest.cc index 7d2831c..83a9e71 100644 --- a/gpu/command_buffer/service/shared_image_factory_unittest.cc +++ b/gpu/command_buffer/service/shared_image_factory_unittest.cc
@@ -40,7 +40,6 @@ factory_ = std::make_unique<SharedImageFactory>( preferences, workarounds, GpuFeatureInfo(), nullptr, &mailbox_manager_, &shared_image_manager_, &image_factory_, nullptr, - /*enable_wrapped_sk_image=*/false, /*is_for_display_compositor=*/false); } @@ -95,7 +94,7 @@ auto other_factory = std::make_unique<SharedImageFactory>( preferences, workarounds, GpuFeatureInfo(), nullptr, &mailbox_manager_, &shared_image_manager_, &image_factory_, nullptr, - /*enable_wrapped_sk_image=*/false, /*is_for_display_compositor=*/false); + /*is_for_display_compositor=*/false); EXPECT_FALSE(other_factory->CreateSharedImage( mailbox, format, size, color_space, kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, surface_handle, usage));
diff --git a/gpu/command_buffer/service/shared_image_video.cc b/gpu/command_buffer/service/shared_image_video.cc index 5313809..961b00f 100644 --- a/gpu/command_buffer/service/shared_image_video.cc +++ b/gpu/command_buffer/service/shared_image_video.cc
@@ -108,6 +108,10 @@ return texture; } +SharedImageBackingType SharedImageVideo::GetType() const { + return SharedImageBackingType::kVideo; +} + gfx::Rect SharedImageVideo::ClearedRect() const { // SharedImageVideo objects are always created from pre-initialized textures // provided by the media decoder. Always treat these as cleared (return the
diff --git a/gpu/command_buffer/service/shared_image_video.h b/gpu/command_buffer/service/shared_image_video.h index b3ea069e..20b30dd 100644 --- a/gpu/command_buffer/service/shared_image_video.h +++ b/gpu/command_buffer/service/shared_image_video.h
@@ -55,6 +55,7 @@ SharedImageVideo& operator=(const SharedImageVideo&) = delete; // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; gfx::Rect ClearedRect() const override; void SetClearedRect(const gfx::Rect& cleared_rect) override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override;
diff --git a/gpu/command_buffer/service/test_shared_image_backing.cc b/gpu/command_buffer/service/test_shared_image_backing.cc index 30a8af5..cabbc1b 100644 --- a/gpu/command_buffer/service/test_shared_image_backing.cc +++ b/gpu/command_buffer/service/test_shared_image_backing.cc
@@ -208,6 +208,10 @@ glDeleteTextures(1, &service_id_); } +SharedImageBackingType TestSharedImageBacking::GetType() const { + return SharedImageBackingType::kTest; +} + gfx::Rect TestSharedImageBacking::ClearedRect() const { return texture_->GetLevelClearedRect(texture_->target(), 0); }
diff --git a/gpu/command_buffer/service/test_shared_image_backing.h b/gpu/command_buffer/service/test_shared_image_backing.h index dc0670f..7a3c32b 100644 --- a/gpu/command_buffer/service/test_shared_image_backing.h +++ b/gpu/command_buffer/service/test_shared_image_backing.h
@@ -35,6 +35,8 @@ GLuint texture_id); ~TestSharedImageBacking() override; + // SharedImageBacking implementation. + SharedImageBackingType GetType() const override; gfx::Rect ClearedRect() const override; void SetClearedRect(const gfx::Rect& cleared_rect) override; void Update(std::unique_ptr<gfx::GpuFence> in_fence) override {}
diff --git a/gpu/command_buffer/service/wrapped_sk_image.cc b/gpu/command_buffer/service/wrapped_sk_image.cc index 1d6530d..a137535 100644 --- a/gpu/command_buffer/service/wrapped_sk_image.cc +++ b/gpu/command_buffer/service/wrapped_sk_image.cc
@@ -150,6 +150,10 @@ } // SharedImageBacking implementation. + SharedImageBackingType GetType() const override { + return SharedImageBackingType::kWrappedSkImage; + } + bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) override { return false; }
diff --git a/gpu/command_buffer/tests/fuzzer_main.cc b/gpu/command_buffer/tests/fuzzer_main.cc index 2a0bdc58..9f8eb7b 100644 --- a/gpu/command_buffer/tests/fuzzer_main.cc +++ b/gpu/command_buffer/tests/fuzzer_main.cc
@@ -408,9 +408,8 @@ shared_image_factory_ = std::make_unique<SharedImageFactory>( gpu_preferences_, config_.workarounds, gpu_feature_info, context_state_.get(), &mailbox_manager_, shared_image_manager_.get(), - nullptr /* image_factory */, nullptr /* memory_tracker */, - false /* enable_wrapped_sk_image */, - false /* is_for_display_compositor */); + /*image_factory=*/nullptr, /*memory_tracker=*/nullptr, + /*is_for_display_compositor=*/false); for (uint32_t usage = SHARED_IMAGE_USAGE_GLES2; usage <= SHARED_IMAGE_USAGE_RGB_EMULATION; usage <<= 1) { Mailbox::Name name;
diff --git a/gpu/ipc/gpu_task_scheduler_helper.h b/gpu/ipc/gpu_task_scheduler_helper.h index c4ea831..7b2a7bc 100644 --- a/gpu/ipc/gpu_task_scheduler_helper.h +++ b/gpu/ipc/gpu_task_scheduler_helper.h
@@ -18,7 +18,6 @@ } namespace viz { -class VizProcessContextProvider; class DisplayCompositorMemoryAndTaskController; } @@ -36,10 +35,9 @@ // when this class is used outside of actual CommandBuffer, we would need to // make sure the order of post tasks still corresponds to the order that tasks // are posted to the CommandBuffer. -// This class is per display compositor. When this is used with command buffer, -// it is created on VizProcessContextProvider. When this is used with -// SkiaRenderer, it is created on SkiaOutputSurfaceImpl. Each user of this class -// would hold a reference. +// This class is per display compositor. When this is used with SkiaRenderer, it +// is created on SkiaOutputSurfaceImpl. Each user of this class would hold a +// reference. class GL_IN_PROCESS_CONTEXT_EXPORT GpuTaskSchedulerHelper { public: // This constructor is only used for SkiaOutputSurface. @@ -86,7 +84,6 @@ friend class gpu::GLInProcessContext; friend class gpu::InProcessCommandBuffer; - friend class viz::VizProcessContextProvider; friend class viz::DisplayCompositorMemoryAndTaskController; // Only used for inside CommandBuffer implementation. SingleTaskSequence* GetTaskSequence() const;
diff --git a/gpu/ipc/in_process_command_buffer.cc b/gpu/ipc/in_process_command_buffer.cc index 79ab4c9c..09aa8e88 100644 --- a/gpu/ipc/in_process_command_buffer.cc +++ b/gpu/ipc/in_process_command_buffer.cc
@@ -109,14 +109,6 @@ command_buffer_->RunTaskOnGpuThread(std::move(task)); } -bool InProcessCommandBuffer::SharedImageInterfaceHelper::EnableWrappedSkImage() - const { - // We need WrappedSkImage to support creating a SharedImage with pixel data - // when GL is unavailable. This is used in various unit tests. - return command_buffer_->context_state_ && - !command_buffer_->context_state_->GrContextIsGL(); -} - InProcessCommandBuffer::InProcessCommandBuffer( CommandBufferTaskExecutor* task_executor, const GURL& active_url)
diff --git a/gpu/ipc/in_process_command_buffer.h b/gpu/ipc/in_process_command_buffer.h index 8d2583a3..ee2b92d5 100644 --- a/gpu/ipc/in_process_command_buffer.h +++ b/gpu/ipc/in_process_command_buffer.h
@@ -185,8 +185,6 @@ void SetError(); void WrapTaskWithGpuCheck(base::OnceClosure task); - bool EnableWrappedSkImage() const; - private: raw_ptr<InProcessCommandBuffer> command_buffer_; };
diff --git a/gpu/ipc/service/gpu_memory_ablation_experiment.cc b/gpu/ipc/service/gpu_memory_ablation_experiment.cc index bc223a4..0a24c73 100644 --- a/gpu/ipc/service/gpu_memory_ablation_experiment.cc +++ b/gpu/ipc/service/gpu_memory_ablation_experiment.cc
@@ -209,7 +209,6 @@ channel_manager->mailbox_manager(), channel_manager->shared_image_manager(), gmb_factory ? gmb_factory->AsImageFactory() : nullptr, this, - /*enable_wrapped_sk_image=*/true, /*is_for_display_compositor=*/false); rep_factory_ = std::make_unique<SharedImageRepresentationFactory>(
diff --git a/gpu/ipc/service/shared_image_stub.cc b/gpu/ipc/service/shared_image_stub.cc index 7877295..00839b3 100644 --- a/gpu/ipc/service/shared_image_stub.cc +++ b/gpu/ipc/service/shared_image_stub.cc
@@ -508,7 +508,6 @@ channel_manager->mailbox_manager(), channel_manager->shared_image_manager(), gmb_factory ? gmb_factory->AsImageFactory() : nullptr, this, - /*enable_wrapped_sk_image=*/true, /*is_for_display_compositor=*/false); return ContextResult::kSuccess; }
diff --git a/gpu/ipc/shared_image_interface_in_process.cc b/gpu/ipc/shared_image_interface_in_process.cc index 3b6f237..a0305e67 100644 --- a/gpu/ipc/shared_image_interface_in_process.cc +++ b/gpu/ipc/shared_image_interface_in_process.cc
@@ -121,14 +121,13 @@ context_state_ = params->context_state.get(); create_factory_ = base::BindOnce( - [](std::unique_ptr<SetUpOnGpuParams> params, - bool enable_wrapped_sk_image) { + [](std::unique_ptr<SetUpOnGpuParams> params) { auto shared_image_factory = std::make_unique<SharedImageFactory>( params->gpu_preferences, params->gpu_workarounds, params->gpu_feature_info, params->context_state, params->mailbox_manager, params->shared_image_manager, params->image_factory, params->memory_tracker, - enable_wrapped_sk_image, params->is_for_display_compositor); + params->is_for_display_compositor); return shared_image_factory; }, std::move(params)); @@ -182,14 +181,7 @@ if (!MakeContextCurrent(/*needs_gl=*/true)) return false; - // We need WrappedSkImage to support creating a SharedImage with pixel data - // when GL is unavailable. This is used in various unit tests. If we don't - // have a command buffer helper, that means this class is created for - // SkiaRenderer, and we definitely need to turn on enable_wrapped_sk_image. - const bool enable_wrapped_sk_image = - !command_buffer_helper_ || command_buffer_helper_->EnableWrappedSkImage(); - shared_image_factory_ = - std::move(create_factory_).Run(enable_wrapped_sk_image); + shared_image_factory_ = std::move(create_factory_).Run(); return true; }
diff --git a/gpu/ipc/shared_image_interface_in_process.h b/gpu/ipc/shared_image_interface_in_process.h index 6adfa810..c02e98a 100644 --- a/gpu/ipc/shared_image_interface_in_process.h +++ b/gpu/ipc/shared_image_interface_in_process.h
@@ -234,9 +234,7 @@ const CommandBufferId command_buffer_id_; std::unique_ptr<CommandBufferHelper> command_buffer_helper_; - base::OnceCallback<std::unique_ptr<SharedImageFactory>( - bool enable_wrapped_sk_image)> - create_factory_; + base::OnceCallback<std::unique_ptr<SharedImageFactory>()> create_factory_; // Sequence checker for tasks that run on the gpu "thread". SEQUENCE_CHECKER(gpu_sequence_checker_);
diff --git a/infra/config/PRESUBMIT.py b/infra/config/PRESUBMIT.py index 6aab7f3e..2acf6d8 100644 --- a/infra/config/PRESUBMIT.py +++ b/infra/config/PRESUBMIT.py
@@ -55,7 +55,7 @@ return input_api.RunTests([ input_api.Command( name='lint-luci-milo', - cmd=[input_api.python_executable, 'lint-luci-milo.py'], + cmd=[input_api.python3_executable, 'lint-luci-milo.py'], kwargs={}, message=output_api.PresubmitError), ]) @@ -66,14 +66,19 @@ 'infra/config/generated/luci/luci-milo-dev.cfg' in input_api.LocalPaths() ): return input_api.RunTests([ - input_api.Command( - name='testing/buildbot config checks', - cmd=[input_api.python_executable, input_api.os_path.join( - '..', '..', 'testing', 'buildbot', - 'generate_buildbot_json.py',), - '--check'], - kwargs={}, - message=output_api.PresubmitError), + input_api.Command(name='testing/buildbot config checks', + cmd=[ + input_api.python3_executable, + input_api.os_path.join( + '..', + '..', + 'testing', + 'buildbot', + 'generate_buildbot_json.py', + ), '--check' + ], + kwargs={}, + message=output_api.PresubmitError), ]) return []
diff --git a/infra/config/lint-luci-milo.py b/infra/config/lint-luci-milo.py index dd31078..e789e63 100755 --- a/infra/config/lint-luci-milo.py +++ b/infra/config/lint-luci-milo.py
@@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -43,12 +43,15 @@ sub_desc = to_list(sub_builders, name) if main_desc != sub_desc: - print ('bot lists different between main waterfall ' + - 'and stand-alone %s waterfall:' % name) - print '\n'.join(difflib.unified_diff(main_desc, sub_desc, - fromfile='main', tofile=name, - lineterm='')) - print + print('bot lists different between main waterfall ' + + 'and stand-alone %s waterfall:' % name) + print('\n'.join( + difflib.unified_diff(main_desc, + sub_desc, + fromfile='main', + tofile=name, + lineterm=''))) + print('') return False return True @@ -81,7 +84,7 @@ referenced_names = set(subwaterfalls.keys()) missing_names = referenced_names - set(all_console_names + excluded_names) if missing_names: - print 'Missing subwaterfall console for', missing_names + print('Missing subwaterfall console for', missing_names) return 1 # Check that the bots on a subwaterfall match the corresponding bots on the
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index d65919f5..fc994c9 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -35,6 +35,7 @@ #include "components/prefs/ios/pref_observer_bridge.h" #include "components/prefs/pref_change_registrar.h" #import "components/previous_session_info/previous_session_info.h" +#import "components/sync/driver/sync_service.h" #include "components/web_resource/web_resource_pref_names.h" #include "ios/chrome/app/app_metrics_app_state_agent.h" #import "ios/chrome/app/application_delegate/metrics_mediator.h" @@ -98,6 +99,7 @@ #include "ios/chrome/browser/signin/authentication_service_factory.h" #import "ios/chrome/browser/snapshots/snapshot_browser_agent.h" #import "ios/chrome/browser/snapshots/snapshot_cache.h" +#import "ios/chrome/browser/sync/sync_service_factory.h" #include "ios/chrome/browser/system_flags.h" #import "ios/chrome/browser/ui/appearance/appearance_customization.h" #import "ios/chrome/browser/ui/commands/browser_commands.h" @@ -1147,13 +1149,7 @@ [[DeferredInitializationRunner sharedInstance] enqueueBlockNamed:kFaviconsCleanup block:^{ - MainController* strongSelf = weakSelf; - if (!strongSelf || !strongSelf.currentBrowserState) { - return; - } - UpdateFaviconsStorage( - IOSChromeFaviconLoaderFactory::GetForBrowserState( - strongSelf.currentBrowserState)); + [weakSelf performFaviconsCleanup]; }]; #endif } @@ -1328,6 +1324,21 @@ ->Remove(timePeriod, removeMask, base::BindOnce(removalCompletion)); } +#if BUILDFLAG(IOS_CREDENTIAL_PROVIDER_ENABLED) +- (void)performFaviconsCleanup { + if (!self.currentBrowserState) + return; + + syncer::SyncService* syncService = + SyncServiceFactory::GetForBrowserState(self.currentBrowserState); + if (syncService) { + UpdateFaviconsStorage(IOSChromeFaviconLoaderFactory::GetForBrowserState( + self.currentBrowserState), + syncService->IsSyncFeatureEnabled()); + } +} +#endif + #pragma mark - BlockingSceneCommands - (void)activateBlockingScene:(UIScene*)requestingScene {
diff --git a/ios/chrome/app/strings/ios_chromium_strings.grd b/ios/chrome/app/strings/ios_chromium_strings.grd index 418b29c..80c6a19 100644 --- a/ios/chrome/app/strings/ios_chromium_strings.grd +++ b/ios/chrome/app/strings/ios_chromium_strings.grd
@@ -380,12 +380,15 @@ <message name="IDS_IOS_MANAGED_DISCONNECT_DIALOG_TITLE_UNITY" desc="Title of the dialog shown when signing out of a managed account.[Length: 50em] [iOS only]."> Clear your Chromium data from this device? </message> - <message name="IDS_IOS_MANAGED_SIGNIN_SUBTITLE" desc="The subtitle of the Sign in to a managed account dialog. [300em]"> + <message name="IDS_IOS_MANAGED_SIGNIN_SUBTITLE" desc="The subtitle of the Sign in to a managed account dialog. If the User Policy feature is enabled, the IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE subtitle will be used instead of this one. [300em]"> You are signing in with an account managed by <ph name="DOMAIN">$1<ex>doe.com</ex></ph> and giving its administrator control over your Chromium data. Your data will become permanently tied to this account. Signing out of Chromium will delete your data from this device, but it will remain stored in your Google Account. </message> <message name="IDS_IOS_MANAGED_SWITCH_SUBTITLE" desc="The subtitle of the Switch from a managed account dialog. [300em]"> You are switching sync accounts from <ph name="USER_EMAIL1">$1<ex>john@doe.com</ex></ph> to <ph name="USER_EMAIL2">$2<ex>johndoe@gmail.com</ex></ph>. Your existing Chromium data is managed by <ph name="DOMAIN">$3<ex>doe.com</ex></ph>. This will delete your data from this device, but your data will remain in <ph name="USER_EMAIL1">$1<ex>john@doe.com</ex></ph>. </message> + <message name="IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE" desc="The subtitle of the Sync with a managed account dialog when User Policy is enabled (alternative to IDS_IOS_MANAGED_SIGNIN_SUBTITLE). [300em][iOS only]"> + Your organization <ph name="DOMAIN">$1<ex>doe.com</ex></ph> will have access to your Chromium data, bookmarks, history, passwords and other settings you store in this account. When you sign out, your data will be cleared from this device. However, your data will remain stored in your managed Google Account and be available to your organization. Your organization can also set user policies specific to that account that can change the behavior of Chromium. + </message> <message name="IDS_IOS_MOVE_TO_DOCK_TIP" desc="Text displayed on the New Tab Page for the move Chromium to the dock promo. [iOS only]"> Tip: <ph name="BEGIN_LINK"><ex>BEGIN_LINK</ex>BEGIN_LINK</ph>Move Chromium to your dock<ph name="END_LINK"><ex>END_LINK</ex>END_LINK</ph> </message>
diff --git a/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1 b/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1 new file mode 100644 index 0000000..be47b91 --- /dev/null +++ b/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +292374f570969a17c3c9b98e87296fa8fbfa0453 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1 b/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1 new file mode 100644 index 0000000..be47b91 --- /dev/null +++ b/ios/chrome/app/strings/ios_chromium_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +292374f570969a17c3c9b98e87296fa8fbfa0453 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_google_chrome_strings.grd b/ios/chrome/app/strings/ios_google_chrome_strings.grd index 2b8beed1..a3cf4270 100644 --- a/ios/chrome/app/strings/ios_google_chrome_strings.grd +++ b/ios/chrome/app/strings/ios_google_chrome_strings.grd
@@ -380,12 +380,15 @@ <message name="IDS_IOS_MANAGED_DISCONNECT_DIALOG_TITLE_UNITY" desc="Title of the dialog shown when signing out of a managed account.[Length: 50em] [iOS only]."> Clear your Chrome data from this device? </message> - <message name="IDS_IOS_MANAGED_SIGNIN_SUBTITLE" desc="The subtitle of the Sign in to a managed account dialog. [300em]"> + <message name="IDS_IOS_MANAGED_SIGNIN_SUBTITLE" desc="The subtitle of the Sign in to a managed account dialog. If the User Policy feature is enabled, the IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE subtitle will be used instead of this one. [300em]"> You are signing in with an account managed by <ph name="DOMAIN">$1<ex>doe.com</ex></ph> and giving its administrator control over your Chrome data. Your data will become permanently tied to this account. Signing out of Chrome will delete your data from this device, but it will remain stored in your Google Account. </message> <message name="IDS_IOS_MANAGED_SWITCH_SUBTITLE" desc="The subtitle of the Switch from a managed account dialog. [300em]"> You are switching sync accounts from <ph name="USER_EMAIL1">$1<ex>john@doe.com</ex></ph> to <ph name="USER_EMAIL2">$2<ex>johndoe@gmail.com</ex></ph>. Your existing Chrome data is managed by <ph name="DOMAIN">$3<ex>doe.com</ex></ph>. This will delete your data from this device, but your data will remain in <ph name="USER_EMAIL1">$1<ex>john@doe.com</ex></ph>. </message> + <message name="IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE" desc="The subtitle of the Sync with a managed account dialog when User Policy is enabled (alternative to IDS_IOS_MANAGED_SIGNIN_SUBTITLE). [300em][iOS only]"> + Your organization <ph name="DOMAIN">$1<ex>doe.com</ex></ph> will have access to your Chrome data, bookmarks, history, passwords and other settings you store in this account. When you sign out, your data will be cleared from this device. However, your data will remain stored in your managed Google Account and be available to your organization. Your organization can also set user policies specific to that account that can change the behavior of Chrome. + </message> <message name="IDS_IOS_MOVE_TO_DOCK_TIP" desc="Text displayed on the New Tab Page for the move Chrome to the dock promo. [iOS only]"> Tip: <ph name="BEGIN_LINK"><ex>BEGIN_LINK</ex>BEGIN_LINK</ph>Move Chrome to your dock<ph name="END_LINK"><ex>END_LINK</ex>END_LINK</ph> </message>
diff --git a/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1 b/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1 new file mode 100644 index 0000000..be47b91 --- /dev/null +++ b/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +292374f570969a17c3c9b98e87296fa8fbfa0453 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1 b/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1 new file mode 100644 index 0000000..be47b91 --- /dev/null +++ b/ios/chrome/app/strings/ios_google_chrome_strings_grd/IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +292374f570969a17c3c9b98e87296fa8fbfa0453 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 1cfbce5d..9591d03 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -1312,6 +1312,9 @@ <message name="IDS_IOS_MANAGED_SWITCH_TITLE" desc="The title of the Switch from a managed account dialog. [40em]"> Sign out of managed account </message> + <message name="IDS_IOS_MANAGED_SYNC_TITLE" desc="The title of the Sync with a managed account dialog (alternative to IDS_IOS_MANAGED_SIGNIN_TITLE). Is only used when the User Policy feature is enabled using the --enable-user-policy-for-ios flag. [40em][iOS only]"> + Sync With Managed Account + </message> <message name="IDS_IOS_MANUAL_FALLBACK_ADD_PAYMENT_METHOD" desc="The title for the button in the manual fallback UI that takes the user to the add new credit card screen through settings. In this screen, the user can input their card details and save them."> Add Payment Method... </message>
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_TITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_TITLE.png.sha1 new file mode 100644 index 0000000..ad314f0 --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SIGNIN_WITH_USER_POLICY_TITLE.png.sha1
@@ -0,0 +1 @@ +5975608d9cb87a161d1108d5e77794649adf256e \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SYNC_TITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SYNC_TITLE.png.sha1 new file mode 100644 index 0000000..ad314f0 --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_MANAGED_SYNC_TITLE.png.sha1
@@ -0,0 +1 @@ +5975608d9cb87a161d1108d5e77794649adf256e \ No newline at end of file
diff --git a/ios/chrome/browser/credential_provider/credential_provider_service.mm b/ios/chrome/browser/credential_provider/credential_provider_service.mm index ef9d50b..eb3a1f4a 100644 --- a/ios/chrome/browser/credential_provider/credential_provider_service.mm +++ b/ios/chrome/browser/credential_provider/credential_provider_service.mm
@@ -247,6 +247,7 @@ std::vector<std::unique_ptr<PasswordForm>> forms) { // User is adding a password (not batch add from user login). const bool should_skip_max_verification = forms.size() == 1; + const bool sync_enabled = sync_service_->IsSyncFeatureEnabled(); for (const auto& form : forms) { NSString* favicon_key = nil; @@ -254,7 +255,7 @@ favicon_key = GetFaviconFileKey(form->url); // Fetch the favicon and save it to the storage. FetchFaviconForURLToPath(favicon_loader_, form->url, favicon_key, - should_skip_max_verification); + should_skip_max_verification, sync_enabled); } ArchivableCredential* credential =
diff --git a/ios/chrome/browser/credential_provider/credential_provider_util.h b/ios/chrome/browser/credential_provider/credential_provider_util.h index fc14e9c..1b7ae96 100644 --- a/ios/chrome/browser/credential_provider/credential_provider_util.h +++ b/ios/chrome/browser/credential_provider/credential_provider_util.h
@@ -20,12 +20,13 @@ void FetchFaviconForURLToPath(FaviconLoader* favicon_loader, const GURL& site_url, NSString* filename, - bool skip_max_verification); + bool skip_max_verification, + bool sync_enabled); // Returns the favicon file key. NSString* GetFaviconFileKey(const GURL& url); // Update favicons in the Chrome app group storage. -void UpdateFaviconsStorage(FaviconLoader* favicon_loader); +void UpdateFaviconsStorage(FaviconLoader* favicon_loader, bool sync_enabled); #endif // IOS_CHROME_BROWSER_CREDENTIAL_PROVIDER_CREDENTIAL_PROVIDER_UTIL_H_
diff --git a/ios/chrome/browser/credential_provider/credential_provider_util.mm b/ios/chrome/browser/credential_provider/credential_provider_util.mm index 186e0c88..8961f81 100644 --- a/ios/chrome/browser/credential_provider/credential_provider_util.mm +++ b/ios/chrome/browser/credential_provider/credential_provider_util.mm
@@ -116,15 +116,17 @@ void ContinueFetchingFavicon(base::WeakPtr<FaviconLoader> weak_favicon_loader, const GURL& site_url, NSString* filename, + bool sync_enabled, bool continue_fetching) { FaviconLoader* favicon_loader = weak_favicon_loader.get(); if (!continue_fetching || !favicon_loader) { // Reached max number of stored favicons or favicon loader is null. return; } + // Fallback to Google server for synced user only. favicon_loader->FaviconForPageUrl( - site_url, kDesiredMediumFaviconSizePt, kMinFaviconSizePt, - /*fallback_to_google_server=*/false, ^(FaviconAttributes* attributes) { + site_url, kDesiredMediumFaviconSizePt, kMinFaviconSizePt, sync_enabled, + ^(FaviconAttributes* attributes) { SaveFaviconToSharedAppContainer(attributes, filename); }); } @@ -132,18 +134,20 @@ void FetchFaviconForURLToPath(FaviconLoader* favicon_loader, const GURL& site_url, NSString* filename, - bool skip_max_verification) { + bool skip_max_verification, + bool sync_enabled) { DCHECK(favicon_loader); DCHECK(filename); if (skip_max_verification) { ContinueFetchingFavicon(favicon_loader->AsWeakPtr(), site_url, filename, + sync_enabled, /* continue_fetching */ YES); } else { base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce(&ShouldContinueFetchingFavicon), base::BindOnce(&ContinueFetchingFavicon, favicon_loader->AsWeakPtr(), - site_url, filename)); + site_url, filename, sync_enabled)); } } @@ -226,7 +230,7 @@ SetFaviconsLastSyncDate(base::Time::Now()); } -void UpdateFaviconsStorage(FaviconLoader* favicon_loader) { +void UpdateFaviconsStorage(FaviconLoader* favicon_loader, bool sync_enabled) { if (!base::FeatureList::IsEnabled( password_manager::features::kEnableFaviconForPasswords)) { // Call clean up to remove the repo when the flag is off. @@ -298,7 +302,8 @@ // Fetch the favicon and save it to the app group storage. if (filename) { - FetchFaviconForURLToPath(favicon_loader, url, filename, YES); + FetchFaviconForURLToPath(favicon_loader, url, filename, + /*skip_max_verification=*/YES, sync_enabled); // Remove file name duplicate because it is part of the top // `kMaxNumberOfFavicons` credentials used by the user.
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index 1924498..91270ea 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -64,7 +64,7 @@ #include "ios/chrome/browser/crash_report/features.h" #include "ios/chrome/browser/flags/ios_chrome_flag_descriptions.h" #import "ios/chrome/browser/ntp/features.h" -#include "ios/chrome/browser/policy/cloud/user_policy_switch.h" +#import "ios/chrome/browser/policy/cloud/user_policy_switch.h" #include "ios/chrome/browser/policy/policy_util.h" #include "ios/chrome/browser/screen_time/screen_time_buildflags.h" #import "ios/chrome/browser/sessions/session_features.h" @@ -1006,6 +1006,9 @@ FEATURE_WITH_PARAMS_VALUE_TYPE(kOmniboxPasteButton, kOmniboxPasteButtonVariations, "OmniboxPasteButton")}, + {"enable-user-policy", flag_descriptions::kEnableUserPolicyName, + flag_descriptions::kEnableUserPolicyDescription, flags_ui::kOsIos, + SINGLE_VALUE_TYPE(policy::kEnableUserPolicy)}, }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index 9cf514a..93a0d99 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -316,6 +316,11 @@ "Enable omnibox suggestions scrolling on iPad and disable suggestions " "hiding on keyboard dismissal."; +const char kEnableUserPolicyName[] = "Enable user policies"; +const char kEnableUserPolicyDescription[] = + "Enable the fetch and application of user policies when synced with a " + "managed account"; + const char kEnableWebChannelsName[] = "Enable WebFeed"; const char kEnableWebChannelsDescription[] = "Enable folowing content from web and display Following feed on NTP based "
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 4216128b..58b63791 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -282,6 +282,10 @@ extern const char kEnableSuggestionsScrollingOnIPadName[]; extern const char kEnableSuggestionsScrollingOnIPadDescription[]; +// Title and description for the flag to enable user policies. +extern const char kEnableUserPolicyName[]; +extern const char kEnableUserPolicyDescription[]; + // Title and description for the flag to introduce following web channels on // Chrome iOS. extern const char kEnableWebChannelsName[];
diff --git a/ios/chrome/browser/policy/cloud/user_policy_switch.h b/ios/chrome/browser/policy/cloud/user_policy_switch.h index 5f5e17c1..252940c 100644 --- a/ios/chrome/browser/policy/cloud/user_policy_switch.h +++ b/ios/chrome/browser/policy/cloud/user_policy_switch.h
@@ -7,6 +7,8 @@ namespace policy { +extern const char kEnableUserPolicy[]; + // Enables User Policy with the commandline switch. void EnableUserPolicy();
diff --git a/ios/chrome/browser/policy/cloud/user_policy_switch.mm b/ios/chrome/browser/policy/cloud/user_policy_switch.mm index 98ba120..8009afab 100644 --- a/ios/chrome/browser/policy/cloud/user_policy_switch.mm +++ b/ios/chrome/browser/policy/cloud/user_policy_switch.mm
@@ -10,15 +10,10 @@ #error "This file requires ARC support." #endif -namespace { - -// True to enable user policy. -const char kEnableUserPolicy[] = "enable-user-policy-for-ios"; - -} // namespace - namespace policy { +const char kEnableUserPolicy[] = "enable-user-policy-for-ios"; + void EnableUserPolicy() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitch(kEnableUserPolicy);
diff --git a/ios/chrome/browser/ui/authentication/authentication_flow.mm b/ios/chrome/browser/ui/authentication/authentication_flow.mm index 0fe7b0f..b487fe54 100644 --- a/ios/chrome/browser/ui/authentication/authentication_flow.mm +++ b/ios/chrome/browser/ui/authentication/authentication_flow.mm
@@ -259,7 +259,7 @@ return REGISTER_FOR_USER_POLICY; return COMPLETE_WITH_SUCCESS; case REGISTER_FOR_USER_POLICY: - if ([_dmToken length] == 0) { + if (!_dmToken.length || !_clientID.length) { // Skip fetching user policies when registration failed. return COMPLETE_WITH_SUCCESS; } @@ -537,7 +537,6 @@ - (void)didRegisterForUserPolicyWithDMToken:(NSString*)dmToken clientID:(NSString*)clientID { DCHECK_EQ(REGISTER_FOR_USER_POLICY, _state); - DCHECK(clientID.length); _dmToken = dmToken; _clientID = clientID;
diff --git a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm index 60ea1fd..741b2a5 100644 --- a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm +++ b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm
@@ -60,22 +60,8 @@ } // namespace -@interface AuthenticationFlowPerformer ()<ImportDataControllerDelegate, - SettingsNavigationControllerDelegate> - -// Starts the watchdog timer with a timeout of -// `kAuthenticationFlowTimeoutSeconds` for the fetching managed status -// operation. It will notify `_delegate` of the failure unless -// `stopWatchdogTimer` is called before it times out. -- (void)startWatchdogTimerForManagedStatus; - -// Stops the watchdog timer, and doesn't call the `timeoutDelegateSelector`. -// Returns whether the watchdog was actually running. -- (BOOL)stopWatchdogTimer; - -// Callback for when the alert is dismissed. -- (void)alertControllerDidDisappear:(AlertCoordinator*)alertCoordinator; - +@interface AuthenticationFlowPerformer () <ImportDataControllerDelegate, + SettingsNavigationControllerDelegate> @end @implementation AuthenticationFlowPerformer { @@ -113,33 +99,6 @@ ->CommitSyncChanges(); } -- (void)startWatchdogTimerForManagedStatus { - __weak AuthenticationFlowPerformer* weakSelf = self; - ProceduralBlock onTimeout = ^{ - AuthenticationFlowPerformer* strongSelf = weakSelf; - if (!strongSelf) - return; - [strongSelf stopWatchdogTimer]; - NSError* error = [NSError errorWithDomain:kAuthenticationErrorDomain - code:TIMED_OUT_FETCH_POLICY - userInfo:nil]; - [strongSelf->_delegate didFailFetchManagedStatus:error]; - }; - _watchdogTimer.reset(new base::OneShotTimer()); - _watchdogTimer->Start(FROM_HERE, - base::Seconds(kAuthenticationFlowTimeoutSeconds), - base::BindOnce(onTimeout)); -} - -- (BOOL)stopWatchdogTimer { - if (_watchdogTimer) { - _watchdogTimer->Stop(); - _watchdogTimer.reset(); - return YES; - } - return NO; -} - - (void)fetchManagedStatus:(ChromeBrowserState*)browserState forIdentity:(ChromeIdentity*)identity { ios::ChromeIdentityService* identityService = @@ -163,20 +122,6 @@ }); } -- (void)handleGetHostedDomain:(NSString*)hostedDomain - error:(NSError*)error - browserState:(ChromeBrowserState*)browserState { - if (![self stopWatchdogTimer]) { - // Watchdog timer has already fired, don't notify the delegate. - return; - } - if (error) { - [_delegate didFailFetchManagedStatus:error]; - return; - } - [_delegate didFetchManagedStatus:hostedDomain]; -} - - (void)signInIdentity:(ChromeIdentity*)identity withHostedDomain:(NSString*)hostedDomain toBrowserState:(ChromeBrowserState*)browserState @@ -200,55 +145,6 @@ /*force_clear_browsing_data=*/false, nil); } -- (void)promptSwitchFromManagedEmail:(NSString*)managedEmail - withHostedDomain:(NSString*)hostedDomain - toEmail:(NSString*)toEmail - viewController:(UIViewController*)viewController - browser:(Browser*)browser { - DCHECK(!_alertCoordinator); - NSString* title = l10n_util::GetNSString(IDS_IOS_MANAGED_SWITCH_TITLE); - NSString* subtitle = l10n_util::GetNSStringF( - IDS_IOS_MANAGED_SWITCH_SUBTITLE, base::SysNSStringToUTF16(managedEmail), - base::SysNSStringToUTF16(toEmail), - base::SysNSStringToUTF16(hostedDomain)); - NSString* acceptLabel = - l10n_util::GetNSString(IDS_IOS_MANAGED_SWITCH_ACCEPT_BUTTON); - NSString* cancelLabel = l10n_util::GetNSString(IDS_CANCEL); - - _alertCoordinator = - [[AlertCoordinator alloc] initWithBaseViewController:viewController - browser:browser - title:title - message:subtitle]; - - __weak AuthenticationFlowPerformer* weakSelf = self; - __weak AlertCoordinator* weakAlert = _alertCoordinator; - ProceduralBlock acceptBlock = ^{ - AuthenticationFlowPerformer* strongSelf = weakSelf; - if (!strongSelf) - return; - [strongSelf alertControllerDidDisappear:weakAlert]; - [[strongSelf delegate] - didChooseClearDataPolicy:SHOULD_CLEAR_DATA_CLEAR_DATA]; - }; - ProceduralBlock cancelBlock = ^{ - AuthenticationFlowPerformer* strongSelf = weakSelf; - if (!strongSelf) - return; - [strongSelf alertControllerDidDisappear:weakAlert]; - [[strongSelf delegate] didChooseCancel]; - }; - - [_alertCoordinator addItemWithTitle:cancelLabel - action:cancelBlock - style:UIAlertActionStyleCancel]; - [_alertCoordinator addItemWithTitle:acceptLabel - action:acceptBlock - style:UIAlertActionStyleDefault]; - [_alertCoordinator setCancelAction:cancelBlock]; - [_alertCoordinator start]; -} - - (void)promptMergeCaseForIdentity:(ChromeIdentity*)identity browser:(Browser*)browser viewController:(UIViewController*)viewController { @@ -374,9 +270,15 @@ viewController:(UIViewController*)viewController browser:(Browser*)browser { DCHECK(!_alertCoordinator); - NSString* title = l10n_util::GetNSString(IDS_IOS_MANAGED_SIGNIN_TITLE); + BOOL userPolicyEnabled = policy::IsUserPolicyEnabled(); + int titleID = userPolicyEnabled ? IDS_IOS_MANAGED_SYNC_TITLE + : IDS_IOS_MANAGED_SIGNIN_TITLE; + NSString* title = l10n_util::GetNSString(titleID); + int subtitleID = userPolicyEnabled + ? IDS_IOS_MANAGED_SYNC_WITH_USER_POLICY_SUBTITLE + : IDS_IOS_MANAGED_SIGNIN_SUBTITLE; NSString* subtitle = l10n_util::GetNSStringF( - IDS_IOS_MANAGED_SIGNIN_SUBTITLE, base::SysNSStringToUTF16(hostedDomain)); + subtitleID, base::SysNSStringToUTF16(hostedDomain)); NSString* acceptLabel = l10n_util::GetNSString(IDS_IOS_MANAGED_SIGNIN_ACCEPT_BUTTON); NSString* cancelLabel = l10n_util::GetNSString(IDS_CANCEL); @@ -455,17 +357,6 @@ [_alertCoordinator start]; } -- (void)alertControllerDidDisappear:(AlertCoordinator*)alertCoordinator { - if (_alertCoordinator != alertCoordinator) { - // Do not reset the `_alertCoordinator` if it has changed. This typically - // happens when the user taps on any of the actions on "Clear Data Before - // Syncing?" dialog, as the sign-in confirmation dialog is created before - // the "Clear Data Before Syncing?" dialog is dismissed. - return; - } - _alertCoordinator = nil; -} - - (void)registerUserPolicy:(ChromeBrowserState*)browserState forIdentity:(ChromeIdentity*)identity { // Should only fetch user policies when the feature is enabled. @@ -481,10 +372,16 @@ policy::UserPolicySigninServiceFactory::GetForBrowserState(browserState); __weak __typeof(self) weakSelf = self; + + [self startWatchdogTimerForUserPolicyRegistration]; userPolicyService->RegisterForPolicyWithAccountId( userEmail, accountID, base::BindOnce(^(const std::string& dmToken, const std::string& clientID) { + if (![self stopWatchdogTimer]) { + // Watchdog timer has already fired, don't notify the delegate. + return; + } [weakSelf.delegate didRegisterForUserPolicyWithDMToken:base::SysUTF8ToNSString(dmToken) clientID:base::SysUTF8ToNSString( @@ -512,11 +409,17 @@ base::SysNSStringToUTF8([identity gaiaID])); __weak __typeof(self) weakSelf = self; + + [self startWatchdogTimerForUserPolicyFetch]; policy_service->FetchPolicyForSignedInUser( accountID, base::SysNSStringToUTF8(dmToken), base::SysNSStringToUTF8(clientID), browserState->GetSharedURLLoaderFactory(), base::BindOnce(^(bool success) { + if (![self stopWatchdogTimer]) { + // Watchdog timer has already fired, don't notify the delegate. + return; + } [weakSelf.delegate didFetchUserPolicyWithSuccess:success]; })); } @@ -586,7 +489,7 @@ return nil; } -#pragma mark - Internal +#pragma mark - Private - (void)updateUserPolicyNotificationStatusIfNeeded:(PrefService*)prefService { if (!policy::IsUserPolicyEnabled()) { @@ -599,4 +502,144 @@ true); } +- (void)handleGetHostedDomain:(NSString*)hostedDomain + error:(NSError*)error + browserState:(ChromeBrowserState*)browserState { + if (![self stopWatchdogTimer]) { + // Watchdog timer has already fired, don't notify the delegate. + return; + } + if (error) { + [_delegate didFailFetchManagedStatus:error]; + return; + } + [_delegate didFetchManagedStatus:hostedDomain]; +} + +// Starts a Watchdog Timer that calls `timeoutBlock` on time out. +- (void)startWatchdogTimerWithTimeoutBlock:(ProceduralBlock)timeoutBlock { + DCHECK(!_watchdogTimer); + _watchdogTimer.reset(new base::OneShotTimer()); + _watchdogTimer->Start(FROM_HERE, + base::Seconds(kAuthenticationFlowTimeoutSeconds), + base::BindOnce(timeoutBlock)); +} + +// Starts the watchdog timer with a timeout of +// `kAuthenticationFlowTimeoutSeconds` for the fetching managed status +// operation. It will notify `_delegate` of the failure unless +// `stopWatchdogTimer` is called before it times out. +- (void)startWatchdogTimerForManagedStatus { + __weak AuthenticationFlowPerformer* weakSelf = self; + ProceduralBlock timeoutBlock = ^{ + AuthenticationFlowPerformer* strongSelf = weakSelf; + if (!strongSelf) + return; + [strongSelf stopWatchdogTimer]; + NSError* error = [NSError errorWithDomain:kAuthenticationErrorDomain + code:TIMED_OUT_FETCH_POLICY + userInfo:nil]; + [strongSelf->_delegate didFailFetchManagedStatus:error]; + }; + [self startWatchdogTimerWithTimeoutBlock:timeoutBlock]; +} + +// Starts a Watchdog Timer that ends the user policy registration on time out. +- (void)startWatchdogTimerForUserPolicyRegistration { + __weak AuthenticationFlowPerformer* weakSelf = self; + ProceduralBlock timeoutBlock = ^{ + AuthenticationFlowPerformer* strongSelf = weakSelf; + if (!strongSelf) + return; + [strongSelf stopWatchdogTimer]; + [strongSelf.delegate didRegisterForUserPolicyWithDMToken:@"" clientID:@""]; + }; + [self startWatchdogTimerWithTimeoutBlock:timeoutBlock]; +} + +// Starts a Watchdog Timer that ends the user policy fetch on time out. +- (void)startWatchdogTimerForUserPolicyFetch { + __weak AuthenticationFlowPerformer* weakSelf = self; + ProceduralBlock timeoutBlock = ^{ + AuthenticationFlowPerformer* strongSelf = weakSelf; + if (!strongSelf) + return; + [strongSelf stopWatchdogTimer]; + [strongSelf->_delegate didFetchUserPolicyWithSuccess:NO]; + }; + [self startWatchdogTimerWithTimeoutBlock:timeoutBlock]; +} + +// Stops the watchdog timer, and doesn't call the `timeoutDelegateSelector`. +// Returns whether the watchdog was actually running. +- (BOOL)stopWatchdogTimer { + if (_watchdogTimer) { + _watchdogTimer->Stop(); + _watchdogTimer.reset(); + return YES; + } + return NO; +} + +- (void)promptSwitchFromManagedEmail:(NSString*)managedEmail + withHostedDomain:(NSString*)hostedDomain + toEmail:(NSString*)toEmail + viewController:(UIViewController*)viewController + browser:(Browser*)browser { + DCHECK(!_alertCoordinator); + NSString* title = l10n_util::GetNSString(IDS_IOS_MANAGED_SWITCH_TITLE); + NSString* subtitle = l10n_util::GetNSStringF( + IDS_IOS_MANAGED_SWITCH_SUBTITLE, base::SysNSStringToUTF16(managedEmail), + base::SysNSStringToUTF16(toEmail), + base::SysNSStringToUTF16(hostedDomain)); + NSString* acceptLabel = + l10n_util::GetNSString(IDS_IOS_MANAGED_SWITCH_ACCEPT_BUTTON); + NSString* cancelLabel = l10n_util::GetNSString(IDS_CANCEL); + + _alertCoordinator = + [[AlertCoordinator alloc] initWithBaseViewController:viewController + browser:browser + title:title + message:subtitle]; + + __weak AuthenticationFlowPerformer* weakSelf = self; + __weak AlertCoordinator* weakAlert = _alertCoordinator; + ProceduralBlock acceptBlock = ^{ + AuthenticationFlowPerformer* strongSelf = weakSelf; + if (!strongSelf) + return; + [strongSelf alertControllerDidDisappear:weakAlert]; + [[strongSelf delegate] + didChooseClearDataPolicy:SHOULD_CLEAR_DATA_CLEAR_DATA]; + }; + ProceduralBlock cancelBlock = ^{ + AuthenticationFlowPerformer* strongSelf = weakSelf; + if (!strongSelf) + return; + [strongSelf alertControllerDidDisappear:weakAlert]; + [[strongSelf delegate] didChooseCancel]; + }; + + [_alertCoordinator addItemWithTitle:cancelLabel + action:cancelBlock + style:UIAlertActionStyleCancel]; + [_alertCoordinator addItemWithTitle:acceptLabel + action:acceptBlock + style:UIAlertActionStyleDefault]; + [_alertCoordinator setCancelAction:cancelBlock]; + [_alertCoordinator start]; +} + +// Callback for when the alert is dismissed. +- (void)alertControllerDidDisappear:(AlertCoordinator*)alertCoordinator { + if (_alertCoordinator != alertCoordinator) { + // Do not reset the `_alertCoordinator` if it has changed. This typically + // happens when the user taps on any of the actions on "Clear Data Before + // Syncing?" dialog, as the sign-in confirmation dialog is created before + // the "Clear Data Before Syncing?" dialog is dismissed. + return; + } + _alertCoordinator = nil; +} + @end
diff --git a/ios/chrome/browser/ui/authentication/signin/forced_signin/OWNERS b/ios/chrome/browser/ui/authentication/signin/forced_signin/OWNERS new file mode 100644 index 0000000..024a15e --- /dev/null +++ b/ios/chrome/browser/ui/authentication/signin/forced_signin/OWNERS
@@ -0,0 +1 @@ +vincb@google.com
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm index c05796aa..26adac2 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm
@@ -477,8 +477,10 @@ _fakeLocationBar.translatesAutoresizingMaskIntoConstraints = NO; if (IsContentSuggestionsUIModuleRefreshEnabled()) { GradientView* gradientView = [[GradientView alloc] - initWithTopColor:[UIColor colorNamed:kGrey300Color] - bottomColor:[UIColor colorNamed:kGrey200Color]]; + initWithTopColor:[UIColor + colorNamed:@"fake_omnibox_top_gradient_color"] + bottomColor: + [UIColor colorNamed:@"fake_omnibox_bottom_gradient_color"]]; gradientView.translatesAutoresizingMaskIntoConstraints = NO; [_fakeLocationBar addSubview:gradientView]; AddSameConstraints(_fakeLocationBar, gradientView);
diff --git a/ios/chrome/browser/ui/first_run/BUILD.gn b/ios/chrome/browser/ui/first_run/BUILD.gn index 5da92d3e..1dfb408 100644 --- a/ios/chrome/browser/ui/first_run/BUILD.gn +++ b/ios/chrome/browser/ui/first_run/BUILD.gn
@@ -248,6 +248,7 @@ "//ios/chrome/browser/ui/settings/google_services:constants", "//ios/chrome/common:string_util", "//ios/chrome/common/ui/promo_style:constants", + "//ios/chrome/common/ui/table_view:cells_constants", "//ios/chrome/test/earl_grey:eg_test_support+eg2", "//ios/chrome/test/earl_grey:switches", "//ios/public/provider/chrome/browser/signin:constants",
diff --git a/ios/chrome/browser/ui/first_run/first_run_two_steps_egtest.mm b/ios/chrome/browser/ui/first_run/first_run_two_steps_egtest.mm index 867cc59..2b60ede 100644 --- a/ios/chrome/browser/ui/first_run/first_run_two_steps_egtest.mm +++ b/ios/chrome/browser/ui/first_run/first_run_two_steps_egtest.mm
@@ -3,9 +3,17 @@ // found in the LICENSE file. #import "components/signin/ios/browser/features.h" +#import "ios/chrome/browser/ui/authentication/signin_earl_grey.h" +#import "ios/chrome/browser/ui/first_run/first_run_app_interface.h" #import "ios/chrome/browser/ui/first_run/first_run_constants.h" #import "ios/chrome/browser/ui/first_run/fre_field_trial.h" +#import "ios/chrome/browser/ui/settings/google_services/google_services_settings_constants.h" #import "ios/chrome/browser/ui/ui_feature_flags.h" +#import "ios/chrome/common/ui/promo_style/constants.h" +#import "ios/chrome/common/ui/table_view/table_view_cells_constants.h" +#import "ios/chrome/test/earl_grey/chrome_actions.h" +#import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" +#import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/chrome/test/earl_grey/test_switches.h" #import "ios/testing/earl_grey/app_launch_configuration.h" @@ -15,6 +23,21 @@ #error "This file requires ARC support." #endif +namespace { + +// Returns matcher for the secondary action button. +id<GREYMatcher> PromoStyleSecondaryActionButtonMatcher() { + return grey_accessibilityID( + kPromoStyleSecondaryActionAccessibilityIdentifier); +} + +// Returns matcher for UMA manage link. +id<GREYMatcher> ManageUMALinkMatcher() { + return grey_accessibilityLabel(@"Manage"); +} + +} // namespace + // Test first run stages @interface FirstRunTwoStepsTestCase : ChromeTestCase @@ -57,10 +80,107 @@ #pragma mark Tests -// First test. -// TODO(crbug.com/1290848): Need to create EGTests for 2 steps FRE. -- (void)testWelcomeScreenUI { +// Tests FRE with UMA default value and without sign-in. +- (void)testWithUMACheckedAndNoSignin { [self verifyWelcomeScreenIsDisplayed]; + // Skip sign-in. + [[self + elementInteractionWithGreyMatcher:PromoStyleSecondaryActionButtonMatcher() + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Check that UMA is ON. + [self checkUMACheckboxValue:YES]; + // Check signed out. + [SigninEarlGrey verifySignedOut]; +} + +// Tests FRE with UMA off and without sign-in. +- (void)testWithUMAUncheckedAndNoSignin { + [self verifyWelcomeScreenIsDisplayed]; + // Scroll to and open the UMA dialog. + [[self elementInteractionWithGreyMatcher:grey_allOf( + ManageUMALinkMatcher(), + grey_sufficientlyVisible(), nil) + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Turn off UMA. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::TableViewSwitchCell( + kImproveChromeItemAccessibilityIdentifier, + /*is_toggled_on=*/YES, + /*enabled=*/YES)] + performAction:chrome_test_util::TurnTableViewSwitchOn(NO)]; + // Close UMA dialog. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + // Skip sign-in. + [[self + elementInteractionWithGreyMatcher:PromoStyleSecondaryActionButtonMatcher() + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Check that UMA is OFF. + GREYAssertFalse( + [FirstRunAppInterface isUMACollectionEnabled], + @"kMetricsReportingEnabled pref was unexpectedly true by default."); + // Check that UMA is OFF in Google Services settings. + [self checkUMACheckboxValue:NO]; + // Check signed out. + [SigninEarlGrey verifySignedOut]; +} + +// Tests FRE with UMA off, reopen UMA dialog and close the FRE without sign-in. +- (void)testUMAUncheckedWhenOpenedSecondTime { + [self verifyWelcomeScreenIsDisplayed]; + // Scroll to and open the UMA dialog. + id<GREYMatcher> manageUMALinkMatcher = + grey_allOf(ManageUMALinkMatcher(), grey_sufficientlyVisible(), nil); + [[self elementInteractionWithGreyMatcher:manageUMALinkMatcher + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Turn off UMA. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::TableViewSwitchCell( + kImproveChromeItemAccessibilityIdentifier, + /*is_toggled_on=*/YES, + /*enabled=*/YES)] + performAction:chrome_test_util::TurnTableViewSwitchOn(NO)]; + // Close UMA dialog. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + // Open UMA dialog again. + [[self elementInteractionWithGreyMatcher:manageUMALinkMatcher + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Check UMA off. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::TableViewSwitchCell( + kImproveChromeItemAccessibilityIdentifier, + /*is_toggled_on=*/NO, + /*enabled=*/YES)] + assertWithMatcher:grey_sufficientlyVisible()]; + // Wait for the toggle to be turned off. + [ChromeEarlGreyUI waitForAppToIdle]; + // Close UMA dialog. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + // Skip sign-in. + [[self + elementInteractionWithGreyMatcher:PromoStyleSecondaryActionButtonMatcher() + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Check that UMA is OFF. + [self checkUMACheckboxValue:NO]; + // Check signed out. + [SigninEarlGrey verifySignedOut]; } #pragma mark Helper @@ -73,4 +193,37 @@ assertWithMatcher:grey_notNil()]; } +// Opens the Google services settings and verify the value of UMA checkbox +// according to `UMACheckboxValue`. +- (void)checkUMACheckboxValue:(BOOL)UMACheckboxValue { + // Open Google services settings. + [ChromeEarlGreyUI openSettingsMenu]; + [ChromeEarlGreyUI + tapSettingsMenuButton:chrome_test_util::GoogleServicesSettingsButton()]; + id<GREYMatcher> cellMatcher = chrome_test_util::TableViewSwitchCell( + kImproveChromeItemAccessibilityIdentifier, + /*is_toggled_on=*/UMACheckboxValue, + /*enabled=*/YES); + [[self + elementInteractionWithGreyMatcher:cellMatcher + scrollViewIdentifier:kGoogleServicesSettingsViewIdentifier] + assertWithMatcher:grey_sufficientlyVisible()]; +} + +// Returns GREYElementInteraction for `matcher`, using `scrollViewMatcher` to +// scroll. +- (GREYElementInteraction*) + elementInteractionWithGreyMatcher:(id<GREYMatcher>)matcher + scrollViewIdentifier:(NSString*)scrollViewIdentifier { + id<GREYMatcher> scrollViewMatcher = + grey_accessibilityID(scrollViewIdentifier); + // Needs to scroll slowly to make sure to not miss a cell if it is not + // currently on the screen. It should not be bigger than the visible part + // of the collection view. + id<GREYAction> searchAction = grey_scrollInDirection(kGREYDirectionDown, 200); + return [[EarlGrey selectElementWithMatcher:matcher] + usingSearchAction:searchAction + onElementWithMatcher:scrollViewMatcher]; +} + @end
diff --git a/ios/chrome/browser/ui/first_run/uma/uma_table_view_controller.mm b/ios/chrome/browser/ui/first_run/uma/uma_table_view_controller.mm index 81ffa3e..53a3fed 100644 --- a/ios/chrome/browser/ui/first_run/uma/uma_table_view_controller.mm +++ b/ios/chrome/browser/ui/first_run/uma/uma_table_view_controller.mm
@@ -135,6 +135,8 @@ switchItem.on = self.UMAReportingUserChoice; switchItem.text = l10n_util::GetNSString(IDS_IOS_FIRST_RUN_UMA_DIALOG_CHECKBOX); + switchItem.accessibilityIdentifier = + kImproveChromeItemAccessibilityIdentifier; [model addItem:switchItem toSectionWithIdentifier:UMAMainSectionIdentifier]; // Adds the footer.
diff --git a/ios/chrome/browser/ui/main/BUILD.gn b/ios/chrome/browser/ui/main/BUILD.gn index fe53bd3..a923d6e 100644 --- a/ios/chrome/browser/ui/main/BUILD.gn +++ b/ios/chrome/browser/ui/main/BUILD.gn
@@ -111,8 +111,6 @@ "scene_delegate.h", "scene_delegate.mm", "scene_state.mm", - "signin_policy_scene_agent.h", - "signin_policy_scene_agent.mm", "ui_blocker_scene_agent.h", "ui_blocker_scene_agent.mm", ]
diff --git a/ios/chrome/browser/ui/main/scene_controller.mm b/ios/chrome/browser/ui/main/scene_controller.mm index 2df19b3e..82a120d 100644 --- a/ios/chrome/browser/ui/main/scene_controller.mm +++ b/ios/chrome/browser/ui/main/scene_controller.mm
@@ -107,9 +107,9 @@ #import "ios/chrome/browser/ui/main/incognito_blocker_scene_agent.h" #import "ios/chrome/browser/ui/main/layout_guide_scene_agent.h" #import "ios/chrome/browser/ui/main/scene_ui_provider.h" -#import "ios/chrome/browser/ui/main/signin_policy_scene_agent.h" #import "ios/chrome/browser/ui/main/ui_blocker_scene_agent.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_feature.h" +#import "ios/chrome/browser/ui/policy/signin_policy_scene_agent.h" #import "ios/chrome/browser/ui/policy/user_policy_scene_agent.h" #import "ios/chrome/browser/ui/policy/user_policy_util.h" #import "ios/chrome/browser/ui/scoped_ui_blocker/scoped_ui_blocker.h"
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index bca81144..2e8c8746 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -146,7 +146,10 @@ ":logo", ":metrics", ":ntp", + "resources:fake_omnibox_bottom_gradient_color", + "resources:fake_omnibox_top_gradient_color", "resources:incognito_icon", + "resources:ntp_background_bottom_gradient_color", "resources:ntp_opentabs", "resources:ntp_opentabs_clock", "resources:ntp_opentabs_header",
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm index 7edb8d0..fe5068e 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm
@@ -148,7 +148,8 @@ if (IsContentSuggestionsUIModuleRefreshEnabled()) { GradientView* gradientView = [[GradientView alloc] initWithTopColor:[UIColor colorNamed:kBackgroundColor] - bottomColor:[UIColor colorNamed:kGrey50Color]]; + bottomColor: + [UIColor colorNamed:@"ntp_background_bottom_gradient_color"]]; gradientView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:gradientView]; AddSameConstraints(self.view, gradientView);
diff --git a/ios/chrome/browser/ui/ntp/resources/BUILD.gn b/ios/chrome/browser/ui/ntp/resources/BUILD.gn index 7441b26..72803fe 100644 --- a/ios/chrome/browser/ui/ntp/resources/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/resources/BUILD.gn
@@ -4,6 +4,18 @@ import("//build/config/ios/asset_catalog.gni") +colorset("fake_omnibox_bottom_gradient_color") { + sources = [ "fake_omnibox_bottom_gradient_color.colorset/Contents.json" ] +} + +colorset("fake_omnibox_top_gradient_color") { + sources = [ "fake_omnibox_top_gradient_color.colorset/Contents.json" ] +} + +colorset("ntp_background_bottom_gradient_color") { + sources = [ "ntp_background_bottom_gradient_color.colorset/Contents.json" ] +} + imageset("ntp_opentabs_last_row_h") { sources = [ "ntp_opentabs_last_row_h.imageset/Contents.json",
diff --git a/ios/chrome/browser/ui/ntp/resources/fake_omnibox_bottom_gradient_color.colorset/Contents.json b/ios/chrome/browser/ui/ntp/resources/fake_omnibox_bottom_gradient_color.colorset/Contents.json new file mode 100644 index 0000000..0e47108 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/fake_omnibox_bottom_gradient_color.colorset/Contents.json
@@ -0,0 +1,38 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + }, + "colors" : [ + { + "idiom" : "universal", + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0xDB", + "green" : "0xDE", + "blue" : "0xE3" + } + } + }, + { + "idiom" : "universal", + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0x51", + "green" : "0x56", + "blue" : "0x5c" + } + } + } + ] +}
diff --git a/ios/chrome/browser/ui/ntp/resources/fake_omnibox_top_gradient_color.colorset/Contents.json b/ios/chrome/browser/ui/ntp/resources/fake_omnibox_top_gradient_color.colorset/Contents.json new file mode 100644 index 0000000..3e0db378 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/fake_omnibox_top_gradient_color.colorset/Contents.json
@@ -0,0 +1,38 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + }, + "colors" : [ + { + "idiom" : "universal", + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0xE9", + "green" : "0xEB", + "blue" : "0xEE" + } + } + }, + { + "idiom" : "universal", + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0x5F", + "green" : "0x63", + "blue" : "0x68" + } + } + } + ] +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_background_bottom_gradient_color.colorset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_background_bottom_gradient_color.colorset/Contents.json new file mode 100644 index 0000000..0cc80d3 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_background_bottom_gradient_color.colorset/Contents.json
@@ -0,0 +1,38 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + }, + "colors" : [ + { + "idiom" : "universal", + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0xF8", + "green" : "0xF9", + "blue" : "0xFA" + } + } + }, + { + "idiom" : "universal", + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "red" : "0x27", + "green" : "0x28", + "blue" : "0x2C" + } + } + } + ] +}
diff --git a/ios/chrome/browser/ui/policy/BUILD.gn b/ios/chrome/browser/ui/policy/BUILD.gn index b4146d53..4535e15f 100644 --- a/ios/chrome/browser/ui/policy/BUILD.gn +++ b/ios/chrome/browser/ui/policy/BUILD.gn
@@ -5,6 +5,8 @@ source_set("user_policy_scene_agent") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ + "signin_policy_scene_agent.h", + "signin_policy_scene_agent.mm", "user_policy_scene_agent.h", "user_policy_scene_agent.mm", "user_policy_util.h", @@ -15,19 +17,28 @@ "//base/ios", "//components/policy/core/common:common_constants", "//components/prefs", + "//components/prefs/ios", "//components/signin/public/base", + "//components/signin/public/identity_manager", + "//components/signin/public/identity_manager/objc", "//ios/chrome/app/application_delegate:app_state_header", "//ios/chrome/app/strings", + "//ios/chrome/app/strings:ios_strings_grit", + "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/main:public", "//ios/chrome/browser/policy", + "//ios/chrome/browser/policy:policy_util", "//ios/chrome/browser/signin", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/authentication", + "//ios/chrome/browser/ui/authentication/enterprise:enterprise_utils", + "//ios/chrome/browser/ui/authentication/signin", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/main:browser_interface_provider", "//ios/chrome/browser/ui/main:observing_scene_agent", "//ios/chrome/browser/ui/main:scene_ui_provider", + "//ios/chrome/browser/ui/scoped_ui_blocker", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/signin", "//ui/base",
diff --git a/ios/chrome/browser/ui/policy/OWNERS b/ios/chrome/browser/ui/policy/OWNERS new file mode 100644 index 0000000..024a15e --- /dev/null +++ b/ios/chrome/browser/ui/policy/OWNERS
@@ -0,0 +1 @@ +vincb@google.com
diff --git a/ios/chrome/browser/ui/main/signin_policy_scene_agent.h b/ios/chrome/browser/ui/policy/signin_policy_scene_agent.h similarity index 88% rename from ios/chrome/browser/ui/main/signin_policy_scene_agent.h rename to ios/chrome/browser/ui/policy/signin_policy_scene_agent.h index a812f9dd..d44dc6c 100644 --- a/ios/chrome/browser/ui/main/signin_policy_scene_agent.h +++ b/ios/chrome/browser/ui/policy/signin_policy_scene_agent.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 IOS_CHROME_BROWSER_UI_MAIN_SIGNIN_POLICY_SCENE_AGENT_H_ -#define IOS_CHROME_BROWSER_UI_MAIN_SIGNIN_POLICY_SCENE_AGENT_H_ +#ifndef IOS_CHROME_BROWSER_UI_POLICY_SIGNIN_POLICY_SCENE_AGENT_H_ +#define IOS_CHROME_BROWSER_UI_POLICY_SIGNIN_POLICY_SCENE_AGENT_H_ #import "ios/chrome/browser/ui/main/observing_scene_state_agent.h" @@ -38,4 +38,4 @@ @end -#endif // IOS_CHROME_BROWSER_UI_MAIN_SIGNIN_POLICY_SCENE_AGENT_H_ +#endif // IOS_CHROME_BROWSER_UI_POLICY_SIGNIN_POLICY_SCENE_AGENT_H_
diff --git a/ios/chrome/browser/ui/main/signin_policy_scene_agent.mm b/ios/chrome/browser/ui/policy/signin_policy_scene_agent.mm similarity index 94% rename from ios/chrome/browser/ui/main/signin_policy_scene_agent.mm rename to ios/chrome/browser/ui/policy/signin_policy_scene_agent.mm index 382b4bd..a99a3202 100644 --- a/ios/chrome/browser/ui/main/signin_policy_scene_agent.mm +++ b/ios/chrome/browser/ui/policy/signin_policy_scene_agent.mm
@@ -2,25 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/browser/ui/main/signin_policy_scene_agent.h" +#import "ios/chrome/browser/ui/policy/signin_policy_scene_agent.h" -#include "components/prefs/ios/pref_observer_bridge.h" -#include "components/prefs/pref_change_registrar.h" -#include "components/prefs/pref_service.h" -#include "components/signin/public/base/signin_metrics.h" -#include "components/signin/public/base/signin_pref_names.h" -#include "components/signin/public/identity_manager/identity_manager.h" +#import "components/prefs/ios/pref_observer_bridge.h" +#import "components/prefs/pref_change_registrar.h" +#import "components/prefs/pref_service.h" +#import "components/signin/public/base/signin_metrics.h" +#import "components/signin/public/base/signin_pref_names.h" +#import "components/signin/public/identity_manager/identity_manager.h" #import "components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h" #import "ios/chrome/app/application_delegate/app_state.h" #import "ios/chrome/app/application_delegate/app_state_observer.h" -#include "ios/chrome/browser/application_context.h" +#import "ios/chrome/browser/application_context.h" #import "ios/chrome/browser/policy/policy_util.h" #import "ios/chrome/browser/policy/policy_watcher_browser_agent.h" #import "ios/chrome/browser/policy/policy_watcher_browser_agent_observer_bridge.h" -#include "ios/chrome/browser/pref_names.h" +#import "ios/chrome/browser/pref_names.h" #import "ios/chrome/browser/signin/authentication_service.h" #import "ios/chrome/browser/signin/authentication_service_factory.h" -#include "ios/chrome/browser/signin/identity_manager_factory.h" +#import "ios/chrome/browser/signin/identity_manager_factory.h" #import "ios/chrome/browser/ui/authentication/enterprise/enterprise_utils.h" #import "ios/chrome/browser/ui/authentication/signin/signin_utils.h" #import "ios/chrome/browser/ui/commands/application_commands.h"
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm index baa759f..2efac12 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm
@@ -40,6 +40,7 @@ #import "ios/chrome/browser/ui/ui_feature_flags.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #import "ios/chrome/common/ui/colors/semantic_color_names.h" +#import "ios/chrome/common/ui/table_view/table_view_cells_constants.h" #include "ios/chrome/grit/ios_chromium_strings.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/public/provider/chrome/browser/signin/chrome_identity.h" @@ -419,6 +420,8 @@ IDS_IOS_GOOGLE_SERVICES_SETTINGS_IMPROVE_CHROME_TEXT detailStringID: IDS_IOS_GOOGLE_SERVICES_SETTINGS_IMPROVE_CHROME_DETAIL]; + improveChromeItem.accessibilityIdentifier = + kImproveChromeItemAccessibilityIdentifier; [items addObject:improveChromeItem]; } if (self.userPrefService->IsManagedPreference(
diff --git a/ios/chrome/browser/ui/settings/password/BUILD.gn b/ios/chrome/browser/ui/settings/password/BUILD.gn index caa7ae96..e6715633 100644 --- a/ios/chrome/browser/ui/settings/password/BUILD.gn +++ b/ios/chrome/browser/ui/settings/password/BUILD.gn
@@ -24,6 +24,7 @@ "//components/autofill/core/common", "//components/password_manager/core/common:features", "//components/signin/public/identity_manager/objc", + "//components/sync", "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/browser_state",
diff --git a/ios/chrome/browser/ui/settings/password/password_issues_coordinator.mm b/ios/chrome/browser/ui/settings/password/password_issues_coordinator.mm index 6d587d9..7210f06 100644 --- a/ios/chrome/browser/ui/settings/password/password_issues_coordinator.mm +++ b/ios/chrome/browser/ui/settings/password/password_issues_coordinator.mm
@@ -8,6 +8,7 @@ #import "ios/chrome/browser/favicon/favicon_loader.h" #include "ios/chrome/browser/favicon/ios_chrome_favicon_loader_factory.h" #import "ios/chrome/browser/main/browser.h" +#import "ios/chrome/browser/sync/sync_service_factory.h" #import "ios/chrome/browser/ui/commands/application_commands.h" #import "ios/chrome/browser/ui/commands/command_dispatcher.h" #import "ios/chrome/browser/ui/settings/password/password_details/password_details_coordinator.h" @@ -67,13 +68,16 @@ // To start, a password check manager should be ready. DCHECK(_manager); + ChromeBrowserState* browserState = self.browser->GetBrowserState(); FaviconLoader* faviconLoader = - IOSChromeFaviconLoaderFactory::GetForBrowserState( - self.browser->GetBrowserState()); + IOSChromeFaviconLoaderFactory::GetForBrowserState(browserState); + syncer::SyncService* syncService = + SyncServiceFactory::GetForBrowserState(browserState); - self.mediator = [[PasswordIssuesMediator alloc] - initWithPasswordCheckManager:_manager - faviconLoader:faviconLoader]; + self.mediator = + [[PasswordIssuesMediator alloc] initWithPasswordCheckManager:_manager + faviconLoader:faviconLoader + syncService:syncService]; PasswordIssuesTableViewController* passwordIssuesTableViewController = [[PasswordIssuesTableViewController alloc]
diff --git a/ios/chrome/browser/ui/settings/password/password_issues_mediator.h b/ios/chrome/browser/ui/settings/password/password_issues_mediator.h index bda8a14..9590909 100644 --- a/ios/chrome/browser/ui/settings/password/password_issues_mediator.h +++ b/ios/chrome/browser/ui/settings/password/password_issues_mediator.h
@@ -7,6 +7,7 @@ #import <Foundation/Foundation.h> +#include "ios/chrome/browser/sync/sync_service_factory.h" #import "ios/chrome/browser/ui/table_view/table_view_favicon_data_source.h" #import "ios/chrome/common/ui/reauthentication/reauthentication_module.h" @@ -25,6 +26,7 @@ - (instancetype)initWithPasswordCheckManager: (IOSChromePasswordCheckManager*)manager faviconLoader:(FaviconLoader*)faviconLoader + syncService:(syncer::SyncService*)syncService NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/settings/password/password_issues_mediator.mm b/ios/chrome/browser/ui/settings/password/password_issues_mediator.mm index f3bfaa8..bd3e45d 100644 --- a/ios/chrome/browser/ui/settings/password/password_issues_mediator.mm +++ b/ios/chrome/browser/ui/settings/password/password_issues_mediator.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/ui/settings/password/password_issues_mediator.h" #include "components/password_manager/core/browser/ui/insecure_credentials_manager.h" +#import "components/sync/driver/sync_service.h" #import "ios/chrome/browser/favicon/favicon_loader.h" #import "ios/chrome/browser/net/crurl.h" #include "ios/chrome/browser/passwords/password_check_observer_bridge.h" @@ -35,15 +36,20 @@ // favicon images. @property(nonatomic, assign) FaviconLoader* faviconLoader; +// Service to know whether passwords are synced. +@property(nonatomic, assign) syncer::SyncService* syncService; + @end @implementation PasswordIssuesMediator - (instancetype)initWithPasswordCheckManager: (IOSChromePasswordCheckManager*)manager - faviconLoader:(FaviconLoader*)faviconLoader { + faviconLoader:(FaviconLoader*)faviconLoader + syncService:(syncer::SyncService*)syncService { self = [super init]; if (self) { + _syncService = syncService; _faviconLoader = faviconLoader; _manager = manager; _passwordCheckObserver.reset( @@ -124,7 +130,8 @@ completion:(void (^)(FaviconAttributes*))completion { self.faviconLoader->FaviconForPageUrl( URL.gurl, kDesiredMediumFaviconSizePt, kMinFaviconSizePt, - /*fallback_to_google_server=*/false, ^(FaviconAttributes* attributes) { + self.syncService->IsSyncFeatureEnabled(), + ^(FaviconAttributes* attributes) { completion(attributes); }); }
diff --git a/ios/chrome/browser/ui/settings/password/password_issues_mediator_unittest.mm b/ios/chrome/browser/ui/settings/password/password_issues_mediator_unittest.mm index 0e927614..647a78af 100644 --- a/ios/chrome/browser/ui/settings/password/password_issues_mediator_unittest.mm +++ b/ios/chrome/browser/ui/settings/password/password_issues_mediator_unittest.mm
@@ -17,6 +17,8 @@ #include "ios/chrome/browser/passwords/ios_chrome_password_check_manager_factory.h" #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h" #include "ios/chrome/browser/passwords/password_check_observer_bridge.h" +#import "ios/chrome/browser/sync/sync_setup_service_factory.h" +#import "ios/chrome/browser/sync/sync_setup_service_mock.h" #import "ios/chrome/browser/ui/settings/password/password_issues_consumer.h" #import "ios/chrome/browser/ui/table_view/chrome_table_view_controller_test.h" #include "ios/web/public/test/web_task_environment.h" @@ -82,6 +84,9 @@ BlockCleanupTest::SetUp(); // Create BrowserState. TestChromeBrowserState::Builder test_cbs_builder; + test_cbs_builder.AddTestingFactory( + SyncSetupServiceFactory::GetInstance(), + base::BindRepeating(&SyncSetupServiceMock::CreateKeyedService)); chrome_browser_state_ = test_cbs_builder.Build(); store_ = CreateAndUseTestPasswordStore(chrome_browser_state_.get()); @@ -95,7 +100,9 @@ initWithPasswordCheckManager:password_check_.get() faviconLoader:IOSChromeFaviconLoaderFactory:: GetForBrowserState( - chrome_browser_state_.get())]; + chrome_browser_state_.get()) + syncService:SyncServiceFactory::GetForBrowserState( + chrome_browser_state_.get())]; mediator_.consumer = consumer_; } @@ -126,7 +133,7 @@ void RunUntilIdle() { task_environment_.RunUntilIdle(); } private: - base::test::TaskEnvironment task_environment_; + web::WebTaskEnvironment task_environment_; std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; scoped_refptr<TestPasswordStore> store_; scoped_refptr<IOSChromePasswordCheckManager> password_check_;
diff --git a/ios/chrome/browser/ui/settings/password/passwords_mediator.mm b/ios/chrome/browser/ui/settings/password/passwords_mediator.mm index 3546c41..18bbbb8a 100644 --- a/ios/chrome/browser/ui/settings/password/passwords_mediator.mm +++ b/ios/chrome/browser/ui/settings/password/passwords_mediator.mm
@@ -376,7 +376,8 @@ completion:(void (^)(FaviconAttributes*))completion { self.faviconLoader->FaviconForPageUrl( URL.gurl, kDesiredMediumFaviconSizePt, kMinFaviconSizePt, - /*fallback_to_google_server=*/false, ^(FaviconAttributes* attributes) { + self.syncService->IsSyncFeatureEnabled(), + ^(FaviconAttributes* attributes) { completion(attributes); }); }
diff --git a/ios/chrome/common/ui/table_view/table_view_cells_constants.h b/ios/chrome/common/ui/table_view/table_view_cells_constants.h index 69f550708..d01d315 100644 --- a/ios/chrome/common/ui/table_view/table_view_cells_constants.h +++ b/ios/chrome/common/ui/table_view/table_view_cells_constants.h
@@ -73,4 +73,8 @@ // Returns a padding according to the width of the current device. extern CGFloat HorizontalPadding(); +// Accessibility identifier for UMA checkbox in the FRE and in Google services +// settings. +extern NSString* const kImproveChromeItemAccessibilityIdentifier; + #endif // IOS_CHROME_COMMON_UI_TABLE_VIEW_TABLE_VIEW_CELLS_CONSTANTS_H_
diff --git a/ios/chrome/common/ui/table_view/table_view_cells_constants.mm b/ios/chrome/common/ui/table_view/table_view_cells_constants.mm index 252301d..6961ea7d 100644 --- a/ios/chrome/common/ui/table_view/table_view_cells_constants.mm +++ b/ios/chrome/common/ui/table_view/table_view_cells_constants.mm
@@ -35,6 +35,9 @@ NSString* const kTableViewURLCellFaviconBadgeViewID = @"TableViewURLCellFaviconBadgeView"; +NSString* const kImproveChromeItemAccessibilityIdentifier = + @"ImproveChromeItemAccessibilityIdentifier"; + CGFloat HorizontalPadding() { if (!IsSmallDevice()) return 0;
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 index e57d898..83e898f3 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -d6b1eb771ac0ce46bf579c38984da931fa0d005b \ No newline at end of file +e28add7579074585f2358812de8776efcef27a32 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 index 71fa1cb7..dd4ccf3 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -2f9790030838889f05609e3709afd13c3a658973 \ No newline at end of file +75d2c2195192db8266f3c4c3f214ac36a0634468 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 index 61ee0f7..20320a9 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -ad75f0ce710965c4dd4d5077b80dc0637ca707e5 \ No newline at end of file +4528b355a44b47fd44587dc51c681e52641f0903 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 index 3bd95f85..8a7f8d6 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -7755450dc8a3ca0ede999d2e50aa04eb96e2e8fc \ No newline at end of file +8990eecbbcf363af85698cacffdbf1a1adb38014 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 index 5e24222..1e149ca 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -fc24f4114ddabf325b5350fde2532278bef88ddd \ No newline at end of file +af826a673db2920221ef80504e48fceab58a7a13 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 index 128507b..25165702 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -a5833abcca3a3e57b42c501994897c2457f5e0c7 \ No newline at end of file +7a278100e98f913e2cd8f9b4357cced8fa1c985c \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 index a4b64ed..3668ef41 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -1a8e92fa18e95fc3ad466483b54c0dcfd684dd11 \ No newline at end of file +81334c644a60a78ac290277c2bed676d641f0937 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 index f1e87088..d9d8366 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -c420faf55a29a041120efdc713459ba19b3a6a53 \ No newline at end of file +6a5cf11949e7d42bfbe98995d29477b09a717c40 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 index 65ac346..661ffcc 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -6288b25249f085814db8414683ecde1b59a450c8 \ No newline at end of file +a9e4fd58c599b71d271aaf59561bca20f6e67423 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 index f2314ee..e8481e56 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -bcdb811e992c5071e9ebdc742f2c9bfc98b9bbd5 \ No newline at end of file +a57095dd2db43bd3263c05bb74223e21f59a670f \ No newline at end of file
diff --git a/media/audio/cras/cras_input.cc b/media/audio/cras/cras_input.cc index df5667d..7ffca72 100644 --- a/media/audio/cras/cras_input.cc +++ b/media/audio/cras/cras_input.cc
@@ -441,7 +441,9 @@ } bool CrasInputStream::IsMuted() { - return false; + int muted = 0; + libcras_client_get_system_capture_muted(client_, &muted); + return static_cast<bool>(muted); } void CrasInputStream::SetOutputDeviceForAec(
diff --git a/media/audio/system_glitch_reporter.cc b/media/audio/system_glitch_reporter.cc index cc57c6b..fea682cc 100644 --- a/media/audio/system_glitch_reporter.cc +++ b/media/audio/system_glitch_reporter.cc
@@ -5,6 +5,7 @@ #include "media/audio/system_glitch_reporter.h" #include "base/metrics/histogram_functions.h" +#include "base/trace_event/trace_event.h" namespace media { @@ -50,6 +51,10 @@ ++callback_count_; if (glitch_duration.is_positive()) { + TRACE_EVENT_INSTANT1("audio", "OsGlitchDetected", TRACE_EVENT_SCOPE_THREAD, + "glitch_duration_ms", + glitch_duration.InMilliseconds()); + if (callback_count_ <= kCallbacksPerLogPeriod) early_glitch_detected_ = true;
diff --git a/net/base/chunked_upload_data_stream.cc b/net/base/chunked_upload_data_stream.cc index 9e812f37..fac1432a 100644 --- a/net/base/chunked_upload_data_stream.cc +++ b/net/base/chunked_upload_data_stream.cc
@@ -26,8 +26,9 @@ base::WeakPtr<ChunkedUploadDataStream> upload_data_stream) : upload_data_stream_(upload_data_stream) {} -ChunkedUploadDataStream::ChunkedUploadDataStream(int64_t identifier) - : UploadDataStream(true, identifier) {} +ChunkedUploadDataStream::ChunkedUploadDataStream(int64_t identifier, + bool has_null_source) + : UploadDataStream(/*is_chunked=*/true, has_null_source, identifier) {} ChunkedUploadDataStream::~ChunkedUploadDataStream() = default;
diff --git a/net/base/chunked_upload_data_stream.h b/net/base/chunked_upload_data_stream.h index 117765d53..a8564f9 100644 --- a/net/base/chunked_upload_data_stream.h +++ b/net/base/chunked_upload_data_stream.h
@@ -56,7 +56,8 @@ const base::WeakPtr<ChunkedUploadDataStream> upload_data_stream_; }; - explicit ChunkedUploadDataStream(int64_t identifier); + explicit ChunkedUploadDataStream(int64_t identifier, + bool has_null_source = false); ChunkedUploadDataStream(const ChunkedUploadDataStream&) = delete; ChunkedUploadDataStream& operator=(const ChunkedUploadDataStream&) = delete;
diff --git a/net/base/upload_data_stream.cc b/net/base/upload_data_stream.cc index c282bd2..3444b89f 100644 --- a/net/base/upload_data_stream.cc +++ b/net/base/upload_data_stream.cc
@@ -35,7 +35,13 @@ } // namespace UploadDataStream::UploadDataStream(bool is_chunked, int64_t identifier) - : identifier_(identifier), is_chunked_(is_chunked) {} + : UploadDataStream(is_chunked, /*has_null_source=*/false, identifier) {} +UploadDataStream::UploadDataStream(bool is_chunked, + bool has_null_source, + int64_t identifier) + : identifier_(identifier), + is_chunked_(is_chunked), + has_null_source_(has_null_source) {} UploadDataStream::~UploadDataStream() = default;
diff --git a/net/base/upload_data_stream.h b/net/base/upload_data_stream.h index 89eeef08..0f9b0c2f 100644 --- a/net/base/upload_data_stream.h +++ b/net/base/upload_data_stream.h
@@ -28,6 +28,7 @@ // cache to formulate a cache key. This value should be unique across browser // sessions. A value of 0 is used to indicate an unspecified identifier. UploadDataStream(bool is_chunked, int64_t identifier); + UploadDataStream(bool is_chunked, bool has_null_source, int64_t identifier); UploadDataStream(const UploadDataStream&) = delete; UploadDataStream& operator=(const UploadDataStream&) = delete; @@ -73,6 +74,10 @@ bool is_chunked() const { return is_chunked_; } + // Returns true if the stream has a null source which is defined at + // https://fetch.spec.whatwg.org/#concept-body-source. + bool has_null_source() const { return has_null_source_; } + // Returns true if all data has been consumed from this upload data // stream. For chunked uploads, returns false until the first read attempt. // This makes some state machines a little simpler. @@ -139,6 +144,7 @@ const int64_t identifier_; const bool is_chunked_; + const bool has_null_source_; // True if the initialization was successful. bool initialized_successfully_ = false;
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index 2b8500a9..2c30eab2 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -2033,15 +2033,11 @@ if (mark_single_keyed_cache_entry_unusable_) { response_.single_keyed_cache_entry_unusable = true; } - if (new_response_->vary_data.is_valid()) { - response_.vary_data = new_response_->vary_data; - } else if (response_.vary_data.is_valid()) { - // There is a vary header in the stored response but not in the current one. - // Update the data with the new request headers. - HttpVaryData new_vary_data; - new_vary_data.Init(*request_, *response_.headers.get()); - response_.vary_data = new_vary_data; - } + + // If the new response didn't have a vary header, we continue to use the + // header from the stored response per the effect of headers->Update(). + // Update the data with the new/updated request headers. + response_.vary_data.Init(*request_, *response_.headers); if (ShouldDisableCaching(*response_.headers)) { if (!entry_->doomed) { @@ -3656,6 +3652,12 @@ void HttpCache::Transaction::SetResponse(const HttpResponseInfo& response) { response_ = response; + + if (response_.headers) { + DCHECK(request_); + response_.vary_data.Init(*request_, *response_.headers); + } + SyncCacheEntryStatusToResponse(); }
diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc index 29fe1a6c..ed658f5 100644 --- a/net/http/http_network_transaction.cc +++ b/net/http/http_network_transaction.cc
@@ -1208,8 +1208,12 @@ return OK; } + const bool has_body_with_null_source = + request_->upload_data_stream && + request_->upload_data_stream->has_null_source(); if (response_.headers->response_code() == 421 && - (enable_ip_based_pooling_ || enable_alternative_services_)) { + (enable_ip_based_pooling_ || enable_alternative_services_) && + !has_body_with_null_source) { #if BUILDFLAG(ENABLE_REPORTING) GenerateNetworkErrorLoggingReport(OK); #endif // BUILDFLAG(ENABLE_REPORTING)
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index fd516c8b1..ccb7058a 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -11169,16 +11169,6 @@ response->response_time = base::Time::Now(); response->was_cached = true; // (Wouldn't ever actually be true...) - { // Setup state for response_.vary_data - HttpRequestInfo request; - std::string temp("HTTP/1.1 200 OK\nVary: foo, bar\n\n"); - std::replace(temp.begin(), temp.end(), '\n', '\0'); - scoped_refptr<HttpResponseHeaders> headers(new HttpResponseHeaders(temp)); - request.extra_headers.SetHeader("Foo", "1"); - request.extra_headers.SetHeader("bar", "23"); - EXPECT_TRUE(response->vary_data.Init(request, *headers.get())); - } - // Cause the above state to be reset. trans.ResetStateForRestart(); @@ -11190,7 +11180,6 @@ EXPECT_FALSE(response->headers); EXPECT_FALSE(response->was_cached); EXPECT_EQ(0U, response->ssl_info.cert_status); - EXPECT_FALSE(response->vary_data.is_valid()); } // Test HTTPS connections to a site with a bad certificate @@ -17636,6 +17625,164 @@ } TEST_F(HttpNetworkTransactionTest, + Response421WithStreamingBodyWithNonNullSource) { + const std::string ip_addr = "1.2.3.4"; + IPAddress ip; + ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr)); + IPEndPoint peer_addr = IPEndPoint(ip, 443); + + session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>(); + session_deps_.host_resolver->rules()->AddRule("www.example.org", ip_addr); + std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_)); + + const std::string request_body = "hello"; + spdy::SpdySerializedFrame req1 = spdy_util_.ConstructChunkedSpdyPost({}, 0); + spdy::SpdySerializedFrame req1_body = + spdy_util_.ConstructSpdyDataFrame(1, request_body, /*fin=*/true); + spdy::SpdySerializedFrame rst = + spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL); + MockWrite writes1[] = { + CreateMockWrite(req1, 0), + CreateMockWrite(req1_body, 1), + CreateMockWrite(rst, 4), + }; + + spdy::Http2HeaderBlock response_headers; + response_headers[spdy::kHttp2StatusHeader] = "421"; + spdy::SpdySerializedFrame resp1 = + spdy_util_.ConstructSpdyReply(1, std::move(response_headers)); + MockRead reads1[] = {CreateMockRead(resp1, 2), MockRead(ASYNC, 0, 3)}; + + MockConnect connect1(ASYNC, OK, peer_addr); + SequencedSocketData data1(connect1, reads1, writes1); + session_deps_.socket_factory->AddSocketDataProvider(&data1); + + AddSSLSocketData(); + + SpdyTestUtil spdy_util2; + spdy::SpdySerializedFrame req2 = spdy_util2.ConstructChunkedSpdyPost({}, 0); + spdy::SpdySerializedFrame req2_body = + spdy_util2.ConstructSpdyDataFrame(1, request_body, /*fin=*/true); + MockWrite writes2[] = { + CreateMockWrite(req2, 0), + CreateMockWrite(req2_body, 1), + }; + + spdy::Http2HeaderBlock resp2_headers; + resp2_headers[spdy::kHttp2StatusHeader] = "200"; + spdy::SpdySerializedFrame resp2 = + spdy_util2.ConstructSpdyReply(1, std::move(resp2_headers)); + spdy::SpdySerializedFrame resp2_body( + spdy_util2.ConstructSpdyDataFrame(1, true)); + MockRead reads2[] = {CreateMockRead(resp2, 2), CreateMockRead(resp2_body, 3), + MockRead(ASYNC, 0, 4)}; + + MockConnect connect2(ASYNC, OK, peer_addr); + SequencedSocketData data2(connect2, reads2, writes2); + session_deps_.socket_factory->AddSocketDataProvider(&data2); + + AddSSLSocketData(); + + TestCompletionCallback callback; + HttpRequestInfo request; + ChunkedUploadDataStream upload_data_stream(0, /*has_null_source=*/false); + upload_data_stream.AppendData(request_body.data(), request_body.size(), + /*is_done=*/true); + request.method = "POST"; + request.url = GURL("https://www.example.org"); + request.load_flags = 0; + request.traffic_annotation = + net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS); + request.upload_data_stream = &upload_data_stream; + HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get()); + + int rv = trans.Start(&request, callback.callback(), + NetLogWithSource::Make(NetLogSourceType::NONE)); + EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); + rv = callback.WaitForResult(); + EXPECT_THAT(rv, IsOk()); + + const HttpResponseInfo* response = trans.GetResponseInfo(); + std::string response_data; + ASSERT_TRUE(response); + ASSERT_TRUE(response->headers); + EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine()); + EXPECT_TRUE(response->was_fetched_via_spdy); + EXPECT_TRUE(response->was_alpn_negotiated); + EXPECT_TRUE(response->ssl_info.cert); + ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk()); + EXPECT_EQ("hello!", response_data); +} + +TEST_F(HttpNetworkTransactionTest, Response421WithStreamingBodyWithNullSource) { + const std::string ip_addr = "1.2.3.4"; + IPAddress ip; + ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr)); + IPEndPoint peer_addr = IPEndPoint(ip, 443); + + session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>(); + session_deps_.host_resolver->rules()->AddRule("www.example.org", ip_addr); + std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_)); + + const std::string request_body = "hello"; + spdy::SpdySerializedFrame req1 = spdy_util_.ConstructChunkedSpdyPost({}, 0); + spdy::SpdySerializedFrame req1_body = + spdy_util_.ConstructSpdyDataFrame(1, request_body, /*fin=*/true); + spdy::SpdySerializedFrame rst = + spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL); + MockWrite writes1[] = { + CreateMockWrite(req1, 0), + CreateMockWrite(req1_body, 1), + CreateMockWrite(rst, 5), + }; + + spdy::Http2HeaderBlock response_headers; + response_headers[spdy::kHttp2StatusHeader] = "421"; + spdy::SpdySerializedFrame resp1 = + spdy_util_.ConstructSpdyReply(1, std::move(response_headers)); + spdy::SpdySerializedFrame resp1_body( + spdy_util_.ConstructSpdyDataFrame(1, true)); + MockRead reads1[] = {CreateMockRead(resp1, 2), CreateMockRead(resp1_body, 3), + MockRead(ASYNC, 0, 4)}; + + MockConnect connect1(ASYNC, OK, peer_addr); + SequencedSocketData data1(connect1, reads1, writes1); + session_deps_.socket_factory->AddSocketDataProvider(&data1); + + AddSSLSocketData(); + + TestCompletionCallback callback; + HttpRequestInfo request; + ChunkedUploadDataStream upload_data_stream(0, /*has_null_source=*/true); + upload_data_stream.AppendData(request_body.data(), request_body.size(), + /*is_done=*/true); + request.method = "POST"; + request.url = GURL("https://www.example.org"); + request.load_flags = 0; + request.traffic_annotation = + net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS); + request.upload_data_stream = &upload_data_stream; + HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get()); + + int rv = trans.Start(&request, callback.callback(), + NetLogWithSource::Make(NetLogSourceType::NONE)); + EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); + rv = callback.WaitForResult(); + EXPECT_THAT(rv, IsOk()); + + const HttpResponseInfo* response = trans.GetResponseInfo(); + std::string response_data; + ASSERT_TRUE(response); + ASSERT_TRUE(response->headers); + EXPECT_EQ("HTTP/1.1 421", response->headers->GetStatusLine()); + EXPECT_TRUE(response->was_fetched_via_spdy); + EXPECT_TRUE(response->was_alpn_negotiated); + EXPECT_TRUE(response->ssl_info.cert); + ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk()); + EXPECT_EQ("hello!", response_data); +} + +TEST_F(HttpNetworkTransactionTest, UseIPConnectionPoolingWithHostCacheExpiration) { // Set up HostResolver to invalidate cached entries after 1 cached resolve. session_deps_.host_resolver =
diff --git a/net/http/http_response_info.h b/net/http/http_response_info.h index e09a96c4..1570e6f 100644 --- a/net/http/http_response_info.h +++ b/net/http/http_response_info.h
@@ -252,6 +252,7 @@ scoped_refptr<HttpResponseHeaders> headers; // The "Vary" header data for this response. + // Initialized and used only by HttpCache::Transaction. HttpVaryData vary_data; // Any DNS aliases for the remote endpoint. Includes all known aliases, e.g.
diff --git a/net/http/http_stream_parser.cc b/net/http/http_stream_parser.cc index 3b7c4b3..3d3a1d5 100644 --- a/net/http/http_stream_parser.cc +++ b/net/http/http_stream_parser.cc
@@ -1035,7 +1035,6 @@ } else if (headers->GetHttpVersion() == HttpVersion(1, 1)) { response_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP1_1; } - response_->vary_data.Init(*request_, *response_->headers); DVLOG(1) << __func__ << "() content_length = \"" << response_->headers->GetContentLength() << "\n\"" << " headers = \"" << GetResponseHeaderLines(*response_->headers)
diff --git a/net/http/http_transaction_test_util.cc b/net/http/http_transaction_test_util.cc index ebd1968..5ea84b3 100644 --- a/net/http/http_transaction_test_util.cc +++ b/net/http/http_transaction_test_util.cc
@@ -507,7 +507,6 @@ response_.response_time = t->response_time; response_.headers = new HttpResponseHeaders(header_data); - response_.vary_data.Init(*request, *response_.headers.get()); response_.ssl_info.cert = t->cert; response_.ssl_info.cert_status = t->cert_status; response_.ssl_info.connection_status = t->ssl_connection_status;
diff --git a/net/quic/quic_http_stream.cc b/net/quic/quic_http_stream.cc index dcbcaef..4eb5f99 100644 --- a/net/quic/quic_http_stream.cc +++ b/net/quic/quic_http_stream.cc
@@ -700,8 +700,6 @@ response_info_->connection_info = ConnectionInfoFromQuicVersion(quic_session()->GetQuicVersion()); - response_info_->vary_data.Init(*request_info_, - *response_info_->headers.get()); response_info_->was_alpn_negotiated = true; response_info_->alpn_negotiated_protocol = HttpResponseInfo::ConnectionInfoToString(response_info_->connection_info);
diff --git a/net/spdy/spdy_http_stream.cc b/net/spdy/spdy_http_stream.cc index be3c2d7..0ec9f44 100644 --- a/net/spdy/spdy_http_stream.cc +++ b/net/spdy/spdy_http_stream.cc
@@ -435,8 +435,6 @@ response_info_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP2; response_info_->alpn_negotiated_protocol = HttpResponseInfo::ConnectionInfoToString(response_info_->connection_info); - response_info_->vary_data - .Init(*request_info_, *response_info_->headers.get()); // Invalidate HttpRequestInfo pointer. This is to allow |this| to be // shared across multiple consumers at the cache layer which might require
diff --git a/net/websockets/websocket_http2_handshake_stream.cc b/net/websockets/websocket_http2_handshake_stream.cc index dfbe503..b5c4e97 100644 --- a/net/websockets/websocket_http2_handshake_stream.cc +++ b/net/websockets/websocket_http2_handshake_stream.cc
@@ -296,8 +296,6 @@ http_response_info_->alpn_negotiated_protocol = HttpResponseInfo::ConnectionInfoToString( http_response_info_->connection_info); - http_response_info_->vary_data.Init(*request_info_, - *http_response_info_->headers.get()); if (callback_) std::move(callback_).Run(ValidateResponse());
diff --git a/remoting/host/policy_watcher.cc b/remoting/host/policy_watcher.cc index a8d94df..e82e73f 100644 --- a/remoting/host/policy_watcher.cc +++ b/remoting/host/policy_watcher.cc
@@ -177,7 +177,9 @@ auto result = std::make_unique<base::DictionaryValue>(); result->SetBoolKey(key::kRemoteAccessHostFirewallTraversal, true); result->SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) result->SetBoolKey(key::kRemoteAccessHostMatchUsername, false); +#endif result->Set(key::kRemoteAccessHostClientDomainList, std::make_unique<base::ListValue>()); result->Set(key::kRemoteAccessHostDomainList, @@ -190,8 +192,11 @@ result->SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, true); result->SetBoolKey(key::kRemoteAccessHostAllowRelayedConnection, true); result->SetStringKey(key::kRemoteAccessHostUdpPortRange, ""); + +#if BUILDFLAG(IS_WIN) result->SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, false); +#endif result->SetIntKey(key::kRemoteAccessHostClipboardSizeBytes, -1); result->SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); #if !BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/remoting/host/policy_watcher_unittest.cc b/remoting/host/policy_watcher_unittest.cc index d2b5ba85..10d3a342 100644 --- a/remoting/host/policy_watcher_unittest.cc +++ b/remoting/host/policy_watcher_unittest.cc
@@ -162,8 +162,10 @@ curtain_true_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, true); curtain_false_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) username_true_.SetBoolKey(key::kRemoteAccessHostMatchUsername, true); username_false_.SetBoolKey(key::kRemoteAccessHostMatchUsername, false); +#endif third_party_auth_partial_.SetStringKey(key::kRemoteAccessHostTokenUrl, "https://token.com"); third_party_auth_partial_.SetStringKey( @@ -316,7 +318,9 @@ dict.SetStringKey(key::kRemoteAccessHostUdpPortRange, ""); dict.SetKey(key::kRemoteAccessHostClientDomainList, base::ListValue()); dict.SetKey(key::kRemoteAccessHostDomainList, base::ListValue()); +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) dict.SetBoolKey(key::kRemoteAccessHostMatchUsername, false); +#endif dict.SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); dict.SetStringKey(key::kRemoteAccessHostTokenUrl, ""); dict.SetStringKey(key::kRemoteAccessHostTokenValidationUrl, ""); @@ -324,8 +328,10 @@ ""); dict.SetBoolKey(key::kRemoteAccessHostAllowClientPairing, true); dict.SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, true); +#if BUILDFLAG(IS_WIN) dict.SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, false); +#endif dict.SetInteger(key::kRemoteAccessHostClipboardSizeBytes, -1); dict.SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); #if !BUILDFLAG(IS_CHROMEOS_ASH) @@ -636,25 +642,22 @@ SetPolicies(curtain_false_); } +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) TEST_F(PolicyWatcherTest, MatchUsername) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); -#if !BUILDFLAG(IS_WIN) EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&username_true_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&username_false_))); -#else -// On Windows the MatchUsername policy is ignored and therefore the 2 -// SetPolicies calls won't result in any calls to OnPolicyUpdate. -#endif SetPolicies(empty_); StartWatching(); SetPolicies(username_true_); SetPolicies(username_false_); } +#endif TEST_F(PolicyWatcherTest, ThirdPartyAuthFull) { testing::InSequence sequence; @@ -716,21 +719,16 @@ i.Advance()) { expected_schema[i.key()] = i.value().type(); } -#if BUILDFLAG(IS_WIN) - // RemoteAccessHostMatchUsername is marked in policy_templates.json as not - // supported on Windows and therefore is (by design) excluded from the schema. - expected_schema.erase(key::kRemoteAccessHostMatchUsername); -#elif BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_CHROMEOS_ASH) // Me2Me Policies are not supported on ChromeOS. expected_schema.erase(key::kRemoteAccessHostAllowGnubbyAuth); expected_schema.erase(key::kRemoteAccessHostAllowClientPairing); - expected_schema.erase(key::kRemoteAccessHostMatchUsername); expected_schema.erase(key::kRemoteAccessHostRequireCurtain); expected_schema.erase(key::kRemoteAccessHostTokenUrl); expected_schema.erase(key::kRemoteAccessHostTokenValidationUrl); expected_schema.erase(key::kRemoteAccessHostTokenValidationCertificateIssuer); expected_schema.erase(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance); -#else // !BUILDFLAG(IS_WIN) +#elif !BUILDFLAG(IS_WIN) // RemoteAssistanceHostAllowUiAccess does not exist on non-Windows platforms. expected_schema.erase(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance); #endif
diff --git a/remoting/host/remoting_me2me_host.cc b/remoting/host/remoting_me2me_host.cc index aa18759..5bd9809f 100644 --- a/remoting/host/remoting_me2me_host.cc +++ b/remoting/host/remoting_me2me_host.cc
@@ -1327,6 +1327,7 @@ // Returns false: never restart the host after this policy update. DCHECK(context_->network_task_runner()->BelongsToCurrentThread()); +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) absl::optional<bool> host_username_match_required = policies->FindBoolKey(policy::key::kRemoteAccessHostMatchUsername); if (!host_username_match_required.has_value()) @@ -1334,6 +1335,7 @@ host_username_match_required_ = host_username_match_required.value(); ApplyUsernamePolicy(); +#endif return false; }
diff --git a/services/BUILD.gn b/services/BUILD.gn index 0677bec..b922497c 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn
@@ -162,6 +162,7 @@ "//third_party/android_support_test_runner:runner_java", "//third_party/androidx:androidx_test_monitor_java", "//third_party/androidx:androidx_test_runner_java", + "//third_party/hamcrest:hamcrest_library_java", "//third_party/junit", "//ui/gfx/geometry/mojom:mojom_java", ]
diff --git a/services/audio/loopback_stream.cc b/services/audio/loopback_stream.cc index f3d7242..f6959d9b 100644 --- a/services/audio/loopback_stream.cc +++ b/services/audio/loopback_stream.cc
@@ -276,7 +276,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(control_sequence_); DCHECK(!is_started()); - timer_.emplace(clock_); + timer_.emplace(); // Note: GenerateMoreAudio() will schedule the timer. first_generate_time_ = clock_->NowTicks(); @@ -401,8 +401,8 @@ // due to integer truncation behaviors in the math above. The timer task // started below will just run immediately and there will be no harmful // effects in the next GenerateMoreAudio() call. http://crbug.com/847487 - timer_->Start(FROM_HERE, next_generate_time_ - now, this, - &FlowNetwork::GenerateMoreAudio); + timer_->Start(FROM_HERE, next_generate_time_, this, + &FlowNetwork::GenerateMoreAudio, base::ExactDeadline(true)); } } // namespace audio
diff --git a/services/audio/loopback_stream.h b/services/audio/loopback_stream.h index dcbacb9..21af2d2 100644 --- a/services/audio/loopback_stream.h +++ b/services/audio/loopback_stream.h
@@ -188,7 +188,7 @@ // This is set once Start() is called, and lives until this FlowNetwork is // destroyed. It is used to schedule cancelable tasks run by the // |flow_task_runner_|. - absl::optional<base::OneShotTimer> timer_; + absl::optional<base::DeadlineTimer> timer_; // These are used to compute when the |timer_| fires and calls // GenerateMoreAudio(). They ensure that each timer task is scheduled to
diff --git a/services/network/BUILD.gn b/services/network/BUILD.gn index 7c7dd11..063dfd25 100644 --- a/services/network/BUILD.gn +++ b/services/network/BUILD.gn
@@ -79,6 +79,8 @@ "network_service.h", "network_service_memory_cache.cc", "network_service_memory_cache.h", + "network_service_memory_cache_url_loader.cc", + "network_service_memory_cache_url_loader.h", "network_service_memory_cache_writer.cc", "network_service_memory_cache_writer.h", "network_service_network_delegate.cc",
diff --git a/services/network/chunked_data_pipe_upload_data_stream.cc b/services/network/chunked_data_pipe_upload_data_stream.cc index 10802b9..5caf1de 100644 --- a/services/network/chunked_data_pipe_upload_data_stream.cc +++ b/services/network/chunked_data_pipe_upload_data_stream.cc
@@ -15,8 +15,10 @@ ChunkedDataPipeUploadDataStream::ChunkedDataPipeUploadDataStream( scoped_refptr<ResourceRequestBody> resource_request_body, - mojo::PendingRemote<mojom::ChunkedDataPipeGetter> chunked_data_pipe_getter) - : net::UploadDataStream(true /* is_chunked */, + mojo::PendingRemote<mojom::ChunkedDataPipeGetter> chunked_data_pipe_getter, + bool has_null_source) + : net::UploadDataStream(/*is_chunked=*/true, + /*has_null_source=*/has_null_source, resource_request_body->identifier()), resource_request_body_(std::move(resource_request_body)), chunked_data_pipe_getter_(std::move(chunked_data_pipe_getter)), @@ -201,6 +203,7 @@ // Clear |buf_| as well, so it's only non-null while there's a pending read. buf_ = nullptr; buf_len_ = 0; + chunked_data_pipe_getter_.reset(); OnReadCompleted(status_);
diff --git a/services/network/chunked_data_pipe_upload_data_stream.h b/services/network/chunked_data_pipe_upload_data_stream.h index 1c0fda4..b02a6271 100644 --- a/services/network/chunked_data_pipe_upload_data_stream.h +++ b/services/network/chunked_data_pipe_upload_data_stream.h
@@ -39,7 +39,8 @@ ChunkedDataPipeUploadDataStream( scoped_refptr<ResourceRequestBody> resource_request_body, mojo::PendingRemote<mojom::ChunkedDataPipeGetter> - chunked_data_pipe_getter); + chunked_data_pipe_getter, + bool has_null_source = false); ChunkedDataPipeUploadDataStream(const ChunkedDataPipeUploadDataStream&) = delete;
diff --git a/services/network/cors/cors_url_loader.cc b/services/network/cors/cors_url_loader.cc index c0ca0f5d..26e34d9a 100644 --- a/services/network/cors/cors_url_loader.cc +++ b/services/network/cors/cors_url_loader.cc
@@ -18,6 +18,7 @@ #include "services/network/cors/cors_url_loader_factory.h" #include "services/network/cors/cors_util.h" #include "services/network/cors/preflight_controller.h" +#include "services/network/network_service_memory_cache.h" #include "services/network/public/cpp/cors/cors.h" #include "services/network/public/cpp/cors/origin_access_list.h" #include "services/network/public/cpp/features.h" @@ -256,7 +257,8 @@ NonWildcardRequestHeadersSupport non_wildcard_request_headers_support, const net::IsolationInfo& isolation_info, mojo::PendingRemote<mojom::DevToolsObserver> devtools_observer, - const mojom::ClientSecurityState* factory_client_security_state) + const mojom::ClientSecurityState* factory_client_security_state, + NetworkServiceMemoryCache* memory_cache) : receiver_(this, std::move(loader_receiver)), process_id_(process_id), request_id_(request_id), @@ -276,6 +278,7 @@ non_wildcard_request_headers_support), isolation_info_(isolation_info), factory_client_security_state_(factory_client_security_state), + memory_cache_(memory_cache), devtools_observer_(std::move(devtools_observer)), // CORS preflight related events are logged in a series of URL_REQUEST // logs. @@ -838,8 +841,21 @@ // Binding |this| as an unretained pointer is safe because // |network_client_receiver_| shares this object's lifetime. network_loader_.reset(); - if (sync_network_loader_factory_ && - base::FeatureList::IsEnabled(features::kURLLoaderSyncClient)) { + + // Check whether a fresh entry exists in the in-memory cache. + absl::optional<std::string> cache_key; + if (memory_cache_) { + cache_key = memory_cache_->CanServe( + request_, isolation_info_.network_isolation_key()); + } + + if (cache_key.has_value()) { + memory_cache_->CreateLoaderAndStart( + network_loader_.BindNewPipeAndPassReceiver(), request_id_, options_, + *cache_key, request_, + network_client_receiver_.BindNewPipeAndPassRemote()); + } else if (sync_network_loader_factory_ && + base::FeatureList::IsEnabled(features::kURLLoaderSyncClient)) { sync_network_loader_factory_->CreateLoaderAndStartWithSyncClient( network_loader_.BindNewPipeAndPassReceiver(), request_id_, options_, request_, network_client_receiver_.BindNewPipeAndPassRemote(),
diff --git a/services/network/cors/cors_url_loader.h b/services/network/cors/cors_url_loader.h index 3347f50..8d7be465 100644 --- a/services/network/cors/cors_url_loader.h +++ b/services/network/cors/cors_url_loader.h
@@ -28,6 +28,7 @@ namespace network { class URLLoaderFactory; +class NetworkServiceMemoryCache; namespace cors { @@ -65,7 +66,8 @@ NonWildcardRequestHeadersSupport non_wildcard_request_headers_support, const net::IsolationInfo& isolation_info, mojo::PendingRemote<mojom::DevToolsObserver> devtools_observer, - const mojom::ClientSecurityState* factory_client_security_state); + const mojom::ClientSecurityState* factory_client_security_state, + NetworkServiceMemoryCache* memory_cache); CorsURLLoader(const CorsURLLoader&) = delete; CorsURLLoader& operator=(const CorsURLLoader&) = delete; @@ -269,6 +271,9 @@ raw_ptr<const mojom::ClientSecurityState> factory_client_security_state_ = nullptr; + // Outlives `this`, or nullptr when the in-memory cache is disabled. + const raw_ptr<NetworkServiceMemoryCache> memory_cache_; + bool has_authorization_covered_by_wildcard_ = false; // Whether the current preflight request is 1) solely sent for PNA, not for
diff --git a/services/network/cors/cors_url_loader_factory.cc b/services/network/cors/cors_url_loader_factory.cc index 572c092b..8d40fc5 100644 --- a/services/network/cors/cors_url_loader_factory.cc +++ b/services/network/cors/cors_url_loader_factory.cc
@@ -303,7 +303,8 @@ context_->cors_exempt_header_list(), GetAllowAnyCorsExemptHeaderForBrowser(), context_->cors_non_wildcard_request_headers_support(), isolation_info_, - std::move(devtools_observer), client_security_state_.get()); + std::move(devtools_observer), client_security_state_.get(), + context_->GetMemoryCache()); auto* raw_loader = loader.get(); OnCorsURLLoaderCreated(std::move(loader)); raw_loader->Start();
diff --git a/services/network/network_service_memory_cache.cc b/services/network/network_service_memory_cache.cc index 8fafa850..90b46ecc 100644 --- a/services/network/network_service_memory_cache.cc +++ b/services/network/network_service_memory_cache.cc
@@ -15,6 +15,7 @@ #include "net/http/http_util.h" #include "net/url_request/url_request.h" #include "services/network/network_context.h" +#include "services/network/network_service_memory_cache_url_loader.h" #include "services/network/network_service_memory_cache_writer.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request.h" @@ -171,7 +172,8 @@ // TODO(https://crbug.com/1339708): Support automatically assigned network // isolation key for request from browsers. See comments in // CorsURLLoaderFactory::CorsURLLoaderFactory. - DCHECK(network_isolation_key.IsFullyPopulated()); + if (!network_isolation_key.IsFullyPopulated()) + return absl::nullopt; const GURL& url = resource_request.url; if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS()) @@ -207,6 +209,43 @@ return std::move(cache_key); } +void NetworkServiceMemoryCache::CreateLoaderAndStart( + mojo::PendingReceiver<mojom::URLLoader> receiver, + int32_t request_id, + uint32_t options, + const std::string& cache_key, + const ResourceRequest& resource_request, + mojo::PendingRemote<mojom::URLLoaderClient> client) { + auto it = entries_.Get(cache_key); + CHECK(it != entries_.end()); + + auto loader = std::make_unique<NetworkServiceMemoryCacheURLLoader>( + this, GetNextTraceId(), resource_request.url, std::move(receiver), + std::move(client), it->second->content); + NetworkServiceMemoryCacheURLLoader* raw_loader = loader.get(); + url_loaders_.insert(std::move(loader)); + + raw_loader->Start(resource_request, it->second->response_head.Clone()); +} + +uint32_t NetworkServiceMemoryCache::GetDataPipeCapacity(size_t content_length) { + if (data_pipe_capacity_for_testing_.has_value()) + return *data_pipe_capacity_for_testing_; + + uint32_t default_capacity = features::GetDataPipeDefaultAllocationSize(); + if (content_length > default_capacity) + return default_capacity; + return static_cast<size_t>(content_length); +} + +void NetworkServiceMemoryCache::OnLoaderCompleted( + NetworkServiceMemoryCacheURLLoader* loader) { + DCHECK(loader); + auto it = url_loaders_.find(loader); + DCHECK(it != url_loaders_.end()); + url_loaders_.erase(it); +} + void NetworkServiceMemoryCache::SetCurrentTimeForTesting( base::Time current_time) { current_time_for_testing_ = current_time; @@ -220,6 +259,11 @@ return it->second->response_head.Clone(); } +void NetworkServiceMemoryCache::SetDataPipeCapacityForTesting( + uint32_t capacity) { + data_pipe_capacity_for_testing_ = capacity; +} + base::Time NetworkServiceMemoryCache::GetCurrentTime() { if (!current_time_for_testing_.is_null()) return current_time_for_testing_;
diff --git a/services/network/network_service_memory_cache.h b/services/network/network_service_memory_cache.h index 8f6856b..d5fb185 100644 --- a/services/network/network_service_memory_cache.h +++ b/services/network/network_service_memory_cache.h
@@ -11,9 +11,13 @@ #include "base/component_export.h" #include "base/containers/lru_cache.h" +#include "base/containers/unique_ptr_adapters.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_completion_status.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -25,6 +29,7 @@ namespace network { +class NetworkServiceMemoryCacheURLLoader; class NetworkServiceMemoryCacheWriter; struct ResourceRequest; @@ -63,11 +68,30 @@ const ResourceRequest& resource_request, const net::NetworkIsolationKey& network_isolation_key); + // Creates and starts a custom URLLoader that serves a response from the + // in-memory cache, instead of creating a network::URLLoader. Must be called + // immediately after CanServe(). + void CreateLoaderAndStart(mojo::PendingReceiver<mojom::URLLoader> receiver, + int32_t request_id, + uint32_t options, + const std::string& cache_key, + const ResourceRequest& resource_request, + mojo::PendingRemote<mojom::URLLoaderClient> client); + + // Returns a suitable capacity for a data pipe that is used to serve a + // response from `this`. + uint32_t GetDataPipeCapacity(size_t content_length); + + // Called when a custom URLLoader is completed. + void OnLoaderCompleted(NetworkServiceMemoryCacheURLLoader* loader); + void SetCurrentTimeForTesting(base::Time current_time); mojom::URLResponseHeadPtr GetResponseHeadForTesting( const std::string& cache_key); + void SetDataPipeCapacityForTesting(uint32_t capacity); + private: struct Entry; using CacheMap = base::LRUCache<std::string, std::unique_ptr<Entry>>; @@ -88,8 +112,14 @@ const size_t max_total_bytes_; size_t total_bytes_ = 0; + std::set<std::unique_ptr<NetworkServiceMemoryCacheURLLoader>, + base::UniquePtrComparator> + url_loaders_; + base::Time current_time_for_testing_; + absl::optional<uint32_t> data_pipe_capacity_for_testing_; + base::WeakPtrFactory<NetworkServiceMemoryCache> weak_ptr_factory_{this}; };
diff --git a/services/network/network_service_memory_cache_unittest.cc b/services/network/network_service_memory_cache_unittest.cc index a05b4b4d..7cf27a1 100644 --- a/services/network/network_service_memory_cache_unittest.cc +++ b/services/network/network_service_memory_cache_unittest.cc
@@ -11,6 +11,7 @@ #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "mojo/public/cpp/bindings/remote.h" +#include "mojo/public/cpp/system/data_pipe_utils.h" #include "net/base/features.h" #include "net/base/schemeful_site.h" #include "net/base/url_util.h" @@ -63,7 +64,8 @@ } // An EmbeddedTestServer request handler that returns a cacheable response of -// which body size and max-age are specified by the query string. +// which body size and max-age are specified by the query string. The content +// body consists of 'a'. std::unique_ptr<net::test_server::HttpResponse> CacheableResponseHandler( const net::test_server::HttpRequest& request) { if (request.GetURL().path_piece() != "/cacheable") @@ -157,6 +159,7 @@ url::Origin origin = url::Origin::Create(url); request.url = url; request.request_initiator = origin; + request.enable_load_timing = true; return request; } @@ -471,4 +474,148 @@ ASSERT_FALSE(CanServeFromMemoryCache(request)); } +TEST_F(NetworkServiceMemoryCacheTest, ServeFromCache_Basic) { + constexpr int kBodySize = 371; + const std::string kExpectedBody(kBodySize, 'a'); + + ResourceRequest request = + CreateRequest(base::StringPrintf("/cacheable?body-size=%d", kBodySize)); + StoreResponseToMemoryCache(request); + + const base::TimeTicks before_start = base::TimeTicks::Now(); + + LoaderPair pair = CreateLoaderAndStart(request); + pair.client->RunUntilComplete(); + ASSERT_EQ(pair.client->completion_status().error_code, net::OK); + + const mojom::URLResponseHeadPtr& response = pair.client->response_head(); + ASSERT_FALSE(response->network_accessed); + ASSERT_FALSE(response->is_validated); + ASSERT_TRUE(response->was_fetched_via_cache); + ASSERT_LT(before_start, response->request_start); + ASSERT_LT(before_start, response->response_start); + + const net::LoadTimingInfo& load_timing = response->load_timing; + ASSERT_LT(before_start, load_timing.request_start); + ASSERT_LT(before_start, load_timing.send_start); + ASSERT_LT(before_start, load_timing.send_end); + ASSERT_LT(before_start, load_timing.receive_headers_start); + ASSERT_LT(before_start, load_timing.receive_headers_end); + + std::string received_body; + ASSERT_TRUE(mojo::BlockingCopyToString(pair.client->response_body_release(), + &received_body)); + ASSERT_EQ(kExpectedBody, received_body); +} + +TEST_F(NetworkServiceMemoryCacheTest, ServeFromCache_DisableLoadTiming) { + ResourceRequest request = CreateRequest("/cacheable"); + StoreResponseToMemoryCache(request); + + const base::TimeTicks before_start = base::TimeTicks::Now(); + + request.enable_load_timing = false; + LoaderPair pair = CreateLoaderAndStart(request); + pair.client->RunUntilComplete(); + ASSERT_EQ(pair.client->completion_status().error_code, net::OK); + + const mojom::URLResponseHeadPtr& response = pair.client->response_head(); + ASSERT_FALSE(response->network_accessed); + ASSERT_FALSE(response->is_validated); + ASSERT_TRUE(response->was_fetched_via_cache); + ASSERT_LT(before_start, response->request_start); + ASSERT_LT(before_start, response->response_start); + + const net::LoadTimingInfo& load_timing = response->load_timing; + ASSERT_TRUE(load_timing.request_start.is_null()); + ASSERT_TRUE(load_timing.send_start.is_null()); + ASSERT_TRUE(load_timing.send_end.is_null()); + ASSERT_TRUE(load_timing.receive_headers_start.is_null()); + ASSERT_TRUE(load_timing.receive_headers_end.is_null()); +} + +TEST_F(NetworkServiceMemoryCacheTest, ServeFromCache_LargeBody) { + constexpr uint32_t kReadDataSize = 512; + // Arbitrary response body size larger than `kReadDataSize`. + constexpr int kBodySize = 4 * 1024 + 659; + + ResourceRequest request = + CreateRequest(base::StringPrintf("/cacheable?body-size=%d", kBodySize)); + StoreResponseToMemoryCache(request); + + LoaderPair pair = CreateLoaderAndStart(request); + pair.client->RunUntilResponseReceived(); + + mojo::ScopedDataPipeConsumerHandle consumer_handle = + pair.client->response_body_release(); + std::string received_body; + while (true) { + char buf[kReadDataSize]; + uint32_t num_bytes = kReadDataSize; + MojoResult result = + consumer_handle->ReadData(buf, &num_bytes, MOJO_READ_DATA_FLAG_NONE); + + if (result == MOJO_RESULT_SHOULD_WAIT) { + base::RunLoop run_loop; + base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, + run_loop.QuitClosure()); + run_loop.Run(); + continue; + } + + if (result == MOJO_RESULT_FAILED_PRECONDITION) + break; + + ASSERT_EQ(result, MOJO_RESULT_OK); + received_body.append(buf, num_bytes); + } + + pair.client->RunUntilComplete(); + ASSERT_EQ(pair.client->completion_status().error_code, net::OK); + + const std::string kExpectedBody(kBodySize, 'a'); + ASSERT_EQ(kExpectedBody, received_body); +} + +TEST_F(NetworkServiceMemoryCacheTest, + ServeFromCache_DataPipeDisconnectWhileReading) { + constexpr int kBodySize = 512; + constexpr int kReadDataSize = kBodySize / 2; + ResourceRequest request = + CreateRequest(base::StringPrintf("/cacheable?body-size=%d", kBodySize)); + StoreResponseToMemoryCache(request); + + // Set a small data pipe capacity so that writing data to a data pipe doesn't + // complete at once. + memory_cache().SetDataPipeCapacityForTesting(kReadDataSize); + + LoaderPair pair = CreateLoaderAndStart(request); + pair.client->RunUntilResponseReceived(); + + mojo::ScopedDataPipeConsumerHandle consumer_handle = + pair.client->response_body_release(); + + // Read the half of the response body. + int num_read = 0; + while (num_read < kReadDataSize) { + char buf[kReadDataSize]; + uint32_t num_bytes = kReadDataSize; + MojoResult result = + consumer_handle->ReadData(buf, &num_bytes, MOJO_READ_DATA_FLAG_NONE); + if (result == MOJO_RESULT_SHOULD_WAIT) { + base::RunLoop run_loop; + base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, + run_loop.QuitClosure()); + run_loop.Run(); + continue; + } + ASSERT_EQ(result, MOJO_RESULT_OK); + num_read += num_bytes; + } + + consumer_handle.reset(); + pair.client->RunUntilComplete(); + ASSERT_EQ(pair.client->completion_status().error_code, net::ERR_FAILED); +} + } // namespace network
diff --git a/services/network/network_service_memory_cache_url_loader.cc b/services/network/network_service_memory_cache_url_loader.cc new file mode 100644 index 0000000..e9f6fb20 --- /dev/null +++ b/services/network/network_service_memory_cache_url_loader.cc
@@ -0,0 +1,206 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/network/network_service_memory_cache_url_loader.h" + +#include "base/trace_event/common/trace_event_common.h" +#include "base/trace_event/trace_event.h" +#include "services/network/network_service_memory_cache.h" +#include "services/network/public/cpp/resource_request.h" + +namespace network { + +NetworkServiceMemoryCacheURLLoader::NetworkServiceMemoryCacheURLLoader( + NetworkServiceMemoryCache* memory_cache, + uint64_t trace_id, + const GURL& url, + mojo::PendingReceiver<mojom::URLLoader> receiver, + mojo::PendingRemote<mojom::URLLoaderClient> client, + scoped_refptr<base::RefCountedBytes> content) + : memory_cache_(memory_cache), + trace_id_(trace_id), + receiver_(this, std::move(receiver)), + client_(std::move(client)), + content_(std::move(content)) { + DCHECK(memory_cache_); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "loading", "NetworkServiceMemoryCacheURLLoader", + TRACE_ID_LOCAL(trace_id_), "url", url.spec()); + + client_.set_disconnect_handler( + base::BindOnce(&NetworkServiceMemoryCacheURLLoader::OnClientDisconnected, + base::Unretained(this))); +} + +NetworkServiceMemoryCacheURLLoader::~NetworkServiceMemoryCacheURLLoader() { + TRACE_EVENT_NESTABLE_ASYNC_END0("loading", + "NetworkServiceMemoryCacheURLLoader", + TRACE_ID_LOCAL(trace_id_)); +} + +void NetworkServiceMemoryCacheURLLoader::Start( + const ResourceRequest& resource_request, + mojom::URLResponseHeadPtr response_head) { + UpdateResponseHead(resource_request, response_head); + + // Create a data pipe. + MojoCreateDataPipeOptions options; + options.struct_size = sizeof(MojoCreateDataPipeOptions); + options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; + options.element_num_bytes = 1; + options.capacity_num_bytes = + memory_cache_->GetDataPipeCapacity(content_->size()); + mojo::ScopedDataPipeConsumerHandle consumer_handle; + MojoResult result = + mojo::CreateDataPipe(&options, producer_handle_, consumer_handle); + if (result != MOJO_RESULT_OK) { + Finish(net::ERR_FAILED); + return; + } + + // Start sending the response. + client_->OnReceiveResponse(std::move(response_head), + std::move(consumer_handle)); + + // Set up data pipe producer. + producer_handle_watcher_ = std::make_unique<mojo::SimpleWatcher>( + FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, + base::SequencedTaskRunnerHandle::Get()); + producer_handle_watcher_->Watch( + producer_handle_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, + MOJO_WATCH_CONDITION_SATISFIED, + base::BindRepeating( + &NetworkServiceMemoryCacheURLLoader::OnProducerHandleReady, + weak_ptr_factory_.GetWeakPtr())); + + WriteMore(); +} + +void NetworkServiceMemoryCacheURLLoader::UpdateResponseHead( + const ResourceRequest& resource_request, + mojom::URLResponseHeadPtr& response_head) { + response_head->network_accessed = false; + response_head->is_validated = false; + response_head->was_fetched_via_cache = true; + + const base::Time now_time = base::Time::Now(); + const base::TimeTicks now_ticks = base::TimeTicks::Now(); + + response_head->request_start = now_ticks; + response_head->response_start = now_ticks; + + net::LoadTimingInfo load_timing; + if (resource_request.enable_load_timing) { + load_timing.request_start_time = now_time; + load_timing.request_start = now_ticks; + + load_timing.send_start = now_ticks; + load_timing.send_end = now_ticks; + load_timing.receive_headers_start = now_ticks; + load_timing.receive_headers_end = now_ticks; + } + response_head->load_timing = load_timing; +} + +void NetworkServiceMemoryCacheURLLoader::WriteMore() { + size_t total_write_size = 0; + bool write_completed = false; + while (true) { + DCHECK_GE(content_->size(), write_position_); + DCHECK_GE(std::numeric_limits<uint32_t>::max(), + content_->size() - write_position_); + uint32_t write_size = + static_cast<uint32_t>(content_->size() - write_position_); + if (write_size == 0) { + write_completed = true; + break; + } + + MojoResult result = + producer_handle_->WriteData(content_->data().data() + write_position_, + &write_size, MOJO_WRITE_DATA_FLAG_NONE); + if (result == MOJO_RESULT_SHOULD_WAIT) { + producer_handle_watcher_->ArmOrNotify(); + break; + } + + if (result != MOJO_RESULT_OK) { + Finish(net::ERR_FAILED); + return; + } + + write_position_ += write_size; + total_write_size += write_size; + } + + TRACE_EVENT_NESTABLE_ASYNC_INSTANT2( + "loading", "NetworkServiceMemoryCacheURLLoader::WriteMore", + TRACE_ID_LOCAL(trace_id_), "write_position", write_position_, + "total_write_bytes", total_write_size); + + if (write_completed) { + Finish(net::OK); + } +} + +void NetworkServiceMemoryCacheURLLoader::OnProducerHandleReady( + MojoResult result, + const mojo::HandleSignalsState& state) { + if (result == MOJO_RESULT_OK) { + WriteMore(); + } else { + Finish(net::ERR_FAILED); + } +} + +void NetworkServiceMemoryCacheURLLoader::Finish(int error_code) { + TRACE_EVENT_NESTABLE_ASYNC_INSTANT0( + "loading", "NetworkServiceMemoryCacheURLLoader::Finish", + TRACE_ID_LOCAL(trace_id_)); + + producer_handle_.reset(); + producer_handle_watcher_.reset(); + + if (error_code == net::OK) { + DCHECK(client_.is_connected()); + + URLLoaderCompletionStatus status; + status.error_code = net::OK; + status.exists_in_cache = true; + status.completion_time = base::TimeTicks::Now(); + status.encoded_body_length = content_->size(); + status.decoded_body_length = content_->size(); + + client_->OnComplete(status); + } else if (client_.is_connected()) { + URLLoaderCompletionStatus status; + status.error_code = error_code; + client_->OnComplete(status); + } + + memory_cache_->OnLoaderCompleted(this); + // `memory_cache_` deleted `this`. +} + +void NetworkServiceMemoryCacheURLLoader::OnClientDisconnected() { + Finish(net::ERR_FAILED); +} + +void NetworkServiceMemoryCacheURLLoader::FollowRedirect( + const std::vector<std::string>& removed_headers, + const net::HttpRequestHeaders& modified_headers, + const net::HttpRequestHeaders& modified_cors_exempt_headers, + const absl::optional<GURL>& new_url) { + NOTREACHED(); +} + +void NetworkServiceMemoryCacheURLLoader::SetPriority( + net::RequestPriority priority, + int32_t intra_priority_value) {} + +void NetworkServiceMemoryCacheURLLoader::PauseReadingBodyFromNet() {} + +void NetworkServiceMemoryCacheURLLoader::ResumeReadingBodyFromNet() {} + +} // namespace network
diff --git a/services/network/network_service_memory_cache_url_loader.h b/services/network/network_service_memory_cache_url_loader.h new file mode 100644 index 0000000..5749941 --- /dev/null +++ b/services/network/network_service_memory_cache_url_loader.h
@@ -0,0 +1,101 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_URL_LOADER_H_ +#define SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_URL_LOADER_H_ + +#include <memory> +#include <vector> + +#include "base/memory/raw_ptr.h" +#include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "mojo/public/cpp/system/data_pipe.h" +#include "mojo/public/cpp/system/simple_watcher.h" +#include "services/network/public/mojom/url_loader.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "url/gurl.h" + +namespace network { + +class NetworkServiceMemoryCache; +struct ResourceRequest; + +// A URLLoader that serves a response from the in-memory cache. Must be used +// only after CORS/CORP checks succeeded. +class NetworkServiceMemoryCacheURLLoader : public mojom::URLLoader { + public: + NetworkServiceMemoryCacheURLLoader( + NetworkServiceMemoryCache* memory_cache, + uint64_t trace_id, + const GURL& url, + mojo::PendingReceiver<mojom::URLLoader> receiver, + mojo::PendingRemote<mojom::URLLoaderClient> client, + scoped_refptr<base::RefCountedBytes> content); + + ~NetworkServiceMemoryCacheURLLoader() override; + + // Starts sending the response. `response_head` is a cached response stored + // in the in-memory cache. + void Start(const ResourceRequest& resource_request, + mojom::URLResponseHeadPtr response_head); + + private: + // Adjusts load timings and cache related fields in `response_head`. + void UpdateResponseHead(const ResourceRequest& resource_request, + mojom::URLResponseHeadPtr& response_head); + + // Sends response body to the client via a mojo data pipe. + void WriteMore(); + + // Called when the client can read response body. + void OnProducerHandleReady(MojoResult result, + const mojo::HandleSignalsState& state); + + // Called when this loader finished. `this` becomes invalid after Finish() + // because `memory_cache_` deletes `this` at the end. + void Finish(int error_code); + + void OnClientDisconnected(); + + // mojom::URLLoader implementations: + void FollowRedirect( + const std::vector<std::string>& removed_headers, + const net::HttpRequestHeaders& modified_headers, + const net::HttpRequestHeaders& modified_cors_exempt_headers, + const absl::optional<GURL>& new_url) override; + void SetPriority(net::RequestPriority priority, + int32_t intra_priority_value) override; + void PauseReadingBodyFromNet() override; + void ResumeReadingBodyFromNet() override; + + // `memory_cache_` owns `this`. + const raw_ptr<NetworkServiceMemoryCache> memory_cache_; + + // For tracing. + const uint64_t trace_id_; + + mojo::Receiver<mojom::URLLoader> receiver_; + mojo::Remote<mojom::URLLoaderClient> client_; + + // The response body to be served. + scoped_refptr<base::RefCountedBytes> content_; + + mojo::ScopedDataPipeProducerHandle producer_handle_; + std::unique_ptr<mojo::SimpleWatcher> producer_handle_watcher_; + size_t write_position_ = 0; + + base::WeakPtrFactory<NetworkServiceMemoryCacheURLLoader> weak_ptr_factory_{ + this}; +}; + +} // namespace network + +#endif // SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_URL_LOADER_H_
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index 54f5037..04ed3a3 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -167,9 +167,10 @@ network::mojom::DataElementDataView::Tag::kChunkedDataPipe) { auto& element = body->elements_mutable()->at(0).As<DataElementChunkedDataPipe>(); + const bool has_null_source = element.read_only_once().value(); auto upload_data_stream = std::make_unique<ChunkedDataPipeUploadDataStream>( - body, element.ReleaseChunkedDataPipeGetter()); + body, element.ReleaseChunkedDataPipeGetter(), has_null_source); if (element.read_only_once()) { upload_data_stream->EnableCache(); }
diff --git a/services/network/url_loader_factory.cc b/services/network/url_loader_factory.cc index 286cd5df..ebc3a95 100644 --- a/services/network/url_loader_factory.cc +++ b/services/network/url_loader_factory.cc
@@ -323,17 +323,12 @@ resource_request.trusted_params->accept_ch_frame_observer)); } - // Check for third party cookies being disabled by testing a non-existant - // third-party cookie. This will also be false if all cookies are disabled. - const auto dummy_cookie = net::CanonicalCookie::Create( - GURL("https://does-not-exist./"), "a=n", base::Time::Now(), absl::nullopt, - absl::nullopt); - + // Check for third party cookies being disabled. This will also be false if + // all cookies are disabled. const bool third_party_cookies_enabled = - context_->cookie_manager()->cookie_settings().IsCookieAccessible( - *dummy_cookie, GURL("https://also-does-not-exist./"), - net::SiteForCookies(net::SchemefulSite(url::Origin())), - url::Origin()); + !context_->cookie_manager() + ->cookie_settings() + .are_third_party_cookies_blocked(); auto loader = std::make_unique<URLLoader>( *this,
diff --git a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/BarcodeDetectionImplTest.java b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/BarcodeDetectionImplTest.java index dadafee..75918f9e 100644 --- a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/BarcodeDetectionImplTest.java +++ b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/BarcodeDetectionImplTest.java
@@ -4,11 +4,10 @@ package org.chromium.shape_detection; -import android.os.Build; - import androidx.test.filters.SmallTest; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,7 +18,7 @@ import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.Batch; -import org.chromium.base.test.util.DisableIf; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.shape_detection.mojom.BarcodeDetection; import org.chromium.shape_detection.mojom.BarcodeDetectionProvider; @@ -38,8 +37,10 @@ @RunWith(ParameterizedRunner.class) @Batch(Batch.UNIT_TESTS) @UseRunnerDelegate(BaseJUnit4RunnerDelegate.class) -@DisableIf.Build(sdk_is_greater_than = Build.VERSION_CODES.N_MR1, message = "crbug.com/1153716") +@DisabledTest(message = "https://crbug.com/1153716") public class BarcodeDetectionImplTest { + private static final float BOUNDS_TOLERANCE = 4.0f; + private static final org.chromium.skia.mojom.BitmapN32 QR_CODE_BITMAP = TestUtils.mojoBitmapFromFile("qr_code.png"); @@ -103,22 +104,25 @@ return toReturn; } + @Before + public void setUp() { + TestUtils.waitForVisionLibraryReady(); + } + @Test @SmallTest @Feature({"ShapeDetection"}) public void testEnumerateSupportedFormats() { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } int[] results = enumerateSupportedFormats(); Assert.assertArrayEquals(SUPPORTED_FORMATS, results); } public static class BarcodeExampleParams implements ParameterProvider { private static List<ParameterSet> sBarcodeExampleParams = Arrays.asList( - new ParameterSet() - .value("aztec.png", BarcodeFormat.AZTEC, "Chromium", 11, 11, 61, 61) - .name("AZTEC"), + // TODO(https://crbug.com/1153716): AZTEC format is failing. + // new ParameterSet() + // .value("aztec.png", BarcodeFormat.AZTEC, "Chromium", 11, 11, 61, 61) + // .name("AZTEC"), new ParameterSet() .value("codabar.png", BarcodeFormat.CODABAR, "A6.2831853B", 24, 24, 448, 95) .name("CODABAR"), @@ -170,17 +174,14 @@ @Feature({"ShapeDetection"}) public void testDetectBarcodeWithHint(String inputFile, int format, String value, float x, float y, float width, float height) { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } org.chromium.skia.mojom.BitmapN32 bitmap = TestUtils.mojoBitmapFromFile(inputFile); BarcodeDetectionResult[] results = detectWithHint(bitmap, format); Assert.assertEquals(1, results.length); Assert.assertEquals(value, results[0].rawValue); - Assert.assertEquals(x, results[0].boundingBox.x, 0.0); - Assert.assertEquals(y, results[0].boundingBox.y, 0.0); - Assert.assertEquals(width, results[0].boundingBox.width, 0.0); - Assert.assertEquals(height, results[0].boundingBox.height, 0.0); + Assert.assertEquals(x, results[0].boundingBox.x, BOUNDS_TOLERANCE); + Assert.assertEquals(y, results[0].boundingBox.y, BOUNDS_TOLERANCE); + Assert.assertEquals(width, results[0].boundingBox.width, BOUNDS_TOLERANCE); + Assert.assertEquals(height, results[0].boundingBox.height, BOUNDS_TOLERANCE); Assert.assertEquals(format, results[0].format); } @@ -190,17 +191,14 @@ @Feature({"ShapeDetection"}) public void testDetectBarcodeWithoutHint(String inputFile, int format, String value, float x, float y, float width, float height) { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } org.chromium.skia.mojom.BitmapN32 bitmap = TestUtils.mojoBitmapFromFile(inputFile); BarcodeDetectionResult[] results = detect(bitmap); Assert.assertEquals(1, results.length); Assert.assertEquals(value, results[0].rawValue); - Assert.assertEquals(x, results[0].boundingBox.x, 0.0); - Assert.assertEquals(y, results[0].boundingBox.y, 0.0); - Assert.assertEquals(width, results[0].boundingBox.width, 0.0); - Assert.assertEquals(height, results[0].boundingBox.height, 0.0); + Assert.assertEquals(x, results[0].boundingBox.x, BOUNDS_TOLERANCE); + Assert.assertEquals(y, results[0].boundingBox.y, BOUNDS_TOLERANCE); + Assert.assertEquals(width, results[0].boundingBox.width, BOUNDS_TOLERANCE); + Assert.assertEquals(height, results[0].boundingBox.height, BOUNDS_TOLERANCE); Assert.assertEquals(format, results[0].format); } @@ -208,9 +206,6 @@ @SmallTest @Feature({"ShapeDetection"}) public void testTryDetectQrCodeWithAztecHint() { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } BarcodeDetectionResult[] results = detectWithHint(QR_CODE_BITMAP, BarcodeFormat.AZTEC); Assert.assertEquals(0, results.length); }
diff --git a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java index 924858b9..fe81def 100644 --- a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java +++ b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java
@@ -4,26 +4,31 @@ package org.chromium.shape_detection; +import static org.hamcrest.Matchers.greaterThan; + import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; +import android.graphics.PointF; import android.graphics.RectF; -import android.os.Build; import androidx.test.filters.SmallTest; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Batch; -import org.chromium.base.test.util.DisableIf; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.shape_detection.mojom.FaceDetection; import org.chromium.shape_detection.mojom.FaceDetectionResult; import org.chromium.shape_detection.mojom.FaceDetectorOptions; +import java.util.Arrays; +import java.util.Comparator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; @@ -32,7 +37,7 @@ */ @RunWith(BaseJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) -@DisableIf.Build(sdk_is_greater_than = Build.VERSION_CODES.N_MR1, message = "crbug.com/1153716") +@DisabledTest(message = "https://crbug.com/1153716") public class FaceDetectionImplTest { private static final org.chromium.skia.mojom.BitmapN32 MONA_LISA_BITMAP = TestUtils.mojoBitmapFromFile("mona_lisa.jpg"); @@ -41,8 +46,10 @@ // Different versions of Android have different implementations of FaceDetector.findFaces(), so // we have to use a large error threshold. private static final double BOUNDING_BOX_POSITION_ERROR = 10.0; - private static final double BOUNDING_BOX_SIZE_ERROR = 5.0; + private static final double BOUNDING_BOX_SIZE_ERROR = 25.0; private static final float ACCURATE_MODE_SIZE = 2.0f; + private static final PointF[] POSE_FACES_LOCATIONS = {new PointF(94.0f, 118.0f), + new PointF(240.0f, 118.0f), new PointF(410.0f, 118.0f), new PointF(597.0f, 118.0f)}; private static enum DetectionProviderType { ANDROID, GMS_CORE } public FaceDetectionImplTest() {} @@ -90,6 +97,11 @@ Assert.assertEquals(20.0, results[0].boundingBox.y, BOUNDING_BOX_POSITION_ERROR); } + @Before + public void setUp() { + TestUtils.waitForVisionLibraryReady(); + } + @Test @SmallTest @Feature({"ShapeDetection"}) @@ -101,9 +113,7 @@ @SmallTest @Feature({"ShapeDetection"}) public void testDetectValidImageWithGmsCore() { - if (TestUtils.IS_GMS_CORE_SUPPORTED) { - detectSucceedsOnValidImage(DetectionProviderType.GMS_CORE); - } + detectSucceedsOnValidImage(DetectionProviderType.GMS_CORE); } @Test @@ -130,29 +140,24 @@ @SmallTest @Feature({"ShapeDetection"}) public void testDetectFacesInProfileWithGmsCore() { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } + final int numFaces = 4; + + // The 4 faces are in a row. + Comparator<FaceDetectionResult> sorter = (f1, f2) -> { + return Float.compare(f1.boundingBox.x, f2.boundingBox.x); + }; + FaceDetectionResult[] fastModeResults = detect(FACE_POSE_BITMAP, true, DetectionProviderType.GMS_CORE); - Assert.assertEquals(4, fastModeResults.length); + Assert.assertEquals(numFaces, fastModeResults.length); + Arrays.sort(fastModeResults, sorter); - FaceDetectionResult[] unorderedResults = - detect(FACE_POSE_BITMAP, false, DetectionProviderType.GMS_CORE); FaceDetectionResult[] accurateModeResults = - new FaceDetectionResult[unorderedResults.length]; - for (int i = 0; i < accurateModeResults.length; i++) { - accurateModeResults[i] = new FaceDetectionResult(); - } - Assert.assertEquals(4, accurateModeResults.length); - // Order face results align with fast mode's order which is different from accurate mode. - accurateModeResults[0].boundingBox = unorderedResults[1].boundingBox; - accurateModeResults[1].boundingBox = unorderedResults[2].boundingBox; - accurateModeResults[2].boundingBox = unorderedResults[0].boundingBox; - accurateModeResults[3].boundingBox = unorderedResults[3].boundingBox; + detect(FACE_POSE_BITMAP, false, DetectionProviderType.GMS_CORE); + Assert.assertEquals(numFaces, accurateModeResults.length); + Arrays.sort(accurateModeResults, sorter); - // The face bounding box of using ACCURATE_MODE is smaller than FAST_MODE - for (int i = 0; i < accurateModeResults.length; i++) { + for (int i = 0; i < numFaces; i++) { RectF fastModeRect = new RectF(); RectF accurateModeRect = new RectF(); @@ -160,14 +165,23 @@ fastModeResults[i].boundingBox.x + fastModeResults[i].boundingBox.width, fastModeResults[i].boundingBox.y + fastModeResults[i].boundingBox.height); - accurateModeRect.set(accurateModeResults[i].boundingBox.x + ACCURATE_MODE_SIZE, - accurateModeResults[i].boundingBox.y + ACCURATE_MODE_SIZE, - accurateModeResults[i].boundingBox.x + accurateModeResults[i].boundingBox.width - - ACCURATE_MODE_SIZE, - accurateModeResults[i].boundingBox.y + accurateModeResults[i].boundingBox.height - - ACCURATE_MODE_SIZE); + accurateModeRect.set(accurateModeResults[i].boundingBox.x, + accurateModeResults[i].boundingBox.y, + accurateModeResults[i].boundingBox.x + accurateModeResults[i].boundingBox.width, + accurateModeResults[i].boundingBox.y + + accurateModeResults[i].boundingBox.height); - Assert.assertEquals(true, fastModeRect.contains(accurateModeRect)); + Assert.assertTrue( + fastModeRect.contains(POSE_FACES_LOCATIONS[i].x, POSE_FACES_LOCATIONS[i].y)); + Assert.assertTrue(accurateModeRect.contains( + POSE_FACES_LOCATIONS[i].x, POSE_FACES_LOCATIONS[i].y)); + for (int j = 0; j < numFaces; j++) { + if (i == j) continue; + Assert.assertFalse(fastModeRect.contains( + POSE_FACES_LOCATIONS[j].x, POSE_FACES_LOCATIONS[j].y)); + Assert.assertFalse(accurateModeRect.contains( + POSE_FACES_LOCATIONS[j].x, POSE_FACES_LOCATIONS[j].y)); + } } } @@ -182,17 +196,14 @@ FaceDetectionResult[] results = detect(TestUtils.mojoBitmapFromBitmap(rotationBitmap), false, DetectionProviderType.GMS_CORE); Assert.assertEquals(1, results.length); - Assert.assertEquals(197.0, results[0].boundingBox.width, BOUNDING_BOX_SIZE_ERROR); - Assert.assertEquals(246.0, results[0].boundingBox.height, BOUNDING_BOX_SIZE_ERROR); + Assert.assertThat(results[0].boundingBox.width, greaterThan(100.0f)); + Assert.assertThat(results[0].boundingBox.height, greaterThan(200.0f)); } @Test @SmallTest @Feature({"ShapeDetection"}) public void testDetectRotatedFaceWithGmsCore() { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } Matrix matrix = new Matrix(); // Rotate the Bitmap.
diff --git a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TestUtils.java b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TestUtils.java index ac1108d3..d68a990 100644 --- a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TestUtils.java +++ b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TestUtils.java
@@ -10,7 +10,15 @@ import android.graphics.Color; import android.graphics.Paint; +import com.google.android.gms.vision.barcode.Barcode; +import com.google.android.gms.vision.barcode.BarcodeDetector; +import com.google.android.gms.vision.face.FaceDetector; +import com.google.android.gms.vision.text.TextRecognizer; + +import org.junit.Assert; + import org.chromium.base.ContextUtils; +import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.UrlUtils; import org.chromium.gms.ChromiumPlayServicesAvailability; import org.chromium.skia.mojom.BitmapN32ImageInfo; @@ -24,12 +32,37 @@ */ public class TestUtils { public static final boolean IS_GMS_CORE_SUPPORTED = isGmsCoreSupported(); + public static boolean sIsVisionLibraryReady; private static boolean isGmsCoreSupported() { return ChromiumPlayServicesAvailability.isGooglePlayServicesAvailable( ContextUtils.getApplicationContext()); } + public static void waitForVisionLibraryReady() { + Assert.assertTrue(IS_GMS_CORE_SUPPORTED); + if (!sIsVisionLibraryReady) { + FaceDetector.Builder builder = + new FaceDetector.Builder(ContextUtils.getApplicationContext()); + builder.setMode(FaceDetector.ACCURATE_MODE); + builder.setLandmarkType(FaceDetector.ALL_LANDMARKS); + FaceDetector faceDetector = builder.build(); + CriteriaHelper.pollInstrumentationThread(() -> faceDetector.isOperational()); + + BarcodeDetector barcodeDetector = + new BarcodeDetector.Builder(ContextUtils.getApplicationContext()) + .setBarcodeFormats(Barcode.ALL_FORMATS) + .build(); + CriteriaHelper.pollInstrumentationThread(() -> barcodeDetector.isOperational()); + + TextRecognizer textRecognizer = + new TextRecognizer.Builder(ContextUtils.getApplicationContext()).build(); + CriteriaHelper.pollInstrumentationThread(() -> textRecognizer.isOperational()); + + sIsVisionLibraryReady = true; + } + } + public static org.chromium.skia.mojom.BitmapN32 mojoBitmapFromBitmap(Bitmap bitmap) { ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); bitmap.copyPixelsToBuffer(buffer);
diff --git a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TextDetectionImplTest.java b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TextDetectionImplTest.java index 864155f0..aafaa4ab 100644 --- a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TextDetectionImplTest.java +++ b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/TextDetectionImplTest.java
@@ -4,17 +4,16 @@ package org.chromium.shape_detection; -import android.os.Build; - import androidx.test.filters.SmallTest; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Batch; -import org.chromium.base.test.util.DisableIf; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.gfx.mojom.RectF; import org.chromium.shape_detection.mojom.TextDetection; @@ -28,8 +27,9 @@ */ @RunWith(BaseJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) -@DisableIf.Build(sdk_is_greater_than = Build.VERSION_CODES.N_MR1, message = "crbug.com/1153716") +@DisabledTest(message = "https://crbug.com/1153716") public class TextDetectionImplTest { + private static final float BOUNDS_TOLERANCE = 20.0f; private static final String[] DETECTION_EXPECTED_TEXT = { "The quick brown fox jumped over the lazy dog.", "Helvetica Neue 36."}; private static final float[][] TEXT_BOUNDING_BOX = { @@ -57,30 +57,43 @@ return toReturn; } + @Before + public void setUp() { + TestUtils.waitForVisionLibraryReady(); + } + @Test @SmallTest @Feature({"ShapeDetection"}) public void testDetectSucceedsOnValidBitmap() { - if (!TestUtils.IS_GMS_CORE_SUPPORTED) { - return; - } TextDetectionResult[] results = detect(TEXT_DETECTION_BITMAP); Assert.assertEquals(DETECTION_EXPECTED_TEXT.length, results.length); for (int i = 0; i < DETECTION_EXPECTED_TEXT.length; i++) { - Assert.assertEquals(results[i].rawValue, DETECTION_EXPECTED_TEXT[i]); - Assert.assertEquals(TEXT_BOUNDING_BOX[i][0], results[i].boundingBox.x, 0.0); - Assert.assertEquals(TEXT_BOUNDING_BOX[i][1], results[i].boundingBox.y, 0.0); - Assert.assertEquals(TEXT_BOUNDING_BOX[i][2], results[i].boundingBox.width, 0.0); - Assert.assertEquals(TEXT_BOUNDING_BOX[i][3], results[i].boundingBox.height, 0.0); + Assert.assertEquals(DETECTION_EXPECTED_TEXT[i], results[i].rawValue); + Assert.assertEquals( + TEXT_BOUNDING_BOX[i][0], results[i].boundingBox.x, BOUNDS_TOLERANCE); + Assert.assertEquals( + TEXT_BOUNDING_BOX[i][1], results[i].boundingBox.y, BOUNDS_TOLERANCE); + Assert.assertEquals( + TEXT_BOUNDING_BOX[i][2], results[i].boundingBox.width, BOUNDS_TOLERANCE); + Assert.assertEquals( + TEXT_BOUNDING_BOX[i][3], results[i].boundingBox.height, BOUNDS_TOLERANCE); RectF cornerRectF = new RectF(); cornerRectF.x = results[i].cornerPoints[0].x; cornerRectF.y = results[i].cornerPoints[0].y; cornerRectF.width = results[i].cornerPoints[1].x - cornerRectF.x; cornerRectF.height = results[i].cornerPoints[2].y - cornerRectF.y; - Assert.assertEquals(results[i].boundingBox, cornerRectF); - Assert.assertEquals(results[i].cornerPoints[3].x, results[i].cornerPoints[1].x, 0.0); + Assert.assertEquals(results[i].boundingBox.x, cornerRectF.x, 0.0); + Assert.assertEquals(results[i].boundingBox.y, cornerRectF.y, 0.0); + Assert.assertEquals(results[i].boundingBox.width, cornerRectF.width, 0.0); + Assert.assertEquals(results[i].boundingBox.height, cornerRectF.height, 0.0); + + // 4 corner points are in clockwise direction starting with top-left by spec. + Assert.assertEquals(results[i].cornerPoints[3].x, results[i].cornerPoints[0].x, 0.0); + Assert.assertEquals(results[i].cornerPoints[2].x, results[i].cornerPoints[1].x, 0.0); + Assert.assertEquals(results[i].cornerPoints[1].y, results[i].cornerPoints[0].y, 0.0); Assert.assertEquals(results[i].cornerPoints[3].y, results[i].cornerPoints[2].y, 0.0); } }
diff --git a/testing/buildbot/chromium.android.fyi.json b/testing/buildbot/chromium.android.fyi.json index 3b2adcd..537e8796 100644 --- a/testing/buildbot/chromium.android.fyi.json +++ b/testing/buildbot/chromium.android.fyi.json
@@ -1245,7 +1245,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb", @@ -3567,7 +3567,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android24.textpb", @@ -3642,7 +3642,7 @@ }, { "args": [ - "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android24.textpb", @@ -8331,15 +8331,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M103/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M103/out/Release", "--client-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -8365,7 +8365,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -8416,15 +8416,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M104/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M104/out/Release", "--client-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -8450,7 +8450,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -8841,15 +8841,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M103/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -8875,7 +8875,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -8926,15 +8926,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M104/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -8960,7 +8960,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}",
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 716c7b7..5913518 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -11448,7 +11448,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android30.textpb", @@ -11526,7 +11526,7 @@ }, { "args": [ - "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android30.textpb", @@ -16138,7 +16138,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android31.textpb", @@ -16216,7 +16216,7 @@ }, { "args": [ - "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android31.textpb", @@ -32574,7 +32574,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb", @@ -42490,7 +42490,7 @@ }, { "args": [ - "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=-org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb", @@ -42565,7 +42565,7 @@ }, { "args": [ - "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*", + "--gtest_filter=org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:org.chromium.shape_detection.*", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb", @@ -46508,15 +46508,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M103/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M103/out/Release", "--client-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -46542,7 +46542,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -46593,15 +46593,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M104/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M104/out/Release", "--client-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -46627,7 +46627,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -47018,15 +47018,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M103/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -47052,7 +47052,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -47103,15 +47103,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M104/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -47137,7 +47137,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -47532,15 +47532,15 @@ { "args": [ "--additional-apk=apks/ChromePublic.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M103/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M103/out/Release", "--client-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -47566,7 +47566,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -47617,15 +47617,15 @@ { "args": [ "--additional-apk=apks/ChromePublic.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M104/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M104/out/Release", "--client-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -47651,7 +47651,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -48042,15 +48042,15 @@ { "args": [ "--additional-apk=apks/ChromePublic.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M103/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -48076,7 +48076,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -48127,15 +48127,15 @@ { "args": [ "--additional-apk=apks/ChromePublic.apk", + "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M104/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -48161,7 +48161,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -48624,15 +48624,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M103/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M103/out/Release", "--client-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -48658,7 +48658,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -48709,15 +48709,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M104/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M104/out/Release", "--client-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -48743,7 +48743,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -49134,15 +49134,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M103/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -49168,7 +49168,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -49219,15 +49219,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M104/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -49253,7 +49253,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -49716,15 +49716,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M103/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M103/out/Release", "--client-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -49750,7 +49750,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -49801,15 +49801,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", + "--client-outdir", + "../../weblayer_instrumentation_test_M104/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M104/out/Release", "--client-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -49835,7 +49835,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -50226,15 +50226,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M103/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=103", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -50260,7 +50260,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M103", - "revision": "version:103.0.5060.116" + "revision": "version:103.0.5060.117" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -50311,15 +50311,15 @@ { "args": [ "--additional-apk=apks/WebLayerShellSystemWebView.apk", + "--webview-apk-path=apks/SystemWebView.apk", "--test-runner-outdir", ".", "--client-outdir", ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", "--implementation-outdir", "../../weblayer_instrumentation_test_M104/out/Release", + "--test-expectations", + "../../weblayer/browser/android/javatests/skew/expectations.txt", "--impl-version=104", "--gs-results-bucket=chromium-result-details", "--recover-devices", @@ -50345,7 +50345,7 @@ { "cipd_package": "chromium/testing/weblayer-x86", "location": "weblayer_instrumentation_test_M104", - "revision": "version:104.0.5112.34" + "revision": "version:104.0.5112.35" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}",
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index eeec9c7..ca6459db 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -5688,21 +5688,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -5715,7 +5715,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true, @@ -5853,21 +5853,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -5879,7 +5879,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "args": [ @@ -5999,21 +5999,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -6025,7 +6025,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true,
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index f57b2304..a3b0009 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -92974,21 +92974,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -92996,7 +92996,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true, @@ -93109,28 +93109,28 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "args": [ @@ -93230,28 +93230,28 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true, @@ -94589,20 +94589,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -94616,7 +94616,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "merge": { @@ -94754,20 +94754,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -94780,7 +94780,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "args": [ @@ -94900,20 +94900,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -94926,7 +94926,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "merge": { @@ -96422,20 +96422,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -96449,7 +96449,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "merge": { @@ -96587,20 +96587,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -96613,7 +96613,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "args": [ @@ -96733,20 +96733,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -96759,7 +96759,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "merge": { @@ -97494,20 +97494,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -97520,7 +97520,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" } ] },
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index bf1977d03..69390c4 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -20874,21 +20874,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5159.0", + "name": "interactive_ui_tests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -20901,7 +20901,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true, @@ -21039,21 +21039,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -21065,7 +21065,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "args": [ @@ -21185,21 +21185,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5159.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 105.0.5161.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v105.0.5159.0", - "revision": "version:105.0.5159.0" + "location": "lacros_version_skew_tests_v105.0.5161.0", + "revision": "version:105.0.5161.0" } ], "dimension_sets": [ @@ -21211,7 +21211,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 105.0.5159.0" + "variant_id": "Lacros version skew testing ash 105.0.5161.0" }, { "isolate_profile_data": true,
diff --git a/testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter b/testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter index 896c2ff2..94d52d81 100644 --- a/testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter +++ b/testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter
@@ -6,7 +6,15 @@ -AppWindowTest.RuntimeFullscreenToAlwaysOnTop -BookmarkBarViewTest* -ChromeVisibilityObserverInteractiveTest.VisibilityTest --CrossSiteSubframe/DragAndDropBrowserTest* +-CrossSiteSubframe/DragAndDropBrowserTest.CrossSiteDrag/* +-CrossSiteSubframe/DragAndDropBrowserTest.CrossTabDrag/* +-CrossSiteSubframe/DragAndDropBrowserTest.DragCorsSameOriginImageBetweenFrames/* +-CrossSiteSubframe/DragAndDropBrowserTest.DragCrossOriginImageBetweenFrames/* +-CrossSiteSubframe/DragAndDropBrowserTest.DragSameOriginImageBetweenFrames/* +-CrossSiteSubframe/DragAndDropBrowserTest.DragStartInFrame/1 +-CrossSiteSubframe/DragAndDropBrowserTest.DragStartInFrame/2 +-CrossSiteSubframe/DragAndDropBrowserTest.DropUrlIntoOmnibox/1 +-CrossSiteSubframe/DragAndDropBrowserTest.DropUrlIntoOmnibox/2 -DesktopWidgetTestInteractive.DesktopNativeWidgetWithModalTransientChild -DesktopWindowTreeHostPlatformImplTest.CaptureEventForwarding -DesktopWindowTreeHostPlatformImplTest.Deactivate @@ -15,7 +23,15 @@ -MenuViewDragAndDropTestNestedDrag.MenuViewDragAndDropNestedDrag -MenuViewDragAndDropTestTestInMenuDrag.TestInMenuDrag -OmniboxViewViewsTest.SelectionClipboard --SameSiteSubframe* +-SameSiteSubframe/DragAndDropBrowserTest.CrossSiteDrag/* +-SameSiteSubframe/DragAndDropBrowserTest.CrossTabDrag/* +-SameSiteSubframe/DragAndDropBrowserTest.DragCorsSameOriginImageBetweenFrames/* +-SameSiteSubframe/DragAndDropBrowserTest.DragCrossOriginImageBetweenFrames/* +-SameSiteSubframe/DragAndDropBrowserTest.DragSameOriginImageBetweenFrames/* +-SameSiteSubframe/DragAndDropBrowserTest.DragStartInFrame/1 +-SameSiteSubframe/DragAndDropBrowserTest.DragStartInFrame/2 +-SameSiteSubframe/DragAndDropBrowserTest.DropUrlIntoOmnibox/1 +-SameSiteSubframe/DragAndDropBrowserTest.DropUrlIntoOmnibox/2 -SitePerProcessInteractiveBrowserTest.TabAndMouseFocusNavigation -TabMetricsLoggerTest.CreateWindowFeaturesTestWindowActivation -WidgetInputMethodInteractiveTest.Activation
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 481d534..219f16b 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -75,7 +75,8 @@ # on images that do not have playstore. # They will be ran in chrome_public_test_apk_with_playstore below. '--gtest_filter=-' - 'org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*' + 'org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:' + 'org.chromium.shape_detection.*' ], 'swarming': { 'shards': 20, @@ -91,7 +92,8 @@ # present. See crbug.com/1056330 for more details. # They should be ran in emulator on images that have playstore. '--gtest_filter=' - 'org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*' + 'org.chromium.chrome.browser.contextualsearch.ContextualSearchManagerTest.test*ExternalNavigationWithUserGesture*:' + 'org.chromium.shape_detection.*' ], 'mixins': [ 'skia_gold_test',
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index 254b59d3..e52d3c1 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -22,15 +22,15 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5159.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v105.0.5161.0/test_ash_chrome', ], - 'identifier': 'Lacros version skew testing ash 105.0.5159.0', + 'identifier': 'Lacros version skew testing ash 105.0.5161.0', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v105.0.5159.0', - 'revision': 'version:105.0.5159.0', + 'location': 'lacros_version_skew_tests_v105.0.5161.0', + 'revision': 'version:105.0.5161.0', }, ], }, @@ -529,16 +529,16 @@ }, 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MILESTONE': { 'args': [ + '--webview-apk-path=apks/AOSP_SystemWebView.apk', '--test-runner-outdir', '.', '--client-outdir', '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/AOSP_SystemWebView.apk', '--implementation-outdir', '../../weblayer_instrumentation_test_M104/out/Release', - '--impl-version=104' + '--test-expectations', + '../../weblayer/browser/android/javatests/skew/expectations.txt', + '--impl-version=104', ], 'identifier': 'with_impl_from_104', 'swarming': { @@ -546,23 +546,23 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M104', - 'revision': 'version:104.0.5112.34' + 'revision': 'version:104.0.5112.35', } - ] - } + ], + }, }, 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE': { 'args': [ + '--webview-apk-path=apks/AOSP_SystemWebView.apk', '--test-runner-outdir', '.', '--client-outdir', '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/AOSP_SystemWebView.apk', '--implementation-outdir', '../../weblayer_instrumentation_test_M103/out/Release', - '--impl-version=103' + '--test-expectations', + '../../weblayer/browser/android/javatests/skew/expectations.txt', + '--impl-version=103', ], 'identifier': 'with_impl_from_103', 'swarming': { @@ -570,10 +570,10 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M103', - 'revision': 'version:103.0.5060.116' + 'revision': 'version:103.0.5060.117', } - ] - } + ], + }, }, 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE': { 'args': [ @@ -673,16 +673,16 @@ }, 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MILESTONE': { 'args': [ + '--webview-apk-path=apks/SystemWebView.apk', '--test-runner-outdir', '.', '--client-outdir', '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', '--implementation-outdir', '../../weblayer_instrumentation_test_M104/out/Release', - '--impl-version=104' + '--test-expectations', + '../../weblayer/browser/android/javatests/skew/expectations.txt', + '--impl-version=104', ], 'identifier': 'with_impl_from_104', 'swarming': { @@ -690,23 +690,23 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M104', - 'revision': 'version:104.0.5112.34' + 'revision': 'version:104.0.5112.35', } - ] - } + ], + }, }, 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE': { 'args': [ + '--webview-apk-path=apks/SystemWebView.apk', '--test-runner-outdir', '.', '--client-outdir', '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', '--implementation-outdir', '../../weblayer_instrumentation_test_M103/out/Release', - '--impl-version=103' + '--test-expectations', + '../../weblayer/browser/android/javatests/skew/expectations.txt', + '--impl-version=103', ], 'identifier': 'with_impl_from_103', 'swarming': { @@ -714,10 +714,10 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M103', - 'revision': 'version:103.0.5060.116' + 'revision': 'version:103.0.5060.117', } - ] - } + ], + }, }, 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE': { 'args': [ @@ -817,16 +817,16 @@ }, 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MILESTONE': { 'args': [ + '--webview-apk-path=apks/SystemWebView.apk', '--test-runner-outdir', '.', + '--client-outdir', + '../../weblayer_instrumentation_test_M104/out/Release', '--implementation-outdir', '.', '--test-expectations', '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', - '--client-outdir', - '../../weblayer_instrumentation_test_M104/out/Release', - '--client-version=104' + '--client-version=104', ], 'identifier': 'with_client_from_104', 'swarming': { @@ -834,23 +834,23 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M104', - 'revision': 'version:104.0.5112.34' + 'revision': 'version:104.0.5112.35', } - ] - } + ], + }, }, 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE': { 'args': [ + '--webview-apk-path=apks/SystemWebView.apk', '--test-runner-outdir', '.', + '--client-outdir', + '../../weblayer_instrumentation_test_M103/out/Release', '--implementation-outdir', '.', '--test-expectations', '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', - '--client-outdir', - '../../weblayer_instrumentation_test_M103/out/Release', - '--client-version=103' + '--client-version=103', ], 'identifier': 'with_client_from_103', 'swarming': { @@ -858,10 +858,10 @@ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M103', - 'revision': 'version:103.0.5060.116' + 'revision': 'version:103.0.5060.117', } - ] - } + ], + }, }, 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE': { 'args': [
diff --git a/testing/unexpected_passes_common/builders.py b/testing/unexpected_passes_common/builders.py index 5f9759f..9d4810f 100644 --- a/testing/unexpected_passes_common/builders.py +++ b/testing/unexpected_passes_common/builders.py
@@ -24,6 +24,9 @@ AUTOGENERATED_JSON_KEY = 'AAAAA1 AUTOGENERATED FILE DO NOT EDIT' +FakeBuildersDict = typing.Dict[data_types.BuilderEntry, typing. + Set[data_types.BuilderEntry]] + _registered_instance = None # pylint: disable=useless-object-inheritance @@ -270,8 +273,7 @@ """ raise NotImplementedError() - def GetFakeCiBuilders(self) -> typing.Dict[data_types.BuilderEntry, typing. - Set[data_types.BuilderEntry]]: + def GetFakeCiBuilders(self) -> FakeBuildersDict: """Gets a mapping of fake CI builders to their mirrored trybots. Returns:
diff --git a/testing/unexpected_passes_common/queries.py b/testing/unexpected_passes_common/queries.py index 77c5224..8ea8af3a6 100644 --- a/testing/unexpected_passes_common/queries.py +++ b/testing/unexpected_passes_common/queries.py
@@ -341,26 +341,26 @@ return False def _GetQueryGeneratorForBuilder(self, builder: data_types.BuilderEntry - ) -> typing.Optional['_BaseQueryGenerator']: - """Returns a _BaseQueryGenerator instance to only include relevant tests. + ) -> typing.Optional['BaseQueryGenerator']: + """Returns a BaseQueryGenerator instance to only include relevant tests. Args: builder: A data_types.BuilderEntry containing the builder to query. Returns: None if the query returned no results. Otherwise, some instance of a - _BaseQueryGenerator. + BaseQueryGenerator. """ raise NotImplementedError() - def _RunBigQueryCommandsForJsonOutput(self, queries: typing.List[str], - parameters: QueryParameters - ) -> typing.List[QueryResult]: + def _RunBigQueryCommandsForJsonOutput( + self, queries: typing.Union[str, typing.List[str]], + parameters: QueryParameters) -> typing.List[QueryResult]: """Runs the given BigQuery queries and returns their outputs as JSON. Args: - queries: A list of strings containing valid BigQuery queries to run or a - single string containing a query. + queries: A string or list of strings containing valid BigQuery queries to + run or a single string containing a query. parameters: A dict specifying parameters to substitute in the query in the format {type: {key: value}}. For example, the dict: {'INT64': {'num_builds': 5}} @@ -480,7 +480,7 @@ raise NotImplementedError() -class _BaseQueryGenerator(object): +class BaseQueryGenerator(object): """Abstract base class for query generators.""" def __init__(self, builder: data_types.BuilderEntry): @@ -510,7 +510,7 @@ # pylint: disable=abstract-method -class FixedQueryGenerator(_BaseQueryGenerator): +class FixedQueryGenerator(BaseQueryGenerator): """Concrete test filter that cannot be split.""" def __init__(self, builder: data_types.BuilderEntry, test_filter: str): @@ -531,7 +531,7 @@ # pylint: disable=abstract-method -class SplitQueryGenerator(_BaseQueryGenerator): +class SplitQueryGenerator(BaseQueryGenerator): """Concrete test filter that can be split to a desired size.""" def __init__(self, builder: data_types.BuilderEntry,
diff --git a/testing/unexpected_passes_common/unittest_utils.py b/testing/unexpected_passes_common/unittest_utils.py index 215a4732..4476f96 100644 --- a/testing/unexpected_passes_common/unittest_utils.py +++ b/testing/unexpected_passes_common/unittest_utils.py
@@ -48,7 +48,7 @@ class SimpleBigQueryQuerier(queries_module.BigQueryQuerier): def _GetQueryGeneratorForBuilder(self, builder: data_types.BuilderEntry - ) -> queries_module._BaseQueryGenerator: + ) -> queries_module.BaseQueryGenerator: if not self._large_query_mode: return SimpleFixedQueryGenerator(builder, 'AND True') return SimpleSplitQueryGenerator(builder, ['test_id'], 200)
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 7d17ca75..c827061 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1435,6 +1435,22 @@ ] } ], + "AutofillServerTypeTakesPrecedenceOnWebView": [ + { + "platforms": [ + "android_weblayer", + "android_webview" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutofillServerTypeTakesPrecedence" + ] + } + ] + } + ], "AutofillShadowDOM": [ { "platforms": [
diff --git a/third_party/blink/perf_tests/accessibility/build-table.html b/third_party/blink/perf_tests/accessibility/build-table.html index ee8ab5f..8a62a28a 100644 --- a/third_party/blink/perf_tests/accessibility/build-table.html +++ b/third_party/blink/perf_tests/accessibility/build-table.html
@@ -29,11 +29,11 @@ } setTimeout(() => { - // Add 100 cells to each row. + // Add 33 cells to each row. for (let row = table.firstElementChild; row; row = row.nextElementSibling) { - for (let i = 0; i < 100; i++) { + for (let i = 0; i < 33; i++) { let cell = document.createElement('td'); cell.innerHTML = i; row.appendChild(cell);
diff --git a/third_party/blink/perf_tests/accessibility/focus-links.html b/third_party/blink/perf_tests/accessibility/focus-links.html index 9d95939..7b429e0 100644 --- a/third_party/blink/perf_tests/accessibility/focus-links.html +++ b/third_party/blink/perf_tests/accessibility/focus-links.html
@@ -47,7 +47,7 @@ // Iterate over some of the links and focus each one with a different // delay. Just focusing a link shouldn't incur a large cost, // even if the page has a lot of elements. - for (let i = 0; i < 100; i++) { + for (let i = 0; i < 33; i++) { window.setTimeout(() => { document.getElementById('link' + i).focus(); }, 10 * i);
diff --git a/third_party/blink/perf_tests/accessibility/insert-block-child-after-many-inline-children.html b/third_party/blink/perf_tests/accessibility/insert-block-child-after-many-inline-children.html index 80c0924..4fa296c8 100644 --- a/third_party/blink/perf_tests/accessibility/insert-block-child-after-many-inline-children.html +++ b/third_party/blink/perf_tests/accessibility/insert-block-child-after-many-inline-children.html
@@ -48,7 +48,7 @@ function insertDivChildAfterManySpanChildren() { testColor(getComputedStyle(container).color, red, 'Initial color'); - for (let i = 0; i < 2500; ++i) + for (let i = 0; i < 833; ++i) container.appendChild(document.createElement("span")); container.appendChild(document.createElement("div")); container.classList.add('a'); @@ -76,4 +76,4 @@ </script> -</html> \ No newline at end of file +</html>
diff --git a/third_party/blink/perf_tests/accessibility/line-breaks.html b/third_party/blink/perf_tests/accessibility/line-breaks.html index f8d3adf..c2e7564 100644 --- a/third_party/blink/perf_tests/accessibility/line-breaks.html +++ b/third_party/blink/perf_tests/accessibility/line-breaks.html
@@ -26,7 +26,7 @@ // in-between. var testElement = document.getElementById('testElement'); var html = ''; - for (var i = 0; i < 1000; i++) { + for (var i = 0; i < 333; i++) { html += randomString() + ' ' + randomString() + '<br>'; } testElement.innerHTML = html;
diff --git a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-auto.html b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-auto.html index 4e83ffd..a6b1fc3 100644 --- a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-auto.html +++ b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-auto.html
@@ -71,7 +71,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 50; i++) { + for (let i = 0; i < 17; i++) { const child1 = generateNodes(100, "blue"); root1.appendChild(child1); const child2 = generateNodes(100, "green");
diff --git a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-hidden.html b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-hidden.html index 0bd078f..c3765d04 100644 --- a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-hidden.html +++ b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-content-visibility-hidden.html
@@ -61,7 +61,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 50; i++) { + for (let i = 0; i < 17; i++) { const child1 = generateNodes(100, "blue"); root1.appendChild(child1); const child2 = generateNodes(100, "green");
diff --git a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none-in-focusable.html b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none-in-focusable.html index 9a14e7aa..9275ca9 100644 --- a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none-in-focusable.html +++ b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none-in-focusable.html
@@ -63,7 +63,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 900; i++) { + for (let i = 0; i < 300; i++) { const child1 = generateNodes(12, "blue"); root1.appendChild(child1); const child2 = generateNodes(12, "green");
diff --git a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none.html b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none.html index a2103ad..c56a6419 100644 --- a/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none.html +++ b/third_party/blink/perf_tests/accessibility/many-nodes-toggle-display-none.html
@@ -61,7 +61,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 900; i++) { + for (let i = 0; i < 300; i++) { const child1 = generateNodes(12, "blue"); root1.appendChild(child1); const child2 = generateNodes(12, "green");
diff --git a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-block-subtree.html b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-block-subtree.html index 1543158..e0f93e2 100644 --- a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-block-subtree.html +++ b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-block-subtree.html
@@ -24,7 +24,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); + appendManyElements(document.body, 6); setTimeout(changeLeafText, 10);
diff --git a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-hidden-subtree.html b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-hidden-subtree.html index 403252b..e249356 100644 --- a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-hidden-subtree.html +++ b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-hidden-subtree.html
@@ -24,7 +24,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); + appendManyElements(document.body, 6); setTimeout(changeLeafText, 10);
diff --git a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-inline-subtree.html b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-inline-subtree.html index 8c4b790..116f23b8 100644 --- a/third_party/blink/perf_tests/accessibility/many-text-changes-deep-inline-subtree.html +++ b/third_party/blink/perf_tests/accessibility/many-text-changes-deep-inline-subtree.html
@@ -24,7 +24,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); + appendManyElements(document.body, 6); setTimeout(changeLeafText, 10);
diff --git a/third_party/blink/perf_tests/accessibility/many-text-changes-small-wait-between.html b/third_party/blink/perf_tests/accessibility/many-text-changes-small-wait-between.html index bdaed4c..5aa235a 100644 --- a/third_party/blink/perf_tests/accessibility/many-text-changes-small-wait-between.html +++ b/third_party/blink/perf_tests/accessibility/many-text-changes-small-wait-between.html
@@ -24,7 +24,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); // Create tree 7 levels deep. + appendManyElements(document.body, 6); // Create tree 6 levels deep. setTimeout(changeLeafText, 10);
diff --git a/third_party/blink/perf_tests/accessibility/slot-updates.html b/third_party/blink/perf_tests/accessibility/slot-updates.html index a5f040c..3322ee4b 100644 --- a/third_party/blink/perf_tests/accessibility/slot-updates.html +++ b/third_party/blink/perf_tests/accessibility/slot-updates.html
@@ -7,9 +7,9 @@ <sn-form slot="form-slot"></sn-form> </sn-show-element> <script> - const TABLE_COLS = 15; - const TABLE_ROWS = 15; - const FORM_CONTROLS = 15; + const TABLE_COLS = 5; + const TABLE_ROWS = 5; + const FORM_CONTROLS = 5; class snShowElement extends HTMLElement { constructor() {
diff --git a/third_party/blink/perf_tests/accessibility/text-changes-ignored-in-focusable.html b/third_party/blink/perf_tests/accessibility/text-changes-ignored-in-focusable.html index adfc3cc..83e7b77 100644 --- a/third_party/blink/perf_tests/accessibility/text-changes-ignored-in-focusable.html +++ b/third_party/blink/perf_tests/accessibility/text-changes-ignored-in-focusable.html
@@ -27,7 +27,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); + appendManyElements(document.body, 6); setTimeout(changeLeafText, 250);
diff --git a/third_party/blink/perf_tests/accessibility/text-changes-unignored-in-focusable.html b/third_party/blink/perf_tests/accessibility/text-changes-unignored-in-focusable.html index ce51f8b0..bfc7318 100644 --- a/third_party/blink/perf_tests/accessibility/text-changes-unignored-in-focusable.html +++ b/third_party/blink/perf_tests/accessibility/text-changes-unignored-in-focusable.html
@@ -24,7 +24,7 @@ startTime = PerfTestRunner.now(); document.body.innerHTML = ''; - appendManyElements(document.body, 7); + appendManyElements(document.body, 6); setTimeout(changeLeafText, 250);
diff --git a/third_party/blink/perf_tests/accessibility/textarea-append.html b/third_party/blink/perf_tests/accessibility/textarea-append.html index c6b29f7..eef60386 100644 --- a/third_party/blink/perf_tests/accessibility/textarea-append.html +++ b/third_party/blink/perf_tests/accessibility/textarea-append.html
@@ -20,7 +20,7 @@ // Fill the textarea with 1000 lines of random numbers. var testElement = document.getElementById('testElement'); - testElement.textContent = new Array(1000).fill(0).map( + testElement.textContent = new Array(333).fill(0).map( (_, i) => Math.floor(100*Math.random())).join('\n'); // Wait to allow the asynchronous accessibility code that's
diff --git a/third_party/blink/perf_tests/accessibility/unassignable-slots-deep-tree.html b/third_party/blink/perf_tests/accessibility/unassignable-slots-deep-tree.html index 5825f23d..00154c76 100644 --- a/third_party/blink/perf_tests/accessibility/unassignable-slots-deep-tree.html +++ b/third_party/blink/perf_tests/accessibility/unassignable-slots-deep-tree.html
@@ -61,7 +61,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 300; i++) { + for (let i = 0; i < 100; i++) { const child1 = generateNodes(20, "blue"); root1.appendChild(child1); const child2 = generateNodes(20, "green");
diff --git a/third_party/blink/perf_tests/accessibility/unassignable-slots-focusable-containers.html b/third_party/blink/perf_tests/accessibility/unassignable-slots-focusable-containers.html index 925e13ad..fa621ca 100644 --- a/third_party/blink/perf_tests/accessibility/unassignable-slots-focusable-containers.html +++ b/third_party/blink/perf_tests/accessibility/unassignable-slots-focusable-containers.html
@@ -63,7 +63,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 300; i++) { + for (let i = 0; i < 100; i++) { const child1 = generateNodes(20, "blue"); root1.appendChild(child1); const child2 = generateNodes(20, "green");
diff --git a/third_party/blink/perf_tests/accessibility/unassignable-slots-wide-tree.html b/third_party/blink/perf_tests/accessibility/unassignable-slots-wide-tree.html index cc758b3..ad285f3 100644 --- a/third_party/blink/perf_tests/accessibility/unassignable-slots-wide-tree.html +++ b/third_party/blink/perf_tests/accessibility/unassignable-slots-wide-tree.html
@@ -61,7 +61,7 @@ root2.id = 'root2'; root2.className = 'root'; - for (let i = 0; i < 30; i++) { + for (let i = 0; i < 10; i++) { const child1 = generateNodes(5, "blue"); root1.appendChild(child1); const child2 = generateNodes(5, "green");
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 9ae0d7b..bd0100e 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -143,6 +143,9 @@ // Fenced Frames: BLINK_COMMON_EXPORT bool IsFencedFramesEnabled(); +// Note: This performs a string comparison on the feature param which is slow. +// When possible, prefer to use the equivalent accessors on blink::Page in the +// renderer and on content::FrameTree in the browser, which cache the value. BLINK_COMMON_EXPORT bool IsFencedFramesMPArchBased(); BLINK_COMMON_EXPORT bool IsFencedFramesShadowDOMBased();
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/third_party/blink/renderer/core/css/resolver/style_resolver.cc index 5947e61..7bfd12c8 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -1215,7 +1215,8 @@ } // TODO(obrufau): support styling nested pseudo-elements - if (style_request.IsPseudoStyleRequest() && element->IsPseudoElement()) { + if (style_request.rules_to_include == StyleRequest::kUAOnly || + (style_request.IsPseudoStyleRequest() && element->IsPseudoElement())) { MatchUARules(*element, collector); } else { MatchAllRules(
diff --git a/third_party/blink/renderer/core/css/style_request.h b/third_party/blink/renderer/core/css/style_request.h index 803b0976..e6fb0ec5 100644 --- a/third_party/blink/renderer/core/css/style_request.h +++ b/third_party/blink/renderer/core/css/style_request.h
@@ -40,6 +40,7 @@ public: enum RequestType { kForRenderer, kForComputedStyle }; + enum RulesToInclude { kUAOnly, kAll }; StyleRequest() = default; @@ -55,6 +56,7 @@ ScrollbarPart scrollbar_part{kNoPart}; CustomScrollbar* scrollbar{nullptr}; AtomicString pseudo_argument{g_null_atom}; + RulesToInclude rules_to_include{kAll}; explicit StyleRequest(const ComputedStyle* parent_override) : parent_override(parent_override),
diff --git a/third_party/blink/renderer/core/document_transition/document_transition.cc b/third_party/blink/renderer/core/document_transition/document_transition.cc index ff25122..06efee2a 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition.cc
@@ -42,6 +42,8 @@ const char kAbortedFromScript[] = "Aborted due to abort() call"; const char kAbortedFromCallback[] = "Aborted due to failure in DocumentTransitionCallback"; +const char kAbortedFromCallbackTimeout[] = + "Aborted due to timeout in DocumentTransitionCallback"; const char kAbortedFromInvalidConfigAtStart[] = "Start failed: invalid element configuration"; @@ -449,10 +451,25 @@ TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( "blink", "DocumentTransition::DeferringCommits", this); constexpr base::TimeDelta kTimeout = base::Seconds(4); + auto& client = document_->GetPage()->GetChromeClient(); deferring_commits_ = - document_->GetPage()->GetChromeClient().StartDeferringCommits( - *document_->GetFrame(), kTimeout, - cc::PaintHoldingReason::kDocumentTransition); + client.StartDeferringCommits(*document_->GetFrame(), kTimeout, + cc::PaintHoldingReason::kDocumentTransition); + DCHECK(deferring_commits_); + client.RegisterForDeferredCommitObservation(this); +} + +void DocumentTransition::WillStopDeferringCommits( + cc::PaintHoldingCommitTrigger trigger) { + // We don't expect to have any other triggers here, since we only register for + // the time we start deferring commits. + DCHECK(trigger == cc::PaintHoldingCommitTrigger::kDocumentTransition || + trigger == cc::PaintHoldingCommitTrigger::kTimeoutDocumentTransition); + if (trigger == cc::PaintHoldingCommitTrigger::kTimeoutDocumentTransition) + CancelPendingTransition(kAbortedFromCallbackTimeout); + document_->GetPage() + ->GetChromeClient() + .UnregisterFromDeferredCommitObservation(this); } void DocumentTransition::StopDeferringCommits() {
diff --git a/third_party/blink/renderer/core/document_transition/document_transition.h b/third_party/blink/renderer/core/document_transition/document_transition.h index 2c449bc8..c9f0c01 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition.h +++ b/third_party/blink/renderer/core/document_transition/document_transition.h
@@ -18,6 +18,7 @@ #include "third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" +#include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/graphics/document_transition_shared_element_id.h" #include "third_party/blink/renderer/platform/graphics/paint/clip_paint_property_node.h" @@ -40,7 +41,8 @@ : public ScriptWrappable, public ActiveScriptWrappable<DocumentTransition>, public ExecutionContextLifecycleObserver, - public LocalFrameView::LifecycleNotificationObserver { + public LocalFrameView::LifecycleNotificationObserver, + public ChromeClient::DeferredCommitObserver { DEFINE_WRAPPERTYPEINFO(); public: @@ -147,6 +149,7 @@ // asynchronously. void StartDeferringCommits(); void StopDeferringCommits(); + void WillStopDeferringCommits(cc::PaintHoldingCommitTrigger) final; // Allow canceling a transition until it reaches start(). void CancelPendingTransition(const char* abort_message);
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_content_element.cc b/third_party/blink/renderer/core/document_transition/document_transition_content_element.cc index ef6377ca..dcc7b0c1 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_content_element.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_content_element.cc
@@ -13,10 +13,12 @@ PseudoId pseudo_id, const AtomicString& document_transition_tag, viz::SharedElementResourceId resource_id, - bool is_live_content_element) + bool is_live_content_element, + const DocumentTransitionStyleTracker* style_tracker) : DocumentTransitionPseudoElementBase(parent, pseudo_id, - document_transition_tag), + document_transition_tag, + style_tracker), resource_id_(resource_id), is_live_content_element_(is_live_content_element) { DCHECK(resource_id_.IsValid());
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_content_element.h b/third_party/blink/renderer/core/document_transition/document_transition_content_element.h index 6a54f6c..18e0ef8 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_content_element.h +++ b/third_party/blink/renderer/core/document_transition/document_transition_content_element.h
@@ -26,7 +26,8 @@ PseudoId, const AtomicString& document_transition_tag, viz::SharedElementResourceId, - bool is_live_content_element); + bool is_live_content_element, + const DocumentTransitionStyleTracker* style_tracker); ~DocumentTransitionContentElement() override; void SetIntrinsicSize(const LayoutSize& intrinsic_size);
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.cc b/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.cc index 212193d..d8527cd 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.cc
@@ -4,15 +4,22 @@ #include "third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.h" +#include "third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h" +#include "third_party/blink/renderer/core/dom/node_computed_style.h" +#include "third_party/blink/renderer/core/style/computed_style.h" + namespace blink { DocumentTransitionPseudoElementBase::DocumentTransitionPseudoElementBase( Element* parent, PseudoId pseudo_id, - const AtomicString& document_transition_tag) - : PseudoElement(parent, pseudo_id, document_transition_tag) { + const AtomicString& document_transition_tag, + const DocumentTransitionStyleTracker* style_tracker) + : PseudoElement(parent, pseudo_id, document_transition_tag), + style_tracker_(style_tracker) { DCHECK(IsTransitionPseudoElement(pseudo_id)); DCHECK(pseudo_id == kPseudoIdPageTransition || document_transition_tag); + DCHECK(style_tracker_); } bool DocumentTransitionPseudoElementBase::CanGeneratePseudoElement( @@ -34,4 +41,19 @@ } } +scoped_refptr<ComputedStyle> +DocumentTransitionPseudoElementBase::CustomStyleForLayoutObject( + const StyleRecalcContext& style_recalc_context) { + Element* parent = ParentOrShadowHostElement(); + auto style_request = StyleRequest(GetPseudoId(), parent->GetComputedStyle(), + document_transition_tag()); + style_request.rules_to_include = style_tracker_->StyleRulesToInclude(); + return parent->StyleForPseudoElement(style_recalc_context, style_request); +} + +void DocumentTransitionPseudoElementBase::Trace(Visitor* visitor) const { + PseudoElement::Trace(visitor); + visitor->Trace(style_tracker_); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.h b/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.h index ddde09ae..3f619e5b 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.h +++ b/third_party/blink/renderer/core/document_transition/document_transition_pseudo_element_base.h
@@ -9,16 +9,24 @@ #include "third_party/blink/renderer/core/dom/pseudo_element.h" namespace blink { +class DocumentTransitionStyleTracker; class CORE_EXPORT DocumentTransitionPseudoElementBase : public PseudoElement { public: DocumentTransitionPseudoElementBase( Element* parent, PseudoId, - const AtomicString& document_transition_tag); + const AtomicString& document_transition_tag, + const DocumentTransitionStyleTracker* style_tracker); ~DocumentTransitionPseudoElementBase() override = default; bool CanGeneratePseudoElement(PseudoId) const override; + scoped_refptr<ComputedStyle> CustomStyleForLayoutObject( + const StyleRecalcContext&) override; + void Trace(Visitor* visitor) const override; + + protected: + Member<const DocumentTransitionStyleTracker> style_tracker_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc index 0544b7f4..6508086 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc
@@ -122,16 +122,11 @@ const DocumentTransitionStyleTracker* style_tracker) : DocumentTransitionPseudoElementBase(parent, pseudo_id, - document_transition_tag), - style_tracker_(style_tracker) {} + document_transition_tag, + style_tracker) {} ~ImageWrapperPseudoElement() override = default; - void Trace(Visitor* visitor) const override { - PseudoElement::Trace(visitor); - visitor->Trace(style_tracker_); - } - private: bool CanGeneratePseudoElement(PseudoId pseudo_id) const override { if (!DocumentTransitionPseudoElementBase::CanGeneratePseudoElement( @@ -178,8 +173,6 @@ } return snapshot_id.IsValid(); } - - Member<const DocumentTransitionStyleTracker> style_tracker_; }; DocumentTransitionStyleTracker::DocumentTransitionStyleTracker( @@ -594,7 +587,7 @@ case kPseudoIdPageTransition: case kPseudoIdPageTransitionContainer: return MakeGarbageCollected<DocumentTransitionPseudoElementBase>( - parent, pseudo_id, document_transition_tag); + parent, pseudo_id, document_transition_tag, this); case kPseudoIdPageTransitionImageWrapper: return MakeGarbageCollected<ImageWrapperPseudoElement>( parent, pseudo_id, document_transition_tag, this); @@ -629,7 +622,7 @@ auto* pseudo_element = MakeGarbageCollected<DocumentTransitionContentElement>( parent, pseudo_id, document_transition_tag, snapshot_id, - /*is_live_content_element=*/false); + /*is_live_content_element=*/false, this); pseudo_element->SetIntrinsicSize(size); return pseudo_element; } @@ -650,7 +643,7 @@ auto* pseudo_element = MakeGarbageCollected<DocumentTransitionContentElement>( parent, pseudo_id, document_transition_tag, snapshot_id, - /*is_live_content_element=*/true); + /*is_live_content_element=*/true, this); pseudo_element->SetIntrinsicSize(size); return pseudo_element; } @@ -883,6 +876,22 @@ return false; } +StyleRequest::RulesToInclude +DocumentTransitionStyleTracker::StyleRulesToInclude() const { + switch (state_) { + case State::kIdle: + case State::kCapturing: + case State::kCaptured: + return StyleRequest::kUAOnly; + case State::kStarted: + case State::kFinished: + return StyleRequest::kAll; + } + + NOTREACHED(); + return StyleRequest::kAll; +} + void DocumentTransitionStyleTracker::InvalidateStyle() { ua_style_sheet_.reset(); document_->GetStyleEngine().InvalidateUADocumentTransitionStyle();
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h index 8ca40a6..d9c312d 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h +++ b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOCUMENT_TRANSITION_DOCUMENT_TRANSITION_STYLE_TRACKER_H_ #include "components/viz/common/shared_element_resource_id.h" +#include "third_party/blink/renderer/core/css/style_request.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/layout/geometry/physical_rect.h" @@ -122,6 +123,10 @@ return std::move(capture_resource_ids_); } + // Returns whether styles applied to pseudo elements should be limited to UA + // rules based on the current phase of the transition. + StyleRequest::RulesToInclude StyleRulesToInclude() const; + private: class ImageWrapperPseudoElement;
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 7b09f4e..c3b623d 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -8607,7 +8607,6 @@ // TODO(khushalsagar): Add the following elements: // 1) SVGElement // 2) HTMLFrameOwnerElement - // 3) HTMLImageElement // See https://github.com/w3c/csswg-drafts/issues/7144 for details on enabling // ink overflow for replaced elements. if (GetPseudoId() == kPseudoIdPageTransitionIncomingImage || @@ -8617,7 +8616,8 @@ if (!RuntimeEnabledFeatures::CSSOverflowForReplacedElementsEnabled()) return false; - return IsA<HTMLVideoElement>(this) || IsA<HTMLCanvasElement>(this); + return IsA<HTMLVideoElement>(this) || IsA<HTMLCanvasElement>(this) || + IsA<HTMLImageElement>(this); } const ComputedStyle* Element::StyleForPositionFallback(unsigned index) {
diff --git a/third_party/blink/renderer/core/fetch/fetch_manager.cc b/third_party/blink/renderer/core/fetch/fetch_manager.cc index 2e6581e..0c593548 100644 --- a/third_party/blink/renderer/core/fetch/fetch_manager.cc +++ b/third_party/blink/renderer/core/fetch/fetch_manager.cc
@@ -790,8 +790,6 @@ resolver_->GetScriptState(), pending_remote.InitWithNewPipeAndPassReceiver()); request.MutableBody().SetStreamBody(std::move(pending_remote)); - request.SetAllowHTTP1ForStreamingUpload( - fetch_request_data_->AllowHTTP1ForStreamingUpload()); } } }
diff --git a/third_party/blink/renderer/core/fetch/fetch_request_data.cc b/third_party/blink/renderer/core/fetch/fetch_request_data.cc index 224b01f8..b7bcdcfd 100644 --- a/third_party/blink/renderer/core/fetch/fetch_request_data.cc +++ b/third_party/blink/renderer/core/fetch/fetch_request_data.cc
@@ -227,8 +227,6 @@ request->is_history_navigation_ = is_history_navigation_; request->window_id_ = window_id_; request->trust_token_params_ = trust_token_params_; - request->allow_http1_for_streaming_upload_ = - allow_http1_for_streaming_upload_; return request; }
diff --git a/third_party/blink/renderer/core/fetch/fetch_request_data.h b/third_party/blink/renderer/core/fetch/fetch_request_data.h index 95ddf06..483518c 100644 --- a/third_party/blink/renderer/core/fetch/fetch_request_data.h +++ b/third_party/blink/renderer/core/fetch/fetch_request_data.h
@@ -154,13 +154,6 @@ trust_token_params_ = std::move(trust_token_params); } - void SetAllowHTTP1ForStreamingUpload(bool allow) { - allow_http1_for_streaming_upload_ = allow; - } - bool AllowHTTP1ForStreamingUpload() const { - return allow_http1_for_streaming_upload_; - } - void Trace(Visitor*) const; private: @@ -212,7 +205,6 @@ HeapMojoRemote<network::mojom::blink::URLLoaderFactory> url_loader_factory_; base::UnguessableToken window_id_; Member<ExecutionContext> execution_context_; - bool allow_http1_for_streaming_upload_ = false; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/fetch/request.cc b/third_party/blink/renderer/core/fetch/request.cc index 1bfea9e..29579a6 100644 --- a/third_party/blink/renderer/core/fetch/request.cc +++ b/third_party/blink/renderer/core/fetch/request.cc
@@ -578,10 +578,6 @@ request->SetTrustTokenParams(std::move(params)); } - if (init->hasAllowHTTP1ForStreamingUpload()) { - request->SetAllowHTTP1ForStreamingUpload( - init->allowHTTP1ForStreamingUpload()); - } // "Let |r| be a new Request object associated with |request| and a new // Headers object whose guard is "request"."
diff --git a/third_party/blink/renderer/core/fetch/request_init.idl b/third_party/blink/renderer/core/fetch/request_init.idl index b61c7f9..ce2c4b2 100644 --- a/third_party/blink/renderer/core/fetch/request_init.idl +++ b/third_party/blink/renderer/core/fetch/request_init.idl
@@ -27,7 +27,6 @@ // contexts, this has to be enforced after the fact because the // SecureContext IDL attribute doesn't affect dictionary members. [RuntimeEnabled=TrustTokens] TrustToken trustToken; - [RuntimeEnabled=FetchUploadStreaming] boolean allowHTTP1ForStreamingUpload; // TODO(domfarolino): add support for RequestInit window member. //any window; // can only be set to null };
diff --git a/third_party/blink/renderer/core/frame/frame.h b/third_party/blink/renderer/core/frame/frame.h index c2e4d9a..74a6f72 100644 --- a/third_party/blink/renderer/core/frame/frame.h +++ b/third_party/blink/renderer/core/frame/frame.h
@@ -284,13 +284,6 @@ return inherited_effective_touch_action_; } - // Continues to bubble logical scroll from |child| in this frame. - // Returns true if the scroll was consumed locally. - virtual bool BubbleLogicalScrollFromChildFrame( - mojom::blink::ScrollDirection direction, - ui::ScrollGranularity granularity, - Frame* child) = 0; - const base::UnguessableToken& GetDevToolsFrameToken() const { return devtools_frame_token_; }
diff --git a/third_party/blink/renderer/core/frame/local_dom_window.cc b/third_party/blink/renderer/core/frame/local_dom_window.cc index 62599fd..0ef9e5c 100644 --- a/third_party/blink/renderer/core/frame/local_dom_window.cc +++ b/third_party/blink/renderer/core/frame/local_dom_window.cc
@@ -1964,9 +1964,11 @@ if (FrameOwner* owner = frame->Owner()) owner->DispatchLoad(); - DEVTOOLS_TIMELINE_TRACE_EVENT_INSTANT( - "MarkLoad", inspector_mark_load_event::Data, frame); - probe::LoadEventFired(frame); + if (frame->IsAttached()) { + DEVTOOLS_TIMELINE_TRACE_EVENT_INSTANT( + "MarkLoad", inspector_mark_load_event::Data, frame); + probe::LoadEventFired(frame); + } } }
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index e80a356..4730c85 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -938,6 +938,23 @@ style_change_reason::kInheritedStyleChangeFromParentFrame)); } +bool LocalFrame::BubbleLogicalScrollInParentFrame( + mojom::blink::ScrollDirection direction, + ui::ScrollGranularity granularity) { + bool is_embedded_main_frame = IsMainFrame() && !IsOutermostMainFrame(); + if (is_embedded_main_frame || IsA<RemoteFrame>(Parent())) { + GetLocalFrameHostRemote().BubbleLogicalScrollInParentFrame(direction, + granularity); + return false; + } else if (auto* local_parent = DynamicTo<LocalFrame>(Parent())) { + return local_parent->BubbleLogicalScrollFromChildFrame(direction, + granularity, this); + } + + DCHECK(IsOutermostMainFrame()); + return false; +} + bool LocalFrame::BubbleLogicalScrollFromChildFrame( mojom::blink::ScrollDirection direction, ui::ScrollGranularity granularity,
diff --git a/third_party/blink/renderer/core/frame/local_frame.h b/third_party/blink/renderer/core/frame/local_frame.h index ba6e2a7..fcddbad 100644 --- a/third_party/blink/renderer/core/frame/local_frame.h +++ b/third_party/blink/renderer/core/frame/local_frame.h
@@ -215,10 +215,6 @@ // subtree, updating the inert bit on all descendant frames. void SetIsInert(bool) override; void SetInheritedEffectiveTouchAction(TouchAction) override; - bool BubbleLogicalScrollFromChildFrame( - mojom::blink::ScrollDirection direction, - ui::ScrollGranularity granularity, - Frame* child) override; void DidFocus() override; bool IsAdSubframe() const override; @@ -314,6 +310,22 @@ // rect has changed. void NotifyVirtualKeyboardOverlayRectObservers(const gfx::Rect&) const; + // Bubbles a logical scroll to the parent frame, if one exists. For a local + // frame, this will continue the scroll synchronously. For remote frames and + // frame tree boundaries, this will IPC the scroll via the browser process. + // Returns true if the scroll is locally consumed, false otherwise. + bool BubbleLogicalScrollInParentFrame(mojom::blink::ScrollDirection direction, + ui::ScrollGranularity granularity); + + // Receives and continues a bubbled logical scroll from the child frame (sent + // via the method above). This can either be called synchronously by the + // method above or from the RemoteFrame child after being sent via IPC. + // Returns true if the scroll is locally consumed, false otherwise. + bool BubbleLogicalScrollFromChildFrame( + mojom::blink::ScrollDirection direction, + ui::ScrollGranularity granularity, + Frame* child); + // ========================================================================= // All public functions below this point are candidates to move out of // LocalFrame into another class.
diff --git a/third_party/blink/renderer/core/frame/remote_frame.cc b/third_party/blink/renderer/core/frame/remote_frame.cc index c4e1fc1..eb7499c 100644 --- a/third_party/blink/renderer/core/frame/remote_frame.cc +++ b/third_party/blink/renderer/core/frame/remote_frame.cc
@@ -402,17 +402,6 @@ inherited_effective_touch_action_ = touch_action; } -bool RemoteFrame::BubbleLogicalScrollFromChildFrame( - mojom::blink::ScrollDirection direction, - ui::ScrollGranularity granularity, - Frame* child) { - DCHECK(child->Client()); - To<LocalFrame>(child) - ->GetLocalFrameHostRemote() - .BubbleLogicalScrollInParentFrame(direction, granularity); - return false; -} - void RemoteFrame::RenderFallbackContent() { Frame::RenderFallbackContent(); } @@ -648,10 +637,19 @@ void RemoteFrame::BubbleLogicalScroll(mojom::blink::ScrollDirection direction, ui::ScrollGranularity granularity) { - Frame* parent_frame = Parent(); - DCHECK(parent_frame); - DCHECK(parent_frame->IsLocalFrame()); + LocalFrame* parent_frame = nullptr; + if (auto* parent = DynamicTo<LocalFrame>(Parent())) { + parent_frame = parent; + } else { + // This message can be received by an embedded frame tree's placeholder + // RemoteFrame in which case Parent() is not connected to the outer frame + // tree. + auto* owner_element = DynamicTo<HTMLFrameOwnerElement>(Owner()); + DCHECK(owner_element); + parent_frame = owner_element->GetDocument().GetFrame(); + } + DCHECK(parent_frame); parent_frame->BubbleLogicalScrollFromChildFrame(direction, granularity, this); }
diff --git a/third_party/blink/renderer/core/frame/remote_frame.h b/third_party/blink/renderer/core/frame/remote_frame.h index 21caf17..be58d64 100644 --- a/third_party/blink/renderer/core/frame/remote_frame.h +++ b/third_party/blink/renderer/core/frame/remote_frame.h
@@ -79,10 +79,6 @@ void SetTextDirection(base::i18n::TextDirection) override {} void SetIsInert(bool) override; void SetInheritedEffectiveTouchAction(TouchAction) override; - bool BubbleLogicalScrollFromChildFrame( - mojom::blink::ScrollDirection direction, - ui::ScrollGranularity granularity, - Frame* child) override; void DidFocus() override; void AddResourceTimingFromChild( mojom::blink::ResourceTimingInfoPtr timing) override;
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc index 5e26e09..2a40485f 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -1366,6 +1366,14 @@ } } +void WebFrameWidgetImpl::OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) { + GetPage()->GetChromeClient().OnDeferCommitsChanged(defer_status, reason, + trigger); +} + void WebFrameWidgetImpl::DidCompletePageScaleAnimation() { // Page scale animations only happen on the main frame. DCHECK(ForMainFrame());
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h index b72cea87..94e5186 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
@@ -407,6 +407,10 @@ void BeginMainFrame(base::TimeTicks last_frame_time) override; void UpdateLifecycle(WebLifecycleUpdate requested_update, DocumentUpdateReason reason) override; + void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) override; // mojom::blink::FrameWidget overrides: void ShowContextMenu(ui::mojom::MenuSourceType source_type,
diff --git a/third_party/blink/renderer/core/html/resources/overflow_replaced.css b/third_party/blink/renderer/core/html/resources/overflow_replaced.css index a4a42c8..4f17f0a 100644 --- a/third_party/blink/renderer/core/html/resources/overflow_replaced.css +++ b/third_party/blink/renderer/core/html/resources/overflow_replaced.css
@@ -13,7 +13,7 @@ This is in a separate file since the CSS is conditionally applied based on a runtime flag. Merge this with html.css. See crbug.com/1338641. */ -video, canvas { +video, canvas, img { overflow: clip; overflow-clip-margin: content-box; }
diff --git a/third_party/blink/renderer/core/input/scroll_manager.cc b/third_party/blink/renderer/core/input/scroll_manager.cc index d8fa46f..5262fa3 100644 --- a/third_party/blink/renderer/core/input/scroll_manager.cc +++ b/third_party/blink/renderer/core/input/scroll_manager.cc
@@ -415,8 +415,6 @@ return false; } -// TODO(bokan): This should be merged with logicalScroll assuming -// defaultSpaceEventHandler's chaining scroll can be done crossing frames. bool ScrollManager::BubblingScroll(mojom::blink::ScrollDirection direction, ui::ScrollGranularity granularity, Node* starting_node, @@ -425,16 +423,10 @@ // here because of an onLoad event, in which case the final layout hasn't been // performed yet. frame_->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kScroll); - // FIXME: enable scroll customization in this case. See crbug.com/410974. if (LogicalScroll(direction, granularity, starting_node, mouse_press_node)) return true; - Frame* parent_frame = frame_->Tree().Parent(); - if (!parent_frame) - return false; - - return parent_frame->BubbleLogicalScrollFromChildFrame(direction, granularity, - frame_); + return frame_->BubbleLogicalScrollInParentFrame(direction, granularity); } void ScrollManager::CustomizedScroll(ScrollState& scroll_state) {
diff --git a/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc b/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc index e9fb1da..342d203 100644 --- a/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc +++ b/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc
@@ -783,10 +783,18 @@ if (StyleRef().IsDeprecatedWebkitBox()) return false; - // TODO(dgrogan): MainAxisOverflowForChild == kClip also qualifies, not just - // kVisible. - return !child.ShouldApplySizeContainment() && - MainAxisOverflowForChild(child) == EOverflow::kVisible; + if (child.ShouldApplySizeContainment()) + return false; + + bool is_replaced_element_respecting_overflow = false; + if (auto* element = DynamicTo<Element>(child.GetNode())) { + is_replaced_element_respecting_overflow = + element->IsReplacedElementRespectingCSSOverflow(); + } + + return MainAxisOverflowForChild(child) == EOverflow::kVisible || + (is_replaced_element_respecting_overflow && + MainAxisOverflowForChild(child) == EOverflow::kClip); } LayoutUnit FlexLayoutAlgorithm::IntrinsicContentBlockSize() const {
diff --git a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc index 9dcdc87..4b30e70 100644 --- a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc +++ b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc
@@ -437,14 +437,14 @@ const Length& child_min_size = is_row_axis ? child.StyleRef().LogicalMinWidth() : child.StyleRef().LogicalMinHeight(); - bool overflow_is_visible = - is_row_axis - ? child.StyleRef().OverflowInlineDirection() == EOverflow::kVisible - : child.StyleRef().OverflowBlockDirection() == EOverflow::kVisible; + auto overflow = is_row_axis ? child.StyleRef().OverflowInlineDirection() + : child.StyleRef().OverflowBlockDirection(); + bool overflow_allows_auto = + overflow == EOverflow::kVisible || overflow == EOverflow::kClip; LayoutUnit baseline_shim = algorithm_->BaselineOffsetForChild( child, GridAxisForDirection(Direction())); - if (child_min_size.IsAuto() && overflow_is_visible) { + if (child_min_size.IsAuto() && overflow_allows_auto) { LayoutUnit min_size = MinContentForChild(child); const GridSpan& span = algorithm_->GetGrid().GridItemSpan(child, Direction());
diff --git a/third_party/blink/renderer/core/layout/layout_block.cc b/third_party/blink/renderer/core/layout/layout_block.cc index 5e937196..d991f6aa 100644 --- a/third_party/blink/renderer/core/layout/layout_block.cc +++ b/third_party/blink/renderer/core/layout/layout_block.cc
@@ -2003,7 +2003,7 @@ // We likewise avoid using the last line box in the case of size containment, // where the block's contents shouldn't be considered when laying out its // ancestors or siblings. - return (!StyleRef().IsOverflowVisibleAlongBothAxes() && + return (!StyleRef().IsOverflowVisibleOrClip() && !StyleRef().ShouldIgnoreOverflowPropertyForInlineBlockBaseline()) || ShouldApplyLayoutContainment(); }
diff --git a/third_party/blink/renderer/core/layout/layout_inline.cc b/third_party/blink/renderer/core/layout/layout_inline.cc index 09bf0313..905cbf4 100644 --- a/third_party/blink/renderer/core/layout/layout_inline.cc +++ b/third_party/blink/renderer/core/layout/layout_inline.cc
@@ -410,9 +410,6 @@ style.MayHaveMargin()) return true; - if (!style.AnchorName().IsNull()) - return true; - return ComputeIsAbsoluteContainer(&style) || NGOutlineUtils::HasPaintedOutline(style, GetNode()) || CanBeHitTestTargetPseudoNodeStyle(style);
diff --git a/third_party/blink/renderer/core/layout/layout_replaced.h b/third_party/blink/renderer/core/layout/layout_replaced.h index eacb3d3a..bf3e2c9 100644 --- a/third_party/blink/renderer/core/layout/layout_replaced.h +++ b/third_party/blink/renderer/core/layout/layout_replaced.h
@@ -133,6 +133,16 @@ return true; } + bool IsInSelfHitTestingPhase(HitTestPhase phase) const final { + NOT_DESTROYED(); + if (LayoutBox::IsInSelfHitTestingPhase(phase)) + return true; + + auto* element = DynamicTo<Element>(GetNode()); + return element && element->IsReplacedElementRespectingCSSOverflow() && + phase == HitTestPhase::kSelfBlockBackground; + } + void WillBeDestroyed() override; void UpdateLayout() override;
diff --git a/third_party/blink/renderer/core/layout/layout_video.h b/third_party/blink/renderer/core/layout/layout_video.h index 7fc587c..4f210cf 100644 --- a/third_party/blink/renderer/core/layout/layout_video.h +++ b/third_party/blink/renderer/core/layout/layout_video.h
@@ -26,6 +26,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_VIDEO_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_VIDEO_H_ +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/layout_media.h" #include "third_party/blink/renderer/platform/wtf/casting.h" @@ -33,7 +34,7 @@ class HTMLVideoElement; -class LayoutVideo final : public LayoutMedia { +class CORE_EXPORT LayoutVideo final : public LayoutMedia { public: explicit LayoutVideo(HTMLVideoElement*); ~LayoutVideo() override;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_anchor_query_test.cc b/third_party/blink/renderer/core/layout/ng/ng_anchor_query_test.cc index e60567fe..e8818ee 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_anchor_query_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_anchor_query_test.cc
@@ -105,65 +105,6 @@ AnchorTestData{"--div3", PhysicalRect(0, 70, 800, 0)})); } -TEST_F(NGAnchorQueryTest, Inline) { - LoadAhem(); - SetBodyInnerHTML(R"HTML( - <style> - html, body { - margin: 0; - width: 800px; - font-family: Ahem; - font-size: 10px; - line-height: 1; - } - img { - width: 10px; - height: 8px; - } - .after .add { - anchor-name: --add; - } - </style> - <div id="container"> - 0 - <!-- culled and non-culled inline boxes. --> - <span style="anchor-name: --culled">23</span> - <span style="anchor-name: --non-culled; background: yellow">56</span> - - <!-- Adding `anchor-name` dynamically should uncull. --> - <span class="add">89</span> - - <!-- Atomic inlines: replaced elements and inline blocks. --> - <img style="anchor-name: --img" src="data:image/gif;base64,R0lGODlhAQABAAAAACw="> - <span style="anchor-name: --inline-block; display: inline-block">X</span> - </div> - )HTML"); - Element* container = GetElementById("container"); - const NGPhysicalAnchorQuery* anchor_query = AnchorQuery(*container); - ASSERT_NE(anchor_query, nullptr); - EXPECT_THAT( - AnchorTestData::ToList(*anchor_query), - testing::ElementsAre( - AnchorTestData{"--culled", PhysicalRect(20, 0, 20, 10)}, - AnchorTestData{"--img", PhysicalRect(110, 0, 10, 8)}, - AnchorTestData{"--inline-block", PhysicalRect(130, 0, 10, 10)}, - AnchorTestData{"--non-culled", PhysicalRect(50, 0, 20, 10)})); - - // Add the "after" class and test anchors are updated accordingly. - container->classList().Add("after"); - UpdateAllLifecyclePhasesForTest(); - anchor_query = AnchorQuery(*container); - ASSERT_NE(anchor_query, nullptr); - EXPECT_THAT( - AnchorTestData::ToList(*anchor_query), - testing::ElementsAre( - AnchorTestData{"--add", PhysicalRect(80, 0, 20, 10)}, - AnchorTestData{"--culled", PhysicalRect(20, 0, 20, 10)}, - AnchorTestData{"--img", PhysicalRect(110, 0, 10, 8)}, - AnchorTestData{"--inline-block", PhysicalRect(130, 0, 10, 10)}, - AnchorTestData{"--non-culled", PhysicalRect(50, 0, 20, 10)})); -} - TEST_F(NGAnchorQueryTest, OutOfFlow) { SetBodyInnerHTML(R"HTML( <style>
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index d1e2d799..6b4142b 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -113,6 +113,13 @@ void SetOverscrollBehavior(LocalFrame& frame, const cc::OverscrollBehavior&) override {} void BeginLifecycleUpdates(LocalFrame& main_frame) override {} + void RegisterForDeferredCommitObservation(DeferredCommitObserver*) override {} + void UnregisterFromDeferredCommitObservation( + DeferredCommitObserver*) override {} + void OnDeferCommitsChanged( + bool, + cc::PaintHoldingReason, + absl::optional<cc::PaintHoldingCommitTrigger>) override {} bool StartDeferringCommits(LocalFrame& main_frame, base::TimeDelta timeout, cc::PaintHoldingReason reason) override;
diff --git a/third_party/blink/renderer/core/page/chrome_client.h b/third_party/blink/renderer/core/page/chrome_client.h index 19313d8..409668c7 100644 --- a/third_party/blink/renderer/core/page/chrome_client.h +++ b/third_party/blink/renderer/core/page/chrome_client.h
@@ -192,6 +192,24 @@ // // Returns false if commits were already deferred, indicating that the call // was a no-op. + struct DeferredCommitObserver : public GarbageCollectedMixin { + virtual void WillStartDeferringCommits(cc::PaintHoldingReason) {} + virtual void WillStopDeferringCommits(cc::PaintHoldingCommitTrigger) {} + + protected: + virtual ~DeferredCommitObserver() = default; + }; + + virtual void RegisterForDeferredCommitObservation( + DeferredCommitObserver*) = 0; + virtual void UnregisterFromDeferredCommitObservation( + DeferredCommitObserver*) = 0; + + virtual void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) = 0; + virtual bool StartDeferringCommits(LocalFrame& main_frame, base::TimeDelta timeout, cc::PaintHoldingReason reason) = 0;
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 be49235..70fab60 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.cc +++ b/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -184,6 +184,7 @@ void ChromeClientImpl::Trace(Visitor* visitor) const { visitor->Trace(popup_opening_observers_); visitor->Trace(external_date_time_chooser_); + visitor->Trace(deferred_commit_observers_); ChromeClient::Trace(visitor); } @@ -1050,6 +1051,31 @@ web_view_->StopDeferringMainFrameUpdate(); } +void ChromeClientImpl::RegisterForDeferredCommitObservation( + DeferredCommitObserver* observer) { + deferred_commit_observers_.insert(observer); +} + +void ChromeClientImpl::UnregisterFromDeferredCommitObservation( + DeferredCommitObserver* observer) { + deferred_commit_observers_.erase(observer); +} + +void ChromeClientImpl::OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) { + DCHECK(defer_status || trigger); + // Make a copy since callbacks may modify the set as we're iterating it. + auto observers = deferred_commit_observers_; + for (auto& observer : observers) { + if (defer_status) + observer->WillStartDeferringCommits(reason); + else + observer->WillStopDeferringCommits(*trigger); + } +} + bool ChromeClientImpl::StartDeferringCommits(LocalFrame& main_frame, base::TimeDelta timeout, cc::PaintHoldingReason reason) {
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 6413b206..2274bf91 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.h +++ b/third_party/blink/renderer/core/page/chrome_client_impl.h
@@ -75,6 +75,13 @@ void TakeFocus(mojom::blink::FocusType) override; void SetKeyboardFocusURL(Element* new_focus_element) override; void BeginLifecycleUpdates(LocalFrame& main_frame) override; + void RegisterForDeferredCommitObservation(DeferredCommitObserver*) override; + void UnregisterFromDeferredCommitObservation( + DeferredCommitObserver*) override; + void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) override; bool StartDeferringCommits(LocalFrame& main_frame, base::TimeDelta timeout, cc::PaintHoldingReason reason) override; @@ -329,6 +336,7 @@ Member<ExternalDateTimeChooser> external_date_time_chooser_; bool did_request_non_empty_tool_tip_; absl::optional<bool> before_unload_confirm_panel_result_for_testing_; + HeapHashSet<WeakMember<DeferredCommitObserver>> deferred_commit_observers_; FRIEND_TEST_ALL_PREFIXES(FileChooserQueueTest, DerefQueuedChooser); };
diff --git a/third_party/blink/renderer/core/page/spatial_navigation.cc b/third_party/blink/renderer/core/page/spatial_navigation.cc index d8d19a6c..9276b5a 100644 --- a/third_party/blink/renderer/core/page/spatial_navigation.cc +++ b/third_party/blink/renderer/core/page/spatial_navigation.cc
@@ -614,7 +614,7 @@ if (focused_layer != candidate_layer) return false; - return !candidate_layer->HasVisibleDescendant(); + return !candidate_layer->HasVisibleSelfPaintingDescendant(); } double ComputeDistanceDataForNode(SpatialNavigationDirection direction,
diff --git a/third_party/blink/renderer/core/paint/image_painter.cc b/third_party/blink/renderer/core/paint/image_painter.cc index 6d103200..ec0b6b0c 100644 --- a/third_party/blink/renderer/core/paint/image_painter.cc +++ b/third_party/blink/renderer/core/paint/image_painter.cc
@@ -178,9 +178,15 @@ PhysicalRect paint_rect = layout_image_.ReplacedContentRect(); paint_rect.offset += paint_offset; - BoxDrawingRecorder recorder(context, layout_image_, paint_info.phase, - paint_offset); - PaintIntoRect(context, paint_rect, content_rect); + // If |overflow| is supported for replaced elements, paint the complete image + // and the painting will be clipped based on overflow value by clip paint + // property nodes. + const PhysicalRect visual_rect = + layout_image_.ClipsToContentBox() ? content_rect : paint_rect; + + DrawingRecorder recorder(context, layout_image_, paint_info.phase, + ToEnclosingRect(visual_rect)); + PaintIntoRect(context, paint_rect, visual_rect); } void ImagePainter::PaintIntoRect(GraphicsContext& context,
diff --git a/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc b/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc index e6da083..e4e0a2c 100644 --- a/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc +++ b/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc
@@ -45,8 +45,9 @@ UpdateAllLifecyclePhasesForTest(); const auto* invalidations = &GetRasterInvalidationTracking(*GetDocument().View())->Invalidations(); - ASSERT_EQ(1u, invalidations->size()); + ASSERT_EQ(2u, invalidations->size()); EXPECT_EQ(gfx::Rect(8, 8, 100, 100), (*invalidations)[0].rect); + EXPECT_EQ(gfx::Rect(8, 8, 100, 100), (*invalidations)[1].rect); EXPECT_EQ(PaintInvalidationReason::kSelection, (*invalidations)[0].reason); GetDocument().View()->SetTracksRasterInvalidations(false); @@ -65,8 +66,9 @@ UpdateAllLifecyclePhasesForTest(); invalidations = &GetRasterInvalidationTracking(*GetDocument().View())->Invalidations(); - ASSERT_EQ(1u, invalidations->size()); + ASSERT_EQ(2u, invalidations->size()); EXPECT_EQ(gfx::Rect(8, 8, 100, 100), (*invalidations)[0].rect); + EXPECT_EQ(gfx::Rect(8, 8, 100, 100), (*invalidations)[1].rect); EXPECT_EQ(PaintInvalidationReason::kSelection, (*invalidations)[0].reason); GetDocument().View()->SetTracksRasterInvalidations(false); }
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index f6fd464..3e3b573 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -173,7 +173,7 @@ has_visible_content_(false), needs_descendant_dependent_flags_update_(true), needs_visual_overflow_recalc_(true), - has_visible_descendant_(false), + has_visible_self_painting_descendant_(false), #if DCHECK_IS_ON() // The root layer (LayoutView) does not need position update at start // because its Location() is always 0. @@ -469,7 +469,7 @@ if (needs_descendant_dependent_flags_update_) { bool old_has_non_isolated_descendant_with_blend_mode = has_non_isolated_descendant_with_blend_mode_; - has_visible_descendant_ = false; + has_visible_self_painting_descendant_ = false; has_non_isolated_descendant_with_blend_mode_ = false; has_fixed_position_descendant_ = false; has_sticky_position_descendant_ = false; @@ -495,8 +495,9 @@ child->UpdateDescendantDependentFlags(); - if (child->has_visible_content_ || child->has_visible_descendant_) - has_visible_descendant_ = true; + if ((child->has_visible_content_ && child->IsSelfPaintingLayer()) || + child->has_visible_self_painting_descendant_) + has_visible_self_painting_descendant_ = true; has_non_isolated_descendant_with_blend_mode_ |= (!child->GetLayoutObject().IsStackingContext() && @@ -892,7 +893,8 @@ old_child->AncestorScrollContainerLayer()); } - if (old_child->has_visible_content_ || old_child->has_visible_descendant_) + if (old_child->has_visible_content_ || + old_child->has_visible_self_painting_descendant_) MarkAncestorChainForFlagsUpdate(); if (old_child->EnclosingPaginationLayer())
diff --git a/third_party/blink/renderer/core/paint/paint_layer.h b/third_party/blink/renderer/core/paint/paint_layer.h index c9c3d15..b2ce440 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.h +++ b/third_party/blink/renderer/core/paint/paint_layer.h
@@ -291,9 +291,9 @@ return has_visible_content_; } - bool HasVisibleDescendant() const { + bool HasVisibleSelfPaintingDescendant() const { DCHECK(!needs_descendant_dependent_flags_update_); - return has_visible_descendant_; + return has_visible_self_painting_descendant_; } void DirtyVisibleContentStatus(); @@ -810,7 +810,7 @@ unsigned needs_descendant_dependent_flags_update_ : 1; unsigned needs_visual_overflow_recalc_ : 1; - unsigned has_visible_descendant_ : 1; + unsigned has_visible_self_painting_descendant_ : 1; #if DCHECK_IS_ON() unsigned needs_position_update_ : 1;
diff --git a/third_party/blink/renderer/core/paint/paint_layer_test.cc b/third_party/blink/renderer/core/paint/paint_layer_test.cc index ca136224d..06f81c9 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_test.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_test.cc
@@ -202,7 +202,7 @@ EXPECT_TRUE(parent->HasNonIsolatedDescendantWithBlendMode()); EXPECT_TRUE(stacking_parent->HasNonIsolatedDescendantWithBlendMode()); EXPECT_FALSE(stacking_grandparent->HasNonIsolatedDescendantWithBlendMode()); - EXPECT_TRUE(parent->HasVisibleDescendant()); + EXPECT_TRUE(parent->HasVisibleSelfPaintingDescendant()); } TEST_P(PaintLayerTest, HasStickyPositionDescendant) { @@ -1046,7 +1046,7 @@ PaintLayerPaintOrderIterator(target, kPositiveZOrderChildren).Next()); } -TEST_P(PaintLayerTest, HasVisibleDescendant) { +TEST_P(PaintLayerTest, HasVisibleSelfPaintingDescendant) { SetBodyInnerHTML(R"HTML( <div id='invisible' style='position:relative'> <div id='visible' style='visibility: visible; position: relative'> @@ -1056,8 +1056,8 @@ PaintLayer* invisible = GetPaintLayerByElementId("invisible"); PaintLayer* visible = GetPaintLayerByElementId("visible"); - EXPECT_TRUE(invisible->HasVisibleDescendant()); - EXPECT_FALSE(visible->HasVisibleDescendant()); + EXPECT_TRUE(invisible->HasVisibleSelfPaintingDescendant()); + EXPECT_FALSE(visible->HasVisibleSelfPaintingDescendant()); EXPECT_FALSE(invisible->HasNonIsolatedDescendantWithBlendMode()); }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc index 206e59ad..4894165 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
@@ -5567,14 +5567,20 @@ )HTML"); const auto* properties = PaintPropertiesForElement("img"); - const auto* border_radius_clip = properties->OverflowClip(); + const auto* overflow_clip = properties->OverflowClip(); + ASSERT_NE(nullptr, overflow_clip); + EXPECT_CLIP_RECT( + FloatRoundedRect(gfx::RectF(18, 18, 50, 50), FloatRoundedRect::Radii(0)), + overflow_clip); + EXPECT_EQ(properties->InnerBorderRadiusClip(), overflow_clip->Parent()); + EXPECT_EQ(DocScrollTranslation(), &overflow_clip->LocalTransformSpace()); + + const auto* border_radius_clip = properties->InnerBorderRadiusClip(); ASSERT_NE(nullptr, border_radius_clip); + EXPECT_EQ(DocContentClip(), border_radius_clip->Parent()); EXPECT_CLIP_RECT( FloatRoundedRect(gfx::RectF(18, 18, 50, 50), FloatRoundedRect::Radii(20)), border_radius_clip); - EXPECT_EQ(DocContentClip(), border_radius_clip->Parent()); - EXPECT_EQ(DocScrollTranslation(), &border_radius_clip->LocalTransformSpace()); - EXPECT_EQ(nullptr, properties->InnerBorderRadiusClip()); } TEST_P(PaintPropertyTreeBuilderTest, FrameClipWhenPrinting) {
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc b/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc index 3cca41d2..993de701 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc
@@ -1428,32 +1428,31 @@ auto* target = GetDocument().getElementById("target"); const auto* properties = PaintPropertiesForElement("target"); - // We don't need paint properties for object-fit: fill because the content - // never overflows. - EXPECT_EQ(nullptr, properties); + // Image elements need a clip node to clip the image to its content box. + EXPECT_NE(nullptr, properties); target->setAttribute(html_names::kStyleAttr, "object-fit: cover"); UpdateAllLifecyclePhasesForTest(); properties = PaintPropertiesForElement("target"); - // We don't need paint properties because image painter always clip to the - // content box. - EXPECT_EQ(nullptr, properties); + // Image elements need a clip node to clip the image to its content box. + EXPECT_NE(nullptr, properties); target->setAttribute(html_names::kStyleAttr, "object-fit: none"); UpdateAllLifecyclePhasesForTest(); properties = PaintPropertiesForElement("target"); // Ditto. - EXPECT_EQ(nullptr, properties); + EXPECT_NE(nullptr, properties); - // We need overflow clip when there is border radius. target->setAttribute(html_names::kStyleAttr, "object-fit: none; border-radius: 2px"); UpdateAllLifecyclePhasesForTest(); properties = PaintPropertiesForElement("target"); ASSERT_TRUE(properties); ASSERT_TRUE(properties->OverflowClip()); - EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 2), + EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 0), properties->OverflowClip()); + EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 2), + properties->InnerBorderRadiusClip()); // We should update clip rect on border radius change. target->setAttribute(html_names::kStyleAttr, @@ -1461,8 +1460,10 @@ UpdateAllLifecyclePhasesForTest(); ASSERT_EQ(properties, PaintPropertiesForElement("target")); ASSERT_TRUE(properties->OverflowClip()); - EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 3), + EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 0), properties->OverflowClip()); + EXPECT_CLIP_RECT(FloatRoundedRect(gfx::RectF(8, 8, 8, 8), 3), + properties->InnerBorderRadiusClip()); // We should update clip rect on padding change. target->setAttribute( @@ -1476,7 +1477,7 @@ EXPECT_CLIP_RECT( FloatRoundedRect(gfx::RectF(12, 9, 2, 4), gfx::SizeF(0, 2), gfx::SizeF(1, 2), gfx::SizeF(), gfx::SizeF(1, 0)), - properties->OverflowClip()); + properties->InnerBorderRadiusClip()); } TEST_P(PaintPropertyTreeUpdateTest, OverflowClipUpdateForVideo) {
diff --git a/third_party/blink/renderer/core/style/computed_style.h b/third_party/blink/renderer/core/style/computed_style.h index c4c8546..69aeb25 100644 --- a/third_party/blink/renderer/core/style/computed_style.h +++ b/third_party/blink/renderer/core/style/computed_style.h
@@ -2306,6 +2306,15 @@ OverflowY() == EOverflow::kVisible; } + // Returns true if 'overflow' is 'visible' or 'clip' along both axes. + bool IsOverflowVisibleOrClip() const { + bool overflow_x = + OverflowX() == EOverflow::kVisible || OverflowX() == EOverflow::kClip; + DCHECK(!overflow_x || OverflowY() == EOverflow::kVisible || + OverflowY() == EOverflow::kClip); + return overflow_x; + } + // An overflow value of visible or clip is not a scroll container, all other // values result in a scroll container. Also note that if visible or clip is // set on one axis, then the other axis must also be visible or clip. For
diff --git a/third_party/blink/renderer/extensions/chromeos/chromeos_extensions.cc b/third_party/blink/renderer/extensions/chromeos/chromeos_extensions.cc index b907c269..2f8b986 100644 --- a/third_party/blink/renderer/extensions/chromeos/chromeos_extensions.cc +++ b/third_party/blink/renderer/extensions/chromeos/chromeos_extensions.cc
@@ -29,8 +29,7 @@ void InstallChromeOSExtensions(ScriptState* script_state) { auto* execution_context = ExecutionContext::From(script_state); - if (!execution_context || - !ExecutionContext::From(script_state)->IsServiceWorkerGlobalScope() || + if (!execution_context || !execution_context->IsServiceWorkerGlobalScope() || !RuntimeEnabledFeatures::BlinkExtensionChromeOSEnabled()) { return; } @@ -44,6 +43,12 @@ v8::Local<v8::Value>(), v8::DontEnum, v8::SideEffectType::kHasNoSideEffect) .ToChecked(); + + // Eagerly initialize objects. This is usually done so that they set up a + // connection to the browser to receive events. + if (RuntimeEnabledFeatures::BlinkExtensionChromeOSWindowManagementEnabled()) { + std::ignore = CrosWindowManagement::From(*execution_context); + } } } // namespace
diff --git a/third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_window_management.cc b/third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_window_management.cc index 2467a1a..08d1e84 100644 --- a/third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_window_management.cc +++ b/third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_window_management.cc
@@ -44,7 +44,12 @@ : Supplement(execution_context), ExecutionContextClient(&execution_context), cros_window_management_(&execution_context), - receiver_(this, &execution_context) {} + receiver_(this, &execution_context) { + auto receiver = cros_window_management_.BindNewPipeAndPassReceiver( + execution_context.GetTaskRunner(TaskType::kMiscPlatformAPI)); + execution_context.GetBrowserInterfaceBroker().GetInterface( + std::move(receiver)); +} void CrosWindowManagement::Trace(Visitor* visitor) const { visitor->Trace(cros_window_management_); @@ -73,10 +78,7 @@ } if (!cros_window_management_.is_bound()) { - auto receiver = cros_window_management_.BindNewPipeAndPassReceiver( - execution_context->GetTaskRunner(TaskType::kMiscPlatformAPI)); - execution_context->GetBrowserInterfaceBroker().GetInterface( - std::move(receiver)); + return nullptr; } return cros_window_management_.get(); }
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad_effect_parameters.idl b/third_party/blink/renderer/modules/gamepad/gamepad_effect_parameters.idl index 6d81895..a301326c 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad_effect_parameters.idl +++ b/third_party/blink/renderer/modules/gamepad/gamepad_effect_parameters.idl
@@ -10,4 +10,7 @@ double startDelay = 0.0; double strongMagnitude = 0.0; double weakMagnitude = 0.0; + // https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/main/GamepadHapticsActuatorTriggerRumble/explainer.md + [RuntimeEnabled=WGIGamepadTriggerRumble] double leftTrigger = 0.0; + [RuntimeEnabled=WGIGamepadTriggerRumble] double rightTrigger = 0.0; };
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc index 7558730..e9f74f6 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc +++ b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc
@@ -23,6 +23,7 @@ const char kGamepadHapticActuatorTypeDualRumble[] = "dual-rumble"; const char kGamepadHapticEffectTypeDualRumble[] = "dual-rumble"; +const char kGamepadHapticEffectTypeTriggerRumble[] = "trigger-rumble"; const char kGamepadHapticsResultComplete[] = "complete"; const char kGamepadHapticsResultPreempted[] = "preempted"; @@ -33,6 +34,9 @@ if (type == kGamepadHapticEffectTypeDualRumble) return GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble; + if (type == kGamepadHapticEffectTypeTriggerRumble) + return GamepadHapticEffectType::GamepadHapticEffectTypeTriggerRumble; + NOTREACHED(); return GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble; } @@ -70,11 +74,20 @@ GamepadHapticActuator::~GamepadHapticActuator() = default; void GamepadHapticActuator::SetType(device::GamepadHapticActuatorType type) { + supported_effect_types_.clear(); switch (type) { case device::GamepadHapticActuatorType::kVibration: type_ = kGamepadHapticActuatorTypeVibration; break; + // Currently devices that have trigger rumble support, also have dual-rumble + // support. Moreover, gamepads that support trigger-rumble should also be + // listed as having GamepadHapticActuatorType::kDualRumble, since we want + // to encourage the the use of 'canPlay' method instead. + case device::GamepadHapticActuatorType::kTriggerRumble: + supported_effect_types_.insert(kGamepadHapticEffectTypeTriggerRumble); + [[fallthrough]]; case device::GamepadHapticActuatorType::kDualRumble: + supported_effect_types_.insert(kGamepadHapticEffectTypeDualRumble); type_ = kGamepadHapticActuatorTypeDualRumble; break; default: @@ -90,7 +103,9 @@ if (params->duration() < 0.0 || params->startDelay() < 0.0 || params->strongMagnitude() < 0.0 || params->strongMagnitude() > 1.0 || - params->weakMagnitude() < 0.0 || params->weakMagnitude() > 1.0) { + params->weakMagnitude() < 0.0 || params->weakMagnitude() > 1.0 || + params->leftTrigger() < 0.0 || params->leftTrigger() > 1.0 || + params->rightTrigger() < 0.0 || params->rightTrigger() > 1.0) { ScriptPromise promise = resolver->Promise(); resolver->Resolve(kGamepadHapticsResultInvalidParameter); return promise; @@ -115,7 +130,8 @@ pad_index_, EffectTypeFromString(type), device::mojom::blink::GamepadEffectParameters::New( params->duration(), params->startDelay(), params->strongMagnitude(), - params->weakMagnitude()), + params->weakMagnitude(), params->leftTrigger(), + params->rightTrigger()), std::move(callback)); return resolver->Promise(); @@ -178,6 +194,10 @@ resolver->Resolve(ResultToString(result)); } +bool GamepadHapticActuator::canPlay(const String& type) { + return supported_effect_types_.Contains(type); +} + void GamepadHapticActuator::Trace(Visitor* visitor) const { visitor->Trace(gamepad_dispatcher_); ScriptWrappable::Trace(visitor);
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h index 40f935a4..b896c4ab 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h +++ b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h
@@ -11,6 +11,7 @@ #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h" #include "third_party/blink/renderer/platform/heap/member.h" +#include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -41,6 +42,8 @@ ScriptPromise reset(ScriptState*); + bool canPlay(const String& type); + void Trace(Visitor*) const override; private: @@ -53,6 +56,7 @@ int pad_index_; String type_; bool should_reset_ = false; + HashSet<String> supported_effect_types_; Member<GamepadDispatcher> gamepad_dispatcher_; };
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.idl b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.idl index d5553c8..1448f6b 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.idl +++ b/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.idl
@@ -9,7 +9,8 @@ }; enum GamepadHapticEffectType { - "dual-rumble" + "dual-rumble", + "trigger-rumble" }; enum GamepadHapticsResult { @@ -25,6 +26,7 @@ Exposed=Window ] interface GamepadHapticActuator { readonly attribute GamepadHapticActuatorType type; + [RuntimeEnabled=WGIGamepadTriggerRumble] boolean canPlay(GamepadHapticEffectType type); [CallWith=ScriptState] Promise<GamepadHapticsResult> playEffect( GamepadHapticEffectType type, GamepadEffectParameters params);
diff --git a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc index d5845b0..e45b756 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc +++ b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc
@@ -28,6 +28,7 @@ #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" #include "third_party/blink/renderer/core/html/media/html_media_element.h" #include "third_party/blink/renderer/core/html/media/html_video_element.h" +#include "third_party/blink/renderer/core/layout/layout_video.h" #include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_event.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" @@ -155,13 +156,23 @@ video_element->BindMediaPlayerReceiver( media_player_remote.InitWithNewEndpointAndPassReceiver()); + gfx::Rect video_bounds; + if (auto* layout_video = + DynamicTo<LayoutVideo>(video_element->GetLayoutObject())) { + PhysicalRect content_rect = layout_video->ReplacedContentRect(); + video_bounds = video_element->GetDocument().View()->FrameToViewport( + ToEnclosingRect(layout_video->LocalToAbsoluteRect(content_rect))); + } else { + video_bounds = video_element->BoundsInViewport(); + } + picture_in_picture_service_->StartSession( video_element->GetWebMediaPlayer()->GetDelegateId(), std::move(media_player_remote), video_element->GetWebMediaPlayer()->GetSurfaceId().value(), video_element->GetWebMediaPlayer()->NaturalSize(), ShouldShowPlayPauseButton(*video_element), std::move(session_observer), - video_element->BoundsInViewport(), + video_bounds, WTF::Bind(&PictureInPictureControllerImpl::OnEnteredPictureInPicture, WrapPersistent(this), WrapPersistent(video_element), WrapPersistent(resolver)));
diff --git a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc index 9dc5103..1c46521 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc +++ b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc
@@ -24,12 +24,17 @@ #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/html/media/html_media_test_helper.h" #include "third_party/blink/renderer/core/html/media/html_video_element.h" +#include "third_party/blink/renderer/core/layout/layout_image.h" +#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" +#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/core/testing/wait_for_event.h" +#include "third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_component.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h" #include "third_party/blink/renderer/platform/testing/empty_web_media_player.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" +#include "third_party/blink/renderer/platform/testing/url_test_helpers.h" using ::testing::_; @@ -202,7 +207,7 @@ std::unique_ptr<WebMediaPlayer> web_media_player_; }; -class PictureInPictureControllerTest : public testing::Test { +class PictureInPictureControllerTest : public RenderingTest { public: void SetUp() override { client_ = std::make_unique<PictureInPictureTestWebFrameClient>( @@ -456,7 +461,7 @@ } TEST_F(PictureInPictureControllerTest, - EnterPictureInPictureProvideSourceBounds) { + EnterPictureInPictureProvideSourceBoundsSetToBoundsInViewport) { EXPECT_EQ(nullptr, PictureInPictureControllerImpl::From(GetDocument()) .PictureInPictureElement()); @@ -477,6 +482,60 @@ EXPECT_EQ(Service().source_bounds(), Video()->BoundsInViewport()); } +TEST_F(PictureInPictureControllerTest, + EnterPictureInPictureProvideSourceBoundsSetToReplacedContentRect) { + // Create one image with a size of 10x10px + SkImageInfo raster_image_info = + SkImageInfo::MakeN32Premul(10, 10, SkColorSpace::MakeSRGB()); + sk_sp<SkSurface> surface(SkSurface::MakeRaster(raster_image_info)); + ImageResourceContent* image_content = ImageResourceContent::CreateLoaded( + UnacceleratedStaticBitmapImage::Create(surface->makeImageSnapshot()) + .get()); + + Element* div = GetDocument().CreateRawElement(html_names::kDivTag); + div->setAttribute(html_names::kStyleAttr, + "padding: 100px;" + "width: 150px;" + "height: 150px;" + "padding: 100px;" + "transform: scale(2)"); + GetDocument().body()->AppendChild(div); + div->AppendChild(Video()); + GetDocument().View()->UpdateAllLifecyclePhasesForTest(); + + // Set poster image to video + auto* layout_image = To<LayoutImage>(Video()->GetLayoutObject()); + const char kPosterUrl[] = "http://example.com/foo.jpg"; + url_test_helpers::RegisterMockedErrorURLLoad( + url_test_helpers::ToKURL(kPosterUrl)); + Video()->setAttribute(html_names::kPosterAttr, kPosterUrl); + Video()->setAttribute(html_names::kStyleAttr, + "object-fit: none;" + "height: 150px;" + "width: 150px;"); + layout_image->ImageResource()->SetImageResource(image_content); + GetDocument().View()->UpdateAllLifecyclePhasesForTest(); + + EXPECT_EQ(nullptr, PictureInPictureControllerImpl::From(GetDocument()) + .PictureInPictureElement()); + + WebMediaPlayer* player = Video()->GetWebMediaPlayer(); + EXPECT_CALL(Service(), + StartSession(player->GetDelegateId(), _, TestSurfaceId(), + player->NaturalSize(), true, _, _, _)); + + PictureInPictureControllerImpl::From(GetDocument()) + .EnterPictureInPicture(Video(), /*promise=*/nullptr); + + MakeGarbageCollected<WaitForEvent>(Video(), + event_type_names::kEnterpictureinpicture); + + // Source bounds are expected to match the poster image size, not the bounds + // of the video element. + EXPECT_EQ(Video()->BoundsInViewport(), gfx::Rect(33, 33, 300, 300)); + EXPECT_EQ(Service().source_bounds(), gfx::Rect(173, 173, 20, 20)); +} + TEST_F(PictureInPictureControllerTest, CreateDocumentPictureInPictureWindow) { EXPECT_EQ(nullptr, PictureInPictureControllerImpl::From(GetDocument()) .pictureInPictureWindow());
diff --git a/third_party/blink/renderer/modules/xr/xr_input_source.cc b/third_party/blink/renderer/modules/xr/xr_input_source.cc index 6dddb79..61bdd4cb 100644 --- a/third_party/blink/renderer/modules/xr/xr_input_source.cc +++ b/third_party/blink/renderer/modules/xr/xr_input_source.cc
@@ -525,11 +525,6 @@ if (hit_document) { Frame* hit_frame = hit_document->GetFrame(); DCHECK(hit_frame); - // TODO(crbug.com/1318055): With MPArch there may be multiple main frames - // so we should use IsCrossOriginToOutermostMainFrame when we intend to - // check if any embedded frame (eg, iframe or fenced frame) is - // cross-origin with respect to the outermost main frame. Follow up to - // confirm correctness. if (hit_frame->IsCrossOriginToOutermostMainFrame()) { // Mark the input source as invisible until the primary button is // released.
diff --git a/third_party/blink/renderer/platform/loader/fetch/fetch_api_request_body_mojom_traits.cc b/third_party/blink/renderer/platform/loader/fetch/fetch_api_request_body_mojom_traits.cc index 5a2d49a..ee2a689 100644 --- a/third_party/blink/renderer/platform/loader/fetch/fetch_api_request_body_mojom_traits.cc +++ b/third_party/blink/renderer/platform/loader/fetch/fetch_api_request_body_mojom_traits.cc
@@ -27,14 +27,12 @@ if (auto form_body = mutable_body.FormBody()) { // Here we need to keep the original body, because other members such as // `identifier` are on the form body. - network_body = NetworkResourceRequestBodyFor( - blink::ResourceRequestBody(form_body), - /*allow_http1_for_streaming_upload=*/false); + network_body = + NetworkResourceRequestBodyFor(blink::ResourceRequestBody(form_body)); } else if (mutable_body.StreamBody()) { // Here we don't need to keep the original body (and it's impossible to do // so, because the streaming body is not copyable). - network_body = NetworkResourceRequestBodyFor( - std::move(mutable_body), /*allow_http1_for_streaming_upload=*/false); + network_body = NetworkResourceRequestBodyFor(std::move(mutable_body)); } if (!network_body) { return WTF::Vector<network::DataElement>();
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_request.h b/third_party/blink/renderer/platform/loader/fetch/resource_request.h index f56b225..e26f529 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_request.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_request.h
@@ -512,13 +512,6 @@ // |url|, bool CanDisplay(const KURL&) const; - void SetAllowHTTP1ForStreamingUpload(bool allow) { - allowHTTP1ForStreamingUpload_ = allow; - } - bool AllowHTTP1ForStreamingUpload() const { - return allowHTTP1ForStreamingUpload_; - } - // The original destination of a request passed through by a service worker. network::mojom::RequestDestination GetOriginalDestination() const { return original_destination_; @@ -636,8 +629,6 @@ // the prefetch cache will be restricted to top-level-navigations. bool prefetch_maybe_for_top_level_navigation_ = false; - bool allowHTTP1ForStreamingUpload_ = false; - // This is used when fetching preload header requests from cross-origin // prefetch responses. The browser process uses this token to ensure the // request is cached correctly.
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.cc b/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.cc index c5d8d1392..a5f768d 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.cc +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.cc
@@ -233,8 +233,7 @@ } // namespace scoped_refptr<network::ResourceRequestBody> NetworkResourceRequestBodyFor( - ResourceRequestBody src_body, - bool allow_http1_for_streaming_upload) { + ResourceRequestBody src_body) { scoped_refptr<network::ResourceRequestBody> dest_body; if (const EncodedFormData* form_body = src_body.FormBody().get()) { dest_body = base::MakeRefCounted<network::ResourceRequestBody>(); @@ -247,8 +246,9 @@ dest_body->SetToChunkedDataPipe( ToCrossVariantMojoType(std::move(stream_body)), network::ResourceRequestBody::ReadOnlyOnce(true)); - dest_body->SetAllowHTTP1ForStreamingUpload( - allow_http1_for_streaming_upload); + } + if (dest_body) { + dest_body->SetAllowHTTP1ForStreamingUpload(false); } return dest_body; } @@ -375,8 +375,7 @@ dest->is_favicon = src.IsFavicon(); - dest->request_body = NetworkResourceRequestBodyFor( - std::move(src_body), src.AllowHTTP1ForStreamingUpload()); + dest->request_body = NetworkResourceRequestBodyFor(std::move(src_body)); if (dest->request_body) { DCHECK_NE(dest->method, net::HttpRequestHeaders::kGetMethod); DCHECK_NE(dest->method, net::HttpRequestHeaders::kHeadMethod);
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.h b/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.h index ece8800..14ad606 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.h +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.h
@@ -20,8 +20,7 @@ class ResourceRequestBody; scoped_refptr<network::ResourceRequestBody> NetworkResourceRequestBodyFor( - const ResourceRequestBody src_body, - bool allow_http1_for_streaming_upload); + const ResourceRequestBody src_body); void PopulateResourceRequest(const ResourceRequestHead& src, ResourceRequestBody src_body,
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 38e9c2e..7089064 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -2841,6 +2841,10 @@ depends_on: ["WebXRARModule"], status: "stable", }, + { + name: "WGIGamepadTriggerRumble", + status: "test", + }, // New behavior for window.open's interpretation of the windowFeatures parameter. { name: "WindowOpenNewPopupBehavior",
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc index 1d8c208c..83e431e 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc
@@ -200,11 +200,13 @@ delegate_->OnDeferMainFrameUpdatesChanged(status); } -void LayerTreeView::OnDeferCommitsChanged(bool status, - cc::PaintHoldingReason reason) { +void LayerTreeView::OnDeferCommitsChanged( + bool status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) { if (!delegate_) return; - delegate_->OnDeferCommitsChanged(status, reason); + delegate_->OnDeferCommitsChanged(status, reason, trigger); } void LayerTreeView::BeginMainFrameNotExpectedSoon() {
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h index bd677739..19fc0b2 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h
@@ -74,8 +74,10 @@ void DidUpdateLayers() override; void BeginMainFrame(const viz::BeginFrameArgs& args) override; void OnDeferMainFrameUpdatesChanged(bool) override; - void OnDeferCommitsChanged(bool defer_status, - cc::PaintHoldingReason reason) override; + void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) override; void BeginMainFrameNotExpectedSoon() override; void BeginMainFrameNotExpectedUntil(base::TimeTicks time) override; void UpdateLayerTreeHost() override;
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h index db5785b..1ccf200 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h
@@ -41,8 +41,10 @@ virtual void BeginMainFrame(base::TimeTicks frame_time) = 0; virtual void OnDeferMainFrameUpdatesChanged(bool) = 0; - virtual void OnDeferCommitsChanged(bool defer_status, - cc::PaintHoldingReason reason) = 0; + virtual void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) = 0; // Notifies that the layer tree host has completed a call to // RequestMainFrameUpdate in response to a BeginMainFrame.
diff --git a/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h b/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h index ac46671f..be971bb 100644 --- a/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h +++ b/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h
@@ -28,8 +28,10 @@ const cc::CompositorCommitData& commit_data) override {} void BeginMainFrame(base::TimeTicks frame_time) override {} void OnDeferMainFrameUpdatesChanged(bool) override {} - void OnDeferCommitsChanged(bool defer_status, - cc::PaintHoldingReason reason) override {} + void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) override {} void DidBeginMainFrame() override {} void DidCommitAndDrawCompositorFrame() override {} void WillCommitCompositorFrame() override {}
diff --git a/third_party/blink/renderer/platform/widget/widget_base.cc b/third_party/blink/renderer/platform/widget/widget_base.cc index e256f7f..9dd62a6e 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.cc +++ b/third_party/blink/renderer/platform/widget/widget_base.cc
@@ -515,11 +515,14 @@ widget_input_handler_manager_->OnDeferMainFrameUpdatesChanged(defer); } -void WidgetBase::OnDeferCommitsChanged(bool defer, - cc::PaintHoldingReason reason) { +void WidgetBase::OnDeferCommitsChanged( + bool defer, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) { // The input handler wants to know about the commit status for metric purposes // and to enable/disable input. widget_input_handler_manager_->OnDeferCommitsChanged(defer, reason); + client_->OnDeferCommitsChanged(defer, reason, trigger); } void WidgetBase::DidBeginMainFrame() {
diff --git a/third_party/blink/renderer/platform/widget/widget_base.h b/third_party/blink/renderer/platform/widget/widget_base.h index 8b7d158b..791e9983 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.h +++ b/third_party/blink/renderer/platform/widget/widget_base.h
@@ -149,8 +149,10 @@ const cc::CompositorCommitData& commit_data) override; void BeginMainFrame(base::TimeTicks frame_time) override; void OnDeferMainFrameUpdatesChanged(bool) override; - void OnDeferCommitsChanged(bool defer_status, - cc::PaintHoldingReason reason) override; + void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) override; void DidBeginMainFrame() override; void RequestNewLayerTreeFrameSink( LayerTreeFrameSinkCallback callback) override;
diff --git a/third_party/blink/renderer/platform/widget/widget_base_client.h b/third_party/blink/renderer/platform/widget/widget_base_client.h index 7e98f795..a9d1e081 100644 --- a/third_party/blink/renderer/platform/widget/widget_base_client.h +++ b/third_party/blink/renderer/platform/widget/widget_base_client.h
@@ -64,6 +64,12 @@ base::TimeTicks frame_begin_time, cc::ActiveFrameSequenceTrackers trackers) {} + // Called when the commit is deferred or restarted + virtual void OnDeferCommitsChanged( + bool defer_status, + cc::PaintHoldingReason reason, + absl::optional<cc::PaintHoldingCommitTrigger> trigger) {} + // Return metrics information for the stages of BeginMainFrame. This is // ultimately implemented by Blink's LocalFrameUKMAggregator. It must be a // distinct call from the FrameMetrics above because the BeginMainFrameMetrics
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index d4c3a28..28b1987 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -1802,6 +1802,11 @@ crbug.com/1321217 virtual/document-transition/wpt_internal/document-transition/new-content-with-overflow.html [ Skip ] crbug.com/1303102 virtual/document-transition/wpt_internal/document-transition/no-root-capture.html [ Skip ] +# The following failures are due to a bug in object-view-box implementation specific to layoutng being disabled. +crbug.com/1310798 virtual/document-transition/wpt_internal/document-transition/old-content-object-view-box-clip-path.html [ Failure ] +crbug.com/1310798 virtual/document-transition/wpt_internal/document-transition/old-content-object-view-box-clip-path-reference.html [ Failure ] +crbug.com/1310798 virtual/document-transition/wpt_internal/document-transition/old-content-object-view-box-overflow.html [ Failure ] + # only NGHighlightPainter has the ability to paint decorations added by ::target-text crbug.com/1223918 wpt_internal/css/css-pseudo/target-text-001.html [ Failure ] crbug.com/1223918 virtual/css-highlight-inheritance/wpt_internal/css/css-pseudo/target-text-001.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility b/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility index 76ca1a4..bb9e3f0 100644 --- a/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility +++ b/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility
@@ -145,3 +145,7 @@ wpt_internal/webcodecs/annexb_decoding.https.any.worker.html [ Skip ] wpt_internal/webcodecs/avc_encoder_config.https.any.html [ Skip ] wpt_internal/webcodecs/avc_encoder_config.https.any.worker.html [ Skip ] + +#Sheriff 2022-7-04 crbug.com/1341679 +virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/reinsert.https.html [ Failure Pass ] +virtual/fenced-frame-mparch/wpt_internal/fenced_frame/reinsert.https.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index fdba8e1a..ffd5b07 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -685,6 +685,10 @@ crbug.com/1267498 [ Fuchsia ] paint/invalidation/svg/animated-svg-as-image-transformed-offscreen.html [ Failure ] crbug.com/1267498 [ Fuchsia ] compositing/layer-creation/fixed-position-out-of-view.html [ Failure ] crbug.com/1267498 [ Fuchsia ] transforms/transformed-caret.html [ Failure ] +crbug.com/1321217 [ Fuchsia ] editing/selection/4402375.html [ Failure ] +crbug.com/1321217 [ Fuchsia ] compositing/images/clip-on-directly-composited-image.html [ Failure ] +crbug.com/1321217 [ Fuchsia ] fast/replaced/selection-rect-transform.html [ Failure ] +crbug.com/1321217 [ Fuchsia ] paint/invalidation/selection/selected-replaced.html [ Failure ] # WebGPU tests are only run on GPU bots, so they are skipped by default and run # separately from other Web Tests. @@ -3364,11 +3368,6 @@ crbug.com/626703 [ Win11 ] virtual/conversions-debug-mode/wpt_internal/attribution-reporting/source-registration.sub.https.html?method=a [ Timeout ] crbug.com/626703 [ Win11 ] virtual/conversions-debug-mode/wpt_internal/attribution-reporting/source-registration.sub.https.html?method=fetch&eligible=event-source [ Timeout ] crbug.com/626703 [ Win11 ] virtual/conversions-debug-mode/wpt_internal/attribution-reporting/source-registration.sub.https.html?method=script&eligible [ Timeout ] -crbug.com/626703 [ Mac11 ] virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html [ Failure ] -crbug.com/626703 [ Mac11 ] virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-interpolation-002.https.html [ Failure ] -crbug.com/626703 [ Mac12 ] virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-interpolation-002.https.html [ Failure ] -crbug.com/626703 [ Mac11 ] virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-value-004.https.html [ Failure ] -crbug.com/626703 external/wpt/css/css-text/hyphens/hyphenate-character-005.html [ Failure ] crbug.com/626703 [ Win10.20h2 ] wpt_internal/geolocation-api/watchPosition-page-visibility.https.html [ Timeout ] crbug.com/626703 [ Win11 ] virtual/conversions-debug-mode/wpt_internal/attribution-reporting/debug-key-test.sub.https.html?include=source [ Timeout ] crbug.com/626703 [ Win11 ] virtual/conversions-debug-mode/wpt_internal/attribution-reporting/simple-event-level-report-test.sub.https.html [ Timeout ] @@ -3896,6 +3895,7 @@ crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphenate-character-002.html [ Failure ] crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphenate-character-003.html [ Failure ] crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphenate-character-004.html [ Failure ] +crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphenate-character-005.html [ Failure ] crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphens-vertical-001.html [ Failure ] crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphens-vertical-002.html [ Failure ] crbug.com/1281208 external/wpt/css/css-text/hyphens/hyphens-vertical-003.html [ Failure ] @@ -6262,6 +6262,8 @@ crbug.com/1249176 [ Mac12-arm64 ] fast/js/instanceof-test.html [ Failure Pass ] crbug.com/1249176 [ Mac12-arm64 ] http/tests/devtools/elements/styles-2/nested-pseudo-elements.js [ Failure Pass ] crbug.com/1249176 [ Mac12-arm64 ] media/controls/overflow-menu-focus.html [ Failure Pass ] +# Sheriff 2022-07-04 +crbug.com/1341689 [ Linux ] media/controls/overflow-menu-focus.html [ Failure Pass ] # Following tests timeout on mac11-arm64 crbug.com/1249176 [ Mac11-arm64 ] http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Failure Timeout ] @@ -6439,6 +6441,9 @@ crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-value-015.https.html [ Skip ] crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/parse-input-arguments-004.https.html [ Skip ] crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/parse-input-arguments-012.https.html [ Skip ] +crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/parse-input-arguments-003.https.html [ Skip ] +crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-interpolation-002.https.html [ Skip ] +crbug.com/1123886 virtual/off-main-thread-css-paint/external/wpt/css/css-paint-api/registered-property-value-004.https.html [ Skip ] # Sheriff 2021-09-29 crbug.com/1254163 [ Mac ] virtual/scroll-unification/ietestcenter/css3/bordersbackgrounds/background-attachment-local-scrolling.htm [ Failure ] @@ -7116,7 +7121,7 @@ crbug.com/1339211 [ Mac ] external/wpt/css/css-text-decor/text-decoration-thickness-fixed.html [ Failure Pass ] crbug.com/1339214 [ Mac ] external/wpt/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html [ Failure Pass ] crbug.com/1339293 external/wpt/content-security-policy/media-src/media-src-7_1_2.sub.html [ Skip ] -crbug.com/1339293 [ Linux ] external/wpt/content-security-policy/media-src/media-src-blocked.sub.html [ Failure Pass ] +crbug.com/1339293 [ Linux ] external/wpt/content-security-policy/media-src/media-src-blocked.sub.html [ Failure Pass Timeout ] crbug.com/1339293 [ Linux ] external/wpt/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-load.html [ Failure Pass ] crbug.com/1339293 [ Linux ] external/wpt/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-pause.html [ Failure Pass ] crbug.com/1339293 [ Linux ] external/wpt/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-play.html [ Failure Pass ] @@ -7144,10 +7149,14 @@ crbug.com/1340716 [ Linux ] accessibility/notification-listeners.html [ Skip ] # Sheriff 2022-06-30 -crbug.com/1340781 virtual/android/fullscreen/full-screen-table-section.html [ Skip ] +crbug.com/1340781 fullscreen/full-screen-table-section.html [ Skip ] crbug.com/1327867 http/tests/inspector-protocol/network/initiator-minified.js [ Failure Pass ] # Temporarily disable the tests during the rollout of V8 that fixes the # behaviors that the test cases excersise. crbug.com/1305302 external/wpt/WebIDL/ecmascript-binding/global-object-implicit-this-value-cross-realm.html [ Skip ] crbug.com/1305302 external/wpt/WebIDL/ecmascript-binding/global-object-implicit-this-value.any.html [ Skip ] + +# Sheriff 2022-07-04 +crbug.com/1340981 virtual/conversions-debug-mode/wpt_internal/attribution-reporting/source-registration.sub.https.html [ Timeout ] +crbug.com/1341693 [ Linux ] external/wpt/dom/nodes/MutationObserver-document.html [ Skip ]
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-canvas-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-canvas-ref.html index b7998653..821c2f3 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-canvas-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-canvas-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -42,7 +42,7 @@ .container_view_box_subset_with_scaling { width: 100px; height: 200px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-img-ref.html index 93624ff0..7a4ac60 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-img-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-img-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -42,7 +42,7 @@ .container_view_box_subset_with_scaling { width: 100px; height: 200px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-svg-ref.html index 66ba39e..b6fea80 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-svg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-svg-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -42,7 +42,7 @@ .container_view_box_subset_with_scaling { width: 100px; height: 200px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-video-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-video-ref.html index 9d33d38..174c4d3b 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-video-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-contain-video-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -42,7 +42,7 @@ .container_view_box_subset_with_scaling { width: 100px; height: 200px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-canvas-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-canvas-ref.html index cd1902b6..558cfe8 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-canvas-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-canvas-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset { @@ -32,7 +32,7 @@ .container_view_box_subset_with_position { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset_with_position { @@ -45,7 +45,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-img-ref.html index dd52c52..7e2bdc7 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-img-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-img-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset { @@ -32,7 +32,7 @@ .container_view_box_subset_with_position { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset_with_position { @@ -45,7 +45,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-svg-ref.html index 36f1941..e449c60 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-svg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-svg-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset { @@ -32,7 +32,7 @@ .container_view_box_subset_with_position { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset_with_position { @@ -45,7 +45,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-video-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-video-ref.html index 4ffac13..5f67394f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-video-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-cover-video-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset { @@ -32,7 +32,7 @@ .container_view_box_subset_with_position { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset_with_position { @@ -45,7 +45,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-canvas-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-canvas-ref.html index 8878162..be3b2214 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-canvas-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-canvas-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; background-color: grey; display: inline-block; } @@ -43,7 +43,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -57,7 +57,7 @@ .container_view_box_superset { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -65,7 +65,7 @@ .container_view_box_superset_with_position { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -78,7 +78,7 @@ .container_view_box_superset_with_scaling { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -91,7 +91,7 @@ .container_view_box_intersection { width: 25px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; clip-path: inset(0px 0px 1px 0px); @@ -106,7 +106,7 @@ .container_view_box_no_intersection { width: 25px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-img-ref.html index f6bf841a..32c97c83 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-img-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-img-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; background-color: grey; display: inline-block; } @@ -43,7 +43,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -57,7 +57,7 @@ .container_view_box_superset { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -65,7 +65,7 @@ .container_view_box_superset_with_position { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -78,7 +78,7 @@ .container_view_box_superset_with_scaling { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -91,7 +91,7 @@ .container_view_box_intersection { width: 25px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; clip-path: inset(0px 0px 1px 0px); @@ -106,7 +106,7 @@ .container_view_box_no_intersection { width: 25px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-svg-ref.html index 5b0f9a8..74c98d6 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-svg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-svg-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; background-color: grey; display: inline-block; } @@ -43,7 +43,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -57,7 +57,7 @@ .container_view_box_superset { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -65,7 +65,7 @@ .container_view_box_superset_with_position { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -78,7 +78,7 @@ .container_view_box_superset_with_scaling { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -91,7 +91,7 @@ .container_view_box_intersection { width: 25px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; clip-path: inset(0px 0px 1px 0px); @@ -106,7 +106,7 @@ .container_view_box_no_intersection { width: 25px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-video-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-video-ref.html index 6eeb1b2..eb46dde 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-video-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-fill-video-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; background-color: grey; display: inline-block; } @@ -43,7 +43,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -57,7 +57,7 @@ .container_view_box_superset { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -65,7 +65,7 @@ .container_view_box_superset_with_position { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -78,7 +78,7 @@ .container_view_box_superset_with_scaling { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -91,7 +91,7 @@ .container_view_box_intersection { width: 25px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; clip-path: inset(0px 0px 1px 0px); @@ -106,7 +106,7 @@ .container_view_box_no_intersection { width: 25px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-canvas-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-canvas-ref.html index a1b3f5e..afb695b 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-canvas-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-canvas-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-img-ref.html index b988298b..74d5fc7 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-img-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-img-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-svg-ref.html index b15cb62..da14fa0 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-svg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-svg-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-video-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-video-ref.html index 2aacfa8..f10e1c1 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-video-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-fit-none-video-ref.html
@@ -18,7 +18,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -30,7 +30,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-canvas-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-canvas-ref.html index 56fa32d5..d9942ed 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-canvas-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-canvas-ref.html
@@ -14,7 +14,7 @@ .container_view_box_subset { width: 50px; height: 75px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-img-ref.html index 8db7bc6..9bcdb8ba 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-img-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-img-ref.html
@@ -14,7 +14,7 @@ .container_view_box_subset { width: 50px; height: 75px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-svg-ref.html index c15b12a..c350dcf 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-svg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-svg-ref.html
@@ -14,7 +14,7 @@ .container_view_box_subset { width: 50px; height: 75px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-video-ref.html b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-video-ref.html index e9b5be9..f42fe016 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-video-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/object-view-box-writing-mode-video-ref.html
@@ -14,7 +14,7 @@ .container_view_box_subset { width: 50px; height: 75px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-contain-ref-template.html b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-contain-ref-template.html index 1277b83..2f112495 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-contain-ref-template.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-contain-ref-template.html
@@ -17,7 +17,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -29,7 +29,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -41,7 +41,7 @@ .container_view_box_subset_with_scaling { width: 100px; height: 200px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-cover-ref-template.html b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-cover-ref-template.html index 9d1fb74..2e830c0 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-cover-ref-template.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-cover-ref-template.html
@@ -17,7 +17,7 @@ .container_view_box_subset { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset { @@ -31,7 +31,7 @@ .container_view_box_subset_with_position { width: 40px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset_with_position { @@ -44,7 +44,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-fill-ref-template.html b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-fill-ref-template.html index b26ce3e..574e2912 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-fill-ref-template.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-fill-ref-template.html
@@ -17,7 +17,7 @@ .container_view_box_subset { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -29,7 +29,7 @@ .container_view_box_subset_with_position { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; background-color: grey; display: inline-block; } @@ -42,7 +42,7 @@ .container_view_box_subset_with_scaling { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; clip-path: inset(1px 0px 0px 0px); } @@ -56,7 +56,7 @@ .container_view_box_superset { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -64,7 +64,7 @@ .container_view_box_superset_with_position { width: 100px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -77,7 +77,7 @@ .container_view_box_superset_with_scaling { width: 50px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -90,7 +90,7 @@ .container_view_box_intersection { width: 25px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; clip-path: inset(0px 0px 1px 0px); @@ -105,7 +105,7 @@ .container_view_box_no_intersection { width: 25px; height: 50px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-none-ref-template.html b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-none-ref-template.html index 421a4a0..861d923 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-none-ref-template.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-fit-none-ref-template.html
@@ -17,7 +17,7 @@ .container_view_box_subset { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; } @@ -29,7 +29,7 @@ .container_view_box_subset_with_position { width: 50px; height: 100px; - overflow: clip; + overflow: hidden; display: inline-block; background-color: grey; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-writing-mode-ref-template.html b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-writing-mode-ref-template.html index 2986e5ac..764ba98 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-writing-mode-ref-template.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/support/object-view-box-writing-mode-ref-template.html
@@ -13,7 +13,7 @@ .container_view_box_subset { width: 50px; height: 75px; - overflow: clip; + overflow: hidden; display: inline-block; } .view_box_subset {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-border-radius.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-border-radius.html new file mode 100644 index 0000000..cec70d6b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-border-radius.html
@@ -0,0 +1,19 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow:visible doesn't clip using border-radius</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<link rel="match" href="overflow-img-ref.html"> +<style> + .default { + width: 25px; + height: 50px; + object-fit: none; + overflow: visible; + border-radius: 50%; + object-position: 0% 0%; + } +</style> +<body> +<img class=default src="../css-images/support/exif-orientation-6-ru.jpg"></img> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position-ref.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position-ref.html new file mode 100644 index 0000000..dde966c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position-ref.html
@@ -0,0 +1,16 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<style> + img { + position: relative; + top: 50px; + left: 25px; + } +</style> +<body> +<img src="../css-images/support/exif-orientation-6-ru.jpg"></img> +</body> +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position.html new file mode 100644 index 0000000..67e6feb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-object-position.html
@@ -0,0 +1,16 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements with object-position</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<link rel="match" href="overflow-img-object-position-ref.html"> +<style> + .default { + object-fit: none; + overflow: visible; + object-position: 25px 50px; + } +</style> +<body> +<img class=default src="../css-images/support/exif-orientation-6-ru.jpg"></img> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-ref.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-ref.html new file mode 100644 index 0000000..77643717 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-ref.html
@@ -0,0 +1,9 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<body> +<img src="../css-images/support/exif-orientation-6-ru.jpg"></img> +</body> +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg-ref.html new file mode 100644 index 0000000..e81f5c15 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg-ref.html
@@ -0,0 +1,9 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements rendering svg</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<body> +<img src="../css-images/support/blue-green-red-yellow-50x100.svg"></img> +</body> +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg.html new file mode 100644 index 0000000..15285ca3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img-svg.html
@@ -0,0 +1,18 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements rendering svg</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<link rel="match" href="overflow-img-svg-ref.html"> +<style> + .default { + width: 25px; + height: 50px; + object-fit: none; + object-position: 0% 0%; + overflow: visible; + } +</style> +<body> +<img class=default src="../css-images/support/blue-green-red-yellow-50x100.svg"></img> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img.html b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img.html new file mode 100644 index 0000000..cd9d30ff --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-img.html
@@ -0,0 +1,18 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Verifies overflow applies to img elements</title> +<link rel="help" href="https://drafts.csswg.org/css-overflow/#propdef-overflow"> +<link rel="author" title="Khushal Sagar" href="mailto:khushalsagar@chromium.org"> +<link rel="match" href="overflow-img-ref.html"> +<style> + .default { + width: 25px; + height: 50px; + object-fit: none; + object-position: 0% 0%; + overflow: visible; + } +</style> +<body> +<img class=default src="../css-images/support/exif-orientation-6-ru.jpg"></img> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/basic/request-upload.h2.any.js b/third_party/blink/web_tests/external/wpt/fetch/api/basic/request-upload.h2.any.js index 70d11ec..e89a039 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/api/basic/request-upload.h2.any.js +++ b/third_party/blink/web_tests/external/wpt/fetch/api/basic/request-upload.h2.any.js
@@ -3,6 +3,8 @@ // META: script=/common/utils.js // META: script=/common/get-host-info.sub.js +const duplex = "half"; + function testUpload(desc, url, method, createBody, expectedBody) { const requestInit = {method}; promise_test(async () => { @@ -17,6 +19,17 @@ }, desc); } +function createStream(chunks) { + return new ReadableStream({ + start: (controller) => { + for (const chunk of chunks) { + controller.enqueue(chunk); + } + controller.close(); + } + }); +} + const url = RESOURCES_DIR + "echo-content.h2.py" testUpload("Fetch with POST with empty ReadableStream", url, @@ -49,7 +62,7 @@ "/fetch/connection-pool/resources/network-partition-key.py?" + `status=421&uuid=${token()}&partition_id=${self.origin}` + `&dispatch=check_partition&addcounter=true`, - {method: "POST", body: body}); + {method: "POST", body: body, duplex}); assert_equals(resp.status, 421); const text = await resp.text(); assert_equals(text, "ok. Request was sent 1 times. 1 connections were created."); @@ -82,3 +95,44 @@ assert_equals(await response.text(), 'test', `Response has correct body`); }, "Feature detect for POST with ReadableStream, using request object"); +promise_test(async (t) => { + const body = createStream(["hello"]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing a String"); + +promise_test(async (t) => { + const body = createStream([null]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing null"); + +promise_test(async (t) => { + const body = createStream([33]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing a number"); + +promise_test(async (t) => { + const url = "/fetch/api/resources/redirect.h2.py?location=/common/blank.html"; + const body = createStream([]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload should fail on redirect (302)"); + +promise_test(async (t) => { + const url = "/fetch/api/resources/redirect.h2.py?" + + "redirect_status=303&location=/common/blank.html"; + const body = createStream([]); + const method = "POST"; + const resp = await fetch(url, { method, body, duplex }); + assert_equals(resp.status, 200, 'status'); +}, "Streaming upload should work with 303"); + +promise_test(async (t) => { + const url = "/fetch/api/resources/authentication.py?realm=test"; + const body = createStream([]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload should fail on a 401 response"); +
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/request/request-init-stream.any.js b/third_party/blink/web_tests/external/wpt/fetch/api/request/request-init-stream.any.js index ac78a253..f0ae441a 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/api/request/request-init-stream.any.js +++ b/third_party/blink/web_tests/external/wpt/fetch/api/request/request-init-stream.any.js
@@ -50,7 +50,7 @@ new Request(request, { body: "..." }); }, "Constructing a Request with a Request on which body.getReader().read() is called"); -promsie_test((t) => { +promise_test(async (t) => { const request = new Request("...", { method: "POST", body: "..." }); const reader = request.body.getReader(); await reader.read();
diff --git a/third_party/blink/web_tests/fast/peerconnection/simulcast-munge.html b/third_party/blink/web_tests/fast/peerconnection/simulcast-munge.html new file mode 100644 index 0000000..7bb4588d --- /dev/null +++ b/third_party/blink/web_tests/fast/peerconnection/simulcast-munge.html
@@ -0,0 +1,50 @@ +<!DOCTYPE html> +<html> + <head> + <title>Simulcast manipulation</title> + <script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> + +<script> + +var canvas = document.createElement('canvas'); + +function createConnection() { + var pc = new RTCPeerConnection({ + iceServers: [], + iceTransportPolicy: 'relay' + }); + var encodings = []; + for (var i = 0; i < 2; i++) { + encodings.push({ rid: String.fromCharCode(97 + i) }); + // rid must be alphabetic and unique + } + pc.addTransceiver(canvas.captureStream(0).getTracks()[0], + { sendEncodings: encodings }); + return pc; +} + +function sdp_munge(offer) { + let sdp = offer.sdp; + sdp = sdp.replace(/\r?\na=rid:(.+)\s+send\r?\na=simulcast:send\s+.+;\1/, ''); + // Check that munging worked + assert_false(sdp === offer.sdp); + offer.sdp = sdp; + return offer; +} + +promise_test(async t => { + const pc = createConnection(); + const offer = await pc.createOffer(); + const sender = pc.getSenders()[0]; + const parametersBefore = sender.getParameters(); + const munged_offer = sdp_munge(offer); + await pc.setLocalDescription(munged_offer); + const parametersAfter = sender.getParameters(); + assert_equals(parametersBefore.encodings.length, + parametersAfter.encodings.length); +}, "Munging SDP simulcast should not cause changes to simulcast envelope") + +</script> +</head> +</html>
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-image-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-image-expected.txt new file mode 100644 index 0000000..39313af --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-image-expected.txt
@@ -0,0 +1,31 @@ +EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification +EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification +EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x600 + LayoutBlockFlow {HTML} at (0,0) size 800x600 + LayoutBlockFlow {BODY} at (8,8) size 784x584 + LayoutBlockFlow {P} at (0,0) size 784x20 + LayoutText {#text} at (0,0) size 354x19 + text run at (0,0) width 354: "This is an automatic test of copying an image document." + LayoutBlockFlow {P} at (0,36) size 784x40 + LayoutText {#text} at (0,0) size 757x39 + text run at (0,0) width 757: "To perform this test manually, click once in the image frame, choose Edit -> Copy then click in the red box and paste the" + text run at (0,20) width 355: "image. If the image pastes successfully the test is passed." + LayoutBlockFlow (anonymous) at (0,92) size 784x154 + LayoutText {#text} at (0,0) size 0x0 + LayoutBlockFlow {DIV} at (0,246) size 784x131 [border: (2px solid #FF0000)] + LayoutText {#text} at (0,0) size 0x0 +layer at (8,100) size 304x154 + LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] + layer at (0,0) size 300x150 + LayoutView at (0,0) size 300x150 + layer at (0,0) size 300x150 + LayoutBlockFlow {HTML} at (0,0) size 300x150 + LayoutBlockFlow {BODY} at (0,0) size 300x150 + layer at (0,0) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (22,268) size 76x103 + LayoutImage {IMG} at (14,14) size 76x103 +caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-oriented-image-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-oriented-image-expected.txt index afd6bb09..69b8e928 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-oriented-image-expected.txt +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/pasteboard/copy-standalone-oriented-image-expected.txt
@@ -16,7 +16,6 @@ LayoutBlockFlow (anonymous) at (0,92) size 784x154 LayoutText {#text} at (0,0) size 0x0 LayoutBlockFlow {DIV} at (0,246) size 784x128 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 50x100 LayoutText {#text} at (0,0) size 0x0 layer at (8,100) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] @@ -25,5 +24,8 @@ layer at (0,0) size 300x150 LayoutBlockFlow {HTML} at (0,0) size 300x150 LayoutBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 50x100 + layer at (0,0) size 50x100 + LayoutImage {IMG} at (0,0) size 50x100 +layer at (22,268) size 50x100 + LayoutImage {IMG} at (14,14) size 50x100 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/4402375-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/4402375-expected.txt index 25fb92f..191188af 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/4402375-expected.txt +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/4402375-expected.txt
@@ -19,10 +19,11 @@ text run at (413,0) width 330: "The image should not be selected, and should not be" text run at (0,20) width 598: "included in the selection rect (you won't see the selection rect when you run this test manually)." LayoutBlockFlow {DIV} at (0,130) size 784x20 - LayoutImage (floating) {IMG} at (708,0) size 76x103 LayoutText {#text} at (0,0) size 178x19 text run at (0,0) width 178: "This text should be selected." layer at (8,64) size 784x2 clip at (0,0) size 0x0 LayoutBlockFlow {HR} at (0,56) size 784x2 [border: (1px inset #EEEEEE)] +layer at (716,138) size 76x103 + LayoutImage (floating) {IMG} at (708,0) size 76x103 selection start: position 0 of child 1 {#text} of child 6 {DIV} of body selection end: position 29 of child 1 {#text} of child 6 {DIV} of body
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/drag-to-contenteditable-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/drag-to-contenteditable-iframe-expected.txt index f8b58193..4ccd14c 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/drag-to-contenteditable-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/drag-to-contenteditable-iframe-expected.txt
@@ -9,7 +9,6 @@ LayoutBlockFlow (anonymous) at (0,0) size 800x213 LayoutText {#text} at (208,193) size 4x19 text run at (208,193) width 4: " " - LayoutImage {IMG} at (212,105) size 76x103 LayoutText {#text} at (0,0) size 0x0 LayoutBlockFlow {UL} at (0,229) size 800x20 LayoutListItem {LI} at (40,0) size 760x20 @@ -23,5 +22,8 @@ layer at (0,0) size 200x200 LayoutBlockFlow {HTML} at (0,0) size 200x200 LayoutBlockFlow {BODY} at (8,8) size 184x184 [bgcolor=#FFFFE0] - LayoutImage {IMG} at (0,0) size 76x103 LayoutText {#text} at (0,0) size 0x0 + layer at (8,8) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (212,105) size 76x103 + LayoutImage {IMG} at (212,105) size 76x103
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/select-missing-image-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/select-missing-image-expected.txt new file mode 100644 index 0000000..65e1757e --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/editing/selection/select-missing-image-expected.txt
@@ -0,0 +1,20 @@ +EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification +EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x600 + LayoutBlockFlow {HTML} at (0,0) size 800x600 + LayoutBlockFlow {BODY} at (8,8) size 784x584 + LayoutBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] + LayoutText {#text} at (0,0) size 0x0 +layer at (22,22) size 550x100 + LayoutBlockFlow {IMG} at (14,14) size 550x100 +layer at (22,22) size 550x100 clip at (23,23) size 548x98 + LayoutBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] + LayoutInline {SPAN} at (18,2) size 480x27 + LayoutText {#text} at (18,2) size 480x27 + text run at (18,2) width 480: "Should see selection tint over this missing image." +layer at (24,24) size 16x16 + LayoutImage (floating) {IMG} at (2,2) size 16x16 +selection start: position 0 of child 1 {IMG} of child 1 {DIV} of body +selection end: position 1 of child 1 {IMG} of child 1 {DIV} of body
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-big-endian-expected.png b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-big-endian-expected.png index 358b974..0807cdb8 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-big-endian-expected.png +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-big-endian-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-little-endian-expected.png b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-little-endian-expected.png index 358b974..0807cdb8 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-little-endian-expected.png +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/encoding/utf-16-little-endian-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/paint/invalidation/non-text-link-invalidation-optimization-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/paint/invalidation/non-text-link-invalidation-optimization-expected.txt index 23259046..3518d8a2 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/paint/invalidation/non-text-link-invalidation-optimization-expected.txt +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/paint/invalidation/non-text-link-invalidation-optimization-expected.txt
@@ -6,11 +6,9 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [164, 8, 145, 19], - [75, 8, 61, 19], + [75, 8, 234, 19], [8, 8, 57, 19], [353, 8, 52, 19], - [136, 8, 28, 19], [319, 8, 24, 19], [343, 13, 10, 10], [309, 13, 10, 10],
diff --git a/third_party/blink/web_tests/flag-specific/disable-site-isolation-trials/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt b/third_party/blink/web_tests/flag-specific/disable-site-isolation-trials/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt deleted file mode 100644 index 79949e23..0000000 --- a/third_party/blink/web_tests/flag-specific/disable-site-isolation-trials/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/flag-specific/highdpi/compositing/backface-visibility/backface-visibility-image-expected.png b/third_party/blink/web_tests/flag-specific/highdpi/compositing/backface-visibility/backface-visibility-image-expected.png index ecf48a8..d252643 100644 --- a/third_party/blink/web_tests/flag-specific/highdpi/compositing/backface-visibility/backface-visibility-image-expected.png +++ b/third_party/blink/web_tests/flag-specific/highdpi/compositing/backface-visibility/backface-visibility-image-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/highdpi/images/yuv-decode-eligible/color-profile-border-radius-expected.png b/third_party/blink/web_tests/flag-specific/highdpi/images/yuv-decode-eligible/color-profile-border-radius-expected.png index 9ce794ef..faef7666 100644 --- a/third_party/blink/web_tests/flag-specific/highdpi/images/yuv-decode-eligible/color-profile-border-radius-expected.png +++ b/third_party/blink/web_tests/flag-specific/highdpi/images/yuv-decode-eligible/color-profile-border-radius-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/highdpi/paint/invalidation/image/image-resize-expected.txt b/third_party/blink/web_tests/flag-specific/highdpi/paint/invalidation/image/image-resize-expected.txt index 42a2b153..8354ad6d 100644 --- a/third_party/blink/web_tests/flag-specific/highdpi/paint/invalidation/image/image-resize-expected.txt +++ b/third_party/blink/web_tests/flag-specific/highdpi/paint/invalidation/image/image-resize-expected.txt
@@ -6,8 +6,8 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [0, 75, 225, 225], - [0, 75, 150, 300] + [0, 75, 150, 300], + [150, 75, 75, 225] ] } ]
diff --git a/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/images/rendering-broken-images-expected.png b/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/images/rendering-broken-images-expected.png index 4b647dcb..7eed5d9 100644 --- a/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/images/rendering-broken-images-expected.png +++ b/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/images/rendering-broken-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/gamepad/gamepad-vibration.html b/third_party/blink/web_tests/gamepad/gamepad-vibration.html index 69ee48b..410b6c1 100644 --- a/third_party/blink/web_tests/gamepad/gamepad-vibration.html +++ b/third_party/blink/web_tests/gamepad/gamepad-vibration.html
@@ -48,6 +48,8 @@ Function.prototype); assert_equals(gamepad.vibrationActuator.reset.__proto__, Function.prototype); + assert_equals(gamepad.vibrationActuator.canPlay.__proto__, + Function.prototype); }, "validate gamepad haptic actuator API"); promise_test(async (t) => { @@ -127,5 +129,44 @@ await disconnectPromise; }, "vibration actuator is null for disconnected gamepad"); +promise_test(async (t) => { + // Connect a gamepad with a dual-rumble vibration actuator. + let connectPromise = ongamepadconnected(t); + gamepadController.connect(0); + gamepadController.setId(0, "Xbox 360"); + gamepadController.setDualRumbleVibrationActuator(0, true); + gamepadController.dispatchConnected(0); + await connectPromise; + + // Connect a gamepad with trigger-rumble vibration actuator. + connectPromise = ongamepadconnected(t); + gamepadController.connect(1); + gamepadController.setId(1, "Xbox Elite"); + gamepadController.setTriggerRumbleVibrationActuator(1, true); + gamepadController.dispatchConnected(1); + await connectPromise; + + let dualRumbleGamepad = navigator.getGamepads()[0]; + assert_true(dualRumbleGamepad.vibrationActuator.canPlay("dual-rumble")); + assert_false(dualRumbleGamepad.vibrationActuator.canPlay("trigger-rumble")); + + let triggerRumbleGamepad = navigator.getGamepads()[1]; + assert_true(triggerRumbleGamepad.vibrationActuator.canPlay("dual-rumble")); + assert_true(triggerRumbleGamepad.vibrationActuator.canPlay("trigger-rumble")); +}, "canPlay should report correct the gamepad capabilites"); + +promise_test(async (t) => { + // Connect a gamepad with trigger-rumble vibration actuator. + connectPromise = ongamepadconnected(t); + gamepadController.connect(0); + gamepadController.setId(0, "Xbox Elite"); + gamepadController.setTriggerRumbleVibrationActuator(0, true); + gamepadController.dispatchConnected(0); + await connectPromise; + + let triggerRumbleGamepad = navigator.getGamepads()[0]; + assert_throws_js(TypeError, () => triggerRumbleGamepad.vibrationActuator.canPlay("unknown-rumble")); +}, "canPlay should throw a TypeError for unknown effect types"); + </script> </body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/script-tests/fetch_upload.js b/third_party/blink/web_tests/http/tests/fetch/script-tests/fetch_upload.js deleted file mode 100644 index 9e123d6..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/script-tests/fetch_upload.js +++ /dev/null
@@ -1,217 +0,0 @@ -if (self.importScripts) { - importScripts('../resources/fetch-test-helpers.js'); -} - -var {BASE_ORIGIN, OTHER_ORIGIN} = get_fetch_test_options(); - -function fetch_echo(stream) { - return fetch('/serviceworker/resources/fetch-echo-body.php', { - method: 'POST', - body: stream, - mode: 'same-origin', - allowHTTP1ForStreamingUpload: true - }); -} - -promise_test(async (t) => { - await promise_rejects_js( - t, TypeError, fetch('/serviceworker/resources/fetch-echo-body.php', { - method: 'POST', - body: create_stream([new Uint8Array(0)]), - allowHTTP1ForStreamingUpload: false - })); -}, 'AllowHTTP1:false makes fetch failed over HTTP/1.'); - -function fetch_echo_body(stream) { - return fetch_echo(stream).then(response => response.text()); -} - -function create_stream(contents) { - return new ReadableStream({ - start: controller => { - for (obj of contents) { - controller.enqueue(obj); - } - controller.close(); - } - }); -} - -promise_test(async () => { - const stream = - create_stream(['Foo', 'Bar']).pipeThrough(new TextEncoderStream()); - const text = await fetch_echo_body(stream); - assert_equals(text, 'FooBar'); -}, 'Fetch with ReadableStream body with Uint8Array'); - -promise_test(async () => { - const stream = create_stream([new Uint8Array(0)]); - const text = await fetch_echo_body(stream); - assert_equals(text, ''); -}, 'Fetch with ReadableStream body with empty Uint8Array'); - -function random_values_array(length) { - const array = new Uint8Array(length); - // crypto.getRandomValues has a quota. See - // https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues. - const cryptoQuota = 65535; - let index = 0; - const buffer = array.buffer; - while (index < buffer.byteLength) { - const bufferView = array.subarray(index, index + cryptoQuota); - crypto.getRandomValues(bufferView); - index += cryptoQuota; - } - return array; -} - -function hash256(array) { - return crypto.subtle.digest('SHA-256', array); -} - -function compare(a, b) { - if (a.length != b.length) - return [false, 'length is not equal']; - for (let i = 0; - 1 < i; i -= 1) { - if ((a[i] !== b[i])) - return [false, `a[${i}](${a[i]}) != b[${i}](${b[i]})`]; - } - return [true, '']; -} - -async function compare_long_array(a, b, description) { - const a_hash = await hash256(a); - const b_hash = await hash256(b); - const [eq, fail_reason] = compare(a_hash, b_hash); - if (eq) - return; - - const [raw_eq, raw_fail_reason] = compare(a, b); - assert_false(raw_eq); - assert_(false, description + ': ' + raw_fail_reason); -} - -async function test_echo_long_array(upload_body, expected_array) { - const response = await fetch_echo(upload_body); - const reader = response.body.getReader(); - let index = 0; - while (index < expected_array.length) { - const chunk = await reader.read(); - assert_false(chunk.done, `chunk.done@${index}/${expected_array.length}`); - const chunk_length = chunk.value.length; - await compare_long_array( - chunk.value, expected_array.subarray(index, index + chunk_length), - `Array of [${index}, ${index + chunk_length - 1}] should be same.`); - index += chunk_length; - } - const final_chunk = await reader.read(); - assert_true(final_chunk.done, 'final_chunk.done'); -} - -promise_test(async () => { - const length = 1000 * 1000; // 1Mbytes - const array = random_values_array(length); - const stream = create_stream([array]); - await test_echo_long_array(stream, array); -}, 'Fetch with ReadableStream body with 1Mbytes Uint8Array'); - -promise_test(async () => { - const length = 1000 * 1000; // 1 Mbytes - const array = random_values_array(length); - await test_echo_long_array(array, array); -}, 'Fetch with Array body with 1 Mbytes Uint8Array'); - -promise_test(async (t) => { - const stream = create_stream(['Foobar']); - await promise_rejects_js(t, TypeError, fetch_echo(stream)); -}, 'Fetch with ReadableStream body containing String should fail'); - -promise_test(async (t) => { - const stream = create_stream([null]); - await promise_rejects_js(t, TypeError, fetch_echo(stream)); -}, 'Fetch with ReadableStream body containing null should fail'); - -promise_test(async (t) => { - const stream = create_stream([42]); - await promise_rejects_js(t, TypeError, fetch_echo(stream)); -}, 'Fetch with ReadableStream body containing number should fail'); - -function create_foo_stream() { - return create_stream(['Foo']).pipeThrough(new TextEncoderStream()); -} - -function fetch_redirect(status) { - const redirect_target_url = - BASE_ORIGIN + '/fetch/resources/fetch-status.php?status=200'; - const redirect_original_url = BASE_ORIGIN + - '/serviceworker/resources/redirect.php?Redirect=' + redirect_target_url; - return fetch(redirect_original_url + `&Status=${status}`, { - method: 'POST', - body: create_foo_stream(), - allowHTTP1ForStreamingUpload: true - }); -} - -promise_test(async (t) => { - await fetch_redirect(303); -}, 'Fetch upload stream should success on 303(See Other) code'); - -promise_test(async (t) => { - await promise_rejects_js(t, TypeError, fetch_redirect(307)); -}, 'Fetch upload stream should fail on non-303 redirect code'); - -promise_test(async () => { - await fetch('/serviceworker/resources/fetch-access-control.php?AuthFail', { - method: 'POST', - body: 'foo', - }); -}, 'Upload text with 401 Unauthorized response should success.'); - -promise_test(async (t) => { - await promise_rejects_js( - t, TypeError, - fetch('/serviceworker/resources/fetch-access-control.php?AuthFail', { - method: 'POST', - body: create_foo_stream(), - mode: 'same-origin', - allowHTTP1ForStreamingUpload: true - })); -}, 'Upload streaming with 401 Unauthorized response should fail.'); - -function report(content) { - return content; -} - -promise_test(async () => { - const request_url = OTHER_ORIGIN + - '/serviceworker/resources/fetch-access-control.php?' + - `ACAOrigin=*&PACAOrigin=*` + - `&PACAHeaders=*&ACAHeaders=*&PreflightTest` + - `&PACMAge=600&Token=${Date.now()}` - const response_text = await fetch(request_url, { - method: 'POST', - body: 'content a', - mode: 'cors', - allowHTTP1ForStreamingUpload: true - }).then(r => r.text()); - const report_json = eval(response_text); - assert_false(report_json['did_preflight'], 'Should not trigger preflight'); -}, 'Uploading text w/o header does not trigger preflight'); - -promise_test(async () => { - const request_url = OTHER_ORIGIN + - '/serviceworker/resources/fetch-access-control.php?' + - `ACAOrigin=*&PACAOrigin=*` + - `&PACAHeaders=*&ACAHeaders=*&PreflightTest` + - `&PACMAge=600&Token=${Date.now()}` - const response_text = await fetch(request_url, { - method: 'POST', - body: create_foo_stream(), - mode: 'cors', - allowHTTP1ForStreamingUpload: true - }).then(r => r.text()); - const report_json = eval(response_text); - assert_true(report_json['did_preflight'], 'Should preflight'); -}, 'Uploading stream always trigger preflight'); - -done();
diff --git a/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload-base-https-other-https.html b/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload-base-https-other-https.html deleted file mode 100644 index a828aff..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload-base-https-other-https.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - service_worker_test( - '../script-tests/fetch_upload.js?-base-https-other-https', - 'fetch_upload-serviceworker'); - t.done(); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload.html b/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload.html deleted file mode 100644 index 139fa216..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/serviceworker/fetch_upload.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - service_worker_test( - '../script-tests/fetch_upload.js?', - 'fetch_upload-serviceworker'); - t.done(); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload-base-https-other-https.html b/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload-base-https-other-https.html deleted file mode 100644 index 83ef445..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload-base-https-other-https.html +++ /dev/null
@@ -1,31 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/fetch/resources/fetch-test-helpers.js"></script> -<script src = "/streams/resources/rs-utils.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - var script = document.createElement('script'); - script.src = '../script-tests/fetch_upload.js?-base-https-other-https'; - script.addEventListener( - 'error', - function() { unreached_rejection(t); }); - script.addEventListener( - 'load', - function() { t.done(); }); - document.body.appendChild(script); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload.html b/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload.html deleted file mode 100644 index 70441fd5..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/window/fetch_upload.html +++ /dev/null
@@ -1,31 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/fetch/resources/fetch-test-helpers.js"></script> -<script src = "/streams/resources/rs-utils.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - var script = document.createElement('script'); - script.src = '../script-tests/fetch_upload.js?'; - script.addEventListener( - 'error', - function() { unreached_rejection(t); }); - script.addEventListener( - 'load', - function() { t.done(); }); - document.body.appendChild(script); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload-base-https-other-https.html b/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload-base-https-other-https.html deleted file mode 100644 index 91f30a1..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload-base-https-other-https.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - fetch_tests_from_worker( - new Worker('../script-tests/fetch_upload.js?-base-https-other-https')); - t.done(); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload.html b/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload.html deleted file mode 100644 index 7519e66..0000000 --- a/third_party/blink/web_tests/http/tests/fetch/workers/fetch_upload.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!doctype html> -<head> -<meta name="timeout" content="long"></meta> -<script src = "/resources/get-host-info.js?pipe=sub"></script> -<script src = "/resources/testharness.js"></script> -<script src = "/resources/testharnessreport.js"></script> -<script src = "/fetch/resources/fetch-test-options.js"></script> -<script src = "/serviceworker/resources/test-helpers.js"></script> -</head> -<body> -<script> -var options = get_fetch_test_options(); -function start(t) { - fetch_tests_from_worker( - new Worker('../script-tests/fetch_upload.js?')); - t.done(); -} -function init() { - return Promise.resolve(); -} -</script> -<script src = "../resources/init.js"></script> -</body>
diff --git a/third_party/blink/web_tests/images/rendering-broken-block-flow-images.html b/third_party/blink/web_tests/images/rendering-broken-block-flow-images.html index 8d8448a2..ac182c6 100644 --- a/third_party/blink/web_tests/images/rendering-broken-block-flow-images.html +++ b/third_party/blink/web_tests/images/rendering-broken-block-flow-images.html
@@ -2,6 +2,7 @@ <style> img { display: block; + overflow: visible; } </style> <p>crbug.com/644802: Render alt text per html5 spec</p>
diff --git a/third_party/blink/web_tests/platform/fuchsia/compositing/images/clip-on-directly-composited-image-expected.txt b/third_party/blink/web_tests/platform/fuchsia/compositing/images/clip-on-directly-composited-image-expected.txt new file mode 100644 index 0000000..1c9bba9 --- /dev/null +++ b/third_party/blink/web_tests/platform/fuchsia/compositing/images/clip-on-directly-composited-image-expected.txt
@@ -0,0 +1,29 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutImage (positioned) IMG class='composited'", + "position": [10, 10], + "bounds": [140, 140], + "contentsOpaqueForText": true, + "transform": 1 + } + ], + "transforms": [ + { + "id": 1, + "transform": [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [200, 13, 0, 1] + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.txt b/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.txt new file mode 100644 index 0000000..1b47dc1 --- /dev/null +++ b/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.txt
@@ -0,0 +1,27 @@ +EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x600 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 131x19 + text run at (0,0) width 131: "This is a testcase for " + LayoutInline {A} at (131,0) size 149x19 [color=#0000EE] + LayoutText {#text} at (131,0) size 149x19 + text run at (131,0) width 149: "rdar://problem/4402375" + LayoutText {#text} at (0,0) size 761x39 + text run at (280,0) width 481: " \"REGRESSION (417.8-TOT): finding text sometimes also selects previous" + text run at (0,20) width 137: "image (5127) (6451)\"" + LayoutNGBlockFlow {P} at (0,74) size 784x40 + LayoutText {#text} at (0,0) size 743x39 + text run at (0,0) width 743: "This test uses a right aligned image next to some left aligned text. The image should not be selected, and should not be" + text run at (0,20) width 598: "included in the selection rect (you won't see the selection rect when you run this test manually)." + LayoutNGBlockFlow {DIV} at (0,130) size 784x20 + LayoutImage (floating) {IMG} at (708,0) size 76x103 + LayoutText {#text} at (0,0) size 178x19 + text run at (0,0) width 178: "This text should be selected." +layer at (8,64) size 784x2 clip at (0,0) size 0x0 + LayoutNGBlockFlow {HR} at (0,56) size 784x2 [border: (1px inset #EEEEEE)] +selection start: position 0 of child 1 {#text} of child 6 {DIV} of body +selection end: position 29 of child 1 {#text} of child 6 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/fuchsia/paint/invalidation/selection/selected-replaced-expected.txt b/third_party/blink/web_tests/platform/fuchsia/paint/invalidation/selection/selected-replaced-expected.txt new file mode 100644 index 0000000..9613d4d --- /dev/null +++ b/third_party/blink/web_tests/platform/fuchsia/paint/invalidation/selection/selected-replaced-expected.txt
@@ -0,0 +1,15 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "invalidations": [ + [8, 132, 214, 232], + [8, 52, 214, 232] + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/platform/generic/compositing/images/clip-on-directly-composited-image-expected.txt b/third_party/blink/web_tests/platform/generic/compositing/images/clip-on-directly-composited-image-expected.txt index 1c9bba9..d8c247b 100644 --- a/third_party/blink/web_tests/platform/generic/compositing/images/clip-on-directly-composited-image-expected.txt +++ b/third_party/blink/web_tests/platform/generic/compositing/images/clip-on-directly-composited-image-expected.txt
@@ -8,8 +8,7 @@ }, { "name": "LayoutImage (positioned) IMG class='composited'", - "position": [10, 10], - "bounds": [140, 140], + "bounds": [200, 200], "contentsOpaqueForText": true, "transform": 1 }
diff --git a/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-expected.png b/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-expected.png index b52a953..19553e16 100644 --- a/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-expected.png +++ b/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-with-opacity-expected.png index c081fa9..9bc8619 100644 --- a/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/blink/web_tests/platform/generic/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any-expected.txt deleted file mode 100644 index b3ca1fb..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS Fetch with POST with empty ReadableStream -PASS Fetch with POST with ReadableStream -FAIL Fetch with POST with ReadableStream on 421 response should return the response and not retry. promise_test: Unhandled rejection with value: object "TypeError: Failed to fetch" -PASS Feature detect for POST with ReadableStream -PASS Feature detect for POST with ReadableStream, using request object -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.serviceworker-expected.txt deleted file mode 100644 index b3ca1fb..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.serviceworker-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS Fetch with POST with empty ReadableStream -PASS Fetch with POST with ReadableStream -FAIL Fetch with POST with ReadableStream on 421 response should return the response and not retry. promise_test: Unhandled rejection with value: object "TypeError: Failed to fetch" -PASS Feature detect for POST with ReadableStream -PASS Feature detect for POST with ReadableStream, using request object -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.sharedworker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.sharedworker-expected.txt deleted file mode 100644 index b3ca1fb..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.sharedworker-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS Fetch with POST with empty ReadableStream -PASS Fetch with POST with ReadableStream -FAIL Fetch with POST with ReadableStream on 421 response should return the response and not retry. promise_test: Unhandled rejection with value: object "TypeError: Failed to fetch" -PASS Feature detect for POST with ReadableStream -PASS Feature detect for POST with ReadableStream, using request object -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.worker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.worker-expected.txt deleted file mode 100644 index b3ca1fb..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/basic/request-upload.h2.any.worker-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS Fetch with POST with empty ReadableStream -PASS Fetch with POST with ReadableStream -FAIL Fetch with POST with ReadableStream on 421 response should return the response and not retry. promise_test: Unhandled rejection with value: object "TypeError: Failed to fetch" -PASS Feature detect for POST with ReadableStream -PASS Feature detect for POST with ReadableStream, using request object -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any-expected.txt index 79949e23..c500108 100644 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any-expected.txt +++ b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any-expected.txt
@@ -1,4 +1,26 @@ This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules +PASS Constructing a Request with a stream holds the original object. +PASS Constructing a Request with a stream on which getReader() is called +PASS Constructing a Request with a stream on which read() is called +PASS Constructing a Request with a stream on which read() and releaseLock() are called +PASS Constructing a Request with a Request on which body.getReader() is called +PASS Constructing a Request with a Request on which body.getReader().read() is called +PASS Constructing a Request with a Request on which read() and releaseLock() are called +PASS It is OK to omit .duplex when the body is null. +PASS It is OK to omit .duplex when the body is a string. +PASS It is OK to omit .duplex when the body is a Uint8Array. +PASS It is OK to omit .duplex when the body is a Blob. +FAIL It is error to omit .duplex when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body })" did not throw +PASS It is OK to set .duplex = 'half' when the body is null. +PASS It is OK to set .duplex = 'half' when the body is a string. +PASS It is OK to set .duplex = 'half' when the body is a Uint8Array. +PASS It is OK to set .duplex = 'half' when the body is a Blob. +PASS It is OK to set .duplex = 'half' when the body is a ReadableStream. +FAIL It is error to set .duplex = 'full' when the body is null. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a string. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Uint8Array. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Blob. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +PASS It is OK to omit duplex when init.body is not given and input.body is given. Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt index 83aaeca..c500108 100644 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt +++ b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt
@@ -1,4 +1,26 @@ This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Unhandled rejection: Failed to register a ServiceWorker for scope ('https://web-platform.test:8444/fetch/api/request/does/not/exist') with script ('https://web-platform.test:8444/fetch/api/request/request-init-stream.any.worker.js'): ServiceWorker script evaluation failed +PASS Constructing a Request with a stream holds the original object. +PASS Constructing a Request with a stream on which getReader() is called +PASS Constructing a Request with a stream on which read() is called +PASS Constructing a Request with a stream on which read() and releaseLock() are called +PASS Constructing a Request with a Request on which body.getReader() is called +PASS Constructing a Request with a Request on which body.getReader().read() is called +PASS Constructing a Request with a Request on which read() and releaseLock() are called +PASS It is OK to omit .duplex when the body is null. +PASS It is OK to omit .duplex when the body is a string. +PASS It is OK to omit .duplex when the body is a Uint8Array. +PASS It is OK to omit .duplex when the body is a Blob. +FAIL It is error to omit .duplex when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body })" did not throw +PASS It is OK to set .duplex = 'half' when the body is null. +PASS It is OK to set .duplex = 'half' when the body is a string. +PASS It is OK to set .duplex = 'half' when the body is a Uint8Array. +PASS It is OK to set .duplex = 'half' when the body is a Blob. +PASS It is OK to set .duplex = 'half' when the body is a ReadableStream. +FAIL It is error to set .duplex = 'full' when the body is null. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a string. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Uint8Array. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Blob. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +PASS It is OK to omit duplex when init.body is not given and input.body is given. Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt index 79949e23..c500108 100644 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt +++ b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.sharedworker-expected.txt
@@ -1,4 +1,26 @@ This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules +PASS Constructing a Request with a stream holds the original object. +PASS Constructing a Request with a stream on which getReader() is called +PASS Constructing a Request with a stream on which read() is called +PASS Constructing a Request with a stream on which read() and releaseLock() are called +PASS Constructing a Request with a Request on which body.getReader() is called +PASS Constructing a Request with a Request on which body.getReader().read() is called +PASS Constructing a Request with a Request on which read() and releaseLock() are called +PASS It is OK to omit .duplex when the body is null. +PASS It is OK to omit .duplex when the body is a string. +PASS It is OK to omit .duplex when the body is a Uint8Array. +PASS It is OK to omit .duplex when the body is a Blob. +FAIL It is error to omit .duplex when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body })" did not throw +PASS It is OK to set .duplex = 'half' when the body is null. +PASS It is OK to set .duplex = 'half' when the body is a string. +PASS It is OK to set .duplex = 'half' when the body is a Uint8Array. +PASS It is OK to set .duplex = 'half' when the body is a Blob. +PASS It is OK to set .duplex = 'half' when the body is a ReadableStream. +FAIL It is error to set .duplex = 'full' when the body is null. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a string. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Uint8Array. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Blob. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +PASS It is OK to omit duplex when init.body is not given and input.body is given. Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.worker-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.worker-expected.txt index 79949e23..c500108 100644 --- a/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.worker-expected.txt +++ b/third_party/blink/web_tests/platform/generic/external/wpt/fetch/api/request/request-init-stream.any.worker-expected.txt
@@ -1,4 +1,26 @@ This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules +PASS Constructing a Request with a stream holds the original object. +PASS Constructing a Request with a stream on which getReader() is called +PASS Constructing a Request with a stream on which read() is called +PASS Constructing a Request with a stream on which read() and releaseLock() are called +PASS Constructing a Request with a Request on which body.getReader() is called +PASS Constructing a Request with a Request on which body.getReader().read() is called +PASS Constructing a Request with a Request on which read() and releaseLock() are called +PASS It is OK to omit .duplex when the body is null. +PASS It is OK to omit .duplex when the body is a string. +PASS It is OK to omit .duplex when the body is a Uint8Array. +PASS It is OK to omit .duplex when the body is a Blob. +FAIL It is error to omit .duplex when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body })" did not throw +PASS It is OK to set .duplex = 'half' when the body is null. +PASS It is OK to set .duplex = 'half' when the body is a string. +PASS It is OK to set .duplex = 'half' when the body is a Uint8Array. +PASS It is OK to set .duplex = 'half' when the body is a Blob. +PASS It is OK to set .duplex = 'half' when the body is a ReadableStream. +FAIL It is error to set .duplex = 'full' when the body is null. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a string. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Uint8Array. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a Blob. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +FAIL It is error to set .duplex = 'full' when the body is a ReadableStream. assert_throws_js: function "() => new Request("...", { method, body, duplex })" did not throw +PASS It is OK to omit duplex when init.body is not given and input.body is given. Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/generic/http/tests/devtools/layers/layer-canvas-log-expected.txt b/third_party/blink/web_tests/platform/generic/http/tests/devtools/layers/layer-canvas-log-expected.txt index c458c28..70db387c 100644 --- a/third_party/blink/web_tests/platform/generic/http/tests/devtools/layers/layer-canvas-log-expected.txt +++ b/third_party/blink/web_tests/platform/generic/http/tests/devtools/layers/layer-canvas-log-expected.txt
@@ -41,6 +41,33 @@ } 10 : { commandIndex : 10 + method : "save" + params : undefined + } + 11 : { + commandIndex : 11 + method : "translate" + params : { + dx : 0 + dy : 71 + } + } + 12 : { + commandIndex : 12 + method : "clipRect" + params : { + SkRegion::Op : "kIntersect_Op" + rect : { + bottom : 150 + left : 0 + right : 300 + top : 0 + } + softClipEdgeStyle : true + } + } + 13 : { + commandIndex : 13 method : "drawRect" params : { paint : { @@ -60,8 +87,8 @@ } } } - 11 : { - commandIndex : 11 + 14 : { + commandIndex : 14 method : "restore" params : undefined } @@ -93,6 +120,25 @@ } 4 : { commandIndex : 4 + method : "clipRect" + params : { + SkRegion::Op : "kIntersect_Op" + rect : { + bottom : 71 + left : 0 + right : 19 + top : 50 + } + softClipEdgeStyle : true + } + } + 5 : { + commandIndex : 5 + method : "save" + params : undefined + } + 6 : { + commandIndex : 6 method : "concat44" params : { matrix44 : [ @@ -115,8 +161,8 @@ ] } } - 5 : { - commandIndex : 5 + 7 : { + commandIndex : 7 method : "drawImage" params : { image : { @@ -141,37 +187,15 @@ top : 0 } } - 6 : { - commandIndex : 6 + 8 : { + commandIndex : 8 method : "restore" params : undefined } - 7 : { - commandIndex : 7 - method : "save" - params : undefined - } - 8 : { - commandIndex : 8 - method : "translate" - params : { - dx : 0 - dy : 71 - } - } 9 : { commandIndex : 9 - method : "clipRect" - params : { - SkRegion::Op : "kIntersect_Op" - rect : { - bottom : 150 - left : 0 - right : 300 - top : 0 - } - softClipEdgeStyle : true - } + method : "restore" + params : undefined } }
diff --git a/third_party/blink/web_tests/platform/generic/paint/invalidation/image/image-resize-expected.txt b/third_party/blink/web_tests/platform/generic/paint/invalidation/image/image-resize-expected.txt index ff9ad0a..575e960 100644 --- a/third_party/blink/web_tests/platform/generic/paint/invalidation/image/image-resize-expected.txt +++ b/third_party/blink/web_tests/platform/generic/paint/invalidation/image/image-resize-expected.txt
@@ -6,8 +6,8 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [0, 50, 150, 150], - [0, 50, 100, 200] + [0, 50, 100, 200], + [100, 50, 50, 150] ] } ]
diff --git a/third_party/blink/web_tests/platform/generic/paint/invalidation/image/percent-size-image-resize-container-expected.txt b/third_party/blink/web_tests/platform/generic/paint/invalidation/image/percent-size-image-resize-container-expected.txt index ff9ad0a..575e960 100644 --- a/third_party/blink/web_tests/platform/generic/paint/invalidation/image/percent-size-image-resize-container-expected.txt +++ b/third_party/blink/web_tests/platform/generic/paint/invalidation/image/percent-size-image-resize-container-expected.txt
@@ -6,8 +6,8 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [0, 50, 150, 150], - [0, 50, 100, 200] + [0, 50, 100, 200], + [100, 50, 50, 150] ] } ]
diff --git a/third_party/blink/web_tests/platform/generic/virtual/backface-visibility-interop/paint/invalidation/image/image-resize-expected.txt b/third_party/blink/web_tests/platform/generic/virtual/backface-visibility-interop/paint/invalidation/image/image-resize-expected.txt new file mode 100644 index 0000000..575e960 --- /dev/null +++ b/third_party/blink/web_tests/platform/generic/virtual/backface-visibility-interop/paint/invalidation/image/image-resize-expected.txt
@@ -0,0 +1,15 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "invalidations": [ + [0, 50, 100, 200], + [100, 50, 50, 150] + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/platform/generic/virtual/plz-dedicated-worker/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt b/third_party/blink/web_tests/platform/generic/virtual/plz-dedicated-worker/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt deleted file mode 100644 index 83aaeca..0000000 --- a/third_party/blink/web_tests/platform/generic/virtual/plz-dedicated-worker/external/wpt/fetch/api/request/request-init-stream.any.serviceworker-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Unhandled rejection: Failed to register a ServiceWorker for scope ('https://web-platform.test:8444/fetch/api/request/does/not/exist') with script ('https://web-platform.test:8444/fetch/api/request/request-init-stream.any.worker.js'): ServiceWorker script evaluation failed -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/composited-reflected-expected.png b/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/composited-reflected-expected.png index 1c4a4ee..a926cc9 100644 --- a/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/composited-reflected-expected.png +++ b/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/composited-reflected-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png b/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png index 5f431971..0567d1a 100644 --- a/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png +++ b/third_party/blink/web_tests/platform/generic/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/platform/generic/webexposed/global-interface-listing-expected.txt index ed30dad..32cbe9e 100644 --- a/third_party/blink/web_tests/platform/generic/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/platform/generic/webexposed/global-interface-listing-expected.txt
@@ -2816,6 +2816,7 @@ interface GamepadHapticActuator attribute @@toStringTag getter type + method canPlay method constructor method playEffect method reset
diff --git a/third_party/blink/web_tests/platform/linux/compositing/direct-image-compositing-expected.png b/third_party/blink/web_tests/platform/linux/compositing/direct-image-compositing-expected.png index 1065126..d000b491 100644 --- a/third_party/blink/web_tests/platform/linux/compositing/direct-image-compositing-expected.png +++ b/third_party/blink/web_tests/platform/linux/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-expected.png b/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-expected.png index 7ac052f..2bef65f 100644 --- a/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-expected.png +++ b/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png index 73166da..9feec27b 100644 --- a/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/blink/web_tests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-image-expected.txt b/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-image-expected.txt index da447b7d..74b547ff 100644 --- a/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-image-expected.txt +++ b/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-image-expected.txt
@@ -4,26 +4,28 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x20 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {P} at (0,0) size 784x20 LayoutText {#text} at (0,0) size 354x19 text run at (0,0) width 354: "This is an automatic test of copying an image document." - LayoutBlockFlow {P} at (0,36) size 784x40 + LayoutNGBlockFlow {P} at (0,36) size 784x40 LayoutText {#text} at (0,0) size 757x39 text run at (0,0) width 757: "To perform this test manually, click once in the image frame, choose Edit -> Copy then click in the red box and paste the" text run at (0,20) width 355: "image. If the image pastes successfully the test is passed." - LayoutBlockFlow (anonymous) at (0,92) size 784x154 + LayoutNGBlockFlow (anonymous) at (0,92) size 784x154 LayoutText {#text} at (0,0) size 0x0 - LayoutBlockFlow {DIV} at (0,246) size 784x131 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 76x103 + LayoutNGBlockFlow {DIV} at (0,246) size 784x131 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 layer at (8,100) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] layer at (0,0) size 300x150 LayoutView at (0,0) size 300x150 layer at (0,0) size 300x150 - LayoutBlockFlow {HTML} at (0,0) size 300x150 - LayoutBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 76x103 + LayoutNGBlockFlow {HTML} at (0,0) size 300x150 + LayoutNGBlockFlow {BODY} at (0,0) size 300x150 + layer at (0,0) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (22,268) size 76x103 + LayoutImage {IMG} at (14,14) size 76x103 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-oriented-image-expected.txt b/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-oriented-image-expected.txt index 361932a..82261fd 100644 --- a/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-oriented-image-expected.txt +++ b/third_party/blink/web_tests/platform/linux/editing/pasteboard/copy-standalone-oriented-image-expected.txt
@@ -16,7 +16,6 @@ LayoutNGBlockFlow (anonymous) at (0,92) size 784x154 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {DIV} at (0,246) size 784x128 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 50x100 LayoutText {#text} at (0,0) size 0x0 layer at (8,100) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] @@ -25,5 +24,8 @@ layer at (0,0) size 300x150 LayoutNGBlockFlow {HTML} at (0,0) size 300x150 LayoutNGBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 50x100 + layer at (0,0) size 50x100 + LayoutImage {IMG} at (0,0) size 50x100 +layer at (22,268) size 50x100 + LayoutImage {IMG} at (14,14) size 50x100 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/linux/editing/selection/4402375-expected.txt b/third_party/blink/web_tests/platform/linux/editing/selection/4402375-expected.txt index 1b47dc1..5f216e89 100644 --- a/third_party/blink/web_tests/platform/linux/editing/selection/4402375-expected.txt +++ b/third_party/blink/web_tests/platform/linux/editing/selection/4402375-expected.txt
@@ -18,10 +18,11 @@ text run at (0,0) width 743: "This test uses a right aligned image next to some left aligned text. The image should not be selected, and should not be" text run at (0,20) width 598: "included in the selection rect (you won't see the selection rect when you run this test manually)." LayoutNGBlockFlow {DIV} at (0,130) size 784x20 - LayoutImage (floating) {IMG} at (708,0) size 76x103 LayoutText {#text} at (0,0) size 178x19 text run at (0,0) width 178: "This text should be selected." layer at (8,64) size 784x2 clip at (0,0) size 0x0 LayoutNGBlockFlow {HR} at (0,56) size 784x2 [border: (1px inset #EEEEEE)] +layer at (716,138) size 76x103 + LayoutImage (floating) {IMG} at (708,0) size 76x103 selection start: position 0 of child 1 {#text} of child 6 {DIV} of body selection end: position 29 of child 1 {#text} of child 6 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/linux/editing/selection/drag-to-contenteditable-iframe-expected.txt b/third_party/blink/web_tests/platform/linux/editing/selection/drag-to-contenteditable-iframe-expected.txt index 3e95e8c..0f612c3 100644 --- a/third_party/blink/web_tests/platform/linux/editing/selection/drag-to-contenteditable-iframe-expected.txt +++ b/third_party/blink/web_tests/platform/linux/editing/selection/drag-to-contenteditable-iframe-expected.txt
@@ -9,7 +9,6 @@ LayoutNGBlockFlow (anonymous) at (0,0) size 800x213 LayoutText {#text} at (208,193) size 4x19 text run at (208,193) width 4: " " - LayoutImage {IMG} at (212,105) size 76x103 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {UL} at (0,229) size 800x20 LayoutNGListItem {LI} at (40,0) size 760x20 @@ -25,5 +24,8 @@ layer at (0,0) size 200x200 LayoutNGBlockFlow {HTML} at (0,0) size 200x200 LayoutNGBlockFlow {BODY} at (8,8) size 184x184 [bgcolor=#FFFFE0] - LayoutImage {IMG} at (0,0) size 76x103 LayoutText {#text} at (0,0) size 0x0 + layer at (8,8) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (212,105) size 76x103 + LayoutImage {IMG} at (212,105) size 76x103
diff --git a/third_party/blink/web_tests/platform/linux/editing/selection/select-missing-image-expected.txt b/third_party/blink/web_tests/platform/linux/editing/selection/select-missing-image-expected.txt index ff6c5fe0..94aa2c0 100644 --- a/third_party/blink/web_tests/platform/linux/editing/selection/select-missing-image-expected.txt +++ b/third_party/blink/web_tests/platform/linux/editing/selection/select-missing-image-expected.txt
@@ -3,16 +3,18 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] - LayoutBlockFlow {IMG} at (14,14) size 550x100 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 +layer at (22,22) size 550x100 + LayoutNGBlockFlow {IMG} at (14,14) size 550x100 layer at (22,22) size 550x100 clip at (23,23) size 548x98 - LayoutBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] - LayoutImage (floating) {IMG} at (2,2) size 16x16 + LayoutNGBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] LayoutInline {SPAN} at (18,2) size 480x27 LayoutText {#text} at (18,2) size 480x27 text run at (18,2) width 480: "Should see selection tint over this missing image." +layer at (24,24) size 16x16 + LayoutImage (floating) {IMG} at (2,2) size 16x16 selection start: position 0 of child 1 {IMG} of child 1 {DIV} of body selection end: position 1 of child 1 {IMG} of child 1 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/linux/fast/block/positioning/061-expected.png b/third_party/blink/web_tests/platform/linux/fast/block/positioning/061-expected.png index a04d95b..3a6f3fc 100644 --- a/third_party/blink/web_tests/platform/linux/fast/block/positioning/061-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/block/positioning/061-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-big-endian-expected.png b/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-big-endian-expected.png index 72181c89..9e2478b 100644 --- a/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-big-endian-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-big-endian-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-little-endian-expected.png b/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-little-endian-expected.png index 72181c89..9e2478b 100644 --- a/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-little-endian-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/encoding/utf-16-little-endian-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/replaced/selection-rect-transform-expected.png b/third_party/blink/web_tests/platform/linux/fast/replaced/selection-rect-transform-expected.png index d768bd3..8d781f2 100644 --- a/third_party/blink/web_tests/platform/linux/fast/replaced/selection-rect-transform-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/replaced/selection-rect-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-expected.png index b3b23a2..1d901ee 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-quirk-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-quirk-expected.png index 44f50dc..634ebca 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-quirk-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-0px-images-quirk-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-10px-images-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-10px-images-expected.png index 07c9cbd9..c897a7c4 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-10px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-10px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-16px-images-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-16px-images-expected.png index 32ddd25..8a7e888 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-16px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-16px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-1px-images-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-1px-images-expected.png index 0464af21..7a02cf7 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-1px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-1px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/images/rendering-broken-images-expected.png b/third_party/blink/web_tests/platform/linux/images/rendering-broken-images-expected.png index 5044e77..bb22c099 100644 --- a/third_party/blink/web_tests/platform/linux/images/rendering-broken-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/images/rendering-broken-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-expected.png index 43f83857..ffd65d4 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-quirk-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-quirk-expected.png index c817fc8d..5415487b 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-quirk-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-0px-images-quirk-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-10px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-10px-images-expected.png index 0208bb0..a49be1a 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-10px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-10px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-16px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-16px-images-expected.png index 242dc96..0ab4e4dd 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-16px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-16px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-1px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-1px-images-expected.png index 6133003..442a7ee 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-1px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-1px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-images-expected.png index 829d70f..36bdc60f 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/exotic-color-space/images/rendering-broken-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-expected.png index 99609258..ca3a8648 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-quirk-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-quirk-expected.png index 681c89b..407f9c7 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-quirk-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-0px-images-quirk-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-10px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-10px-images-expected.png index c727339..e98967b6 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-10px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-10px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-16px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-16px-images-expected.png index f4e2fa0f..c907978 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-16px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-16px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-1px-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-1px-images-expected.png index 501c9b6..820e11e 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-1px-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-1px-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-images-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-images-expected.png index 4b647dcb..7eed5d9 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-images-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu-rasterization/images/rendering-broken-images-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/plz-dedicated-worker/http/tests/devtools/layers/layer-canvas-log-expected.txt b/third_party/blink/web_tests/platform/linux/virtual/plz-dedicated-worker/http/tests/devtools/layers/layer-canvas-log-expected.txt new file mode 100644 index 0000000..70db387c --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/plz-dedicated-worker/http/tests/devtools/layers/layer-canvas-log-expected.txt
@@ -0,0 +1,201 @@ +Tests layer command log + +Canvas log: +{ + 0 : { + commandIndex : 0 + method : "drawPaint" + params : { + paint : { + blendMode : "Src" + color : "#00000000" + flags : "none" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + } + } + 1 : { + commandIndex : 1 + method : "drawRect" + params : { + paint : { + color : "#FF0000FF" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 100 + left : 0 + right : 100 + top : 0 + } + } + } + 10 : { + commandIndex : 10 + method : "save" + params : undefined + } + 11 : { + commandIndex : 11 + method : "translate" + params : { + dx : 0 + dy : 71 + } + } + 12 : { + commandIndex : 12 + method : "clipRect" + params : { + SkRegion::Op : "kIntersect_Op" + rect : { + bottom : 150 + left : 0 + right : 300 + top : 0 + } + softClipEdgeStyle : true + } + } + 13 : { + commandIndex : 13 + method : "drawRect" + params : { + paint : { + color : "#7F000000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 10 + left : 0 + right : 10 + top : 0 + } + } + } + 14 : { + commandIndex : 14 + method : "restore" + params : undefined + } + 2 : { + commandIndex : 2 + method : "drawRect" + params : { + paint : { + color : "#FFFF0000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 50 + left : 0 + right : 50 + top : 0 + } + } + } + 3 : { + commandIndex : 3 + method : "save" + params : undefined + } + 4 : { + commandIndex : 4 + method : "clipRect" + params : { + SkRegion::Op : "kIntersect_Op" + rect : { + bottom : 71 + left : 0 + right : 19 + top : 50 + } + softClipEdgeStyle : true + } + } + 5 : { + commandIndex : 5 + method : "save" + params : undefined + } + 6 : { + commandIndex : 6 + method : "concat44" + params : { + matrix44 : [ + 1 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 50 + 0 + 1 + ] + } + } + 7 : { + commandIndex : 7 + method : "drawImage" + params : { + image : { + height : 21 + opaque : false + width : 19 + } + left : 0 + paint : { + color : "#FF000000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + sampling : { + filter : "kLinear" + mipmap : "kNearest" + } + top : 0 + } + } + 8 : { + commandIndex : 8 + method : "restore" + params : undefined + } + 9 : { + commandIndex : 9 + method : "restore" + params : undefined + } +} +
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/composited-reflected-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/composited-reflected-expected.png index 8cdd4f86..eb1dfc4 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/composited-reflected-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/composited-reflected-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png index 86f5795..1531084 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index ddecfb7..a989e1c4 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index 35c4f0e..5db2406 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png index 0beadcd..21822697f 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-chained-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/fast/overflow/overflow-update-transform-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/fast/overflow/overflow-update-transform-expected.png index f13ddef..9e752d01 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/fast/overflow/overflow-update-transform-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/fast/overflow/overflow-update-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/direct-image-compositing-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/direct-image-compositing-expected.png index 103a86e8..4e9e1c9 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/direct-image-compositing-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-expected.png index 0389d73..605f0378 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-with-opacity-expected.png index 38f4c4af..af8deae 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/direct-image-compositing-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/direct-image-compositing-expected.png index 103a86e8..4e9e1c9 100644 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/direct-image-compositing-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-expected.png index 0389d73..605f0378 100644 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-with-opacity-expected.png index 38f4c4af..af8deae 100644 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/http/tests/devtools/layers/layer-canvas-log-expected.txt b/third_party/blink/web_tests/platform/mac-mac12-arm64/http/tests/devtools/layers/layer-canvas-log-expected.txt new file mode 100644 index 0000000..c458c28 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/http/tests/devtools/layers/layer-canvas-log-expected.txt
@@ -0,0 +1,177 @@ +Tests layer command log + +Canvas log: +{ + 0 : { + commandIndex : 0 + method : "drawPaint" + params : { + paint : { + blendMode : "Src" + color : "#00000000" + flags : "none" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + } + } + 1 : { + commandIndex : 1 + method : "drawRect" + params : { + paint : { + color : "#FF0000FF" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 100 + left : 0 + right : 100 + top : 0 + } + } + } + 10 : { + commandIndex : 10 + method : "drawRect" + params : { + paint : { + color : "#7F000000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 10 + left : 0 + right : 10 + top : 0 + } + } + } + 11 : { + commandIndex : 11 + method : "restore" + params : undefined + } + 2 : { + commandIndex : 2 + method : "drawRect" + params : { + paint : { + color : "#FFFF0000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + rect : { + bottom : 50 + left : 0 + right : 50 + top : 0 + } + } + } + 3 : { + commandIndex : 3 + method : "save" + params : undefined + } + 4 : { + commandIndex : 4 + method : "concat44" + params : { + matrix44 : [ + 1 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 50 + 0 + 1 + ] + } + } + 5 : { + commandIndex : 5 + method : "drawImage" + params : { + image : { + height : 21 + opaque : false + width : 19 + } + left : 0 + paint : { + color : "#FF000000" + flags : "AntiAlias" + strokeCap : "Butt" + strokeJoin : "Miter" + strokeMiter : 4 + strokeWidth : 0 + styleName : "Fill" + } + sampling : { + filter : "kLinear" + mipmap : "kNearest" + } + top : 0 + } + } + 6 : { + commandIndex : 6 + method : "restore" + params : undefined + } + 7 : { + commandIndex : 7 + method : "save" + params : undefined + } + 8 : { + commandIndex : 8 + method : "translate" + params : { + dx : 0 + dy : 71 + } + } + 9 : { + commandIndex : 9 + method : "clipRect" + params : { + SkRegion::Op : "kIntersect_Op" + rect : { + bottom : 150 + left : 0 + right : 300 + top : 0 + } + softClipEdgeStyle : true + } + } +} +
diff --git a/third_party/blink/web_tests/platform/mac/compositing/direct-image-compositing-expected.png b/third_party/blink/web_tests/platform/mac/compositing/direct-image-compositing-expected.png index aa006d6b..df770ed7 100644 --- a/third_party/blink/web_tests/platform/mac/compositing/direct-image-compositing-expected.png +++ b/third_party/blink/web_tests/platform/mac/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-image-expected.txt b/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-image-expected.txt index 7c3ceb1..122e877 100644 --- a/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-image-expected.txt +++ b/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-image-expected.txt
@@ -4,26 +4,28 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x18 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {P} at (0,0) size 784x18 LayoutText {#text} at (0,0) size 362x18 text run at (0,0) width 362: "This is an automatic test of copying an image document." - LayoutBlockFlow {P} at (0,34) size 784x36 + LayoutNGBlockFlow {P} at (0,34) size 784x36 LayoutText {#text} at (0,0) size 773x36 text run at (0,0) width 773: "To perform this test manually, click once in the image frame, choose Edit -> Copy then click in the red box and paste the" text run at (0,18) width 365: "image. If the image pastes successfully the test is passed." - LayoutBlockFlow (anonymous) at (0,86) size 784x154 + LayoutNGBlockFlow (anonymous) at (0,86) size 784x154 LayoutText {#text} at (0,0) size 0x0 - LayoutBlockFlow {DIV} at (0,240) size 784x131 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 76x103 + LayoutNGBlockFlow {DIV} at (0,240) size 784x131 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 layer at (8,94) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] layer at (0,0) size 300x150 LayoutView at (0,0) size 300x150 layer at (0,0) size 300x150 - LayoutBlockFlow {HTML} at (0,0) size 300x150 - LayoutBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 76x103 + LayoutNGBlockFlow {HTML} at (0,0) size 300x150 + LayoutNGBlockFlow {BODY} at (0,0) size 300x150 + layer at (0,0) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (22,262) size 76x103 + LayoutImage {IMG} at (14,14) size 76x103 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-oriented-image-expected.txt b/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-oriented-image-expected.txt index 8b14dcad..37f54bb0 100644 --- a/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-oriented-image-expected.txt +++ b/third_party/blink/web_tests/platform/mac/editing/pasteboard/copy-standalone-oriented-image-expected.txt
@@ -16,7 +16,6 @@ LayoutNGBlockFlow (anonymous) at (0,86) size 784x154 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {DIV} at (0,240) size 784x128 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 50x100 LayoutText {#text} at (0,0) size 0x0 layer at (8,94) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] @@ -25,5 +24,8 @@ layer at (0,0) size 300x150 LayoutNGBlockFlow {HTML} at (0,0) size 300x150 LayoutNGBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 50x100 + layer at (0,0) size 50x100 + LayoutImage {IMG} at (0,0) size 50x100 +layer at (22,262) size 50x100 + LayoutImage {IMG} at (14,14) size 50x100 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/mac/editing/selection/4402375-expected.txt b/third_party/blink/web_tests/platform/mac/editing/selection/4402375-expected.txt index 464465f..4126221f 100644 --- a/third_party/blink/web_tests/platform/mac/editing/selection/4402375-expected.txt +++ b/third_party/blink/web_tests/platform/mac/editing/selection/4402375-expected.txt
@@ -18,10 +18,11 @@ text run at (0,0) width 759: "This test uses a right aligned image next to some left aligned text. The image should not be selected, and should not be" text run at (0,18) width 612: "included in the selection rect (you won't see the selection rect when you run this test manually)." LayoutNGBlockFlow {DIV} at (0,122) size 784x18 - LayoutImage (floating) {IMG} at (708,0) size 76x103 LayoutText {#text} at (0,0) size 182x18 text run at (0,0) width 182: "This text should be selected." layer at (8,60) size 784x2 clip at (0,0) size 0x0 LayoutNGBlockFlow {HR} at (0,52) size 784x2 [border: (1px inset #EEEEEE)] +layer at (716,130) size 76x103 + LayoutImage (floating) {IMG} at (708,0) size 76x103 selection start: position 0 of child 1 {#text} of child 6 {DIV} of body selection end: position 29 of child 1 {#text} of child 6 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/mac/editing/selection/drag-to-contenteditable-iframe-expected.txt b/third_party/blink/web_tests/platform/mac/editing/selection/drag-to-contenteditable-iframe-expected.txt index 71cf5ec..7327d38 100644 --- a/third_party/blink/web_tests/platform/mac/editing/selection/drag-to-contenteditable-iframe-expected.txt +++ b/third_party/blink/web_tests/platform/mac/editing/selection/drag-to-contenteditable-iframe-expected.txt
@@ -9,7 +9,6 @@ LayoutNGBlockFlow (anonymous) at (0,0) size 800x212 LayoutText {#text} at (208,194) size 4x18 text run at (208,194) width 4: " " - LayoutImage {IMG} at (212,105) size 76x103 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {UL} at (0,228) size 800x18 LayoutNGListItem {LI} at (40,0) size 760x18 @@ -25,5 +24,8 @@ layer at (0,0) size 200x200 LayoutNGBlockFlow {HTML} at (0,0) size 200x200 LayoutNGBlockFlow {BODY} at (8,8) size 184x184 [bgcolor=#FFFFE0] - LayoutImage {IMG} at (0,0) size 76x103 LayoutText {#text} at (0,0) size 0x0 + layer at (8,8) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (212,105) size 76x103 + LayoutImage {IMG} at (212,105) size 76x103
diff --git a/third_party/blink/web_tests/platform/mac/editing/selection/select-missing-image-expected.txt b/third_party/blink/web_tests/platform/mac/editing/selection/select-missing-image-expected.txt index b4ed7b8c..5e45b58 100644 --- a/third_party/blink/web_tests/platform/mac/editing/selection/select-missing-image-expected.txt +++ b/third_party/blink/web_tests/platform/mac/editing/selection/select-missing-image-expected.txt
@@ -3,16 +3,18 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] - LayoutBlockFlow {IMG} at (14,14) size 550x100 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 +layer at (22,22) size 550x100 + LayoutNGBlockFlow {IMG} at (14,14) size 550x100 layer at (22,22) size 550x100 clip at (23,23) size 548x98 - LayoutBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] - LayoutImage (floating) {IMG} at (2,2) size 16x16 + LayoutNGBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] LayoutInline {SPAN} at (18,2) size 475x28 LayoutText {#text} at (18,2) size 475x28 text run at (18,2) width 475: "Should see selection tint over this missing image." +layer at (24,24) size 16x16 + LayoutImage (floating) {IMG} at (2,2) size 16x16 selection start: position 0 of child 1 {IMG} of child 1 {DIV} of body selection end: position 1 of child 1 {IMG} of child 1 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/mac/fast/block/positioning/061-expected.png b/third_party/blink/web_tests/platform/mac/fast/block/positioning/061-expected.png index 75957c3..4f672ff 100644 --- a/third_party/blink/web_tests/platform/mac/fast/block/positioning/061-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/block/positioning/061-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/overflow/overflow-update-transform-expected.png b/third_party/blink/web_tests/platform/mac/fast/overflow/overflow-update-transform-expected.png index 696b202..37c050ab 100644 --- a/third_party/blink/web_tests/platform/mac/fast/overflow/overflow-update-transform-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/overflow/overflow-update-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/replaced/selection-rect-transform-expected.png b/third_party/blink/web_tests/platform/mac/fast/replaced/selection-rect-transform-expected.png index 46fb3ae..f6b53d60 100644 --- a/third_party/blink/web_tests/platform/mac/fast/replaced/selection-rect-transform-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/replaced/selection-rect-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt b/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt index a854c3d9..290a5b4 100644 --- a/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt +++ b/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt
@@ -9,7 +9,7 @@ [0, 735, 785, 94], [8, 86, 732, 94], [58, 230, 489, 537], - [58, 136, 489, 537] + [58, 136, 489, 94] ] }, {
diff --git a/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt b/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt index 318eea7..f7c0292 100644 --- a/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt +++ b/third_party/blink/web_tests/platform/mac/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt
@@ -8,7 +8,7 @@ "invalidations": [ [8, 86, 732, 94], [58, 136, 489, 537], - [58, 234, 489, 501] + [58, 673, 489, 62] ] }, {
diff --git a/third_party/blink/web_tests/platform/mac/paint/invalidation/selection/selected-replaced-expected.txt b/third_party/blink/web_tests/platform/mac/paint/invalidation/selection/selected-replaced-expected.txt index 728f0c9..0f242259 100644 --- a/third_party/blink/web_tests/platform/mac/paint/invalidation/selection/selected-replaced-expected.txt +++ b/third_party/blink/web_tests/platform/mac/paint/invalidation/selection/selected-replaced-expected.txt
@@ -6,8 +6,8 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [8, 148, 214, 232], - [8, 68, 214, 232] + [8, 68, 214, 232], + [8, 300, 214, 80] ] } ]
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index 59f8d865..aea1188 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index 52b3bb79..1015305 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/compositing/direct-image-compositing-expected.png b/third_party/blink/web_tests/platform/win/compositing/direct-image-compositing-expected.png index 17f5a6f7..dade3c6 100644 --- a/third_party/blink/web_tests/platform/win/compositing/direct-image-compositing-expected.png +++ b/third_party/blink/web_tests/platform/win/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-image-expected.txt b/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-image-expected.txt index f9906acf..7da197d 100644 --- a/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-image-expected.txt +++ b/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-image-expected.txt
@@ -4,26 +4,28 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x20 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {P} at (0,0) size 784x20 LayoutText {#text} at (0,0) size 334x19 text run at (0,0) width 334: "This is an automatic test of copying an image document." - LayoutBlockFlow {P} at (0,36) size 784x40 + LayoutNGBlockFlow {P} at (0,36) size 784x40 LayoutText {#text} at (0,0) size 778x39 text run at (0,0) width 778: "To perform this test manually, click once in the image frame, choose Edit -> Copy then click in the red box and paste the image. If" text run at (0,20) width 283: "the image pastes successfully the test is passed." - LayoutBlockFlow (anonymous) at (0,92) size 784x154 + LayoutNGBlockFlow (anonymous) at (0,92) size 784x154 LayoutText {#text} at (0,0) size 0x0 - LayoutBlockFlow {DIV} at (0,246) size 784x131 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 76x103 + LayoutNGBlockFlow {DIV} at (0,246) size 784x131 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 layer at (8,100) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] layer at (0,0) size 300x150 LayoutView at (0,0) size 300x150 layer at (0,0) size 300x150 - LayoutBlockFlow {HTML} at (0,0) size 300x150 - LayoutBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 76x103 + LayoutNGBlockFlow {HTML} at (0,0) size 300x150 + LayoutNGBlockFlow {BODY} at (0,0) size 300x150 + layer at (0,0) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (22,268) size 76x103 + LayoutImage {IMG} at (14,14) size 76x103 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-oriented-image-expected.txt b/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-oriented-image-expected.txt index 7bb7833..b095120570 100644 --- a/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-oriented-image-expected.txt +++ b/third_party/blink/web_tests/platform/win/editing/pasteboard/copy-standalone-oriented-image-expected.txt
@@ -16,7 +16,6 @@ LayoutNGBlockFlow (anonymous) at (0,92) size 784x154 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {DIV} at (0,246) size 784x128 [border: (2px solid #FF0000)] - LayoutImage {IMG} at (14,14) size 50x100 LayoutText {#text} at (0,0) size 0x0 layer at (8,100) size 304x154 LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px solid #0000FF)] @@ -25,5 +24,8 @@ layer at (0,0) size 300x150 LayoutNGBlockFlow {HTML} at (0,0) size 300x150 LayoutNGBlockFlow {BODY} at (0,0) size 300x150 - LayoutImage {IMG} at (0,0) size 50x100 + layer at (0,0) size 50x100 + LayoutImage {IMG} at (0,0) size 50x100 +layer at (22,268) size 50x100 + LayoutImage {IMG} at (14,14) size 50x100 caret: position 1 of child 0 {IMG} of child 7 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/win/editing/selection/4402375-expected.txt b/third_party/blink/web_tests/platform/win/editing/selection/4402375-expected.txt index 04ad246..645be2e 100644 --- a/third_party/blink/web_tests/platform/win/editing/selection/4402375-expected.txt +++ b/third_party/blink/web_tests/platform/win/editing/selection/4402375-expected.txt
@@ -18,10 +18,11 @@ text run at (0,0) width 772: "This test uses a right aligned image next to some left aligned text. The image should not be selected, and should not be included in" text run at (0,20) width 497: "the selection rect (you won't see the selection rect when you run this test manually)." LayoutNGBlockFlow {DIV} at (0,130) size 784x20 - LayoutImage (floating) {IMG} at (708,0) size 76x103 LayoutText {#text} at (0,0) size 170x19 text run at (0,0) width 170: "This text should be selected." layer at (8,64) size 784x2 clip at (0,0) size 0x0 LayoutNGBlockFlow {HR} at (0,56) size 784x2 [border: (1px inset #EEEEEE)] +layer at (716,138) size 76x103 + LayoutImage (floating) {IMG} at (708,0) size 76x103 selection start: position 0 of child 1 {#text} of child 6 {DIV} of body selection end: position 29 of child 1 {#text} of child 6 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/win/editing/selection/drag-to-contenteditable-iframe-expected.txt b/third_party/blink/web_tests/platform/win/editing/selection/drag-to-contenteditable-iframe-expected.txt index 2cfecbb..4d97e2fd 100644 --- a/third_party/blink/web_tests/platform/win/editing/selection/drag-to-contenteditable-iframe-expected.txt +++ b/third_party/blink/web_tests/platform/win/editing/selection/drag-to-contenteditable-iframe-expected.txt
@@ -9,7 +9,6 @@ LayoutNGBlockFlow (anonymous) at (0,0) size 800x213 LayoutText {#text} at (208,193) size 4x19 text run at (208,193) width 4: " " - LayoutImage {IMG} at (212,105) size 76x103 LayoutText {#text} at (0,0) size 0x0 LayoutNGBlockFlow {UL} at (0,229) size 800x20 LayoutNGListItem {LI} at (40,0) size 760x20 @@ -25,5 +24,8 @@ layer at (0,0) size 200x200 LayoutNGBlockFlow {HTML} at (0,0) size 200x200 LayoutNGBlockFlow {BODY} at (8,8) size 184x184 [bgcolor=#FFFFE0] - LayoutImage {IMG} at (0,0) size 76x103 LayoutText {#text} at (0,0) size 0x0 + layer at (8,8) size 76x103 + LayoutImage {IMG} at (0,0) size 76x103 +layer at (212,105) size 76x103 + LayoutImage {IMG} at (212,105) size 76x103
diff --git a/third_party/blink/web_tests/platform/win/editing/selection/select-missing-image-expected.txt b/third_party/blink/web_tests/platform/win/editing/selection/select-missing-image-expected.txt index 3ac6fac..b78203b 100644 --- a/third_party/blink/web_tests/platform/win/editing/selection/select-missing-image-expected.txt +++ b/third_party/blink/web_tests/platform/win/editing/selection/select-missing-image-expected.txt
@@ -3,16 +3,18 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] - LayoutBlockFlow {IMG} at (14,14) size 550x100 + LayoutNGBlockFlow {HTML} at (0,0) size 800x600 + LayoutNGBlockFlow {BODY} at (8,8) size 784x584 + LayoutNGBlockFlow {DIV} at (0,0) size 784x128 [border: (2px solid #FF0000)] LayoutText {#text} at (0,0) size 0x0 +layer at (22,22) size 550x100 + LayoutNGBlockFlow {IMG} at (14,14) size 550x100 layer at (22,22) size 550x100 clip at (23,23) size 548x98 - LayoutBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] - LayoutImage (floating) {IMG} at (2,2) size 16x16 + LayoutNGBlockFlow {SPAN} at (0,0) size 550x100 [border: (1px solid #C0C0C0)] LayoutInline {SPAN} at (18,2) size 467x27 LayoutText {#text} at (18,2) size 467x27 text run at (18,2) width 467: "Should see selection tint over this missing image." +layer at (24,24) size 16x16 + LayoutImage (floating) {IMG} at (2,2) size 16x16 selection start: position 0 of child 1 {IMG} of child 1 {DIV} of body selection end: position 1 of child 1 {IMG} of child 1 {DIV} of body
diff --git a/third_party/blink/web_tests/platform/win/fast/block/positioning/061-expected.png b/third_party/blink/web_tests/platform/win/fast/block/positioning/061-expected.png index 43dcae43..692bd9a 100644 --- a/third_party/blink/web_tests/platform/win/fast/block/positioning/061-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/block/positioning/061-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/overflow/overflow-update-transform-expected.png b/third_party/blink/web_tests/platform/win/fast/overflow/overflow-update-transform-expected.png index 7620000..6a20a1c 100644 --- a/third_party/blink/web_tests/platform/win/fast/overflow/overflow-update-transform-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/overflow/overflow-update-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/replaced/selection-rect-transform-expected.png b/third_party/blink/web_tests/platform/win/fast/replaced/selection-rect-transform-expected.png index 7bdc69e..43ccfc4 100644 --- a/third_party/blink/web_tests/platform/win/fast/replaced/selection-rect-transform-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/replaced/selection-rect-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt b/third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt similarity index 93% rename from third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt rename to third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt index a61513e5..7887ff3 100644 --- a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt +++ b/third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt
@@ -9,7 +9,7 @@ [0, 742, 785, 94], [8, 92, 732, 94], [58, 236, 489, 537], - [58, 142, 489, 537] + [58, 142, 489, 94] ] }, {
diff --git a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt b/third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt similarity index 92% rename from third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt rename to third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt index 8971e737..b0ee101 100644 --- a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt +++ b/third_party/blink/web_tests/platform/win/paint/invalidation/position/shift-relative-positioned-container-with-image-removal-expected.txt
@@ -8,7 +8,7 @@ "invalidations": [ [8, 92, 732, 94], [58, 142, 489, 537], - [58, 241, 489, 501] + [58, 679, 489, 63] ] }, {
diff --git a/third_party/blink/web_tests/platform/win/paint/invalidation/selection/selected-replaced-expected.txt b/third_party/blink/web_tests/platform/win/paint/invalidation/selection/selected-replaced-expected.txt index 9613d4d..f7dd438 100644 --- a/third_party/blink/web_tests/platform/win/paint/invalidation/selection/selected-replaced-expected.txt +++ b/third_party/blink/web_tests/platform/win/paint/invalidation/selection/selected-replaced-expected.txt
@@ -6,8 +6,8 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [8, 132, 214, 232], - [8, 52, 214, 232] + [8, 52, 214, 232], + [8, 284, 214, 80] ] } ]
diff --git a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt b/third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt similarity index 93% copy from third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt copy to third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt index a61513e5..7887ff3 100644 --- a/third_party/blink/web_tests/platform/generic/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt +++ b/third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/position/shift-relative-positioned-container-with-image-addition-expected.txt
@@ -9,7 +9,7 @@ [0, 742, 785, 94], [8, 92, 732, 94], [58, 236, 489, 537], - [58, 142, 489, 537] + [58, 142, 489, 94] ] }, {
diff --git a/third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/selection/selected-replaced-expected.txt b/third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/selection/selected-replaced-expected.txt new file mode 100644 index 0000000..f7dd438 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/backface-visibility-interop/paint/invalidation/selection/selected-replaced-expected.txt
@@ -0,0 +1,15 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "invalidations": [ + [8, 52, 214, 232], + [8, 284, 214, 80] + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png index b93bbcd7..8252d78f 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index 2fd3d545..14e1758 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index a2e4be5..763634c 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/commit-timeout-crash.html b/third_party/blink/web_tests/wpt_internal/document-transition/commit-timeout-crash.html new file mode 100644 index 0000000..69bfbfe5 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/document-transition/commit-timeout-crash.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<meta name="timeout" content="long"> +<html class=reftest-wait> +<title>Long timeout</title> +<link rel="help" href="https://github.com/WICG/shared-element-transitions"> +<link rel="author" href="mailto:vmpstr@chromium.org"> + +<script src="/common/reftest-wait.js"></script> + +<style> +.square { + contain: paint; + width: 100px; + height: 100px; + background: green; + page-transition-tag: square; +} +</style> + +<div class=square></div> + +<script> +async function runTest() { + let t = document.createDocumentTransition(); + t.start(async () => { + await new Promise(resolve => setTimeout(resolve, 5000)); + takeScreenshot(); + }); +} +onload = () => requestAnimationFrame(runTest); +</script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/pseudo-get-computed-style.html b/third_party/blink/web_tests/wpt_internal/document-transition/pseudo-get-computed-style.html index 2e29996..b6e43aa2 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/pseudo-get-computed-style.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/pseudo-get-computed-style.html
@@ -27,15 +27,27 @@ document.createDocumentTransition().start(() => { assert_equals(getComputedStyle(document.documentElement, ":page-transition").position, "fixed"); assert_equals(getComputedStyle(document.documentElement, ":page-transition-container(target)").position, "absolute"); - // We changed this in the style block above. - assert_equals(getComputedStyle(document.documentElement, ":page-transition-image-wrapper(target)").position, "fixed"); + // We changed this in the style block above but it will not apply until the animation phase. + assert_equals(getComputedStyle(document.documentElement, ":page-transition-image-wrapper(target)").position, "absolute"); assert_equals(getComputedStyle(document.documentElement, ":page-transition-outgoing-image(target)").position, "absolute"); assert_equals(getComputedStyle(document.documentElement, ":page-transition-container(root)").position, "absolute"); assert_equals(getComputedStyle(document.documentElement, ":page-transition-image-wrapper(root)").position, "absolute"); assert_equals(getComputedStyle(document.documentElement, ":page-transition-outgoing-image(root)").position, "absolute"); - t.done(); + + requestAnimationFrame(() => { + assert_equals(getComputedStyle(document.documentElement, ":page-transition").position, "fixed"); + assert_equals(getComputedStyle(document.documentElement, ":page-transition-container(target)").position, "absolute"); + assert_equals(getComputedStyle(document.documentElement, ":page-transition-image-wrapper(target)").position, "fixed"); + + assert_equals(getComputedStyle(document.documentElement, ":page-transition-outgoing-image(target)").position, "absolute"); + + assert_equals(getComputedStyle(document.documentElement, ":page-transition-container(root)").position, "absolute"); + assert_equals(getComputedStyle(document.documentElement, ":page-transition-image-wrapper(root)").position, "absolute"); + assert_equals(getComputedStyle(document.documentElement, ":page-transition-outgoing-image(root)").position, "absolute"); + t.done(); + }); }); }, "position property of pseudo elements"); </script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html b/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html index 0f53118a..acde409 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html
@@ -39,12 +39,9 @@ t.start(() => { e1.classList.remove("left"); e1.classList.add("right"); + setTimeout(takeScreenshot, 500); }); } -function runTest() { - startTransition(); - setTimeout(takeScreenshot, 500); -} -onload = runTest; +onload = startTransition; </script>
diff --git a/third_party/blink/web_tests/wpt_internal/fenced_frame/key-scrolling.https.html b/third_party/blink/web_tests/wpt_internal/fenced_frame/key-scrolling.https.html new file mode 100644 index 0000000..7a23a72 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/fenced_frame/key-scrolling.https.html
@@ -0,0 +1,67 @@ +<!DOCTYPE html> +<title>Test keyboard scroll bubbling from a fenced frame.</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-actions.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/utils.js"></script> +<style> + body { + /* Make main frame scrollable */ + width: 200vw; + height: 200vh; + } +</style> + +<body> +<script> + +// Ensure keyboard scrolling from inside a fenced frame is bubbled out to the +// embedding frame. +promise_test(async t => { + const frame = attachFencedFrameContext({html: ` + <!DOCTYPE html> + <style> + body { + /* Make fenced frame scrollable */ + width: 200vw; + height: 200vh; + } + </style> + <script src="/resources/testdriver.js"><\/script> + <script src="/resources/testdriver-actions.js"><\/script> + <script src="/resources/testdriver-vendor.js"><\/script> + `}); + + // Scroll the fenced frame to its full extent so that left/down arrow key + // scrolling will bubble to the embedder. + await frame.execute(async () => { + window.scrollTo(10000, 10000); + }); + + assert_equals(window.scrollX, 0, '[PRECONDITION] main frame has no x scroll.'); + assert_equals(window.scrollY, 0, '[PRECONDITION] main frame has no y scroll.'); + + // Simulate a right arrow and down arrow key in the fenced frame. + await frame.execute(async () => { + const arrow_right = "\uE014"; + const arrow_down = "\uE015"; + + test_driver.send_keys(document.body, arrow_right); + test_driver.send_keys(document.body, arrow_down); + }); + + // Use step_wait to poll since the scroll may be executed asynchronously + // (e.g. IPC to embedder, scroll animation). + await t.step_wait(() => window.scrollX > 0, "Wait for horizontal scroll."); + assert_greater_than(window.scrollX, 0, 'Horizontal scroll should bubble to main frame.'); + + await t.step_wait(() => window.scrollY > 0, "Wait for vertical scroll."); + assert_greater_than(window.scrollY, 0, 'Vertical scroll should bubble to main frame.'); +}, 'Keyboard scrolling bubbles out of fenced frame'); + +</script> +</body>
diff --git a/third_party/closure_compiler/externs/file_manager_private.js b/third_party/closure_compiler/externs/file_manager_private.js index 9a269c4..28f324c 100644 --- a/third_party/closure_compiler/externs/file_manager_private.js +++ b/third_party/closure_compiler/externs/file_manager_private.js
@@ -1468,6 +1468,11 @@ chrome.fileManagerPrivate.pollDriveHostedFilePinStates = function() {}; /** + * Opens the page to manage currently syncing folders. + */ +chrome.fileManagerPrivate.openManageSyncSettings = function() {}; + +/** * Returns color via `callback` for Files app foreground window frame. * @param {function(string): void} callback |color| String containing the color * of the title bar.
diff --git a/tools/gritsettings/resource_ids.spec b/tools/gritsettings/resource_ids.spec index c7937223..1c50dbb9 100644 --- a/tools/gritsettings/resource_ids.spec +++ b/tools/gritsettings/resource_ids.spec
@@ -434,6 +434,10 @@ "META": {"sizes": {"includes": [20]}}, "includes": [2640], }, + "<(SHARED_INTERMEDIATE_DIR)/chrome/browser/resources/chromeos/manage_mirrorsync/resources.grd": { + "META": {"sizes": {"includes": [10]}}, + "includes": [2650], + }, # END chrome/ WebUI resources section # START chrome/ miscellaneous section.
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9b2e8033..49735d3 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -6008,7 +6008,7 @@ <int value="21" label="No trigger script available"/> <int value="22" label="Failed to show"/> <int value="23" label="Disabled proactive help setting"/> - <int value="24" label="Base64 decoding error"/> + <int value="24" label="(Obsolete) Base64 decoding error"/> <int value="25" label="The user rejected the bottom sheet onboarding"/> <int value="26" label="CCT -> tab not supported"/> <int value="27" label="Canceled"/> @@ -34890,6 +34890,7 @@ <int value="1676" label="AUTOTESTPRIVATE_SENDARCOVERLAYCOLOR"/> <int value="1677" label="AUTOTESTPRIVATE_ISINPUTMETHODREADYFORTESTING"/> <int value="1678" label="AUTOTESTPRIVATE_GETARCAPPKILLS"/> + <int value="1679" label="FILEMANAGERPRIVATE_OPENMANAGESYNCSETTINGS"/> </enum> <enum name="ExtensionIconState"> @@ -64881,6 +64882,7 @@ <int value="28" label="AboutThisSite"/> <int value="29" label="Translate"/> <int value="30" label="OfferNotification"/> + <int value="31" label="ExternalNavigation"/> </enum> <enum name="MessageLoopProblems"> @@ -85135,11 +85137,6 @@ <int value="5" label="Request failed"/> <int value="6" label="Request cancelled"/> <int value="7" label="Request served"/> - <int value="8" label="Was served to prerender navigation stack"/> - <int value="9" - label="Serving to prerender navigation stack and user navigated to - search terms"/> - <int value="10" label="Upgraded to prerender and succeeded"/> </enum> <enum name="SearchPrefetchServingReason"> @@ -85153,8 +85150,6 @@ <int value="7" label="Prefetch request failed"/> <int value="8" label="Another reason (unexpected)"/> <int value="9" label="POST, reload, link, or other non-cache loads."/> - <int value="10" - label="A prerender navigation request has taken this response away."/> </enum> <enum name="SearchResultExtractorClientStatus">
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index d43537c4..df3be15 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -93,6 +93,7 @@ <variant name=".AutoDarkWebContents"/> <variant name=".ChromeSurvey"/> <variant name=".DownloadProgress"/> + <variant name=".ExternalNavigation"/> <variant name=".GeneratedPasswordSaved"/> <variant name=".InstallableAmbientBadge"/> <variant name=".InstantApps"/>
diff --git a/tools/metrics/histograms/metadata/apps/histograms.xml b/tools/metrics/histograms/metadata/apps/histograms.xml index 87c6473..da64dc90 100644 --- a/tools/metrics/histograms/metadata/apps/histograms.xml +++ b/tools/metrics/histograms/metadata/apps/histograms.xml
@@ -759,7 +759,7 @@ </histogram> <histogram name="Apps.AppList.PersistentProto.ReadStatus" - enum="PersistentProtoReadStatus" expires_after="2022-12-11"> + enum="PersistentProtoReadStatus" expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> @@ -772,7 +772,7 @@ </histogram> <histogram name="Apps.AppList.PersistentProto.WriteStatus" - enum="PersistentProtoWriteStatus" expires_after="2022-08-07"> + enum="PersistentProtoWriteStatus" expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> @@ -863,7 +863,7 @@ </histogram> <histogram name="Apps.AppList.Search.Error" enum="AppListUserEventError" - expires_after="2022-12-25"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -874,7 +874,7 @@ </histogram> <histogram name="Apps.AppList.Search.{SearchView}" enum="AppListSearchAction" - expires_after="2022-08-15"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -901,7 +901,7 @@ </histogram> <histogram name="Apps.AppList.Search.{SearchView}.LaunchIndex" units="index" - expires_after="2022-08-15"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -913,7 +913,7 @@ </histogram> <histogram name="Apps.AppList.Search.{SearchView}.{SearchAction}" - enum="AppListSearchResult" expires_after="2022-08-15"> + enum="AppListSearchResult" expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -943,7 +943,7 @@ </histogram> <histogram name="Apps.AppList.SearchQueryLength.Apps" units="characters" - expires_after="2022-12-11"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -968,7 +968,7 @@ </histogram> <histogram name="Apps.AppList.SearchSuccess.Apps" enum="AppListLaunchedFrom" - expires_after="2022-10-29"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>thanhdng@chromium.org</owner> <owner>tby@chromium.org</owner> @@ -1068,10 +1068,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.LaunchIndex{LauncherUISurface}" - units="index" expires_after="2022-08-15"> + units="index" expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> Emitted on a usage of the launcher, and records overall impressions, launches, and abandons for a launcher UI view. The bucket proportion is not @@ -1089,10 +1089,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.Overall{LauncherUISurface}" - enum="AppListUserEvent" expires_after="2022-08-15"> + enum="AppListUserEvent" expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> Emitted on a usage of the launcher, and records overall impressions, launches, and abandons for a launcher UI view. The bucket proportion is not @@ -1110,10 +1110,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.Query" enum="Boolean" - expires_after="2022-08-15"> + expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> Emits true when the user enters a query into the Chrome OS launcher search box. Entering any number of characters is considered only one query, but @@ -1127,10 +1127,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.TypeAbandon{LauncherUISurface}" - enum="AppListSearchResult" expires_after="2022-08-15"> + enum="AppListSearchResult" expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> Emitted after an impression, if the user then closes the launcher or moves to a different view without launching any search result. This is emitted @@ -1150,10 +1150,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.TypeImpression{LauncherUISurface}" - enum="AppListSearchResult" expires_after="2022-08-15"> + enum="AppListSearchResult" expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> When a set of results is displayed for 2 seconds and the user has probably seen it, or the user interacted with the results and has definitely seen it, @@ -1179,10 +1179,10 @@ </histogram> <histogram name="Apps.AppList.UserEvent.TypeLaunch{LauncherUISurface}" - enum="AppListSearchResult" expires_after="2022-08-15"> + enum="AppListSearchResult" expires_after="2023-01-31"> + <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> - <owner>wrong@chromium.org</owner> <summary> Emitted after an impression, if the user launches a result. Records the type of the launched result. See Apps.AppList.UserEvent.TypeImpression for more @@ -1201,7 +1201,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateDriveProvider.Relevance" units="score" - expires_after="2022-06-30"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> @@ -1212,7 +1212,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateFileProvider.Latency" units="ms" - expires_after="2022-10-04"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <summary> @@ -1222,7 +1222,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateFileProvider.Relevance" units="score" - expires_after="2022-06-30"> + expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <owner>thanhdng@chromium.org</owner> @@ -1233,7 +1233,7 @@ </histogram> <histogram name="Apps.AppList.ZeroStateResults.LaunchedItemType" - enum="ZeroStateResultType" expires_after="2022-10-31"> + enum="ZeroStateResultType" expires_after="2023-01-31"> <owner>wrong@chromium.org</owner> <owner>tby@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/autofill/histograms.xml b/tools/metrics/histograms/metadata/autofill/histograms.xml index 9b09385..3e8e6ff 100644 --- a/tools/metrics/histograms/metadata/autofill/histograms.xml +++ b/tools/metrics/histograms/metadata/autofill/histograms.xml
@@ -2085,6 +2085,10 @@ <histogram name="Autofill.Offer.StoredOfferCount" units="offers" expires_after="2022-12-04"> + <obsolete> + Deprecated in June 2022. Subsumed by + Autofill.Offer.StoredOfferCount.{OfferType}. + </obsolete> <owner>siyua@chromium.org</owner> <owner>payments-autofill-team@google.com</owner> <summary> @@ -2093,6 +2097,17 @@ </summary> </histogram> +<histogram name="Autofill.Offer.StoredOfferCount.{OfferType}" units="offers" + expires_after="2022-12-04"> + <owner>siyua@chromium.org</owner> + <owner>payments-autofill-team@google.com</owner> + <summary> + Tracks the number of Autofill offers a user has stored, separated by offer + type, and measured at Chrome profile launch time. + </summary> + <token key="OfferType" variants="Autofill.OfferNotification.Type"/> +</histogram> + <histogram name="Autofill.Offer.StoredOfferRelatedCardCount" units="cards" expires_after="2022-12-04"> <owner>siyua@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/content_creation/histograms.xml b/tools/metrics/histograms/metadata/content_creation/histograms.xml index f4e7ea1..f01a835 100644 --- a/tools/metrics/histograms/metadata/content_creation/histograms.xml +++ b/tools/metrics/histograms/metadata/content_creation/histograms.xml
@@ -222,7 +222,7 @@ </histogram> <histogram name="NoteCreation.CreationStatus" enum="BooleanCreated" - expires_after="2022-10-30"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary> @@ -232,7 +232,7 @@ </histogram> <histogram name="NoteCreation.Funnel" enum="NoteCreationFunnel" - expires_after="2022-12-11"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary> @@ -242,14 +242,14 @@ </histogram> <histogram name="NoteCreation.NoteShared" enum="BooleanShared" - expires_after="2022-08-28"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary>Records whether the created note was shared or not.</summary> </histogram> <histogram name="NoteCreation.NumberOfTemplateChanges" - units="Number of changes" expires_after="2022-08-14"> + units="Number of changes" expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary> @@ -282,7 +282,7 @@ </histogram> <histogram name="NoteCreation.SelectedTemplate" enum="NoteTemplate" - expires_after="2022-10-30"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary> @@ -291,7 +291,7 @@ </histogram> <histogram name="NoteCreation.ShareDestination" enum="NoteShareDestination" - expires_after="2022-10-30"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary> @@ -310,7 +310,7 @@ </histogram> <histogram name="NoteCreation.TimeTo{action}" units="ms" - expires_after="2022-08-10"> + expires_after="2022-12-04"> <owner>sebsg@chromium.org</owner> <owner>chrome-creation@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/net/histograms.xml b/tools/metrics/histograms/metadata/net/histograms.xml index 89ea24b..e07e0e21 100644 --- a/tools/metrics/histograms/metadata/net/histograms.xml +++ b/tools/metrics/histograms/metadata/net/histograms.xml
@@ -1369,7 +1369,7 @@ </histogram> <histogram name="Net.DomainReliability.BeaconOutcome" - enum="DomainReliabilityBeaconOutcome" expires_after="2022-07-03"> + enum="DomainReliabilityBeaconOutcome" expires_after="2022-12-29"> <owner>mmenke@chromium.org</owner> <owner>src/net/network_error_logging/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/omnibox/histograms.xml b/tools/metrics/histograms/metadata/omnibox/histograms.xml index c89caf6..f13533fc 100644 --- a/tools/metrics/histograms/metadata/omnibox/histograms.xml +++ b/tools/metrics/histograms/metadata/omnibox/histograms.xml
@@ -1275,28 +1275,6 @@ </summary> </histogram> -<histogram name="Omnibox.SearchPrefetch.PrefetchServingReason.Prerender" - enum="SearchPrefetchServingReason" expires_after="2022-12-11"> - <owner>lingqi@chromium.org</owner> - <owner>ryansturm@chromium.org</owner> - <owner>chrome-prerendering@google.com</owner> - <summary> - Records whether a search prerender request uses the prefetched response. - SearchPrefetchService records this metric when - SearchPrefetchURLLoaderInterceptor attempts to intercept a prerendering main - resource request, for prerender main frame navigations with the feature flag - of SearchPrefetchUpgradeToPrerender enabled. - - Backgound: A search prerender request should use the prefetched response - instead of resending the same request, otherwise it will waste resources. - The search suggestion service may suggest to prefetch a result page, and - then ask the client to prerender the page. When the client attempts - prerender the page, it has received the response associated with the - prefetch request (by design), and should serve the prefetched response to - the prerender request. - </summary> -</histogram> - <histogram name="Omnibox.SearchPrefetch.StartTime.NavigationPrefetch" units="ms" expires_after="2022-10-30"> <owner>ryansturm@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/page/histograms.xml b/tools/metrics/histograms/metadata/page/histograms.xml index fffe8c6..457ddea 100644 --- a/tools/metrics/histograms/metadata/page/histograms.xml +++ b/tools/metrics/histograms/metadata/page/histograms.xml
@@ -2045,7 +2045,7 @@ </histogram> <histogram name="PageLoad.InteractiveTiming.FirstInputTimestamp4" units="ms" - expires_after="2022-07-03"> + expires_after="2023-07-03"> <owner>sullivan@chromium.org</owner> <owner>speed-metrics-dev@chromium.org</owner> <summary> @@ -2247,7 +2247,7 @@ <histogram name="PageLoad.Internal.PaintTiming.LargestContentfulPaint.MainFrame.ContentType" - enum="LargestContentType" expires_after="2022-07-03"> + enum="LargestContentType" expires_after="2023-07-03"> <owner>npm@chromium.org</owner> <owner>speed-metrics-dev@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index 47ce70a..76efaa66 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -134,63 +134,6 @@ </summary> </histogram> -<histogram name="Discarding.HighPMFPolicy.DiscardAttemptsCount" units="tabs" - expires_after="2021-12-06"> - <owner>chrisha@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - The number of tab discard attempts during a high-PMF session. Recorded at - the end of each high PMF session, or when the number of discard attempts - within the same high-PMF session reaches 100 (at which point the counter - will reset, e.g. 102 discards attempts would be recorded in two pieces as - "100" and "2"). - </summary> -</histogram> - -<histogram name="Discarding.HighPMFPolicy.DiscardSuccess" enum="BooleanSuccess" - expires_after="2021-12-06"> - <owner>chrisha@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - Indicates if a tab has been successfully discarded during a high-PMF - session. - </summary> -</histogram> - -<histogram name="Discarding.HighPMFPolicy.MemoryPressureLevel" - enum="MemoryPressureLevel" expires_after="2022-02-06"> - <owner>chrisha@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - The memory pressure level when the High-PMF policy decides to discard a tab. - Windows and Mac only. - </summary> -</histogram> - -<histogram name="Discarding.HighPMFPolicy.MemoryReclaimedKbAfterDiscardingATab" - units="KB" expires_after="2021-12-06"> - <owner>chrisha@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - The amount of memory that has been reclaimed after discarding a tab during a - high-PMF session. In the case of a memory increase the value will be - reported as 0 and will go in the underflow bucket. - </summary> -</histogram> - -<histogram name="Discarding.HighPMFPolicy.SuccessfulDiscardsCount" units="tabs" - expires_after="2021-12-06"> - <owner>chrisha@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - The number of successful tab discards during a high-PMF session. Recorded at - the end of each high PMF session, or when the number of successful discards - within the same high-PMF session reaches 100 (at which point the counter - will reset, e.g. 102 successful discards would be recorded in two pieces as - "100" and "2"). - </summary> -</histogram> - <histogram name="Discarding.LargestTabFootprint" units="MiB" expires_after="2021-02-28"> <owner>chrisha@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index d8987eb..78a33938 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,24 +5,24 @@ "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "836c993b348d0ca5b59f58999143ddf5d019e1ba", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/d86457ab539f83842f0e6c891c459bd764267b8d/trace_processor_shell.exe" + "hash": "8f54baebd8c6f45dad0af18f35449b6532b05bd7", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/80dd4d929a592772a530e67c30d9f76bb63f5219/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "86145908aed91663341ff82850a62108e55baac2", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/bb4e6b261ffdcda41c15bf830e594f9c9fe0ce3e/trace_processor_shell" + "hash": "7db84be27e17cdc421d71c50746795bc47ccc0af", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/80dd4d929a592772a530e67c30d9f76bb63f5219/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6", "full_remote_path": "perfetto-luci-artifacts/v25.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "3963de6f2c1864244db56893a436bf609dcda8a3", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/bb4e6b261ffdcda41c15bf830e594f9c9fe0ce3e/trace_processor_shell" + "hash": "96a6d55536fe9e1c00ed537e551094fe03fd93ab", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/80dd4d929a592772a530e67c30d9f76bb63f5219/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index 5298fbb7..a620aee 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -74,6 +74,10 @@ crbug.com/1300680 [ android ] blink_perf.webcodecs/software-video-encoding.html [ Skip ] crbug.com/1301260 [ linux ] blink_perf.webcodecs/hardware-video-encoding.html [ Skip ] +# Benchmark: blink_perf.webgl +crbug.com/1341884 [ linux ] blink_perf.webgl_fast_call/binding-buffer-sub-data.html [ Skip ] +crbug.com/1341884 [ linux ] blink_perf.webgl/binding-buffer-sub-data.html [ Skip ] + # Benchmark: jetstream crbug.com/1009843 [ android ] jetstream/JetStream [ Skip ] @@ -186,6 +190,18 @@ crbug.com/1306653 [ fuchsia-chrome ] media.desktop/video.html?src=smpte_3840x2160_60fps_vp9.webm&seek [ Skip ] crbug.com/1306653 [ fuchsia-chrome ] media.desktop/video.html?src=tulip2.vp9.webm&background [ Skip ] crbug.com/1325314 [ win ] rendering.desktop/espn_pinch_2018 [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_attrib_arrays [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_fast_call [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_indexed [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_indexed_fast_call [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_indexed_multi_draw [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_indexed_multi_draw_base_vertex_base_instance [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/animometer_webgl_multi_draw [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/aquarium [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/aquarium_20k [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/aquarium_20k_fast_call [ Skip ] +crbug.com/1341890 [ chromeos ] rendering.desktop/blob [ Skip ] # Benchmark: rendering.mobile crbug.com/785485 [ android-webview ] rendering.mobile/kevs_3d [ Skip ]
diff --git a/ui/compositor/compositor.h b/ui/compositor/compositor.h index 68332e45..e0345f59 100644 --- a/ui/compositor/compositor.h +++ b/ui/compositor/compositor.h
@@ -350,7 +350,10 @@ void WillBeginMainFrame() override {} void DidBeginMainFrame() override {} void OnDeferMainFrameUpdatesChanged(bool) override {} - void OnDeferCommitsChanged(bool, cc::PaintHoldingReason) override {} + void OnDeferCommitsChanged( + bool, + cc::PaintHoldingReason, + absl::optional<cc::PaintHoldingCommitTrigger>) override {} void WillUpdateLayers() override {} void DidUpdateLayers() override; void BeginMainFrame(const viz::BeginFrameArgs& args) override;
diff --git a/ui/file_manager/file_manager/foreground/css/file_manager.css b/ui/file_manager/file_manager/foreground/css/file_manager.css index a093442..0c38b7f8 100644 --- a/ui/file_manager/file_manager/foreground/css/file_manager.css +++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -1425,6 +1425,7 @@ } body.files-ng grid .grid-title { + box-sizing: border-box; color: var(--cros-text-color-secondary); font-family: 'Roboto Medium'; padding-inline-start: 16px; @@ -1432,8 +1433,21 @@ width: 100%; } -body.files-ng grid .grid-title.files { - padding-top: calc(20px + 16px); +grid .grid-title.group-by-isDirectory { + /* Folders/Files heading doesn't have border bottom, so having a padding + * bottom together with grid item's margin-top will make the gap too big. + * To prevent that, we can treat grid item (.thumbnail-item)'s margin-top + * (16px) as heading's padding bottom, that's why we use the desired height + * to minus the margin-top value here. + */ + height: calc(56px - 16px); +} + +grid .grid-title.group-by-modificationTime { + border-bottom: 1px solid var(--cros-separator-color); + /* The desired height plus the border width. */ + height: calc(56px + 1px); + padding-bottom: 16px; } body.files-ng .thumbnail-frame > .img-container { @@ -1756,7 +1770,8 @@ /* Modify GROUP_HEADING_HEIGHT in file_table_list.js if this height changes. */ #list-container li[group-heading] { - margin-top: 56px; + /* The desired height plus the border width. */ + margin-top: calc(56px + 1px); } #list-container li[group-heading]::before { @@ -1764,13 +1779,16 @@ color: var(--cros-text-color-secondary); content: attr(group-heading); display: block; - font-size: 13px; - font-weight: 500; + font-family: 'Roboto Medium'; left: 0; - padding: 20px 20px 16px 16px; + padding-bottom: 16px; + padding-inline-end: 20px; + padding-inline-start: 16px; + padding-top: 20px; pointer-events: none; position: absolute; - top: -56px; + /* Align with li[group-heading]'s margin-top. */ + top: -57px; width: 100%; }
diff --git a/ui/file_manager/file_manager/foreground/js/BUILD.gn b/ui/file_manager/file_manager/foreground/js/BUILD.gn index 33660db6..52e5744 100644 --- a/ui/file_manager/file_manager/foreground/js/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/BUILD.gn
@@ -331,6 +331,7 @@ js_library("app_state_controller") { deps = [ ":directory_model", + ":file_list_model", "ui:file_manager_ui", "ui:list_container", "//ui/file_manager/file_manager/common/js:app_util", @@ -525,7 +526,9 @@ "//ui/file_manager/file_manager/common/js:recent_date_bucket", "//ui/file_manager/file_manager/common/js:util", "//ui/file_manager/file_manager/externs:entry_location", + "//ui/file_manager/file_manager/externs:files_app_entry_interfaces", "//ui/file_manager/file_manager/externs:volume_manager", + "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js/cr/ui:array_data_model.m", ] }
diff --git a/ui/file_manager/file_manager/foreground/js/app_state_controller.js b/ui/file_manager/file_manager/foreground/js/app_state_controller.js index 538ecb7..1dbec3d 100644 --- a/ui/file_manager/file_manager/foreground/js/app_state_controller.js +++ b/ui/file_manager/file_manager/foreground/js/app_state_controller.js
@@ -10,6 +10,7 @@ import {xfm} from '../../common/js/xfm.js'; import {DirectoryModel} from './directory_model.js'; +import {GROUP_BY_FIELD_DIRECTORY, GROUP_BY_FIELD_MODIFICATION_TIME} from './file_list_model.js'; import {FileManagerUI} from './ui/file_manager_ui.js'; import {ListContainer} from './ui/list_container.js'; @@ -192,17 +193,24 @@ // 1) 'date-mofidied' and 'desc' order on Recent folder. // 2) preferred field and direction on other folders. const isOnRecent = util.isRecentRoot(event.newDirEntry); + const fileListModel = this.directoryModel_.getFileList(); + this.ui_.listContainer.isOnRecent = isOnRecent; const isOnRecentBefore = event.previousDirEntry && util.isRecentRoot(event.previousDirEntry); if (isOnRecent != isOnRecentBefore) { if (isOnRecent) { - this.directoryModel_.getFileList().toggleGroupHeading(true); - this.directoryModel_.getFileList().sort( + if (util.isRecentsFilterV2Enabled()) { + fileListModel.groupByField = GROUP_BY_FIELD_MODIFICATION_TIME; + } + fileListModel.sort( AppStateController.DEFAULT_SORT_FIELD, AppStateController.DEFAULT_SORT_DIRECTION); } else { - this.directoryModel_.getFileList().toggleGroupHeading(false); - this.directoryModel_.getFileList().sort( + const isGridView = this.ui_.listContainer.currentListType === + ListContainer.ListType.THUMBNAIL; + fileListModel.groupByField = + isGridView ? GROUP_BY_FIELD_DIRECTORY : null; + fileListModel.sort( this.fileListSortField_, this.fileListSortDirection_); } }
diff --git a/ui/file_manager/file_manager/foreground/js/banner_controller.js b/ui/file_manager/file_manager/foreground/js/banner_controller.js index cf5dc9ce..f5c6b847 100644 --- a/ui/file_manager/file_manager/foreground/js/banner_controller.js +++ b/ui/file_manager/file_manager/foreground/js/banner_controller.js
@@ -820,11 +820,15 @@ return; } for (const volumeId of this.pendingVolumeSizeUpdates_) { - const sizeStats = await getSizeStats(volumeId); - if (!sizeStats || sizeStats.totalSize === 0) { - continue; + try { + const sizeStats = await getSizeStats(volumeId); + if (!sizeStats || sizeStats.totalSize === 0) { + continue; + } + this.volumeSizeStats_[volumeId] = sizeStats; + } catch (e) { + console.warn('Error getting size stats', e); } - this.volumeSizeStats_[volumeId] = sizeStats; } this.pendingVolumeSizeUpdates_.clear(); await this.reconcile();
diff --git a/ui/file_manager/file_manager/foreground/js/file_list_model.js b/ui/file_manager/file_manager/foreground/js/file_list_model.js index c7c9722..d0140c06 100644 --- a/ui/file_manager/file_manager/foreground/js/file_list_model.js +++ b/ui/file_manager/file_manager/foreground/js/file_list_model.js
@@ -2,29 +2,44 @@ // 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 {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; import {FileExtensionType, FileType} from '../../common/js/file_type.js'; import {getRecentDateBucket, getTranslationKeyForDateBucket} from '../../common/js/recent_date_bucket.js'; import {str, strf, util} from '../../common/js/util.js'; import {EntryLocation} from '../../externs/entry_location.js'; +import {FilesAppEntry} from '../../externs/files_app_entry_interfaces.js'; import {VolumeManager} from '../../externs/volume_manager.js'; import {MetadataModel} from './metadata/metadata_model.js'; +export const GROUP_BY_FIELD_MODIFICATION_TIME = 'modificationTime'; +export const GROUP_BY_FIELD_DIRECTORY = 'isDirectory'; + const FIELDS_SUPPORT_GROUP_BY = new Set([ - 'modificationTime', + GROUP_BY_FIELD_MODIFICATION_TIME, + GROUP_BY_FIELD_DIRECTORY, ]); /** + * Currently we only support group by modificationTime or isDirectory, so the + * group value can only be one of them. + * @typedef {!chrome.fileManagerPrivate.RecentDateBucket|boolean} + */ +export let GroupValue; + +/** * This represents a group header. * * startIndex: the start index of this group. * * endIndex: the end index of this group. + * * group: the actual group value. * * label: the group label. * * @typedef {{ * startIndex: number, * endIndex: number, + * group: (GroupValue|undefined), * label: string, * }} */ @@ -111,12 +126,17 @@ this.locationInfo_ = null; /** - * @private {boolean} + * @type {boolean} */ - this.enableGroupHeading_ = false; + this.hasGroupHeadingBeforeSort = false; /** - * The key is the filed name which is used by groupBy. The value is a + * @private {string|null} The field to do group by on. + */ + this.groupByField_ = null; + + /** + * The key is the field name which is used by groupBy. The value is a * object with type GroupBySnapshot. * * @private {!Object<string, !GroupBySnapshot>} @@ -157,6 +177,7 @@ * @override */ sort(field, direction) { + this.hasGroupHeadingBeforeSort = this.shouldShowGroupHeading(); this.isDescendingOrder_ = direction === 'desc'; ArrayDataModel.prototype.sort.call(this, field, direction); } @@ -536,10 +557,20 @@ } /** - * @param {boolean} value enable or disable group heading. + * @return {string|null} */ - toggleGroupHeading(value) { - this.enableGroupHeading_ = value; + get groupByField() { + return this.groupByField_; + } + + /** + * @param {string|null} field the field to group by. + */ + set groupByField(field) { + this.groupByField_ = field; + if (!field || this.groupBySnapshot_[field].groups.length === 0) { + this.updateGroupBySnapshot_(); + } } /** @@ -547,8 +578,57 @@ * @return {boolean} */ shouldShowGroupHeading() { - return util.isRecentsFilterV2Enabled() && this.enableGroupHeading_ && - FIELDS_SUPPORT_GROUP_BY.has(this.sortStatus.field); + if (!this.groupByField_) { + return false; + } + // GroupBy modification time is only valid when the current sort field is + // modification time. + if (this.groupByField_ === GROUP_BY_FIELD_MODIFICATION_TIME) { + return this.sortStatus.field === this.groupByField_; + } + return FIELDS_SUPPORT_GROUP_BY.has(this.groupByField_); + } + + /** + * @param {!Entry} item Item in the file list model. + * @param {number} now Timestamp represents now. + * @return {!chrome.fileManagerPrivate.RecentDateBucket} + * @private + */ + getGroupForModificationTime_(item, now) { + const properties = this.metadataModel_.getCache( + [item], ['modificationTime', 'modificationByMeTime']); + return getRecentDateBucket( + new Date(this.getMtime_(properties[0])), new Date(now)); + } + + /** + * @param {!Entry} item Item in the file list model. + * @return {boolean} + * @private + */ + getGroupForDirectory_(item) { + return item.isDirectory; + } + + /** + * @param {GroupValue|undefined} value + * @return {string} + * @private + */ + getGroupLabel_(value) { + switch (this.groupByField_) { + case GROUP_BY_FIELD_MODIFICATION_TIME: + const dateBucket = + /** @type {chrome.fileManagerPrivate.RecentDateBucket} */ (value); + return str(getTranslationKeyForDateBucket(dateBucket)); + case GROUP_BY_FIELD_DIRECTORY: + const isDirectory = /** @type {boolean} */ (value); + return isDirectory ? str('GRID_VIEW_FOLDERS_TITLE') : + str('GRID_VIEW_FILES_TITLE'); + default: + return ''; + } } /** @@ -559,36 +639,38 @@ if (!this.shouldShowGroupHeading()) { return; } - if (this.sortStatus.field === 'modificationTime') { - /** @type {!GroupBySnapshot} */ - const snapshot = this.groupBySnapshot_.modificationTime; - snapshot.sortDirection = this.sortStatus.direction; - snapshot.groups = []; + assert(this.groupByField_); + /** @type {!GroupBySnapshot} */ + const snapshot = this.groupBySnapshot_[this.groupByField_]; + snapshot.sortDirection = this.sortStatus.direction; + snapshot.groups = []; - const now = Date.now(); - let prevDateBucket = null; - for (let i = 0; i < this.length; i++) { - const item = this.item(i); - const properties = this.metadataModel_.getCache( - [item], ['modificationTime', 'modificationByMeTime']); - const dateBucket = getRecentDateBucket( - new Date(this.getMtime_(properties[0])), new Date(now)); - if (prevDateBucket !== dateBucket) { - if (i > 1) { - snapshot.groups[snapshot.groups.length - 1].endIndex = i - 1; - } - snapshot.groups.push({ - startIndex: i, - endIndex: -1, - label: str(getTranslationKeyForDateBucket(dateBucket)), - }); + const now = Date.now(); + let prevItemGroup = null; + for (let i = 0; i < this.length; i++) { + const item = /** @type {!Entry} */ (this.item(i)); + let curItemGroup; + if (this.groupByField_ === GROUP_BY_FIELD_MODIFICATION_TIME) { + curItemGroup = this.getGroupForModificationTime_(item, now); + } else if (this.groupByField_ === GROUP_BY_FIELD_DIRECTORY) { + curItemGroup = this.getGroupForDirectory_(item); + } + if (prevItemGroup !== curItemGroup) { + if (i > 0) { + snapshot.groups[snapshot.groups.length - 1].endIndex = i - 1; } - prevDateBucket = dateBucket; + snapshot.groups.push({ + startIndex: i, + endIndex: -1, + group: curItemGroup, + label: this.getGroupLabel_(curItemGroup), + }); } - if (snapshot.groups.length > 0) { - // The last element is always the end of the last group. - snapshot.groups[snapshot.groups.length - 1].endIndex = this.length - 1; - } + prevItemGroup = curItemGroup; + } + if (snapshot.groups.length > 0) { + // The last element is always the end of the last group. + snapshot.groups[snapshot.groups.length - 1].endIndex = this.length - 1; } } @@ -600,10 +682,11 @@ if (!this.shouldShowGroupHeading()) { return []; } - if (this.sortStatus.field === 'modificationTime') { - /** @type {GroupBySnapshot} */ - const snapshot = this.groupBySnapshot_.modificationTime; - if (this.sortStatus.direction == snapshot.sortDirection) { + assert(this.groupByField_); + /** @type {GroupBySnapshot} */ + const snapshot = this.groupBySnapshot_[this.groupByField_]; + if (this.groupByField_ === GROUP_BY_FIELD_MODIFICATION_TIME) { + if (this.sortStatus.direction === snapshot.sortDirection) { return snapshot.groups; } // Why are we calculating reverse order data in the snapshot instead @@ -616,10 +699,16 @@ return { startIndex: this.length - 1 - group.endIndex, endIndex: this.length - 1 - group.startIndex, + group: group.group, label: group.label, }; }); } + // Grid view Folders/Files group order never changes, e.g. Folders group + // always shows first, and then Files group. + if (this.groupByField_ === GROUP_BY_FIELD_DIRECTORY) { + return snapshot.groups; + } return []; } }
diff --git a/ui/file_manager/file_manager/foreground/js/file_list_model_unittest.js b/ui/file_manager/file_manager/foreground/js/file_list_model_unittest.js index f3661b9..a2b954f 100644 --- a/ui/file_manager/file_manager/foreground/js/file_list_model_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/file_list_model_unittest.js
@@ -7,7 +7,7 @@ import {installMockChrome} from '../../common/js/mock_chrome.js'; -import {FileListModel, GroupHeader} from './file_list_model.js'; +import {FileListModel, GROUP_BY_FIELD_DIRECTORY, GROUP_BY_FIELD_MODIFICATION_TIME, GroupHeader} from './file_list_model.js'; import {MetadataModel} from './metadata/metadata_model.js'; const TEST_METADATA = { @@ -40,6 +40,8 @@ 'RECENT_TIME_HEADING_THIS_MONTH': 'earlier_this_month', 'RECENT_TIME_HEADING_THIS_YEAR': 'earlier_this_year', 'RECENT_TIME_HEADING_OLDER': 'older', + 'GRID_VIEW_FOLDERS_TITLE': 'folders', + 'GRID_VIEW_FILES_TITLE': 'files', }); // Set up mock of chrome.fileManagerPrivate APIs. @@ -260,13 +262,15 @@ export function testShouldShowGroupHeading() { const fileListModel = makeSimpleFileListModel([]); assertFalse(fileListModel.shouldShowGroupHeading()); - fileListModel.sort('modificationTime', 'asc'); + fileListModel.groupByField = GROUP_BY_FIELD_MODIFICATION_TIME; assertFalse(fileListModel.shouldShowGroupHeading()); - fileListModel.toggleGroupHeading(true); + fileListModel.sort(GROUP_BY_FIELD_MODIFICATION_TIME, 'asc'); + assertTrue(fileListModel.shouldShowGroupHeading()); + fileListModel.groupByField = GROUP_BY_FIELD_DIRECTORY; assertTrue(fileListModel.shouldShowGroupHeading()); } -export function testGetGroupBySnapshot() { +export function testGroupByModificationTime() { /** * @type {!Array<{ * metadataMap: !Object<string, {modificationTime: Date}>, @@ -289,8 +293,10 @@ modificationTime: new Date(2022, 5, 8, 8, 0, 2), }, }, - expectedGroups: [{startIndex: 0, endIndex: 0, label: 'today'}], - expectedReversedGroups: [{startIndex: 0, endIndex: 0, label: 'today'}], + expectedGroups: + [{startIndex: 0, endIndex: 0, label: 'today', group: 'today'}], + expectedReversedGroups: + [{startIndex: 0, endIndex: 0, label: 'today', group: 'today'}], }, // All items are in the same group. { @@ -308,8 +314,10 @@ modificationTime: new Date(2022, 5, 8, 6, 0, 2), }, }, - expectedGroups: [{startIndex: 0, endIndex: 2, label: 'today'}], - expectedReversedGroups: [{startIndex: 0, endIndex: 2, label: 'today'}], + expectedGroups: + [{startIndex: 0, endIndex: 2, label: 'today', group: 'today'}], + expectedReversedGroups: + [{startIndex: 0, endIndex: 2, label: 'today', group: 'today'}], }, // Items belong to different groups. { @@ -344,18 +352,48 @@ }, }, expectedGroups: [ - {startIndex: 0, endIndex: 1, label: 'today'}, - {startIndex: 2, endIndex: 2, label: 'yesterday'}, - {startIndex: 3, endIndex: 4, label: 'earlier_this_week'}, - {startIndex: 5, endIndex: 5, label: 'earlier_this_month'}, - {startIndex: 6, endIndex: 6, label: 'earlier_this_year'}, + {startIndex: 0, endIndex: 1, label: 'today', group: 'today'}, + {startIndex: 2, endIndex: 2, label: 'yesterday', group: 'yesterday'}, + { + startIndex: 3, + endIndex: 4, + label: 'earlier_this_week', + group: 'earlier_this_week' + }, + { + startIndex: 5, + endIndex: 5, + label: 'earlier_this_month', + group: 'earlier_this_month' + }, + { + startIndex: 6, + endIndex: 6, + label: 'earlier_this_year', + group: 'earlier_this_year' + }, ], expectedReversedGroups: [ - {startIndex: 0, endIndex: 0, label: 'earlier_this_year'}, - {startIndex: 1, endIndex: 1, label: 'earlier_this_month'}, - {startIndex: 2, endIndex: 3, label: 'earlier_this_week'}, - {startIndex: 4, endIndex: 4, label: 'yesterday'}, - {startIndex: 5, endIndex: 6, label: 'today'}, + { + startIndex: 0, + endIndex: 0, + label: 'earlier_this_year', + group: 'earlier_this_year' + }, + { + startIndex: 1, + endIndex: 1, + label: 'earlier_this_month', + group: 'earlier_this_month' + }, + { + startIndex: 2, + endIndex: 3, + label: 'earlier_this_week', + group: 'earlier_this_week' + }, + {startIndex: 4, endIndex: 4, label: 'yesterday', group: 'yesterday'}, + {startIndex: 5, endIndex: 6, label: 'today', group: 'today'}, ], }, ]; @@ -363,8 +401,8 @@ for (const test of testData) { const fileListModel = new FileListModel(createFakeMetadataModel(test.metadataMap)); - fileListModel.toggleGroupHeading(true); - fileListModel.sort('modificationTime', 'desc'); + fileListModel.groupByField = GROUP_BY_FIELD_MODIFICATION_TIME; + fileListModel.sort(GROUP_BY_FIELD_MODIFICATION_TIME, 'desc'); const files = Object.keys(test.metadataMap).map(fileName => { return {name: fileName, isDirectory: false}; }); @@ -372,8 +410,95 @@ const snapshot = fileListModel.getGroupBySnapshot(); assertArrayEquals(snapshot, test.expectedGroups); // Reverse order. - fileListModel.sort('modificationTime', 'asc'); + fileListModel.sort(GROUP_BY_FIELD_MODIFICATION_TIME, 'asc'); const snapshotReverse = fileListModel.getGroupBySnapshot(); assertArrayEquals(snapshotReverse, test.expectedReversedGroups); } } + +export function testGroupByDirectory() { + /** + * @type {!Array<{ + * metadataMap: !Object<string, {isDirectory: boolean}>, + * expectedGroups: !Array<!GroupHeader>, + * expectedFileList: !Array<string>, + * expectedReversedFileList: !Array<string>, + * }>} + */ + const testData = [ + // Empty list. + { + metadataMap: {}, + expectedGroups: [], + expectedFileList: [], + expectedReversedFileList: [], + }, + // Only one item. + { + metadataMap: { + 'a.txt': {isDirectory: false}, + }, + expectedGroups: + [{startIndex: 0, endIndex: 0, label: 'files', group: false}], + expectedFileList: ['a.txt'], + expectedReversedFileList: ['a.txt'], + }, + // All items are in the same group. + { + metadataMap: { + 'a': {isDirectory: true}, + 'b': {isDirectory: true}, + 'c': {isDirectory: true}, + }, + expectedGroups: + [{startIndex: 0, endIndex: 2, label: 'folders', group: true}], + expectedFileList: ['a', 'b', 'c'], + expectedReversedFileList: ['c', 'b', 'a'], + }, + // Items belong to different groups. + { + metadataMap: { + 'a': {isDirectory: true}, + 'c': {isDirectory: true}, + 'f': {isDirectory: true}, + 'b.txt': {isDirectory: false}, + 'd.txt': {isDirectory: false}, + 'e.txt': {isDirectory: false}, + }, + expectedGroups: [ + {startIndex: 0, endIndex: 2, label: 'folders', group: true}, + {startIndex: 3, endIndex: 5, label: 'files', group: false}, + ], + expectedFileList: ['a', 'c', 'f', 'b.txt', 'd.txt', 'e.txt'], + expectedReversedFileList: ['f', 'c', 'a', 'e.txt', 'd.txt', 'b.txt'], + }, + ]; + + for (const test of testData) { + const fileListModel = new FileListModel(createFakeMetadataModel({})); + fileListModel.groupByField = GROUP_BY_FIELD_DIRECTORY; + fileListModel.sort('name', 'asc'); + const files = Object.keys(test.metadataMap).map(fileName => { + return { + name: fileName, + isDirectory: test.metadataMap[fileName].isDirectory + }; + }); + fileListModel.push(...files); + const snapshot = fileListModel.getGroupBySnapshot(); + assertArrayEquals(snapshot, test.expectedGroups); + for (let i = 0; i < fileListModel.length; i++) { + const item = fileListModel.item(i); + assertEquals(item.name, test.expectedFileList[i]); + } + // Reverse order won't change the group snapshot, e.g Folders are always + // at the beginning. + fileListModel.sort('name', 'desc'); + const snapshotReverse = fileListModel.getGroupBySnapshot(); + assertArrayEquals(snapshotReverse, test.expectedGroups); + for (let i = 0; i < fileListModel.length; i++) { + const item = fileListModel.item(i); + assertEquals(item.name, test.expectedReversedFileList[i]); + } + } +}
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js index 5d28934..70ae59a 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
@@ -2363,7 +2363,7 @@ CommandHandler.COMMANDS_['manage-mirrorsync'] = new (class extends FilesCommand { execute(event, fileManager) { - // TODO(b/237066325): Wire this up to the `ManageMirrorSyncDialog`. + chrome.fileManagerPrivate.openManageSyncSettings(); } /**
diff --git a/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn b/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn index b5d84def..c611da5 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn
@@ -280,6 +280,7 @@ "//ui/file_manager/file_manager/externs:files_app_entry_interfaces", "//ui/file_manager/file_manager/externs:volume_manager", "//ui/file_manager/file_manager/externs/background:import_history", + "//ui/file_manager/file_manager/foreground/js:file_list_model", "//ui/file_manager/file_manager/foreground/js:list_thumbnail_loader", "//ui/file_manager/file_manager/foreground/js/metadata:metadata_model", "//ui/webui/resources/js:assert.m", @@ -292,6 +293,24 @@ ] } +js_unittest("file_grid_unittest") { + deps = [ + ":a11y_announce", + ":file_grid", + "//chrome/test/data/webui:chai_assert", + "//ui/file_manager/file_manager/background/js:mock_volume_manager", + "//ui/file_manager/file_manager/common/js:files_app_entry_types", + "//ui/file_manager/file_manager/common/js:mock_chrome", + "//ui/file_manager/file_manager/common/js:volume_manager_types", + "//ui/file_manager/file_manager/externs/background:import_history", + "//ui/file_manager/file_manager/foreground/js:file_list_model", + "//ui/file_manager/file_manager/foreground/js/metadata:metadata_model", + "//ui/file_manager/file_manager/foreground/js/metadata:mock_metadata", + "//ui/webui/resources/js:load_time_data.m", + "//ui/webui/resources/js/cr/ui:list_selection_model.m", + ] +} + js_library("file_list_selection_model") { deps = [ "//ui/webui/resources/js/cr/ui:list_selection_model.m", @@ -421,6 +440,7 @@ ":a11y_announce", ":file_list_selection_model", ":file_tap_handler", + "table:table", "table:table_list", "//ui/file_manager/file_manager/common/js:file_type", "//ui/file_manager/file_manager/common/js:util", @@ -448,7 +468,6 @@ "//ui/file_manager/file_manager/common/js:files_app_entry_types", "//ui/file_manager/file_manager/common/js:volume_manager_types", "//ui/file_manager/file_manager/externs/background:import_history", - "//ui/file_manager/file_manager/foreground/js:directory_model", "//ui/file_manager/file_manager/foreground/js:file_list_model", "//ui/file_manager/file_manager/foreground/js/metadata:metadata_model", "//ui/file_manager/file_manager/foreground/js/metadata:mock_metadata", @@ -667,6 +686,7 @@ ":actions_submenu_unittest", ":breadcrumb_unittest", ":directory_tree_unittest", + ":file_grid_unittest", ":file_list_selection_model_unittest", ":file_manager_dialog_base_unittest", ":file_table_list_unittest",
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js index 99df6ec7..866d994 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js
@@ -13,10 +13,11 @@ import {AsyncUtil} from '../../../common/js/async_util.js'; import {FileType} from '../../../common/js/file_type.js'; import {importer} from '../../../common/js/importer_common.js'; -import {str, util} from '../../../common/js/util.js'; +import {util} from '../../../common/js/util.js'; import {importerHistoryInterfaces} from '../../../externs/background/import_history.js'; import {FilesAppEntry} from '../../../externs/files_app_entry_interfaces.js'; import {VolumeManager} from '../../../externs/volume_manager.js'; +import {FileListModel, GROUP_BY_FIELD_DIRECTORY, GROUP_BY_FIELD_MODIFICATION_TIME, GroupValue} from '../file_list_model.js'; import {ListThumbnailLoader} from '../list_thumbnail_loader.js'; import {MetadataModel} from '../metadata/metadata_model.js'; @@ -25,6 +26,12 @@ import {filelist} from './file_table_list.js'; import {FileTapHandler} from './file_tap_handler.js'; + +// Align with CSS .grid-title.group-by-modificationTime. +const MODIFICATION_TIME_GROUP_HEADING_HEIGHT = 57; +// Align with CSS .grid-title.group-by-isDirectory. +const DIRECTORY_GROUP_HEADING_HEIGHT = 40; + /** * FileGrid constructor. * @@ -114,11 +121,13 @@ // listener for the current data model. if (this.dataModel) { this.dataModel.removeEventListener('splice', this.onSplice_.bind(this)); + this.dataModel.removeEventListener('sorted', this.onSorted_.bind(this)); } this.dataModelDescriptor_.set.call(this, model); if (this.dataModel) { this.dataModel.addEventListener('splice', this.onSplice_.bind(this)); this.classList.toggle('image-dominant', this.dataModel.isImageDominant()); + this.dataModel.addEventListener('sorted', this.onSorted_.bind(this)); } } @@ -265,69 +274,12 @@ */ mergeItems(beginIndex, endIndex) { List.prototype.mergeItems.call(this, beginIndex, endIndex); - - const afterFiller = this.afterFiller_; - const columns = this.columns; - let previousTitle = ''; - - for (let item = this.beforeFiller_.nextSibling; item !== afterFiller;) { - const next = item.nextSibling; - if (isSpacer(item)) { - // Spacer found on a place it mustn't be. - this.removeChild(item); - item = next; - continue; - } - const index = item.listIndex; - const nextIndex = index + 1; - - const entry = this.dataModel.item(index); - if (entry) { - if (entry.isDirectory && previousTitle !== 'dir') { - // For first Directory we add a title div before the element. - const title = document.createElement('div'); - title.innerText = str('GRID_VIEW_FOLDERS_TITLE'); - title.classList.add('grid-title', 'folders'); - this.insertBefore(title, item); - previousTitle = 'dir'; - } else if (!entry.isDirectory && previousTitle !== 'file') { - // For first File we add a title div before the element. - const title = document.createElement('div'); - title.innerText = str('GRID_VIEW_FILES_TITLE'); - title.classList.add('grid-title', 'files'); - this.insertBefore(title, item); - previousTitle = 'file'; - } - } - - // Invisible pinned item could be outside of the - // [beginIndex, endIndex). Ignore it. - if (index >= beginIndex && nextIndex < endIndex && - (nextIndex < this.dataModel.getFolderCount() ? - nextIndex % columns === 0 : - (nextIndex - this.dataModel.getFolderCount()) % columns === 0)) { - const isFolderSpacer = nextIndex === this.dataModel.getFolderCount(); - if (isSpacer(next)) { - // Leave the spacer on its place. - next.classList.toggle('folder-spacer', isFolderSpacer); - item = next.nextSibling; - } else { - // Insert spacer. - const spacer = this.ownerDocument.createElement('div'); - spacer.className = 'spacer'; - spacer.classList.toggle('folder-spacer', isFolderSpacer); - this.insertBefore(spacer, next); - item = next; - } - } else { - item = next; - } - } - - function isSpacer(child) { - return child.classList.contains('spacer') && - child !== afterFiller; // Must not be removed. - } + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = + fileListModel ? fileListModel.getGroupBySnapshot() : []; + const startIndexToGroupLabel = new Map(groupBySnapshot.map(group => { + return [group.startIndex, group]; + })); // Make sure that grid item's selected attribute is updated just after the // mergeItems operation is done. This prevents shadow of selected grid items @@ -341,6 +293,15 @@ if (item.selected !== isSelected) { item.selected = isSelected; } + // Check if index i is the start of a new group. + if (startIndexToGroupLabel.has(i)) { + // For first item in each group, we add a title div before the element. + const title = document.createElement('div'); + title.innerText = startIndexToGroupLabel.get(i).label; + title.classList.add( + 'grid-title', `group-by-${fileListModel.groupByField}`); + this.insertBefore(title, item); + } } // Keep these values to set range when a new list thumbnail loader is set. @@ -355,28 +316,58 @@ * @override */ getItemTop(index) { - if (index < this.dataModel.getFolderCount()) { - return Math.floor(index / this.columns) * this.getFolderItemHeight_(); - } + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); - const folderRows = this.getFolderRowCount(); - const indexInFiles = index - this.dataModel.getFolderCount(); - return folderRows * this.getFolderItemHeight_() + - (folderRows > 0 ? this.getSeparatorHeight_() : 0) + - Math.floor(indexInFiles / this.columns) * this.getFileItemHeight_(); + let top = 0; + let totalItemCount = 0; + for (const group of groupBySnapshot) { + if (index <= group.endIndex) { + // The index falls into the current group. Calculates how many rows + // we have in the current group up until this index. + const indexInCurGroup = index - totalItemCount; + const rowsInCurGroup = Math.floor(indexInCurGroup / this.columns); + top += (rowsInCurGroup > 0 ? this.getGroupHeadingHeight_() : 0) + + rowsInCurGroup * this.getGroupItemHeight_(group.group); + break; + } else { + // The index is not in the current group. Add all row heights in this + // group to the final result. + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / this.columns); + top += this.getGroupHeadingHeight_() + + groupRowCount * this.getGroupItemHeight_(group.group); + totalItemCount += groupItemCount; + } + } + return top; } /** * @override */ getItemRow(index) { - if (index < this.dataModel.getFolderCount()) { - return Math.floor(index / this.columns); - } + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); - const folderRows = this.getFolderRowCount(); - const indexInFiles = index - this.dataModel.getFolderCount(); - return folderRows + Math.floor(indexInFiles / this.columns); + let rows = 0; + let totalItemCount = 0; + for (const group of groupBySnapshot) { + if (index <= group.endIndex) { + // The index falls into the current group. Calculates how many rows + // we have in the current group up until this index. + const indexInCurGroup = index - totalItemCount; + rows += Math.floor(indexInCurGroup / this.columns); + break; + } else { + // The index is not in the current group. Add all rows in this + // group to the final result. + const groupItemCount = group.endIndex - group.startIndex + 1; + rows += Math.ceil(groupItemCount / this.columns); + totalItemCount += groupItemCount; + } + } + return rows; } /** @@ -384,12 +375,21 @@ * @param {number} index The item index. */ getItemColumn(index) { - if (index < this.dataModel.getFolderCount()) { - return index % this.columns; - } + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); - const indexInFiles = index - this.dataModel.getFolderCount(); - return indexInFiles % this.columns; + let totalItemCount = 0; + for (const group of groupBySnapshot) { + if (index <= group.endIndex) { + // The index falls into the current group. Calculates the column index + // with the remaining index in this group. + const indexInCurGroup = index - totalItemCount; + return indexInCurGroup % this.columns; + } + const groupItemCount = group.endIndex - group.startIndex + 1; + totalItemCount += groupItemCount; + } + return 0; } /** @@ -402,27 +402,53 @@ if (row < 0 || column < 0 || column >= this.columns) { return -1; } - const folderCount = this.dataModel.getFolderCount(); - const folderRows = this.getFolderRowCount(); - let index; - if (row < folderRows) { - index = row * this.columns + column; - return index < folderCount ? index : -1; + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); + + let curRow = 0; + let index = 0; + for (const group of groupBySnapshot) { + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / this.columns); + if (row < curRow + groupRowCount) { + // The row falls into the current group. Calculate the index based on + // the column value and return. + const isLastRowInGroup = row === curRow + groupRowCount - 1; + const itemCountInLastRow = + groupItemCount - (groupRowCount - 1) * this.columns; + if (isLastRowInGroup && column >= itemCountInLastRow) { + // column is larger than the item count in this row, return -1. + // This happens when we try to find the index for the above/below + // items. For example: + // -------------------------------------- + // item 0 item 1 item 2 + // item 3 (end of group) + // item 4 item 5 (end of group) + // -------------------------------------- + // * To find above index for item 5, we pass (row - 1, col), col is + // not existed in the above row. + // * To find the below index for item 2, we pass (row + 1, col), col + // is not existed in the below row. + return -1; + } + return index + (row - curRow) * this.columns + column; + } + curRow += groupRowCount; + index = group.endIndex + 1; } - index = folderCount + (row - folderRows) * this.columns + column; - return index < this.dataModel.length ? index : -1; + // `row` index is larger than the last row, return -1. + return -1; } /** * @override */ getFirstItemInRow(row) { - const folderRows = this.getFolderRowCount(); - if (row < folderRows) { - return row * this.columns; + if (row < 0) { + return 0; } - - return this.dataModel.getFolderCount() + (row - folderRows) * this.columns; + const index = this.getItemIndex(row, 0); + return index === -1 ? this.dataModel.length : index; } /** @@ -434,9 +460,7 @@ return; } - const itemHeight = index < this.dataModel.getFolderCount() ? - this.getFolderItemHeight_() : - this.getFileItemHeight_(); + const itemHeight = this.getItemHeightByIndex_(index); const scrollTop = this.scrollTop; const top = this.getItemTop(index); const clientHeight = this.clientHeight; @@ -476,14 +500,20 @@ * @override */ getItemsInViewPort(scrollTop, clientHeight) { - const beginRow = this.getRowForListOffset_(scrollTop); - const endRow = this.getRowForListOffset_(scrollTop + clientHeight - 1) + 1; - const beginIndex = this.getFirstItemInRow(beginRow); + // Render 1 more row above to make the scrolling more smooth. + const beginRow = this.getRowForListOffset_(scrollTop) - 1; + // Render 1 more rows below, +2 here because "endIndex" is the first item + // of the row, in order to render the whole +1 row, we need to make sure + // the "endIndex" is the first item of +2 row. + const endRow = this.getRowForListOffset_(scrollTop + clientHeight - 1) + 2; + const beginIndex = Math.max(0, this.getFirstItemInRow(beginRow)); const endIndex = Math.min(this.getFirstItemInRow(endRow), this.dataModel.length); const result = { - first: beginIndex, - length: endIndex - beginIndex, + // beginIndex + 1 here because "first" will be -1 when it's being + // consumed in redraw() method in the parent class. + first: beginIndex + 1, + length: endIndex - beginIndex - 1, last: endIndex - 1 }; return result; @@ -493,35 +523,36 @@ * @override */ getAfterFillerHeight(lastIndex) { - const folderRows = this.getFolderRowCount(); - const fileRows = this.getFileRowCount(); - const row = this.getItemRow(lastIndex - 1); - if (row < folderRows) { - let fillerHeight = (folderRows - 1 - row) * this.getFolderItemHeight_() + - fileRows * this.getFileItemHeight_(); - if (fileRows > 0) { - fillerHeight += this.getSeparatorHeight_(); + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); + // Excluding the current index, because [firstIndex, lastIndex) is used + // in mergeItems(). + const index = lastIndex - 1; + + let afterFillerHeight = 0; + let totalItemCount = 0; + let shouldAdd = false; + // Find the group of "index" and accumulate the height after that group. + for (const group of groupBySnapshot) { + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / this.columns); + if (shouldAdd) { + afterFillerHeight += this.getGroupHeadingHeight_() + + groupRowCount * this.getGroupItemHeight_(group.group); + } else if (index <= group.endIndex) { + // index falls into the current group. Starting from this group we need + // to add all remaining group heights into the final result. + const indexInCurGroup = Math.max(0, index - totalItemCount); + // For current group, we need to add the row heights starting from the + // row which current index locates. + afterFillerHeight += + (groupRowCount - Math.floor(indexInCurGroup / this.columns)) * + this.getGroupItemHeight_(group.group); + shouldAdd = true; } - return fillerHeight; + totalItemCount += groupItemCount; } - const rowInFiles = row - folderRows; - return (fileRows - 1 - rowInFiles) * this.getFileItemHeight_(); - } - - /** - * Returns the number of rows in folders section. - * @return {number} - */ - getFolderRowCount() { - return Math.ceil(this.dataModel.getFolderCount() / this.columns); - } - - /** - * Returns the number of rows in files section. - * @return {number} - */ - getFileRowCount() { - return Math.ceil(this.dataModel.getFileCount() / this.columns); + return afterFillerHeight; } /** @@ -529,7 +560,9 @@ * @return {number} The height of folder items. */ getFolderItemHeight_() { - return 44; // TODO(fukino): Read from DOM and cache it. + // Align with CSS value for .thumbnail-item.directory: height + margin + + // border. + return 40 + this.getItemMarginTop_() + 2; } /** @@ -537,7 +570,67 @@ * @return {number} The height of file items. */ getFileItemHeight_() { - return 184; // TODO(fukino): Read from DOM and cache it. + // Align with CSS value for .thumbnail-item: height + margin + border. + return 160 + this.getItemMarginTop_() + 2; + } + + /** + * Returns the height of group heading. + * @return {number} + * @private + */ + getGroupHeadingHeight_() { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + switch (fileListModel.groupByField) { + case GROUP_BY_FIELD_DIRECTORY: + return DIRECTORY_GROUP_HEADING_HEIGHT; + case GROUP_BY_FIELD_MODIFICATION_TIME: + return MODIFICATION_TIME_GROUP_HEADING_HEIGHT; + default: + return 0; + } + } + + /** + * Returns the height of the item in the group based on the group value. + * @param {GroupValue|undefined} groupValue + * @return {number} + * @private + */ + getGroupItemHeight_(groupValue) { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + switch (fileListModel.groupByField) { + case GROUP_BY_FIELD_DIRECTORY: + return groupValue === true ? this.getFolderItemHeight_() : + this.getFileItemHeight_(); + case GROUP_BY_FIELD_MODIFICATION_TIME: + return this.getFileItemHeight_(); + default: + return this.getFileItemHeight_(); + } + } + + /** + * Returns the height of the item specified by the index. + * @param {number} index + * @return {number} + * @private + */ + getItemHeightByIndex_(index) { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + if (fileListModel.groupByField === GROUP_BY_FIELD_MODIFICATION_TIME) { + return this.getFileItemHeight_(); + } + + const groupBySnapshot = fileListModel.getGroupBySnapshot(); + for (const group of groupBySnapshot) { + if (index <= group.endIndex) { + // The index falls into the current group, return group item height + // by its group value. + return this.getGroupItemHeight_(group.group); + } + } + return this.getFileItemHeight_(); } /** @@ -545,7 +638,8 @@ * @return {number} */ getItemWidth_() { - return 184; // TODO(fukino): Read from DOM and cache it. + // Align with CSS value for .thumbnail-item: width + margin + border. + return 180 + this.getItemMarginLeft_() + 2; } /** @@ -553,7 +647,8 @@ * @return {number}; */ getItemMarginTop_() { - return 4; // TODO(fukino): Read from DOM and cache it. + // Align with CSS value for .thumbnail-item: margin-top. + return 16; } /** @@ -561,15 +656,8 @@ * @return {number} */ getItemMarginLeft_() { - return 4; // TODO(fukino): Read from DOM and cache it. - } - - /** - * Returns the height of the separator which separates folders and files. - * @return {number} The height of the separator. - */ - getSeparatorHeight_() { - return 5; // TODO(fukino): Read from DOM and cache it. + // Align with CSS value for .thumbnail-item: margin-inline-start. + return 16; } /** @@ -580,16 +668,34 @@ */ getRowForListOffset_(offset) { const innerOffset = Math.max(0, offset - this.paddingTop_); - const folderRows = this.getFolderRowCount(); - if (innerOffset < folderRows * this.getFolderItemHeight_()) { - return Math.floor(innerOffset / this.getFolderItemHeight_()); - } + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); - let offsetInFiles = innerOffset - folderRows * this.getFolderItemHeight_(); - if (folderRows > 0) { - offsetInFiles = Math.max(0, offsetInFiles - this.getSeparatorHeight_()); + // Loop through all the groups, calculate the accumulated height for all + // items (item height + group heading height), until the total height + // reaches "offset", then we know how many items can be included in this + // offset. + let currentHeight = 0; + let curRow = 0; + for (const group of groupBySnapshot) { + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / this.columns); + const groupHeight = this.getGroupHeadingHeight_() + + groupRowCount * this.getGroupItemHeight_(group.group); + + if (currentHeight + groupHeight > innerOffset) { + // Current offset falls into the current group. Calculates how many + // rows in the offset within the group. + const offsetInCurGroup = Math.max( + 0, innerOffset - currentHeight - this.getGroupHeadingHeight_()); + return curRow + + Math.floor( + offsetInCurGroup / this.getGroupItemHeight_(group.group)); + } + currentHeight += groupHeight; + curRow += groupRowCount; } - return folderRows + Math.floor(offsetInFiles / this.getFileItemHeight_()); + return this.getItemRow(fileListModel.length - 1); } /** @@ -779,6 +885,21 @@ } /** + * @private + */ + onSorted_() { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const hasGroupHeadingAfterSort = fileListModel.shouldShowGroupHeading(); + // Sort doesn't trigger redraw sometimes, e.g. if we sort by Name for now, + // then we sort by time, if the list order doesn't change, no permuted event + // is triggered, thus no redraw is triggered. In this scenario, we need to + // manually trigger a redraw to remove/add the group heading. + if (hasGroupHeadingAfterSort !== fileListModel.hasGroupHeadingBeforeSort) { + this.redraw(); + } + } + + /** * Sets thumbnail image to the box. * @param {!HTMLDivElement} box A div element to hold thumbnails. * @param {!Entry} entry An entry of the thumbnail. @@ -907,47 +1028,64 @@ /** * Returns the index of row corresponding to the given y position. * - * If the reverse is false, this returns index of the first row in which + * If `isStart` is true, this returns index of the first row in which * bottom of grid items is greater than or equal to y. Otherwise, this returns * index of the last row in which top of grid items is less than or equal to * y. * @param {number} y - * @param {boolean} reverse + * @param {boolean} isStart * @return {number} * @private */ - getHitRowIndex_(y, reverse) { - const folderRows = this.getFolderRowCount(); - const folderHeight = this.getFolderItemHeight_(); - const fileHeight = this.getFileItemHeight_(); + getHitRowIndex_(y, isStart) { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); - if (y < folderHeight * folderRows) { - const shift = reverse ? -this.getItemMarginTop_() : 0; - return Math.floor((y + shift) / folderHeight); + let currentHeight = 0; + let curRow = 0; + const shift = isStart ? 0 : -this.getItemMarginTop_(); + const yAfterShift = y + shift; + for (const group of groupBySnapshot) { + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / this.columns); + const groupHeight = this.getGroupHeadingHeight_() + + groupRowCount * this.getGroupItemHeight_(group.group); + if (yAfterShift < currentHeight + groupHeight) { + // The y falls into the current group. + const yInCurGroup = + yAfterShift - currentHeight - this.getGroupHeadingHeight_(); + if (yInCurGroup < 0) { + // The remaining y in this group can't cover the current group + // heading height. + return isStart ? curRow : curRow - 1; + } + return Math.min( + curRow + groupRowCount - 1, + curRow + + Math.floor( + yInCurGroup / this.getGroupItemHeight_(group.group))); + } + currentHeight += groupHeight; + curRow += groupRowCount; } - let yInFiles = y - folderHeight * folderRows; - if (folderRows > 0) { - yInFiles = Math.max(0, yInFiles - this.getSeparatorHeight_()); - } - const shift = reverse ? -this.getItemMarginTop_() : 0; - return folderRows + Math.floor((yInFiles + shift) / fileHeight); + return curRow; } /** * Returns the index of column corresponding to the given x position. * - * If the reverse is false, this returns index of the first column in which + * If `isStart` is true, this returns index of the first column in which * left of grid items is greater than or equal to x. Otherwise, this returns * index of the last column in which right of grid items is less than or equal * to x. * @param {number} x - * @param {boolean} reverse + * @param {boolean} isStart * @return {number} * @private */ - getHitColumnIndex_(x, reverse) { + getHitColumnIndex_(x, isStart) { const itemWidth = this.getItemWidth_(); - const shift = reverse ? -this.getItemMarginLeft_() : 0; + const shift = isStart ? 0 : -this.getItemMarginLeft_(); return Math.floor((x + shift) / itemWidth); } @@ -971,10 +1109,10 @@ const top = Math.max(0, y - this.paddingTop_); const bottom = top + (opt_height ? opt_height - 1 : 0); - const firstRow = this.getHitRowIndex_(top, false); - const lastRow = this.getHitRowIndex_(bottom, true); - const firstColumn = this.getHitColumnIndex_(startX, false); - const lastColumn = this.getHitColumnIndex_(endX, true); + const firstRow = this.getHitRowIndex_(top, /* isStart= */ true); + const lastRow = this.getHitRowIndex_(bottom, /* isStart= */ false); + const firstColumn = this.getHitColumnIndex_(startX, /* isStart= */ true); + const lastColumn = this.getHitColumnIndex_(endX, /* isStart= */ false); for (let row = firstRow; row <= lastRow; row++) { for (let col = firstColumn; col <= lastColumn; col++) { @@ -1083,9 +1221,24 @@ const col = grid.getItemColumn(index); const nextIndex = grid.getItemIndex(row + 1, col); if (nextIndex === -1) { - return row + 1 < grid.getFolderRowCount() ? - grid.dataModel.getFolderCount() - 1 : - grid.dataModel.length - 1; + // The row (index `row + 1`) doesn't exist or doesn't have the enough + // columns to get the column (index `col`), and `row + 1` must be the + // last row of the group. We just need to return the last index of that + // group. + const fileListModel = /** @type {FileListModel} */ (grid.dataModel); + const groupBySnapshot = fileListModel.getGroupBySnapshot(); + let curRow = 0; + for (const group of groupBySnapshot) { + const groupItemCount = group.endIndex - group.startIndex + 1; + const groupRowCount = Math.ceil(groupItemCount / grid.columns); + if (row + 1 < curRow + groupRowCount) { + // The row falls into the current group. Return the last index in the + // current group. + return group.endIndex; + } + curRow += groupRowCount; + } + return grid.dataModel.length - 1; } return nextIndex; } @@ -1101,15 +1254,16 @@ const grid = /** @type {!FileGrid} */ (this.grid_); const row = grid.getItemRow(index); + // First row, no items above, just return the first index. if (row - 1 < 0) { return 0; } const col = grid.getItemColumn(index); const nextIndex = grid.getItemIndex(row - 1, col); if (nextIndex === -1) { - return row - 1 < grid.getFolderRowCount() ? - grid.dataModel.getFolderCount() - 1 : - grid.dataModel.length - 1; + // The row (index `row - 1`) doesn't have the enough columns to get the + // column (index `col`), we need to find the last index on "row - 1". + return grid.getFirstItemInRow(row) - 1; } return nextIndex; }
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_grid_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/file_grid_unittest.js new file mode 100644 index 0000000..78fa5ab --- /dev/null +++ b/ui/file_manager/file_manager/foreground/js/ui/file_grid_unittest.js
@@ -0,0 +1,602 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {ListSelectionModel} from 'chrome://resources/js/cr/ui/list_selection_model.m.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {assertEquals} from 'chrome://webui-test/chai_assert.js'; + +import {MockVolumeManager} from '../../../background/js/mock_volume_manager.js'; +import {FakeEntryImpl} from '../../../common/js/files_app_entry_types.js'; +import {installMockChrome} from '../../../common/js/mock_chrome.js'; +import {VolumeManagerCommon} from '../../../common/js/volume_manager_types.js'; +import {importerHistoryInterfaces} from '../../../externs/background/import_history.js'; +import {FileListModel, GROUP_BY_FIELD_DIRECTORY, GROUP_BY_FIELD_MODIFICATION_TIME} from '../file_list_model.js'; +import {MetadataModel} from '../metadata/metadata_model.js'; +import {MockMetadataModel} from '../metadata/mock_metadata.js'; + +import {A11yAnnounce} from './a11y_announce.js'; +import {FileGrid, FileGridSelectionController} from './file_grid.js'; + +/** @type {!MockVolumeManager} */ +let volumeManager; + +/** @type {!MetadataModel} */ +let metadataModel; + +/** @type {!importerHistoryInterfaces.HistoryLoader} */ +let historyLoader; + +/** @type {!HTMLElement} */ +let element; + +/** @type {!A11yAnnounce} */ +let a11y; + +/** + * Returns the element used to parent the file grid. The element is + * attached to the body, and styled for visual display. + * + * @return {!HTMLElement} + */ +function setupBody() { + const style = ` + <style> + grid { + display: block; + height: 200px; + width: 800px; + } + </style> + `; + document.body.innerHTML = style; + + const element = document.createElement('div'); + document.body.appendChild(element); + return /** @type {!HTMLElement} */ (element); +} + +// Set up test components. +export function setUp() { + // Mock LoadTimeData strings. + loadTimeData.getString = id => id; + loadTimeData.resetForTesting({}); + + // Set up mock of chrome.fileManagerPrivate APIs. + const mockChrome = { + fileManagerPrivate: { + RecentDateBucket: { + TODAY: 'today', + YESTERDAY: 'yesterday', + EARLIER_THIS_WEEK: 'earlier_this_week', + EARLIER_THIS_MONTH: 'earlier_this_month', + EARLIER_THIS_YEAR: 'earlier_this_year', + OLDER: 'older', + }, + }, + }; + installMockChrome(mockChrome); + + // Setup mock components. + volumeManager = new MockVolumeManager(); + metadataModel = new MockMetadataModel({}); + historyLoader = /** @type {!importerHistoryInterfaces.HistoryLoader} */ ({ + getHistory: () => { + return Promise.resolve(); + }, + }); + + const a11Messages = []; + a11y = /** @type {!A11yAnnounce} */ ({ + speakA11yMessage: (text) => { + a11Messages.push(text); + }, + }); + + // Create DOM element parent of the file grid under test. + element = setupBody(); +} + +// Force round number heights to simplify the math in the test. +const FILE_ITEM_HEIGHT = 50; +const FOLDER_ITEM_HEIGHT = 20; +const GROUP_HEADING_HEIGHT = 30; +const ITEM_WIDTH = 100; +const ITEM_MARGIN_TOP = 10; +const ITEM_MARGIN_LEFT = 10; + +/** + * @return {!FileGrid} + */ +function setupFileGrid() { + FileGrid.decorate(element, metadataModel, volumeManager, historyLoader, a11y); + + // Add 10 fake files. + const entries = []; + for (let i = 1; i <= 20; i++) { + entries.push( + new FakeEntryImpl(`${i}.txt`, VolumeManagerCommon.RootType.RECENT)); + } + const dataModel = new FileListModel(metadataModel); + dataModel.splice(0, 0, ...entries); + const grid = /** @type {!FileGrid} */ (element); + grid.dataModel = dataModel; + /** @suppress {accessControls} modify protected method in test. */ + // Mock item size. + grid.getFileItemHeight_ = () => FILE_ITEM_HEIGHT; + grid.getFolderItemHeight_ = () => FOLDER_ITEM_HEIGHT; + grid.getItemWidth_ = () => ITEM_WIDTH; + grid.getItemMarginTop_ = () => ITEM_MARGIN_TOP; + grid.getItemMarginLeft_ = () => ITEM_MARGIN_LEFT; + // 3 columns in each row. + grid.columns = 3; + return grid; +} + +/** + * @param {!FileListModel} fileListModel + */ +function groupByModificationTime(fileListModel) { + // Mock group by information. + fileListModel.shouldShowGroupHeading = () => true; + fileListModel.groupByField = GROUP_BY_FIELD_MODIFICATION_TIME; + // Visual illustration of the grid (in total 8 rows with 6 headings): + // ----------------------------------------------------------------- + // Heading #1/today: + // (row 0) Item 0 Item 1 + // Heading #2/yesterday: + // (row 1) Item 2 Item 3 Item 4 + // Heading #3/earlier_this_week: + // (row 2) Item 5 Item 6 Item 7 + // (row 3) Item 8 Item 9 + // Heading #4/earlier_this_month: + // (row 4) Item 10 Item 11 Item 12 + // (row 5) Item 13 Item 14 Item 15 + // Heading #5/earlier_this_year: + // (row 6) Item 16 + // Heading #6/older: + // (row 7) Item 17 Item 18 Item 19 + fileListModel.getGroupBySnapshot = () => { + return [ + {startIndex: 0, endIndex: 1, label: 'today', group: 'today'}, + {startIndex: 2, endIndex: 4, label: 'yesterday', group: 'yesterday'}, + { + startIndex: 5, + endIndex: 9, + label: 'earlier_this_week', + group: 'earlier_this_week' + }, + { + startIndex: 10, + endIndex: 15, + label: 'earlier_this_month', + group: 'earlier_this_month' + }, + { + startIndex: 16, + endIndex: 16, + label: 'earlier_this_year', + group: 'earlier_this_year' + }, + {startIndex: 17, endIndex: 19, label: 'older', group: 'older'}, + ]; + }; +} + +/** + * @param {!FileListModel} fileListModel + */ +function groupByDirectory(fileListModel) { + // Mock group by information. + fileListModel.shouldShowGroupHeading = () => true; + fileListModel.groupByField = GROUP_BY_FIELD_DIRECTORY; + // Visual illustration of the grid (in total 8 rows with 2 headings): + // ----------------------------------------------------------------- + // Heading #1/folders: + // (row 0) Item 0 Item 1 Item 2 + // (row 1) Item 3 + // Heading #2/files: + // (row 2) Item 4 Item 5 Item 6 + // (row 3) Item 7 Item 8 Item 9 + // (row 4) Item 10 Item 11 Item 12 + // (row 5) Item 13 Item 14 Item 15 + // (row 6) Item 16 Item 17 Item 18 + // (row 7) Item 19 + fileListModel.getGroupBySnapshot = () => { + return [ + {startIndex: 0, endIndex: 3, label: 'folders', group: true}, + {startIndex: 4, endIndex: 19, label: 'files', group: false}, + ]; + }; +} + +export function testGetItemTop() { + const grid = setupFileGrid(); + /** @suppress {accessControls} modify protected method in test. */ + grid.getGroupHeadingHeight_ = () => GROUP_HEADING_HEIGHT; + const ROW_HEIGHT = FILE_ITEM_HEIGHT; + // Enable group by modification time. + groupByModificationTime(grid.dataModel); + // Item 0,1 is in group #1/today, nothing is above it. + assertEquals(grid.getItemTop(0), 0); + assertEquals(grid.getItemTop(1), 0); + // Item 2,3,4 is in group #2/yesterday, 1 row above + 1 header. + assertEquals(grid.getItemTop(2), 1 * ROW_HEIGHT + GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(3), 1 * ROW_HEIGHT + GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(4), 1 * ROW_HEIGHT + GROUP_HEADING_HEIGHT); + // Item 5,6,7 is in group #3/earlier_this_week, 2 rows above + 2 headers. + assertEquals(grid.getItemTop(5), 2 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(6), 2 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(7), 2 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + // Item 8,9 is in group #3/earlier_this_week, 3 rows above + 3 headers. + assertEquals(grid.getItemTop(8), 3 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(9), 3 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + // Item 10,11,12 is in group #4/earlier_this_month, 4 rows above + 3 headers. + assertEquals(grid.getItemTop(10), 4 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(11), 4 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(12), 4 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + // Item 13,14,15 is in group #4/earlier_this_month, 5 rows above + 4 headers. + assertEquals(grid.getItemTop(13), 5 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(14), 5 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(15), 5 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + // Item 16 is in group #5/earlier_this_year, 6 rows above + 4 headers. + assertEquals(grid.getFirstItemInRow(6), 16); + assertEquals(grid.getItemTop(16), 6 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + // Item 17,18,19 is in group #6/older, 7 rows above + 5 header. + assertEquals(grid.getFirstItemInRow(7), 17); + assertEquals(grid.getItemTop(17), 7 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(18), 7 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); + assertEquals(grid.getItemTop(19), 7 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); +} + +// Test functions related to item position: getItemRow(), getItemColumn(), +// getItemIndex(), getFirstItemInRow(). +export function testGetItemPosition() { + const grid = setupFileGrid(); + // Enable group by modification time. + groupByModificationTime(grid.dataModel); + // Check the comment in groupByModificationTime() for a visual illustration. + // Item 0,1 is in group #1/today, row 0. + assertEquals(grid.getFirstItemInRow(0), 0); + assertEquals(grid.getItemRow(0), 0); + assertEquals(grid.getItemColumn(0), 0); + assertEquals(grid.getItemIndex(0, 0), 0); + assertEquals(grid.getItemRow(1), 0); + assertEquals(grid.getItemColumn(1), 1); + assertEquals(grid.getItemIndex(0, 1), 1); + // Item 2,3,4 is in group #2/yesterday, row 1. + assertEquals(grid.getFirstItemInRow(1), 2); + assertEquals(grid.getItemRow(2), 1); + assertEquals(grid.getItemColumn(2), 0); + assertEquals(grid.getItemIndex(1, 0), 2); + assertEquals(grid.getItemRow(3), 1); + assertEquals(grid.getItemColumn(3), 1); + assertEquals(grid.getItemIndex(1, 1), 3); + assertEquals(grid.getItemRow(4), 1); + assertEquals(grid.getItemColumn(4), 2); + assertEquals(grid.getItemIndex(1, 2), 4); + // Item 5,6,7 is in group #3/earlier_this_week, row 2. + assertEquals(grid.getFirstItemInRow(2), 5); + assertEquals(grid.getItemRow(5), 2); + assertEquals(grid.getItemColumn(5), 0); + assertEquals(grid.getItemIndex(2, 0), 5); + assertEquals(grid.getItemRow(6), 2); + assertEquals(grid.getItemColumn(6), 1); + assertEquals(grid.getItemIndex(2, 1), 6); + assertEquals(grid.getItemRow(7), 2); + assertEquals(grid.getItemColumn(7), 2); + assertEquals(grid.getItemIndex(2, 2), 7); + // Item 8,9 is in group #3/earlier_this_week, row 3. + assertEquals(grid.getFirstItemInRow(3), 8); + assertEquals(grid.getItemRow(8), 3); + assertEquals(grid.getItemColumn(8), 0); + assertEquals(grid.getItemIndex(3, 0), 8); + assertEquals(grid.getItemRow(9), 3); + assertEquals(grid.getItemColumn(9), 1); + assertEquals(grid.getItemIndex(3, 1), 9); + // Item 10,11,12 is in group #4/earlier_this_month, row 4. + assertEquals(grid.getFirstItemInRow(4), 10); + assertEquals(grid.getItemRow(10), 4); + assertEquals(grid.getItemColumn(10), 0); + assertEquals(grid.getItemIndex(4, 0), 10); + assertEquals(grid.getItemRow(11), 4); + assertEquals(grid.getItemColumn(11), 1); + assertEquals(grid.getItemIndex(4, 1), 11); + assertEquals(grid.getItemRow(12), 4); + assertEquals(grid.getItemColumn(12), 2); + assertEquals(grid.getItemIndex(4, 2), 12); + // Item 13,14,15 is in group #4/earlier_this_month, row 5. + assertEquals(grid.getFirstItemInRow(5), 13); + assertEquals(grid.getItemRow(13), 5); + assertEquals(grid.getItemColumn(13), 0); + assertEquals(grid.getItemIndex(5, 0), 13); + assertEquals(grid.getItemRow(14), 5); + assertEquals(grid.getItemColumn(14), 1); + assertEquals(grid.getItemIndex(5, 1), 14); + assertEquals(grid.getItemRow(15), 5); + assertEquals(grid.getItemColumn(15), 2); + assertEquals(grid.getItemIndex(5, 2), 15); + // Item 16 is in group #5/earlier_this_year, row 6. + assertEquals(grid.getFirstItemInRow(6), 16); + assertEquals(grid.getItemRow(16), 6); + assertEquals(grid.getItemColumn(16), 0); + assertEquals(grid.getItemIndex(6, 0), 16); + // Item 17,18,19 is in group #6/older, row 7. + assertEquals(grid.getFirstItemInRow(7), 17); + assertEquals(grid.getItemRow(17), 7); + assertEquals(grid.getItemColumn(17), 0); + assertEquals(grid.getItemIndex(7, 0), 17); + assertEquals(grid.getItemRow(18), 7); + assertEquals(grid.getItemColumn(18), 1); + assertEquals(grid.getItemIndex(7, 1), 18); + assertEquals(grid.getItemRow(19), 7); + assertEquals(grid.getItemColumn(19), 2); + assertEquals(grid.getItemIndex(7, 2), 19); + + // Invalid inputs: + // row and column is negative. + assertEquals(grid.getItemIndex(-1, -1), -1); + assertEquals(grid.getFirstItemInRow(-1), 0); + // column is too big. + assertEquals(grid.getItemIndex(0, 10), -1); + // row is too big. + assertEquals(grid.getItemIndex(10, 0), -1); + assertEquals(grid.getFirstItemInRow(10), grid.dataModel.length); + // column on a specific row is too big for that row. + assertEquals(grid.getItemIndex(0, 2), -1); + assertEquals(grid.getItemIndex(6, 2), -1); + assertEquals(grid.getItemIndex(6, 3), -1); +} + +export function testGetAfterFillerHeight() { + const grid = setupFileGrid(); + /** @suppress {accessControls} modify protected method in test. */ + grid.getGroupHeadingHeight_ = () => GROUP_HEADING_HEIGHT; + const ROW_HEIGHT = FILE_ITEM_HEIGHT; + // Enable group by modification time. + groupByModificationTime(grid.dataModel); + // Check the comment in groupByModificationTime() for a visual illustration. + // Note: the index itself is being excluded. + // Item 0,1 is in group #1/today, 8 rows below + 5 headers. + assertEquals( + grid.getAfterFillerHeight(0), 8 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(1), 8 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(2), 8 * ROW_HEIGHT + 5 * GROUP_HEADING_HEIGHT); + // Item 2,3,4 is in group #2/yesterday, 7 rows below + 4 header. + assertEquals( + grid.getAfterFillerHeight(3), 7 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(4), 7 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(5), 7 * ROW_HEIGHT + 4 * GROUP_HEADING_HEIGHT); + // Item 5,6,7 is in group #3/earlier_this_week, 6 rows below + 3 headers. + assertEquals( + grid.getAfterFillerHeight(6), 6 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(7), 6 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(8), 6 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + // Item 8,9 is in group #3/earlier_this_week, 5 rows below + 3 headers. + assertEquals( + grid.getAfterFillerHeight(9), 5 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(10), 5 * ROW_HEIGHT + 3 * GROUP_HEADING_HEIGHT); + // Item 10,11,12 is in group #4/earlier_this_month, 4 rows below + 2 headers. + assertEquals( + grid.getAfterFillerHeight(11), 4 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(12), 4 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(13), 4 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + // Item 13,14,15 is in group #4/earlier_this_month, 3 rows below + 2 headers. + assertEquals( + grid.getAfterFillerHeight(14), 3 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(15), 3 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + assertEquals( + grid.getAfterFillerHeight(16), 3 * ROW_HEIGHT + 2 * GROUP_HEADING_HEIGHT); + // Item 16 is in group #5/earlier_this_year, 2 rows below + 1 header. + assertEquals( + grid.getAfterFillerHeight(17), 2 * ROW_HEIGHT + 1 * GROUP_HEADING_HEIGHT); + // Item 17,18,19 is in group #6/older, 1 row below. + assertEquals(grid.getAfterFillerHeight(18), 1 * ROW_HEIGHT); + assertEquals(grid.getAfterFillerHeight(19), 1 * ROW_HEIGHT); + assertEquals(grid.getAfterFillerHeight(20), 1 * ROW_HEIGHT); +} + +/** + * @suppress {accessControls} test the private method here. + */ +export function testGetRowForListOffset() { + const grid = setupFileGrid(); + /** @suppress {accessControls} modify protected method in test. */ + grid.getGroupHeadingHeight_ = () => GROUP_HEADING_HEIGHT; + grid.paddingTop_ = 0; // To ease calculation. + // Enable group by modification time. + groupByModificationTime(grid.dataModel); + // index height total height + // -------------------------------------------------------------------- + // Heading #1/today: 30 30 + // (row 0) Item 0 Item 1 50 80 + // Heading #2/yesterday: 30 110 + // (row 1) Item 2 Item 3 Item 4 50 160 + // Heading #3/earlier_this_week: 30 190 + // (row 2) Item 5 Item 6 Item 7 50 240 + // (row 3) Item 8 Item 9 50 290 + // Heading #4/earlier_this_month: 30 320 + // (row 4) Item 10 Item 11 Item 12 50 370 + // (row 5) Item 13 Item 14 Item 15 50 420 + // Heading #5/earlier_this_year: 30 450 + // (row 6) Item 16 50 500 + // Heading #6/older: 30 530 + // (row 7) Item 17 Item 18 Item 19 50 580 + assertEquals(grid.getRowForListOffset_(0), 0); + assertEquals(grid.getRowForListOffset_(30), 0); + assertEquals(grid.getRowForListOffset_(100), 1); + assertEquals(grid.getRowForListOffset_(200), 2); + assertEquals(grid.getRowForListOffset_(240), 3); + assertEquals(grid.getRowForListOffset_(300), 4); + assertEquals(grid.getRowForListOffset_(400), 5); + assertEquals(grid.getRowForListOffset_(450), 6); + assertEquals(grid.getRowForListOffset_(500), 7); + assertEquals(grid.getRowForListOffset_(600), 7); +} + +/** + * @suppress {accessControls} test the private method here. + */ +export function testItemHeightForGroupByModificationTime() { + const grid = setupFileGrid(); + // Enable group by modification time. + groupByModificationTime(grid.dataModel); + + // We are testing the logic in getGroupHeadingHeight_(), so we should use + // the real MODIFICATION_TIME_GROUP_HEADING_HEIGHT(57) from file_grid. + assertEquals(grid.getGroupHeadingHeight_(), 57); + for (let i = 0; i < 20; i++) { + assertEquals(grid.getItemHeightByIndex_(i), FILE_ITEM_HEIGHT); + } +} + +/** + * @suppress {accessControls} test the private method here. + */ +export function testItemHeightForGroupByDirectory() { + const grid = setupFileGrid(); + // Enable group by directory. + groupByDirectory(grid.dataModel); + + // We are testing the logic in getGroupHeadingHeight_(), so we should use + // the real DIRECTORY_GROUP_HEADING_HEIGHT(40) from file_grid. + assertEquals(grid.getGroupHeadingHeight_(), 40); + for (let i = 0; i < 20; i++) { + // index 3 is the last item for folders + assertEquals( + grid.getItemHeightByIndex_(i), + i <= 3 ? FOLDER_ITEM_HEIGHT : FILE_ITEM_HEIGHT); + } +} + +/** + * @suppress {accessControls} test the private method here. + */ +export function testGetHitRowIndex() { + const grid = setupFileGrid(); + // Enable group by directory. + groupByDirectory(grid.dataModel); + /** @suppress {accessControls} modify protected method in test. */ + grid.getGroupHeadingHeight_ = () => GROUP_HEADING_HEIGHT; + + // index height total height + // -------------------------------------------------------------------- + // Heading #1/folders: 30 30 + // (row 0) Item 0 Item 1 Item 2 20 50 + // (row 1) Item 3 20 70 + // Heading #2/files: 30 100 + // (row 2) Item 4 Item 5 Item 6 50 150 + // (row 3) Item 7 Item 8 Item 9 50 200 + // (row 4) Item 10 Item 11 Item 12 50 250 + // (row 5) Item 13 Item 14 Item 15 50 300 + // (row 6) Item 16 Item 17 Item 18 50 350 + // (row 7) Item 19 50 400 + assertEquals(grid.getHitRowIndex_(0, true), 0); + assertEquals(grid.getHitRowIndex_(0, false), -1); + assertEquals(grid.getHitRowIndex_(30, true), 0); + assertEquals(grid.getHitRowIndex_(30, false), -1); + assertEquals(grid.getHitRowIndex_(70, true), 2); + assertEquals(grid.getHitRowIndex_(70, false), 1); + assertEquals(grid.getHitRowIndex_(70 + ITEM_MARGIN_TOP, true), 2); + assertEquals(grid.getHitRowIndex_(70 + ITEM_MARGIN_TOP, false), 1); + assertEquals(grid.getHitRowIndex_(100, true), 2); + assertEquals(grid.getHitRowIndex_(100, false), 1); + assertEquals(grid.getHitRowIndex_(180, true), 3); + assertEquals(grid.getHitRowIndex_(180, false), 3); + assertEquals(grid.getHitRowIndex_(250 + ITEM_MARGIN_TOP - 1, true), 5); + assertEquals(grid.getHitRowIndex_(250 + ITEM_MARGIN_TOP - 1, false), 4); + // For larger y, the out of bound row index will be returned (e.g. max + // index = 7), which is expected. + assertEquals(grid.getHitRowIndex_(450, true), 8); + assertEquals(grid.getHitRowIndex_(450, false), 8); +} + +/** + * @suppress {accessControls} test the private method here. + */ +export function testGetHitColumnIndex() { + const grid = setupFileGrid(); + // Enable group by directory. + groupByDirectory(grid.dataModel); + /** @suppress {accessControls} modify protected method in test. */ + grid.getGroupHeadingHeight_ = () => GROUP_HEADING_HEIGHT; + + // (col 0) (col 1) (col 2) + // ----------------------------------------- + // | 100 | | 100 | | 100 | + // ----------------------------------------- + // Heading #1/folders: + // (row 0) Item 0 Item 1 Item 2 + // (row 1) Item 3 + // Heading #2/files: + // (row 2) Item 4 Item 5 Item 6 + // (row 3) Item 7 Item 8 Item 9 + // (row 4) Item 10 Item 11 Item 12 + // (row 5) Item 13 Item 14 Item 15 + // (row 6) Item 16 Item 17 Item 18 + // (row 7) Item 19 + assertEquals(grid.getHitColumnIndex_(0, true), 0); + assertEquals(grid.getHitColumnIndex_(0, false), -1); + assertEquals(grid.getHitColumnIndex_(60, true), 0); + assertEquals(grid.getHitColumnIndex_(60, false), 0); + assertEquals(grid.getHitColumnIndex_(100 + ITEM_MARGIN_LEFT - 1, true), 1); + assertEquals(grid.getHitColumnIndex_(100 + ITEM_MARGIN_LEFT - 1, false), 0); + // For larger x, the out of bound column index will be returned (e.g. max + // index = 2), which is expected. + assertEquals(grid.getHitColumnIndex_(400, true), 4); + assertEquals(grid.getHitColumnIndex_(400, false), 3); +} + +// Test FileGridSelectionController's getIndexAbove() and getIndexBelow(). +export function testSelectionModelIndexMovement() { + const grid = setupFileGrid(); + groupByDirectory(grid.dataModel); + const sm = new FileGridSelectionController( + new ListSelectionModel(grid.dataModel.length), grid); + // Heading #1/folders: + // (row 0) Item 0 Item 1 Item 2 + // (row 1) Item 3 + // Heading #2/files: + // (row 2) Item 4 Item 5 Item 6 + // (row 3) Item 7 Item 8 Item 9 + // (row 4) Item 10 Item 11 Item 12 + // (row 5) Item 13 Item 14 Item 15 + // (row 6) Item 16 Item 17 Item 18 + // (row 7) Item 19 + + // getIndexAbove() + assertEquals(sm.getIndexAbove(0), -1); + assertEquals(sm.getIndexAbove(1), 0); + assertEquals(sm.getIndexAbove(2), 0); + assertEquals(sm.getIndexAbove(3), 0); + assertEquals(sm.getIndexAbove(4), 3); + // The col above item 5/6 doesn't have items, so fall back to 3. + assertEquals(sm.getIndexAbove(5), 3); + assertEquals(sm.getIndexAbove(6), 3); + assertEquals(sm.getIndexAbove(11), 8); + assertEquals(sm.getIndexAbove(15), 12); + assertEquals(sm.getIndexAbove(19), 16); + // getIndexBelow() + assertEquals(sm.getIndexBelow(0), 3); + // The col below item 1/2 doesn't have items, so fall back to 3. + assertEquals(sm.getIndexBelow(1), 3); + assertEquals(sm.getIndexBelow(2), 3); + assertEquals(sm.getIndexBelow(3), 4); + assertEquals(sm.getIndexBelow(4), 7); + assertEquals(sm.getIndexBelow(8), 11); + assertEquals(sm.getIndexBelow(12), 15); + // The col below item 17/18 doesn't have items, so fall back to 19. + assertEquals(sm.getIndexBelow(17), 19); + assertEquals(sm.getIndexBelow(18), 19); + assertEquals(sm.getIndexBelow(19), -1); +}
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table.js b/ui/file_manager/file_manager/foreground/js/ui/file_table.js index c17321d..3f86b0c 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_table.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_table.js
@@ -576,10 +576,7 @@ return; } const fieldName = cm.getId(index); - const fileListModel = /** @type {FileListModel} */ (this.dataModel); - const sortStatus = fileListModel.sortStatus; - const isGroupHeadingShownBeforeSort = - fileListModel.shouldShowGroupHeading(); + const sortStatus = this.dataModel.sortStatus; let sortDirection = cm.getDefaultOrder(index); if (sortStatus.field === fieldName) { @@ -595,13 +592,19 @@ // Delegate to parent to sort. super.sort(index); this.a11y.speakA11yMessage(msg); + } + /** + * @override + */ + onDataModelSorted() { + const fileListModel = /** @type {FileListModel} */ (this.dataModel); + const hasGroupHeadingAfterSort = fileListModel.shouldShowGroupHeading(); // Sort doesn't trigger redraw sometimes, e.g. if we sort by Name for now, // then we sort by time, if the list order doesn't change, no permuted event // is triggered, thus no redraw is triggered. In this scenario, we need to // manually trigger a redraw to remove/add the group heading. - const isGroupHeadingShownAfterSort = fileListModel.shouldShowGroupHeading(); - if (isGroupHeadingShownBeforeSort !== isGroupHeadingShownAfterSort) { + if (hasGroupHeadingAfterSort !== fileListModel.hasGroupHeadingBeforeSort) { this.list.redraw(); } }
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js b/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js index 4f50e62..4a6d9749 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js
@@ -27,7 +27,7 @@ const filelist = {}; // Group Heading height, align with CSS #list-container li[group-heading]. -const GROUP_HEADING_HEIGHT = 56; +const GROUP_HEADING_HEIGHT = 57; /** * File table list.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table_list_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/file_table_list_unittest.js index ddabeea..70ecd8e8 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_table_list_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_table_list_unittest.js
@@ -9,7 +9,6 @@ import {FakeEntryImpl} from '../../../common/js/files_app_entry_types.js'; import {VolumeManagerCommon} from '../../../common/js/volume_manager_types.js'; import {importerHistoryInterfaces} from '../../../externs/background/import_history.js'; -import {DirectoryModel} from '../directory_model.js'; import {FileListModel} from '../file_list_model.js'; import {MetadataModel} from '../metadata/metadata_model.js'; import {MockMetadataModel} from '../metadata/mock_metadata.js'; @@ -22,9 +21,6 @@ /** @type {!MockVolumeManager} */ let volumeManager; -/** @type {!DirectoryModel} */ -let directoryModel; - /** @type {!MetadataModel} */ let metadataModel; @@ -367,12 +363,27 @@ fileListModel.shouldShowGroupHeading = () => true; fileListModel.getGroupBySnapshot = () => { return [ - {startIndex: 0, endIndex: 1, label: 'today'}, - {startIndex: 2, endIndex: 2, label: 'yesterday'}, - {startIndex: 3, endIndex: 4, label: 'earlier_this_week'}, - {startIndex: 5, endIndex: 6, label: 'earlier_this_month'}, - {startIndex: 7, endIndex: 8, label: 'earlier_this_year'}, - {startIndex: 9, endIndex: 9, label: 'older'}, + {startIndex: 0, endIndex: 1, label: 'today', group: 'today'}, + {startIndex: 2, endIndex: 2, label: 'yesterday', group: 'yesterday'}, + { + startIndex: 3, + endIndex: 4, + label: 'earlier_this_week', + group: 'earlier_this_week' + }, + { + startIndex: 5, + endIndex: 6, + label: 'earlier_this_month', + group: 'earlier_this_month' + }, + { + startIndex: 7, + endIndex: 8, + label: 'earlier_this_year', + group: 'earlier_this_year' + }, + {startIndex: 9, endIndex: 9, label: 'older', group: 'older'}, ]; }; }
diff --git a/ui/file_manager/file_manager/foreground/js/ui/gear_menu.js b/ui/file_manager/file_manager/foreground/js/ui/gear_menu.js index b1c6d5b..5b50a9d 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/gear_menu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/gear_menu.js
@@ -107,27 +107,31 @@ this.volumeSpaceInnerBar_.style.width = '100%'; } - spaceInfoPromise.then(spaceInfo => { - if (this.spaceInfoPromise_ != spaceInfoPromise) { - return; - } - this.volumeSpaceInnerBar_.removeAttribute('pending'); - this.volumeSpaceOuterBar_.hidden = true; - if (spaceInfo) { - const sizeStr = util.bytesToString(spaceInfo.remainingSize); - this.volumeSpaceInfoLabel_.textContent = - strf('SPACE_AVAILABLE', sizeStr); + spaceInfoPromise.then( + spaceInfo => { + if (this.spaceInfoPromise_ != spaceInfoPromise) { + return; + } + this.volumeSpaceInnerBar_.removeAttribute('pending'); + this.volumeSpaceOuterBar_.hidden = true; + if (spaceInfo) { + const sizeStr = util.bytesToString(spaceInfo.remainingSize); + this.volumeSpaceInfoLabel_.textContent = + strf('SPACE_AVAILABLE', sizeStr); - if (spaceInfo.totalSize > 0) { - const usedSpace = spaceInfo.totalSize - spaceInfo.remainingSize; - this.volumeSpaceInnerBar_.style.width = - (100 * usedSpace / spaceInfo.totalSize) + '%'; + if (spaceInfo.totalSize > 0) { + const usedSpace = spaceInfo.totalSize - spaceInfo.remainingSize; + this.volumeSpaceInnerBar_.style.width = + (100 * usedSpace / spaceInfo.totalSize) + '%'; - this.volumeSpaceOuterBar_.hidden = false; - } - } else { - this.volumeSpaceInfoLabel_.textContent = str('FAILED_SPACE_INFO'); - } - }); + this.volumeSpaceOuterBar_.hidden = false; + } + } else { + this.volumeSpaceInfoLabel_.textContent = str('FAILED_SPACE_INFO'); + } + }, + error => { + console.warn('Failed get space info', error); + }); } }
diff --git a/ui/file_manager/file_manager/foreground/js/ui/list_container.js b/ui/file_manager/file_manager/foreground/js/ui/list_container.js index 2b338f7..f7486f6 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/list_container.js +++ b/ui/file_manager/file_manager/foreground/js/ui/list_container.js
@@ -12,7 +12,7 @@ import {DialogType} from '../../../common/js/dialog_type.js'; import {util} from '../../../common/js/util.js'; -import {FileListModel} from '../file_list_model.js'; +import {FileListModel, GROUP_BY_FIELD_DIRECTORY, GROUP_BY_FIELD_MODIFICATION_TIME} from '../file_list_model.js'; import {ListThumbnailLoader} from '../list_thumbnail_loader.js'; import {FileGrid} from './file_grid.js'; @@ -125,6 +125,13 @@ */ this.allowContextMenuByTouch_ = false; + /** + * List container needs to know if the current active directory is Recent + * or not so it can update groupBy filed accordingly. + * @public {boolean} + */ + this.isOnRecent = false; + // Overriding the default role 'list' to 'listbox' for better accessibility // on ChromeOS. this.table.list.setAttribute('role', 'listbox'); @@ -234,6 +241,8 @@ // view that is not in use. switch (listType) { case ListContainer.ListType.DETAIL: + this.dataModel.groupByField = + this.isOnRecent ? GROUP_BY_FIELD_MODIFICATION_TIME : null; this.table.dataModel = this.dataModel; this.table.setListThumbnailLoader(this.listThumbnailLoader); this.table.selectionModel = this.selectionModel; @@ -245,6 +254,13 @@ break; case ListContainer.ListType.THUMBNAIL: + if (this.isOnRecent) { + this.dataModel.groupByField = util.isRecentsFilterV2Enabled() ? + GROUP_BY_FIELD_MODIFICATION_TIME : + null; + } else { + this.dataModel.groupByField = GROUP_BY_FIELD_DIRECTORY; + } this.grid.dataModel = this.dataModel; this.grid.setListThumbnailLoader(this.listThumbnailLoader); this.grid.selectionModel = this.selectionModel;
diff --git a/ui/file_manager/file_manager/foreground/js/ui/table/table.js b/ui/file_manager/file_manager/foreground/js/ui/table/table.js index d788b28..a9b1a91 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/table/table.js +++ b/ui/file_manager/file_manager/foreground/js/ui/table/table.js
@@ -295,9 +295,16 @@ */ handleSorted_(e) { this.header_.redraw(); + this.onDataModelSorted(); } /** + * Override to inject custom logic after data model sorting is done. + * @protected + */ + onDataModelSorted() {} + + /** * This handles data model 'change' and 'splice' events. * Since they may change the visibility of scrollbar, table may need to * re-calculation the width of column headers.
diff --git a/ui/file_manager/file_names.gni b/ui/file_manager/file_names.gni index af5f097..92d2d2c 100644 --- a/ui/file_manager/file_names.gni +++ b/ui/file_manager/file_names.gni
@@ -394,6 +394,7 @@ "file_manager/foreground/js/ui/file_tap_handler_unittest.js", "file_manager/foreground/js/ui/install_linux_package_dialog_unittest.js", "file_manager/foreground/js/ui/file_table_list_unittest.js", + "file_manager/foreground/js/ui/file_grid_unittest.js", "file_manager/foreground/js/ui/multi_menu_unittest.js", "file_manager/foreground/js/ui/splitter_unittest.js", "file_manager/foreground/js/ui/banners/state_banner_unittest.js",
diff --git a/ui/gfx/swap_result.h b/ui/gfx/swap_result.h index 39a62d5..03e5011 100644 --- a/ui/gfx/swap_result.h +++ b/ui/gfx/swap_result.h
@@ -41,15 +41,13 @@ // dicontinuities in associated UMA data. base::TimeTicks swap_end; - // When Display Compositor thread scheduled work to GPU Thread. For GLRenderer - // it's when InProcessCommandBuffer::Flush() happens, for SkiaRenderer it's - // PostTask time for FinishPaintRenderPass or SwapBuffers whichever comes - // first. + // When Display Compositor thread scheduled work to GPU Thread. For + // SkiaRenderer it's PostTask time for FinishPaintRenderPass or SwapBuffers + // whichever comes first. base::TimeTicks viz_scheduled_draw; // When GPU thread started draw submitted by Display Compositor thread. For - // GLRenderer it's InProcessCommandBuffer::FlushOnGpuThread, for SkiaRenderer - // it's FinishPaintRenderPass/SwapBuffers. + // SkiaRenderer it's FinishPaintRenderPass/SwapBuffers. base::TimeTicks gpu_started_draw; // When GPU scheduler removed the last required dependency.
diff --git a/ui/views/accessible_pane_view_unittest.cc b/ui/views/accessible_pane_view_unittest.cc index 5109474..f9ba7f1 100644 --- a/ui/views/accessible_pane_view_unittest.cc +++ b/ui/views/accessible_pane_view_unittest.cc
@@ -42,7 +42,8 @@ void Init(); raw_ptr<LabelButton> child_button_; - raw_ptr<LabelButton> second_child_button_; + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<LabelButton, DegradeToNoOpWhenMTE> second_child_button_; raw_ptr<LabelButton> third_child_button_; std::unique_ptr<LabelButton> not_child_button_; };
diff --git a/ui/views/animation/animation_delegate_views.h b/ui/views/animation/animation_delegate_views.h index 2c6cfbd6..da01fe1 100644 --- a/ui/views/animation/animation_delegate_views.h +++ b/ui/views/animation/animation_delegate_views.h
@@ -59,7 +59,8 @@ void ClearAnimationRunner(); raw_ptr<View> view_; - raw_ptr<gfx::AnimationContainer> container_ = nullptr; + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<gfx::AnimationContainer, DegradeToNoOpWhenMTE> container_ = nullptr; // The animation runner that |container_| uses. raw_ptr<CompositorAnimationRunner> compositor_animation_runner_ = nullptr;
diff --git a/ui/views/animation/bounds_animator_unittest.cc b/ui/views/animation/bounds_animator_unittest.cc index f876166..db4a235a 100644 --- a/ui/views/animation/bounds_animator_unittest.cc +++ b/ui/views/animation/bounds_animator_unittest.cc
@@ -200,7 +200,8 @@ private: TestView parent_; - raw_ptr<TestView> child_; // Owned by |parent_|. + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<TestView, DegradeToNoOpWhenMTE> child_; // Owned by |parent_|. std::unique_ptr<BoundsAnimator> animator_; };
diff --git a/ui/views/controls/scroll_view_unittest.cc b/ui/views/controls/scroll_view_unittest.cc index 47334b0..3f3131c 100644 --- a/ui/views/controls/scroll_view_unittest.cc +++ b/ui/views/controls/scroll_view_unittest.cc
@@ -113,7 +113,8 @@ private: base::ScopedObservation<View, ViewObserver> observer_{this}; - raw_ptr<View> deleted_view_ = nullptr; + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<View, DegradeToNoOpWhenMTE> deleted_view_ = nullptr; }; } // namespace test
diff --git a/ui/views/controls/table/table_view_unittest.cc b/ui/views/controls/table/table_view_unittest.cc index 348de27..d8b5317 100644 --- a/ui/views/controls/table/table_view_unittest.cc +++ b/ui/views/controls/table/table_view_unittest.cc
@@ -608,7 +608,9 @@ std::unique_ptr<TestTableModel2> model_; // Owned by |parent_|. - raw_ptr<TableView> table_ = nullptr; + // + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<TableView, DegradeToNoOpWhenMTE> table_ = nullptr; std::unique_ptr<TableViewTestHelper> helper_;
diff --git a/ui/views/interaction/element_tracker_views_unittest.cc b/ui/views/interaction/element_tracker_views_unittest.cc index 00ffc1c..250f80a9 100644 --- a/ui/views/interaction/element_tracker_views_unittest.cc +++ b/ui/views/interaction/element_tracker_views_unittest.cc
@@ -106,7 +106,8 @@ const ElementEventType event_type_; ui::ElementTracker::Subscription subscription_; int event_count_ = 0; - raw_ptr<View> last_view_ = nullptr; + // TODO(crbug.com/1298696): Breaks views_unittests. + raw_ptr<View, DegradeToNoOpWhenMTE> last_view_ = nullptr; }; ElementTrackerViews::ViewList ElementsToViews(