diff --git a/AUTHORS b/AUTHORS index 31bdaf3..fdca76b 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -281,6 +281,7 @@ Dhi Aurrahman <dio@rockybars.com> Di Wu <meetwudi@gmail.com> Diana Suvorova <diana.suvorova@gmail.com> +Diego Fernández Santos <agujaydedal@gmail.com> Diego Ferreiro Val <elfogris@gmail.com> Dillon Sellars <dill.sellars@gmail.com> Divya Bansal <divya.bansal@samsung.com>
diff --git a/DEPS b/DEPS index b0f5faca..fdc7e0e 100644 --- a/DEPS +++ b/DEPS
@@ -228,11 +228,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'd71fac66edf1dd38a7c0e35d7710b2f82e6e36da', + 'skia_revision': '47f76853c6266d02bfc914fe4e8160b60a1f903a', # 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': '15d13e153994fc94e57e771bb93137ef1ce7f2ec', + 'v8_revision': '52090340d5cba199f8bdf35054b9c4ab36748f78', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -275,7 +275,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. - 'freetype_revision': '6d19b29fbcd48bdfeb3ae10d26460137f65ebac8', + 'freetype_revision': 'a29e020059ca6f73a212ec76af94b22a694ad765', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. @@ -303,7 +303,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': 'fae6bd0cb73c7f4368971fd164e12ed4a26b38e4', + 'devtools_frontend_revision': '3a286afd3b34af74c622cc762ae46008d5a887f9', # 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. @@ -343,7 +343,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': 'ba662950338abc0ad985b43fa4aa91486ee04786', + 'dawn_revision': '30eeac75784aac8c3a2df867ee21d8188f5f3fad', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -485,7 +485,7 @@ } ], 'dep_type': 'cipd', - 'condition': '(host_os == "linux" or host_os == "win") and checkout_reclient', + 'condition': 'checkout_reclient', }, 'src/third_party/android_rust_toolchain/toolchain': { 'packages': [ @@ -773,7 +773,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'wKA9jIpyBbuq6zmaiAE4Zck1k0PzGf4wsEKeYsmq3EoC', + 'version': 'L-v7Lp_nVRhjXf1b1XWKe2CPp3Vd5WuJqb5nShZ7ZOoC', }, ], 'condition': 'checkout_android', @@ -1476,7 +1476,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/aemu/linux-amd64', - 'version': '35rwW0ni0eziJ2doq4bSBym86edze8jHjf2fyZhjl8kC' + 'version': 'DJruGwXsn7A79ZGy_9mpp5-OHYZqoyeiKRuVvgu_TiQC' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1616,7 +1616,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '9ec0bd5501c6a35eb365dc49be7618a763135a10', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'be9a3d7c775567348bb4ae9cb453a5320e77df68', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'b0291fd966b55a5efc496772555b94842bde1085', 'src/third_party/webrtc': Var('webrtc_git') + '/src.git' + '@' + 'b3c9d3da8f3466a1969c2bbee308cb57105720f6', @@ -1677,7 +1677,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@a4113d198829c2dcfed55f20cb811572f5354b3e', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d1fe1bc5bf7cb458c42a09f3de19a7a5709679eb', 'condition': 'checkout_src_internal', }, @@ -1718,7 +1718,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/projector_app/app', - 'version': 'Z1npKtY5oXpkyG0Vp5rRL6i1MQ9ulV7kLiTjquyL7eIC', + 'version': 'OvuD_rtiyl-Jgd08zyM4PvrhLaBiaoquqq1Zkmv9zVkC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/WATCHLISTS b/WATCHLISTS index c75ca776..56ea209 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1288,7 +1288,7 @@ '|components/media_router/' }, 'media_webrtc': { - 'filepath': 'media/webrtc/' + 'filepath': '^media/webrtc/' }, 'message_loop': { 'filepath': 'base/message_' @@ -1324,7 +1324,7 @@ '|chrome/browser/ash/cryptauth/'\ '|chrome/browser/ash/device_sync/'\ '|chrome/browser/ash/multidevice_setup/'\ - '|chrome/browser/chromeos/secure_channel/'\ + '|chrome/browser/ash/secure_channel/'\ '|chrome/browser/resources/chromeos/multidevice_setup/'\ '|chrome/browser/resources/settings/multidevice_page/'\ '|chrome/browser/resources/settings/chromeos/multidevice_page/'\ @@ -1543,7 +1543,7 @@ '|permission_context', }, 'phonehub': { - 'filepath': 'chrome/browser/chromeos/phonehub/'\ + 'filepath': 'chrome/browser/ash/phonehub/'\ '|chromeos/components/phonehub/'\ '|ash/system/phonehub/', },
diff --git a/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java b/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java index ad58490..baec92e 100644 --- a/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java +++ b/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java
@@ -46,6 +46,10 @@ private static final String TAG = "WebViewApkApp"; // Called by the framework for ALL processes. Runs before ContentProviders are created. + // + // Logic here is specific for standalone WebView and trichrome but does not run by + // Monochrome. Common logic between all WebView flavours should be go into + // maybeInitProcessGlobals instead which is called by Monochrome too. // Quirk: context.getApplicationContext() returns null during this method. @Override protected void attachBaseContext(Context context) { @@ -63,12 +67,6 @@ // MonochromeApplication has its own locale configuration already, so call this here // rather than in maybeInitProcessGlobals. ResourceBundle.setAvailablePakLocales(AwLocaleConfig.getWebViewSupportedPakLocales()); - - // Only register nonembedded SafeMode actions for webview_apk or webview_service processes. - if (isWebViewProcess()) { - SafeModeController controller = SafeModeController.getInstance(); - controller.registerActions(NonembeddedSafeModeActionsList.sList); - } } @Override @@ -94,6 +92,11 @@ UmaRecorderHolder.setUpNativeUmaRecorder(false); UmaRecorderHolder.setNonNativeDelegate(new AwNonembeddedUmaRecorder()); + + // Only register nonembedded SafeMode actions for webview_apk or webview_service + // processes. + SafeModeController controller = SafeModeController.getInstance(); + controller.registerActions(NonembeddedSafeModeActionsList.sList); } // Limit to N+ since external services were added in N.
diff --git a/ash/system/phonehub/phone_hub_recent_apps_view.cc b/ash/system/phonehub/phone_hub_recent_apps_view.cc index 2b0d600e..bae63db 100644 --- a/ash/system/phonehub/phone_hub_recent_apps_view.cc +++ b/ash/system/phonehub/phone_hub_recent_apps_view.cc
@@ -156,11 +156,11 @@ } for (const auto& recent_app : recent_apps_list) { - auto pressed_callback = - base::BindRepeating(&chromeos::phonehub::RecentAppsInteractionHandler:: - NotifyRecentAppClicked, - base::Unretained(recent_apps_interaction_handler_), - recent_app.package_name); + auto pressed_callback = base::BindRepeating( + &chromeos::phonehub::RecentAppsInteractionHandler:: + NotifyRecentAppClicked, + base::Unretained(recent_apps_interaction_handler_), + recent_app.package_name, recent_app.visible_app_name); recent_app_button_list_.push_back(std::make_unique<PhoneHubRecentAppButton>( recent_app.icon, pressed_callback)); recent_app_buttons_view_->AddRecentAppButton(
diff --git a/ash/webui/diagnostics_ui/diagnostics_ui.cc b/ash/webui/diagnostics_ui/diagnostics_ui.cc index 003a9ea3..5e74cd6 100644 --- a/ash/webui/diagnostics_ui/diagnostics_ui.cc +++ b/ash/webui/diagnostics_ui/diagnostics_ui.cc
@@ -176,6 +176,8 @@ {"memoryBannerMessage", IDS_DIAGNOSTICS_MEMORY_BANNER_MESSAGE}, {"memoryRoutineText", IDS_DIAGNOSTICS_MEMORY_ROUTINE_TEXT}, {"memoryTitle", IDS_DIAGNOSTICS_MEMORY_TITLE}, + {"missingNameServersText", + IDS_NETWORK_DIAGNOSTICS_MISSING_NAME_SERVERS_TEXT}, {"nameResolutionGroupLabel", IDS_DIAGNOSTICS_NAME_RESOLUTION_GROUP_LABEL}, {"networkAuthenticationLabel", IDS_NETWORK_DIAGNOSTICS_AUTHENTICATION}, {"networkBssidLabel", IDS_ONC_WIFI_BSSID},
diff --git a/ash/webui/diagnostics_ui/resources/diagnostics_utils.js b/ash/webui/diagnostics_ui/resources/diagnostics_utils.js index ba3fb3c0..78b35fe 100644 --- a/ash/webui/diagnostics_ui/resources/diagnostics_utils.js +++ b/ash/webui/diagnostics_ui/resources/diagnostics_utils.js
@@ -5,7 +5,7 @@ import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {LockType, NetworkState, NetworkType, RoutineProperties, RoutineResult, RoutineType, StandardRoutineResult} from './diagnostics_types.js'; +import {LockType, Network, NetworkState, NetworkType, RoutineProperties, RoutineResult, RoutineType, StandardRoutineResult} from './diagnostics_types.js'; import {RoutineGroup} from './routine_group.js'; /** @@ -281,3 +281,12 @@ return false; } } + +/** + * @param {!Network} network + * @return {boolean} + */ +export function isNetworkMissingNameServers(network) { + return !network.ipConfig || !network.ipConfig.nameServers || + network.ipConfig.nameServers.length === 0; +}
diff --git a/ash/webui/diagnostics_ui/resources/network_card.js b/ash/webui/diagnostics_ui/resources/network_card.js index 7a64bf1..cda6b4f 100644 --- a/ash/webui/diagnostics_ui/resources/network_card.js +++ b/ash/webui/diagnostics_ui/resources/network_card.js
@@ -13,7 +13,7 @@ import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Network, NetworkHealthProviderInterface, NetworkState, NetworkStateObserverInterface, NetworkStateObserverReceiver, NetworkType, TroubleshootingInfo} from './diagnostics_types.js'; -import {formatMacAddress, getNetworkState, getNetworkType, isConnectedOrOnline} from './diagnostics_utils.js'; +import {formatMacAddress, getNetworkState, getNetworkType, isConnectedOrOnline, isNetworkMissingNameServers} from './diagnostics_utils.js'; import {getNetworkHealthProvider} from './mojo_interface_provider.js'; const BASE_SUPPORT_URL = 'https://support.google.com/chromebook?p=diagnostics_'; @@ -27,6 +27,7 @@ kDisabled: 0, kNotConnected: 1, kMissingIpAddress: 2, + kMissingNameServers: 3, }; /** @@ -79,7 +80,7 @@ showNetworkDataPoints_: { type: Boolean, computed: 'computeShouldShowNetworkDataPoints_(network.state,' + - ' unableToObtainIpAddress_)', + ' unableToObtainIpAddress_, isMissingNameServers_)', }, /** @protected {boolean} */ @@ -104,7 +105,7 @@ troubleshootingInfo_: { type: Object, computed: 'computeTroubleshootingInfo_(network.*,' + - ' unableToObtainIpAddress_)', + ' unableToObtainIpAddress_, isMissingNameServers_)', }, /** @private */ @@ -112,6 +113,12 @@ type: Number, value: -1, }, + + /** @protected {boolean} */ + isMissingNameServers_: { + type: Boolean, + value: false, + }, }, observers: ['observeNetwork_(guid)'], @@ -155,8 +162,10 @@ let isIpAddressMissing = !network.ipConfig || !network.ipConfig.ipAddress; let isTimerInProgress = this.timerId_ !== -1; - if (!isIpAddressMissing && this.unableToObtainIpAddress_) { + if (!isIpAddressMissing) { + // Reset this flag now that this network has a valid IP Address. this.unableToObtainIpAddress_ = false; + this.isMissingNameServers_ = isNetworkMissingNameServers(network); } if (isIpAddressMissing && !isTimerInProgress) { @@ -198,7 +207,7 @@ return false; } - if (this.unableToObtainIpAddress_) { + if (this.unableToObtainIpAddress_ || this.isMissingNameServers_) { return false; } @@ -283,13 +292,17 @@ let troubleshootingState = null; if (!this.network || isConnectedOrOnline(this.network.state)) { // Hide the troubleshooting banner if we're in an active state - // unlesss the network's IP Address has been missing for >=30 - // seconds in which case we'd like to display the bannner to - // the user. + // unlesss the network's IP Address has been missing for >= 30 + // seconds or we're missing name servers in which case we'd like + // to display the bannner to the user. if (this.unableToObtainIpAddress_) { troubleshootingState = TroubleshootingState.kMissingIpAddress; } + if (this.isMissingNameServers_) { + troubleshootingState = TroubleshootingState.kMissingNameServers; + } + if (troubleshootingState == null) { this.showTroubleshootingCard_ = false; return { @@ -333,6 +346,18 @@ /** * @private + * @return {!TroubleshootingInfo} + */ + getMissingNameServersInfo_() { + return { + header: this.i18n('missingNameServersText'), + linkText: this.i18n('visitSettingsToConfigureLinkText'), + url: SETTINGS_URL, + } + }, + + /** + * @private * @param {!TroubleshootingState} state * @return {!TroubleshootingInfo} */ @@ -344,6 +369,8 @@ return this.getNotConnectedTroubleshootingInfo_(); case TroubleshootingState.kMissingIpAddress: return this.getMissingIpAddressInfo_(); + case TroubleshootingState.kMissingNameServers: + return this.getMissingNameServersInfo_(); default: return { header: '', linkText: '', url: '',
diff --git a/base/BUILD.gn b/base/BUILD.gn index 7dd2bbf..c1d9d815 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1670,6 +1670,8 @@ "fuchsia/intl_profile_watcher.h", "fuchsia/koid.cc", "fuchsia/koid.h", + "fuchsia/mem_buffer_util.cc", + "fuchsia/mem_buffer_util.h", "fuchsia/process_context.cc", "fuchsia/process_context.h", "fuchsia/scheduler.h",
diff --git a/base/allocator/partition_allocator/partition_alloc_constants.h b/base/allocator/partition_allocator/partition_alloc_constants.h index 64ce0db..404ff59 100644 --- a/base/allocator/partition_allocator/partition_alloc_constants.h +++ b/base/allocator/partition_allocator/partition_alloc_constants.h
@@ -308,6 +308,10 @@ // Constant for the memory reclaim logic. constexpr size_t kMaxFreeableSpans = 16; +// Constant for the memory reclaim logic. +constexpr int kEmptyCacheIndexBits = 8; +// Has to fit into SlotSpanMetadata::empty_cache_index. +static_assert(kMaxFreeableSpans < (1 << (kEmptyCacheIndexBits - 1)), ""); // If the total size in bytes of allocated but not committed pages exceeds this // value (probably it is a "out of virtual address space" crash), a special
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index b920992..05202c72 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -412,8 +412,10 @@ // TODO(ajwong): The waste calculation seems wrong. The PTE usage should cover // both used and unsed pages. // http://crbug.com/776537 +// static template <bool thread_safe> -uint8_t PartitionBucket<thread_safe>::get_system_pages_per_slot_span() { +uint8_t PartitionBucket<thread_safe>::ComputeSystemPagesPerSlotSpan( + size_t slot_size) { // This works out reasonably for the current bucket sizes of the generic // allocator, and the current values of partition page size and constants. // Specifically, we have enough room to always pack the slots perfectly into @@ -474,7 +476,7 @@ empty_slot_spans_head = nullptr; decommitted_slot_spans_head = nullptr; num_full_slot_spans = 0; - num_system_pages_per_slot_span = get_system_pages_per_slot_span(); + num_system_pages_per_slot_span = ComputeSystemPagesPerSlotSpan(slot_size); } template <bool thread_safe> @@ -896,6 +898,13 @@ new_slot_span->next_slot_span = nullptr; new_slot_span->ToSuperPageExtent() ->IncrementNumberOfNonemptySlotSpans(); + + // Re-activating an empty slot span, update accounting. + size_t dirty_size = bits::AlignUp(new_slot_span->GetProvisionedSize(), + SystemPageSize()); + PA_DCHECK(root->empty_slot_spans_dirty_bytes >= dirty_size); + root->empty_slot_spans_dirty_bytes -= dirty_size; + break; } PA_DCHECK(new_slot_span->is_decommitted());
diff --git a/base/allocator/partition_allocator/partition_bucket.h b/base/allocator/partition_allocator/partition_bucket.h index 419d9fd..c150c326 100644 --- a/base/allocator/partition_allocator/partition_bucket.h +++ b/base/allocator/partition_allocator/partition_bucket.h
@@ -99,8 +99,8 @@ return static_cast<uint16_t>(get_bytes_per_span() / slot_size); } // Returns a natural number of partition pages (calculated by - // get_system_pages_per_slot_span()) to allocate from the current - // super page when the bucket runs out of slots. + // ComputeSystemPagesPerSlotSpan()) to allocate from the current super page + // when the bucket runs out of slots. ALWAYS_INLINE uint16_t get_pages_per_slot_span() const { // Rounds up to nearest multiple of NumSystemPagesPerPartitionPage(). return (num_system_pages_per_slot_span + @@ -142,7 +142,7 @@ // allocate for the given slot_size to minimize wasted space. It uses a // heuristic that looks at number of bytes wasted after the last slot and // attempts to account for the PTE usage of each system page. - uint8_t get_system_pages_per_slot_span(); + static uint8_t ComputeSystemPagesPerSlotSpan(size_t slot_size); // Allocates a new slot span with size |num_partition_pages| from the // current extent. Metadata within this slot span will be initialized.
diff --git a/base/allocator/partition_allocator/partition_page.cc b/base/allocator/partition_allocator/partition_page.cc index 642ddfb2..904f9c4 100644 --- a/base/allocator/partition_allocator/partition_page.cc +++ b/base/allocator/partition_allocator/partition_page.cc
@@ -85,6 +85,9 @@ PartitionRoot<thread_safe>::FromSlotSpan(slot_span); root->lock_.AssertAcquired(); + root->empty_slot_spans_dirty_bytes += + base::bits::AlignUp(slot_span->GetProvisionedSize(), SystemPageSize()); + slot_span->ToSuperPageExtent()->DecrementNumberOfNonemptySlotSpans(); // If the slot span is already registered as empty, give it another life. @@ -195,10 +198,12 @@ PA_DCHECK(!bucket->is_direct_mapped()); void* slot_span_start = SlotSpanMetadata::ToSlotSpanStartPtr(this); // If lazy commit is enabled, only provisioned slots are committed. + size_t dirty_size = bits::AlignUp(GetProvisionedSize(), SystemPageSize()); size_t size_to_decommit = - root->use_lazy_commit - ? bits::AlignUp(GetProvisionedSize(), SystemPageSize()) - : bucket->get_bytes_per_span(); + root->use_lazy_commit ? dirty_size : bucket->get_bytes_per_span(); + + PA_DCHECK(root->empty_slot_spans_dirty_bytes >= dirty_size); + root->empty_slot_spans_dirty_bytes -= dirty_size; // Not decommitted slot span must've had at least 1 allocation. PA_DCHECK(size_to_decommit > 0);
diff --git a/base/allocator/partition_allocator/partition_page.h b/base/allocator/partition_allocator/partition_page.h index 2dc6f5d..fd4fe89 100644 --- a/base/allocator/partition_allocator/partition_page.h +++ b/base/allocator/partition_allocator/partition_page.h
@@ -114,16 +114,18 @@ struct __attribute__((packed)) SlotSpanMetadata { PartitionFreelistEntry* freelist_head = nullptr; SlotSpanMetadata<thread_safe>* next_slot_span = nullptr; - PartitionBucket<thread_safe>* const bucket; + PartitionBucket<thread_safe>* const bucket = nullptr; // Deliberately signed, 0 for empty or decommitted slot spans, -n for full // slot spans: int16_t num_allocated_slots = 0; uint16_t num_unprovisioned_slots = 0; - int8_t empty_cache_index = 0; // -1 if not in the empty cache. - // < kMaxFreeableSpans. - static_assert(kMaxFreeableSpans < std::numeric_limits<int8_t>::max(), ""); - const bool can_store_raw_size; + // -1 if not in the empty cache. < kMaxFreeableSpans. + int16_t empty_cache_index : kEmptyCacheIndexBits; + uint16_t can_store_raw_size : 1; + uint16_t unused : (16 - kEmptyCacheIndexBits - 1); + // Cannot use the full 64 bits in this bitfield, as this structure is embedded + // in PartitionPage, which has other fields as well, and must fit in 32 bytes. explicit SlotSpanMetadata(PartitionBucket<thread_safe>* bucket); @@ -237,7 +239,7 @@ static SlotSpanMetadata sentinel_slot_span_; // For the sentinel. constexpr SlotSpanMetadata() noexcept - : bucket(nullptr), can_store_raw_size(false) {} + : empty_cache_index(0), can_store_raw_size(false), unused(0) {} }; static_assert(sizeof(SlotSpanMetadata<ThreadSafe>) <= kPageMetadataSize, "SlotSpanMetadata must fit into a Page Metadata slot."); @@ -262,7 +264,7 @@ // more than 1 page, the page metadata may contain rudimentary additional // information. template <bool thread_safe> -struct PartitionPage { +struct __attribute__((packed)) PartitionPage { // "Pack" the union so that common page metadata still fits within // kPageMetadataSize. (SlotSpanMetadata is also "packed".) union __attribute__((packed)) { @@ -289,7 +291,7 @@ static constexpr uint16_t kMaxSlotSpanMetadataBits = 6; static constexpr uint16_t kMaxSlotSpanMetadataOffset = (1 << kMaxSlotSpanMetadataBits) - 1; - uint8_t slot_span_metadata_offset; + uint8_t slot_span_metadata_offset : kMaxSlotSpanMetadataBits; // |is_valid| tells whether the page is part of a slot span. If |false|, // |has_valid_span_after_this| tells whether it's an unused region in between @@ -299,6 +301,7 @@ // |!slot_span_metadata_offset && slot_span_metadata->bucket|. bool is_valid : 1; bool has_valid_span_after_this : 1; + uint8_t unused; ALWAYS_INLINE static PartitionPage* FromPtr(void* slot_start);
diff --git a/base/allocator/partition_allocator/partition_root.cc b/base/allocator/partition_allocator/partition_root.cc index b21a6a0..b3a4469 100644 --- a/base/allocator/partition_allocator/partition_root.cc +++ b/base/allocator/partition_allocator/partition_root.cc
@@ -491,6 +491,8 @@ slot_span->DecommitIfPossible(this); slot_span = nullptr; } + // Just decommitted everything, and holding the lock, should be exactly 0. + PA_DCHECK(empty_slot_spans_dirty_bytes == 0); } template <bool thread_safe>
diff --git a/base/allocator/partition_allocator/partition_root.h b/base/allocator/partition_allocator/partition_root.h index e75057c..ecd5fc47 100644 --- a/base/allocator/partition_allocator/partition_root.h +++ b/base/allocator/partition_allocator/partition_root.h
@@ -311,6 +311,12 @@ std::atomic<size_t> total_size_of_brp_quarantined_bytes{0}; std::atomic<size_t> total_count_of_brp_quarantined_slots{0}; #endif + // Slot span memory which has been provisioned, and is currently unused as + // it's part of an empty SlotSpan. This is not clean memory, since it has + // either been used for a memory allocation, and/or contains freelist + // entries. But it might have been moved to swap. Note that all this memory + // can be decommitted at any time. + size_t empty_slot_spans_dirty_bytes GUARDED_BY(lock_) = 0; char* next_super_page = nullptr; char* next_partition_page = nullptr; @@ -318,8 +324,9 @@ SuperPageExtentEntry* current_extent = nullptr; SuperPageExtentEntry* first_extent = nullptr; DirectMapExtent* direct_map_list GUARDED_BY(lock_) = nullptr; - SlotSpan* global_empty_slot_span_ring[kMaxFreeableSpans] = {}; - int16_t global_empty_slot_span_ring_index = 0; + SlotSpan* global_empty_slot_span_ring[kMaxFreeableSpans] GUARDED_BY( + lock_) = {}; + int16_t global_empty_slot_span_ring_index GUARDED_BY(lock_) = 0; // Integrity check = ~reinterpret_cast<uintptr_t>(this). uintptr_t inverted_self = 0;
diff --git a/base/fuchsia/mem_buffer_util.cc b/base/fuchsia/mem_buffer_util.cc new file mode 100644 index 0000000..2ab643ee --- /dev/null +++ b/base/fuchsia/mem_buffer_util.cc
@@ -0,0 +1,120 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/fuchsia/mem_buffer_util.h" + +#include <lib/fdio/io.h> + +#include <lib/zx/vmo.h> +#include <string> +#include <utility> + +#include "base/files/file.h" +#include "base/fuchsia/fuchsia_logging.h" +#include "base/strings/string_piece.h" +#include "base/strings/utf_string_conversions.h" + +namespace base { + +absl::optional<std::u16string> ReadUTF8FromVMOAsUTF16( + const fuchsia::mem::Buffer& buffer) { + absl::optional<std::string> output_utf8 = StringFromMemBuffer(buffer); + if (!output_utf8) + return absl::nullopt; + std::u16string output; + return UTF8ToUTF16(&output_utf8->front(), output_utf8->size(), &output) + ? absl::optional<std::u16string>(std::move(output)) + : absl::nullopt; +} + +fuchsia::mem::Buffer MemBufferFromString(StringPiece data, StringPiece name) { + fuchsia::mem::Buffer buffer; + + zx_status_t status = zx::vmo::create(data.size(), 0, &buffer.vmo); + ZX_CHECK(status == ZX_OK, status) << "zx_vmo_create"; + status = buffer.vmo.set_property(ZX_PROP_NAME, name.data(), name.size()); + ZX_DCHECK(status == ZX_OK, status); + if (data.size() > 0) { + status = buffer.vmo.write(data.data(), 0, data.size()); + ZX_CHECK(status == ZX_OK, status) << "zx_vmo_write"; + } + + buffer.size = data.size(); + return buffer; +} + +fuchsia::mem::Buffer MemBufferFromString16(StringPiece16 data, + StringPiece name) { + return MemBufferFromString( + StringPiece(reinterpret_cast<const char*>(data.data()), + data.size() * sizeof(char16_t)), + name); +} + +absl::optional<std::string> StringFromMemBuffer( + const fuchsia::mem::Buffer& buffer) { + std::string result; + + if (buffer.size == 0) + return result; + + result.resize(buffer.size); + zx_status_t status = buffer.vmo.read(&result[0], 0, buffer.size); + if (status == ZX_OK) + return result; + + ZX_LOG(ERROR, status) << "zx_vmo_read"; + return absl::nullopt; +} + +absl::optional<std::string> StringFromMemData(const fuchsia::mem::Data& data) { + switch (data.Which()) { + case fuchsia::mem::Data::kBytes: { + const std::vector<uint8_t>& bytes = data.bytes(); + return std::string(bytes.begin(), bytes.end()); + } + case fuchsia::mem::Data::kBuffer: + return StringFromMemBuffer(data.buffer()); + case fuchsia::mem::Data::kUnknown: + case fuchsia::mem::Data::Invalid: + // TODO(fxbug.dev/66155): Determine whether to use a default case instead. + break; + } + + return absl::nullopt; +} + +fuchsia::mem::Buffer MemBufferFromFile(File file) { + if (!file.IsValid()) + return {}; + + zx::vmo vmo; + zx_status_t status = + fdio_get_vmo_copy(file.GetPlatformFile(), vmo.reset_and_get_address()); + if (status != ZX_OK) { + ZX_LOG(ERROR, status) << "fdio_get_vmo_copy"; + return {}; + } + + fuchsia::mem::Buffer output; + output.vmo = std::move(vmo); + output.size = file.GetLength(); + return output; +} + +fuchsia::mem::Buffer CloneBuffer(const fuchsia::mem::Buffer& buffer, + StringPiece name) { + fuchsia::mem::Buffer output; + output.size = buffer.size; + zx_status_t status = buffer.vmo.create_child( + ZX_VMO_CHILD_SNAPSHOT_AT_LEAST_ON_WRITE, 0, buffer.size, &output.vmo); + ZX_CHECK(status == ZX_OK, status) << "zx_vmo_create_child"; + + status = output.vmo.set_property(ZX_PROP_NAME, name.data(), name.size()); + ZX_DCHECK(status == ZX_OK, status); + + return output; +} + +} // namespace base
diff --git a/base/fuchsia/mem_buffer_util.h b/base/fuchsia/mem_buffer_util.h new file mode 100644 index 0000000..0323a83 --- /dev/null +++ b/base/fuchsia/mem_buffer_util.h
@@ -0,0 +1,52 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_FUCHSIA_MEM_BUFFER_UTIL_H_ +#define BASE_FUCHSIA_MEM_BUFFER_UTIL_H_ + +#include <fuchsia/mem/cpp/fidl.h> +#include <string> + +#include "base/base_export.h" +#include "base/files/file.h" +#include "base/strings/string_piece_forward.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace base { + +// Returns the contents of `buffer` (which must be a valid UTF-8 string), or +// null in case of a conversion error. +BASE_EXPORT absl::optional<std::u16string> ReadUTF8FromVMOAsUTF16( + const fuchsia::mem::Buffer& buffer); + +// Creates a Fuchsia memory buffer from `data`. The resulting virtual memory +// object will be given the name `name`. +BASE_EXPORT fuchsia::mem::Buffer MemBufferFromString(StringPiece data, + StringPiece name); + +// Creates a Fuchsia memory buffer from the UTF-16 string `data`. The resulting +// virtual memory object will be given the name `name`. +BASE_EXPORT fuchsia::mem::Buffer MemBufferFromString16(StringPiece16 data, + StringPiece name); + +// Returns the contents of `buffer`, or null if the read operation fails. +BASE_EXPORT absl::optional<std::string> StringFromMemBuffer( + const fuchsia::mem::Buffer& buffer); + +// Returns the contents of `data`, or null if the read operation fails. +BASE_EXPORT absl::optional<std::string> StringFromMemData( + const fuchsia::mem::Data& data); + +// Creates a memory-mapped, read-only Buffer with the contents of `file`. Will +// return an empty Buffer if the file could not be opened. +BASE_EXPORT fuchsia::mem::Buffer MemBufferFromFile(File file); + +// Creates a non-resizeable, copy-on-write shared memory clone of `buffer`. The +// resulting virtual memory object will be given the name `name`. +BASE_EXPORT fuchsia::mem::Buffer CloneBuffer(const fuchsia::mem::Buffer& buffer, + StringPiece name); + +} // namespace base + +#endif // BASE_FUCHSIA_MEM_BUFFER_UTIL_H_
diff --git a/base/memory/raw_ptr_unittest.cc b/base/memory/raw_ptr_unittest.cc index fa096819..63f39cad 100644 --- a/base/memory/raw_ptr_unittest.cc +++ b/base/memory/raw_ptr_unittest.cc
@@ -826,19 +826,19 @@ raw_ptr<uint64_t> wrapped_ptr1 = raw_ptr1; EXPECT_EQ(allocator.root()->total_size_of_brp_quarantined_bytes.load( std::memory_order_relaxed), - 0); + 0U); EXPECT_EQ(allocator.root()->total_count_of_brp_quarantined_slots.load( std::memory_order_relaxed), - 0); + 0U); // Memory should get quarantined. allocator.root()->Free(raw_ptr1); EXPECT_GT(allocator.root()->total_size_of_brp_quarantined_bytes.load( std::memory_order_relaxed), - 0); + 0U); EXPECT_EQ(allocator.root()->total_count_of_brp_quarantined_slots.load( std::memory_order_relaxed), - 1); + 1U); // Non quarantined free should not effect total_size_of_brp_quarantined_bytes void* raw_ptr2 = allocator.root()->Alloc(sizeof(uint64_t), ""); @@ -848,10 +848,10 @@ wrapped_ptr1 = nullptr; EXPECT_EQ(allocator.root()->total_size_of_brp_quarantined_bytes.load( std::memory_order_relaxed), - 0); + 0U); EXPECT_EQ(allocator.root()->total_count_of_brp_quarantined_slots.load( std::memory_order_relaxed), - 0); + 0U); } #if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS)
diff --git a/build/android/BUILD.gn b/build/android/BUILD.gn index c24fce52..2446381c 100644 --- a/build/android/BUILD.gn +++ b/build/android/BUILD.gn
@@ -125,9 +125,11 @@ ":devil_chromium_py", "//third_party/catapult/tracing:convert_chart_json", ] + data = [ build_vars_file, android_readelf, + rebase_path("$android_ndk_library_path/libc++.so.1", root_build_dir), ] }
diff --git a/build/android/gyp/assert_static_initializers.py b/build/android/gyp/assert_static_initializers.py index 9af5e2b..5f746e9 100755 --- a/build/android/gyp/assert_static_initializers.py +++ b/build/android/gyp/assert_static_initializers.py
@@ -23,8 +23,9 @@ def _RunReadelf(so_path, options, tool_prefix=''): - return subprocess.check_output([tool_prefix + 'readelf'] + options + - [so_path]).decode('utf8') + return subprocess.check_output( + [tool_prefix + 'readobj', '--elf-output-style=GNU'] + options + + [so_path]).decode('utf8') def _ParseLibBuildId(so_path, tool_prefix):
diff --git a/build/android/resource_sizes.py b/build/android/resource_sizes.py index 825edad..0ffe235 100755 --- a/build/android/resource_sizes.py +++ b/build/android/resource_sizes.py
@@ -168,8 +168,10 @@ def _RunReadelf(so_path, options, tool_prefix=''): - return cmd_helper.GetCmdOutput( - [tool_prefix + 'readelf'] + options + [so_path]) + return cmd_helper.GetCmdOutput([ + tool_prefix + 'readobj', + '--elf-output-style=GNU', + ] + options + [so_path]) def _ExtractLibSectionSizesFromApk(apk_path, lib_path, tool_prefix):
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index e7540e8..57efc1c 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -343,8 +343,9 @@ } android_toolchain_root = "$android_ndk_root/toolchains/llvm/prebuilt/${android_host_os}-${android_host_arch}" - android_tool_prefix = "$android_toolchain_root/bin/$_binary_prefix-" - android_readelf = "${android_tool_prefix}readelf" + android_ndk_library_path = "$android_toolchain_root/lib64" + android_tool_prefix = "$android_toolchain_root/bin/llvm-" + android_readelf = "${android_tool_prefix}readobj" android_objcopy = "${android_tool_prefix}objcopy" android_gdbserver = "$android_ndk_root/prebuilt/$android_prebuilt_arch/gdbserver/gdbserver"
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index f48d2fd..9778107 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -6.20210923.2.1 +6.20210924.1.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index f48d2fd..9778107 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -6.20210923.2.1 +6.20210924.1.1
diff --git a/build/toolchain/android/BUILD.gn b/build/toolchain/android/BUILD.gn index 728885e..8988f2d 100644 --- a/build/toolchain/android/BUILD.gn +++ b/build/toolchain/android/BUILD.gn
@@ -43,23 +43,25 @@ # Output linker map files for binary size analysis. enable_linker_map = true - _android_tool_prefix = - "$android_toolchain_root/bin/${invoker.binary_prefix}-" + _android_tool_prefix = "$android_toolchain_root/bin/" # The tools should be run relative to the build dir. _tool_prefix = rebase_path("$_android_tool_prefix", root_build_dir) - _prefix = rebase_path("$clang_base_path/bin", root_build_dir) cc = "$_prefix/clang" cxx = "$_prefix/clang++" ar = "$_prefix/llvm-ar" ld = cxx - readelf = _tool_prefix + "readelf" + readelf = _tool_prefix + "llvm-readobj" nm = "$_prefix/llvm-nm" strip = "$_prefix/llvm-strip" if (_use_debug_fission) { - dwp = _tool_prefix + "dwp" + _dwp_tool_prefix = + rebase_path("$android_toolchain_root/bin/${invoker.binary_prefix}-", + root_build_dir) + dwp = _dwp_tool_prefix + "dwp" } + use_unstripped_as_runtime_outputs = android_unstripped_runtime_outputs # Don't use .cr.so for loadable_modules since they are always loaded via @@ -69,7 +71,9 @@ } android_clang_toolchain("android_clang_x86") { - binary_prefix = "i686-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "i686-linux-android" + } toolchain_args = { current_cpu = "x86" @@ -94,21 +98,27 @@ } android_clang_toolchain("android_clang_arm") { - binary_prefix = "arm-linux-androideabi" + if (use_debug_fission && target_os == "android") { + binary_prefix = "arm-linux-androideabi" + } toolchain_args = { current_cpu = "arm" } } android_clang_toolchain("android_clang_mipsel") { - binary_prefix = "mipsel-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "mipsel-linux-android" + } toolchain_args = { current_cpu = "mipsel" } } android_clang_toolchain("android_clang_x64") { - binary_prefix = "x86_64-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "x86_64-linux-android" + } toolchain_args = { current_cpu = "x64" @@ -133,14 +143,18 @@ } android_clang_toolchain("android_clang_arm64") { - binary_prefix = "aarch64-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "aarch64-linux-android" + } toolchain_args = { current_cpu = "arm64" } } android_clang_toolchain("android_clang_arm64_hwasan") { - binary_prefix = "aarch64-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "aarch64-linux-android" + } toolchain_args = { current_cpu = "arm64" is_hwasan = true @@ -149,7 +163,9 @@ } android_clang_toolchain("android_clang_mips64el") { - binary_prefix = "mips64el-linux-android" + if (use_debug_fission && target_os == "android") { + binary_prefix = "mips64el-linux-android" + } toolchain_args = { current_cpu = "mips64el" }
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index 54c36770..b8d4c0a4 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -322,7 +322,8 @@ "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/BottomSheetOnboardingCoordinatorTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/DirectActionsIntegrationTest.java", - "javatests/src/org/chromium/chrome/browser/autofill_assistant/InChromeTriggeringTest.java", + "javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromGsaTest.java", + "javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromNonGsaTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/MiniActionTestUtil.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/PasswordChangeFixtureParameters.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/PasswordChangeFixtureTest.java",
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java index ff0989c..067a72cc 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java
@@ -349,6 +349,36 @@ }; } + /** + * Runs the main loop for at least the specified amount of time. Useful in cases where you need + * to ensure a negative, e.g., a certain view is never displayed. Intended usage: + * onView(isRoot()).waitAtLeast(...); + */ + static ViewAction waitAtLeast(long millis) { + return new ViewAction() { + @Override + public Matcher<View> getConstraints() { + return ViewMatchers.isRoot(); + } + + @Override + public String getDescription() { + return "Waits/idles for a specified amount of time"; + } + + @Override + public void perform(UiController uiController, View view) { + uiController.loopMainThreadUntilIdle(); + + long endTime = System.currentTimeMillis() + millis; + while (System.currentTimeMillis() < endTime) { + uiController.loopMainThreadForAtLeast( + Math.max(endTime - System.currentTimeMillis(), 50)); + } + } + }; + } + static ViewAction openTextLink(String textLink) { return new ViewAction() { @Override
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InChromeTriggeringTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromGsaTest.java similarity index 88% rename from chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InChromeTriggeringTest.java rename to chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromGsaTest.java index 8b0e715..9ff57c01 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InChromeTriggeringTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromGsaTest.java
@@ -15,6 +15,9 @@ import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.waitUntilViewAssertionTrue; import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.waitUntilViewMatchesCondition; +import android.provider.Browser; +import android.support.test.InstrumentationRegistry; + import androidx.test.filters.MediumTest; import com.google.protobuf.GeneratedMessageLite; @@ -25,27 +28,29 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.autofill_assistant.proto.GetTriggerScriptsResponseProto; import org.chromium.chrome.browser.autofill_assistant.proto.TriggerScriptProto; +import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; +import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridge; import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.content_public.browser.test.util.TestThreadUtils; /** - * Tests for TriggerContext. + * Tests for heuristics-based triggering in tabs created by GSA. */ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @RunWith(ChromeJUnit4ClassRunner.class) -public class InChromeTriggeringTest { +public class InCctTriggeringFromGsaTest { private static final String HTML_DIRECTORY = "/components/test/data/autofill_assistant/html/"; private static final String TEST_PAGE_UNSUPPORTED = "autofill_assistant_target_website.html"; private static final String TEST_PAGE_SUPPORTED = "cart.html"; @Rule - public ChromeTabbedActivityTestRule mTestRule = new ChromeTabbedActivityTestRule(); + public CustomTabActivityTestRule mTestRule = new CustomTabActivityTestRule(); private String getTargetWebsiteUrl(String testPage) { return mTestRule.getTestServer().getURL(HTML_DIRECTORY + testPage); @@ -60,7 +65,11 @@ @Before public void setUp() { - mTestRule.startMainActivityOnBlankPage(); + mTestRule.startCustomTabActivityWithIntent( + CustomTabsTestUtils + .createMinimalCustomTabIntent(InstrumentationRegistry.getTargetContext(), + getTargetWebsiteUrl(TEST_PAGE_UNSUPPORTED)) + .putExtra(Browser.EXTRA_APPLICATION_ID, IntentHandler.PACKAGE_GSA)); // Enable MSBB. AutofillAssistantPreferencesUtil.setProactiveHelpSwitch(true); @@ -102,7 +111,7 @@ @MediumTest // clang-format off @CommandLineFlags. - Add({"enable-features=AutofillAssistantInTabTriggering<FakeStudyName," + Add({"enable-features=AutofillAssistantInCctTriggering<FakeStudyName," +"AutofillAssistantUrlHeuristics<FakeStudyName", "force-fieldtrials=FakeStudyName/Enabled", "force-fieldtrial-params=FakeStudyName.Enabled:json_parameters/"
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromNonGsaTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromNonGsaTest.java new file mode 100644 index 0000000..d9bba1b --- /dev/null +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/InCctTriggeringFromNonGsaTest.java
@@ -0,0 +1,131 @@ +// 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. + +package org.chromium.chrome.browser.autofill_assistant; + +import static org.chromium.base.test.util.CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL; +import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.waitAtLeast; + +import android.provider.Browser; +import android.support.test.InstrumentationRegistry; + +import androidx.test.filters.MediumTest; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.browser.autofill_assistant.proto.GetTriggerScriptsResponseProto; +import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; +import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; +import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridge; +import org.chromium.chrome.browser.tabmodel.TabModelUtils; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.content_public.browser.test.util.TestThreadUtils; + +/** + * Tests for heuristics-based triggering in tabs created *not* by GSA. + */ +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +@RunWith(ChromeJUnit4ClassRunner.class) +public class InCctTriggeringFromNonGsaTest { + private static final String HTML_DIRECTORY = "/components/test/data/autofill_assistant/html/"; + private static final String TEST_PAGE_UNSUPPORTED = "autofill_assistant_target_website.html"; + private static final String TEST_PAGE_SUPPORTED = "cart.html"; + + @Rule + public CustomTabActivityTestRule mTestRule = new CustomTabActivityTestRule(); + + private String getTargetWebsiteUrl(String testPage) { + return mTestRule.getTestServer().getURL(HTML_DIRECTORY + testPage); + } + + private void setupTriggerScripts(GetTriggerScriptsResponseProto triggerScripts) { + AutofillAssistantTestServiceRequestSender testServiceRequestSender = + new AutofillAssistantTestServiceRequestSender(); + testServiceRequestSender.setNextResponse(/* httpStatus = */ 200, triggerScripts); + testServiceRequestSender.scheduleForInjection(); + } + + private void enableMsbb() { + AutofillAssistantPreferencesUtil.setProactiveHelpSwitch(true); + TestThreadUtils.runOnUiThreadBlocking(() -> { + UnifiedConsentServiceBridge.setUrlKeyedAnonymizedDataCollectionEnabled( + AutofillAssistantUiController.getProfile(), true); + + // Force native to pick up the changes we made to Chrome preferences. + AutofillAssistantTabHelper + .get(TabModelUtils.getCurrentTab(mTestRule.getActivity().getCurrentTabModel())) + .forceSettingsChangeNotificationForTesting(); + }); + } + + /** + * Tests a simple trigger heuristic that checks URLs for the appearance of 'cart'. The activity + * is started by a fake third-party app and thus should not trigger autofill assistant. + */ + @Test + @MediumTest + // clang-format off + @CommandLineFlags. + Add({"enable-features=AutofillAssistantInCctTriggering<FakeStudyName," + +"AutofillAssistantUrlHeuristics<FakeStudyName", + "force-fieldtrials=FakeStudyName/Enabled", + "force-fieldtrial-params=FakeStudyName.Enabled:json_parameters/" + +"%7B%22heuristics%22%3A%5B%7B%22intent%22%3A%22SHOPPING_ASSISTED_CHECKOUT" + +"%22%2C%22conditionSet%22%3A%7B%22urlMatches%22%3A%22.*cart.*%22%7D%7D%5D%7D"}) + // clang-format on + public void + doNotTriggerForExternalCct() throws InterruptedException { + mTestRule.startCustomTabActivityWithIntent( + CustomTabsTestUtils + .createMinimalCustomTabIntent(InstrumentationRegistry.getTargetContext(), + getTargetWebsiteUrl(TEST_PAGE_UNSUPPORTED)) + .putExtra(Browser.EXTRA_APPLICATION_ID, "com.example")); + enableMsbb(); + + AutofillAssistantTestServiceRequestSender testServiceRequestSender = + new AutofillAssistantTestServiceRequestSender(); + testServiceRequestSender.scheduleForInjection(); + + // The test service should not receive a request while waiting here. If it does, it will + // assert-fail because no response has been configured. + mTestRule.loadUrl(getTargetWebsiteUrl(TEST_PAGE_SUPPORTED)); + waitAtLeast(DEFAULT_MAX_TIME_TO_POLL); + } + + /** + * Tests a simple trigger heuristic that checks URLs for the appearance of 'cart'. The activity + * does not identify its origin and thus should not trigger autofill assistant. + */ + @Test + @MediumTest + // clang-format off + @CommandLineFlags. + Add({"enable-features=AutofillAssistantInCctTriggering<FakeStudyName," + +"AutofillAssistantUrlHeuristics<FakeStudyName", + "force-fieldtrials=FakeStudyName/Enabled", + "force-fieldtrial-params=FakeStudyName.Enabled:json_parameters/" + +"%7B%22heuristics%22%3A%5B%7B%22intent%22%3A%22SHOPPING_ASSISTED_CHECKOUT" + +"%22%2C%22conditionSet%22%3A%7B%22urlMatches%22%3A%22.*cart.*%22%7D%7D%5D%7D"}) + // clang-format on + public void + doNotTriggerForCctWithUnknownOrigin() throws InterruptedException { + mTestRule.startCustomTabActivityWithIntent(CustomTabsTestUtils.createMinimalCustomTabIntent( + InstrumentationRegistry.getTargetContext(), + getTargetWebsiteUrl(TEST_PAGE_UNSUPPORTED))); + enableMsbb(); + + AutofillAssistantTestServiceRequestSender testServiceRequestSender = + new AutofillAssistantTestServiceRequestSender(); + testServiceRequestSender.scheduleForInjection(); + + // The test service should not receive a request while waiting here. If it does, it will + // assert-fail because no response has been configured. + mTestRule.loadUrl(getTargetWebsiteUrl(TEST_PAGE_SUPPORTED)); + waitAtLeast(DEFAULT_MAX_TIME_TO_POLL); + } +}
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/Starter.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/Starter.java index e322340..5f8dd8e 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/Starter.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/Starter.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.autofill_assistant; +import android.content.Intent; + import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; @@ -11,6 +13,8 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; +import org.chromium.chrome.browser.IntentHandler; +import org.chromium.chrome.browser.IntentHandler.ExternalAppId; import org.chromium.chrome.browser.autofill_assistant.metrics.FeatureModuleInstallation; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridge; @@ -287,6 +291,20 @@ return mDependencies; } + @CalledByNative + private boolean getIsTabCreatedByGSA() { + // This can fail for certain tabs (e.g., hidden background tabs). + if (TabUtils.getActivity(mTab) == null) { + return false; + } + Intent intent = TabUtils.getActivity(mTab).getIntent(); + if (intent == null) { + // This should never happen, this is just a failsafe. + return false; + } + return IntentHandler.determineExternalIntentSource(intent) == ExternalAppId.GSA; + } + @NativeMethods interface Natives { long fromWebContents(WebContents webContents);
diff --git a/chrome/android/java/res/xml/privacy_preferences.xml b/chrome/android/java/res/xml/privacy_preferences.xml index 654d517c..909f440 100644 --- a/chrome/android/java/res/xml/privacy_preferences.xml +++ b/chrome/android/java/res/xml/privacy_preferences.xml
@@ -24,6 +24,11 @@ android:key="https_first_mode" android:title="@string/settings_https_first_mode_title" android:summary="@string/settings_https_first_mode_summary"/> + <org.chromium.chrome.browser.incognito.IncognitoReauthSettingSwitchPreference + android:key="incognito_lock" + android:title="@string/settings_incognito_tab_lock_title" + android:summary="@string/settings_incognito_tab_lock_summary_android_setting_off" + android:persistent="false"/> <org.chromium.components.browser_ui.settings.ChromeSwitchPreference android:key="can_make_payment" android:title="@string/can_make_payment_title"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java index 244f9ed..640402e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java
@@ -592,21 +592,22 @@ .get(mMode == ContextMenuMode.CUSTOM_TAB ? 0 : groupedItems.size() - 1) .second; - if (mMode == ContextMenuMode.WEB_APP - && UrlUtilities.isAcceptedScheme(mParams.getUrl())) { - items.add(createListItem(Item.OPEN_IN_CHROME)); - } else if (mMode == ContextMenuMode.CUSTOM_TAB && !mItemDelegate.isIncognito()) { - boolean addNewEntries = !UrlUtilities.isInternalScheme(mParams.getUrl()) - && !isEmptyUrl(mParams.getUrl()); - if (SharedPreferencesManager.getInstance().readBoolean( - ChromePreferenceKeys.CHROME_DEFAULT_BROWSER, false) - && addNewEntries) { - if (mItemDelegate.isIncognitoSupported()) { - items.add(0, createListItem(Item.OPEN_IN_CHROME_INCOGNITO_TAB)); + if (UrlUtilities.isAcceptedScheme(mParams.getUrl())) { + if (mMode == ContextMenuMode.WEB_APP) { + items.add(createListItem(Item.OPEN_IN_CHROME)); + } else if (mMode == ContextMenuMode.CUSTOM_TAB && !mItemDelegate.isIncognito()) { + boolean addNewEntries = !UrlUtilities.isInternalScheme(mParams.getUrl()) + && !isEmptyUrl(mParams.getUrl()); + if (SharedPreferencesManager.getInstance().readBoolean( + ChromePreferenceKeys.CHROME_DEFAULT_BROWSER, false) + && addNewEntries) { + if (mItemDelegate.isIncognitoSupported()) { + items.add(0, createListItem(Item.OPEN_IN_CHROME_INCOGNITO_TAB)); + } + items.add(0, createListItem(Item.OPEN_IN_NEW_CHROME_TAB)); + } else if (addNewEntries && UrlUtilities.isAcceptedScheme(mParams.getUrl())) { + items.add(0, createListItem(Item.OPEN_IN_BROWSER_ID)); } - items.add(0, createListItem(Item.OPEN_IN_NEW_CHROME_TAB)); - } else if (addNewEntries && UrlUtilities.isAcceptedScheme(mParams.getUrl())) { - items.add(0, createListItem(Item.OPEN_IN_BROWSER_ID)); } } if (groupedItems.isEmpty() && items.size() > 0) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/privacy/settings/PrivacySettings.java b/chrome/android/java/src/org/chromium/chrome/browser/privacy/settings/PrivacySettings.java index d695e3dd..897f4d4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/privacy/settings/PrivacySettings.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/privacy/settings/PrivacySettings.java
@@ -18,6 +18,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.feedback.HelpAndFeedbackLauncherImpl; import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.incognito.IncognitoReauthManager; +import org.chromium.chrome.browser.incognito.IncognitoReauthSettingSwitchPreference; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.privacy.secure_dns.SecureDnsSettings; import org.chromium.chrome.browser.privacy_review.PrivacyReviewDialog; @@ -58,6 +60,7 @@ private static final String PREF_CLEAR_BROWSING_DATA = "clear_browsing_data"; private static final String PREF_PRIVACY_SANDBOX = "privacy_sandbox"; private static final String PREF_PRIVACY_REVIEW = "privacy_review"; + private static final String PREF_INCOGNITO_LOCK = "incognito_lock"; private ManagedPreferenceDelegate mManagedPreferenceDelegate; @@ -91,6 +94,8 @@ }); } + setUpIncognitoReauthPreference(); + Preference safeBrowsingPreference = findPreference(PREF_SAFE_BROWSING); safeBrowsingPreference.setSummary( SafeBrowsingSettingsFragment.getSafeBrowsingSummaryString(getContext())); @@ -130,7 +135,7 @@ Preference syncAndServicesLink = findPreference(PREF_SYNC_AND_SERVICES_LINK); syncAndServicesLink.setSummary(buildSyncAndServicesLink()); - updateSummaries(); + updatePreferences(); } private SpannableString buildSyncAndServicesLink() { @@ -157,6 +162,35 @@ new SpanApplier.SpanInfo("<link2>", "</link2>", servicesLink)); } + private void setUpIncognitoReauthPreference() { + IncognitoReauthSettingSwitchPreference incognitoReauthPreference = + (IncognitoReauthSettingSwitchPreference) findPreference(PREF_INCOGNITO_LOCK); + if (!IncognitoReauthManager.shouldShowSetting()) { + incognitoReauthPreference.setVisible(false); + return; + } + incognitoReauthPreference.setLinkClickDelegate(() -> { + getActivity().startActivity(IncognitoReauthManager.getSystemLocationSettingsIntent()); + }); + incognitoReauthPreference.setOnPreferenceChangeListener(this); + + updateIncognitoReauthPreference(); + } + + private void updateIncognitoReauthPreference() { + if (!IncognitoReauthManager.shouldShowSetting()) return; + IncognitoReauthSettingSwitchPreference incognitoReauthPreference = + (IncognitoReauthSettingSwitchPreference) findPreference(PREF_INCOGNITO_LOCK); + incognitoReauthPreference.setSummary( + IncognitoReauthManager.getSummaryString(getActivity())); + incognitoReauthPreference.setPreferenceInteractable( + IncognitoReauthManager.isDeviceScreenLockEnabled()); + + boolean lastPrefValue = UserPrefs.get(Profile.getLastUsedRegularProfile()) + .getBoolean(Pref.INCOGNITO_REAUTHENTICATION_FOR_ANDROID); + incognitoReauthPreference.setChecked(lastPrefValue); + } + @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); @@ -169,6 +203,9 @@ } else if (PREF_HTTPS_FIRST_MODE.equals(key)) { UserPrefs.get(Profile.getLastUsedRegularProfile()) .setBoolean(Pref.HTTPS_ONLY_MODE_ENABLED, (boolean) newValue); + } else if (PREF_INCOGNITO_LOCK.equals(key)) { + UserPrefs.get(Profile.getLastUsedRegularProfile()) + .setBoolean(Pref.INCOGNITO_REAUTHENTICATION_FOR_ANDROID, (boolean) newValue); } return true; @@ -177,13 +214,13 @@ @Override public void onResume() { super.onResume(); - updateSummaries(); + updatePreferences(); } /** - * Updates the summaries for several preferences. + * Updates the preferences. */ - public void updateSummaries() { + public void updatePreferences() { PrefService prefService = UserPrefs.get(Profile.getLastUsedRegularProfile()); ChromeSwitchPreference canMakePaymentPref = @@ -219,7 +256,7 @@ .create(getActivity(), true, (didConfirm) -> { if (didConfirm) { - updateSummaries(); + updatePreferences(); } }) .show(); @@ -235,6 +272,8 @@ privacySandboxPreference.setSummary( PrivacySandboxSettingsFragment.getStatusString(getContext())); } + + updateIncognitoReauthPreference(); } private ChromeManagedPreferenceDelegate createManagedPreferenceDelegate() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateDataFetcher.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateDataFetcher.java index 67c43fc..30a69b2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateDataFetcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateDataFetcher.java
@@ -120,7 +120,8 @@ String[] iconUrls, @WebDisplayMode int displayMode, int orientation, long themeColor, long backgroundColor, String shareAction, String shareParamsTitle, String shareParamsText, boolean isShareMethodPost, boolean isShareEncTypeMultipart, - String[] shareParamsFileNames, String[][] shareParamsAccepts, String[][] shortcuts) { + String[] shareParamsFileNames, String[][] shareParamsAccepts, String[][] shortcuts, + byte[][] shortcutIconData) { Context appContext = ContextUtils.getApplicationContext(); HashMap<String, String> iconUrlToMurmur2HashMap = new HashMap<String, String>(); @@ -135,11 +136,12 @@ } List<WebApkExtras.ShortcutItem> shortcutItems = new ArrayList<>(); - for (String[] shortcutData : shortcuts) { + for (int i = 0; i < shortcuts.length; i++) { + String[] shortcutData = shortcuts[i]; shortcutItems.add(new WebApkExtras.ShortcutItem(shortcutData[0] /* name */, shortcutData[1] /* shortName */, shortcutData[2] /* launchUrl */, shortcutData[3] /* iconUrl */, shortcutData[4] /* iconHash */, - new WebappIcon(shortcutData[5], false /* isTrusted */))); + new WebappIcon(shortcutIconData[i]))); } // When share action is empty, we use a default empty share target
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java index 3949537..867c431 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java
@@ -509,10 +509,12 @@ } String[][] shortcuts = new String[info.shortcutItems().size()][]; + byte[][] shortcutIconData = new byte[info.shortcutItems().size()][]; for (int j = 0; j < info.shortcutItems().size(); j++) { WebApkExtras.ShortcutItem shortcut = info.shortcutItems().get(j); shortcuts[j] = new String[] {shortcut.name, shortcut.shortName, shortcut.launchUrl, - shortcut.iconUrl, shortcut.iconHash, shortcut.icon.encoded()}; + shortcut.iconUrl, shortcut.iconHash}; + shortcutIconData[j] = shortcut.icon.data(); } String shareTargetAction = ""; @@ -545,9 +547,9 @@ info.displayMode(), info.orientation(), info.toolbarColor(), info.backgroundColor(), shareTargetAction, shareTargetParamTitle, shareTargetParamText, shareTargetIsMethodPost, shareTargetIsEncTypeMultipart, shareTargetParamFileNames, - shareTargetParamAccepts, shortcuts, info.manifestUrl(), info.webApkPackageName(), - versionCode, isManifestStale, isAppIdentityUpdateSupported, updateReasonsArray, - callback); + shareTargetParamAccepts, shortcuts, shortcutIconData, info.manifestUrl(), + info.webApkPackageName(), versionCode, isManifestStale, + isAppIdentityUpdateSupported, updateReasonsArray, callback); } @NativeMethods @@ -561,8 +563,9 @@ String shareTargetParamTitle, String shareTargetParamText, boolean shareTargetParamIsMethodPost, boolean shareTargetParamIsEncTypeMultipart, String[] shareTargetParamFileNames, Object[] shareTargetParamAccepts, - String[][] shortcuts, String manifestUrl, String webApkPackage, int webApkVersion, - boolean isManifestStale, boolean isAppIdentityUpdateSupported, int[] updateReasons, + String[][] shortcuts, byte[][] shortcutIconData, String manifestUrl, + String webApkPackage, int webApkVersion, boolean isManifestStale, + boolean isAppIdentityUpdateSupported, int[] updateReasons, Callback<Boolean> callback); public void updateWebApkFromFile(String updateRequestPath, WebApkUpdateCallback callback); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/privacy/settings/PrivacySettingsFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/privacy/settings/PrivacySettingsFragmentTest.java index 8cd3639..7cbf584 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/privacy/settings/PrivacySettingsFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/privacy/settings/PrivacySettingsFragmentTest.java
@@ -4,9 +4,17 @@ package org.chromium.chrome.browser.privacy.settings; +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.assertion.ViewAssertions.matches; +import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; +import static androidx.test.espresso.matcher.ViewMatchers.withText; + +import android.text.TextUtils; import android.view.View; +import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; +import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.filters.LargeTest; import org.junit.Before; @@ -20,6 +28,7 @@ import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.incognito.IncognitoReauthManager; import org.chromium.chrome.browser.settings.SettingsActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; @@ -61,6 +70,22 @@ }); } + private View getIncognitoReauthSettingView(PrivacySettings privacySettings) { + String incognito_lock_title = mSettingsActivityTestRule.getActivity().getString( + R.string.settings_incognito_tab_lock_title); + RecyclerViewActions.scrollTo(withText(incognito_lock_title)); + onView(withText(incognito_lock_title)).check(matches(isDisplayed())); + + for (int i = 0; i < privacySettings.getListView().getChildCount(); ++i) { + View view = privacySettings.getListView().getChildAt(i); + String title = ((TextView) view.findViewById(android.R.id.title)).getText().toString(); + if (!TextUtils.isEmpty(title) && TextUtils.equals(incognito_lock_title, title)) { + return view; + } + } + return null; + } + @Test @LargeTest @Feature({"RenderTest"}) @@ -89,4 +114,34 @@ .getRootView(); mRenderTestRule.render(view, "privacy_and_security_settings_bottom_view"); } + + @Test + @LargeTest + @Feature({"RenderTest"}) + public void testRenderIncognitoLockView_DeviceScreenLockDisabled() throws IOException { + IncognitoReauthManager.setShouldShowSettingForTesting(true); + IncognitoReauthManager.setIsDeviceScreenLockEnabledForTesting(false); + + mSettingsActivityTestRule.startSettingsActivity(); + waitForOptionsMenu(); + PrivacySettings fragment = mSettingsActivityTestRule.getFragment(); + + mRenderTestRule.render(getIncognitoReauthSettingView(fragment), + "incognito_reauth_setting_screen_lock_disabled"); + } + + @Test + @LargeTest + @Feature({"RenderTest"}) + public void testRenderIncognitoLockView_DeviceScreenLockEnabled() throws IOException { + IncognitoReauthManager.setShouldShowSettingForTesting(true); + IncognitoReauthManager.setIsDeviceScreenLockEnabledForTesting(true); + + mSettingsActivityTestRule.startSettingsActivity(); + waitForOptionsMenu(); + PrivacySettings fragment = mSettingsActivityTestRule.getFragment(); + + mRenderTestRule.render(getIncognitoReauthSettingView(fragment), + "incognito_reauth_setting_screen_lock_enabled"); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java index 6fc008e..f971b4a1 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java
@@ -443,6 +443,7 @@ if (fullName != null) { onView(withText(fullName)).check(matches(isDisplayed())); } + onView(withId(R.id.signin_fre_selected_account_expand_icon)).check(matches(isDisplayed())); final String continueAsText = mFragment.getString( R.string.signin_promo_continue_as, profileData.getGivenNameOrFullNameOrEmail()); onView(withText(continueAsText)).check(matches(isDisplayed())); @@ -465,6 +466,8 @@ onView(withText(R.string.fre_welcome)).check(matches(isDisplayed())); onView(withText(TEST_EMAIL1)).check(matches(not(isDisplayed()))); onView(withText(FULL_NAME1)).check(matches(not(isDisplayed()))); + onView(withId(R.id.signin_fre_selected_account_expand_icon)) + .check(matches(not(isDisplayed()))); final String continueAsText = mChromeActivityTestRule.getActivity().getString( R.string.signin_promo_continue_as, GIVEN_NAME1); onView(withText(continueAsText)).check(matches(not(isDisplayed()))); @@ -481,6 +484,8 @@ mFragment.getView().findViewById(R.id.signin_fre_selected_account).isEnabled()); onView(withText(CHILD_EMAIL)).check(matches(isDisplayed())); onView(withText(CHILD_FULL_NAME)).check(matches(isDisplayed())); + onView(withId(R.id.signin_fre_selected_account_expand_icon)) + .check(matches(not(isDisplayed()))); final String continueAsText = mFragment.getString(R.string.signin_promo_continue_as, CHILD_FULL_NAME); onView(withText(continueAsText)).check(matches(isDisplayed()));
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SyncConsentFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SyncConsentFragmentTest.java index d195f74aa..bf4e3c1c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SyncConsentFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SyncConsentFragmentTest.java
@@ -52,7 +52,6 @@ import org.chromium.chrome.browser.firstrun.SyncConsentFirstRunFragment; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.signin.services.FREMobileIdentityConsistencyFieldTrial; import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; import org.chromium.chrome.browser.sync.SyncService; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -78,7 +77,8 @@ * Render tests for sync consent fragment. */ @RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +@CommandLineFlags. +Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeSwitches.FORCE_ENABLE_SIGNIN_FRE}) public class SyncConsentFragmentTest { private static final int RENDER_REVISION = 1; private static final String RENDER_DESCRIPTION = "Change button style"; @@ -134,7 +134,6 @@ @Before public void setUp() { - FREMobileIdentityConsistencyFieldTrial.enableForTesting(); when(mExternalAuthUtilsMock.canUseGooglePlayServices(any())).thenReturn(true); ExternalAuthUtils.setInstanceForTesting(mExternalAuthUtilsMock); mActivityTestRule.setFinishActivity(true); @@ -308,8 +307,8 @@ @Test @LargeTest @Feature("RenderTest") + @CommandLineFlags.Remove({ChromeSwitches.FORCE_ENABLE_SIGNIN_FRE}) public void testFragmentWithRegularChildAccountLegacy() throws IOException { - FREMobileIdentityConsistencyFieldTrial.disableForTesting(); HistogramDelta countHistogram = new HistogramDelta("Signin.AndroidDeviceAccountsNumberWhenEnteringFRE", 1); HistogramDelta startPageHistogram = @@ -332,8 +331,8 @@ @Test @LargeTest @Feature("RenderTest") + @CommandLineFlags.Remove({ChromeSwitches.FORCE_ENABLE_SIGNIN_FRE}) public void testFragmentWithUSMChildAccountLegacy() throws IOException { - FREMobileIdentityConsistencyFieldTrial.disableForTesting(); HistogramDelta countHistogram = new HistogramDelta("Signin.AndroidDeviceAccountsNumberWhenEnteringFRE", 1); HistogramDelta startPageHistogram =
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java index 830cd7c..c725eb2 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java
@@ -149,8 +149,9 @@ String shareTargetParamTitle, String shareTargetParamText, boolean shareTargetParamIsMethodPost, boolean shareTargetParamIsEncTypeMultipart, String[] shareTargetParamFileNames, Object[] shareTargetParamAccepts, - String[][] shortcuts, String manifestUrl, String webApkPackage, int webApkVersion, - boolean isManifestStale, boolean isAppIdentityUpdateSupported, int[] updateReasons, + String[][] shortcuts, byte[][] shortcutIconData, String manifestUrl, + String webApkPackage, int webApkVersion, boolean isManifestStale, + boolean isAppIdentityUpdateSupported, int[] updateReasons, Callback<Boolean> callback) {} @Override
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index b8a91c01..1003d16f 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3287,11 +3287,6 @@ {"debug-packed-apps", flag_descriptions::kDebugPackedAppName, flag_descriptions::kDebugPackedAppDescription, kOsDesktop, SINGLE_VALUE_TYPE(switches::kDebugPackedApps)}, - {"use-lookalikes-for-navigation-suggestions", - flag_descriptions::kUseLookalikesForNavigationSuggestionsName, - flag_descriptions::kUseLookalikesForNavigationSuggestionsDescription, - kOsAll, - FEATURE_VALUE_TYPE(net::features::kUseLookalikesForNavigationSuggestions)}, {"username-first-flow", flag_descriptions::kUsernameFirstFlowName, flag_descriptions::kUsernameFirstFlowDescription, kOsAll, FEATURE_VALUE_TYPE(password_manager::features::kUsernameFirstFlow)}, @@ -4795,10 +4790,6 @@ kTabGroupsSaveUIVariations, "TabGroupsSave")}, - {"new-tabstrip-animation", flag_descriptions::kNewTabstripAnimationName, - flag_descriptions::kNewTabstripAnimationDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kNewTabstripAnimation)}, - {flag_descriptions::kScrollableTabStripFlagId, flag_descriptions::kScrollableTabStripName, flag_descriptions::kScrollableTabStripDescription,
diff --git a/chrome/browser/android/autofill_assistant/starter_android.cc b/chrome/browser/android/autofill_assistant/starter_android.cc index 5299a6b..9da2813 100644 --- a/chrome/browser/android/autofill_assistant/starter_android.cc +++ b/chrome/browser/android/autofill_assistant/starter_android.cc
@@ -220,6 +220,16 @@ return ui_controller_android_utils::IsCustomTab(web_contents_); } +bool StarterAndroid::GetIsTabCreatedByGSA() const { + if (!java_object_) { + // Failsafe, should never happen. + DCHECK(false); + return false; + } + return Java_Starter_getIsTabCreatedByGSA(base::android::AttachCurrentThread(), + java_object_); +} + void StarterAndroid::CreateJavaDependenciesIfNecessary() { if (java_dependencies_) { return;
diff --git a/chrome/browser/android/autofill_assistant/starter_android.h b/chrome/browser/android/autofill_assistant/starter_android.h index eba49dfb..65874f82 100644 --- a/chrome/browser/android/autofill_assistant/starter_android.h +++ b/chrome/browser/android/autofill_assistant/starter_android.h
@@ -74,6 +74,7 @@ void SetProactiveHelpSettingEnabled(bool enabled) override; bool GetMakeSearchesAndBrowsingBetterEnabled() const override; bool GetIsCustomTab() const override; + bool GetIsTabCreatedByGSA() const override; // Called by Java to start an autofill-assistant flow for an incoming intent. void Start(
diff --git a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/WebappIcon.java b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/WebappIcon.java index 25cac30..ce110994 100644 --- a/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/WebappIcon.java +++ b/chrome/browser/android/browserservices/intents/java/src/org/chromium/chrome/browser/browserservices/intents/WebappIcon.java
@@ -8,6 +8,7 @@ import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; +import android.util.Base64; import androidx.annotation.VisibleForTesting; @@ -16,6 +17,7 @@ /** Represents bitmap icon. Lazily converts icon format. */ public class WebappIcon { + private byte[] mUnsafeData; private String mEncoded; private Bitmap mBitmap; private String mWebApkPackageName; @@ -24,6 +26,10 @@ public WebappIcon() {} + public WebappIcon(byte[] unsafeData) { + mUnsafeData = unsafeData; + } + /** * @param encoded The encoded data of a bitmap. * @param isTrusted Whether the encoded data came from a trusted source. If false, the data @@ -43,6 +49,13 @@ mResourceId = resourceId; } + public byte[] data() { + if (mUnsafeData != null) { + return mUnsafeData; + } + return Base64.decode(encoded(), Base64.DEFAULT); + } + public String encoded() { if (mEncoded == null) { mEncoded = BitmapHelper.encodeBitmapAsString(bitmap());
diff --git a/chrome/browser/android/webapk/webapk_update_data_fetcher.cc b/chrome/browser/android/webapk/webapk_update_data_fetcher.cc index 32433ab..d4dcd7ed 100644 --- a/chrome/browser/android/webapk/webapk_update_data_fetcher.cc +++ b/chrome/browser/android/webapk/webapk_update_data_fetcher.cc
@@ -261,6 +261,9 @@ // The inner vector represents a shortcut items, with the following fields: // <name>, <short name>, <launch url>, <icon url>, <icon hash>. std::vector<std::vector<std::u16string>> shortcuts; + // Each entry contains the icon data for the corresponding entry in + // |shortcuts|. + std::vector<std::string> shortcut_icon_data; DCHECK_EQ(info_.shortcut_items.size(), info_.best_shortcut_icon_urls.size()); for (size_t i = 0; i < info_.shortcut_items.size(); i++) { @@ -279,8 +282,8 @@ shortcut.short_name.value_or(std::u16string()), base::UTF8ToUTF16(shortcut.url.spec()), base::UTF8ToUTF16(chosen_icon_url.spec()), - base::UTF8ToUTF16(chosen_icon_hash), - base::UTF8ToUTF16(chosen_icon_data)}); + base::UTF8ToUTF16(chosen_icon_hash)}); + shortcut_icon_data.push_back(std::move(chosen_icon_data)); } Java_WebApkUpdateDataFetcher_onDataAvailable( @@ -295,5 +298,6 @@ java_share_params_title, java_share_params_text, java_share_params_is_method_post, java_share_params_is_enctype_multipart, java_share_params_file_names, java_share_params_accepts, - base::android::ToJavaArrayOfStringArray(env, shortcuts)); + base::android::ToJavaArrayOfStringArray(env, shortcuts), + base::android::ToJavaArrayOfByteArray(env, shortcut_icon_data)); }
diff --git a/chrome/browser/android/webapk/webapk_update_manager.cc b/chrome/browser/android/webapk/webapk_update_manager.cc index 22c39ad..ede51fc 100644 --- a/chrome/browser/android/webapk/webapk_update_manager.cc +++ b/chrome/browser/android/webapk/webapk_update_manager.cc
@@ -76,6 +76,7 @@ const JavaParamRef<jobjectArray>& java_share_target_param_file_names, const JavaParamRef<jobjectArray>& java_share_target_param_accepts, const JavaParamRef<jobjectArray>& java_shortcuts, + const JavaParamRef<jobjectArray>& java_shortcut_icon_data, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, @@ -174,11 +175,18 @@ ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); std::vector<std::vector<std::u16string>> shortcuts; + std::vector<std::string> shortcut_icon_data; base::android::Java2dStringArrayTo2dStringVector(env, java_shortcuts, &shortcuts); + base::android::JavaArrayOfByteArrayToStringVector( + env, java_shortcut_icon_data, &shortcut_icon_data); - for (const auto& shortcut_data : shortcuts) { - DCHECK_EQ(shortcut_data.size(), 6u); + DCHECK_EQ(shortcuts.size(), shortcut_icon_data.size()); + + for (size_t i = 0; i < shortcuts.size(); i++) { + const auto& shortcut_data = shortcuts[i]; + DCHECK_EQ(shortcut_data.size(), 5u); + blink::Manifest::ShortcutItem shortcut_item; shortcut_item.name = shortcut_data[0]; shortcut_item.short_name = shortcut_data[1]; @@ -193,7 +201,7 @@ if (icon_src.is_valid()) { icon_url_to_murmur2_hash[icon_src.spec()] = webapps::WebApkIconHasher::Icon{ - /* data= */ base::UTF16ToUTF8(shortcut_data[5]), + /* data= */ std::move(shortcut_icon_data[i]), /* hash= */ base::UTF16ToUTF8(shortcut_data[4])}; } info.best_shortcut_icon_urls.push_back(std::move(icon_src));
diff --git a/chrome/browser/ash/arc/input_method_manager/arc_input_method_manager_service.cc b/chrome/browser/ash/arc/input_method_manager/arc_input_method_manager_service.cc index 76c1ead..4552f74 100644 --- a/chrome/browser/ash/arc/input_method_manager/arc_input_method_manager_service.cc +++ b/chrome/browser/ash/arc/input_method_manager/arc_input_method_manager_service.cc
@@ -467,7 +467,7 @@ state->RemoveInputMethodExtension(proxy_ime_extension_id_); const InputMethodDescriptors installed_imes = - arc_ime_state_.GetActiveInputMethods(); + arc_ime_state_.GetAvailableInputMethods(); if (installed_imes.empty()) { // If no ARC IME is installed or allowed, remove ARC IME entry from // preferences.
diff --git a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.cc b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.cc index f8b7f3cb..d6ec3c5 100644 --- a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.cc +++ b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.cc
@@ -42,7 +42,7 @@ SetInputMethodEnabled(ime_id, false); } -InputMethodDescriptors ArcInputMethodState::GetActiveInputMethods() const { +InputMethodDescriptors ArcInputMethodState::GetAvailableInputMethods() const { const bool all_allowed = delegate_->ShouldArcIMEAllowed(); InputMethodDescriptors result;
diff --git a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.h b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.h index 7fd16c3..0e11cf63 100644 --- a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.h +++ b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state.h
@@ -39,7 +39,7 @@ void DisableInputMethod(const std::string& ime_id); // Return the InputMethodDescriptors which are installed and allowed. - ash::input_method::InputMethodDescriptors GetActiveInputMethods() const; + ash::input_method::InputMethodDescriptors GetAvailableInputMethods() const; // Return the InputMethodDescriptors which are enabled and allowed. ash::input_method::InputMethodDescriptors GetEnabledInputMethods() const;
diff --git a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state_unittest.cc b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state_unittest.cc index 1dce857..21d8890 100644 --- a/chrome/browser/ash/arc/input_method_manager/arc_input_method_state_unittest.cc +++ b/chrome/browser/ash/arc/input_method_manager/arc_input_method_state_unittest.cc
@@ -50,7 +50,7 @@ ArcInputMethodState empty_state(&delegate); InputMethodDescriptors empty_vector; - EXPECT_EQ(0u, empty_state.GetActiveInputMethods().size()); + EXPECT_EQ(0u, empty_state.GetAvailableInputMethods().size()); EXPECT_EQ(0u, empty_state.GetEnabledInputMethods().size()); } @@ -65,7 +65,7 @@ imes.push_back(GenerateImeInfo("ime_d", false, true)); state.InitializeWithImeInfo("ime_id", imes); - InputMethodDescriptors active_imes = state.GetActiveInputMethods(); + InputMethodDescriptors active_imes = state.GetAvailableInputMethods(); EXPECT_EQ(2u, active_imes.size()); EXPECT_EQ("ime_b", active_imes[0].id()); EXPECT_EQ("ime_d", active_imes[1].id()); @@ -97,15 +97,15 @@ imes.push_back(GenerateImeInfo("ime_b", true, false)); state.InitializeWithImeInfo("ime_id", imes); - EXPECT_EQ(1u, state.GetActiveInputMethods().size()); - EXPECT_EQ("ime_a", state.GetActiveInputMethods()[0].id()); + EXPECT_EQ(1u, state.GetAvailableInputMethods().size()); + EXPECT_EQ("ime_a", state.GetAvailableInputMethods()[0].id()); delegate.allowed = true; - EXPECT_EQ(2u, state.GetActiveInputMethods().size()); + EXPECT_EQ(2u, state.GetAvailableInputMethods().size()); delegate.allowed = false; - EXPECT_EQ(1u, state.GetActiveInputMethods().size()); - EXPECT_EQ("ime_a", state.GetActiveInputMethods()[0].id()); + EXPECT_EQ(1u, state.GetAvailableInputMethods().size()); + EXPECT_EQ("ime_a", state.GetAvailableInputMethods()[0].id()); } TEST(ArcInputMethodState, Histogram) {
diff --git a/chrome/browser/ash/input_method/input_method_manager_impl.cc b/chrome/browser/ash/input_method/input_method_manager_impl.cc index 574185e..47a89662 100644 --- a/chrome/browser/ash/input_method/input_method_manager_impl.cc +++ b/chrome/browser/ash/input_method/input_method_manager_impl.cc
@@ -133,9 +133,16 @@ // ------------------------ InputMethodManagerImpl::StateImpl -InputMethodManagerImpl::StateImpl::StateImpl(InputMethodManagerImpl* manager, - Profile* profile) - : profile(profile), manager_(manager) {} +InputMethodManagerImpl::StateImpl::StateImpl( + InputMethodManagerImpl* manager, + Profile* profile, + const InputMethodDescriptor* initial_input_method) + : profile(profile), manager_(manager) { + if (initial_input_method) { + enabled_input_method_ids_.push_back(initial_input_method->id()); + current_input_method_ = *initial_input_method; + } +} InputMethodManagerImpl::StateImpl::~StateImpl() = default; @@ -147,20 +154,20 @@ InputMethodManagerImpl::StateImpl::Clone() const { scoped_refptr<StateImpl> new_state(new StateImpl(this->manager_, profile)); - new_state->last_used_input_method_id = last_used_input_method_id; - new_state->current_input_method = current_input_method; + new_state->last_used_input_method_id_ = last_used_input_method_id_; + new_state->current_input_method_ = current_input_method_; - new_state->enabled_input_method_ids = enabled_input_method_ids; - new_state->allowed_keyboard_layout_input_method_ids = - allowed_keyboard_layout_input_method_ids; + new_state->enabled_input_method_ids_ = enabled_input_method_ids_; + new_state->allowed_keyboard_layout_input_method_ids_ = + allowed_keyboard_layout_input_method_ids_; - new_state->pending_input_method_id = pending_input_method_id; + new_state->pending_input_method_id_ = pending_input_method_id_; - new_state->enabled_extension_imes = enabled_extension_imes; + new_state->enabled_extension_imes_ = enabled_extension_imes_; new_state->available_input_methods = available_input_methods; new_state->menu_activated = menu_activated; - new_state->input_view_url = input_view_url; - new_state->input_view_url_overridden = input_view_url_overridden; + new_state->input_view_url_ = input_view_url_; + new_state->input_view_url_overridden_ = input_view_url_overridden_; new_state->ui_style_ = ui_style_; return scoped_refptr<InputMethodManager::State>(new_state.get()); @@ -170,8 +177,8 @@ InputMethodManagerImpl::StateImpl::GetEnabledInputMethods() const { std::unique_ptr<InputMethodDescriptors> result(new InputMethodDescriptors); // Build the enabled input method descriptors from the enabled input - // methods cache |enabled_input_method_ids|. - for (const auto& input_method_id : enabled_input_method_ids) { + // methods cache |enabled_input_method_ids_|. + for (const auto& input_method_id : enabled_input_method_ids_) { const InputMethodDescriptor* descriptor = manager_->util_.GetInputMethodDescriptorFromId(input_method_id); if (descriptor) { @@ -185,7 +192,7 @@ } } if (result->empty()) { - // Initially |enabled_input_method_ids| is empty. browser_tests might take + // Initially |enabled_input_method_ids_| is empty. browser_tests might take // this path. result->push_back( InputMethodUtil::GetFallbackInputMethodDescriptor()); @@ -195,11 +202,11 @@ const std::vector<std::string>& InputMethodManagerImpl::StateImpl::GetEnabledInputMethodIds() const { - return enabled_input_method_ids; + return enabled_input_method_ids_; } size_t InputMethodManagerImpl::StateImpl::GetNumEnabledInputMethods() const { - return enabled_input_method_ids.size(); + return enabled_input_method_ids_.size(); } const InputMethodDescriptor* @@ -269,13 +276,13 @@ } manager_->MigrateInputMethods(&layouts); - enabled_input_method_ids.swap(layouts); + enabled_input_method_ids_.swap(layouts); if (IsActive()) { // Initialize candidate window controller and widgets such as // candidate window, infolist and mode indicator. Note, mode // indicator is used by only keyboard layout input methods. - if (enabled_input_method_ids.size() > 1) + if (enabled_input_method_ids_.size() > 1) manager_->MaybeInitializeCandidateWindowController(); // you can pass empty |initial_layout|. @@ -294,7 +301,7 @@ manager_->util_.GetHardwareLoginInputMethodIds(); std::vector<std::string> new_enabled_input_method_ids; - for (const auto& input_method_id : enabled_input_method_ids) { + for (const auto& input_method_id : enabled_input_method_ids_) { // Skip if it's not a keyboard layout. Drop input methods including // extension ones. We need to keep all IMEs to support inputting on inline // reply on a notification if notifications on lock screen is enabled. @@ -308,7 +315,7 @@ } // We'll add the hardware keyboard if it's not included in - // |enabled_input_method_ids| so that the user can always use the hardware + // |enabled_input_method_ids_| so that the user can always use the hardware // keyboard on the screen locker. for (const auto& hardware_keyboard_id : hardware_keyboard_ids) { if (added_ids.count(hardware_keyboard_id)) @@ -317,10 +324,10 @@ added_ids.insert(hardware_keyboard_id); } - enabled_input_method_ids.swap(new_enabled_input_method_ids); + enabled_input_method_ids_.swap(new_enabled_input_method_ids); - // Re-check current_input_method. - ChangeInputMethod(current_input_method.id(), false); + // Re-check current_input_method_. + ChangeInputMethod(current_input_method_.id(), false); } // Adds new input method to given list. @@ -346,7 +353,7 @@ bool InputMethodManagerImpl::StateImpl::EnableInputMethod( const std::string& input_method_id) { - if (!EnableInputMethodImpl(input_method_id, &enabled_input_method_ids)) + if (!EnableInputMethodImpl(input_method_id, &enabled_input_method_ids_)) return false; manager_->ReconfigureIMFramework(this); @@ -372,25 +379,25 @@ // Copy extension IDs to |new_enabled_input_method_ids_filtered|. We have to // keep relative order of the extension input method IDs. - for (const auto& input_method_id : enabled_input_method_ids) { + for (const auto& input_method_id : enabled_input_method_ids_) { if (extension_ime_util::IsExtensionIME(input_method_id)) new_enabled_input_method_ids_filtered.push_back(input_method_id); } - enabled_input_method_ids.swap(new_enabled_input_method_ids_filtered); - manager_->MigrateInputMethods(&enabled_input_method_ids); + enabled_input_method_ids_.swap(new_enabled_input_method_ids_filtered); + manager_->MigrateInputMethods(&enabled_input_method_ids_); manager_->ReconfigureIMFramework(this); - // If |current_input_method| is no longer in |enabled_input_method_ids|, - // ChangeInputMethod() picks the first one in |enabled_input_method_ids|. - ChangeInputMethod(current_input_method.id(), false); + // If |current_input_method_| is no longer in |enabled_input_method_ids_|, + // ChangeInputMethod() picks the first one in |enabled_input_method_ids_|. + ChangeInputMethod(current_input_method_.id(), false); // Record histogram for enabled input method count; "active" in the metric // name is a legacy misnomer; "active" should refer to just the single current // aka. activated input method that's one of the enabled input methods whose // total count is being tracked by this metric. UMA_HISTOGRAM_COUNTS_1M("InputMethod.ActiveCount", - enabled_input_method_ids.size()); + enabled_input_method_ids_.size()); return true; } @@ -398,16 +405,16 @@ bool InputMethodManagerImpl::StateImpl::SetAllowedInputMethods( const std::vector<std::string>& new_allowed_input_method_ids, bool enable_allowed_input_methods) { - allowed_keyboard_layout_input_method_ids.clear(); + allowed_keyboard_layout_input_method_ids_.clear(); for (auto input_method_id : new_allowed_input_method_ids) { std::string migrated_id = manager_->util_.MigrateInputMethod(input_method_id); if (manager_->util_.IsValidInputMethodId(migrated_id)) { - allowed_keyboard_layout_input_method_ids.push_back(migrated_id); + allowed_keyboard_layout_input_method_ids_.push_back(migrated_id); } } - if (allowed_keyboard_layout_input_method_ids.empty()) { + if (allowed_keyboard_layout_input_method_ids_.empty()) { // None of the passed input methods were valid, so allow everything. return false; } @@ -415,13 +422,13 @@ std::vector<std::string> new_enabled_input_method_ids; if (enable_allowed_input_methods) { // Enable all allowed input methods. - new_enabled_input_method_ids = allowed_keyboard_layout_input_method_ids; + new_enabled_input_method_ids = allowed_keyboard_layout_input_method_ids_; } else { // Filter all currently enabled input methods and leave only non-keyboard or // allowed keyboard layouts. If no input method remains, take a fallback // keyboard layout. bool has_keyboard_layout = false; - for (auto enabled_input_method_id : enabled_input_method_ids) { + for (auto enabled_input_method_id : enabled_input_method_ids_) { if (IsInputMethodAllowed(enabled_input_method_id)) { new_enabled_input_method_ids.push_back(enabled_input_method_id); has_keyboard_layout |= @@ -437,19 +444,19 @@ const std::vector<std::string>& InputMethodManagerImpl::StateImpl::GetAllowedInputMethods() { - return allowed_keyboard_layout_input_method_ids; + return allowed_keyboard_layout_input_method_ids_; } bool InputMethodManagerImpl::StateImpl::IsInputMethodAllowed( const std::string& input_method_id) const { // Every input method is allowed if SetAllowedKeyboardLayoutInputMethods has // not been called. - if (allowed_keyboard_layout_input_method_ids.empty()) + if (allowed_keyboard_layout_input_method_ids_.empty()) return true; - return base::Contains(allowed_keyboard_layout_input_method_ids, + return base::Contains(allowed_keyboard_layout_input_method_ids_, input_method_id) || - base::Contains(allowed_keyboard_layout_input_method_ids, + base::Contains(allowed_keyboard_layout_input_method_ids_, manager_->util_.MigrateInputMethod(input_method_id)); } @@ -460,7 +467,7 @@ if (IsInputMethodAllowed(hardware_id)) return hardware_id; } - return allowed_keyboard_layout_input_method_ids[0]; + return allowed_keyboard_layout_input_method_ids_[0]; } void InputMethodManagerImpl::StateImpl::ChangeInputMethod( @@ -472,9 +479,9 @@ bool notify_menu = false; // Always lookup input method, even if it is the same as - // |current_input_method| because If it is no longer in - // |enabled_input_method_ids|, pick the first one in - // |enabled_input_method_ids|. + // |current_input_method_| because If it is no longer in + // |enabled_input_method_ids_|, pick the first one in + // |enabled_input_method_ids_|. const InputMethodDescriptor* descriptor = manager_->LookupInputMethod(input_method_id, this); if (!descriptor) { @@ -492,11 +499,11 @@ // So here to record the 3rd party IME to be activated, and activate it // when SetEnabledExtensionImes happens later. if (MethodAwaitsExtensionLoad(input_method_id)) - pending_input_method_id = input_method_id; + pending_input_method_id_ = input_method_id; - if (descriptor->id() != current_input_method.id()) { - last_used_input_method_id = current_input_method.id(); - current_input_method = *descriptor; + if (descriptor->id() != current_input_method_.id()) { + last_used_input_method_id_ = current_input_method_.id(); + current_input_method_ = *descriptor; notify_menu = true; } @@ -507,7 +514,7 @@ notify_menu); } - manager_->RecordInputMethodUsage(current_input_method.id()); + manager_->RecordInputMethodUsage(current_input_method_.id()); } void InputMethodManagerImpl::StateImpl::ChangeInputMethodToJpKeyboard() { @@ -556,9 +563,9 @@ for (const auto& descriptor : descriptors) { const std::string& id = descriptor.id(); available_input_methods[id] = descriptor; - if (base::Contains(enabled_extension_imes, id)) { - if (!base::Contains(enabled_input_method_ids, id)) { - enabled_input_method_ids.push_back(id); + if (base::Contains(enabled_extension_imes_, id)) { + if (!base::Contains(enabled_input_method_ids_, id)) { + enabled_input_method_ids_.push_back(id); } else { DVLOG(1) << "AddInputMethodExtension: already added: " << id << ", " << descriptor.name(); @@ -569,10 +576,10 @@ if (IsActive()) { if (extension_id == extension_ime_util::GetExtensionIDFromInputMethodID( - current_input_method.id())) { + current_input_method_.id())) { ui::IMEBridge::Get()->SetCurrentEngineHandler(engine); engine->Enable(extension_ime_util::GetComponentIDByInputMethodID( - current_input_method.id())); + current_input_method_.id())); } // Ensure that the input method daemon is running. @@ -588,12 +595,12 @@ const std::string& extension_id) { // Remove the enabled input methods with |extension_id|. std::vector<std::string> new_enabled_input_method_ids; - for (const auto& enabled_input_method_id : enabled_input_method_ids) { + for (const auto& enabled_input_method_id : enabled_input_method_ids_) { if (extension_id != extension_ime_util::GetExtensionIDFromInputMethodID( enabled_input_method_id)) new_enabled_input_method_ids.push_back(enabled_input_method_id); } - enabled_input_method_ids.swap(new_enabled_input_method_ids); + enabled_input_method_ids_.swap(new_enabled_input_method_ids); // Remove the input methods registered by `extension_id`. std::map<std::string, InputMethodDescriptor> new_available_input_methods; @@ -612,9 +619,9 @@ manager_->engine_map_[profile].erase(extension_id); } - // If |current_input_method| is no longer in |enabled_input_method_ids|, - // switch to the first one in |enabled_input_method_ids|. - ChangeInputMethod(current_input_method.id(), false); + // If |current_input_method_| is no longer in |enabled_input_method_ids_|, + // switch to the first one in |enabled_input_method_ids_|. + ChangeInputMethod(current_input_method_.id(), false); manager_->NotifyInputMethodExtensionRemoved(extension_id); } @@ -632,9 +639,9 @@ void InputMethodManagerImpl::StateImpl::SetEnabledExtensionImes( std::vector<std::string>* ids) { - enabled_extension_imes.clear(); - enabled_extension_imes.insert( - enabled_extension_imes.end(), ids->begin(), ids->end()); + enabled_extension_imes_.clear(); + enabled_extension_imes_.insert(enabled_extension_imes_.end(), ids->begin(), + ids->end()); bool enabled_imes_changed = false; bool switch_to_pending = false; @@ -642,22 +649,22 @@ if (extension_ime_util::IsComponentExtensionIME(entry.first)) continue; // Do not filter component extension. - if (pending_input_method_id == entry.first) + if (pending_input_method_id_ == entry.first) switch_to_pending = true; const auto currently_enabled_iter = - std::find(enabled_input_method_ids.begin(), - enabled_input_method_ids.end(), entry.first); + std::find(enabled_input_method_ids_.begin(), + enabled_input_method_ids_.end(), entry.first); bool currently_enabled = - currently_enabled_iter != enabled_input_method_ids.end(); - bool enabled = base::Contains(enabled_extension_imes, entry.first); + currently_enabled_iter != enabled_input_method_ids_.end(); + bool enabled = base::Contains(enabled_extension_imes_, entry.first); if (currently_enabled && !enabled) - enabled_input_method_ids.erase(currently_enabled_iter); + enabled_input_method_ids_.erase(currently_enabled_iter); if (!currently_enabled && enabled) - enabled_input_method_ids.push_back(entry.first); + enabled_input_method_ids_.push_back(entry.first); if (currently_enabled == !enabled) enabled_imes_changed = true; @@ -667,12 +674,12 @@ manager_->MaybeInitializeCandidateWindowController(); if (switch_to_pending) { - ChangeInputMethod(pending_input_method_id, false); - pending_input_method_id.clear(); + ChangeInputMethod(pending_input_method_id_, false); + pending_input_method_id_.clear(); } else { - // If |current_input_method| is no longer in |enabled_input_method_ids_|, + // If |current_input_method_| is no longer in |enabled_input_method_ids_|, // switch to the first one in |enabled_input_method_ids_|. - ChangeInputMethod(current_input_method.id(), false); + ChangeInputMethod(current_input_method_.id(), false); } } } @@ -717,7 +724,7 @@ manager_->util_.UpdateHardwareLayoutCache(); EnableLoginLayouts(locale, layouts); - manager_->LoadNecessaryComponentExtensions(this); + LoadNecessaryComponentExtensions(); } void InputMethodManagerImpl::StateImpl::SetInputMethodLoginDefault() { @@ -744,23 +751,23 @@ } } EnableLoginLayouts(locale, input_methods_to_be_enabled); - manager_->LoadNecessaryComponentExtensions(this); + LoadNecessaryComponentExtensions(); } } bool InputMethodManagerImpl::StateImpl::CanCycleInputMethod() const { // Sanity checks. - if (enabled_input_method_ids.empty()) { + if (enabled_input_method_ids_.empty()) { DVLOG(1) << "enabled input method is empty"; return false; } - if (current_input_method.id().empty()) { - DVLOG(1) << "current_input_method is unknown"; + if (current_input_method_.id().empty()) { + DVLOG(1) << "current_input_method_ is unknown"; return false; } - return enabled_input_method_ids.size() > 1; + return enabled_input_method_ids_.size() > 1; } void InputMethodManagerImpl::StateImpl::SwitchToNextInputMethod() { @@ -768,12 +775,12 @@ return; auto iter = - std::find(enabled_input_method_ids.begin(), - enabled_input_method_ids.end(), current_input_method.id()); - if (iter != enabled_input_method_ids.end()) + std::find(enabled_input_method_ids_.begin(), + enabled_input_method_ids_.end(), current_input_method_.id()); + if (iter != enabled_input_method_ids_.end()) ++iter; - if (iter == enabled_input_method_ids.end()) - iter = enabled_input_method_ids.begin(); + if (iter == enabled_input_method_ids_.end()) + iter = enabled_input_method_ids_.begin(); ChangeInputMethod(*iter, true); } @@ -781,17 +788,17 @@ if (!CanCycleInputMethod()) return; - if (last_used_input_method_id.empty() || - last_used_input_method_id == current_input_method.id()) { + if (last_used_input_method_id_.empty() || + last_used_input_method_id_ == current_input_method_.id()) { SwitchToNextInputMethod(); return; } const auto iter = - std::find(enabled_input_method_ids.begin(), - enabled_input_method_ids.end(), last_used_input_method_id); - if (iter == enabled_input_method_ids.end()) { - // last_used_input_method_id is not supported. + std::find(enabled_input_method_ids_.begin(), + enabled_input_method_ids_.end(), last_used_input_method_id_); + if (iter == enabled_input_method_ids_.end()) { + // last_used_input_method_id_ is not supported. SwitchToNextInputMethod(); return; } @@ -800,29 +807,29 @@ InputMethodDescriptor InputMethodManagerImpl::StateImpl::GetCurrentInputMethod() const { - if (current_input_method.id().empty()) + if (current_input_method_.id().empty()) return InputMethodUtil::GetFallbackInputMethodDescriptor(); - return current_input_method; + return current_input_method_; } bool InputMethodManagerImpl::StateImpl::InputMethodIsEnabled( const std::string& input_method_id) const { - return base::Contains(enabled_input_method_ids, input_method_id); + return base::Contains(enabled_input_method_ids_, input_method_id); } void InputMethodManagerImpl::StateImpl::EnableInputView() { - if (!input_view_url_overridden) { - input_view_url = current_input_method.input_view_url(); + if (!input_view_url_overridden_) { + input_view_url_ = current_input_method_.input_view_url(); } } void InputMethodManagerImpl::StateImpl::DisableInputView() { - input_view_url = GURL(); + input_view_url_ = GURL(); } const GURL& InputMethodManagerImpl::StateImpl::GetInputViewUrl() const { - return input_view_url; + return input_view_url_; } InputMethodManager::UIStyle InputMethodManagerImpl::StateImpl::GetUIStyle() @@ -836,13 +843,41 @@ } void InputMethodManagerImpl::StateImpl::OverrideInputViewUrl(const GURL& url) { - input_view_url = url; - input_view_url_overridden = true; + input_view_url_ = url; + input_view_url_overridden_ = true; } void InputMethodManagerImpl::StateImpl::ResetInputViewUrl() { - input_view_url = current_input_method.input_view_url(); - input_view_url_overridden = false; + input_view_url_ = current_input_method_.input_view_url(); + input_view_url_overridden_ = false; +} + +void InputMethodManagerImpl::StateImpl::LoadNecessaryComponentExtensions() { + // Load component extensions but also update |enabled_input_method_ids_| as + // some component extension IMEs may have been removed from the Chrome OS + // image. If specified component extension IME no longer exists, falling back + // to an existing IME. + TRACE_EVENT0( + "ime", + "InputMethodManagerImpl::StateImpl::LoadNecessaryComponentExtensions"); + std::vector<std::string> unfiltered_input_method_ids; + unfiltered_input_method_ids.swap(enabled_input_method_ids_); + std::set<std::string> ext_loaded; + for (const auto& unfiltered_input_method_id : unfiltered_input_method_ids) { + if (!extension_ime_util::IsComponentExtensionIME( + unfiltered_input_method_id)) { + // Legacy IMEs or xkb layouts are alwayes enabled. + enabled_input_method_ids_.push_back(unfiltered_input_method_id); + } else if (manager_->component_extension_ime_manager_->IsAllowlisted( + unfiltered_input_method_id)) { + if (manager_->enable_extension_loading_) { + manager_->component_extension_ime_manager_->LoadComponentExtensionIME( + profile, unfiltered_input_method_id, &ext_loaded); + } + + enabled_input_method_ids_.push_back(unfiltered_input_method_id); + } + } } // ------------------------ InputMethodManagerImpl @@ -859,7 +894,8 @@ // Starts or stops the system input method framework as needed. void InputMethodManagerImpl::ReconfigureIMFramework( InputMethodManagerImpl::StateImpl* state) { - LoadNecessaryComponentExtensions(state); + DCHECK(state); + state->LoadNecessaryComponentExtensions(); // Initialize candidate window controller and widgets such as // candidate window, infolist and mode indicator. Note, mode @@ -878,7 +914,7 @@ state_ = new_impl_state; - if (state_.get() && state_->enabled_input_method_ids.size()) { + if (state_.get() && state_->GetNumEnabledInputMethods()) { // Initialize candidate window controller and widgets such as // candidate window, infolist and mode indicator. Note, mode // indicator is used by only keyboard layout input methods. @@ -1052,14 +1088,14 @@ engine->Disable(); // Configure the next engine handler. - // This must be after |current_input_method| has been set to new input + // This must be after |current_input_method_| has been set to new input // method, because engine's Enable() method needs to access it. const std::string& extension_id = extension_ime_util::GetExtensionIDFromInputMethodID( - state_->current_input_method.id()); + state_->GetCurrentInputMethod().id()); const std::string& component_id = extension_ime_util::GetComponentIDByInputMethodID( - state_->current_input_method.id()); + state_->GetCurrentInputMethod().id()); if (!engine_map_.count(state_->profile) || !engine_map_[state_->profile].count(extension_id)) { LOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS()) @@ -1080,9 +1116,9 @@ // Change the keyboard layout to a preferred layout for the input method. if (!keyboard_->SetCurrentKeyboardLayoutByName( - state_->current_input_method.keyboard_layout())) { + state_->GetCurrentInputMethod().keyboard_layout())) { LOG(ERROR) << "Failed to change keyboard layout to " - << state_->current_input_method.keyboard_layout(); + << state_->GetCurrentInputMethod().keyboard_layout(); } // Update input method indicators (e.g. "US", "DV") in Chrome windows. @@ -1092,35 +1128,6 @@ NotifyImeMenuListChanged(); } -void InputMethodManagerImpl::LoadNecessaryComponentExtensions( - InputMethodManagerImpl::StateImpl* state) { - // Load component extensions but also update |enabled_input_method_ids| as - // some component extension IMEs may have been removed from the Chrome OS - // image. If specified component extension IME no longer exists, falling back - // to an existing IME. - DCHECK(state); - TRACE_EVENT0("ime", - "InputMethodManagerImpl::LoadNecessaryComponentExtensions"); - std::vector<std::string> unfiltered_input_method_ids; - unfiltered_input_method_ids.swap(state->enabled_input_method_ids); - std::set<std::string> ext_loaded; - for (const auto& unfiltered_input_method_id : unfiltered_input_method_ids) { - if (!extension_ime_util::IsComponentExtensionIME( - unfiltered_input_method_id)) { - // Legacy IMEs or xkb layouts are alwayes enabled. - state->enabled_input_method_ids.push_back(unfiltered_input_method_id); - } else if (component_extension_ime_manager_->IsAllowlisted( - unfiltered_input_method_id)) { - if (enable_extension_loading_) { - component_extension_ime_manager_->LoadComponentExtensionIME( - state->profile, unfiltered_input_method_id, &ext_loaded); - } - - state->enabled_input_method_ids.push_back(unfiltered_input_method_id); - } - } -} - void InputMethodManagerImpl::ActivateInputMethodMenuItem( const std::string& key) { DCHECK(!key.empty()); @@ -1183,8 +1190,6 @@ scoped_refptr<InputMethodManager::State> InputMethodManagerImpl::CreateNewState( Profile* profile) { - auto* new_state = new StateImpl(this, profile); - // Enabled and current (active) IM should be set to owner/user's default. PrefService* prefs = g_browser_process->local_state(); PrefService* user_prefs = profile ? profile->GetPrefs() : nullptr; @@ -1203,10 +1208,8 @@ initial_input_method_id.empty() ? GetInputMethodUtil()->GetFallbackInputMethodDescriptor().id() : initial_input_method_id); - if (descriptor) { - new_state->enabled_input_method_ids.push_back(descriptor->id()); - new_state->current_input_method = *descriptor; - } + + auto* new_state = new StateImpl(this, profile, descriptor); return scoped_refptr<InputMethodManager::State>(new_state); }
diff --git a/chrome/browser/ash/input_method/input_method_manager_impl.h b/chrome/browser/ash/input_method/input_method_manager_impl.h index 2ba5f73..ce62fb876 100644 --- a/chrome/browser/ash/input_method/input_method_manager_impl.h +++ b/chrome/browser/ash/input_method/input_method_manager_impl.h
@@ -48,26 +48,15 @@ public: class StateImpl : public InputMethodManager::State { public: - StateImpl(InputMethodManagerImpl* manager, Profile* profile); + StateImpl(InputMethodManagerImpl* manager, + Profile* profile, + const InputMethodDescriptor* initial_input_method = nullptr); - // Returns true if (manager_->state_ == this). - bool IsActive() const; - - // Adds new input method to given list if possible - bool EnableInputMethodImpl( - const std::string& input_method_id, - std::vector<std::string>* new_enabled_input_method_ids) const; - - // Returns true if |input_method_id| is in |enabled_input_method_ids|. + // Returns true if |input_method_id| is in |enabled_input_method_ids_|. bool InputMethodIsEnabled(const std::string& input_method_id) const; - // Returns true if given input method requires pending extension. - bool MethodAwaitsExtensionLoad(const std::string& input_method_id) const; - - // Returns whether the input method (or keyboard layout) can be switched - // to the next or previous one. Returns false if only one input method is - // enabled. - bool CanCycleInputMethod() const; + // TODO(nona): Support dynamical unloading. + void LoadNecessaryComponentExtensions(); // InputMethodManager::State overrides. scoped_refptr<InputMethodManager::State> Clone() const override; @@ -122,27 +111,10 @@ // ------------------------- Data members. Profile* const profile; - std::string last_used_input_method_id; - InputMethodDescriptor current_input_method; - - // The enabled input method ids cache. - std::vector<std::string> enabled_input_method_ids; - - // The allowed keyboard layout input methods (e.g. by policy). - std::vector<std::string> allowed_keyboard_layout_input_method_ids; - - // The pending input method id for delayed 3rd party IME enabling. - std::string pending_input_method_id; - - // The list of enabled extension IMEs. - std::vector<std::string> enabled_extension_imes; - // All input methods that have been registered by InputMethodEngines. // The key is the input method ID. std::map<std::string, InputMethodDescriptor> available_input_methods; - InputMethodManagerImpl* const manager_; - // True if the opt-in IME menu is activated. bool menu_activated = false; @@ -151,6 +123,22 @@ ~StateImpl() override; private: + // Returns true if (manager_->state_ == this). + bool IsActive() const; + + // Adds new input method to given list if possible + bool EnableInputMethodImpl( + const std::string& input_method_id, + std::vector<std::string>* new_enabled_input_method_ids) const; + + // Returns true if given input method requires pending extension. + bool MethodAwaitsExtensionLoad(const std::string& input_method_id) const; + + // Returns whether the input method (or keyboard layout) can be switched + // to the next or previous one. Returns false if only one input method is + // enabled. + bool CanCycleInputMethod() const; + // Returns true if the passed input method is allowed. By default, all input // methods are allowed. After SetAllowedKeyboardLayoutInputMethods was // called, the passed keyboard layout input methods are allowed and all @@ -161,13 +149,29 @@ // allowed input method, if no hardware input method is allowed. std::string GetAllowedFallBackKeyboardLayout() const; + InputMethodManagerImpl* const manager_; + + std::string last_used_input_method_id_; + + InputMethodDescriptor current_input_method_; + + std::vector<std::string> enabled_input_method_ids_; + + // The allowed keyboard layout input methods (e.g. by policy). + std::vector<std::string> allowed_keyboard_layout_input_method_ids_; + + // The pending input method id for delayed 3rd party IME enabling. + std::string pending_input_method_id_; + + std::vector<std::string> enabled_extension_imes_; + // The URL of the input view of the current (active) ime with parameters // (e.g. layout, keyset). - GURL input_view_url; + GURL input_view_url_; // Whether the input view URL has been forcibly overridden e.g. to show a // specific keyset. - bool input_view_url_overridden = false; + bool input_view_url_overridden_ = false; InputMethodManager::UIStyle ui_style_ = InputMethodManager::UIStyle::kNormal; @@ -215,20 +219,15 @@ const std::string& extension_id) override; void NotifyInputMethodExtensionRemoved( const std::string& extension_id) override; - ImeKeyboard* GetImeKeyboard() override; InputMethodUtil* GetInputMethodUtil() override; ComponentExtensionIMEManager* GetComponentExtensionIMEManager() override; bool IsLoginKeyboard(const std::string& layout) const override; - bool MigrateInputMethods(std::vector<std::string>* input_method_ids) override; - scoped_refptr<InputMethodManager::State> CreateNewState( Profile* profile) override; - scoped_refptr<InputMethodManager::State> GetActiveIMEState() override; void SetState(scoped_refptr<InputMethodManager::State> state) override; - void ImeMenuActivationChanged(bool is_active) override; // Sets |candidate_window_controller_|. @@ -268,10 +267,6 @@ void ChangeInputMethodInternalFromActiveState(bool show_message, bool notify_menu); - // Loads necessary component extensions. - // TODO(nona): Support dynamical unloading. - void LoadNecessaryComponentExtensions(StateImpl* state); - // Starts or stops the system input method framework as needed. // (after list of enabled input methods has been updated). // If state is active, current (active) input method is updated.
diff --git a/chrome/browser/ash/login/easy_unlock/easy_unlock_service_factory.cc b/chrome/browser/ash/login/easy_unlock/easy_unlock_service_factory.cc index 99f3e70a..71b28da 100644 --- a/chrome/browser/ash/login/easy_unlock/easy_unlock_service_factory.cc +++ b/chrome/browser/ash/login/easy_unlock/easy_unlock_service_factory.cc
@@ -14,7 +14,7 @@ #include "chrome/browser/ash/login/easy_unlock/easy_unlock_tpm_key_manager_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h"
diff --git a/chrome/browser/ash/login/session/user_session_initializer.cc b/chrome/browser/ash/login/session/user_session_initializer.cc index 3193c31f2..99a9cab 100644 --- a/chrome/browser/ash/login/session/user_session_initializer.cc +++ b/chrome/browser/ash/login/session/user_session_initializer.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/ash/crostini/crostini_manager.h" #include "chrome/browser/ash/lock_screen_apps/state_controller.h" #include "chrome/browser/ash/login/startup_utils.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_manager.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_manager_factory.h" #include "chrome/browser/ash/policy/reporting/app_install_event_log_manager_wrapper.h" @@ -31,7 +32,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/chromeos/eche_app/eche_app_manager_factory.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/component_updater/crl_set_component_installer.h" #include "chrome/browser/component_updater/sth_set_component_remover.h" #include "chrome/browser/google/google_brand_chromeos.h"
diff --git a/chrome/browser/chromeos/phonehub/DEPS b/chrome/browser/ash/phonehub/DEPS similarity index 100% rename from chrome/browser/chromeos/phonehub/DEPS rename to chrome/browser/ash/phonehub/DEPS
diff --git a/chrome/browser/chromeos/phonehub/DIR_METADATA b/chrome/browser/ash/phonehub/DIR_METADATA similarity index 100% rename from chrome/browser/chromeos/phonehub/DIR_METADATA rename to chrome/browser/ash/phonehub/DIR_METADATA
diff --git a/chrome/browser/chromeos/phonehub/OWNERS b/chrome/browser/ash/phonehub/OWNERS similarity index 100% rename from chrome/browser/chromeos/phonehub/OWNERS rename to chrome/browser/ash/phonehub/OWNERS
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.cc b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.cc similarity index 96% rename from chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.cc rename to chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.cc index 9e5ad81..ba9ab05a 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.cc +++ b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h" +#include "chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h" #include "base/barrier_closure.h" #include "components/favicon/core/history_ui_favicon_request_handler.h" @@ -10,7 +10,7 @@ #include "components/sync_sessions/synced_session.h" #include "components/ukm/scheme_constants.h" -namespace chromeos { +namespace ash { namespace phonehub { namespace { @@ -118,4 +118,4 @@ } } // namespace phonehub -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h similarity index 85% rename from chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h rename to chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h index c536744..3d72a2a 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h +++ b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_ +#ifndef CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_ +#define CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_ #include "base/memory/weak_ptr.h" #include "chromeos/components/phonehub/browser_tabs_metadata_fetcher.h" +#include "chromeos/components/phonehub/browser_tabs_model.h" namespace favicon_base { struct FaviconImageResult; @@ -16,7 +17,7 @@ class HistoryUiFaviconRequestHandler; } // namespace favicon -namespace chromeos { +namespace ash { namespace phonehub { // BrowserTabsMetadataFetcher implementation. First, a vector containing @@ -53,6 +54,6 @@ }; } // namespace phonehub -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_ +#endif // CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_IMPL_H_
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc similarity index 98% rename from chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc rename to chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc index 2e2e6f2..6863138 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc +++ b/chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h" +#include "chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h" #include <deque> @@ -18,7 +18,7 @@ #include "ui/gfx/favicon_size.h" #include "ui/gfx/image/image_unittest_util.h" -namespace chromeos { +namespace ash { namespace phonehub { namespace { @@ -349,4 +349,4 @@ } } // namespace phonehub -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.cc b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.cc similarity index 97% rename from chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.cc rename to chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.cc index db50733..81853f13 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.cc +++ b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h" +#include "chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h" #include "chromeos/components/multidevice/remote_device_ref.h" #include "chromeos/components/phonehub/browser_tabs_metadata_fetcher.h" @@ -12,7 +12,7 @@ #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "components/sync_sessions/session_sync_service.h" -namespace chromeos { +namespace ash { namespace phonehub { BrowserTabsModelProviderImpl::BrowserTabsModelProviderImpl( @@ -129,4 +129,4 @@ } } // namespace phonehub -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h similarity index 90% rename from chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h rename to chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h index 1566665..a71360d 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h +++ b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_ +#ifndef CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_ +#define CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_ #include <ostream> @@ -21,7 +21,7 @@ class SyncService; } // namespace syncer -namespace chromeos { +namespace ash { namespace phonehub { // Gets the browser tab model info by finding a SyncedSession (provided lazily @@ -75,6 +75,6 @@ }; } // namespace phonehub -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_ +#endif // CHROME_BROWSER_ASH_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_IMPL_H_
diff --git a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl_unittest.cc b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl_unittest.cc similarity index 94% rename from chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl_unittest.cc rename to chrome/browser/ash/phonehub/browser_tabs_model_provider_impl_unittest.cc index 133496e..116a97a0 100644 --- a/chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl_unittest.cc +++ b/chrome/browser/ash/phonehub/browser_tabs_model_provider_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h" +#include "chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h" #include "chromeos/components/multidevice/remote_device_test_util.h" #include "chromeos/components/phonehub/fake_browser_tabs_metadata_fetcher.h" @@ -15,14 +15,19 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { +namespace ash { namespace phonehub { -using testing::_; -using testing::Return; - namespace { +// TODO(https://crbug.com/1164001): remove after chromeos/components/phonehub is +// migrated. +using ::chromeos::phonehub::CreateFakeBrowserTabMetadata; +using ::chromeos::phonehub::FakeBrowserTabsMetadataFetcher; +using ::chromeos::phonehub::MutablePhoneModel; + +using ::testing::_; + const char kPhoneNameOne[] = "Pixel"; const char kPhoneNameTwo[] = "Galaxy"; @@ -126,9 +131,10 @@ } void SetPiiFreeName(const std::string& pii_free_name) { - fake_multidevice_setup_client_.SetHostStatusWithDevice(std::make_pair( - multidevice_setup::mojom::HostStatus::kEligibleHostExistsButNoHostSet, - CreatePhoneDevice(/*pii_name=*/pii_free_name))); + fake_multidevice_setup_client_.SetHostStatusWithDevice( + std::make_pair(chromeos::multidevice_setup::mojom::HostStatus:: + kEligibleHostExistsButNoHostSet, + CreatePhoneDevice(/*pii_name=*/pii_free_name))); } base::CallbackListSubscription MockSubscribeToForeignSessionsChanged( @@ -289,4 +295,4 @@ } } // namespace phonehub -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/phonehub/phone_hub_manager_factory.cc b/chrome/browser/ash/phonehub/phone_hub_manager_factory.cc similarity index 85% rename from chrome/browser/chromeos/phonehub/phone_hub_manager_factory.cc rename to chrome/browser/ash/phonehub/phone_hub_manager_factory.cc index 717d4a8..64b83f1 100644 --- a/chrome/browser/chromeos/phonehub/phone_hub_manager_factory.cc +++ b/chrome/browser/ash/phonehub/phone_hub_manager_factory.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/system_tray.h" #include "chrome/browser/ash/device_sync/device_sync_client_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" +#include "chrome/browser/ash/phonehub/browser_tabs_metadata_fetcher_impl.h" +#include "chrome/browser/ash/phonehub/browser_tabs_model_provider_impl.h" #include "chrome/browser/ash/profiles/profile_helper.h" -#include "chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h" -#include "chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connector_factory.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_factory.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/session_sync_service_factory.h" @@ -28,15 +28,24 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" -namespace chromeos { +namespace ash { namespace phonehub { namespace { +// TODO(https://crbug.com/1164001): remove after chromeos/components/phonehub is +// migrated. +using ::chromeos::phonehub::MultideviceSetupStateUpdater; +using ::chromeos::phonehub::NotificationAccessManagerImpl; +using ::chromeos::phonehub::OnboardingUiTrackerImpl; +using ::chromeos::phonehub::PhoneHubManagerImpl; +using ::chromeos::phonehub::ScreenLockManagerImpl; + content::BrowserContext* g_context_for_service = nullptr; bool IsProhibitedByPolicy(Profile* profile) { return !multidevice_setup::IsFeatureAllowed( - multidevice_setup::mojom::Feature::kPhoneHub, profile->GetPrefs()); + chromeos::multidevice_setup::mojom::Feature::kPhoneHub, + profile->GetPrefs()); } bool IsLoggedInAsPrimaryUser(Profile* profile) { @@ -110,7 +119,7 @@ // Provide |phone_hub_manager| to the system tray so that it can be used by // the UI. - ash::SystemTray::Get()->SetPhoneHubManager(phone_hub_manager); + SystemTray::Get()->SetPhoneHubManager(phone_hub_manager); DCHECK(!g_context_for_service); g_context_for_service = context; @@ -138,7 +147,7 @@ // expected to be deleted *before* the Profile, so this check is only expected // to be necessary in tests. if (g_context_for_service == context) { - ash::SystemTray* system_tray = ash::SystemTray::Get(); + auto* system_tray = SystemTray::Get(); if (system_tray) system_tray->SetPhoneHubManager(nullptr); @@ -157,4 +166,4 @@ } } // namespace phonehub -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h b/chrome/browser/ash/phonehub/phone_hub_manager_factory.h similarity index 81% rename from chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h rename to chrome/browser/ash/phonehub/phone_hub_manager_factory.h index cf761ef1..79dbef0 100644 --- a/chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h +++ b/chrome/browser/ash/phonehub/phone_hub_manager_factory.h
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_ -#define CHROME_BROWSER_CHROMEOS_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_ +#ifndef CHROME_BROWSER_ASH_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_ +#define CHROME_BROWSER_ASH_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_ #include "base/memory/singleton.h" +// TODO(https://crbug.com/1164001): move to forward declaration. +#include "chromeos/components/phonehub/phone_hub_manager.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" class Profile; -namespace chromeos { +namespace ash { namespace phonehub { -class PhoneHubManager; - class PhoneHubManagerFactory : public BrowserContextKeyedServiceFactory { public: // Returns the PhoneHubManager instance associated with |profile|. Null is @@ -43,14 +43,14 @@ }; } // namespace phonehub -} // namespace chromeos +} // namespace ash // TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos // source migration is finished. -namespace ash { +namespace chromeos { namespace phonehub { -using ::chromeos::phonehub::PhoneHubManagerFactory; +using ::ash::phonehub::PhoneHubManagerFactory; } -} // namespace ash +} // namespace chromeos -#endif // CHROME_BROWSER_CHROMEOS_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_ +#endif // CHROME_BROWSER_ASH_PHONEHUB_PHONE_HUB_MANAGER_FACTORY_H_
diff --git a/chrome/browser/ash/policy/dlp/clipboard_bubble.cc b/chrome/browser/ash/policy/dlp/clipboard_bubble.cc index f0f5eb6..5d09e8a8 100644 --- a/chrome/browser/ash/policy/dlp/clipboard_bubble.cc +++ b/chrome/browser/ash/policy/dlp/clipboard_bubble.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ash/policy/dlp/clipboard_bubble.h" #include "ash/constants/ash_features.h" +#include "ash/public/cpp/new_window_delegate.h" #include "ash/public/cpp/style/color_provider.h" #include "chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h" #include "components/strings/grit/components_strings.h" @@ -16,6 +17,7 @@ #include "ui/gfx/text_utils.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/button/label_button.h" +#include "ui/views/controls/link.h" namespace policy { @@ -96,6 +98,11 @@ } }; +void OnLearnMoreLinkClicked() { + ash::NewWindowDelegate::GetInstance()->OpenUrl( + GURL(kDlpLearnMoreUrl), /*from_user_interaction=*/true); +} + } // namespace BEGIN_METADATA(Button, views::LabelButton) @@ -143,6 +150,25 @@ label_->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); label_->SetAutoColorReadabilityEnabled(false); + // Add "Learn more" link. + // TODO(crbug.com/1252779): Move it to continue the label text, not below it. + link_ = AddChildView( + std::make_unique<views::Link>(l10n_util::GetStringUTF16(IDS_LEARN_MORE))); + link_->SetPaintToLayer(); + link_->layer()->SetFillsBoundsOpaquely(false); + link_->SetPosition( + gfx::Point(kBubblePadding + kManagedIconSize + kIconLabelSpacing, + kBubblePadding + label_->height())); + link_->SetFontList(gfx::FontList({kTextFontName}, gfx::Font::NORMAL, + kTextFontSize, gfx::Font::Weight::NORMAL)); + link_->SetLineHeight(kLineHeight); + link_->SetMultiLine(true); + link_->SizeToFit(kBubbleWidth - 2 * kBubblePadding - kManagedIconSize - + kIconLabelSpacing); + link_->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); + link_->SetAutoColorReadabilityEnabled(false); + link_->SetCallback(base::BindRepeating(&OnLearnMoreLinkClicked)); + // Bubble borders border_ = AddChildView(std::make_unique<views::ImageView>()); border_->SetPaintToLayer(); @@ -155,6 +181,7 @@ shadow_border->set_insets(kBubbleBorderInsets); border_->SetSize({kBubbleWidth, INT_MAX}); border_->SetBorder(std::move(shadow_border)); + border_->SetCanProcessEventsWithinSubtree(false); } ClipboardBubbleView::~ClipboardBubbleView() = default;
diff --git a/chrome/browser/ash/policy/dlp/clipboard_bubble.h b/chrome/browser/ash/policy/dlp/clipboard_bubble.h index 86f51522..a1906af 100644 --- a/chrome/browser/ash/policy/dlp/clipboard_bubble.h +++ b/chrome/browser/ash/policy/dlp/clipboard_bubble.h
@@ -13,9 +13,10 @@ #include "ui/views/view.h" namespace views { -class Label; class ImageView; +class Label; class LabelButton; +class Link; } // namespace views namespace policy { @@ -37,6 +38,7 @@ views::Label* label_ = nullptr; views::ImageView* managed_icon_ = nullptr; views::ImageView* border_ = nullptr; + views::Link* link_ = nullptr; }; class ClipboardBlockBubble : public ClipboardBubbleView {
diff --git a/chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h b/chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h index db100298..185cec4 100644 --- a/chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h +++ b/chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h
@@ -36,6 +36,10 @@ // The duration of the clipboard warning shown before paste. constexpr int kClipboardDlpWarnDurationMs = 16000; +// Link to the Help Center article about Data Leak Prevention. +constexpr char kDlpLearnMoreUrl[] = + "https://support.google.com/chrome/a/?p=chromeos_datacontrols"; + } // namespace policy #endif // CHROME_BROWSER_ASH_POLICY_DLP_DLP_CLIPBOARD_BUBBLE_CONSTANTS_H_
diff --git a/chrome/browser/ash/policy/dlp/dlp_content_manager.cc b/chrome/browser/ash/policy/dlp/dlp_content_manager.cc index b161c18..67caf12 100644 --- a/chrome/browser/ash/policy/dlp/dlp_content_manager.cc +++ b/chrome/browser/ash/policy/dlp/dlp_content_manager.cc
@@ -55,6 +55,22 @@ reporting_manager->ReportEvent(src_url, restriction, level); } +// Helper method to check whether the restriction level is kBlock +bool IsBlocked(RestrictionLevelAndUrl restriction_info) { + return restriction_info.level == DlpRulesManager::Level::kBlock; +} + +// Helper method to check whether the restriction level is kWarn +bool IsWarn(RestrictionLevelAndUrl restriction_info) { + return restriction_info.level == DlpRulesManager::Level::kWarn; +} + +// Helper method to check if event should be reported +bool IsReported(RestrictionLevelAndUrl restriction_info) { + return restriction_info.level == DlpRulesManager::Level::kReport || + IsBlocked(restriction_info); +} + } // namespace static DlpContentManager* g_dlp_content_manager = nullptr; @@ -89,51 +105,46 @@ const ScreenshotArea& area) const { RestrictionLevelAndUrl restriction_info = GetAreaRestrictionInfo(area, DlpContentRestriction::kScreenshot); - const bool is_blocked = - restriction_info.level == DlpRulesManager::Level::kBlock; - if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + if (IsReported(restriction_info)) { SYSLOG(INFO) << "DLP blocked taking a screenshot"; if (reporting_manager_) ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kScreenshot, restriction_info.level, reporting_manager_); } - DlpBooleanHistogram(dlp::kScreenshotBlockedUMA, is_blocked); - return is_blocked; + DlpBooleanHistogram(dlp::kScreenshotBlockedUMA, IsBlocked(restriction_info)); + return IsBlocked(restriction_info); } bool DlpContentManager::IsVideoCaptureRestricted( const ScreenshotArea& area) const { RestrictionLevelAndUrl restriction_info = GetAreaRestrictionInfo(area, DlpContentRestriction::kVideoCapture); - const bool is_blocked = - restriction_info.level == DlpRulesManager::Level::kBlock; - if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + if (IsReported(restriction_info)) { SYSLOG(INFO) << "DLP blocked taking a video capture"; if (reporting_manager_) ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kScreenshot, restriction_info.level, reporting_manager_); } - DlpBooleanHistogram(dlp::kVideoCaptureBlockedUMA, is_blocked); - return is_blocked; + DlpBooleanHistogram(dlp::kVideoCaptureBlockedUMA, + IsBlocked(restriction_info)); + return IsBlocked(restriction_info); } bool DlpContentManager::IsPrintingRestricted( content::WebContents* web_contents) const { RestrictionLevelAndUrl restriction_info = GetPrintingRestrictionInfo(web_contents); - const bool is_blocked = - restriction_info.level == DlpRulesManager::Level::kBlock; - DlpBooleanHistogram(dlp::kPrintingBlockedUMA, is_blocked); - if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + DlpBooleanHistogram(dlp::kPrintingBlockedUMA, IsBlocked(restriction_info)); + if (IsReported(restriction_info)) { SYSLOG(INFO) << "DLP blocked printing"; if (reporting_manager_) ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kPrinting, restriction_info.level, reporting_manager_); } - return is_blocked; + return IsBlocked(restriction_info); } bool DlpContentManager::ShouldWarnBeforePrinting( @@ -141,24 +152,22 @@ RestrictionLevelAndUrl restriction_info = GetPrintingRestrictionInfo(web_contents); // TODO(crbug.com/1227700): Add reporting and metrics for WARN - return restriction_info.level == DlpRulesManager::Level::kWarn; + return IsWarn(restriction_info); } bool DlpContentManager::IsScreenCaptureRestricted( const content::DesktopMediaID& media_id) const { RestrictionLevelAndUrl restriction_info = GetScreenCaptureRestrictionInfo(media_id); - const bool is_blocked = - restriction_info.level == DlpRulesManager::Level::kBlock; - if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + if (IsReported(restriction_info)) { SYSLOG(INFO) << "DLP blocked screen sharing"; if (reporting_manager_) ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kScreenShare, restriction_info.level, reporting_manager_); } - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, is_blocked); - return is_blocked; + DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, IsBlocked(restriction_info)); + return IsBlocked(restriction_info); } void DlpContentManager::OnVideoCaptureStarted(const ScreenshotArea& area) { @@ -185,17 +194,16 @@ screenshot_restriction_info.level >= videocapture_restriction_info.level ? screenshot_restriction_info : videocapture_restriction_info; - const bool is_blocked = - restriction_info.level == DlpRulesManager::Level::kBlock; - if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + if (IsReported(restriction_info)) { SYSLOG(INFO) << "DLP blocked taking a screen capture"; if (reporting_manager_) ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kScreenshot, restriction_info.level, reporting_manager_); } - DlpBooleanHistogram(dlp::kCaptureModeInitBlockedUMA, is_blocked); - return is_blocked; + DlpBooleanHistogram(dlp::kCaptureModeInitBlockedUMA, + IsBlocked(restriction_info)); + return IsBlocked(restriction_info); } void DlpContentManager::OnScreenCaptureStarted( @@ -574,10 +582,7 @@ GetScreenCaptureRestrictionInfo(capture.media_id); const bool is_allowed = restriction_info.level != DlpRulesManager::Level::kBlock; - const bool is_reported = - restriction_info.level == DlpRulesManager::Level::kBlock || - restriction_info.level == DlpRulesManager::Level::kReport; - if (is_reported && capture.is_running) { + if (IsReported(restriction_info) && capture.is_running) { SYSLOG(INFO) << "DLP " << (is_allowed ? "resumed" : "paused") << " running screen share"; if (reporting_manager_) {
diff --git a/chrome/browser/ash/policy/dlp/dlp_notification_helper.cc b/chrome/browser/ash/policy/dlp/dlp_notification_helper.cc index 17c823e3..b24269ee 100644 --- a/chrome/browser/ash/policy/dlp/dlp_notification_helper.cc +++ b/chrome/browser/ash/policy/dlp/dlp_notification_helper.cc
@@ -4,7 +4,9 @@ #include "chrome/browser/ash/policy/dlp/dlp_notification_helper.h" +#include "ash/public/cpp/new_window_delegate.h" #include "ash/public/cpp/notification_utils.h" +#include "chrome/browser/ash/policy/dlp/dlp_clipboard_bubble_constants.h" #include "chrome/browser/ash/policy/dlp/dlp_warn_dialog.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/profiles/profile.h" @@ -31,6 +33,15 @@ "screen_capture_dlp_resumed-"; constexpr char kDlpPolicyNotifierId[] = "policy.dlp"; +void OnNotificationClicked(const std::string id) { + ash::NewWindowDelegate::GetInstance()->OpenUrl( + GURL(kDlpLearnMoreUrl), /*from_user_interaction=*/true); + + NotificationDisplayService::GetForProfile( + ProfileManager::GetActiveUserProfile()) + ->Close(NotificationHandler::Type::TRANSIENT, id); +} + void ShowDlpNotification(const std::string& id, const std::u16string& title, const std::u16string& message) { @@ -42,7 +53,8 @@ message_center::NotifierType::SYSTEM_COMPONENT, kDlpPolicyNotifierId), message_center::RichNotificationData(), - base::MakeRefCounted<message_center::NotificationDelegate>(), + base::MakeRefCounted<message_center::HandleNotificationClickDelegate>( + base::BindRepeating(&OnNotificationClicked, id)), vector_icons::kBusinessIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); notification->set_renotify(true);
diff --git a/chrome/browser/ash/policy/remote_commands/crd_host_delegate.cc b/chrome/browser/ash/policy/remote_commands/crd_host_delegate.cc index b88e54ff..21ccd28 100644 --- a/chrome/browser/ash/policy/remote_commands/crd_host_delegate.cc +++ b/chrome/browser/ash/policy/remote_commands/crd_host_delegate.cc
@@ -16,9 +16,9 @@ namespace policy { -using ResultCode = DeviceCommandStartCRDSessionJob::ResultCode; -using AccessCodeCallback = DeviceCommandStartCRDSessionJob::AccessCodeCallback; -using ErrorCallback = DeviceCommandStartCRDSessionJob::ErrorCallback; +using ResultCode = DeviceCommandStartCrdSessionJob::ResultCode; +using AccessCodeCallback = DeviceCommandStartCrdSessionJob::AccessCodeCallback; +using ErrorCallback = DeviceCommandStartCrdSessionJob::ErrorCallback; namespace { @@ -186,7 +186,7 @@ std::move(callback).Run(); } -void CrdHostDelegate::StartCRDHostAndGetCode( +void CrdHostDelegate::StartCrdHostAndGetCode( const SessionParameters& parameters, AccessCodeCallback success_callback, ErrorCallback error_callback) {
diff --git a/chrome/browser/ash/policy/remote_commands/crd_host_delegate.h b/chrome/browser/ash/policy/remote_commands/crd_host_delegate.h index 5b1c113..0ac0d034 100644 --- a/chrome/browser/ash/policy/remote_commands/crd_host_delegate.h +++ b/chrome/browser/ash/policy/remote_commands/crd_host_delegate.h
@@ -18,7 +18,7 @@ // Delegate that will start a session with the CRD native host. // Will keep the session alive and active as long as this class lives. // Deleting this class object will forcefully interrupt the active CRD session. -class CrdHostDelegate : public DeviceCommandStartCRDSessionJob::Delegate { +class CrdHostDelegate : public DeviceCommandStartCrdSessionJob::Delegate { public: // Proxy class to establish a connection with the Remoting service. // Overwritten in unittests to inject a test service. @@ -44,13 +44,13 @@ CrdHostDelegate& operator=(const CrdHostDelegate&) = delete; ~CrdHostDelegate() override; - // DeviceCommandStartCRDSessionJob::Delegate implementation: + // DeviceCommandStartCrdSessionJob::Delegate implementation: bool HasActiveSession() const override; void TerminateSession(base::OnceClosure callback) override; - void StartCRDHostAndGetCode( + void StartCrdHostAndGetCode( const SessionParameters& parameters, - DeviceCommandStartCRDSessionJob::AccessCodeCallback success_callback, - DeviceCommandStartCRDSessionJob::ErrorCallback error_callback) override; + DeviceCommandStartCrdSessionJob::AccessCodeCallback success_callback, + DeviceCommandStartCrdSessionJob::ErrorCallback error_callback) override; private: class CrdHostSession;
diff --git a/chrome/browser/ash/policy/remote_commands/crd_host_delegate_unittest.cc b/chrome/browser/ash/policy/remote_commands/crd_host_delegate_unittest.cc index bd377123..2487e85c 100644 --- a/chrome/browser/ash/policy/remote_commands/crd_host_delegate_unittest.cc +++ b/chrome/browser/ash/policy/remote_commands/crd_host_delegate_unittest.cc
@@ -22,7 +22,7 @@ namespace { using SessionParameters = - DeviceCommandStartCRDSessionJob::Delegate::SessionParameters; + DeviceCommandStartCrdSessionJob::Delegate::SessionParameters; using StartSupportSessionCallback = crosapi::mojom::Remoting::StartSupportSessionCallback; using remoting::mojom::StartSupportSessionResponse; @@ -118,7 +118,7 @@ return Response(access_code); } - static Response Error(DeviceCommandStartCRDSessionJob::ResultCode error_code, + static Response Error(DeviceCommandStartCrdSessionJob::ResultCode error_code, const std::string& error_message) { return Response(error_code, error_message); } @@ -134,9 +134,9 @@ return error_message_.value_or("<no error received>"); } - DeviceCommandStartCRDSessionJob::ResultCode error_code() const { + DeviceCommandStartCrdSessionJob::ResultCode error_code() const { return error_code_.value_or( - DeviceCommandStartCRDSessionJob::ResultCode::SUCCESS); + DeviceCommandStartCrdSessionJob::ResultCode::SUCCESS); } std::string access_code() const { @@ -146,12 +146,12 @@ private: explicit Response(const std::string& access_code) : access_code_(access_code) {} - Response(DeviceCommandStartCRDSessionJob::ResultCode error_code, + Response(DeviceCommandStartCrdSessionJob::ResultCode error_code, const std::string& error_message) : error_code_(error_code), error_message_(error_message) {} absl::optional<std::string> access_code_; - absl::optional<DeviceCommandStartCRDSessionJob::ResultCode> error_code_; + absl::optional<DeviceCommandStartCrdSessionJob::ResultCode> error_code_; absl::optional<std::string> error_message_; }; @@ -179,7 +179,7 @@ auto error_callback() { return base::BindOnce( [](base::OnceCallback<void(Response)> setter, - DeviceCommandStartCRDSessionJob::ResultCode error_code, + DeviceCommandStartCrdSessionJob::ResultCode error_code, const std::string& error_message) { std::move(setter).Run(Response::Error(error_code, error_message)); }, @@ -190,7 +190,7 @@ // and return the response. Response WaitForResponse() { return result_.Take(); } - // Call delegate().StartCRDHostAndGetCode() and wait until the + // Call delegate().StartCrdHostAndGetCode() and wait until the // |SupportHostObserver| is bound. // This observer is used by the CRD host code to inform our delegate of status // updates, and is returned by this method so we can spoof these status @@ -206,7 +206,7 @@ std::move(callback).Run(std::move(response)); }); - delegate().StartCRDHostAndGetCode(SessionParameters{}, success_callback(), + delegate().StartCrdHostAndGetCode(SessionParameters{}, success_callback(), error_callback()); EXPECT_TRUE(observer_.is_bound()) << "StartSession() was not called"; @@ -233,7 +233,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); ASSERT_FALSE(actual_parameters.is_null()); @@ -248,7 +248,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); ASSERT_FALSE(actual_parameters.is_null()); @@ -264,7 +264,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); EXPECT_EQ(actual_parameters.suppress_notifications, false); @@ -280,7 +280,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); EXPECT_EQ(actual_parameters.suppress_notifications, true); @@ -296,7 +296,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); EXPECT_EQ(actual_parameters.terminate_upon_input, false); @@ -310,7 +310,7 @@ EXPECT_CALL(remoting_service(), StartSession) .WillOnce(SaveParamAndInvokeCallback(&actual_parameters)); - delegate().StartCRDHostAndGetCode(parameters, success_callback(), + delegate().StartCrdHostAndGetCode(parameters, success_callback(), error_callback()); EXPECT_EQ(actual_parameters.terminate_upon_input, true); @@ -326,12 +326,12 @@ std::move(callback).Run(std::move(response)); }); - delegate().StartCRDHostAndGetCode(SessionParameters{}, success_callback(), + delegate().StartCrdHostAndGetCode(SessionParameters{}, success_callback(), error_callback()); Response response = WaitForResponse(); ASSERT_TRUE(response.HasError()); - EXPECT_EQ(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + EXPECT_EQ(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, response.error_code()); } @@ -355,7 +355,7 @@ Response response = WaitForResponse(); ASSERT_TRUE(response.HasError()); EXPECT_EQ("host disconnected", response.error_message()); - EXPECT_EQ(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + EXPECT_EQ(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, response.error_code()); } @@ -368,7 +368,7 @@ Response response = WaitForResponse(); ASSERT_TRUE(response.HasError()); EXPECT_EQ("policy error", response.error_message()); - EXPECT_EQ(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + EXPECT_EQ(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, response.error_code()); } @@ -381,7 +381,7 @@ Response response = WaitForResponse(); ASSERT_TRUE(response.HasError()); EXPECT_EQ("invalid domain error", response.error_message()); - EXPECT_EQ(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + EXPECT_EQ(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, response.error_code()); } @@ -394,21 +394,21 @@ Response response = WaitForResponse(); ASSERT_TRUE(response.HasError()); EXPECT_EQ("host state error", response.error_message()); - EXPECT_EQ(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + EXPECT_EQ(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, response.error_code()); } TEST_F(CrdHostDelegateTest, HasActiveSessionShouldBeTrueWhenASessionIsStarted) { EXPECT_FALSE(delegate().HasActiveSession()); - delegate().StartCRDHostAndGetCode(SessionParameters{}, success_callback(), + delegate().StartCrdHostAndGetCode(SessionParameters{}, success_callback(), error_callback()); EXPECT_TRUE(delegate().HasActiveSession()); } TEST_F(CrdHostDelegateTest, TerminateSessionShouldTerminateTheActiveSession) { - delegate().StartCRDHostAndGetCode(SessionParameters{}, success_callback(), + delegate().StartCrdHostAndGetCode(SessionParameters{}, success_callback(), error_callback()); EXPECT_TRUE(delegate().HasActiveSession());
diff --git a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.cc b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.cc index 2d8cea7..76bd544 100644 --- a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.cc +++ b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.cc
@@ -57,7 +57,7 @@ // Result payload fields: -// Integer value containing DeviceCommandStartCRDSessionJob::ResultCode +// Integer value containing DeviceCommandStartCrdSessionJob::ResultCode const char kResultCodeFieldName[] = "resultCode"; // CRD Access Code if job was completed successfully @@ -86,7 +86,7 @@ // Helper class that asynchronously fetches the OAuth token, and passes it to // the given callback. -class DeviceCommandStartCRDSessionJob::OAuthTokenFetcher +class DeviceCommandStartCrdSessionJob::OAuthTokenFetcher : public OAuth2AccessTokenManager::Consumer { public: OAuthTokenFetcher(DeviceOAuth2TokenService& oauth_service, @@ -133,20 +133,20 @@ CRD_DVLOG(1) << "Failed to get OAuth access token: " << error.ToString(); oauth_request_.reset(); std::move(error_callback_) - .Run(DeviceCommandStartCRDSessionJob::FAILURE_NO_OAUTH_TOKEN, + .Run(DeviceCommandStartCrdSessionJob::FAILURE_NO_OAUTH_TOKEN, error.ToString()); } DeviceOAuth2TokenService& oauth_service_; absl::optional<std::string> oauth_token_for_test_; - DeviceCommandStartCRDSessionJob::OAuthTokenCallback success_callback_; - DeviceCommandStartCRDSessionJob::ErrorCallback error_callback_; + DeviceCommandStartCrdSessionJob::OAuthTokenCallback success_callback_; + DeviceCommandStartCrdSessionJob::ErrorCallback error_callback_; // Handler for the OAuth access token request. // When deleted the token manager will cancel the request (and not call us). std::unique_ptr<OAuth2AccessTokenManager::Request> oauth_request_; }; -class DeviceCommandStartCRDSessionJob::ResultPayload +class DeviceCommandStartCrdSessionJob::ResultPayload : public RemoteCommandJob::ResultPayload { public: ResultPayload(ResultCode result_code, @@ -170,7 +170,7 @@ std::string payload_; }; -DeviceCommandStartCRDSessionJob::ResultPayload::ResultPayload( +DeviceCommandStartCrdSessionJob::ResultPayload::ResultPayload( ResultCode result_code, const absl::optional<std::string>& access_code, const absl::optional<base::TimeDelta>& time_delta, @@ -188,24 +188,24 @@ base::JSONWriter::Write(value, &payload_); } -std::unique_ptr<DeviceCommandStartCRDSessionJob::ResultPayload> -DeviceCommandStartCRDSessionJob::ResultPayload::CreateSuccessPayload( +std::unique_ptr<DeviceCommandStartCrdSessionJob::ResultPayload> +DeviceCommandStartCrdSessionJob::ResultPayload::CreateSuccessPayload( const std::string& access_code) { return std::make_unique<ResultPayload>(ResultCode::SUCCESS, access_code, /*time_delta=*/absl::nullopt, /*error_message=*/absl::nullopt); } -std::unique_ptr<DeviceCommandStartCRDSessionJob::ResultPayload> -DeviceCommandStartCRDSessionJob::ResultPayload::CreateNonIdlePayload( +std::unique_ptr<DeviceCommandStartCrdSessionJob::ResultPayload> +DeviceCommandStartCrdSessionJob::ResultPayload::CreateNonIdlePayload( const base::TimeDelta& time_delta) { return std::make_unique<ResultPayload>( ResultCode::FAILURE_NOT_IDLE, /*access_code=*/absl::nullopt, time_delta, /*error_message/*/ absl::nullopt); } -std::unique_ptr<DeviceCommandStartCRDSessionJob::ResultPayload> -DeviceCommandStartCRDSessionJob::ResultPayload::CreateErrorPayload( +std::unique_ptr<DeviceCommandStartCrdSessionJob::ResultPayload> +DeviceCommandStartCrdSessionJob::ResultPayload::CreateErrorPayload( ResultCode result_code, const std::string& error_message) { DCHECK(result_code != ResultCode::SUCCESS); @@ -216,29 +216,29 @@ } std::unique_ptr<std::string> -DeviceCommandStartCRDSessionJob::ResultPayload::Serialize() { +DeviceCommandStartCrdSessionJob::ResultPayload::Serialize() { return std::make_unique<std::string>(payload_); } -DeviceCommandStartCRDSessionJob::DeviceCommandStartCRDSessionJob( +DeviceCommandStartCrdSessionJob::DeviceCommandStartCrdSessionJob( Delegate* crd_host_delegate) : delegate_(crd_host_delegate) { DCHECK(crd_host_delegate); } -DeviceCommandStartCRDSessionJob::~DeviceCommandStartCRDSessionJob() = default; +DeviceCommandStartCrdSessionJob::~DeviceCommandStartCrdSessionJob() = default; enterprise_management::RemoteCommand_Type -DeviceCommandStartCRDSessionJob::GetType() const { +DeviceCommandStartCrdSessionJob::GetType() const { return enterprise_management::RemoteCommand_Type_DEVICE_START_CRD_SESSION; } -void DeviceCommandStartCRDSessionJob::SetOAuthTokenForTest( +void DeviceCommandStartCrdSessionJob::SetOAuthTokenForTest( const std::string& token) { oauth_token_for_test_ = token; } -bool DeviceCommandStartCRDSessionJob::ParseCommandPayload( +bool DeviceCommandStartCrdSessionJob::ParseCommandPayload( const std::string& command_payload) { absl::optional<base::Value> root(base::JSONReader::Read(command_payload)); if (!root) @@ -260,18 +260,18 @@ return true; } -bool DeviceCommandStartCRDSessionJob::AreServicesReady() const { +bool DeviceCommandStartCrdSessionJob::AreServicesReady() const { return user_manager::UserManager::IsInitialized() && ui::UserActivityDetector::Get() != nullptr && oauth_service() != nullptr; } -bool DeviceCommandStartCRDSessionJob::UserTypeSupportsCRD() const { +bool DeviceCommandStartCrdSessionJob::UserTypeSupportsCrd() const { const UserType current_user_type = GetUserType(); CRD_DVLOG(2) << "User is of type " << UserTypeToString(current_user_type); - if (base::FeatureList::IsEnabled(features::kCRDForManagedUserSessions)) { + if (base::FeatureList::IsEnabled(features::kCrdForManagedUserSessions)) { switch (current_user_type) { case UserType::kAffiliatedUser: case UserType::kAutoLaunchedKiosk: @@ -289,8 +289,8 @@ } } -DeviceCommandStartCRDSessionJob::UserType -DeviceCommandStartCRDSessionJob::GetUserType() const { +DeviceCommandStartCrdSessionJob::UserType +DeviceCommandStartCrdSessionJob::GetUserType() const { const auto* user_manager = user_manager::UserManager::Get(); if (!user_manager->IsUserLoggedIn()) @@ -312,7 +312,7 @@ return UserType::kOther; } -bool DeviceCommandStartCRDSessionJob::IsRunningAutoLaunchedKiosk() const { +bool DeviceCommandStartCrdSessionJob::IsRunningAutoLaunchedKiosk() const { const auto* user_manager = user_manager::UserManager::Get(); const auto* kiosk_app_manager = GetKioskAppManagerIfKioskAppIsRunning(user_manager); @@ -322,17 +322,17 @@ return kiosk_app_manager->current_app_was_auto_launched_with_zero_delay(); } -bool DeviceCommandStartCRDSessionJob::IsDeviceIdle() const { +bool DeviceCommandStartCrdSessionJob::IsDeviceIdle() const { return GetDeviceIdlenessPeriod() >= idleness_cutoff_; } -base::TimeDelta DeviceCommandStartCRDSessionJob::GetDeviceIdlenessPeriod() +base::TimeDelta DeviceCommandStartCrdSessionJob::GetDeviceIdlenessPeriod() const { return base::TimeTicks::Now() - ui::UserActivityDetector::Get()->last_activity_time(); } -void DeviceCommandStartCRDSessionJob::FetchOAuthTokenASync( +void DeviceCommandStartCrdSessionJob::FetchOAuthTokenASync( OAuthTokenCallback on_success, ErrorCallback on_error) { DCHECK(!oauth_token_fetcher_ || !oauth_token_fetcher_->is_running()); @@ -344,7 +344,7 @@ oauth_token_fetcher_->Start(); } -void DeviceCommandStartCRDSessionJob::FinishWithError( +void DeviceCommandStartCrdSessionJob::FinishWithError( const ResultCode result_code, const std::string& message) { CRD_LOG(INFO) << "Not starting CRD session because of error (code " @@ -358,7 +358,7 @@ ResultPayload::CreateErrorPayload(result_code, message))); } -void DeviceCommandStartCRDSessionJob::FinishWithNotIdleError() { +void DeviceCommandStartCrdSessionJob::FinishWithNotIdleError() { CRD_LOG(INFO) << "Not starting CRD session because device is not idle"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(failed_callback_), @@ -366,7 +366,7 @@ GetDeviceIdlenessPeriod()))); } -void DeviceCommandStartCRDSessionJob::RunImpl( +void DeviceCommandStartCrdSessionJob::RunImpl( CallbackWithResult succeeded_callback, CallbackWithResult failed_callback) { CRD_LOG(INFO) << "Running start CRD session command"; @@ -377,7 +377,7 @@ CRD_DVLOG(1) << "Terminating active session"; delegate_->TerminateSession(base::BindOnce( - &DeviceCommandStartCRDSessionJob::RunImpl, weak_factory_.GetWeakPtr(), + &DeviceCommandStartCrdSessionJob::RunImpl, weak_factory_.GetWeakPtr(), std::move(succeeded_callback), std::move(failed_callback))); return; } @@ -391,7 +391,7 @@ return; } - if (!UserTypeSupportsCRD()) { + if (!UserTypeSupportsCrd()) { FinishWithError(ResultCode::FAILURE_UNSUPPORTED_USER_TYPE, ""); return; } @@ -403,14 +403,14 @@ FetchOAuthTokenASync( /*on_success=*/base::BindOnce( - &DeviceCommandStartCRDSessionJob::OnOAuthTokenReceived, + &DeviceCommandStartCrdSessionJob::OnOAuthTokenReceived, weak_factory_.GetWeakPtr()), /*on_error=*/base::BindOnce( - &DeviceCommandStartCRDSessionJob::FinishWithError, + &DeviceCommandStartCrdSessionJob::FinishWithError, weak_factory_.GetWeakPtr())); } -void DeviceCommandStartCRDSessionJob::OnOAuthTokenReceived( +void DeviceCommandStartCrdSessionJob::OnOAuthTokenReceived( const std::string& token) { CRD_DVLOG(1) << "Received OAuth token, now retrieving CRD access code"; Delegate::SessionParameters parameters{ @@ -418,15 +418,15 @@ /*user_name=*/GetRobotAccountUserName(), /*terminate_upon_input=*/ShouldTerminateUponInput(), /*show_confirmation_dialog=*/ShouldShowConfirmationDialog()}; - delegate_->StartCRDHostAndGetCode( + delegate_->StartCrdHostAndGetCode( parameters, - base::BindOnce(&DeviceCommandStartCRDSessionJob::OnAccessCodeReceived, + base::BindOnce(&DeviceCommandStartCrdSessionJob::OnAccessCodeReceived, weak_factory_.GetWeakPtr()), - base::BindOnce(&DeviceCommandStartCRDSessionJob::FinishWithError, + base::BindOnce(&DeviceCommandStartCrdSessionJob::FinishWithError, weak_factory_.GetWeakPtr())); } -void DeviceCommandStartCRDSessionJob::OnAccessCodeReceived( +void DeviceCommandStartCrdSessionJob::OnAccessCodeReceived( const std::string& access_code) { if (!succeeded_callback_) return; // Task was terminated. @@ -438,7 +438,7 @@ ResultPayload::CreateSuccessPayload(access_code))); } -std::string DeviceCommandStartCRDSessionJob::GetRobotAccountUserName() const { +std::string DeviceCommandStartCrdSessionJob::GetRobotAccountUserName() const { CoreAccountId account_id = oauth_service()->GetRobotAccountId(); // TODO(msarda): This conversion will not be correct once account id is @@ -446,7 +446,7 @@ return account_id.ToString(); } -bool DeviceCommandStartCRDSessionJob::ShouldShowConfirmationDialog() const { +bool DeviceCommandStartCrdSessionJob::ShouldShowConfirmationDialog() const { switch (GetUserType()) { case UserType::kAffiliatedUser: case UserType::kManagedGuestSession: @@ -461,7 +461,7 @@ return false; } -bool DeviceCommandStartCRDSessionJob::ShouldTerminateUponInput() const { +bool DeviceCommandStartCrdSessionJob::ShouldTerminateUponInput() const { switch (GetUserType()) { case UserType::kAffiliatedUser: case UserType::kManagedGuestSession: @@ -487,7 +487,7 @@ return false; } -bool DeviceCommandStartCRDSessionJob::ShouldUseEnterpriseUserDialog() const { +bool DeviceCommandStartCrdSessionJob::ShouldUseEnterpriseUserDialog() const { switch (GetUserType()) { case UserType::kAffiliatedUser: case UserType::kManagedGuestSession: @@ -502,19 +502,19 @@ return false; } -DeviceOAuth2TokenService* DeviceCommandStartCRDSessionJob::oauth_service() +DeviceOAuth2TokenService* DeviceCommandStartCrdSessionJob::oauth_service() const { return DeviceOAuth2TokenServiceFactory::Get(); } -void DeviceCommandStartCRDSessionJob::TerminateImpl() { +void DeviceCommandStartCrdSessionJob::TerminateImpl() { succeeded_callback_.Reset(); failed_callback_.Reset(); weak_factory_.InvalidateWeakPtrs(); delegate_->TerminateSession(base::OnceClosure()); } -const char* DeviceCommandStartCRDSessionJob::UserTypeToString( +const char* DeviceCommandStartCrdSessionJob::UserTypeToString( UserType value) const { switch (value) { case UserType::kAutoLaunchedKiosk:
diff --git a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.h b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.h index 4faf86f..1379bdf 100644 --- a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.h +++ b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_job.h
@@ -8,7 +8,6 @@ #include <string> #include "base/callback.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "components/policy/core/common/remote_commands/remote_command_job.h" @@ -20,7 +19,7 @@ // Remote command that would start Chrome Remote Desktop host and return auth // code. This command is usable only for devices running Kiosk sessions, for // Affiliated Users and for Managed Guest Sessions. -class DeviceCommandStartCRDSessionJob : public RemoteCommandJob { +class DeviceCommandStartCrdSessionJob : public RemoteCommandJob { public: enum ResultCode { // Successfully obtained access code. @@ -70,19 +69,18 @@ virtual void TerminateSession(base::OnceClosure callback) = 0; // Attempts to start CRD host and get Auth Code. - virtual void StartCRDHostAndGetCode(const SessionParameters& parameters, + virtual void StartCrdHostAndGetCode(const SessionParameters& parameters, AccessCodeCallback success_callback, ErrorCallback error_callback) = 0; }; - explicit DeviceCommandStartCRDSessionJob(Delegate* crd_host_delegate); + explicit DeviceCommandStartCrdSessionJob(Delegate* crd_host_delegate); + ~DeviceCommandStartCrdSessionJob() override; - DeviceCommandStartCRDSessionJob(const DeviceCommandStartCRDSessionJob&) = + DeviceCommandStartCrdSessionJob(const DeviceCommandStartCrdSessionJob&) = delete; - DeviceCommandStartCRDSessionJob& operator=( - const DeviceCommandStartCRDSessionJob&) = delete; - - ~DeviceCommandStartCRDSessionJob() override; + DeviceCommandStartCrdSessionJob& operator=( + const DeviceCommandStartCrdSessionJob&) = delete; // RemoteCommandJob: enterprise_management::RemoteCommand_Type GetType() const override; @@ -114,7 +112,7 @@ // Check if all required system services (singletons) are ready. bool AreServicesReady() const; - bool UserTypeSupportsCRD() const; + bool UserTypeSupportsCrd() const; UserType GetUserType() const; bool IsRunningAutoLaunchedKiosk() const; bool IsDeviceIdle() const; @@ -166,7 +164,7 @@ bool terminate_session_attempted_ = false; - base::WeakPtrFactory<DeviceCommandStartCRDSessionJob> weak_factory_{this}; + base::WeakPtrFactory<DeviceCommandStartCrdSessionJob> weak_factory_{this}; }; } // namespace policy
diff --git a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_unittest.cc b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_unittest.cc index 969635d..5e4ac45 100644 --- a/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_unittest.cc +++ b/chrome/browser/ash/policy/remote_commands/device_command_start_crd_session_unittest.cc
@@ -105,10 +105,10 @@ return command_proto; } -class StubCRDHostDelegate : public DeviceCommandStartCRDSessionJob::Delegate { +class StubCrdHostDelegate : public DeviceCommandStartCrdSessionJob::Delegate { public: - StubCRDHostDelegate() = default; - ~StubCRDHostDelegate() override = default; + StubCrdHostDelegate() = default; + ~StubCrdHostDelegate() override = default; void SetHasActiveSession(bool value) { has_active_session_ = value; } void MakeAccessCodeFetchFail() { access_code_success_ = false; } @@ -116,20 +116,20 @@ // Returns if TerminateSession() was called to terminate the active session. bool IsActiveSessionTerminated() const { return terminate_session_called_; } - // Returns the |SessionParameters| sent to the last StartCRDHostAndGetCode() + // Returns the |SessionParameters| sent to the last StartCrdHostAndGetCode() // call. SessionParameters session_parameters() { EXPECT_TRUE(received_session_parameters_.has_value()); return received_session_parameters_.value_or(SessionParameters{}); } - // DeviceCommandStartCRDSessionJob::Delegate implementation: + // DeviceCommandStartCrdSessionJob::Delegate implementation: bool HasActiveSession() const override; void TerminateSession(base::OnceClosure callback) override; - void StartCRDHostAndGetCode( + void StartCrdHostAndGetCode( const SessionParameters& parameters, - DeviceCommandStartCRDSessionJob::AccessCodeCallback success_callback, - DeviceCommandStartCRDSessionJob::ErrorCallback error_callback) override; + DeviceCommandStartCrdSessionJob::AccessCodeCallback success_callback, + DeviceCommandStartCrdSessionJob::ErrorCallback error_callback) override; private: bool has_active_session_ = false; @@ -138,27 +138,27 @@ absl::optional<SessionParameters> received_session_parameters_; }; -bool StubCRDHostDelegate::HasActiveSession() const { +bool StubCrdHostDelegate::HasActiveSession() const { return has_active_session_; } -void StubCRDHostDelegate::TerminateSession(base::OnceClosure callback) { +void StubCrdHostDelegate::TerminateSession(base::OnceClosure callback) { has_active_session_ = false; terminate_session_called_ = true; std::move(callback).Run(); } -void StubCRDHostDelegate::StartCRDHostAndGetCode( +void StubCrdHostDelegate::StartCrdHostAndGetCode( const SessionParameters& parameters, - DeviceCommandStartCRDSessionJob::AccessCodeCallback success_callback, - DeviceCommandStartCRDSessionJob::ErrorCallback error_callback) { + DeviceCommandStartCrdSessionJob::AccessCodeCallback success_callback, + DeviceCommandStartCrdSessionJob::ErrorCallback error_callback) { received_session_parameters_ = parameters; if (access_code_success_) { std::move(success_callback).Run(kTestAccessCode); } else { std::move(error_callback) - .Run(DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR, + .Run(DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR, std::string()); } } @@ -170,9 +170,9 @@ } // namespace -class DeviceCommandStartCRDSessionJobTest : public ash::DeviceSettingsTestBase { +class DeviceCommandStartCrdSessionJobTest : public ash::DeviceSettingsTestBase { public: - DeviceCommandStartCRDSessionJobTest() + DeviceCommandStartCrdSessionJobTest() : ash::DeviceSettingsTestBase( base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} @@ -210,7 +210,7 @@ std::string CreateSuccessPayload(const std::string& access_code); std::string CreateErrorPayload( - DeviceCommandStartCRDSessionJob::ResultCode result_code, + DeviceCommandStartCrdSessionJob::ResultCode result_code, const std::string& error_message); std::string CreateNotIdlePayload(base::TimeDelta idleness); @@ -291,8 +291,8 @@ void DeleteUserActivityDetector() { user_activity_detector_ = nullptr; } void DeleteUserManager() { user_manager_enabler_ = nullptr; } - StubCRDHostDelegate& crd_host_delegate() { return crd_host_delegate_; } - DeviceCommandStartCRDSessionJob& job() { return job_; } + StubCrdHostDelegate& crd_host_delegate() { return crd_host_delegate_; } + DeviceCommandStartCrdSessionJob& job() { return job_; } private: ash::FakeChromeUserManager& user_manager() { return *user_manager_; } @@ -319,7 +319,7 @@ InitializeJob(); bool launched = job().Run( base::Time::Now(), base::TimeTicks::Now(), - base::BindOnce(&DeviceCommandStartCRDSessionJobTest::OnJobFinished, + base::BindOnce(&DeviceCommandStartCrdSessionJobTest::OnJobFinished, base::Unretained(this))); EXPECT_TRUE(launched); } @@ -346,8 +346,8 @@ network::TestURLLoaderFactory test_url_loader_factory_; TestingPrefServiceSimple local_state_; - StubCRDHostDelegate crd_host_delegate_; - DeviceCommandStartCRDSessionJob job_{&crd_host_delegate_}; + StubCrdHostDelegate crd_host_delegate_; + DeviceCommandStartCrdSessionJob job_{&crd_host_delegate_}; // Future value that will be populated with the result once the remote command // job is completed. @@ -356,19 +356,19 @@ base::TimeTicks test_start_time_; }; -std::string DeviceCommandStartCRDSessionJobTest::CreateSuccessPayload( +std::string DeviceCommandStartCrdSessionJobTest::CreateSuccessPayload( const std::string& access_code) { std::string payload; base::Value root(base::Value::Type::DICTIONARY); root.SetKey(kResultCodeFieldName, - base::Value(DeviceCommandStartCRDSessionJob::SUCCESS)); + base::Value(DeviceCommandStartCrdSessionJob::SUCCESS)); root.SetKey(kResultAccessCodeFieldName, base::Value(access_code)); base::JSONWriter::Write(root, &payload); return payload; } -std::string DeviceCommandStartCRDSessionJobTest::CreateErrorPayload( - DeviceCommandStartCRDSessionJob::ResultCode result_code, +std::string DeviceCommandStartCrdSessionJobTest::CreateErrorPayload( + DeviceCommandStartCrdSessionJob::ResultCode result_code, const std::string& error_message = "") { std::string payload; base::Value root(base::Value::Type::DICTIONARY); @@ -379,19 +379,19 @@ return payload; } -std::string DeviceCommandStartCRDSessionJobTest::CreateNotIdlePayload( +std::string DeviceCommandStartCrdSessionJobTest::CreateNotIdlePayload( base::TimeDelta idleness) { std::string payload; base::Value root(base::Value::Type::DICTIONARY); root.SetKey(kResultCodeFieldName, - base::Value(DeviceCommandStartCRDSessionJob::FAILURE_NOT_IDLE)); + base::Value(DeviceCommandStartCrdSessionJob::FAILURE_NOT_IDLE)); root.SetKey(kResultLastActivityFieldName, base::Value(static_cast<int>(idleness.InSeconds()))); base::JSONWriter::Write(root, &payload); return payload; } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldSucceedIfAccessTokenCanBeFetched) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -401,7 +401,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldTerminateActiveSessionAndThenSucceed) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -414,7 +414,7 @@ EXPECT_TRUE(crd_host_delegate().IsActiveSessionTerminated()); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfOAuthTokenServiceIsNotRunning) { DeviceOAuth2TokenServiceFactory::Shutdown(); @@ -423,74 +423,74 @@ Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_SERVICES_NOT_READY); + DeviceCommandStartCrdSessionJob::FAILURE_SERVICES_NOT_READY); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfUserActivityDetectorIsNotRunning) { DeleteUserActivityDetector(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_SERVICES_NOT_READY); + DeviceCommandStartCrdSessionJob::FAILURE_SERVICES_NOT_READY); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfUserManagerIsNotRunning) { DeleteUserManager(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_SERVICES_NOT_READY); + DeviceCommandStartCrdSessionJob::FAILURE_SERVICES_NOT_READY); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldFailForManagedGuestUser) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForManagedGuestUser) { base::test::ScopedFeatureList disable_crd_for_user_sessions_; disable_crd_for_user_sessions_.InitAndDisableFeature( - features::kCRDForManagedUserSessions); + features::kCrdForManagedUserSessions); LogInAsManagedGuestSessionUser(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldFailForGuestUser) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForGuestUser) { LogInAsGuestUser(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldFailForAffiliatedUser) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForAffiliatedUser) { base::test::ScopedFeatureList disable_crd_for_user_sessions_; disable_crd_for_user_sessions_.InitAndDisableFeature( - features::kCRDForManagedUserSessions); + features::kCrdForManagedUserSessions); LogInAsAffiliatedUser(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldFailForRegularUser) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForRegularUser) { LogInAsRegularUser(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForKioskUserWithoutAutoLaunch) { LogInAsKioskAppUser(); @@ -500,10 +500,10 @@ Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldSucceedForKioskUserWithZeroDelayAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -516,7 +516,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForArcKioskUserWithoutAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -527,10 +527,10 @@ Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldSucceedForArcKioskUserWithZeroDelayAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -543,7 +543,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailForWebKioskUserWithoutAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -554,10 +554,10 @@ Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldSucceedForWebKioskUserWithZeroDelayAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -570,7 +570,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfDeviceIdleTimeIsLessThanIdlenessCutoffValue) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -587,7 +587,7 @@ EXPECT_EQ(result.payload, CreateNotIdlePayload(device_idle_time)); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldSucceedIfDeviceIdleTimeIsMoreThanIdlenessCutoffValue) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -603,18 +603,18 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfWeCantFetchTheOAuthToken) { LogInAsAutoLaunchedKioskAppUser(); ClearOAuthToken(); Result result = RunJobAndWaitForResult(); - EXPECT_ERROR(result, DeviceCommandStartCRDSessionJob::FAILURE_NO_OAUTH_TOKEN, + EXPECT_ERROR(result, DeviceCommandStartCrdSessionJob::FAILURE_NO_OAUTH_TOKEN, kTestNoOAuthTokenReason); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldFailIfCRDHostReportsAnError) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldFailIfCrdHostReportsAnError) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -622,10 +622,10 @@ Result result = RunJobAndWaitForResult(); - EXPECT_ERROR(result, DeviceCommandStartCRDSessionJob::FAILURE_CRD_HOST_ERROR); + EXPECT_ERROR(result, DeviceCommandStartCrdSessionJob::FAILURE_CRD_HOST_ERROR); } -TEST_F(DeviceCommandStartCRDSessionJobTest, ShouldPassOAuthTokenToDelegate) { +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldPassOAuthTokenToDelegate) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken("the-oauth-token"); @@ -636,7 +636,7 @@ crd_host_delegate().session_parameters().oauth_token); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldPassRobotAccountNameToDelegate) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -650,7 +650,7 @@ crd_host_delegate().session_parameters().user_name); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldPassTerminateUponInputTrueToDelegateForKioskUser) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -664,7 +664,7 @@ crd_host_delegate().session_parameters().terminate_upon_input); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldPassTerminateUponInputFalseToDelegate) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -679,7 +679,7 @@ } TEST_F( - DeviceCommandStartCRDSessionJobTest, + DeviceCommandStartCrdSessionJobTest, ShouldPassTerminateUponInputTrueToDelegateForKioskUserIfAckedUserPresenceSetFalse) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -694,7 +694,7 @@ } TEST_F( - DeviceCommandStartCRDSessionJobTest, + DeviceCommandStartCrdSessionJobTest, ShouldPassTerminateUponInputFalseToDelegateForKioskUserIfAckedUserPresenceSetTrue) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -709,7 +709,7 @@ } TEST_F( - DeviceCommandStartCRDSessionJobTest, + DeviceCommandStartCrdSessionJobTest, TerminateUponInputFieldShouldBeIgnoredIfAckedUserPresenseFieldIsSetFalse) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -725,7 +725,7 @@ } TEST_F( - DeviceCommandStartCRDSessionJobTest, + DeviceCommandStartCrdSessionJobTest, TerminateUponInputFieldShouldBeIgnoredIfAckedUserPresenseFieldIsSetTrue) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -740,7 +740,7 @@ crd_host_delegate().session_parameters().terminate_upon_input); } -TEST_F(DeviceCommandStartCRDSessionJobTest, +TEST_F(DeviceCommandStartCrdSessionJobTest, ShouldPassShowConfirmationDialogFalseToDelegateForKioskUser) { LogInAsAutoLaunchedKioskAppUser(); SetOAuthToken(kTestOAuthToken); @@ -752,27 +752,27 @@ crd_host_delegate().session_parameters().show_confirmation_dialog); } -// This test fixture enables the |kCRDForManagedUserSessions| feature flag, +// This test fixture enables the |kCrdForManagedUserSessions| feature flag, // and tests the additional functionality enabled by the flag. -class DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest - : public DeviceCommandStartCRDSessionJobTest { +class DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest + : public DeviceCommandStartCrdSessionJobTest { public: - DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest() = default; - DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest( - const DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest&) = + DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest() = default; + DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest( + const DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest&) = delete; - DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest& operator=( - const DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest&) = + DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest& operator=( + const DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest&) = delete; - ~DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest() override = + ~DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest() override = default; private: base::test::ScopedFeatureList enable_crd_for_user_sessions_{ - features::kCRDForManagedUserSessions}; + features::kCrdForManagedUserSessions}; }; -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldSucceedForKioskUserWithZeroDelayAutoLaunch) { SetOAuthToken(kTestOAuthToken); @@ -785,17 +785,17 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldFailForRegularUser) { LogInAsRegularUser(); Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldFailForGuestUser) { // Note that guest user != managed guest user LogInAsGuestUser(); @@ -803,18 +803,18 @@ Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldFailIfNoUserIsLoggedIn) { Result result = RunJobAndWaitForResult(); EXPECT_ERROR(result, - DeviceCommandStartCRDSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); + DeviceCommandStartCrdSessionJob::FAILURE_UNSUPPORTED_USER_TYPE); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldSucceedForManagedGuestUser) { SetOAuthToken(kTestOAuthToken); @@ -824,7 +824,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldSucceedForAffiliatedUser) { SetOAuthToken(kTestOAuthToken); @@ -834,7 +834,7 @@ EXPECT_SUCCESS(result); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldPassShowConfirmationDialogTrueToDelegateForManagedGuestUser) { LogInAsManagedGuestSessionUser(); SetOAuthToken(kTestOAuthToken); @@ -846,7 +846,7 @@ crd_host_delegate().session_parameters().show_confirmation_dialog); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldPassShowConfirmationDialogTrueToDelegateForAffiliatedUser) { LogInAsAffiliatedUser(); SetOAuthToken(kTestOAuthToken); @@ -858,7 +858,7 @@ crd_host_delegate().session_parameters().show_confirmation_dialog); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldPassTerminateUponInputFalseToDelegateForAffiliatedUser) { LogInAsAffiliatedUser(); SetOAuthToken(kTestOAuthToken); @@ -872,7 +872,7 @@ crd_host_delegate().session_parameters().terminate_upon_input); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldPassTerminateUponInputFalseToDelegateForManagedGuestUser) { LogInAsManagedGuestSessionUser(); SetOAuthToken(kTestOAuthToken); @@ -886,7 +886,7 @@ crd_host_delegate().session_parameters().terminate_upon_input); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldNeverSendTerminateUponInputTrueToDelegateForAffiliatedUser) { LogInAsAffiliatedUser(); SetOAuthToken(kTestOAuthToken); @@ -900,7 +900,7 @@ crd_host_delegate().session_parameters().terminate_upon_input); } -TEST_F(DeviceCommandStartCRDSessionJobWithCRDForUserSessionsFeatureTest, +TEST_F(DeviceCommandStartCrdSessionJobWithCrdForUserSessionsFeatureTest, ShouldNeverSendTerminateUponInputTrueToDelegateForManagedGuestUser) { LogInAsManagedGuestSessionUser(); SetOAuthToken(kTestOAuthToken);
diff --git a/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.cc b/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.cc index cc1d995a2..9cfb911 100644 --- a/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.cc +++ b/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.cc
@@ -47,7 +47,7 @@ case em::RemoteCommand_Type_DEVICE_SET_VOLUME: return std::make_unique<DeviceCommandSetVolumeJob>(); case em::RemoteCommand_Type_DEVICE_START_CRD_SESSION: - return std::make_unique<DeviceCommandStartCRDSessionJob>( + return std::make_unique<DeviceCommandStartCrdSessionJob>( GetCrdHostDelegate()); case em::RemoteCommand_Type_DEVICE_FETCH_STATUS: return std::make_unique<DeviceCommandFetchStatusJob>(); @@ -74,7 +74,7 @@ } } -DeviceCommandStartCRDSessionJob::Delegate* +DeviceCommandStartCrdSessionJob::Delegate* DeviceCommandsFactoryAsh::GetCrdHostDelegate() { if (!crd_host_delegate_) { crd_host_delegate_ = std::make_unique<CrdHostDelegate>();
diff --git a/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.h b/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.h index 6c68ff9..6be41d73 100644 --- a/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.h +++ b/chrome/browser/ash/policy/remote_commands/device_commands_factory_ash.h
@@ -32,9 +32,9 @@ private: DeviceCloudPolicyManagerAsh* policy_manager_; - std::unique_ptr<DeviceCommandStartCRDSessionJob::Delegate> crd_host_delegate_; + std::unique_ptr<DeviceCommandStartCrdSessionJob::Delegate> crd_host_delegate_; - DeviceCommandStartCRDSessionJob::Delegate* GetCrdHostDelegate(); + DeviceCommandStartCrdSessionJob::Delegate* GetCrdHostDelegate(); }; } // namespace policy
diff --git a/chrome/browser/ash/scanning/scan_service.cc b/chrome/browser/ash/scanning/scan_service.cc index 23fc68a..cc4e1b6 100644 --- a/chrome/browser/ash/scanning/scan_service.cc +++ b/chrome/browser/ash/scanning/scan_service.cc
@@ -95,10 +95,11 @@ bool SaveAsPdf(const std::vector<std::string>& jpg_images, const base::FilePath& file_path, bool rotate_alternate_pages, - bool is_multi_page_scan) { + bool is_multi_page_scan, + absl::optional<int> dpi) { const base::TimeTicks pdf_start_time = base::TimeTicks::Now(); const bool pdf_saved = chromeos::ConvertJpgImagesToPdf( - jpg_images, file_path, rotate_alternate_pages); + jpg_images, file_path, rotate_alternate_pages, dpi); base::UmaHistogramTimes(is_multi_page_scan ? "Scanning.MultiPageScan.PDFGenerationTime" : "Scanning.PDFGenerationTime", @@ -279,6 +280,9 @@ rotate_alternate_pages_ = lorgnette_scanner_manager_->IsRotateAlternate( scanner_name, settings->source_name); + // Save the DPI information for the scan. + scan_dpi_ = settings->resolution_dpi; + base::Time::Now().LocalExplode(&start_time_); lorgnette_scanner_manager_->Scan( scanner_name, @@ -506,7 +510,7 @@ base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, base::BindOnce(&SaveAsPdf, scanned_images_, scanned_file_paths_.back(), - rotate_alternate_pages_, is_multi_page_scan), + rotate_alternate_pages_, is_multi_page_scan, scan_dpi_), base::BindOnce(&ScanService::OnPdfSaved, weak_ptr_factory_.GetWeakPtr())); } @@ -591,6 +595,7 @@ void ScanService::ClearScanState() { page_save_failed_ = false; rotate_alternate_pages_ = false; + scan_dpi_ = absl::nullopt; scanned_file_paths_.clear(); scanned_images_.clear(); num_pages_scanned_ = 0;
diff --git a/chrome/browser/ash/scanning/scan_service.h b/chrome/browser/ash/scanning/scan_service.h index e22178c..3921c7c 100644 --- a/chrome/browser/ash/scanning/scan_service.h +++ b/chrome/browser/ash/scanning/scan_service.h
@@ -211,6 +211,9 @@ // scanner that flips them. bool rotate_alternate_pages_; + // Stores the dots per inch (DPI) of the requested scan. + absl::optional<int> scan_dpi_; + // The time at which GetScanners() is called. Used to record the time between // a user launching the Scan app and being able to interact with it. base::TimeTicks get_scanners_time_;
diff --git a/chrome/browser/chromeos/secure_channel/DIR_METADATA b/chrome/browser/ash/secure_channel/DIR_METADATA similarity index 100% rename from chrome/browser/chromeos/secure_channel/DIR_METADATA rename to chrome/browser/ash/secure_channel/DIR_METADATA
diff --git a/chrome/browser/chromeos/secure_channel/OWNERS b/chrome/browser/ash/secure_channel/OWNERS similarity index 100% rename from chrome/browser/chromeos/secure_channel/OWNERS rename to chrome/browser/ash/secure_channel/OWNERS
diff --git a/chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.cc b/chrome/browser/ash/secure_channel/fake_nearby_connection_broker.cc similarity index 81% rename from chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.cc rename to chrome/browser/ash/secure_channel/fake_nearby_connection_broker.cc index 20ca65b..f10e41f 100644 --- a/chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.cc +++ b/chrome/browser/ash/secure_channel/fake_nearby_connection_broker.cc
@@ -2,11 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.h" +#include "chrome/browser/ash/secure_channel/fake_nearby_connection_broker.h" -namespace chromeos { +namespace ash { namespace secure_channel { +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + FakeNearbyConnectionBroker::FakeNearbyConnectionBroker( const std::vector<uint8_t>& bluetooth_public_address, mojo::PendingReceiver<mojom::NearbyMessageSender> message_sender_receiver, @@ -28,4 +32,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.h b/chrome/browser/ash/secure_channel/fake_nearby_connection_broker.h similarity index 67% rename from chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.h rename to chrome/browser/ash/secure_channel/fake_nearby_connection_broker.h index 6154095..9693ea33 100644 --- a/chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.h +++ b/chrome/browser/ash/secure_channel/fake_nearby_connection_broker.h
@@ -2,20 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_ -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker.h" -namespace chromeos { +namespace ash { namespace secure_channel { class FakeNearbyConnectionBroker : public NearbyConnectionBroker { public: FakeNearbyConnectionBroker( const std::vector<uint8_t>& bluetooth_public_address, - mojo::PendingReceiver<mojom::NearbyMessageSender> message_sender_receiver, - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver_remote, + mojo::PendingReceiver< + chromeos::secure_channel::mojom::NearbyMessageSender> + message_sender_receiver, + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver_remote, base::OnceClosure on_connected_callback, base::OnceClosure on_disconnected_callback); ~FakeNearbyConnectionBroker() override; @@ -43,6 +47,6 @@ }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_CONNECTION_BROKER_H_
diff --git a/chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.cc b/chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.cc similarity index 73% rename from chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.cc rename to chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.cc index 603077f8..0bb08e7 100644 --- a/chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.cc +++ b/chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h" -namespace chromeos { +namespace ash { namespace secure_channel { FakeNearbyEndpointFinder::FakeNearbyEndpointFinder() = default; @@ -12,4 +12,4 @@ FakeNearbyEndpointFinder::~FakeNearbyEndpointFinder() = default; } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h b/chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h similarity index 65% rename from chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h rename to chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h index 1101ac9..1aaebc2 100644 --- a/chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h +++ b/chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_ -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder.h" -namespace chromeos { +namespace ash { namespace secure_channel { class FakeNearbyEndpointFinder : public NearbyEndpointFinder { @@ -26,6 +26,6 @@ }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_FAKE_NEARBY_ENDPOINT_FINDER_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connection_broker.cc b/chrome/browser/ash/secure_channel/nearby_connection_broker.cc similarity index 87% rename from chrome/browser/chromeos/secure_channel/nearby_connection_broker.cc rename to chrome/browser/ash/secure_channel/nearby_connection_broker.cc index a3d17e5..ef85f56a 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connection_broker.cc +++ b/chrome/browser/ash/secure_channel/nearby_connection_broker.cc
@@ -2,16 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker.h" #include "base/bind.h" #include "base/check.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" -namespace chromeos { +namespace ash { namespace secure_channel { +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + NearbyConnectionBroker::NearbyConnectionBroker( const std::vector<uint8_t>& bluetooth_public_address, mojo::PendingReceiver<mojom::NearbyMessageSender> message_sender_receiver, @@ -48,4 +52,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connection_broker.h b/chrome/browser/ash/secure_channel/nearby_connection_broker.h similarity index 70% rename from chrome/browser/chromeos/secure_channel/nearby_connection_broker.h rename to chrome/browser/ash/secure_channel/nearby_connection_broker.h index dbcdbce..c8e9dcf 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connection_broker.h +++ b/chrome/browser/ash/secure_channel/nearby_connection_broker.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_ #include <string> #include <vector> @@ -15,7 +15,7 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -namespace chromeos { +namespace ash { namespace secure_channel { // Attempts to create a Nearby Connection to a remote device and exchange @@ -26,15 +26,20 @@ // // An instance of this class is only meant to be used for one connection // request to a single device. To make a new request, create a new object. -class NearbyConnectionBroker : public mojom::NearbyMessageSender { +class NearbyConnectionBroker + : public chromeos::secure_channel::mojom::NearbyMessageSender { public: ~NearbyConnectionBroker() override; protected: NearbyConnectionBroker( const std::vector<uint8_t>& bluetooth_public_address, - mojo::PendingReceiver<mojom::NearbyMessageSender> message_sender_receiver, - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver_remote, + mojo::PendingReceiver< + chromeos::secure_channel::mojom::NearbyMessageSender> + message_sender_receiver, + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver_remote, base::OnceClosure on_connected_callback, base::OnceClosure on_disconnected_callback); @@ -52,13 +57,15 @@ private: std::vector<uint8_t> bluetooth_public_address_; - mojo::Receiver<mojom::NearbyMessageSender> message_sender_receiver_; - mojo::Remote<mojom::NearbyMessageReceiver> message_receiver_remote_; + mojo::Receiver<chromeos::secure_channel::mojom::NearbyMessageSender> + message_sender_receiver_; + mojo::Remote<chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver_remote_; base::OnceClosure on_connected_callback_; base::OnceClosure on_disconnected_callback_; }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.cc b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl.cc similarity index 94% rename from chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.cc rename to chrome/browser/ash/secure_channel/nearby_connection_broker_impl.cc index 1eb832cb..7666dc50 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.cc +++ b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl.cc
@@ -2,33 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h" #include "ash/constants/ash_features.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/rand_util.h" #include "base/time/time.h" -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h" -#include "chrome/browser/chromeos/secure_channel/util/histogram_util.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/util/histogram_util.h" #include "chromeos/components/multidevice/logging/logging.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace { -using location::nearby::connections::mojom::BytesPayload; -using location::nearby::connections::mojom::ConnectionInfoPtr; -using location::nearby::connections::mojom::ConnectionOptions; -using location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; -using location::nearby::connections::mojom::Medium; -using location::nearby::connections::mojom::MediumSelection; -using location::nearby::connections::mojom::NearbyConnections; -using location::nearby::connections::mojom::Payload; -using location::nearby::connections::mojom::PayloadContent; -using location::nearby::connections::mojom::PayloadPtr; -using location::nearby::connections::mojom::PayloadTransferUpdatePtr; -using location::nearby::connections::mojom::Status; +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + +using ::location::nearby::connections::mojom::BytesPayload; +using ::location::nearby::connections::mojom::ConnectionInfoPtr; +using ::location::nearby::connections::mojom::ConnectionOptions; +using ::location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; +using ::location::nearby::connections::mojom::Medium; +using ::location::nearby::connections::mojom::MediumSelection; +using ::location::nearby::connections::mojom::NearbyConnections; +using ::location::nearby::connections::mojom::Payload; +using ::location::nearby::connections::mojom::PayloadContent; +using ::location::nearby::connections::mojom::PayloadPtr; +using ::location::nearby::connections::mojom::Status; NearbyConnectionBrokerImpl::Factory* g_test_factory = nullptr; @@ -232,10 +235,10 @@ /*webrtc=*/true, /*wifi_lan=*/false), /*remote_bluetooth_mac_address=*/absl::nullopt, - ash::features::IsNearbyKeepAliveFixEnabled() + features::IsNearbyKeepAliveFixEnabled() ? absl::make_optional(kKeepAliveInterval) : absl::nullopt, - ash::features::IsNearbyKeepAliveFixEnabled() + features::IsNearbyKeepAliveFixEnabled() ? absl::make_optional(kKeepAliveTimeout) : absl::nullopt), connection_lifecycle_listener_receiver_.BindNewPipeAndPassRemote(), @@ -552,4 +555,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h similarity index 86% rename from chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h rename to chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h index f74472a7..c780872e 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h +++ b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_ #include <memory> #include <ostream> @@ -12,12 +12,12 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker.h" -#include "chrome/browser/chromeos/secure_channel/util/histogram_util.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker.h" +#include "chrome/browser/ash/secure_channel/util/histogram_util.h" #include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" #include "mojo/public/cpp/bindings/shared_remote.h" -namespace chromeos { +namespace ash { namespace secure_channel { class NearbyEndpointFinder; @@ -43,9 +43,11 @@ const std::vector<uint8_t>& bluetooth_public_address, const std::vector<uint8_t>& eid, NearbyEndpointFinder* endpoint_finder, - mojo::PendingReceiver<mojom::NearbyMessageSender> + mojo::PendingReceiver< + chromeos::secure_channel::mojom::NearbyMessageSender> message_sender_receiver, - mojo::PendingRemote<mojom::NearbyMessageReceiver> + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> message_receiver_remote, const mojo::SharedRemote< location::nearby::connections::mojom::NearbyConnections>& @@ -62,9 +64,11 @@ virtual std::unique_ptr<NearbyConnectionBroker> CreateInstance( const std::vector<uint8_t>& bluetooth_public_address, NearbyEndpointFinder* endpoint_finder, - mojo::PendingReceiver<mojom::NearbyMessageSender> + mojo::PendingReceiver< + chromeos::secure_channel::mojom::NearbyMessageSender> message_sender_receiver, - mojo::PendingRemote<mojom::NearbyMessageReceiver> + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> message_receiver_remote, const mojo::SharedRemote< location::nearby::connections::mojom::NearbyConnections>& @@ -95,8 +99,12 @@ const std::vector<uint8_t>& bluetooth_public_address, const std::vector<uint8_t>& eid, NearbyEndpointFinder* endpoint_finder, - mojo::PendingReceiver<mojom::NearbyMessageSender> message_sender_receiver, - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver_remote, + mojo::PendingReceiver< + chromeos::secure_channel::mojom::NearbyMessageSender> + message_sender_receiver, + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver_remote, const mojo::SharedRemote< location::nearby::connections::mojom::NearbyConnections>& nearby_connections, @@ -194,6 +202,6 @@ NearbyConnectionBrokerImpl::ConnectionStatus status); } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTION_BROKER_IMPL_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl_unittest.cc b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl_unittest.cc similarity index 93% rename from chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl_unittest.cc rename to chrome/browser/ash/secure_channel/nearby_connection_broker_impl_unittest.cc index 4306939..11f8dcf 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl_unittest.cc +++ b/chrome/browser/ash/secure_channel/nearby_connection_broker_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h" #include <memory> #include <vector> @@ -13,7 +13,7 @@ #include "base/test/bind.h" #include "base/test/task_environment.h" #include "base/timer/mock_timer.h" -#include "chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h" #include "chromeos/services/nearby/public/cpp/mock_nearby_connections.h" #include "chromeos/services/secure_channel/public/mojom/nearby_connector.mojom.h" #include "mojo/public/cpp/bindings/remote.h" @@ -21,25 +21,27 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace { -using location::nearby::connections::mojom::BytesPayload; -using location::nearby::connections::mojom::ConnectionInfo; -using location::nearby::connections::mojom::ConnectionLifecycleListener; -using location::nearby::connections::mojom::ConnectionOptionsPtr; -using location::nearby::connections::mojom::DiscoveredEndpointInfo; -using location::nearby::connections::mojom::EndpointDiscoveryListener; -using location::nearby::connections::mojom::FilePayload; -using location::nearby::connections::mojom::Payload; -using location::nearby::connections::mojom::PayloadContent; -using location::nearby::connections::mojom::PayloadListener; -using location::nearby::connections::mojom::PayloadPtr; -using location::nearby::connections::mojom::Status; +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; -using testing::_; -using testing::Invoke; +using ::location::nearby::connections::mojom::BytesPayload; +using ::location::nearby::connections::mojom::ConnectionInfo; +using ::location::nearby::connections::mojom::ConnectionLifecycleListener; +using ::location::nearby::connections::mojom::ConnectionOptionsPtr; +using ::location::nearby::connections::mojom::DiscoveredEndpointInfo; +using ::location::nearby::connections::mojom::FilePayload; +using ::location::nearby::connections::mojom::Payload; +using ::location::nearby::connections::mojom::PayloadContent; +using ::location::nearby::connections::mojom::PayloadListener; +using ::location::nearby::connections::mojom::PayloadPtr; +using ::location::nearby::connections::mojom::Status; +using ::testing::_; +using ::testing::Invoke; const char kEndpointId[] = "endpointId"; const int64_t kInvalidPayloadTypeId = 1234; @@ -507,4 +509,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connector_factory.cc b/chrome/browser/ash/secure_channel/nearby_connector_factory.cc similarity index 87% rename from chrome/browser/chromeos/secure_channel/nearby_connector_factory.cc rename to chrome/browser/ash/secure_channel/nearby_connector_factory.cc index 1c2f638..b38a92e 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connector_factory.cc +++ b/chrome/browser/ash/secure_channel/nearby_connector_factory.cc
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connector_factory.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_factory.h" #include "chrome/browser/ash/nearby/nearby_process_manager_factory.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connector_impl.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_impl.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/services/secure_channel/public/cpp/client/secure_channel_client.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -namespace chromeos { +namespace ash { namespace secure_channel { // static @@ -58,4 +58,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connector_factory.h b/chrome/browser/ash/secure_channel/nearby_connector_factory.h similarity index 66% rename from chrome/browser/chromeos/secure_channel/nearby_connector_factory.h rename to chrome/browser/ash/secure_channel/nearby_connector_factory.h index 9c72963..1c66dd0 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connector_factory.h +++ b/chrome/browser/ash/secure_channel/nearby_connector_factory.h
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_ #include "base/memory/singleton.h" +// TODO(https://crbug.com/1164001): move to forward declaration. +#include "chromeos/services/secure_channel/public/cpp/client/nearby_connector.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" class Profile; -namespace chromeos { +namespace ash { namespace secure_channel { -class NearbyConnector; - class NearbyConnectorFactory : public BrowserContextKeyedServiceFactory { public: static NearbyConnector* GetForProfile(Profile* profile); @@ -36,6 +36,13 @@ }; } // namespace secure_channel +} // namespace ash + +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace chromeos { +namespace secure_channel { +using ::ash::secure_channel::NearbyConnectorFactory; +} } // namespace chromeos -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_FACTORY_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connector_impl.cc b/chrome/browser/ash/secure_channel/nearby_connector_impl.cc similarity index 93% rename from chrome/browser/chromeos/secure_channel/nearby_connector_impl.cc rename to chrome/browser/ash/secure_channel/nearby_connector_impl.cc index 53f721f..701733f 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connector_impl.cc +++ b/chrome/browser/ash/secure_channel/nearby_connector_impl.cc
@@ -2,20 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connector_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_impl.h" #include "base/bind.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h" -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h" -#include "chrome/browser/chromeos/secure_channel/util/histogram_util.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h" +#include "chrome/browser/ash/secure_channel/util/histogram_util.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/services/nearby/public/cpp/nearby_process_manager.h" #include "chromeos/services/secure_channel/public/cpp/client/nearby_connector.h" #include "components/keyed_service/core/keyed_service.h" -namespace chromeos { +namespace ash { namespace secure_channel { +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + using NearbyProcessShutdownReason = nearby::NearbyProcessManager::NearbyProcessShutdownReason; @@ -218,4 +222,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connector_impl.h b/chrome/browser/ash/secure_channel/nearby_connector_impl.h similarity index 75% rename from chrome/browser/chromeos/secure_channel/nearby_connector_impl.h rename to chrome/browser/ash/secure_channel/nearby_connector_impl.h index 0535b0e..8b2958a2 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connector_impl.h +++ b/chrome/browser/ash/secure_channel/nearby_connector_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_ #include <memory> #include <vector> @@ -18,7 +18,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" -namespace chromeos { +namespace ash { namespace secure_channel { class NearbyConnectionBroker; @@ -45,8 +45,10 @@ ConnectionRequestMetadata( const std::vector<uint8_t>& bluetooth_public_address, const std::vector<uint8_t>& eid, - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver, - ConnectCallback callback); + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver, + chromeos::secure_channel::NearbyConnector::ConnectCallback callback); ConnectionRequestMetadata(const ConnectionRequestMetadata&) = delete; ConnectionRequestMetadata& operator=(const ConnectionRequestMetadata&) = delete; @@ -54,28 +56,31 @@ std::vector<uint8_t> bluetooth_public_address; std::vector<uint8_t> eid; - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver; - ConnectCallback callback; + mojo::PendingRemote<chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver; + chromeos::secure_channel::NearbyConnector::ConnectCallback callback; }; struct ActiveConnectionAttempt { ActiveConnectionAttempt( const base::UnguessableToken& attempt_id, std::unique_ptr<NearbyEndpointFinder> endpoint_finder, - ConnectCallback callback); + chromeos::secure_channel::NearbyConnector::ConnectCallback callback); ~ActiveConnectionAttempt(); base::UnguessableToken attempt_id; std::unique_ptr<NearbyEndpointFinder> endpoint_finder; - ConnectCallback callback; + chromeos::secure_channel::NearbyConnector::ConnectCallback callback; }; /// mojom::NearbyConnector: - void Connect( - const std::vector<uint8_t>& bluetooth_public_address, - const std::vector<uint8_t>& eid, - mojo::PendingRemote<mojom::NearbyMessageReceiver> message_receiver, - ConnectCallback callback) override; + void Connect(const std::vector<uint8_t>& bluetooth_public_address, + const std::vector<uint8_t>& eid, + mojo::PendingRemote< + chromeos::secure_channel::mojom::NearbyMessageReceiver> + message_receiver, + chromeos::secure_channel::NearbyConnector::ConnectCallback + callback) override; // KeyedService: void Shutdown() override; @@ -89,12 +94,13 @@ void RecordNearbyDisconnectionForActiveBrokers( nearby::NearbyProcessManager::NearbyProcessShutdownReason shutdown_reason); - void OnConnected(const base::UnguessableToken& id, - mojo::PendingRemote<mojom::NearbyMessageSender> - message_sender_pending_remote); + void OnConnected( + const base::UnguessableToken& id, + mojo::PendingRemote<chromeos::secure_channel::mojom::NearbyMessageSender> + message_sender_pending_remote); void OnDisconnected(const base::UnguessableToken& id); void InvokeActiveConnectionAttemptCallback( - mojo::PendingRemote<mojom::NearbyMessageSender> + mojo::PendingRemote<chromeos::secure_channel::mojom::NearbyMessageSender> message_sender_pending_remote); nearby::NearbyProcessManager* nearby_process_manager_; @@ -127,6 +133,6 @@ }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_CONNECTOR_IMPL_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_connector_impl_unittest.cc b/chrome/browser/ash/secure_channel/nearby_connector_impl_unittest.cc similarity index 95% rename from chrome/browser/chromeos/secure_channel/nearby_connector_impl_unittest.cc rename to chrome/browser/ash/secure_channel/nearby_connector_impl_unittest.cc index 96cce43..5f4372eb 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_connector_impl_unittest.cc +++ b/chrome/browser/ash/secure_channel/nearby_connector_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_connector_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_impl.h" #include <memory> #include <vector> @@ -11,19 +11,23 @@ #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" -#include "chrome/browser/chromeos/secure_channel/fake_nearby_connection_broker.h" -#include "chrome/browser/chromeos/secure_channel/fake_nearby_endpoint_finder.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connection_broker_impl.h" -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h" +#include "chrome/browser/ash/secure_channel/fake_nearby_connection_broker.h" +#include "chrome/browser/ash/secure_channel/fake_nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/nearby_connection_broker_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h" #include "chromeos/services/nearby/public/cpp/fake_nearby_process_manager.h" #include "chromeos/services/secure_channel/public/mojom/nearby_connector.mojom.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace { +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + int g_next_message_receiver_id = 0; const std::vector<uint8_t> GetEid() { @@ -372,4 +376,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.cc b/chrome/browser/ash/secure_channel/nearby_endpoint_finder.cc similarity index 90% rename from chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.cc rename to chrome/browser/ash/secure_channel/nearby_endpoint_finder.cc index 4b2a48e..a4c9122 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.cc +++ b/chrome/browser/ash/secure_channel/nearby_endpoint_finder.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder.h" -namespace chromeos { +namespace ash { namespace secure_channel { NearbyEndpointFinder::NearbyEndpointFinder() = default; @@ -38,4 +38,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h b/chrome/browser/ash/secure_channel/nearby_endpoint_finder.h similarity index 87% rename from chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h rename to chrome/browser/ash/secure_channel/nearby_endpoint_finder.h index 6c7dbc4..a1b1d39 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h +++ b/chrome/browser/ash/secure_channel/nearby_endpoint_finder.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_ #include "base/unguessable_token.h" #include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" -namespace chromeos { +namespace ash { namespace secure_channel { // Discovers an endpoint corresponding to a remote device via the Nearby @@ -56,6 +56,6 @@ }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.cc b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.cc similarity index 89% rename from chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.cc rename to chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.cc index 8302f8f..51e5329 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.cc +++ b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.cc
@@ -2,24 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h" #include "base/base64.h" #include "base/memory/ptr_util.h" #include "base/rand_util.h" -#include "chrome/browser/chromeos/secure_channel/util/histogram_util.h" +#include "chrome/browser/ash/secure_channel/util/histogram_util.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/services/secure_channel/public/mojom/nearby_connector.mojom.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace { -using location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; -using location::nearby::connections::mojom::DiscoveryOptions; -using location::nearby::connections::mojom::MediumSelection; -using location::nearby::connections::mojom::Status; -using location::nearby::connections::mojom::Strategy; +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + +using ::location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; +using ::location::nearby::connections::mojom::DiscoveryOptions; +using ::location::nearby::connections::mojom::MediumSelection; +using ::location::nearby::connections::mojom::Status; +using ::location::nearby::connections::mojom::Strategy; NearbyEndpointFinderImpl::Factory* g_test_factory = nullptr; @@ -178,4 +182,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h similarity index 88% rename from chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h rename to chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h index 57586852..b7eddcae 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h +++ b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_ #include "base/memory/weak_ptr.h" -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder.h" #include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/shared_remote.h" -namespace chromeos { +namespace ash { namespace secure_channel { // NearbyEndpointFinder implementation which uses a Mojo connection to the @@ -82,6 +82,6 @@ }; } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_NEARBY_ENDPOINT_FINDER_IMPL_H_
diff --git a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl_unittest.cc b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl_unittest.cc similarity index 91% rename from chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl_unittest.cc rename to chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl_unittest.cc index 15bb9cb5..9828737 100644 --- a/chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl_unittest.cc +++ b/chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/nearby_endpoint_finder_impl.h" +#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h" #include <memory> #include <vector> @@ -16,17 +16,20 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace { -using location::nearby::connections::mojom::DiscoveredEndpointInfo; -using location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; -using location::nearby::connections::mojom::EndpointDiscoveryListener; -using location::nearby::connections::mojom::Status; +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; -using testing::_; -using testing::Invoke; +using ::location::nearby::connections::mojom::DiscoveredEndpointInfo; +using ::location::nearby::connections::mojom::DiscoveredEndpointInfoPtr; +using ::location::nearby::connections::mojom::EndpointDiscoveryListener; +using ::location::nearby::connections::mojom::Status; +using ::testing::_; +using ::testing::Invoke; const std::vector<uint8_t> GetEid() { return std::vector<uint8_t>{0, 1}; @@ -228,4 +231,4 @@ } } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/secure_channel_client_provider.cc b/chrome/browser/ash/secure_channel/secure_channel_client_provider.cc similarity index 82% rename from chrome/browser/chromeos/secure_channel/secure_channel_client_provider.cc rename to chrome/browser/ash/secure_channel/secure_channel_client_provider.cc index b18e0f8..a537ce3 100644 --- a/chrome/browser/chromeos/secure_channel/secure_channel_client_provider.cc +++ b/chrome/browser/ash/secure_channel/secure_channel_client_provider.cc
@@ -2,17 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chromeos/services/secure_channel/public/cpp/client/secure_channel_client_impl.h" #include "chromeos/services/secure_channel/secure_channel_base.h" #include "chromeos/services/secure_channel/secure_channel_initializer.h" #include "mojo/public/cpp/bindings/pending_remote.h" -namespace chromeos { - +namespace ash { namespace secure_channel { +// TODO(https://crbug.com/1164001): remove after +// chromeos/services/secure_channel is moved to namespace ash. +namespace mojom = ::chromeos::secure_channel::mojom; + SecureChannelClientProvider::SecureChannelClientProvider() = default; SecureChannelClientProvider::~SecureChannelClientProvider() = default; @@ -38,5 +41,4 @@ } } // namespace secure_channel - -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h b/chrome/browser/ash/secure_channel/secure_channel_client_provider.h similarity index 70% rename from chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h rename to chrome/browser/ash/secure_channel/secure_channel_client_provider.h index ca82fbb..56cf542 100644 --- a/chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h +++ b/chrome/browser/ash/secure_channel/secure_channel_client_provider.h
@@ -2,20 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_ #include <memory> #include "base/macros.h" #include "base/no_destructor.h" +// TODO(https://crbug.com/1164001): move to forward declaration. +#include "chromeos/services/secure_channel/public/cpp/client/secure_channel_client.h" -namespace chromeos { - +namespace ash { namespace secure_channel { -class SecureChannelClient; - // Singleton that owns a single SecureChannelClient instance associated with the // browser process. class SecureChannelClientProvider { @@ -36,15 +35,14 @@ }; } // namespace secure_channel - -} // namespace chromeos +} // namespace ash // TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos // source migration is finished. -namespace ash { +namespace chromeos { namespace secure_channel { -using ::chromeos::secure_channel::SecureChannelClientProvider; +using ::ash::secure_channel::SecureChannelClientProvider; } -} // namespace ash +} // namespace chromeos -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_SECURE_CHANNEL_CLIENT_PROVIDER_H_
diff --git a/chrome/browser/chromeos/secure_channel/util/histogram_util.cc b/chrome/browser/ash/secure_channel/util/histogram_util.cc similarity index 90% rename from chrome/browser/chromeos/secure_channel/util/histogram_util.cc rename to chrome/browser/ash/secure_channel/util/histogram_util.cc index de5adbc..4ccec32c 100644 --- a/chrome/browser/chromeos/secure_channel/util/histogram_util.cc +++ b/chrome/browser/ash/secure_channel/util/histogram_util.cc
@@ -2,16 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/secure_channel/util/histogram_util.h" +#include "chrome/browser/ash/secure_channel/util/histogram_util.h" #include "base/metrics/histogram_functions.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace util { + namespace { -using location::nearby::connections::mojom::Status; -} // namespace + +using ::location::nearby::connections::mojom::Status; + +} void RecordStartDiscoveryResult(Status status) { base::UmaHistogramEnumeration( @@ -65,4 +68,4 @@ } // namespace util } // namespace secure_channel -} // namespace chromeos +} // namespace ash
diff --git a/chrome/browser/chromeos/secure_channel/util/histogram_util.h b/chrome/browser/ash/secure_channel/util/histogram_util.h similarity index 89% rename from chrome/browser/chromeos/secure_channel/util/histogram_util.h rename to chrome/browser/ash/secure_channel/util/histogram_util.h index fdd3e59..cc3b5ab 100644 --- a/chrome/browser/chromeos/secure_channel/util/histogram_util.h +++ b/chrome/browser/ash/secure_channel/util/histogram_util.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_ -#define CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_ +#ifndef CHROME_BROWSER_ASH_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_ +#define CHROME_BROWSER_ASH_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_ #include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" -namespace chromeos { +namespace ash { namespace secure_channel { namespace util { @@ -65,6 +65,6 @@ } // namespace util } // namespace secure_channel -} // namespace chromeos +} // namespace ash -#endif // CHROME_BROWSER_CHROMEOS_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_ +#endif // CHROME_BROWSER_ASH_SECURE_CHANNEL_UTIL_HISTOGRAM_UTIL_H_
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index fe25b5e..a5c1b86 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -2111,6 +2111,12 @@ "../ash/ownership/owner_settings_service_ash_factory.h", "../ash/pcie_peripheral/ash_usb_detector.cc", "../ash/pcie_peripheral/ash_usb_detector.h", + "../ash/phonehub/browser_tabs_metadata_fetcher_impl.cc", + "../ash/phonehub/browser_tabs_metadata_fetcher_impl.h", + "../ash/phonehub/browser_tabs_model_provider_impl.cc", + "../ash/phonehub/browser_tabs_model_provider_impl.h", + "../ash/phonehub/phone_hub_manager_factory.cc", + "../ash/phonehub/phone_hub_manager_factory.h", "../ash/plugin_vm/plugin_vm_diagnostics.cc", "../ash/plugin_vm/plugin_vm_diagnostics.h", "../ash/plugin_vm/plugin_vm_drive_image_download_service.cc", @@ -2687,6 +2693,22 @@ "../ash/scanning/zeroconf_scanner_detector.h", "../ash/scanning/zeroconf_scanner_detector_utils.cc", "../ash/scanning/zeroconf_scanner_detector_utils.h", + "../ash/secure_channel/nearby_connection_broker.cc", + "../ash/secure_channel/nearby_connection_broker.h", + "../ash/secure_channel/nearby_connection_broker_impl.cc", + "../ash/secure_channel/nearby_connection_broker_impl.h", + "../ash/secure_channel/nearby_connector_factory.cc", + "../ash/secure_channel/nearby_connector_factory.h", + "../ash/secure_channel/nearby_connector_impl.cc", + "../ash/secure_channel/nearby_connector_impl.h", + "../ash/secure_channel/nearby_endpoint_finder.cc", + "../ash/secure_channel/nearby_endpoint_finder.h", + "../ash/secure_channel/nearby_endpoint_finder_impl.cc", + "../ash/secure_channel/nearby_endpoint_finder_impl.h", + "../ash/secure_channel/secure_channel_client_provider.cc", + "../ash/secure_channel/secure_channel_client_provider.h", + "../ash/secure_channel/util/histogram_util.cc", + "../ash/secure_channel/util/histogram_util.h", "../ash/settings/about_flags.cc", "../ash/settings/about_flags.h", "../ash/settings/cros_settings.cc", @@ -3105,12 +3127,6 @@ "note_taking_controller_client.h", "note_taking_helper.cc", "note_taking_helper.h", - "phonehub/browser_tabs_metadata_fetcher_impl.cc", - "phonehub/browser_tabs_metadata_fetcher_impl.h", - "phonehub/browser_tabs_model_provider_impl.cc", - "phonehub/browser_tabs_model_provider_impl.h", - "phonehub/phone_hub_manager_factory.cc", - "phonehub/phone_hub_manager_factory.h", "platform_keys/key_permissions/arc_key_permissions_manager_delegate.cc", "platform_keys/key_permissions/arc_key_permissions_manager_delegate.h", "platform_keys/key_permissions/key_permissions_manager.h", @@ -3175,22 +3191,6 @@ "process_snapshot_server.h", "scheduler_configuration_manager.cc", "scheduler_configuration_manager.h", - "secure_channel/nearby_connection_broker.cc", - "secure_channel/nearby_connection_broker.h", - "secure_channel/nearby_connection_broker_impl.cc", - "secure_channel/nearby_connection_broker_impl.h", - "secure_channel/nearby_connector_factory.cc", - "secure_channel/nearby_connector_factory.h", - "secure_channel/nearby_connector_impl.cc", - "secure_channel/nearby_connector_impl.h", - "secure_channel/nearby_endpoint_finder.cc", - "secure_channel/nearby_endpoint_finder.h", - "secure_channel/nearby_endpoint_finder_impl.cc", - "secure_channel/nearby_endpoint_finder_impl.h", - "secure_channel/secure_channel_client_provider.cc", - "secure_channel/secure_channel_client_provider.h", - "secure_channel/util/histogram_util.cc", - "secure_channel/util/histogram_util.h", "session_length_limiter.cc", "session_length_limiter.h", "set_time_dialog.cc", @@ -3280,6 +3280,12 @@ "extensions/file_system_provider/provider_function.h", "extensions/input_method_api.cc", "extensions/input_method_api.h", + "extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.cc", + "extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h", + "extensions/login_screen/login/cleanup/cleanup_manager.cc", + "extensions/login_screen/login/cleanup/cleanup_manager.h", + "extensions/login_screen/login/cleanup/open_windows_cleanup_handler.cc", + "extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h", "extensions/login_screen/login/login_api.cc", "extensions/login_screen/login/login_api.h", "extensions/login_screen/login/login_api_lock_handler.cc", @@ -3614,6 +3620,10 @@ "../ash/policy/handlers/fake_device_name_policy_handler.h", "../ash/policy/handlers/minimum_version_policy_test_helpers.cc", "../ash/policy/handlers/minimum_version_policy_test_helpers.h", + "../ash/secure_channel/fake_nearby_connection_broker.cc", + "../ash/secure_channel/fake_nearby_connection_broker.h", + "../ash/secure_channel/fake_nearby_endpoint_finder.cc", + "../ash/secure_channel/fake_nearby_endpoint_finder.h", "../ash/settings/scoped_testing_cros_settings.cc", "../ash/settings/scoped_testing_cros_settings.h", "extensions/test_external_cache.cc", @@ -3634,10 +3644,6 @@ "printing/test_cups_printers_manager.h", "printing/test_printer_configurer.cc", "printing/test_printer_configurer.h", - "secure_channel/fake_nearby_connection_broker.cc", - "secure_channel/fake_nearby_connection_broker.h", - "secure_channel/fake_nearby_endpoint_finder.cc", - "secure_channel/fake_nearby_endpoint_finder.h", ] deps = [ @@ -4071,6 +4077,8 @@ "../ash/notifications/update_required_notification_unittest.cc", "../ash/ownership/owner_settings_service_ash_unittest.cc", "../ash/pcie_peripheral/ash_usb_detector_unittest.cc", + "../ash/phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc", + "../ash/phonehub/browser_tabs_model_provider_impl_unittest.cc", "../ash/plugin_vm/mock_plugin_vm_manager.cc", "../ash/plugin_vm/mock_plugin_vm_manager.h", "../ash/plugin_vm/plugin_vm_features_unittest.cc", @@ -4258,6 +4266,9 @@ "../ash/scanning/scanning_file_path_helper_unittest.cc", "../ash/scanning/scanning_type_converters_unittest.cc", "../ash/scanning/zeroconf_scanner_detector_unittest.cc", + "../ash/secure_channel/nearby_connection_broker_impl_unittest.cc", + "../ash/secure_channel/nearby_connector_impl_unittest.cc", + "../ash/secure_channel/nearby_endpoint_finder_impl_unittest.cc", "../ash/settings/cros_settings_unittest.cc", "../ash/settings/device_settings_cache_unittest.cc", "../ash/settings/device_settings_provider_unittest.cc", @@ -4337,6 +4348,9 @@ "extensions/file_manager/system_notification_manager_unittest.cc", "extensions/gfx_utils_unittest.cc", "extensions/install_limiter_unittest.cc", + "extensions/login_screen/login/cleanup/cleanup_manager_unittest.cc", + "extensions/login_screen/login/cleanup/mock_cleanup_handler.cc", + "extensions/login_screen/login/cleanup/mock_cleanup_handler.h", "extensions/login_screen/login/login_api_unittest.cc", "extensions/login_screen/login_screen_ui/ui_handler_unittest.cc", "extensions/login_screen/login_state/login_state_api_unittest.cc", @@ -4395,8 +4409,6 @@ "net/system_proxy_manager_unittest.cc", "network_change_manager_client_unittest.cc", "note_taking_helper_unittest.cc", - "phonehub/browser_tabs_metadata_fetcher_impl_unittest.cc", - "phonehub/browser_tabs_model_provider_impl_unittest.cc", "platform_keys/key_permissions/arc_key_permissions_manager_delegate_unittest.cc", "platform_keys/key_permissions/key_permissions_service_impl_unittest.cc", "preferences_unittest.cc", @@ -4409,9 +4421,6 @@ "process_snapshot_server_unittest.cc", "proxy_config_service_impl_unittest.cc", "scheduler_configuration_manager_unittest.cc", - "secure_channel/nearby_connection_broker_impl_unittest.cc", - "secure_channel/nearby_connector_impl_unittest.cc", - "secure_channel/nearby_endpoint_finder_impl_unittest.cc", "session_length_limiter_unittest.cc", "startup_settings_cache_unittest.cc", "system_token_cert_db_initializer_unittest.cc",
diff --git a/chrome/browser/chromeos/browser_context_keyed_service_factories.cc b/chrome/browser/chromeos/browser_context_keyed_service_factories.cc index 4fd0e17b..8600c9d 100644 --- a/chrome/browser/chromeos/browser_context_keyed_service_factories.cc +++ b/chrome/browser/chromeos/browser_context_keyed_service_factories.cc
@@ -20,6 +20,7 @@ #include "chrome/browser/ash/nearby/nearby_connections_dependencies_provider_factory.h" #include "chrome/browser/ash/nearby/nearby_process_manager_factory.h" #include "chrome/browser/ash/ownership/owner_settings_service_ash_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_engagement_metrics_service.h" #include "chrome/browser/ash/policy/core/user_cloud_policy_token_forwarder_factory.h" #include "chrome/browser/ash/policy/dlp/dlp_rules_manager_factory.h" @@ -28,6 +29,7 @@ #include "chrome/browser/ash/printing/history/print_job_history_service_factory.h" #include "chrome/browser/ash/printing/print_management/printing_manager_factory.h" #include "chrome/browser/ash/printing/synced_printers_manager_factory.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_factory.h" #include "chrome/browser/ash/smb_client/smb_service_factory.h" #include "chrome/browser/ash/web_applications/crosh_loader_factory.h" #include "chrome/browser/chromeos/eche_app/eche_app_manager_factory.h" @@ -37,12 +39,10 @@ #include "chrome/browser/chromeos/extensions/media_player_api.h" #include "chrome/browser/chromeos/extensions/printing_metrics/print_job_finished_event_dispatcher.h" #include "chrome/browser/chromeos/fileapi/file_change_service_factory.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/chromeos/platform_keys/key_permissions/key_permissions_service_factory.h" #include "chrome/browser/chromeos/platform_keys/key_permissions/user_private_token_kpm_service_factory.h" #include "chrome/browser/chromeos/printing/cups_print_job_manager_factory.h" #include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connector_factory.h" #include "chrome/browser/chromeos/tether/tether_service_factory.h" #include "chrome/browser/ui/ash/calendar/calendar_keyed_service_factory.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_factory.h"
diff --git a/chrome/browser/chromeos/eche_app/eche_app_manager_factory.cc b/chrome/browser/chromeos/eche_app/eche_app_manager_factory.cc index 6e38ae5..fefee2e5 100644 --- a/chrome/browser/chromeos/eche_app/eche_app_manager_factory.cc +++ b/chrome/browser/chromeos/eche_app/eche_app_manager_factory.cc
@@ -9,15 +9,16 @@ #include "ash/constants/ash_features.h" #include "base/bind.h" #include "base/metrics/histogram_functions.h" +#include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "base/time/time.h" #include "chrome/browser/ash/device_sync/device_sync_client_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/ash/secure_channel/nearby_connector_factory.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/chromeos/eche_app/eche_app_notification_controller.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" -#include "chrome/browser/chromeos/secure_channel/nearby_connector_factory.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" @@ -68,23 +69,27 @@ void LaunchSystemWebApp(Profile* profile, const std::string& package_name, - const absl::optional<int64_t>& notification_id) { - std::string url; + const absl::optional<int64_t>& notification_id, + const std::u16string& visible_name) { + std::u16string url; // Use hash mark(#) to send params to webui so we don't need to reload the // whole eche window. if (notification_id.has_value()) { - url = "chrome://eche-app/#notification_id="; - url.append(base::NumberToString(notification_id.value())); - url.append("&package_name="); + url = u"chrome://eche-app/#notification_id="; + url.append(base::NumberToString16(notification_id.value())); + url.append(u"&package_name="); } else { - url = "chrome://eche-app/#package_name="; + url = u"chrome://eche-app/#package_name="; } - url.append(package_name); - url.append("×tamp="); + std::u16string u16_package_name = base::UTF8ToUTF16(package_name); + url.append(u16_package_name); + url.append(u"&visible_app_name="); + url.append(visible_name); + url.append(u"×tamp="); double now_seconds = base::Time::Now().ToDoubleT(); int64_t now_ms = static_cast<int64_t>(now_seconds * 1000); - url.append(base::NumberToString(now_ms)); + url.append(base::NumberToString16(now_ms)); web_app::SystemAppLaunchParams params; params.url = GURL(url); web_app::LaunchSystemWebAppAsync(profile, web_app::SystemAppType::ECHE, @@ -93,8 +98,9 @@ void LaunchEcheApp(Profile* profile, const absl::optional<int64_t>& notification_id, - const std::string& package_name) { - LaunchSystemWebApp(profile, package_name, notification_id); + const std::string& package_name, + const std::u16string& visible_name) { + LaunchSystemWebApp(profile, package_name, notification_id, visible_name); base::UmaHistogramEnumeration("Eche.NotificationClicked", NotificationInteraction::kOpenAppStreaming); }
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.cc b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.cc new file mode 100644 index 0000000..a6e4bea --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.cc
@@ -0,0 +1,59 @@ +// 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. + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h" + +#include <utility> + +#include "base/strings/string_number_conversions.h" +#include "base/time/time.h" +#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "content/public/browser/browsing_data_remover.h" + +namespace chromeos { + +BrowsingDataCleanupHandler::BrowsingDataCleanupHandler() = default; + +BrowsingDataCleanupHandler::~BrowsingDataCleanupHandler() = default; + +void BrowsingDataCleanupHandler::Cleanup(CleanupHandlerCallback callback) { + DCHECK(callback_.is_null()); + + Profile* profile = ProfileManager::GetActiveUserProfile(); + if (!profile) { + std::move(callback).Run( + "Browsing data cleanup error: There is no active user"); + return; + } + + callback_ = std::move(callback); + + remover_ = profile->GetBrowsingDataRemover(); + remover_->AddObserver(this); + + remover_->RemoveAndReply( + base::Time(), base::Time::Max(), + chrome_browsing_data_remover::ALL_DATA_TYPES, + content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB | + content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, + this); +} + +void BrowsingDataCleanupHandler::OnBrowsingDataRemoverDone( + uint64_t failed_data_types) { + remover_->RemoveObserver(this); + + if (failed_data_types == 0) { + std::move(callback_).Run(absl::nullopt); + return; + } + + std::move(callback_).Run( + "Browsing data cleanup error: Failed to cleanup all data with flag: " + + base::NumberToString(failed_data_types)); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h new file mode 100644 index 0000000..ffab3dd --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h
@@ -0,0 +1,37 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_BROWSING_DATA_CLEANUP_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_BROWSING_DATA_CLEANUP_HANDLER_H_ + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h" +#include "content/public/browser/browsing_data_remover.h" + +namespace chromeos { + +// A cleanup handler which clears the profile's browsing data using +// `BrowsingDataRemover`. See `chrome_browsing_data_remover::ALL_DATA_TYPES` +// for the list of data types removed. +// TODO(jityao, b:200678974) Add browser tests. +class BrowsingDataCleanupHandler + : public CleanupHandler, + public content::BrowsingDataRemover::Observer { + public: + BrowsingDataCleanupHandler(); + ~BrowsingDataCleanupHandler() override; + + // CleanupHandler: + void Cleanup(CleanupHandlerCallback callback) override; + + // content::BrowsingDataRemover::Observer: + void OnBrowsingDataRemoverDone(uint64_t failed_data_types) override; + + private: + content::BrowsingDataRemover* remover_; + CleanupHandlerCallback callback_; +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_BROWSING_DATA_CLEANUP_HANDLER_H_
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h new file mode 100644 index 0000000..7b9cb082 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h
@@ -0,0 +1,30 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_HANDLER_H_ + +#include "base/callback.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace chromeos { + +// A handler which is owned by `CleanupManager`. Each `CleanupHandler` is +// in charge of a separate cleanup step. +class CleanupHandler { + public: + using CleanupHandlerCallback = base::OnceCallback<void( + const absl::optional<std::string>& error_message)>; + // `callback` is called after handler has finished its cleanup step. + // `callback` must be called exactly once or there will be a memory leak. The + // handler can assume that `CleanupManager` will not call `Cleanup` before + // the current cleanup step has finished. + virtual void Cleanup(CleanupHandlerCallback callback) = 0; + + virtual ~CleanupHandler() = default; +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_HANDLER_H_
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.cc b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.cc new file mode 100644 index 0000000..57dd710 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.cc
@@ -0,0 +1,96 @@ +// 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. + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h" + +#include <utility> + +#include "base/barrier_closure.h" +#include "base/bind.h" +#include "base/strings/string_util.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/browsing_data_cleanup_handler.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h" + +#include "base/logging.h" + +namespace chromeos { + +// static +CleanupManager* CleanupManager::Get() { + static base::NoDestructor<CleanupManager> instance; + return instance.get(); +} + +CleanupManager::CleanupManager() { + InitializeCleanupHandlers(); +} + +CleanupManager::~CleanupManager() = default; + +void CleanupManager::Cleanup(CleanupCallback callback) { + if (is_cleanup_in_progress_) { + std::move(callback).Run("Cleanup is already in progress"); + return; + } + + callback_ = std::move(callback); + errors_.clear(); + is_cleanup_in_progress_ = true; + + base::RepeatingClosure barrier_closure = base::BarrierClosure( + cleanup_handlers_.size(), + base::BindOnce(&CleanupManager::OnAllCleanupHandlersDone, + base::Unretained(this))); + + for (auto& handler : cleanup_handlers_) { + handler->Cleanup(base::BindOnce(&CleanupManager::OnCleanupHandlerDone, + base::Unretained(this), barrier_closure)); + } +} + +void CleanupManager::SetCleanupHandlersForTesting( + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers) { + cleanup_handlers_.swap(cleanup_handlers); +} + +void CleanupManager::ResetCleanupHandlersForTesting() { + cleanup_handlers_.clear(); + is_cleanup_in_progress_ = false; + InitializeCleanupHandlers(); +} + +void CleanupManager::SetIsCleanupInProgressForTesting( + bool is_cleanup_in_progress) { + is_cleanup_in_progress_ = is_cleanup_in_progress; +} + +void CleanupManager::InitializeCleanupHandlers() { + cleanup_handlers_.emplace_back( + std::make_unique<BrowsingDataCleanupHandler>()); + cleanup_handlers_.emplace_back(std::make_unique<OpenWindowsCleanupHandler>()); +} + +void CleanupManager::OnCleanupHandlerDone( + base::RepeatingClosure barrier_closure, + const absl::optional<std::string>& error) { + if (error) { + errors_.push_back(*error); + } + + std::move(barrier_closure).Run(); +} + +void CleanupManager::OnAllCleanupHandlersDone() { + is_cleanup_in_progress_ = false; + + if (errors_.empty()) { + std::move(callback_).Run(absl::nullopt); + return; + } + + std::string errors = base::JoinString(errors_, "\n"); + std::move(callback_).Run(errors); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h new file mode 100644 index 0000000..abda802 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h
@@ -0,0 +1,65 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_MANAGER_H_ +#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_MANAGER_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "base/callback.h" +#include "base/callback_forward.h" +#include "base/no_destructor.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace chromeos { + +// A singleton which manages the cleanup handlers. +class CleanupManager { + public: + static CleanupManager* Get(); + + CleanupManager(const CleanupManager&) = delete; + CleanupManager& operator=(const CleanupManager&) = delete; + + using CleanupCallback = base::OnceCallback<void(absl::optional<std::string>)>; + // Calls the cleanup handlers and runs `callback` when the cleanup has + // finished. After `Cleanup` is called and before `callback` is run, + // `is_cleanup_in_progress()` returns true. Fails if there is another cleanup + // already in progress. + void Cleanup(CleanupCallback callback); + + bool is_cleanup_in_progress() const { return is_cleanup_in_progress_; } + + void SetCleanupHandlersForTesting( + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers); + + void ResetCleanupHandlersForTesting(); + + void SetIsCleanupInProgressForTesting(bool is_cleanup_in_progress); + + private: + friend class base::NoDestructor<CleanupManager>; + + CleanupManager(); + ~CleanupManager(); + + void InitializeCleanupHandlers(); + + void OnCleanupHandlerDone(base::RepeatingClosure barrier_closure, + const absl::optional<std::string>& error); + + void OnAllCleanupHandlersDone(); + + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers_; + std::vector<std::string> errors_; + bool is_cleanup_in_progress_ = false; + CleanupCallback callback_; +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_CLEANUP_MANAGER_H_
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager_unittest.cc b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager_unittest.cc new file mode 100644 index 0000000..7ac19f1 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager_unittest.cc
@@ -0,0 +1,132 @@ +// 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. + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h" + +#include <utility> + +#include "base/barrier_closure.h" +#include "base/callback_forward.h" +#include "base/callback_helpers.h" +#include "base/run_loop.h" +#include "base/test/bind.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h" +#include "content/public/test/browser_task_environment.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::_; +using testing::Invoke; +using testing::WithArg; + +namespace chromeos { + +class CleanupManagerUnittest : public testing::Test { + public: + CleanupManagerUnittest() = default; + ~CleanupManagerUnittest() override = default; + + void TearDown() override { + CleanupManager::Get()->ResetCleanupHandlersForTesting(); + testing::Test::TearDown(); + } + + content::BrowserTaskEnvironment task_environment_; +}; + +TEST_F(CleanupManagerUnittest, Cleanup) { + auto no_error_callback = [](CleanupHandler::CleanupHandlerCallback callback) { + std::move(callback).Run(absl::nullopt); + }; + std::unique_ptr<MockCleanupHandler> mock_cleanup_handler1 = + std::make_unique<MockCleanupHandler>(); + EXPECT_CALL(*mock_cleanup_handler1, Cleanup(_)) + .WillOnce(WithArg<0>(Invoke(no_error_callback))); + std::unique_ptr<MockCleanupHandler> mock_cleanup_handler2 = + std::make_unique<MockCleanupHandler>(); + EXPECT_CALL(*mock_cleanup_handler2, Cleanup(_)) + .WillOnce(WithArg<0>(Invoke(no_error_callback))); + + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers; + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler1)); + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler2)); + CleanupManager* manager = CleanupManager::Get(); + manager->SetCleanupHandlersForTesting(std::move(cleanup_handlers)); + + base::RunLoop run_loop; + manager->Cleanup( + base::BindLambdaForTesting([&](absl::optional<std::string> error) { + EXPECT_EQ(absl::nullopt, error); + run_loop.QuitClosure().Run(); + })); + run_loop.Run(); +} + +TEST_F(CleanupManagerUnittest, CleanupInProgress) { + std::unique_ptr<MockCleanupHandler> mock_cleanup_handler = + std::make_unique<MockCleanupHandler>(); + CleanupHandler::CleanupHandlerCallback callback; + EXPECT_CALL(*mock_cleanup_handler, Cleanup(_)) + .WillOnce(WithArg<0>(Invoke( + ([&callback](CleanupHandler::CleanupHandlerCallback callback_arg) { + callback = std::move(callback_arg); + })))); + + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers; + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler)); + CleanupManager* manager = CleanupManager::Get(); + manager->SetCleanupHandlersForTesting(std::move(cleanup_handlers)); + + base::RunLoop run_loop; + base::RepeatingClosure barrier_closure = + base::BarrierClosure(2, run_loop.QuitClosure()); + + manager->Cleanup( + base::BindLambdaForTesting([&](absl::optional<std::string> error) { + EXPECT_EQ(absl::nullopt, error); + barrier_closure.Run(); + })); + + manager->Cleanup( + base::BindLambdaForTesting([&](absl::optional<std::string> error) { + EXPECT_EQ("Cleanup is already in progress", *error); + barrier_closure.Run(); + })); + + std::move(callback).Run(absl::nullopt); + run_loop.Run(); +} + +TEST_F(CleanupManagerUnittest, CleanupErrors) { + std::unique_ptr<MockCleanupHandler> mock_cleanup_handler1 = + std::make_unique<MockCleanupHandler>(); + EXPECT_CALL(*mock_cleanup_handler1, Cleanup(_)) + .WillOnce(WithArg<0>( + Invoke([](CleanupHandler::CleanupHandlerCallback callback) { + std::move(callback).Run("Handler 1 error"); + }))); + std::unique_ptr<MockCleanupHandler> mock_cleanup_handler2 = + std::make_unique<MockCleanupHandler>(); + EXPECT_CALL(*mock_cleanup_handler2, Cleanup(_)) + .WillOnce(WithArg<0>( + Invoke([](CleanupHandler::CleanupHandlerCallback callback) { + std::move(callback).Run("Handler 2 error"); + }))); + + std::vector<std::unique_ptr<CleanupHandler>> cleanup_handlers; + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler1)); + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler2)); + CleanupManager* manager = CleanupManager::Get(); + manager->SetCleanupHandlersForTesting(std::move(cleanup_handlers)); + + base::RunLoop run_loop; + manager->Cleanup( + base::BindLambdaForTesting([&](absl::optional<std::string> error) { + EXPECT_EQ("Handler 1 error\nHandler 2 error", *error); + run_loop.QuitClosure().Run(); + })); + run_loop.Run(); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.cc b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.cc new file mode 100644 index 0000000..a2e70e1 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.cc
@@ -0,0 +1,13 @@ +// 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. + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h" + +namespace chromeos { + +MockCleanupHandler::MockCleanupHandler() = default; + +MockCleanupHandler::~MockCleanupHandler() = default; + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h new file mode 100644 index 0000000..a3d794842 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h
@@ -0,0 +1,27 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_MOCK_CLEANUP_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_MOCK_CLEANUP_HANDLER_H_ + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace chromeos { + +class MockCleanupHandler : public CleanupHandler { + public: + MockCleanupHandler(); + + MockCleanupHandler(const MockCleanupHandler&) = delete; + MockCleanupHandler& operator=(const MockCleanupHandler&) = delete; + + ~MockCleanupHandler() override; + + MOCK_METHOD(void, Cleanup, (CleanupHandlerCallback callback), (override)); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_MOCK_CLEANUP_HANDLER_H_
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.cc b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.cc new file mode 100644 index 0000000..01e0230 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.cc
@@ -0,0 +1,46 @@ +// 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. + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h" + +#include "base/bind.h" +#include "base/files/file_path.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/browser_list.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace chromeos { + +OpenWindowsCleanupHandler::OpenWindowsCleanupHandler() = default; + +OpenWindowsCleanupHandler::~OpenWindowsCleanupHandler() = default; + +void OpenWindowsCleanupHandler::Cleanup(CleanupHandlerCallback callback) { + DCHECK(callback_.is_null()); + + Profile* profile = ProfileManager::GetActiveUserProfile(); + if (!profile) { + std::move(callback).Run( + "Open windows cleanup error: There is no active user"); + return; + } + + callback_ = std::move(callback); + + // `on_close_aborted` cannot be reached since `skip_beforeunload` is true. + BrowserList::CloseAllBrowsersWithProfile( + profile, + /*on_close_success=*/ + base::BindRepeating(&OpenWindowsCleanupHandler::OnCloseDone, + base::Unretained(this)), + /*on_close_aborted=*/BrowserList::CloseCallback(), + /*skip_beforeunload=*/true); +} + +void OpenWindowsCleanupHandler::OnCloseDone(const base::FilePath& file_path) { + std::move(callback_).Run(absl::nullopt); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h new file mode 100644 index 0000000..59c8ae2 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/cleanup/open_windows_cleanup_handler.h
@@ -0,0 +1,36 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_OPEN_WINDOWS_CLEANUP_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_OPEN_WINDOWS_CLEANUP_HANDLER_H_ + +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_handler.h" + +namespace base { +class FilePath; +} + +namespace chromeos { + +// A cleanup handler which closes all open browser windows. Windows created by +// the chrome.app.window are not closed but they will be handled separately by +// the extension and app cleanup handler. +// TODO(jityao, b:200678974) Add browser tests. +class OpenWindowsCleanupHandler : public CleanupHandler { + public: + OpenWindowsCleanupHandler(); + ~OpenWindowsCleanupHandler() override; + + // CleanupHandler: + void Cleanup(CleanupHandlerCallback callback) override; + + private: + void OnCloseDone(const base::FilePath& file_path); + + CleanupHandlerCallback callback_; +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_CLEANUP_OPEN_WINDOWS_CLEANUP_HANDLER_H_
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/login_api_unittest.cc b/chrome/browser/chromeos/extensions/login_screen/login/login_api_unittest.cc index 8deb440..434c268 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login/login_api_unittest.cc +++ b/chrome/browser/chromeos/extensions/login_screen/login/login_api_unittest.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/callback.h" +#include "base/callback_helpers.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" @@ -19,6 +20,8 @@ #include "chrome/browser/ash/login/users/fake_chrome_user_manager.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h" #include "chrome/browser/chromeos/extensions/login_screen/login/login_api_lock_handler.h" #include "chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h" #include "chrome/browser/extensions/extension_api_unittest.h" @@ -46,6 +49,7 @@ using testing::Invoke; using testing::Return; using testing::SaveArg; +using testing::StrictMock; namespace { @@ -524,6 +528,8 @@ GetCrosSettingsHelper()->ReplaceDeviceSettingsProviderWithStub(); GetCrosSettingsHelper()->SetBoolean( ash::kDeviceRestrictedManagedGuestSessionEnabled, true); + // Remove cleanup handlers. + chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting({}); LoginApiUnittest::SetUp(); } @@ -531,11 +537,49 @@ void TearDown() override { GetCrosSettingsHelper()->RestoreRealDeviceSettingsProvider(); chromeos::SharedSessionHandler::Get()->ResetStateForTesting(); + chromeos::CleanupManager::Get()->ResetCleanupHandlersForTesting(); testing_profile_.reset(); LoginApiUnittest::TearDown(); } + void SetUpCleanupHandlerMocks( + absl::optional<std::string> error1 = absl::nullopt, + absl::optional<std::string> error2 = absl::nullopt) { + std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler1 = + std::make_unique<StrictMock<chromeos::MockCleanupHandler>>(); + EXPECT_CALL(*mock_cleanup_handler1, Cleanup(_)) + .WillOnce(Invoke( + ([error1]( + chromeos::CleanupHandler::CleanupHandlerCallback callback) { + std::move(callback).Run(error1); + }))); + std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler2 = + std::make_unique<StrictMock<chromeos::MockCleanupHandler>>(); + EXPECT_CALL(*mock_cleanup_handler2, Cleanup(_)) + .WillOnce(Invoke( + ([error2]( + chromeos::CleanupHandler::CleanupHandlerCallback callback) { + std::move(callback).Run(error2); + }))); + + std::vector<std::unique_ptr<chromeos::CleanupHandler>> cleanup_handlers; + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler1)); + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler2)); + chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting( + std::move(cleanup_handlers)); + } + + void SetUpCleanupHandlerMockNotCalled() { + std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler = + std::make_unique<chromeos::MockCleanupHandler>(); + EXPECT_CALL(*mock_cleanup_handler, Cleanup(_)).Times(0); + std::vector<std::unique_ptr<chromeos::CleanupHandler>> cleanup_handlers; + cleanup_handlers.emplace_back(std::move(mock_cleanup_handler)); + chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting( + std::move(cleanup_handlers)); + } + void LaunchSharedManagedGuestSession(const std::string& password) { SetExtensionWithId(kExtensionId); EXPECT_CALL(*mock_existing_user_controller_, @@ -760,9 +804,24 @@ "[\"foo\"]")); } +// Test that calling `login.unlockSharedSession()` returns an error when there +// is a cleanup in progress. +TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionCleanupInProgress) { + LaunchSharedManagedGuestSession("foo"); + session_manager::SessionManager::Get()->SetSessionState( + session_manager::SessionState::LOCKED); + + chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true); + + ASSERT_EQ(login_api_errors::kCleanupInProgress, + RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(), + "[\"foo\"]")); +} + // Test that calling `login.endSharedSession()` clears the user hash and salt // and locks the screen when the screen is not locked. TEST_F(LoginApiSharedSessionUnittest, EndSharedSession) { + SetUpCleanupHandlerMocks(); LaunchSharedManagedGuestSession("foo"); EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return()); @@ -778,6 +837,7 @@ // Test that calling `login.endSharedSession()` works on the lock screen as // well. TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionLocked) { + SetUpCleanupHandlerMocks(); LaunchSharedManagedGuestSession("foo"); session_manager::SessionManager::Get()->SetSessionState( @@ -793,9 +853,25 @@ EXPECT_EQ("", handler->GetUserSecretSaltForTesting()); } +// Test that calling `login.endSharedSession()` returns an error when the there +// is an error in the cleanup handlers. +TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionCleanupError) { + std::string error1 = "Mock cleanup handler 1 error"; + std::string error2 = "Mock cleanup handler 2 error"; + SetUpCleanupHandlerMocks(error1, error2); + LaunchSharedManagedGuestSession("foo"); + + EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return()); + + ASSERT_EQ( + error1 + "\n" + error2, + RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]")); +} + // Test that calling `login.endSharedSession()` returns an error when no shared // MGS was launched. TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionNoSharedMGS) { + SetUpCleanupHandlerMockNotCalled(); ASSERT_EQ( login_api_errors::kNoSharedMGSFound, RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]")); @@ -804,6 +880,7 @@ // Test that calling `login.endSharedSession()` returns an error when there is // no shared session active. TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionNoSharedSession) { + SetUpCleanupHandlerMocks(); LaunchSharedManagedGuestSession("foo"); RunFunction(new LoginEndSharedSessionFunction(), "[]"); @@ -812,9 +889,21 @@ RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]")); } +// Test that calling `login.endSharedSession()` returns an error when there +// is a cleanup in progress. +TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionCleanupInProgress) { + LaunchSharedManagedGuestSession("foo"); + chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true); + + ASSERT_EQ(login_api_errors::kCleanupInProgress, + RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), + "[\"foo\"]")); +} + // Test that calling `login.enterSharedSession()` with a password sets the user // hash and salt. TEST_F(LoginApiSharedSessionUnittest, EnterSharedSession) { + SetUpCleanupHandlerMocks(); LaunchSharedManagedGuestSession("foo"); RunFunction(new LoginEndSharedSessionFunction(), "[]"); session_manager::SessionManager::Get()->SetSessionState( @@ -893,8 +982,23 @@ "[\"foo\"]")); } +// Test that calling `login.enterSharedSession()` returns an error when there +// is a cleanup in progress. +TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionCleanupInProgress) { + LaunchSharedManagedGuestSession("foo"); + RunFunction(new LoginEndSharedSessionFunction(), "[]"); + session_manager::SessionManager::Get()->SetSessionState( + session_manager::SessionState::LOCKED); + chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true); + + ASSERT_EQ(login_api_errors::kCleanupInProgress, + RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(), + "[\"foo\"]")); +} + // Test the full shared session flow. TEST_F(LoginApiSharedSessionUnittest, SharedSessionFlow) { + SetUpCleanupHandlerMocks(); LaunchSharedManagedGuestSession("foo"); chromeos::SharedSessionHandler* handler =
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.cc b/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.cc index 114af84..41654da 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.cc +++ b/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "chrome/browser/ash/login/existing_user_controller.h" #include "chrome/browser/ash/settings/cros_settings.h" +#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h" #include "chrome/browser/chromeos/extensions/login_screen/login/login_api.h" #include "chrome/browser/chromeos/extensions/login_screen/login/login_api_lock_handler.h" #include "chrome/browser/ui/ash/session_controller_client_impl.h" @@ -131,7 +132,7 @@ CHECK(user_secret_salt_.empty()); - if (cleanup_in_progress_) { + if (chromeos::CleanupManager::Get()->is_cleanup_in_progress()) { std::move(callback).Run(extensions::login_api_errors::kCleanupInProgress); return; } @@ -148,7 +149,7 @@ } UnlockWithSessionSecret( - base::BindOnce(&SharedSessionHandler::OnAuthenticateComplete, + base::BindOnce(&SharedSessionHandler::OnAuthenticateDone, base::Unretained(this), std::move(callback))); } @@ -174,7 +175,7 @@ CHECK(!user_secret_salt_.empty()); - if (cleanup_in_progress_) { + if (chromeos::CleanupManager::Get()->is_cleanup_in_progress()) { std::move(callback).Run(extensions::login_api_errors::kCleanupInProgress); return; } @@ -205,7 +206,7 @@ } UnlockWithSessionSecret( - base::BindOnce(&SharedSessionHandler::OnAuthenticateComplete, + base::BindOnce(&SharedSessionHandler::OnAuthenticateDone, base::Unretained(this), std::move(callback))); } @@ -222,7 +223,8 @@ return; } - if (cleanup_in_progress_) { + chromeos::CleanupManager* cleanup_manager = chromeos::CleanupManager::Get(); + if (cleanup_manager->is_cleanup_in_progress()) { std::move(callback).Run(extensions::login_api_errors::kCleanupInProgress); return; } @@ -235,13 +237,13 @@ user_secret_hash_.clear(); user_secret_salt_.clear(); - // TODO(crbug.com/1229170): Implement cleanup. if (session_state != session_manager::SessionState::LOCKED) { LoginApiLockHandler::Get()->RequestLockScreen(); } - cleanup_in_progress_ = false; - std::move(callback).Run(absl::nullopt); + cleanup_manager->Cleanup(base::BindOnce(&SharedSessionHandler::OnCleanupDone, + base::Unretained(this), + std::move(callback))); } const std::string& SharedSessionHandler::GetSessionSecretForTesting() const { @@ -304,7 +306,7 @@ return true; } -void SharedSessionHandler::OnAuthenticateComplete( +void SharedSessionHandler::OnAuthenticateDone( CallbackWithOptionalError callback, bool auth_success) { if (!auth_success) { @@ -315,6 +317,16 @@ std::move(callback).Run(absl::nullopt); } +void SharedSessionHandler::OnCleanupDone(CallbackWithOptionalError callback, + absl::optional<std::string> errors) { + if (errors) { + std::move(callback).Run(*errors); + return; + } + + std::move(callback).Run(absl::nullopt); +} + std::string SharedSessionHandler::GenerateRandomString(size_t size) { char random_bytes[size]; crypto::RandBytes(random_bytes, size);
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h b/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h index c3e82db..5643b39 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h +++ b/chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h
@@ -73,15 +73,17 @@ bool CreateAndSetUserSecretHashAndSalt(const std::string& password); - void OnAuthenticateComplete(CallbackWithOptionalError callback, - bool auth_success); + void OnAuthenticateDone(CallbackWithOptionalError callback, + bool auth_success); + + void OnCleanupDone(CallbackWithOptionalError callback, + absl::optional<std::string> errors); std::string GenerateRandomString(size_t size); std::string session_secret_; std::string user_secret_hash_; std::string user_secret_salt_; - bool cleanup_in_progress_ = false; }; } // namespace chromeos
diff --git a/chrome/browser/chromeos/tether/tether_service_factory.cc b/chrome/browser/chromeos/tether/tether_service_factory.cc index 8754c62..316e998 100644 --- a/chrome/browser/chromeos/tether/tether_service_factory.cc +++ b/chrome/browser/chromeos/tether/tether_service_factory.cc
@@ -10,7 +10,7 @@ #include "base/strings/string_number_conversions.h" #include "chrome/browser/ash/device_sync/device_sync_client_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/chromeos/tether/fake_tether_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" @@ -71,7 +71,7 @@ chromeos::PowerManagerClient::Get(), ash::device_sync::DeviceSyncClientFactory::GetForProfile( Profile::FromBrowserContext(context)), - chromeos::secure_channel::SecureChannelClientProvider::GetInstance() + ash::secure_channel::SecureChannelClientProvider::GetInstance() ->GetClient(), ash::multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile( Profile::FromBrowserContext(context)), @@ -91,7 +91,7 @@ Profile::FromBrowserContext(context), chromeos::PowerManagerClient::Get(), ash::device_sync::DeviceSyncClientFactory::GetForProfile( Profile::FromBrowserContext(context)), - chromeos::secure_channel::SecureChannelClientProvider::GetInstance() + ash::secure_channel::SecureChannelClientProvider::GetInstance() ->GetClient(), ash::multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile( Profile::FromBrowserContext(context)),
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index e61c730..5a496ac 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -724,6 +724,13 @@ continue; } + // We aren't yet including the new sec-ch-device-memory, sec-ch-dpr, + // sec-ch-width, sec-ch-viewport-width + if (header == "sec-ch-device-memory" || header == "sec-ch-dpr" || + header == "sec-ch-width" || header == "sec-ch-viewport-width") { + continue; + } + EXPECT_EQ(expect_client_hints, base::Contains(request.headers, header)); } }
diff --git a/chrome/browser/content_settings/content_settings_manager_delegate.cc b/chrome/browser/content_settings/content_settings_manager_delegate.cc index ffe4ae01..118f431 100644 --- a/chrome/browser/content_settings/content_settings_manager_delegate.cc +++ b/chrome/browser/content_settings/content_settings_manager_delegate.cc
@@ -9,6 +9,7 @@ #include "chrome/browser/profiles/profile.h" #include "components/content_settings/browser/page_specific_content_settings.h" #include "components/content_settings/core/browser/cookie_settings.h" +#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_features.h" #include "extensions/buildflags/buildflags.h" @@ -96,13 +97,21 @@ StorageType::FILE_SYSTEM && extensions::WebViewRendererState::GetInstance()->IsGuest( render_process_id)) { - content::RunOrPostTaskOnThread( - FROM_HERE, content::BrowserThread::UI, + base::OnceClosure task = base::BindOnce(&OnFileSystemAccessedInGuestView, render_process_id, render_frame_id, url, allowed, base::BindOnce(&RunOrPostTaskOnSequence, base::SequencedTaskRunnerHandle::Get(), - std::move(*callback)))); + std::move(*callback))); + // We may or may not be on the UI thread depending on whether the + // NavigationThreadingOptimizations feature is enabled. + // TODO(https://crbug.com/1187753): Clean this up once the feature is + // shipped and the code path is removed. + if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) + std::move(task).Run(); + else + content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(task)); + return true; } #endif
diff --git a/chrome/browser/extensions/content_verifier_browsertest.cc b/chrome/browser/extensions/content_verifier_browsertest.cc index 8ce077ab..6283853 100644 --- a/chrome/browser/extensions/content_verifier_browsertest.cc +++ b/chrome/browser/extensions/content_verifier_browsertest.cc
@@ -598,10 +598,9 @@ base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedTempDir temp_dir; - base::FilePath test_dir = - test_data_dir_.AppendASCII("content_verifier/missing_verified_contents"); - base::FilePath extension_dir = test_dir.AppendASCII("source"); - base::FilePath resource_path = base::FilePath().AppendASCII("script.js"); + base::FilePath extension_dir = + test_data_dir_.AppendASCII("content_verifier/storage_permission"); + base::FilePath resource_path = base::FilePath().AppendASCII("background.js"); extensions::content_verifier_test_utils::TestExtensionBuilder verified_contents_builder; @@ -644,15 +643,13 @@ InstallationFailureForCrxWithMalformedVerifiedContentsInjectedInHeader) { base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedTempDir temp_dir; - base::FilePath test_dir = - test_data_dir_.AppendASCII("content_verifier/missing_verified_contents"); + base::FilePath test_dir = test_data_dir_.AppendASCII("content_verifier/v1"); std::string extension_id; std::string verified_contents = "Not a valid verified contents, not even a valid JSON."; base::FilePath crx_path; ASSERT_TRUE(CreateCrxWithVerifiedContentsInHeader( - &temp_dir, test_dir.AppendASCII("source"), verified_contents, - &extension_id, &crx_path)); + &temp_dir, test_dir, verified_contents, &extension_id, &crx_path)); const Extension* extension = InstallExtensionFromWebstore(crx_path, 0); EXPECT_FALSE(extension); @@ -663,15 +660,15 @@ IN_PROC_BROWSER_TEST_F(ContentVerifierTest, VerificationFailureForMissingVerifiedContents) { base::ScopedAllowBlockingForTesting allow_blocking; - base::FilePath unpacked_path = test_data_dir_.AppendASCII( - "content_verifier/missing_verified_contents/source"); + base::FilePath unpacked_path = + test_data_dir_.AppendASCII("content_verifier/storage_permission"); base::FilePath crx_path = PackExtension(unpacked_path); ASSERT_TRUE(base::PathExists(crx_path.DirName().AppendASCII("temp.pem"))); const std::string extension_id = GetExtensionIdFromPrivateKeyFile( crx_path.DirName().AppendASCII("temp.pem")); TestContentVerifySingleJobObserver observer( - extension_id, base::FilePath().AppendASCII("script.js")); + extension_id, base::FilePath().AppendASCII("background.js")); const Extension* extension = InstallExtensionFromWebstore(crx_path, 1); ASSERT_TRUE(extension);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 2d6bd563..bcd3541 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -139,16 +139,6 @@ "expiry_milestone": 97 }, { - "name": "android-multiple-display", - "owners": [ "lazzzis@google.com", "twellington" ], - "expiry_milestone": 87 - }, - { - "name": "android-partner-customization-phenotype", - "owners": [ "bttk" ], - "expiry_milestone": 90 - }, - { "name": "android-picture-in-picture-api", "owners": [ "steimel", "jazzhsu", "media-dev" ], "expiry_milestone": 100 @@ -489,16 +479,6 @@ "expiry_milestone": 82 }, { - "name": "autofill-save-card-infobar-edit-support", - "owners": [ "sczs", "bling-flags@google.com" ], - "expiry_milestone": 84 - }, - { - "name": "autofill-show-all-profiles-on-prefilled-forms", - "owners": [ "olivierrobin", "bling-flags@google.com" ], - "expiry_milestone": 86 - }, - { "name":"autofill-suggest-virtual-cards-on-incomplete-form", "owners": ["siashah", "siyua"], "expiry_milestone":98 @@ -1358,11 +1338,6 @@ "expiry_milestone": 98 }, { - "name": "edit-bookmarks-ios", - "owners": [ "edchin", "rohitrao", "bling-flags@google.com" ], - "expiry_milestone": 90 - }, - { "name": "edit-passwords-in-settings", "owners": [ "fhorschig", "ioanap", "kazinova" ], "expiry_milestone": 98 @@ -1388,11 +1363,6 @@ "expiry_milestone": 95 }, { - "name": "enable-ambient-mode", - "owners": [ "croissant-eng" ], - "expiry_milestone": 88 - }, - { "name": "enable-android-dark-search", "owners": [ "wylieb", "twellington", "fgorski" ], "expiry_milestone": 95 @@ -1403,11 +1373,6 @@ "expiry_milestone": 95 }, { - "name": "enable-android-night-mode-tab-reparenting", - "owners": [ "wylieb", "twellington", "tedchoc" ], - "expiry_milestone": 88 - }, - { "name": "enable-app-discovery-for-oobe", "owners": [ "melzhang", "tsergeant", "chromeos-apps-foundation-team" ], "expiry_milestone": 100 @@ -1448,11 +1413,6 @@ "expiry_milestone": 88 }, { - "name": "enable-assistant-media-session-integration", - "owners": [ "croissant-eng" ], - "expiry_milestone": 88 - }, - { "name": "enable-assistant-routines", "owners": [ "croissant-eng" ], "expiry_milestone": 82 @@ -1463,11 +1423,6 @@ "expiry_milestone": 88 }, { - "name": "enable-assistant-timers-v2", - "owners": ["croissant-eng"], - "expiry_milestone": 88 - }, - { "name": "enable-async-dns", "owners": [ "ericorth", "net-dev" ], "expiry_milestone": 81 @@ -1531,11 +1486,6 @@ "expiry_milestone": 95 }, { - "name": "enable-autofill-password-reauth-ios", - "owners": [ "javierrobles", "bling-flags@google.com" ], - "expiry_milestone": 90 - }, - { "name": "enable-autofill-refresh-style", "owners": [ "tmartino@chromium.org" ], "expiry_milestone": 78 @@ -1777,16 +1727,6 @@ "expiry_milestone": 99 }, { - "name": "enable-defer-all-script", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 90 - }, - { - "name": "enable-defer-all-script-without-optimization-hints", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 90 - }, - { "name": "enable-desktop-pwas-additional-windowing-controls", "owners": [ "laurila@google.com", "isandrk@chromium.org", "desktop-pwas-team@google.com" ], "expiry_milestone": 101 @@ -2231,16 +2171,6 @@ "expiry_milestone": 96 }, { - "name": "enable-mark-http-as", - "owners": [ "cthomp", "estark" ], - "expiry_milestone": 86 - }, - { - "name": "enable-md-rounded-corners-on-dialogs", - "owners": [ "tluk" ], - "expiry_milestone": 90 - }, - { "name": "enable-media-feeds", "owners": [ "beccahughes", "media-dev" ], "expiry_milestone": 90 @@ -2305,6 +2235,11 @@ "expiry_milestone": 90 }, { + "name": "enable-new-download-api", + "owners": [ "sdefresne", "bling-flags@google.com" ], + "expiry_milestone": 130 + }, + { "name": "enable-new-download-backend", "owners": [ "shaktisahu", "dtrainor" ], "expiry_milestone": 97 @@ -2472,11 +2407,6 @@ "expiry_milestone": 96 }, { - "name": "enable-previews-coin-flip", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 90 - }, - { "name": "enable-process-sharing-with-default-site-instances", "owners": [ "creis" ], "expiry_milestone": 81 @@ -2995,11 +2925,6 @@ "expiry_milestone": 94 }, { - "name": "enhanced_clipboard_simple_render", - "owners":["newcomer@chromium.org", "gzadina@google.com"], - "expiry_milestone": 90 - }, - { "name": "enhanced-network-voices", "owners": ["joelriley@google.com", "leileilei@google.com", "dmazzoni"], "expiry_milestone": 95 @@ -3055,11 +2980,6 @@ "expiry_milestone": 95 }, { - "name": "extension-checkup", - "owners": [ "archanasimha" ], - "expiry_milestone": 82 - }, - { "name": "extension-content-verification", "owners": [ "//extensions/OWNERS" ], "expiry_milestone": 86 @@ -3568,11 +3488,6 @@ "expiry_milestone": 95 }, { - "name": "ios-lookalike-url-navigation-suggestions-ui", - "owners": [ "livvielin", "bling-flags@google.com" ], - "expiry_milestone": 89 - }, - { "name": "ios-persist-crash-restore-infobar", "owners": [ "thegreenfrog", "bling-flags@google.com" ], "expiry_milestone": 91 @@ -3707,11 +3622,6 @@ "expiry_milestone": 88 }, { - "name": "managed-bookmarks-ios", - "owners": [ "edchin", "rohitrao", "bling-flags@google.com" ], - "expiry_milestone": 90 - }, - { "name": "mbi-mode", "owners": [ "dom", "blink-isolation-dev@chromium.org" ], "expiry_milestone": 103 @@ -4186,11 +4096,6 @@ "expiry_milestone": 97 }, { - "name": "omnibox-local-zero-suggest-frecency-ranking", - "owners": [ "mahmadi", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 89 - }, - { "name": "omnibox-max-url-matches", "owners": [ "orinj", "chrome-omnibox-team@google.com" ], "expiry_milestone": 95 @@ -4221,11 +4126,6 @@ "expiry_milestone": 93 }, { - "name": "omnibox-on-focus-suggestions", - "owners": [ "ender", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 97 - }, - { "name": "omnibox-on-focus-suggestions-contextual-web", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 95 @@ -4291,16 +4191,6 @@ "expiry_milestone": 95 }, { - "name": "omnibox-search-engine-logo", - "owners": [ "wylieb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 90 - }, - { - "name": "omnibox-search-ready-incognito", - "owners": [ "fgorski", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 90 - }, - { "name": "omnibox-spare-renderer", "owners": [ "instant-nav@google.com" ], "expiry_milestone": 92 @@ -4316,26 +4206,11 @@ "expiry_milestone": 97 }, { - "name": "omnibox-ui-hide-steady-state-url-path-query-and-ref-on-interaction", - "owners": [ "estark", "carlosil", "chrome-security-enamel@google.com" ], - "expiry_milestone": 89 - }, - { "name": "omnibox-ui-max-autocomplete-matches", "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], "expiry_milestone": 95 }, { - "name": "omnibox-ui-reveal-steady-state-url-path-query-and-ref-on-hover", - "owners": [ "estark", "carlosil", "chrome-security-enamel@google.com" ], - "expiry_milestone": 89 - }, - { - "name": "omnibox-ui-sometimes-elide-to-registrable-domain", - "owners": [ "estark", "carlosil", "chrome-security-enamel@google.com" ], - "expiry_milestone": 89 - }, - { "name": "omnibox-updated-connection-security-indicators", "owners": [ "meacer", "chrome-trusty-transport@google.com" ], "expiry_milestone": 96 @@ -4410,11 +4285,6 @@ "expiry_milestone": 97 }, { - "name": "page-info-performance-hints", - "owners": [ "jds" ], - "expiry_milestone": 90 - }, - { "name": "page-info-version-2-desktop", "owners": [ "bsep", "olesiamarukhno" ], "expiry_milestone": 95 @@ -4792,11 +4662,6 @@ "expiry_milestone": -1 }, { - "name": "report-feed-user-actions", - "owners": [ "//chrome/android/feed/OWNERS", "feed@chromium.org" ], - "expiry_milestone": 90 - }, - { "name": "request-desktop-site-for-tablets", "owners": [ "gangwu@chromium.org", "fgorski@chromium.org" ], "expiry_milestone": 96 @@ -4998,11 +4863,6 @@ "expiry_milestone": 98 }, { - "name": "send-uma-cellular", - "owners": [ "thegreenfrog", "bling-flags@google.com" ], - "expiry_milestone": 80 - }, - { "name": "send-webui-javascript-error-reports", "owners": ["iby", "cros-telemetry@google.com"], "expiry_milestone": 97 @@ -5245,11 +5105,6 @@ "expiry_milestone": 96 }, { - "name": "snapshot-draw-view", - "owners": [ "//ios/chrome/browser/snapshots/OWNERS", "bling-flags@google.com" ], - "expiry_milestone": 90 - }, - { "name": "spectre-v2-mitigation", "owners": [ "chromeos-security@google.com" ], "expiry_milestone": 92 @@ -5388,11 +5243,6 @@ "expiry_milestone": 94 }, { - "name": "texture-layer-skip-wait-for-activation", - "owners": [ "fserb@chromium.org", "aaronhk@chromium.org" ], - "expiry_milestone": 90 - }, - { "name": "theme-refactor-android", "owners": [ "sinansahin@google.com", "twellington", "clank-app-team@google.com" ], "expiry_milestone": 100
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 20d357f..85e875c 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -199,12 +199,6 @@ "information, refer to the deprecation announcement at " "https://groups.google.com/a/chromium.org/g/blink-dev/c/xHC3AtU_65A"; -const char kUseLookalikesForNavigationSuggestionsName[] = - "Use lookalike URL suggestions for navigation suggestions"; -const char kUseLookalikesForNavigationSuggestionsDescription[] = - "Use lookalike URL suggestions to suggest navigations to users who " - "face domain not found error."; - const char kUseStorkSmdsServerAddressName[] = "Use Stork SM-DS address"; const char kUseStorkSmdsServerAddressDescription[] = "Use the Stork SM-DS address to fetch pending eSIM profiles managed by the " @@ -1686,10 +1680,6 @@ const char kNewUsbBackendDescription[] = "Enables the new experimental USB backend for macOS"; -const char kNewTabstripAnimationName[] = "New tabstrip animations"; -const char kNewTabstripAnimationDescription[] = - "New implementation of tabstrip animations."; - const char kNotificationIndicatorName[] = "Notification Indicators"; const char kNotificationIndicatorDescription[] = "Enable notification indicators, which appear on shelf app icons and "
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 08623a0..f0d7f4f7 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -136,9 +136,6 @@ extern const char kU2FSecurityKeyAPIName[]; extern const char kU2FSecurityKeyAPIDescription[]; -extern const char kUseLookalikesForNavigationSuggestionsName[]; -extern const char kUseLookalikesForNavigationSuggestionsDescription[]; - extern const char kUseStorkSmdsServerAddressName[]; extern const char kUseStorkSmdsServerAddressDescription[]; @@ -970,9 +967,6 @@ extern const char kNewUsbBackendName[]; extern const char kNewUsbBackendDescription[]; -extern const char kNewTabstripAnimationName[]; -extern const char kNewTabstripAnimationDescription[]; - extern const char kNotificationIndicatorName[]; extern const char kNotificationIndicatorDescription[];
diff --git a/chrome/browser/incognito/BUILD.gn b/chrome/browser/incognito/BUILD.gn index eacd803..c45bbe59 100644 --- a/chrome/browser/incognito/BUILD.gn +++ b/chrome/browser/incognito/BUILD.gn
@@ -7,6 +7,7 @@ android_library("java") { sources = [ "android/java/src/org/chromium/chrome/browser/incognito/IncognitoCctProfileManager.java", + "android/java/src/org/chromium/chrome/browser/incognito/IncognitoReauthManager.java", "android/java/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingSwitchPreference.java", "android/java/src/org/chromium/chrome/browser/incognito/IncognitoStartup.java", "android/java/src/org/chromium/chrome/browser/incognito/IncognitoTabPersistence.java", @@ -15,12 +16,16 @@ deps = [ "//base:base_java", "//chrome/browser/dependency_injection:java", + "//chrome/browser/flags:java", "//chrome/browser/profiles/android:java", "//chrome/browser/tab:java", "//chrome/browser/tabmodel:java", "//chrome/browser/tabpersistence:java", + "//chrome/browser/ui/android/strings:ui_strings_grd", "//chrome/browser/util:java", "//components/browser_ui/settings/android:java", + "//components/browser_ui/settings/android:java_resources", + "//components/browser_ui/strings/android:browser_ui_strings_grd", "//third_party/android_deps:dagger_java", "//third_party/android_deps:javax_inject_javax_inject_java", "//third_party/androidx:androidx_annotation_annotation_java", @@ -29,6 +34,7 @@ "//url:gurl_java", ] annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] + resources_package = "org.chromium.chrome.browser.incognito" } generate_jni("jni_headers") { @@ -38,18 +44,27 @@ android_library("incognito_java_tests") { testonly = true - sources = [ "android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingSwitchPreferenceTest.java" ] + sources = [ + "android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingSwitchPreferenceTest.java", + "android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingTest.java", + ] deps = [ ":java", + "//base:base_java_test_support", "//chrome/android:chrome_java", + "//chrome/browser/flags:java", "//chrome/browser/settings:javatests", "//chrome/browser/settings:test_support_java", "//chrome/test/android:chrome_java_test_support", "//third_party/android_deps:espresso_java", + "//third_party/android_support_test_runner:runner_java", "//third_party/androidx:androidx_preference_preference_java", + "//third_party/androidx:androidx_recyclerview_recyclerview_java", "//third_party/androidx:androidx_test_runner_java", + "//third_party/hamcrest:hamcrest_core_java", "//third_party/junit:junit", "//third_party/mockito:mockito_java", + "//ui/android:ui_java_test_support", ] }
diff --git a/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/IncognitoReauthManager.java b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/IncognitoReauthManager.java new file mode 100644 index 0000000..8fcaecc --- /dev/null +++ b/chrome/browser/incognito/android/java/src/org/chromium/chrome/browser/incognito/IncognitoReauthManager.java
@@ -0,0 +1,103 @@ +// 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. + +package org.chromium.chrome.browser.incognito; + +import android.app.Activity; +import android.content.Intent; +import android.os.Build; +import android.provider.Settings; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; + +import androidx.annotation.VisibleForTesting; + +import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.ui.text.SpanApplier; + +/** + * This class is responsible for managing the reauthentication flow when the Incognito session is + * locked. + */ +public class IncognitoReauthManager { + @VisibleForTesting + private static Boolean sIsDeviceScreenLockEnabledForTesting; + + @VisibleForTesting + private static Boolean sShouldShowSettingForTesting; + + /** + * @return A boolean indicating if the Incognito lock setting needs to be shown in the Privacy + * and Security settings. + */ + public static boolean shouldShowSetting() { + if (sShouldShowSettingForTesting != null) { + return sShouldShowSettingForTesting; + } + + // The current phase relies on using the {@link BiometricManager} API which was added in + // Android Version 29. + return ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_REAUTHENTICATION_FOR_ANDROID) + && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q); + } + + /** + * @return A boolean indicating if the screen lock is enabled in device or not. + */ + public static boolean isDeviceScreenLockEnabled() { + if (sIsDeviceScreenLockEnabledForTesting != null) { + return sIsDeviceScreenLockEnabledForTesting; + } + + // TODO(crbug.com/1227656): This would be added later when the Incognito reauth MVC is in + // place. + return false; + } + + /** + * This method returns the summary string that needs to be set in the Incognito lock setting. + * The content of the summary string depends on whether the screen lock is enabled on device or + * not. + * + * @param activity The {@link Activity} from which the string resource must be fetched. + * @return A {@link CharSequence} containing the summary string for the Incognito lock setting. + */ + public static CharSequence getSummaryString(Activity activity) { + return (isDeviceScreenLockEnabled()) ? activity.getString( + R.string.settings_incognito_tab_lock_summary_android_setting_on) + : buildIntentToAndroidScreenLockSettingsLink(activity); + } + + /** + * @return An {@link Intent} intent with the action to launch the Android security settings + * page. + */ + public static Intent getSystemLocationSettingsIntent() { + Intent i = new Intent(Settings.ACTION_SECURITY_SETTINGS); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + return i; + } + + @VisibleForTesting + public static void setShouldShowSettingForTesting(boolean value) { + sShouldShowSettingForTesting = value; + } + + @VisibleForTesting + public static void setIsDeviceScreenLockEnabledForTesting(boolean value) { + sIsDeviceScreenLockEnabledForTesting = value; + } + + private static SpannableString buildIntentToAndroidScreenLockSettingsLink(Activity activity) { + int color = ApiCompatibilityUtils.getColor( + activity.getResources(), R.color.default_control_color_active); + ForegroundColorSpan linkSpan = new ForegroundColorSpan(color); + + return SpanApplier.applySpans( + activity.getString( + R.string.settings_incognito_tab_lock_summary_android_setting_off), + new SpanApplier.SpanInfo("<link>", "</link>", linkSpan)); + } +}
diff --git a/chrome/browser/incognito/android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingTest.java b/chrome/browser/incognito/android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingTest.java new file mode 100644 index 0000000..00d4a95 --- /dev/null +++ b/chrome/browser/incognito/android/javatests/src/org/chromium/chrome/browser/incognito/IncognitoReauthSettingTest.java
@@ -0,0 +1,75 @@ +// 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. + +package org.chromium.chrome.browser.incognito; + +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.intent.Intents.intended; +import static androidx.test.espresso.intent.Intents.intending; +import static androidx.test.espresso.intent.matcher.IntentMatchers.anyIntent; +import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; +import static androidx.test.espresso.matcher.ViewMatchers.withText; + +import static org.hamcrest.CoreMatchers.allOf; + +import android.app.Activity; +import android.app.Instrumentation; +import android.content.Intent; +import android.provider.Settings; +import android.support.test.InstrumentationRegistry; + +import androidx.test.espresso.intent.Intents; +import androidx.test.filters.LargeTest; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.R; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.privacy.settings.PrivacySettings; +import org.chromium.chrome.browser.settings.SettingsActivityTestRule; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.util.browser.Features; + +/** + * Tests for the Incognito reauth lock settings in Privacy and security. + * TODO(crbug.com/1227656) : Add reauth check when user toggles the setting once the reauth feature + * is implemented. + */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +@Features.EnableFeatures(ChromeFeatureList.INCOGNITO_REAUTHENTICATION_FOR_ANDROID) +public class IncognitoReauthSettingTest { + private final SettingsActivityTestRule<PrivacySettings> mSettingsActivityTestRule = + new SettingsActivityTestRule<>(PrivacySettings.class); + + private PrivacySettings mPrivacySettings; + + private void launchSettingsActivity() { + mSettingsActivityTestRule.startSettingsActivity(); + mPrivacySettings = mSettingsActivityTestRule.getFragment(); + } + + @Test + @LargeTest + public void testIncognitoReauthSetting_WhenDisabled_AndOnClickSummary() { + IncognitoReauthManager.setShouldShowSettingForTesting(true); + IncognitoReauthManager.setIsDeviceScreenLockEnabledForTesting(false); + launchSettingsActivity(); + Intent intent = new Intent(); + Instrumentation.ActivityResult result = + new Instrumentation.ActivityResult(Activity.RESULT_OK, intent); + Intents.init(); + intending(anyIntent()).respondWith(result); + String summaryText = InstrumentationRegistry.getContext().getResources().getString( + R.string.settings_incognito_tab_lock_summary_android_setting_off); + summaryText = summaryText.replaceAll("</?link>", ""); + onView(withText(summaryText)).perform(click()); + intended(allOf(hasAction(Settings.ACTION_SECURITY_SETTINGS))); + Intents.release(); + } +}
diff --git a/chrome/browser/media/webrtc/desktop_capture_devices_util.cc b/chrome/browser/media/webrtc/desktop_capture_devices_util.cc index ff0656b9..30c8907 100644 --- a/chrome/browser/media/webrtc/desktop_capture_devices_util.cc +++ b/chrome/browser/media/webrtc/desktop_capture_devices_util.cc
@@ -7,7 +7,9 @@ #include <string> #include <utility> +#include "base/strings/strcat.h" #include "base/strings/string_util.h" +#include "base/unguessable_token.h" #include "build/build_config.h" #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/browser/ui/screen_capture_notification_ui.h" @@ -17,6 +19,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "media/mojo/mojom/capture_handle.mojom.h" #include "media/mojo/mojom/display_media_information.mojom.h" @@ -220,6 +223,21 @@ return std::string(); } +std::string DeviceName(content::WebContents* web_contents, + blink::mojom::MediaStreamType requested_stream_type, + const content::DesktopMediaID& media_id) { + const std::string prefix = + DeviceNamePrefix(web_contents, requested_stream_type, media_id); + if (media_id.type == content::DesktopMediaID::TYPE_WEB_CONTENTS) { + return base::StrCat({prefix, content::kWebContentsCaptureScheme, + base::UnguessableToken::Create().ToString()}); + } else { + // TODO(crbug.com/1252682): MediaStreamTrack.label leaks internal state for + // screen/window + return base::StrCat({prefix, media_id.ToString()}); + } +} + } // namespace std::unique_ptr<content::MediaStreamUI> GetDevicesForDesktopCapture( @@ -244,11 +262,9 @@ << registered_extension_name; // Add selected desktop source to the list. - const std::string device_id = media_id.ToString(); - const std::string device_name = - DeviceNamePrefix(web_contents, devices_video_type, media_id) + device_id; - auto device = - blink::MediaStreamDevice(devices_video_type, device_id, device_name); + auto device = blink::MediaStreamDevice( + devices_video_type, media_id.ToString(), + DeviceName(web_contents, devices_video_type, media_id)); device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, capturer_origin, media_id); devices->push_back(device);
diff --git a/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chrome/browser/media/webrtc/native_desktop_media_list.cc index 4c822ebc..9123f98 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list.cc
@@ -95,7 +95,7 @@ #if defined(OS_MAC) const base::Feature kWindowCaptureMacV2{"WindowCaptureMacV2", - base::FEATURE_ENABLED_BY_DEFAULT}; + base::FEATURE_DISABLED_BY_DEFAULT}; #endif } // namespace
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index e9e6fc8e..3999194 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -215,12 +215,11 @@ &Memory_Experimental::SetMalloc_AllocatedObjects}, #if BUILDFLAG(USE_BACKUP_REF_PTR) // TODO(keishi): Add brp_quarantined metrics for the Blink partitions. - {"malloc/partitions/allocator/brp_quarantined_size", - "Malloc.BRPQuarantined", MetricSize::kSmall, kSize, EmitTo::kSizeInUmaOnly, + {"malloc/partitions/allocator", "Malloc.BRPQuarantined", MetricSize::kSmall, + "brp_quarantined_size", EmitTo::kSizeInUmaOnly, nullptr}, + {"malloc/partitions/allocator", "Malloc.BRPQuarantinedCount", + MetricSize::kTiny, "brp_quarantined_count", EmitTo::kSizeInUmaOnly, nullptr}, - {"malloc/partitions/allocator/brp_quarantined_count", - "Malloc.BRPQuarantinedCount", MetricSize::kTiny, - MemoryAllocatorDump::kNameObjectCount, EmitTo::kSizeInUmaOnly, nullptr}, #endif #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) {"malloc/partitions/allocator/thread_cache", "Malloc.ThreadCache",
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc b/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc index 5592aff..19f457a 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_controller_browsertest.cc
@@ -46,6 +46,7 @@ #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/media_start_stop_observer.h" +#include "content/public/test/prerender_test_util.h" #include "content/public/test/test_navigation_observer.h" #include "media/base/media_switches.h" #include "net/dns/mock_host_resolver.h" @@ -1550,6 +1551,53 @@ EXPECT_EQ(false, EvalJs(active_web_contents, "isPaused();")); } +class PictureInPictureWindowControllerPrerenderBrowserTest + : public PictureInPictureWindowControllerBrowserTest { + public: + PictureInPictureWindowControllerPrerenderBrowserTest() + : prerender_helper_(base::BindRepeating( + &PictureInPictureWindowControllerPrerenderBrowserTest:: + GetWebContents, + base::Unretained(this))) {} + + content::test::PrerenderTestHelper& prerender_test_helper() { + return prerender_helper_; + } + + content::WebContents* GetWebContents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + + private: + content::test::PrerenderTestHelper prerender_helper_; +}; + +IN_PROC_BROWSER_TEST_F(PictureInPictureWindowControllerPrerenderBrowserTest, + EnterPipThenNavigateAwayCloseWindow) { + GURL test_page_url = embedded_test_server()->GetURL( + "example.com", "/media/picture-in-picture/window-size.html"); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page_url)); + + ASSERT_TRUE(GetWebContents()); + + SetUpWindowController(GetWebContents()); + ASSERT_TRUE(window_controller()); + + // Open Picture-in-Picture window + ASSERT_EQ(true, EvalJs(GetWebContents(), "enterPictureInPicture();")); + EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); + + // Navigation to prerendered page should not close Picture-in-Picture window. + GURL prerendering_page_url = embedded_test_server()->GetURL( + "example.com", "/media/picture-in-picture/window-size.html?prerender"); + prerender_test_helper().AddPrerender(prerendering_page_url); + EXPECT_TRUE(window_controller()->GetWindowForTesting()->IsVisible()); + + // Picture-in-Picture window should be closed after navigating away. + prerender_test_helper().NavigatePrimaryPage(prerendering_page_url); + EXPECT_FALSE(window_controller()->GetWindowForTesting()->IsVisible()); +} + class MediaSessionPictureInPictureWindowControllerBrowserTest : public PictureInPictureWindowControllerBrowserTest { public:
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc index 72fb779..b80b0548 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc
@@ -20,16 +20,8 @@ ~ContentsObserver() final = default; - void DidFinishNavigation(content::NavigationHandle* navigation_handle) final { + void PrimaryPageChanged(content::Page& page) final { // Closes the active Picture-in-Picture window if user navigates away. - // TODO(https://crbug.com/1218946): With MPArch there may be multiple main - // frames. This caller was converted automatically to the primary main frame - // to preserve its semantics. Follow up to confirm correctness. - if (!navigation_handle->IsInPrimaryMainFrame() || - !navigation_handle->HasCommitted() || - navigation_handle->IsSameDocument()) { - return; - } owner_->CloseWindowInternal(); }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 3896365..0e66c65 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1318,9 +1318,6 @@ { key::kPrintPreviewUseSystemDefaultPrinter, prefs::kPrintPreviewUseSystemDefaultPrinter, base::Value::Type::BOOLEAN }, - { key::kCloudPolicyOverridesPlatformPolicy, - policy_prefs::kCloudPolicyOverridesPlatformPolicy, - base::Value::Type::BOOLEAN }, { key::kUserDataSnapshotRetentionLimit, prefs::kUserDataSnapshotRetentionLimit, base::Value::Type::INTEGER },
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index af47cdf..ab70bc9 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -470,19 +470,6 @@ "local_discovery.notifications_enabled"; #endif -// Deprecated 9/2020 -const char kBlockThirdPartyCookies[] = "profile.block_third_party_cookies"; - -// Deprecated 9/2020 -const char kPluginsDeprecationInfobarLastShown[] = - "plugins.deprecation_infobar_last_shown"; - -const char kPasswordManagerOnboardingState[] = - "profile.password_manager_onboarding_state"; - -const char kWasOnboardingFeatureCheckedBefore[] = - "profile.was_pwm_onboarding_feature_checked_before"; - // Deprecated 10/2020 const char kHistoryMenuPromoShown[] = "history.menu_promo_shown"; @@ -672,6 +659,7 @@ const char kPrivacyBudgetActiveSurfaces[] = "privacy_budget.active_surfaces"; const char kPrivacyBudgetRetiredSurfaces[] = "privacy_budget.retired_surfaces"; const char kPrivacyBudgetSeed[] = "privacy_budget.randomizer_seed"; +const char kCloudPolicyOverridesPlatformPolicy[] = "policy.cloud_override"; // Register local state used only for migration (clearing or moving to a new // key). @@ -706,6 +694,8 @@ registry->RegisterBooleanPref(kUserAgentClientHintsEnabled, true); + registry->RegisterBooleanPref(kCloudPolicyOverridesPlatformPolicy, false); + #if BUILDFLAG(ENABLE_EXTENSIONS) registry->RegisterBooleanPref(kPinnedExtensionsMigrationComplete, false); #endif @@ -728,13 +718,6 @@ chrome_browser_net::secure_dns::RegisterProbesSettingBackupPref(registry); - registry->RegisterBooleanPref(kBlockThirdPartyCookies, false); - - registry->RegisterTimePref(kPluginsDeprecationInfobarLastShown, base::Time()); - - registry->RegisterIntegerPref(kPasswordManagerOnboardingState, 0); - registry->RegisterBooleanPref(kWasOnboardingFeatureCheckedBefore, false); - registry->RegisterBooleanPref(prefs::kWebAppsUserDisplayModeCleanedUp, false); registry->RegisterBooleanPref(kHistoryMenuPromoShown, true); @@ -1483,6 +1466,9 @@ local_state->ClearPref(kPrivacyBudgetRetiredSurfaces); local_state->ClearPref(kPrivacyBudgetSeed); + // Added 09/2021. + local_state->ClearPref(kCloudPolicyOverridesPlatformPolicy); + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS } @@ -1508,14 +1494,6 @@ chrome_browser_net::secure_dns::MigrateProbesSettingToOrFromBackup( profile_prefs); - // Added 9/2020 - profile_prefs->ClearPref(kBlockThirdPartyCookies); - - // Added 9/2020 - profile_prefs->ClearPref(kPluginsDeprecationInfobarLastShown); - profile_prefs->ClearPref(kPasswordManagerOnboardingState); - profile_prefs->ClearPref(kWasOnboardingFeatureCheckedBefore); - // Added 10/2020 profile_prefs->ClearPref(kHistoryMenuPromoShown);
diff --git a/chrome/browser/prefs/incognito_mode_prefs.cc b/chrome/browser/prefs/incognito_mode_prefs.cc index 07280df8..9e58406d 100644 --- a/chrome/browser/prefs/incognito_mode_prefs.cc +++ b/chrome/browser/prefs/incognito_mode_prefs.cc
@@ -62,6 +62,10 @@ user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref(prefs::kIncognitoModeAvailability, static_cast<int>(kDefaultAvailability)); +#if defined(OS_ANDROID) + registry->RegisterBooleanPref(prefs::kIncognitoReauthenticationForAndroid, + false); +#endif } // static
diff --git a/chrome/browser/profiles/incognito_profile_containment_browsertest.cc b/chrome/browser/profiles/incognito_profile_containment_browsertest.cc index 94f149e..0befa4b 100644 --- a/chrome/browser/profiles/incognito_profile_containment_browsertest.cc +++ b/chrome/browser/profiles/incognito_profile_containment_browsertest.cc
@@ -61,6 +61,8 @@ "/Last Browser"}; #elif defined(OS_CHROMEOS) const char* kAllowListPrefixesForPlatform[] = { + "/Default/Local Storage/leveldb/CURRENT", + "/Default/Site Characteristics Database", "/Default/Sync Data/LevelDB", "/test-user/.variations-list.txt"}; #elif defined(OS_LINUX) const char* kAllowListPrefixesForPlatform[] = {"/Default/Web Data"};
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 52d23e27..50c668d 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -191,10 +191,10 @@ #include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h" #include "chrome/browser/ash/policy/core/user_policy_manager_builder_ash.h" #include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/ash/settings/device_settings_service.h" #include "chrome/browser/chromeos/locale_change_guard.h" #include "chrome/browser/chromeos/preferences.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/signin/chrome_device_id_helper.h" #include "components/account_manager_core/chromeos/account_manager.h" #include "components/session_manager/core/session_manager.h"
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn index 82acc38..bb33dd3 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn
@@ -103,6 +103,7 @@ ":autoclick", ":dictation", ":magnifier", + "../common:chrome_event_handler", "../common:event_generator", "../common:event_handler", "../common:instance_checker",
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/background.html b/chrome/browser/resources/chromeos/accessibility/accessibility_common/background.html index a2e9e746..3ad0664d 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/background.html +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/background.html
@@ -1,4 +1,5 @@ <!-- Global scripts. --> +<script src="/common/chrome_event_handler.js"></script> <script src="/common/closure_shim.js"></script> <script src="/common/instance_checker.js"></script> <script src="/common/event_generator.js"></script>
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier.js b/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier.js index a6fdd52..a0a56ed6 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier.js +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier.js
@@ -48,12 +48,15 @@ [], chrome.automation.EventType.CARET_BOUNDS_CHANGED, event => this.onCaretBoundsChanged(event)); - /** @private {function(!chrome.accessibilityPrivate.ScreenRect)} */ - this.onMagnifierBoundsChangedListener_ = bounds => - this.onMagnifierBoundsChanged_(bounds); + /** @private {!ChromeEventHandler} */ + this.onMagnifierBoundsChangedHandler_ = new ChromeEventHandler( + chrome.accessibilityPrivate.onMagnifierBoundsChanged, + bounds => this.onMagnifierBoundsChanged_(bounds)); - /** @private {function(!Array<!chrome.settingsPrivate.PrefObject>)} */ - this.updateFromPrefsListener_ = prefs => this.updateFromPrefs_(prefs); + /** @private {ChromeEventHandler} */ + this.updateFromPrefsHandler_ = new ChromeEventHandler( + chrome.settingsPrivate.onPrefsChanged, + prefs => this.updateFromPrefs_(prefs)); this.init_(); } @@ -63,12 +66,8 @@ this.focusHandler_.stop(); this.activeDescendantHandler_.stop(); this.onCaretBoundsChangedHandler.stop(); - - chrome.accessibilityPrivate.onMagnifierBoundsChanged.removeListener( - this.onMagnifierBoundsChangedListener_); - - chrome.settingsPrivate.onPrefsChanged.removeListener( - this.updateFromPrefsListener_); + this.onMagnifierBoundsChangedHandler_.stop(); + this.updateFromPrefsHandler_.stop(); } /** @@ -77,8 +76,7 @@ */ init_() { chrome.settingsPrivate.getAllPrefs(prefs => this.updateFromPrefs_(prefs)); - chrome.settingsPrivate.onPrefsChanged.addListener( - this.updateFromPrefsListener_); + this.updateFromPrefsHandler_.start(); chrome.automation.getDesktop(desktop => { this.focusHandler_.setNodes(desktop); @@ -89,8 +87,7 @@ this.onCaretBoundsChangedHandler.start(); }); - chrome.accessibilityPrivate.onMagnifierBoundsChanged.addListener( - this.onMagnifierBoundsChangedListener_); + this.onMagnifierBoundsChangedHandler_.start(); this.isInitializing_ = true;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/phonetic_data_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/phonetic_data_test.js index 809b4bce..62068d6 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/phonetic_data_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/phonetic_data_test.js
@@ -37,6 +37,10 @@ ['1', 'イチ'], ['ー', 'チョウオン'], ['。', 'マル'], + ['@', 'アットマーク'], + ['@', 'アットマーク'], + ['Α', 'ギリシャ アルファ'], + ['α', 'ギリシャ アルファ'], ['亜', 'アジア ノ ア'], ['今', 'コンゲツノコン'], ['日', 'ニチヨウビノニチ'], @@ -57,9 +61,13 @@ assertEquals('オオモジ A', PhoneticData.forCharacter('A', 'ja')); assertEquals('ハンカク a', PhoneticData.forCharacter('a', 'ja')); assertEquals('ハンカク 1', PhoneticData.forCharacter('1', 'ja')); + assertEquals('ハンカク @', PhoneticData.forCharacter('@', 'ja')); assertEquals('ゼンカクオオモジ A', PhoneticData.forCharacter('A', 'ja')); assertEquals('ゼンカク a', PhoneticData.forCharacter('a', 'ja')); assertEquals('ゼンカク 1', PhoneticData.forCharacter('1', 'ja')); + assertEquals('ゼンカク @', PhoneticData.forCharacter('@', 'ja')); + assertEquals('オオモジ Α', PhoneticData.forCharacter('Α', 'ja')); + assertEquals('コモジ α', PhoneticData.forCharacter('α', 'ja')); assertEquals('アジア ノ ア', PhoneticData.forCharacter('亜', 'ja')); }); @@ -73,9 +81,13 @@ assertEquals('オオモジ A', PhoneticData.forText('A', 'ja')); assertEquals('a', PhoneticData.forText('a', 'ja')); assertEquals('1', PhoneticData.forText('1', 'ja')); + assertEquals('アットマーク', PhoneticData.forText('@', 'ja')); assertEquals('ゼンカクオオモジ A', PhoneticData.forText('A', 'ja')); assertEquals('ゼンカク a', PhoneticData.forText('a', 'ja')); assertEquals('ゼンカク 1', PhoneticData.forText('1', 'ja')); + assertEquals('ゼンカク アットマーク', PhoneticData.forText('@', 'ja')); + assertEquals('オオモジ ギリシャ アルファ', PhoneticData.forText('Α', 'ja')); + assertEquals('ギリシャ アルファ', PhoneticData.forText('α', 'ja')); assertEquals('アジア ノ ア', PhoneticData.forText('亜', 'ja')); }); @@ -162,6 +174,17 @@ TEST_F( 'ChromeVoxPhoneticDataTest', + 'forTextJaPairCharacters_EndWithHalfWidthSymbol', function() { + assertEquals( + 'アットマーク アットマーク', PhoneticData.forText('@@', 'ja')); + assertEquals('あ アットマーク', PhoneticData.forText('あ@', 'ja')); + assertEquals( + 'ゼンカクオオモジ A ハンカク アットマーク', + PhoneticData.forText('A@', 'ja')); + }); + +TEST_F( + 'ChromeVoxPhoneticDataTest', 'forTextJaPairCharacters_EndWithFullWidthAlphabetUpper', function() { assertEquals('ゼンカクオオモジ AA', PhoneticData.forText('AA', 'ja')); assertEquals( @@ -189,6 +212,41 @@ }); TEST_F( + 'ChromeVoxPhoneticDataTest', + 'forTextJaPairCharacters_EndWithFullWidthSymbol', function() { + assertEquals( + 'ゼンカク アットマーク アットマーク', + PhoneticData.forText('@@', 'ja')); + assertEquals( + 'ゼンカクオオモジ A アットマーク', + PhoneticData.forText('A@', 'ja')); + assertEquals( + 'あ ゼンカク アットマーク', PhoneticData.forText('あ@', 'ja')); + }); + +TEST_F( + 'ChromeVoxPhoneticDataTest', + 'forTextJaPairCharacters_EndWithFullWidthGreekUpper', function() { + assertEquals( + 'オオモジ ギリシャ アルファ ギリシャ アルファ', + PhoneticData.forText('ΑΑ', 'ja')); + assertEquals( + 'あ オオモジ ギリシャ アルファ', PhoneticData.forText('あΑ', 'ja')); + }); + +TEST_F( + 'ChromeVoxPhoneticDataTest', + 'forTextJaPairCharacters_EndWithFullWidthGreekLower', function() { + assertEquals( + 'ギリシャ アルファ ギリシャ アルファ', + PhoneticData.forText('αα', 'ja')); + assertEquals( + 'オオモジ ギリシャ アルファ コモジ ギリシャ アルファ', + PhoneticData.forText('Αα', 'ja')); + assertEquals('あ ギリシャ アルファ', PhoneticData.forText('あα', 'ja')); + }); + +TEST_F( 'ChromeVoxPhoneticDataTest', 'forTextJaPairCharacters_EndWithOther', function() { assertEquals(
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/third_party/tamachiyomi/ja_phonetic_data.js b/chrome/browser/resources/chromeos/accessibility/chromevox/third_party/tamachiyomi/ja_phonetic_data.js index 384a13e..34d5dc4f 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/third_party/tamachiyomi/ja_phonetic_data.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/third_party/tamachiyomi/ja_phonetic_data.js
@@ -49,22 +49,21 @@ for (const char of chars) { const currentCharacterSet = JaPhoneticData.getCharacterSet(char, lastCharacterSet); - if (currentCharacterSet !== JaPhoneticData.CharacterSet.OTHER) { - const info = - JaPhoneticData.getPrefixInfo(lastCharacterSet, currentCharacterSet); - if (info.prefix) { - // Need to announce the new charset explicitly. - result.push(info.prefix); - } - if (info.delimiter === false && result.length > 0) { - // Does not convert small Kana if it is not the beginning of the - // element. - result[result.length - 1] += char; - } else { - result.push(JaPhoneticData.maybeGetLargeLetterKana(char)); - } - } else { + const info = + JaPhoneticData.getPrefixInfo(lastCharacterSet, currentCharacterSet); + if (info.prefix) { + // Need to announce the new character set explicitly. + result.push(info.prefix); + } + + if (info.delimiter === false && result.length > 0) { + // Does not convert small Kana if it is not the beginning of the + // element. + result[result.length - 1] += char; + } else if (JaPhoneticData.alwaysReadPhonetically(currentCharacterSet)) { result.push(JaPhoneticData.phoneticMap_.get(char) || char); + } else { + result.push(JaPhoneticData.maybeGetLargeLetterKana(char)); } lastCharacterSet = currentCharacterSet; @@ -108,6 +107,10 @@ if (character >= '0' && character <= '9') { return JaPhoneticData.CharacterSet.HALF_WIDTH_NUMERIC; } + // See https://unicode.org/charts/PDF/U0000.pdf + if (character >= '!' && character <= '~') { + return JaPhoneticData.CharacterSet.HALF_WIDTH_SYMBOL; + } if (character >= 'A' && character <= 'Z') { return JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_UPPER; } @@ -117,6 +120,10 @@ if (character >= '0' && character <= '9') { return JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC; } + // See https://unicode.org/charts/PDF/UFF00.pdf + if (character >= '!' && character <= '~') { + return JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL; + } if (character === 'ー') { switch (lastCharacterSet) { case JaPhoneticData.CharacterSet.HIRAGANA: @@ -126,6 +133,16 @@ return lastCharacterSet; } } + // See https://www.unicode.org/charts/PDF/U0400.pdf and + // https://www.unicode.org/charts/PDF/U0370.pdf + if ((character >= 'А' && character <= 'Я') || + (character >= 'Α' && character <= 'Ω')) { + return JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_UPPER; + } + if ((character >= 'а' && character <= 'я') || + (character >= 'α' && character <= 'ω')) { + return JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_LOWER; + } // Returns OTHER for all other characters, including Kanji. return JaPhoneticData.CharacterSet.OTHER; } @@ -168,9 +185,12 @@ * prefix: a string that represents the character set. Null if unncessary. */ static getPrefixInfo(lastCharacterSet, currentCharacterSet) { - // Don't add prefixes for the same character set. + // Don't add prefixes for the same character set except for the sets always + // read phonetically. if (lastCharacterSet === currentCharacterSet) { - return {delimiter: false, prefix: null}; + return JaPhoneticData.alwaysReadPhonetically(currentCharacterSet) ? + {delimiter: true, prefix: null} : + {delimiter: false, prefix: null}; } // Exceptional cases: switch (currentCharacterSet) { @@ -227,12 +247,14 @@ case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_UPPER: case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL: case JaPhoneticData.CharacterSet.OTHER: return {delimiter: true, prefix: 'ハンカクオオモジ'}; } break; case JaPhoneticData.CharacterSet.HALF_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.HALF_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.HALF_WIDTH_SYMBOL: switch (lastCharacterSet) { case JaPhoneticData.CharacterSet.NONE: return {delimiter: false, prefix: null}; @@ -245,6 +267,7 @@ case JaPhoneticData.CharacterSet.HALF_WIDTH_ALPHABET_UPPER: case JaPhoneticData.CharacterSet.HALF_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.HALF_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.HALF_WIDTH_SYMBOL: return {delimiter: true, prefix: null}; } break; @@ -252,19 +275,33 @@ switch (lastCharacterSet) { case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL: case JaPhoneticData.CharacterSet.OTHER: return {delimiter: true, prefix: 'オオモジ'}; } break; case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL: switch (lastCharacterSet) { case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_UPPER: case JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_LOWER: case JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC: + case JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL: return {delimiter: true, prefix: null}; } break; + case JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_LOWER: + switch (lastCharacterSet) { + case JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_UPPER: + return { + delimiter: true, + prefix: JaPhoneticData.getDefaultPrefix(currentCharacterSet) + }; + } + return {delimiter: true, prefix: null}; + case JaPhoneticData.CharacterSet.OTHER: + return {delimiter: true, prefix: null}; } // Returns the default prefix. return { @@ -272,24 +309,44 @@ prefix: JaPhoneticData.getDefaultPrefix(currentCharacterSet) }; } + + /** + * @param {JaPhoneticData.CharacterSet} characterSet + * @return {boolean} + */ + static alwaysReadPhonetically(characterSet) { + switch (characterSet) { + case JaPhoneticData.CharacterSet.HALF_WIDTH_SYMBOL: + case JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL: + case JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_UPPER: + case JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_LOWER: + case JaPhoneticData.CharacterSet.OTHER: + return true; + } + return false; + } }; /** @enum {number} */ JaPhoneticData.CharacterSet = { NONE: 0, - HIRAGANA: 1, // 'あ' - KATAKANA: 2, // 'ア' - HIRAGANA_SMALL_LETTER: 3, // 'ぁ' - KATAKANA_SMALL_LETTER: 4, // 'ァ' - HALF_WIDTH_KATAKANA: 5, // 'ア' - HALF_WIDTH_KATAKANA_SMALL_LETTER: 6, // 'ァ' - HALF_WIDTH_ALPHABET_UPPER: 7, // 'A' - HALF_WIDTH_ALPHABET_LOWER: 8, // 'a' - HALF_WIDTH_NUMERIC: 9, // '1' - FULL_WIDTH_ALPHABET_UPPER: 10, // 'A' - FULL_WIDTH_ALPHABET_LOWER: 11, // 'a' - FULL_WIDTH_NUMERIC: 12, // '1' - OTHER: 13 // Kanji, symbol... + HIRAGANA: 1, // 'あ' + KATAKANA: 2, // 'ア' + HIRAGANA_SMALL_LETTER: 3, // 'ぁ' + KATAKANA_SMALL_LETTER: 4, // 'ァ' + HALF_WIDTH_KATAKANA: 5, // 'ア' + HALF_WIDTH_KATAKANA_SMALL_LETTER: 6, // 'ァ' + HALF_WIDTH_ALPHABET_UPPER: 7, // 'A' + HALF_WIDTH_ALPHABET_LOWER: 8, // 'a' + HALF_WIDTH_NUMERIC: 9, // '1' + HALF_WIDTH_SYMBOL: 10, // '@' + FULL_WIDTH_ALPHABET_UPPER: 11, // 'A' + FULL_WIDTH_ALPHABET_LOWER: 12, // 'a' + FULL_WIDTH_NUMERIC: 13, // '1' + FULL_WIDTH_SYMBOL: 14, // '@' + FULL_WIDTH_CYRILLIC_OR_GREEK_UPPER: 15, // 'Α' + FULL_WIDTH_CYRILLIC_OR_GREEK_LOWER: 16, // 'α' + OTHER: 17 // Kanji and unsupported symbols }; /** @@ -318,12 +375,20 @@ [JaPhoneticData.CharacterSet.HALF_WIDTH_ALPHABET_LOWER, 'ハンカク'], // '1' [JaPhoneticData.CharacterSet.HALF_WIDTH_NUMERIC, 'ハンカク'], + // '@' + [JaPhoneticData.CharacterSet.HALF_WIDTH_SYMBOL, 'ハンカク'], // 'A' [JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_UPPER, 'ゼンカクオオモジ'], // 'a' [JaPhoneticData.CharacterSet.FULL_WIDTH_ALPHABET_LOWER, 'ゼンカク'], // '1' [JaPhoneticData.CharacterSet.FULL_WIDTH_NUMERIC, 'ゼンカク'], + // '@' + [JaPhoneticData.CharacterSet.FULL_WIDTH_SYMBOL, 'ゼンカク'], + // 'Α' + [JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_UPPER, 'オオモジ'], + // 'α' + [JaPhoneticData.CharacterSet.FULL_WIDTH_CYRILLIC_OR_GREEK_LOWER, 'コモジ'], ]); /**
diff --git a/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn index 1d041cd..b14ec468 100644 --- a/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn
@@ -31,6 +31,7 @@ "array_util.js", "automation_predicate.js", "automation_util.js", + "chrome_event_handler.js", "closure_shim.js", "constants.js", "cursors/cursor.js", @@ -94,6 +95,10 @@ ] } +js_library("chrome_event_handler") { + externs_list = [ "$externs_path/automation.js" ] +} + js_library("event_generator") { deps = [ ":key_code" ] externs_list = [ "$externs_path/accessibility_private.js" ]
diff --git a/chrome/browser/resources/chromeos/accessibility/common/chrome_event_handler.js b/chrome/browser/resources/chromeos/accessibility/common/chrome_event_handler.js new file mode 100644 index 0000000..a41cc58 --- /dev/null +++ b/chrome/browser/resources/chromeos/accessibility/common/chrome_event_handler.js
@@ -0,0 +1,40 @@ +// 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. + +/** + * This class wraps ChromeEvent listeners, adding some convenience + * functions. + */ +class ChromeEventHandler { + /** + * @param {!ChromeEvent} chromeEvent + * @param {function(...)} callback + */ + constructor(chromeEvent, callback) { + /** @private {!ChromeEvent} */ + this.chromeEvent_ = chromeEvent; + + /** @private {function(...)} */ + this.callback_ = callback; + + /** @private {boolean} */ + this.listening_ = false; + } + + /** Starts listening to events. */ + start() { + if (this.listening_) { + return; + } + + this.listening_ = true; + this.chromeEvent_.addListener(this.callback_); + } + + /** Stops listening or handling future events. */ + stop() { + this.listening_ = false; + this.chromeEvent_.removeListener(this.callback_); + } +}
diff --git a/chrome/browser/resources/read_later/app.html b/chrome/browser/resources/read_later/app.html index 8c8cf66..0c59eca 100644 --- a/chrome/browser/resources/read_later/app.html +++ b/chrome/browser/resources/read_later/app.html
@@ -103,10 +103,16 @@ } :host([side-panel]) .hr { - border-top: 1px solid #dbdbdb; + border-top: 1px solid var(--google-grey-refresh-300); margin-block-start: 8px; } + @media (prefers-color-scheme: dark) { + :host([side-panel]) .hr { + border-top: 1px solid var(--google-grey-refresh-700); + } + } + #empty-state-container { text-align: center; }
diff --git a/chrome/browser/resources/settings/BUILD.gn b/chrome/browser/resources/settings/BUILD.gn index be893482..d319764 100644 --- a/chrome/browser/resources/settings/BUILD.gn +++ b/chrome/browser/resources/settings/BUILD.gn
@@ -188,10 +188,10 @@ ] } in_files += [ - "languages_page/languages.js", - "languages_page/languages_browser_proxy.js", + "languages_page/languages.ts", + "languages_page/languages_browser_proxy.ts", "languages_page/languages_settings_metrics_proxy.ts", - "languages_page/languages_types.js", + "languages_page/languages_types.ts", "people_page/import_data_browser_proxy.js", "people_page/manage_profile_browser_proxy.js", ] @@ -397,10 +397,6 @@ "settings_page:closure_compile", ] - if (!is_chromeos_ash) { - deps += [ "languages_page:closure_compile" ] - } - if (is_chromeos_ash) { deps += [ "chromeos:closure_compile_module" ] } @@ -413,7 +409,6 @@ ":base_mixin", ":extension_control_browser_proxy", ":i18n_setup", - ":lazy_load", ":lifetime_browser_proxy", ":open_window_proxy", ":page_visibility", @@ -469,19 +464,6 @@ ] } -js_library("lazy_load") { - sources = - [ "$root_gen_dir/chrome/browser/resources/settings/tsc/lazy_load.js" ] - - if (!is_chromeos_ash) { - deps = [ - "languages_page:languages_browser_proxy", - "languages_page:languages_types", - ] - } - extra_deps = [ ":build_ts" ] -} - js_library("lifetime_browser_proxy") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/tsc/lifetime_browser_proxy.js" ] deps = [ "//ui/webui/resources/js:cr.m" ] @@ -817,12 +799,12 @@ } in_files += [ "languages_page/add_languages_dialog.ts", - "languages_page/languages_browser_proxy.js", - "languages_page/languages.js", + "languages_page/languages_browser_proxy.ts", + "languages_page/languages.ts", "languages_page/languages_page.ts", "languages_page/languages_settings_metrics_proxy.ts", "languages_page/languages_subpage.ts", - "languages_page/languages_types.js", + "languages_page/languages_types.ts", "people_page/import_data_browser_proxy.js", "people_page/import_data_dialog.js", "people_page/manage_profile_browser_proxy.js",
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index eff39e2..b6e2e8fc 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -255,6 +255,9 @@ "chromeos/os_apps_page/app_management_page/util.js", "chromeos/os_apps_page/app_notifications_page/mojo_interface_provider.js", "chromeos/os_languages_page/input_method_settings.js", + "chromeos/os_languages_page/languages_browser_proxy.js", + "chromeos/os_languages_page/languages.js", + "chromeos/os_languages_page/languages_types.js", "chromeos/os_printing_page/cups_printers_entry_list_behavior.js", "chromeos/os_printing_page/cups_printer_dialog_util.js", "chromeos/os_printing_page/cups_printer_types.js", @@ -273,9 +276,6 @@ "chromeos/os_privacy_page/peripheral_data_access_browser_proxy.js", "controls/pref_control_behavior.js", "controls/settings_boolean_control_behavior.js", - "languages_page/languages.js", - "languages_page/languages_browser_proxy.js", - "languages_page/languages_types.js", "people_page/account_manager_browser_proxy.js", "people_page/profile_info_browser_proxy.js", "chromeos/ambient_mode_page/ambient_mode_browser_proxy.js",
diff --git a/chrome/browser/resources/settings/chromeos/lazy_load.js b/chrome/browser/resources/settings/chromeos/lazy_load.js index f6792c90..66f2e68 100644 --- a/chrome/browser/resources/settings/chromeos/lazy_load.js +++ b/chrome/browser/resources/settings/chromeos/lazy_load.js
@@ -56,13 +56,13 @@ import '../privacy_page/secure_dns_input.js'; export {SmbBrowserProxyImpl, SmbMountResult} from 'chrome://resources/cr_components/chromeos/smb_shares/smb_browser_proxy.m.js'; -export {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from '../languages_page/languages_browser_proxy.js'; export {LifetimeBrowserProxyImpl} from '../lifetime_browser_proxy.js'; export {PrivacyPageBrowserProxyImpl, SecureDnsMode, SecureDnsUiManagementMode} from '../privacy_page/privacy_page_browser_proxy.js'; export {CrostiniBrowserProxy, CrostiniBrowserProxyImpl} from './crostini_page/crostini_browser_proxy.js'; export {TimeZoneAutoDetectMethod} from './date_time_page/date_time_types.js'; export {TimeZoneBrowserProxyImpl} from './date_time_page/timezone_browser_proxy.js'; export {CROSTINI_TYPE, GuestOsBrowserProxy, GuestOsBrowserProxyImpl, GuestOsSharedUsbDevice, PLUGIN_VM_TYPE} from './guest_os/guest_os_browser_proxy.js'; +export {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from './os_languages_page/languages_browser_proxy.js'; export {InputsShortcutReminderState, LanguagesMetricsProxy, LanguagesMetricsProxyImpl, LanguagesPageInteraction} from './os_languages_page/languages_metrics_proxy.m.js'; export {PrinterType} from './os_printing_page/cups_printer_types.js'; export {CupsPrintersBrowserProxy, CupsPrintersBrowserProxyImpl, PrinterSetupResult, PrintServerResult} from './os_printing_page/cups_printers_browser_proxy.js';
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn index 45fafee..66a27bc 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn
@@ -164,8 +164,8 @@ "//chrome/browser/resources/settings:router", "//chrome/browser/resources/settings/chromeos:deep_linking_behavior.m", "//chrome/browser/resources/settings/chromeos:os_route.m", + "//chrome/browser/resources/settings/chromeos/os_languages_page:languages_browser_proxy", "//chrome/browser/resources/settings/controls:settings_slider", - "//chrome/browser/resources/settings/languages_page:languages_browser_proxy", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_button:cr_button.m", "//ui/webui/resources/cr_elements/cr_expand_button:cr_expand_button.m",
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/tts_subpage.js b/chrome/browser/resources/settings/chromeos/os_a11y_page/tts_subpage.js index fc250e8..8440931 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/tts_subpage.js +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/tts_subpage.js
@@ -20,9 +20,9 @@ import {WebUIListenerBehavior} from '//resources/js/web_ui_listener_behavior.m.js'; import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from '../../languages_page/languages_browser_proxy.js'; import {Route, RouteObserverBehavior, Router} from '../../router.js'; import {DeepLinkingBehavior} from '../deep_linking_behavior.m.js'; +import {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from '../os_languages_page/languages_browser_proxy.js'; import {routes} from '../os_route.m.js'; import {TtsSubpageBrowserProxy, TtsSubpageBrowserProxyImpl} from './tts_subpage_browser_proxy.js';
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn index 0c7b216..cfdb5b7 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn
@@ -21,7 +21,10 @@ ":input_method_options_page.m", ":input_method_util.m", ":input_page.m", + ":languages", + ":languages_browser_proxy", ":languages_metrics_proxy.m", + ":languages_types", ":os_add_languages_dialog.m", ":os_edit_dictionary_page.m", ":os_languages_page_v2.m", @@ -30,6 +33,47 @@ ] } +js_library("languages_types") { + externs_list = [ "$externs_path/language_settings_private.js" ] +} + +js_library("languages") { + deps = [ + ":languages_browser_proxy", + ":languages_types", + "../../prefs:prefs", + "../../prefs:prefs_behavior", + "../../prefs:prefs_types", + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + "//ui/webui/resources/js:assert.m", + "//ui/webui/resources/js:cr.m", + "//ui/webui/resources/js:i18n_behavior.m", + "//ui/webui/resources/js:load_time_data.m", + "//ui/webui/resources/js:promise_resolver.m", + ] + externs_list = [ + "$externs_path/input_method_private.js", + "$externs_path/language_settings_private.js", + ] + extra_sources = [ + "$interfaces_path/input_method_private_interface.js", + "$interfaces_path/language_settings_private_interface.js", + ] +} + +js_library("languages_browser_proxy") { + deps = [ "//ui/webui/resources/js:cr.m" ] + externs_list = [ + "$externs_path/chrome_send.js", + "$externs_path/input_method_private.js", + "$externs_path/language_settings_private.js", + ] + extra_sources = [ + "$interfaces_path/input_method_private_interface.js", + "$interfaces_path/language_settings_private_interface.js", + ] +} + js_library("add_input_methods_dialog.m") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/add_input_methods_dialog.m.js" ] deps = [ ":cr_checkbox_with_policy" ] @@ -39,8 +83,8 @@ js_library("add_spellcheck_languages_dialog") { deps = [ ":cr_checkbox_with_policy", + ":languages_types", "..:metrics_recorder.m", - "../../languages_page:languages_types", "../../prefs:prefs_behavior", "//third_party/polymer/v3_0/components-chromium/iron-flex-layout:iron-flex-layout-classes", "//third_party/polymer/v3_0/components-chromium/iron-list:iron-list", @@ -56,8 +100,8 @@ js_library("change_device_language_dialog.m") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/change_device_language_dialog.m.js" ] deps = [ + ":languages", "../..:lifetime_browser_proxy", - "../../languages_page:languages", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements:cr_scrollable_behavior.m", "//ui/webui/resources/cr_elements/cr_search_field:cr_search_field", @@ -132,7 +176,7 @@ js_library("os_add_languages_dialog.m") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/os_add_languages_dialog.m.js" ] deps = [ - "../../languages_page:languages", + ":languages", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements:cr_scrollable_behavior.m", "//ui/webui/resources/cr_elements:find_shortcut_behavior", @@ -144,9 +188,9 @@ js_library("os_edit_dictionary_page.m") { sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/os_edit_dictionary_page.m.js" ] deps = [ + ":languages_browser_proxy", "..:global_scroll_target_behavior", "..:os_route.m", - "../../languages_page:languages_browser_proxy", "//third_party/polymer/v3_0/components-chromium/iron-list:iron-list", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_button:cr_button.m", @@ -183,10 +227,10 @@ deps = [ ":input_method_options_page.m", ":input_page.m", + ":languages", ":os_languages_page_v2.m", "..:os_route.m", "../..:router", - "../../languages_page:languages", "../../settings_page:settings_animated_pages", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:cr.m", @@ -234,7 +278,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] } polymer_modulizer("add_spellcheck_languages_dialog") { @@ -249,7 +293,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] } polymer_modulizer("cr_checkbox_with_policy") { @@ -264,7 +308,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] } polymer_modulizer("os_edit_dictionary_page") { @@ -282,7 +326,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel,LanguageState" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel,LanguageState" ] } polymer_modulizer("os_languages_section") { @@ -291,7 +335,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel" ] } polymer_modulizer("input_method_options_page") { @@ -300,7 +344,7 @@ html_type = "dom-module" migrated_imports = os_settings_migrated_imports namespace_rewrites = os_settings_namespace_rewrites - auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper" ] + auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper" ] } polymer_modulizer("input_page") { @@ -311,7 +355,7 @@ namespace_rewrites = os_settings_namespace_rewrites auto_imports = os_settings_auto_imports + [ "chrome/browser/resources/settings/controls/settings_toggle_button.html|SettingsToggleButtonElement", - "chrome/browser/resources/settings/languages_page/languages_types.html|LanguageHelper,LanguagesModel,LanguageState,SpellCheckLanguageState", + "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html|LanguageHelper,LanguagesModel,LanguageState,SpellCheckLanguageState", ] }
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/add_input_methods_dialog.html b/chrome/browser/resources/settings/chromeos/os_languages_page/add_input_methods_dialog.html index c9cce15..3928426 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/add_input_methods_dialog.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/add_input_methods_dialog.html
@@ -8,8 +8,8 @@ <link rel="import" href="./cr_checkbox_with_policy.html"> <link rel="import" href="../metrics_recorder.html"> <link rel="import" href="shared_style.html"> -<link rel="import" href="../../languages_page/languages.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages.html"> +<link rel="import" href="languages_types.html"> <link rel="import" href="../../settings_shared_css.html"> <dom-module id="os-settings-add-input-methods-dialog">
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/add_spellcheck_languages_dialog.js b/chrome/browser/resources/settings/chromeos/os_languages_page/add_spellcheck_languages_dialog.js index af8107f5..4925c10 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/add_spellcheck_languages_dialog.js +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/add_spellcheck_languages_dialog.js
@@ -19,10 +19,11 @@ import {FindShortcutBehavior} from '//resources/cr_elements/find_shortcut_behavior.js'; import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {LanguageHelper, LanguagesModel, SpellCheckLanguageState} from '../../languages_page/languages_types.js'; import {PrefsBehavior} from '../../prefs/prefs_behavior.js'; import {recordClick, recordNavigation, recordPageBlur, recordPageFocus, recordSearch, recordSettingChange, setUserActionRecorderForTesting} from '../metrics_recorder.m.js'; +import {LanguageHelper, LanguagesModel, SpellCheckLanguageState} from './languages_types.js'; + Polymer({ is: 'os-settings-add-spellcheck-languages-dialog',
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/change_device_language_dialog.html b/chrome/browser/resources/settings/chromeos/os_languages_page/change_device_language_dialog.html index 2a7760c..a63ab1a 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/change_device_language_dialog.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/change_device_language_dialog.html
@@ -13,8 +13,8 @@ <link rel="import" href="shared_style.html"> <link rel="import" href="chrome://resources/cr_components/chromeos/localized_link/localized_link.html"> <link rel="import" href="../metrics_recorder.html"> -<link rel="import" href="../../languages_page/languages.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages.html"> +<link rel="import" href="languages_types.html"> <link rel="import" href="../../lifetime_browser_proxy.html"> <link rel="import" href="../../settings_shared_css.html">
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_options_page.html b/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_options_page.html index bd946e6..eb5e113 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_options_page.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_options_page.html
@@ -9,7 +9,7 @@ <link rel="import" href="../../router.html"> <link rel="import" href="../../settings_shared_css.html"> <link rel="import" href="../../prefs/prefs_behavior.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages_types.html"> <dom-module id="settings-input-method-options-page"> <template>
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/input_page.html b/chrome/browser/resources/settings/chromeos/os_languages_page/input_page.html index 1fd3102..866aba5 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/input_page.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/input_page.html
@@ -23,7 +23,7 @@ <link rel="import" href="../../router.html"> <link rel="import" href="../../settings_shared_css.html"> <link rel="import" href="../../settings_page/settings_animated_pages.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages_types.html"> <dom-module id="os-settings-input-page"> <template>
diff --git a/chrome/browser/resources/settings/languages_page/languages.js b/chrome/browser/resources/settings/chromeos/os_languages_page/languages.js similarity index 95% rename from chrome/browser/resources/settings/languages_page/languages.js rename to chrome/browser/resources/settings/chromeos/os_languages_page/languages.js index 7622222..7bab7c9 100644 --- a/chrome/browser/resources/settings/languages_page/languages.js +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/languages.js
@@ -10,15 +10,15 @@ * this class via languageHelper. */ -import '../prefs/prefs.js'; +import '../../prefs/prefs.js'; import {assert} from '//resources/js/assert.m.js'; import {loadTimeData} from '//resources/js/load_time_data.m.js'; import {PromiseResolver} from '//resources/js/promise_resolver.m.js'; import {html, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {PrefsBehavior, PrefsBehaviorInterface} from '../prefs/prefs_behavior.js'; -import {CrSettingsPrefs} from '../prefs/prefs_types.js'; +import {PrefsBehavior, PrefsBehaviorInterface} from '../../prefs/prefs_behavior.js'; +import {CrSettingsPrefs} from '../../prefs/prefs_types.js'; import {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from './languages_browser_proxy.js'; import {InputMethodsModel, LanguageHelper, LanguagesModel, LanguageState, SpellCheckLanguageState} from './languages_types.js'; @@ -48,12 +48,10 @@ // one in ui/base/ime/ash/extension_ime_util.h. const kArcImeLanguage = '_arc_ime_language_'; -// <if expr="chromeos"> // The IME ID for the Accessibility Common extension used by Dictation. /** @type {string} */ const ACCESSIBILITY_COMMON_IME_ID = '_ext_ime_egfdjlfmgnehecnclamagfafdccgfndpdictation'; -// </if> /** * @typedef {{ @@ -147,7 +145,6 @@ }, }, - // <if expr="chromeos"> /** * Hash map of supported input methods by ID for fast lookup. * @private {!Map<string, chrome.languageSettingsPrivate.InputMethod>} @@ -182,12 +179,9 @@ return new Set(); } }, - // </if> - // <if expr="is_win or chromeos"> /** @private Prospective UI language when the page was loaded. */ originalProspectiveUILanguage_: String, - // </if> }; } @@ -199,9 +193,7 @@ 'prefs.translate_whitelists.value.*, languages)', 'neverTranslateLanguagesPrefChanged_(' + 'prefs.translate_blocked_languages.value.*, languages)', - // <if expr="is_win or chromeos"> 'prospectiveUILanguageChanged_(prefs.intl.app_locale.value, languages)', - // </if> 'preferredLanguagesPrefChanged_(' + 'prefs.intl.accept_languages.value, languages)', 'preferredLanguagesPrefChanged_(' + @@ -229,10 +221,8 @@ constructor() { super(); - // <if expr="not is_macosx"> /** @private {?Function} */ this.boundOnSpellcheckDictionariesChanged_ = null; - // </if> /** @private {!LanguagesBrowserProxy} */ this.browserProxy_ = LanguagesBrowserProxyImpl.getInstance(); @@ -241,7 +231,6 @@ this.languageSettingsPrivate_ = this.browserProxy_.getLanguageSettingsPrivate(); - // <if expr="chromeos"> /** @private {!InputMethodPrivate} */ this.inputMethodPrivate_ = this.browserProxy_.getInputMethodPrivate(); @@ -253,7 +242,6 @@ /** @private {?Function} */ this.boundOnInputMethodChanged_ = null; - // </if> } /** @override */ @@ -296,7 +284,6 @@ resolve); }).then(result => args.translateTarget = result)); - // <if expr="chromeos"> promises.push( new Promise(resolve => { this.languageSettingsPrivate_.getInputMethodLists(function(lists) { @@ -308,7 +295,6 @@ promises.push(new Promise(resolve => { this.inputMethodPrivate_.getCurrentInputMethod(resolve); }).then(result => args.currentInputMethodId = result)); - // </if> // Get the list of language-codes to always translate. promises.push(new Promise(resolve => { @@ -322,7 +308,6 @@ resolve); }).then(result => args.neverTranslateCodes = result)); - // <if expr="is_win or chromeos"> // Fetch the starting UI language, which affects which actions should be // enabled. promises.push(this.browserProxy_.getProspectiveUILanguage().then( @@ -330,7 +315,6 @@ this.originalProspectiveUILanguage_ = prospectiveUILanguage || window.navigator.language; })); - // </if> Promise.all(promises).then(results => { if (!this.isConnected) { @@ -341,19 +325,16 @@ this.createModel_(args); - // <if expr="not is_macosx"> this.boundOnSpellcheckDictionariesChanged_ = this.onSpellcheckDictionariesChanged_.bind(this); this.languageSettingsPrivate_.onSpellcheckDictionariesChanged.addListener( this.boundOnSpellcheckDictionariesChanged_); this.languageSettingsPrivate_.getSpellcheckDictionaryStatuses( this.boundOnSpellcheckDictionariesChanged_); - // </if> this.resolver_.resolve(); }); - // <if expr="chromeos"> this.boundOnInputMethodChanged_ = this.onInputMethodChanged_.bind(this); this.inputMethodPrivate_.onChanged.addListener( assert(this.boundOnInputMethodChanged_)); @@ -363,14 +344,12 @@ this.boundOnInputMethodRemoved_ = this.onInputMethodRemoved_.bind(this); this.languageSettingsPrivate_.onInputMethodRemoved.addListener( this.boundOnInputMethodRemoved_); - // </if> } /** @override */ disconnectedCallback() { super.disconnectedCallback(); - // <if expr="chromeos"> this.inputMethodPrivate_.onChanged.removeListener( assert(this.boundOnInputMethodChanged_)); this.boundOnInputMethodChanged_ = null; @@ -380,18 +359,14 @@ this.languageSettingsPrivate_.onInputMethodRemoved.removeListener( assert(this.boundOnInputMethodRemoved_)); this.boundOnInputMethodRemoved_ = null; - // </if> - // <if expr="not is_macosx"> if (this.boundOnSpellcheckDictionariesChanged_) { this.languageSettingsPrivate_.onSpellcheckDictionariesChanged .removeListener(this.boundOnSpellcheckDictionariesChanged_); this.boundOnSpellcheckDictionariesChanged_ = null; } - // </if> } - // <if expr="is_win or chromeos"> /** * Updates the prospective UI language based on the new pref value. * @param {string} prospectiveUILanguage @@ -402,7 +377,6 @@ 'languages.prospectiveUILanguage', prospectiveUILanguage || this.originalProspectiveUILanguage_); } - // </if> /** * Updates the list of enabled languages from the preferred languages pref. @@ -424,12 +398,10 @@ this.set('languages.enabled', enabledLanguageStates); - // <if expr="not is_macosx"> if (this.boundOnSpellcheckDictionariesChanged_) { this.languageSettingsPrivate_.getSpellcheckDictionaryStatuses( this.boundOnSpellcheckDictionariesChanged_); } - // </if> // Update translate target language. new Promise(resolve => { @@ -640,12 +612,10 @@ } let prospectiveUILanguage; - // <if expr="is_win or chromeos"> // eslint-disable-next-line prefer-const prospectiveUILanguage = /** @type {string} */ (this.getPref('intl.app_locale').value) || this.originalProspectiveUILanguage_; - // </if> // Create a list of enabled languages from the supported languages. const enabledLanguageStates = this.getEnabledLanguageStates_( @@ -674,11 +644,8 @@ spellCheckOffLanguages, }); - // <if expr="is_win or chromeos"> model.prospectiveUILanguage = prospectiveUILanguage; - // </if> - // <if expr="chromeos"> if (args.supportedInputMethods) { this.createInputMethodModel_(args.supportedInputMethods); } @@ -687,7 +654,6 @@ enabled: this.getEnabledInputMethods_(), currentId: args.currentInputMethodId, }); - // </if> // Initialize the Polymer languages model. this._setLanguages(model); @@ -776,7 +742,6 @@ (!prospectiveUILanguage || code !== prospectiveUILanguage); } - // <if expr="not is_macosx"> /** * Updates the dictionary download status for spell check languages in order * to track the number of times a spell check dictionary download has failed. @@ -815,7 +780,6 @@ }); }); } - // </if> /** * Updates the |removable| property of the enabled language states based @@ -830,9 +794,7 @@ // TODO(michaelpg): Enabled input methods can affect which languages are // removable, so run updateEnabledInputMethods_ first (if it has been // scheduled). - // <if expr="chromeos"> this.updateEnabledInputMethods_(); - // </if> for (let i = 0; i < this.languages.enabled.length; i++) { const languageState = this.languages.enabled[i]; @@ -862,7 +824,6 @@ return this.resolver_.promise; } - // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't affect * the actual UI language until a restart. @@ -880,7 +841,6 @@ return this.originalProspectiveUILanguage_ !== this.languages.prospectiveUILanguage; } - // </if> /** * @return {string} The language code for ARC IMEs. @@ -943,24 +903,16 @@ return; } - // Remove the language from spell check. - // <if expr="not chromeos"> - this.deletePrefListItem('spellcheck.dictionaries', languageCode); - // </if> - - // <if expr="chromeos"> // For CrOS language settings V2 update 2, languages and spell check are // decoupled so there's no need to remove the language from spell check. if (!this.isChromeOSLanguageSettingsV2Update2_()) { this.deletePrefListItem('spellcheck.dictionaries', languageCode); } - // </if> // Remove the language from preferred languages. this.languageSettingsPrivate_.disableLanguage(languageCode); } - // <if expr="chromeos"> /** * @return {boolean} * @private @@ -969,7 +921,6 @@ return loadTimeData.valueExists('enableLanguageSettingsV2Update2') && loadTimeData.getBoolean('enableLanguageSettingsV2Update2'); } - // </if> /** * @param {!LanguageState} languageState @@ -986,15 +937,6 @@ * @return {boolean} */ canDisableLanguage(languageState) { - // Cannot disable the prospective UI language. - // Exception for Chrome OS as language preference is decoupled from - // UI language. - // <if expr="not chromeos"> - if (languageState.language.code === this.languages.prospectiveUILanguage) { - return false; - } - // </if> - // Cannot disable the only enabled language. if (this.languages.enabled.length === 1) { return false; @@ -1180,10 +1122,6 @@ this.languageSettingsPrivate_.retryDownloadDictionary(languageCode); } - // TODO(crbug/1126259): Once migration is over, use separate languages.js for - // browser and chromeos - - // <if expr="chromeos"> /** * Constructs the input method part of the languages model. * @param {!Array<!chrome.languageSettingsPrivate.InputMethod>} @@ -1375,7 +1313,6 @@ } return inputMethod.displayName; } - // </if> } customElements.define(SettingsLanguagesElement.is, SettingsLanguagesElement);
diff --git a/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js b/chrome/browser/resources/settings/chromeos/os_languages_page/languages_browser_proxy.js similarity index 90% rename from chrome/browser/resources/settings/languages_page/languages_browser_proxy.js rename to chrome/browser/resources/settings/chromeos/os_languages_page/languages_browser_proxy.js index 8f542e9..b70243f 100644 --- a/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/languages_browser_proxy.js
@@ -11,9 +11,8 @@ import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; // clang-format on - /** @interface */ +/** @interface */ export class LanguagesBrowserProxy { - // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't * affect the actual UI language until a restart. @@ -24,22 +23,17 @@ /** @return {!Promise<string>} */ getProspectiveUILanguage() {} - // </if> - /** @return {!LanguageSettingsPrivate} */ getLanguageSettingsPrivate() {} - // <if expr="chromeos"> /** @return {!InputMethodPrivate} */ getInputMethodPrivate() {} - // </if> } /** * @implements {LanguagesBrowserProxy} */ export class LanguagesBrowserProxyImpl { - // <if expr="chromeos or is_win"> /** @override */ setProspectiveUILanguage(languageCode) { chrome.send('setProspectiveUILanguage', [languageCode]); @@ -50,20 +44,16 @@ return sendWithPromise('getProspectiveUILanguage'); } - // </if> - /** @override */ getLanguageSettingsPrivate() { return /** @type {!LanguageSettingsPrivate} */ ( chrome.languageSettingsPrivate); } - // <if expr="chromeos"> /** @override */ getInputMethodPrivate() { return /** @type {!InputMethodPrivate} */ (chrome.inputMethodPrivate); } - // </if> /** @return {!LanguagesBrowserProxy} */ static getInstance() {
diff --git a/chrome/browser/resources/settings/languages_page/languages_types.js b/chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.js similarity index 98% rename from chrome/browser/resources/settings/languages_page/languages_types.js rename to chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.js index b7eb532..578e8e62 100644 --- a/chrome/browser/resources/settings/languages_page/languages_types.js +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.js
@@ -87,7 +87,6 @@ /** @return {!Promise} */ whenReady() {} - // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't affect * the actual UI language until a restart. @@ -101,8 +100,6 @@ */ requiresRestart() {} - // </if> - /** * @return {string} The language code for ARC IMEs. */ @@ -226,7 +223,6 @@ /** @param {string} languageCode */ retryDownloadDictionary(languageCode) {} - // <if expr="chromeos"> /** @param {string} id */ addInputMethod(id) {} @@ -274,5 +270,4 @@ * @return {string} */ getInputMethodDisplayName(id) {} - // </if> }
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/os_add_languages_dialog.html b/chrome/browser/resources/settings/chromeos/os_languages_page/os_add_languages_dialog.html index 295d18e..3231a25 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/os_add_languages_dialog.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/os_add_languages_dialog.html
@@ -10,8 +10,8 @@ <link rel="import" href="chrome://resources/html/load_time_data.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html"> <link rel="import" href="shared_style.html"> -<link rel="import" href="../../languages_page/languages.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages.html"> +<link rel="import" href="languages_types.html"> <link rel="import" href="../../settings_shared_css.html"> <dom-module id="os-settings-add-languages-dialog">
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/os_edit_dictionary_page.html b/chrome/browser/resources/settings/chromeos/os_languages_page/os_edit_dictionary_page.html index 04816ba..4ae332a 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/os_edit_dictionary_page.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/os_edit_dictionary_page.html
@@ -11,7 +11,7 @@ <link rel="import" href="../os_route.html"> <link rel="import" href="../global_scroll_target_behavior.html"> <link rel="import" href="../../settings_shared_css.html"> -<link rel="import" href="../../languages_page/languages_browser_proxy.html"> +<link rel="import" href="languages_browser_proxy.html"> <dom-module id="os-settings-edit-dictionary-page"> <template>
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page_v2.html b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page_v2.html index 444e3e8..3c5e1261 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page_v2.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page_v2.html
@@ -25,7 +25,7 @@ <link rel="import" href="../../router.html"> <link rel="import" href="../../settings_shared_css.html"> <link rel="import" href="../metrics_recorder.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages_types.html"> <dom-module id="os-settings-languages-page-v2"> <template>
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_section.html b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_section.html index 0e925758..3fae712 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_section.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_section.html
@@ -8,14 +8,14 @@ <link rel="import" href="smart_inputs_page.html"> <link rel="import" href="input_method_options_page.html"> <link rel="import" href="../../i18n_setup.html"> -<link rel="import" href="../../languages_page/languages.html"> +<link rel="import" href="languages.html"> <link rel="import" href="../os_route.html"> <link rel="import" href="../../router.html"> <link rel="import" href="../../settings_page/settings_animated_pages.html"> <link rel="import" href="../../settings_page/settings_subpage.html"> <link rel="import" href="../../settings_shared_css.html"> <link rel="import" href="../../settings_vars_css.html"> -<link rel="import" href="../../languages_page/languages_types.html"> +<link rel="import" href="languages_types.html"> <dom-module id="os-settings-languages-section"> <template>
diff --git a/chrome/browser/resources/settings/chromeos/os_settings.gni b/chrome/browser/resources/settings/chromeos/os_settings.gni index cb2e506..820639f 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings.gni +++ b/chrome/browser/resources/settings/chromeos/os_settings.gni
@@ -238,7 +238,7 @@ "chrome/browser/resources/settings/chromeos/route_origin_behavior.html|RouteOriginBehaviorImpl,RouteOriginBehavior", "chrome/browser/resources/settings/controls/settings_dropdown_menu.html|DropdownMenuOptionList", "chrome/browser/resources/settings/chromeos/global_scroll_target_behavior.html|GlobalScrollTargetBehavior,setGlobalScrollTarget", - "chrome/browser/resources/settings/languages_page/languages_browser_proxy.html|LanguagesBrowserProxy,LanguagesBrowserProxyImpl", + "chrome/browser/resources/settings/chromeos/os_languages_page/languages_browser_proxy.html|LanguagesBrowserProxy,LanguagesBrowserProxyImpl", "chrome/browser/resources/settings/lifetime_browser_proxy.html|LifetimeBrowserProxyImpl", "chrome/browser/resources/settings/people_page/account_manager_browser_proxy.html|AccountManagerBrowserProxy,AccountManagerBrowserProxyImpl,Account", "chrome/browser/resources/settings/people_page/profile_info_browser_proxy.html|ProfileInfoBrowserProxyImpl,ProfileInfoBrowserProxy,ProfileInfo", @@ -430,6 +430,9 @@ "chrome/browser/resources/settings/chromeos/os_files_page/smb_shares_page.html", "chrome/browser/resources/settings/chromeos/os_languages_page/add_spellcheck_languages_dialog.html", "chrome/browser/resources/settings/chromeos/os_languages_page/cr_checkbox_with_policy.html", + "chrome/browser/resources/settings/chromeos/os_languages_page/languages_browser_proxy.html", + "chrome/browser/resources/settings/chromeos/os_languages_page/languages.html", + "chrome/browser/resources/settings/chromeos/os_languages_page/languages_types.html", "chrome/browser/resources/settings/chromeos/os_printing_page/cups_add_print_server_dialog.html", "chrome/browser/resources/settings/chromeos/os_printing_page/cups_add_printer_dialog.html", "chrome/browser/resources/settings/chromeos/os_printing_page/cups_add_printer_manually_dialog.html", @@ -488,9 +491,6 @@ "chrome/browser/resources/settings/chromeos/global_scroll_target_behavior.html", "chrome/browser/resources/settings/i18n_setup.html", "chrome/browser/resources/settings/icons.html", - "chrome/browser/resources/settings/languages_page/languages_browser_proxy.html", - "chrome/browser/resources/settings/languages_page/languages.html", - "chrome/browser/resources/settings/languages_page/languages_types.html", "chrome/browser/resources/settings/lifetime_browser_proxy.html", "chrome/browser/resources/settings/people_page/account_manager_browser_proxy.html", "chrome/browser/resources/settings/people_page/profile_info_browser_proxy.html",
diff --git a/chrome/browser/resources/settings/languages_page/BUILD.gn b/chrome/browser/resources/settings/languages_page/BUILD.gn index ca3cbca..911dfdcd 100644 --- a/chrome/browser/resources/settings/languages_page/BUILD.gn +++ b/chrome/browser/resources/settings/languages_page/BUILD.gn
@@ -3,68 +3,15 @@ # found in the LICENSE file. import("//build/config/chromeos/ui_mode.gni") -import("//third_party/closure_compiler/compile_js.gni") import("//tools/polymer/html_to_js.gni") -import("../settings.gni") -js_type_check("closure_compile") { - is_polymer3 = true - closure_flags = settings_closure_flags - deps = [ - ":languages", - ":languages_browser_proxy", - ":languages_types", - ] -} +assert(!is_chromeos_ash) -js_library("languages_types") { - externs_list = [ "$externs_path/language_settings_private.js" ] -} - -js_library("languages") { - deps = [ - ":languages_browser_proxy", - ":languages_types", - "../prefs:prefs", - "../prefs:prefs_behavior", - "../prefs:prefs_types", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - "//ui/webui/resources/js:assert.m", - "//ui/webui/resources/js:cr.m", - "//ui/webui/resources/js:i18n_behavior.m", - "//ui/webui/resources/js:load_time_data.m", - "//ui/webui/resources/js:promise_resolver.m", +html_to_js("web_components") { + js_files = [ + "add_languages_dialog.ts", + "edit_dictionary_page.ts", + "languages_page.ts", + "languages_subpage.ts", ] - externs_list = [ - "$externs_path/input_method_private.js", - "$externs_path/language_settings_private.js", - ] - extra_sources = [ - "$interfaces_path/input_method_private_interface.js", - "$interfaces_path/language_settings_private_interface.js", - ] -} - -js_library("languages_browser_proxy") { - deps = [ "//ui/webui/resources/js:cr.m" ] - externs_list = [ - "$externs_path/chrome_send.js", - "$externs_path/input_method_private.js", - "$externs_path/language_settings_private.js", - ] - extra_sources = [ - "$interfaces_path/input_method_private_interface.js", - "$interfaces_path/language_settings_private_interface.js", - ] -} - -if (!is_chromeos_ash) { - html_to_js("web_components") { - js_files = [ - "add_languages_dialog.ts", - "edit_dictionary_page.ts", - "languages_page.ts", - "languages_subpage.ts", - ] - } }
diff --git a/chrome/browser/resources/settings/languages_page/languages.ts b/chrome/browser/resources/settings/languages_page/languages.ts new file mode 100644 index 0000000..5a7edc5 --- /dev/null +++ b/chrome/browser/resources/settings/languages_page/languages.ts
@@ -0,0 +1,979 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview 'settings-languages' handles Chrome's language and input + * method settings. The 'languages' property, which reflects the current + * language settings, must not be changed directly. Instead, changes to + * language settings should be made using the LanguageHelper APIs provided by + * this class via languageHelper. + */ + +import '../prefs/prefs.js'; + +import {assert} from '//resources/js/assert.m.js'; +import {loadTimeData} from '//resources/js/load_time_data.m.js'; +import {PromiseResolver} from '//resources/js/promise_resolver.m.js'; +import {html, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {PrefsBehavior, PrefsBehaviorInterface} from '../prefs/prefs_behavior.js'; +import {CrSettingsPrefs} from '../prefs/prefs_types.js'; + +import {LanguagesBrowserProxy, LanguagesBrowserProxyImpl} from './languages_browser_proxy.js'; +import {LanguageHelper, LanguagesModel, LanguageState, SpellCheckLanguageState} from './languages_types.js'; + +type SpellCheckLanguages = { + on: Array<SpellCheckLanguageState>, + off: Array<SpellCheckLanguageState>, +}; + +const MoveType = chrome.languageSettingsPrivate.MoveType; + +// Translate server treats some language codes the same. +// See also: components/translate/core/common/translate_util.cc. +const kLanguageCodeToTranslateCode: {[key: string]: string} = { + 'nb': 'no', + 'fil': 'tl', + 'zh-HK': 'zh-TW', + 'zh-MO': 'zh-TW', + 'zh-SG': 'zh-CN', +}; + +// Some ISO 639 language codes have been renamed, e.g. "he" to "iw", but +// Translate still uses the old versions. TODO(michaelpg): Chrome does too. +// Follow up with Translate owners to understand the right thing to do. +const kTranslateLanguageSynonyms: {[key: string]: string} = { + 'he': 'iw', + 'jv': 'jw', +}; + +// The fake language name used for ARC IMEs. The value must be in sync with the +// one in ui/base/ime/ash/extension_ime_util.h. +const kArcImeLanguage: string = '_arc_ime_language_'; + +type ModelArgs = { + initialized: boolean, + supportedLanguages: Array<chrome.languageSettingsPrivate.Language>, + translateTarget: string, + alwaysTranslateCodes: Array<string>, + neverTranslateCodes: Array<string>, + startingUILanguage: string, + supportedInputMethods?: Array<chrome.languageSettingsPrivate.InputMethod>, + currentInputMethodId?: string, +}; + +/** + * Singleton element that generates the languages model on start-up and + * updates it whenever Chrome's pref store and other settings change. + */ + +const SettingsLanguagesElementBase = + mixinBehaviors([PrefsBehavior], PolymerElement) as + {new (): PolymerElement & PrefsBehaviorInterface}; + +class SettingsLanguagesElement extends SettingsLanguagesElementBase implements + LanguageHelper { + static get is() { + return 'settings-languages'; + } + + static get properties() { + return { + languages: { + type: Object, + notify: true, + }, + + /** + * This element, as a LanguageHelper instance for API usage. + */ + languageHelper: { + type: Object, + notify: true, + readOnly: true, + value() { + return this; + }, + }, + + /** + * PromiseResolver to be resolved when the singleton has been initialized. + */ + resolver_: { + type: Object, + value: () => new PromiseResolver(), + }, + + /** + * Hash map of supported languages by language codes for fast lookup. + */ + supportedLanguageMap_: { + type: Object, + value: () => new Map(), + }, + + /** + * Hash set of enabled language codes for membership testing. + */ + enabledLanguageSet_: { + type: Object, + value: () => new Set(), + }, + + // <if expr="is_win"> + /** Prospective UI language when the page was loaded. */ + originalProspectiveUILanguage_: String, + // </if> + }; + } + + static get observers() { + return [ + // All observers wait for the model to be populated by including the + // |languages| property. + 'alwaysTranslateLanguagesPrefChanged_(' + + 'prefs.translate_whitelists.value.*, languages)', + 'neverTranslateLanguagesPrefChanged_(' + + 'prefs.translate_blocked_languages.value.*, languages)', + // <if expr="is_win"> + 'prospectiveUILanguageChanged_(prefs.intl.app_locale.value, languages)', + // </if> + 'preferredLanguagesPrefChanged_(' + + 'prefs.intl.accept_languages.value, languages)', + 'preferredLanguagesPrefChanged_(' + + 'prefs.intl.forced_languages.value.*, languages)', + 'spellCheckDictionariesPrefChanged_(' + + 'prefs.spellcheck.dictionaries.value.*, ' + + 'prefs.spellcheck.forced_dictionaries.value.*, ' + + 'prefs.spellcheck.blocked_dictionaries.value.*, languages)', + 'translateLanguagesPrefChanged_(' + + 'prefs.translate_blocked_languages.value.*, languages)', + 'translateTargetPrefChanged_(' + + 'prefs.translate_recent_target.value, languages)', + 'updateRemovableLanguages_(' + + 'prefs.intl.app_locale.value, languages.enabled)', + 'updateRemovableLanguages_(' + + 'prefs.translate_blocked_languages.value.*)', + ]; + } + + languages?: LanguagesModel|undefined; + languageHelper: LanguageHelper; + private resolver_: PromiseResolver<void>; + private supportedLanguageMap_: + Map<string, chrome.languageSettingsPrivate.Language>; + private enabledLanguageSet_: Set<string>; + + // <if expr="is_win"> + private originalProspectiveUILanguage_: string; + // </if> + + // <if expr="not is_macosx"> + private boundOnSpellcheckDictionariesChanged_: + ((statuses: + Array<chrome.languageSettingsPrivate.SpellcheckDictionaryStatus>) => + void)|null = null; + // </if> + + private browserProxy_: LanguagesBrowserProxy = + LanguagesBrowserProxyImpl.getInstance(); + private languageSettingsPrivate_: typeof chrome.languageSettingsPrivate; + + constructor() { + super(); + + this.languageSettingsPrivate_ = + this.browserProxy_.getLanguageSettingsPrivate(); + } + + connectedCallback() { + super.connectedCallback(); + + const promises = []; + + /** + * An object passed into createModel to keep track of platform-specific + * arguments, populated by the "promises" array. + */ + const args: ModelArgs = { + initialized: false, + supportedLanguages: [], + translateTarget: '', + alwaysTranslateCodes: [], + neverTranslateCodes: [], + startingUILanguage: '', + + // Only used by ChromeOS + supportedInputMethods: [], + currentInputMethodId: '', + }; + + // Wait until prefs are initialized before creating the model, so we can + // include information about enabled languages. + promises.push( + CrSettingsPrefs.initialized.then(result => args.initialized = result)); + + // Get the language list. + promises.push( + new Promise<Array<chrome.languageSettingsPrivate.Language>>(resolve => { + this.languageSettingsPrivate_.getLanguageList(resolve); + }).then(result => { + args.supportedLanguages = result; + })); + + // Get the translate target language. + promises.push(new Promise<string>(resolve => { + this.languageSettingsPrivate_.getTranslateTargetLanguage( + resolve); + }).then(result => args.translateTarget = result)); + + // Get the list of language-codes to always translate. + promises.push(new Promise<Array<string>>(resolve => { + this.languageSettingsPrivate_.getAlwaysTranslateLanguages( + resolve); + }).then(result => { + args.alwaysTranslateCodes = result; + })); + + // Get the list of language-codes to never translate. + promises.push(new Promise<Array<string>>(resolve => { + this.languageSettingsPrivate_.getNeverTranslateLanguages( + resolve); + }).then(result => { + args.neverTranslateCodes = result; + })); + + // <if expr="is_win"> + // Fetch the starting UI language, which affects which actions should be + // enabled. + promises.push(this.browserProxy_.getProspectiveUILanguage().then( + prospectiveUILanguage => { + this.originalProspectiveUILanguage_ = + prospectiveUILanguage || window.navigator.language; + })); + // </if> + + Promise.all(promises).then(() => { + if (!this.isConnected) { + // Return early if this element was detached from the DOM before + // this async callback executes (can happen during testing). + return; + } + + this.createModel_(args); + + // <if expr="not is_macosx"> + this.boundOnSpellcheckDictionariesChanged_ = + this.onSpellcheckDictionariesChanged_.bind(this); + this.languageSettingsPrivate_.onSpellcheckDictionariesChanged.addListener( + this.boundOnSpellcheckDictionariesChanged_); + this.languageSettingsPrivate_.getSpellcheckDictionaryStatuses( + this.boundOnSpellcheckDictionariesChanged_); + // </if> + + this.resolver_.resolve(); + }); + } + + disconnectedCallback() { + super.disconnectedCallback(); + + // <if expr="not is_macosx"> + if (this.boundOnSpellcheckDictionariesChanged_) { + this.languageSettingsPrivate_.onSpellcheckDictionariesChanged + .removeListener(this.boundOnSpellcheckDictionariesChanged_); + this.boundOnSpellcheckDictionariesChanged_ = null; + } + // </if> + } + + // <if expr="is_win"> + /** + * Updates the prospective UI language based on the new pref value. + */ + private prospectiveUILanguageChanged_(prospectiveUILanguage: string) { + this.set( + 'languages.prospectiveUILanguage', + prospectiveUILanguage || this.originalProspectiveUILanguage_); + } + // </if> + + /** + * Updates the list of enabled languages from the preferred languages pref. + */ + private preferredLanguagesPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + + const enabledLanguageStates = this.getEnabledLanguageStates_( + this.languages.translateTarget, this.languages.prospectiveUILanguage); + + // Recreate the enabled language set before updating languages.enabled. + this.enabledLanguageSet_.clear(); + for (let i = 0; i < enabledLanguageStates.length; i++) { + this.enabledLanguageSet_.add(enabledLanguageStates[i].language.code); + } + + this.set('languages.enabled', enabledLanguageStates); + + // <if expr="not is_macosx"> + if (this.boundOnSpellcheckDictionariesChanged_) { + this.languageSettingsPrivate_.getSpellcheckDictionaryStatuses( + this.boundOnSpellcheckDictionariesChanged_); + } + // </if> + + // Update translate target language. + new Promise(resolve => { + this.languageSettingsPrivate_.getTranslateTargetLanguage(resolve); + }).then(result => { + this.set('languages.translateTarget', result); + }); + } + + /** + * Updates the spellCheckEnabled state of each enabled language. + */ + private spellCheckDictionariesPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + + const spellCheckSet = + this.makeSetFromArray_(this.getPref('spellcheck.dictionaries').value); + const spellCheckForcedSet = this.makeSetFromArray_( + this.getPref('spellcheck.forced_dictionaries').value); + const spellCheckBlockedSet = this.makeSetFromArray_( + this.getPref('spellcheck.blocked_dictionaries').value); + + for (let i = 0; i < this.languages.enabled.length; i++) { + const languageState = this.languages.enabled[i]; + const isUser = spellCheckSet.has(languageState.language.code); + const isForced = spellCheckForcedSet.has(languageState.language.code); + const isBlocked = spellCheckBlockedSet.has(languageState.language.code); + this.set( + `languages.enabled.${i}.spellCheckEnabled`, + (isUser && !isBlocked) || isForced); + this.set(`languages.enabled.${i}.isManaged`, isForced || isBlocked); + } + + const {on: spellCheckOnLanguages, off: spellCheckOffLanguages} = + this.getSpellCheckLanguages_(this.languages.supported); + this.set('languages.spellCheckOnLanguages', spellCheckOnLanguages); + this.set('languages.spellCheckOffLanguages', spellCheckOffLanguages); + } + + /** + * Returns two arrays of SpellCheckLanguageStates for spell check languages: + * one for spell check on, one for spell check off. + * @param supportedLanguages The list of supported languages, normally + * this.languages.supported. + */ + private getSpellCheckLanguages_( + supportedLanguages: Array<chrome.languageSettingsPrivate.Language>): + SpellCheckLanguages { + // The spell check preferences are prioritised in this order: + // forced_dictionaries, blocked_dictionaries, dictionaries. + + // The set of all language codes seen thus far. + const seenCodes = new Set<string>(); + + /** + * Gets the list of language codes indicated by the preference name, and + * de-duplicates it with all other language codes. + */ + const getPrefAndDedupe = (prefName: string): Array<string> => { + const result = + this.getPref(prefName).value.filter((x: string) => !seenCodes.has(x)); + result.forEach((code: string) => seenCodes.add(code)); + return result; + }; + + const forcedCodes = getPrefAndDedupe('spellcheck.forced_dictionaries'); + const forcedCodesSet = new Set(forcedCodes); + const blockedCodes = getPrefAndDedupe('spellcheck.blocked_dictionaries'); + const blockedCodesSet = new Set(blockedCodes); + const enabledCodes = getPrefAndDedupe('spellcheck.dictionaries'); + + const /** !Array<SpellCheckLanguageState> */ on = []; + // We want to add newly enabled languages to the end of the "on" list, so we + // should explicitly move the forced languages to the front of the list. + for (const code of [...forcedCodes, ...enabledCodes]) { + const language = this.supportedLanguageMap_.get(code); + // language could be undefined if code is not in supportedLanguageMap_. + // This should be rare, but could happen if supportedLanguageMap_ is + // missing languages or the prefs are manually modified. We want to fail + // gracefully if this happens - throwing an error here would cause + // language settings to not load. + if (language) { + on.push({ + language, + isManaged: forcedCodesSet.has(code), + spellCheckEnabled: true, + downloadDictionaryStatus: null, + downloadDictionaryFailureCount: 0, + }); + } + } + + // Because the list of "spell check supported" languages is only exposed + // through "supported languages", we need to filter that list along with + // whether we've seen the language before. + // We don't want to split this list in "forced" / "not-forced" like the + // spell check on list above, as we don't want to explicitly surface / hide + // blocked languages to the user. + const /** !Array<SpellCheckLanguageState> */ off = []; + + for (const language of supportedLanguages) { + // If spell check is off for this language, it must either not be in any + // spell check pref, or be in the blocked dictionaries pref. + if (language.supportsSpellcheck && + (!seenCodes.has(language.code) || + blockedCodesSet.has(language.code))) { + off.push({ + language, + isManaged: blockedCodesSet.has(language.code), + spellCheckEnabled: false, + downloadDictionaryStatus: null, + downloadDictionaryFailureCount: 0 + }); + } + } + + return { + on, + off, + }; + } + + /** + * Updates the list of always translate languages from translate prefs. + */ + private alwaysTranslateLanguagesPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + const alwaysTranslateCodes = + Object.keys(this.getPref('translate_whitelists').value); + const alwaysTranslateLanguages = + alwaysTranslateCodes.map(code => this.getLanguage(code)); + this.set('languages.alwaysTranslate', alwaysTranslateLanguages); + } + + /** + * Updates the list of never translate languages from translate prefs. + */ + private neverTranslateLanguagesPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + const neverTranslateCodes = + this.getPref('translate_blocked_languages').value; + const neverTranslateLanguages = + neverTranslateCodes.map((code: string) => this.getLanguage(code)); + this.set('languages.neverTranslate', neverTranslateLanguages); + } + + private translateLanguagesPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + + const translateBlockedPrefValue = + this.getPref('translate_blocked_languages').value as Array<string>; + const translateBlockedSet = + this.makeSetFromArray_(translateBlockedPrefValue); + + for (let i = 0; i < this.languages.enabled.length; i++) { + const language = this.languages.enabled[i].language; + const translateEnabled = this.isTranslateEnabled_( + language.code, !!language.supportsTranslate, translateBlockedSet, + this.languages.translateTarget, this.languages.prospectiveUILanguage); + this.set( + 'languages.enabled.' + i + '.translateEnabled', translateEnabled); + } + } + + private translateTargetPrefChanged_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + this.set( + 'languages.translateTarget', + this.getPref('translate_recent_target').value); + } + + /** + * Constructs the languages model. + * @param args used to populate the model above. + */ + private createModel_(args: ModelArgs) { + // Populate the hash map of supported languages. + for (let i = 0; i < args.supportedLanguages.length; i++) { + const language = args.supportedLanguages[i]; + language.supportsUI = !!language.supportsUI; + language.supportsTranslate = !!language.supportsTranslate; + language.supportsSpellcheck = !!language.supportsSpellcheck; + language.isProhibitedLanguage = !!language.isProhibitedLanguage; + this.supportedLanguageMap_.set(language.code, language); + } + + let prospectiveUILanguage; + // <if expr="is_win"> + // eslint-disable-next-line prefer-const + prospectiveUILanguage = this.getPref('intl.app_locale').value || + this.originalProspectiveUILanguage_; + // </if> + + // Create a list of enabled languages from the supported languages. + const enabledLanguageStates = this.getEnabledLanguageStates_( + args.translateTarget, prospectiveUILanguage); + // Populate the hash set of enabled languages. + for (let l = 0; l < enabledLanguageStates.length; l++) { + this.enabledLanguageSet_.add(enabledLanguageStates[l].language.code); + } + + const {on: spellCheckOnLanguages, off: spellCheckOffLanguages} = + this.getSpellCheckLanguages_(args.supportedLanguages); + + const alwaysTranslateLanguages = + args.alwaysTranslateCodes.map(code => this.getLanguage(code)!); + + const neverTranslateLangauges = + args.neverTranslateCodes.map(code => this.getLanguage(code)!); + + const model = { + supported: args.supportedLanguages, + enabled: enabledLanguageStates, + translateTarget: args.translateTarget, + alwaysTranslate: alwaysTranslateLanguages, + neverTranslate: neverTranslateLangauges, + spellCheckOnLanguages, + spellCheckOffLanguages, + // <if expr="is_win"> + prospectiveUILanguage: prospectiveUILanguage, + // </if> + }; + + // Initialize the Polymer languages model. + this.languages = model; + } + + /** + * Returns a list of LanguageStates for each enabled language in the supported + * languages list. + * @param translateTarget Language code of the default translate + * target language. + * @param prospectiveUILanguage Prospective UI display language. Only defined + * on Windows and Chrome OS. + */ + private getEnabledLanguageStates_( + translateTarget: string, + prospectiveUILanguage: string|undefined): Array<LanguageState> { + assert(CrSettingsPrefs.isInitialized); + + const pref = this.getPref('intl.accept_languages'); + const enabledLanguageCodes = pref.value.split(','); + const languagesForcedPref = this.getPref('intl.forced_languages'); + const spellCheckPref = this.getPref('spellcheck.dictionaries'); + const spellCheckForcedPref = this.getPref('spellcheck.forced_dictionaries'); + const spellCheckBlockedPref = + this.getPref('spellcheck.blocked_dictionaries'); + const languageForcedSet = this.makeSetFromArray_(languagesForcedPref.value); + const spellCheckSet = this.makeSetFromArray_( + spellCheckPref.value.concat(spellCheckForcedPref.value)); + const spellCheckForcedSet = + this.makeSetFromArray_(spellCheckForcedPref.value); + const spellCheckBlockedSet = + this.makeSetFromArray_(spellCheckBlockedPref.value); + + const translateBlockedPrefValue = + this.getPref('translate_blocked_languages').value as Array<string>; + const translateBlockedSet = + this.makeSetFromArray_(translateBlockedPrefValue); + + const enabledLanguageStates: Array<LanguageState> = []; + + for (let i = 0; i < enabledLanguageCodes.length; i++) { + const code = enabledLanguageCodes[i]; + const language = this.supportedLanguageMap_.get(code); + // Skip unsupported languages. + if (!language) { + continue; + } + const languageState: LanguageState = { + language: language, + spellCheckEnabled: + spellCheckSet.has(code) && !spellCheckBlockedSet.has(code) || + spellCheckForcedSet.has(code), + translateEnabled: this.isTranslateEnabled_( + code, !!language.supportsTranslate, translateBlockedSet, + translateTarget, prospectiveUILanguage), + isManaged: + spellCheckForcedSet.has(code) || spellCheckBlockedSet.has(code), + isForced: languageForcedSet.has(code), + downloadDictionaryFailureCount: 0, + removable: false, + downloadDictionaryStatus: null, + }; + enabledLanguageStates.push(languageState); + } + return enabledLanguageStates; + } + + /** + * True iff we translate pages that are in the given language. + * @param code Language code. + * @param supportsTranslate If translation supports the given language. + * @param translateBlockedSet Set of languages for which translation is + * blocked. + * @param translateTarget Language code of the default translate target + * language. + * @param prospectiveUILanguage Prospective UI display language. Only define + * on Windows and Chrome OS. + */ + private isTranslateEnabled_( + code: string, supportsTranslate: boolean, + translateBlockedSet: Set<string>, translateTarget: string, + prospectiveUILanguage: string|undefined): boolean { + const translateCode = this.convertLanguageCodeForTranslate(code); + return supportsTranslate && !translateBlockedSet.has(translateCode) && + translateCode !== translateTarget && + (!prospectiveUILanguage || code !== prospectiveUILanguage); + } + + // <if expr="not is_macosx"> + /** + * Updates the dictionary download status for spell check languages in order + * to track the number of times a spell check dictionary download has failed. + */ + private onSpellcheckDictionariesChanged_( + statuses: + Array<chrome.languageSettingsPrivate.SpellcheckDictionaryStatus>) { + const statusMap = new Map(); + statuses.forEach(status => { + statusMap.set(status.languageCode, status); + }); + + const collectionNames = + ['enabled', 'spellCheckOnLanguages', 'spellCheckOffLanguages']; + const languages = this.languages as unknown as + {[k: string]: Array<LanguageState|SpellCheckLanguageState>}; + collectionNames.forEach(collectionName => { + languages[collectionName].forEach((languageState, index) => { + const status = statusMap.get(languageState.language.code); + if (!status) { + return; + } + + const previousStatus = languageState.downloadDictionaryStatus; + const keyPrefix = `languages.${collectionName}.${index}`; + this.set(`${keyPrefix}.downloadDictionaryStatus`, status); + + const failureCountKey = `${keyPrefix}.downloadDictionaryFailureCount`; + if (status.downloadFailed && + !(previousStatus && previousStatus.downloadFailed)) { + const failureCount = languageState.downloadDictionaryFailureCount + 1; + this.set(failureCountKey, failureCount); + } else if ( + status.isReady && !(previousStatus && previousStatus.isReady)) { + this.set(failureCountKey, 0); + } + }); + }); + } + // </if> + + /** + * Updates the |removable| property of the enabled language states based + * on what other languages and input methods are enabled. + */ + private updateRemovableLanguages_() { + if (this.prefs === undefined || this.languages === undefined) { + return; + } + + for (let i = 0; i < this.languages.enabled.length; i++) { + const languageState = this.languages.enabled[i]; + this.set( + 'languages.enabled.' + i + '.removable', + this.canDisableLanguage(languageState)); + } + } + + /** + * Creates a Set from the elements of the array. + */ + private makeSetFromArray_<T>(list: Array<T>): Set<T> { + return new Set(list); + } + + // LanguageHelper implementation. + whenReady(): Promise<void> { + return this.resolver_.promise; + } + + // <if expr="is_win"> + /** + * Sets the prospective UI language to the chosen language. This won't affect + * the actual UI language until a restart. + */ + setProspectiveUILanguage(languageCode: string) { + this.browserProxy_.setProspectiveUILanguage(languageCode); + } + + /** + * True if the prospective UI language was changed from its starting value. + */ + requiresRestart(): boolean { + return this.originalProspectiveUILanguage_ !== + this.languages!.prospectiveUILanguage; + } + // </if> + + /** + * @return The language code for ARC IMEs. + */ + getArcImeLanguageCode(): string { + return kArcImeLanguage; + } + + /** + * @return True if the language is for ARC IMEs. + */ + isLanguageCodeForArcIme(languageCode: string): boolean { + return languageCode === kArcImeLanguage; + } + + /** + * @return True if the language can be translated by Chrome. + */ + isLanguageTranslatable(language: chrome.languageSettingsPrivate.Language): + boolean { + if (language.code === 'zh-CN' || language.code === 'zh-TW') { + // In Translate, general Chinese is not used, and the sub code is + // necessary as a language code for the Translate server. + return true; + } + if (language.code === this.getLanguageCodeWithoutRegion(language.code) && + language.supportsTranslate) { + return true; + } + return false; + } + + /** + * @return True if the language is enabled. + */ + isLanguageEnabled(languageCode: string): boolean { + return this.enabledLanguageSet_.has(languageCode); + } + + /** + * Enables the language, making it available for spell check and input. + */ + enableLanguage(languageCode: string) { + if (!CrSettingsPrefs.isInitialized) { + return; + } + + this.languageSettingsPrivate_.enableLanguage(languageCode); + } + + /** + * Disables the language. + */ + disableLanguage(languageCode: string) { + if (!CrSettingsPrefs.isInitialized) { + return; + } + + // Remove the language from spell check. + this.deletePrefListItem('spellcheck.dictionaries', languageCode); + + // Remove the language from preferred languages. + this.languageSettingsPrivate_.disableLanguage(languageCode); + } + + isOnlyTranslateBlockedLanguage(languageState: LanguageState): boolean { + return !languageState.translateEnabled && + this.languages!.enabled.filter(lang => !lang.translateEnabled) + .length === 1; + } + + canDisableLanguage(languageState: LanguageState): boolean { + // Cannot disable the prospective UI language. + if (languageState.language.code === this.languages!.prospectiveUILanguage) { + return false; + } + + // Cannot disable the only enabled language. + if (this.languages!.enabled.length === 1) { + return false; + } + + // Cannot disable the last translate blocked language. + if (this.isOnlyTranslateBlockedLanguage(languageState)) { + return false; + } + + return true; + } + + canEnableLanguage(language: chrome.languageSettingsPrivate.Language): + boolean { + return !( + this.isLanguageEnabled(language.code) || + language.isProhibitedLanguage || + this.isLanguageCodeForArcIme(language.code) /* internal use only */); + } + + /** + * Sets whether a given language should always be automatically translated. + */ + setLanguageAlwaysTranslateState( + languageCode: string, alwaysTranslate: boolean) { + this.languageSettingsPrivate_.setLanguageAlwaysTranslateState( + languageCode, alwaysTranslate); + } + + /** + * Moves the language in the list of enabled languages either up (toward the + * front of the list) or down (toward the back). + * @param upDirection True if we need to move up, false if we need to move + * down + */ + moveLanguage(languageCode: string, upDirection: boolean) { + if (!CrSettingsPrefs.isInitialized) { + return; + } + + if (upDirection) { + this.languageSettingsPrivate_.moveLanguage(languageCode, MoveType.UP); + } else { + this.languageSettingsPrivate_.moveLanguage(languageCode, MoveType.DOWN); + } + } + + /** + * Moves the language directly to the front of the list of enabled languages. + */ + moveLanguageToFront(languageCode: string) { + if (!CrSettingsPrefs.isInitialized) { + return; + } + + this.languageSettingsPrivate_.moveLanguage(languageCode, MoveType.TOP); + } + + /** + * Enables translate for the given language by removing the translate + * language from the blocked languages preference. + */ + enableTranslateLanguage(languageCode: string) { + this.languageSettingsPrivate_.setEnableTranslationForLanguage( + languageCode, true); + } + + /** + * Disables translate for the given language by adding the translate + * language to the blocked languages preference. + */ + disableTranslateLanguage(languageCode: string) { + this.languageSettingsPrivate_.setEnableTranslationForLanguage( + languageCode, false); + } + + /** + * Sets the translate target language and adds it to the content languages if + * not already there. + */ + setTranslateTargetLanguage(languageCode: string) { + this.languageSettingsPrivate_.setTranslateTargetLanguage(languageCode); + } + + /** + * Enables or disables spell check for the given language. + */ + toggleSpellCheck(languageCode: string, enable: boolean) { + if (!this.languages) { + return; + } + + if (enable) { + const spellCheckPref = this.getPref('spellcheck.dictionaries'); + this.appendPrefListItem('spellcheck.dictionaries', languageCode); + } else { + this.deletePrefListItem('spellcheck.dictionaries', languageCode); + } + } + + /** + * Converts the language code for translate. There are some differences + * between the language set the Translate server uses and that for + * Accept-Language. + */ + convertLanguageCodeForTranslate(languageCode: string): string { + if (languageCode in kLanguageCodeToTranslateCode) { + return kLanguageCodeToTranslateCode[languageCode]; + } + + const main = languageCode.split('-')[0]; + if (main === 'zh') { + // In Translate, general Chinese is not used, and the sub code is + // necessary as a language code for the Translate server. + return languageCode; + } + if (main in kTranslateLanguageSynonyms) { + return kTranslateLanguageSynonyms[main]; + } + + return main; + } + + /** + * Given a language code, returns just the base language. E.g., converts + * 'en-GB' to 'en'. + */ + getLanguageCodeWithoutRegion(languageCode: string): string { + // The Norwegian languages fall under the 'no' macrolanguage. + if (languageCode === 'nb' || languageCode === 'nn') { + return 'no'; + } + + // The installer still uses the old language code "iw", instead of "he", + // for Hebrew. It needs to be converted to "he", otherwise it will not be + // found in supportedLanguageMap_. + // + // Note that this value is saved in the user's local state. Even + // if the installer is changed to use "he", because the installer does not + // overwrite this value, the conversion is still needed for old users. + if (languageCode === 'iw') { + return 'he'; + } + + // Match the characters before the hyphen. + const result = languageCode.match(/^([^-]+)-?/)!; + assert(result.length === 2); + return result[1]; + } + + getLanguage(languageCode: string): chrome.languageSettingsPrivate.Language + |undefined { + // If a languageCode is not found, try language without location. + return this.supportedLanguageMap_.get(languageCode) || + this.supportedLanguageMap_.get( + this.getLanguageCodeWithoutRegion(languageCode)); + } + + /** + * Retries downloading the dictionary for |languageCode|. + */ + retryDownloadDictionary(languageCode: string) { + this.languageSettingsPrivate_.retryDownloadDictionary(languageCode); + } +} + +customElements.define(SettingsLanguagesElement.is, SettingsLanguagesElement);
diff --git a/chrome/browser/resources/settings/languages_page/languages_browser_proxy.ts b/chrome/browser/resources/settings/languages_page/languages_browser_proxy.ts new file mode 100644 index 0000000..3bc607e0 --- /dev/null +++ b/chrome/browser/resources/settings/languages_page/languages_browser_proxy.ts
@@ -0,0 +1,54 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview A helper object used from the languages section + * to interact with the browser. + */ + +// clang-format off +import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; +// clang-format on + +export interface LanguagesBrowserProxy { + // <if expr="is_win"> + /** + * Sets the prospective UI language to the chosen language. This won't + * affect the actual UI language until a restart. + */ + setProspectiveUILanguage(languageCode: string): void; + + getProspectiveUILanguage(): Promise<string>; + + // </if> + + getLanguageSettingsPrivate(): typeof chrome.languageSettingsPrivate; +} + +export class LanguagesBrowserProxyImpl implements LanguagesBrowserProxy { + // <if expr="is_win"> + setProspectiveUILanguage(languageCode: string) { + chrome.send('setProspectiveUILanguage', [languageCode]); + } + + getProspectiveUILanguage() { + return sendWithPromise('getProspectiveUILanguage'); + } + + // </if> + + getLanguageSettingsPrivate() { + return chrome.languageSettingsPrivate; + } + + static getInstance(): LanguagesBrowserProxy { + return instance || (instance = new LanguagesBrowserProxyImpl()); + } + + static setInstance(obj: LanguagesBrowserProxy) { + instance = obj; + } +} + +let instance: LanguagesBrowserProxy|null = null;
diff --git a/chrome/browser/resources/settings/languages_page/languages_types.ts b/chrome/browser/resources/settings/languages_page/languages_types.ts new file mode 100644 index 0000000..5d3841b --- /dev/null +++ b/chrome/browser/resources/settings/languages_page/languages_types.ts
@@ -0,0 +1,168 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Closure typedefs for dictionaries and interfaces used by + * language settings. + */ + +/** + * Settings and state for a particular enabled language. + */ +export type LanguageState = { + language: chrome.languageSettingsPrivate.Language, + removable: boolean, + spellCheckEnabled: boolean, + translateEnabled: boolean, + isManaged: boolean, + isForced: boolean, + downloadDictionaryFailureCount: number, + downloadDictionaryStatus: + (chrome.languageSettingsPrivate.SpellcheckDictionaryStatus|null), +}; + +/** + * Settings and state for spellcheck languages. + */ +export type SpellCheckLanguageState = { + language: chrome.languageSettingsPrivate.Language, + spellCheckEnabled: boolean, + isManaged: boolean, + downloadDictionaryFailureCount: number, + downloadDictionaryStatus: + (chrome.languageSettingsPrivate.SpellcheckDictionaryStatus|null), +}; + +/** + * Languages data to expose to consumers. + * supported: an array of languages, ordered alphabetically, set once + * at initialization. + * enabled: an array of enabled language states, ordered by preference. + * translateTarget: the default language to translate into. + * prospectiveUILanguage: the "prospective" UI language, i.e., the one to be + * used on next restart. Matches the current UI language preference unless + * the user has chosen a different language without restarting. May differ + * from the actually used language (navigator.language). Chrome OS and + * Windows only. + * spellCheckOnLanguages: an array of spell check languages that are currently + * in use, including the languages force-enabled by policy. + * spellCheckOffLanguages: an array of spell check languages that are currently + * not in use, including the languages force-disabled by policy. + */ +export type LanguagesModel = { + supported: Array<chrome.languageSettingsPrivate.Language>, + enabled: Array<LanguageState>, + translateTarget: string, + alwaysTranslate: Array<chrome.languageSettingsPrivate.Language>, + neverTranslate: Array<chrome.languageSettingsPrivate.Language>, + spellCheckOnLanguages: Array<SpellCheckLanguageState>, + spellCheckOffLanguages: Array<SpellCheckLanguageState>, + // TODO(dpapad): Wrap prospectiveUILanguage with if expr "is_win" block. + prospectiveUILanguage?: string, +}; + +/** + * Helper methods for reading and writing language settings. + * @interface + */ +export interface LanguageHelper { + whenReady(): Promise<void>; + + // <if expr="is_win"> + /** + * Sets the prospective UI language to the chosen language. This won't affect + * the actual UI language until a restart. + */ + setProspectiveUILanguage(languageCode: string): void; + + /** + * True if the prospective UI language has been changed. + */ + requiresRestart(): boolean; + + // </if> + + /** + * @return The language code for ARC IMEs. + */ + getArcImeLanguageCode(): string; + + isLanguageCodeForArcIme(languageCode: string): boolean; + + isLanguageTranslatable(language: chrome.languageSettingsPrivate.Language): + boolean; + isLanguageEnabled(languageCode: string): boolean; + + /** + * Enables the language, making it available for spell check and input. + */ + enableLanguage(languageCode: string): void; + + disableLanguage(languageCode: string): void; + + /** + * Returns true iff provided languageState is the only blocked language. + */ + isOnlyTranslateBlockedLanguage(languageState: LanguageState): boolean; + + /** + * Returns true iff provided languageState can be disabled. + */ + canDisableLanguage(languageState: LanguageState): boolean; + + canEnableLanguage(language: chrome.languageSettingsPrivate.Language): boolean; + + /** + * Moves the language in the list of enabled languages by the given offset. + * @param upDirection True if we need to move toward the front, false if we + * need to move toward the back. + */ + moveLanguage(languageCode: string, upDirection: boolean): void; + + /** + * Moves the language directly to the front of the list of enabled languages. + */ + moveLanguageToFront(languageCode: string): void; + + /** + * Enables translate for the given language by removing the translate + * language from the blocked languages preference. + */ + enableTranslateLanguage(languageCode: string): void; + + /** + * Disables translate for the given language by adding the translate + * language to the blocked languages preference. + */ + disableTranslateLanguage(languageCode: string): void; + + /** + * Sets whether a given language should always be automatically translated. + */ + setLanguageAlwaysTranslateState( + languageCode: string, alwaysTranslate: boolean): void; + + /** + * Enables or disables spell check for the given language. + */ + toggleSpellCheck(languageCode: string, enable: boolean): void; + + /** + * Converts the language code for translate. There are some differences + * between the language set the Translate server uses and that for + * Accept-Language. + */ + convertLanguageCodeForTranslate(languageCode: string): string; + + /** + * Given a language code, returns just the base language. E.g., converts + * 'en-GB' to 'en'. + */ + getLanguageCodeWithoutRegion(languageCode: string): string; + + getLanguage(languageCode: string): chrome.languageSettingsPrivate.Language + |undefined; + + retryDownloadDictionary(languageCode: string): void; +}
diff --git a/chrome/browser/signin/services/android/java/src/org/chromium/chrome/browser/signin/services/FREMobileIdentityConsistencyFieldTrial.java b/chrome/browser/signin/services/android/java/src/org/chromium/chrome/browser/signin/services/FREMobileIdentityConsistencyFieldTrial.java index 8bc6f3f..38f38d0 100644 --- a/chrome/browser/signin/services/android/java/src/org/chromium/chrome/browser/signin/services/FREMobileIdentityConsistencyFieldTrial.java +++ b/chrome/browser/signin/services/android/java/src/org/chromium/chrome/browser/signin/services/FREMobileIdentityConsistencyFieldTrial.java
@@ -7,7 +7,9 @@ import androidx.annotation.AnyThread; import androidx.annotation.MainThread; +import org.chromium.base.CommandLine; import org.chromium.base.annotations.CalledByNative; +import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; @@ -30,8 +32,8 @@ @AnyThread public static boolean isEnabled() { - // Disabled by default. - return ENABLED_GROUP.equals(getFirstRunTrialGroup()); + return CommandLine.getInstance().hasSwitch(ChromeSwitches.FORCE_ENABLE_SIGNIN_FRE) + || ENABLED_GROUP.equals(getFirstRunTrialGroup()); } @CalledByNative @@ -72,26 +74,4 @@ ChromePreferenceKeys.FIRST_RUN_FIELD_TRIAL_GROUP, group); } } - - /** - * Enables MobileIdentityConsistencyFRE experiment for tests. - */ - @AnyThread - public static void enableForTesting() { - synchronized (LOCK) { - SharedPreferencesManager.getInstance().writeString( - ChromePreferenceKeys.FIRST_RUN_FIELD_TRIAL_GROUP, ENABLED_GROUP); - } - } - - /** - * Disables MobileIdentityConsistencyFRE experiment for tests. - */ - @AnyThread - public static void disableForTesting() { - synchronized (LOCK) { - SharedPreferencesManager.getInstance().writeString( - ChromePreferenceKeys.FIRST_RUN_FIELD_TRIAL_GROUP, DISABLED_GROUP); - } - } } \ No newline at end of file
diff --git a/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml b/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml index 6595a3a..7271a1f 100644 --- a/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml +++ b/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml
@@ -71,6 +71,7 @@ <include layout="@layout/account_row" /> <ImageView + android:id="@+id/signin_fre_selected_account_expand_icon" android:layout_width="24dp" android:layout_height="24dp" android:layout_marginStart="16dp"
diff --git a/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/fre/SigninFirstRunViewBinder.java b/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/fre/SigninFirstRunViewBinder.java index 33a4904..aee989e 100644 --- a/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/fre/SigninFirstRunViewBinder.java +++ b/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/fre/SigninFirstRunViewBinder.java
@@ -74,11 +74,12 @@ .setVisibility(model.get(SigninFirstRunProperties.SELECTED_ACCOUNT_DATA) == null ? View.GONE : View.VISIBLE); + final boolean isSelectedAccountSupervised = + model.get(SigninFirstRunProperties.IS_SELECTED_ACCOUNT_SUPERVISED); view.findViewById(R.id.signin_fre_dismiss_button) - .setVisibility( - model.get(SigninFirstRunProperties.IS_SELECTED_ACCOUNT_SUPERVISED) - ? View.GONE - : View.VISIBLE); + .setVisibility(isSelectedAccountSupervised ? View.GONE : View.VISIBLE); + view.findViewById(R.id.signin_fre_selected_account_expand_icon) + .setVisibility(isSelectedAccountSupervised ? View.INVISIBLE : View.VISIBLE); } else { view.findViewById(R.id.signin_fre_selected_account).setVisibility(View.GONE); view.findViewById(R.id.signin_fre_dismiss_button).setVisibility(View.GONE);
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 3becd710..250ac5e 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1903,6 +1903,8 @@ "app_list/search/ranking/ranker.h", "app_list/search/ranking/ranker_delegate.cc", "app_list/search/ranking/ranker_delegate.h", + "app_list/search/ranking/score_normalizer.cc", + "app_list/search/ranking/score_normalizer.h", "app_list/search/ranking/score_normalizing_ranker.cc", "app_list/search/ranking/score_normalizing_ranker.h", "app_list/search/ranking/top_match_ranker.cc",
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 2a37d00..cba4e80 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -321,6 +321,15 @@ <message name="IDS_AUTOCOMPLETE_SEARCHES_AND_URLS_SUMMARY" desc="Summary for a checkbox in Settings that controls URL and search autocompletion and informs the user about the data shared by this feature."> Sends some cookies and searches from the address bar and search box to your default search engine </message> + <message name ="IDS_SETTINGS_INCOGNITO_TAB_LOCK_TITLE" desc = "Title for a toggle in Settings that allows users to lock their existing Incognito tabs with a device reauthentication mechanism."> + Lock Incognito tabs when you leave Chrome + </message> + <message name ="IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_ON" desc = "Summary for a toggle in Settings that allows users to lock their existing Incognito tabs with a device reauthentication mechanism. This summary is shown to the user when the screen lock setting is on in the device."> + Use screen lock to see open Incognito tabs + </message> + <message name ="IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_OFF" desc = "Summary for the Incognito tab lock toggle in Settings which asks the user to turn on screen lock in Android settings if it's off. Clicking on the text takes the user to Android settings."> + <ph name="BEGIN_LINK"><link></ph>Turn on screen lock in Android settings<ph name="END_LINK"></link></ph> + </message> <message name="IDS_PRELOAD_PAGES_TITLE" desc="Title for a checkbox in Settings that controls pages preloading and informs the user about the data shared by this feature."> Preload pages for faster browsing and searching </message>
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_OFF.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_OFF.png.sha1 new file mode 100644 index 0000000..8a9a5919 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_OFF.png.sha1
@@ -0,0 +1 @@ +0d4e81b3200587bf44526e20581f2cfda89194aa \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_ON.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_ON.png.sha1 new file mode 100644 index 0000000..07f67c8 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_SUMMARY_ANDROID_SETTING_ON.png.sha1
@@ -0,0 +1 @@ +06d2f6e2ba6ac602444572177d7604e1d31e20b0 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_TITLE.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_TITLE.png.sha1 new file mode 100644 index 0000000..8a9a5919 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SETTINGS_INCOGNITO_TAB_LOCK_TITLE.png.sha1
@@ -0,0 +1 @@ +0d4e81b3200587bf44526e20581f2cfda89194aa \ No newline at end of file
diff --git a/chrome/browser/ui/app_list/search/ranking/BUILD.gn b/chrome/browser/ui/app_list/search/ranking/BUILD.gn index 1f4aeb3..3851d55 100644 --- a/chrome/browser/ui/app_list/search/ranking/BUILD.gn +++ b/chrome/browser/ui/app_list/search/ranking/BUILD.gn
@@ -8,5 +8,6 @@ sources = [ "mrfu_cache.proto", "persistent_proto_test.proto", + "score_normalizer.proto", ] }
diff --git a/chrome/browser/ui/app_list/search/ranking/mrfu_cache.h b/chrome/browser/ui/app_list/search/ranking/mrfu_cache.h index 7de7bdb8a..a1f9071 100644 --- a/chrome/browser/ui/app_list/search/ranking/mrfu_cache.h +++ b/chrome/browser/ui/app_list/search/ranking/mrfu_cache.h
@@ -8,6 +8,7 @@ #include <map> #include <string> +#include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/app_list/search/ranking/mrfu_cache.pb.h"
diff --git a/chrome/browser/ui/app_list/search/ranking/score_normalizer.cc b/chrome/browser/ui/app_list/search/ranking/score_normalizer.cc new file mode 100644 index 0000000..a9fdc74e --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/score_normalizer.cc
@@ -0,0 +1,44 @@ +// 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. + +#include "chrome/browser/ui/app_list/search/ranking/score_normalizer.h" + +namespace app_list { +namespace { + +// This should be incremented whenever a change to the algorithm is made that +// is incompatible with on-disk state. On reading, any state is wiped if its +// version doesn't match. +const int32_t kModelVersion = 1; + +} // namespace + +ScoreNormalizer::ScoreNormalizer(const base::FilePath& filepath, + const Params& params) + : params_(params) { + proto_.Init( + filepath, params.write_delay, + base::BindOnce(&ScoreNormalizer::OnProtoRead, weak_factory_.GetWeakPtr()), + base::DoNothing()); +} + +ScoreNormalizer::~ScoreNormalizer() {} + +void ScoreNormalizer::OnProtoRead(ReadStatus status) { + DCHECK(proto_.initialized()); + + // TODO(crbug.com/1199206): Add error metrics based on |status|. + + if ((proto_->has_model_version() && + proto_->model_version() != kModelVersion) || + (proto_->has_parameter_version() && + proto_->parameter_version() != params_.version)) { + proto_.Purge(); + } + + proto_->set_model_version(kModelVersion); + proto_->set_parameter_version(params_.version); +} + +} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/score_normalizer.h b/chrome/browser/ui/app_list/search/ranking/score_normalizer.h new file mode 100644 index 0000000..4f41dd8 --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/score_normalizer.h
@@ -0,0 +1,58 @@ +// 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. + +#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_SCORE_NORMALIZER_H_ +#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_SCORE_NORMALIZER_H_ + +#include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/app_list/search/ranking/persistent_proto.h" +#include "chrome/browser/ui/app_list/search/ranking/score_normalizer.pb.h" + +namespace app_list { + +// The score normalizer is a heuristic model that attempts to map a incoming +// stream of numbers drawn from a fixed distribution into a uniform +// distribution. +// +// TODO(crbug.com/1199206): Add more description once the algorithm is +// finalized. +class ScoreNormalizer { + public: + // All user-settable parameters of the score normalizer. The struct has some + // reasonable defaults, but this should be customized per use-case. + struct Params { + // A version for this set of parameters. This is saved alongside on-disk + // state for the ScoreNormalizer and, if it doesn't match on reading, the + // on-disk state is cleared. + int32_t version = 1; + + // How long to wait until writing any updates to disk. + base::TimeDelta write_delay = base::TimeDelta::FromSeconds(30); + + // TODO(crbug.com/1199206): Add model parameters. + }; + + ScoreNormalizer(const base::FilePath& filepath, const Params& params); + ~ScoreNormalizer(); + + ScoreNormalizer(const ScoreNormalizer&) = delete; + ScoreNormalizer& operator=(const ScoreNormalizer&) = delete; + + // TODO(crbug.com/1199206): Add API methods. + + private: + friend class ScoreNormalizerTest; + + void OnProtoRead(ReadStatus status); + + PersistentProto<ScoreNormalizerProto> proto_; + Params params_; + + base::WeakPtrFactory<ScoreNormalizer> weak_factory_{this}; +}; + +} // namespace app_list + +#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_SCORE_NORMALIZER_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/score_normalizer.proto b/chrome/browser/ui/app_list/search/ranking/score_normalizer.proto new file mode 100644 index 0000000..11f00bb0 --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/score_normalizer.proto
@@ -0,0 +1,26 @@ +// 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. + +syntax = "proto2"; + +option optimize_for = LITE_RUNTIME; + +package app_list; + +// The storage proto for the ScoreNormalizer class, see its header comment for +// more information. +message ScoreNormalizerProto { + // Versioning information for the ScoreNormalizer itself, which is used to + // discard on-disk state if an incompatible change is made to the score + // normalizer's algorithm. + optional int32 model_version = 1; + + // Versioning information for the user-settable parameters of each instance + // of a ScoreNormalizer. This is set with the |version| member of the Params + // passed to a ScoreNormalizer. On initialization, if the versions don't + // match, the on-disk state is wiped. + optional int32 parameter_version = 2; + + // TODO(crbug.com/1199206): Add model state. +}
diff --git a/chrome/browser/ui/app_list/search/ranking/score_normalizer_unittest.cc b/chrome/browser/ui/app_list/search/ranking/score_normalizer_unittest.cc new file mode 100644 index 0000000..873afc16 --- /dev/null +++ b/chrome/browser/ui/app_list/search/ranking/score_normalizer_unittest.cc
@@ -0,0 +1,77 @@ +// 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. + +#include "chrome/browser/ui/app_list/search/ranking/score_normalizer.h" + +#include "base/files/scoped_temp_dir.h" +#include "base/logging.h" +#include "base/test/task_environment.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace app_list { + +class ScoreNormalizerTest : public testing::Test { + public: + void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } + + base::FilePath GetPath() { return temp_dir_.GetPath().Append("proto"); } + + ScoreNormalizer::Params TestingParams() { + ScoreNormalizer::Params params; + params.version = 4; + params.write_delay = base::TimeDelta::FromSeconds(0); + return params; + } + + ScoreNormalizerProto ReadFromDisk() { + std::string proto_str; + CHECK(base::ReadFileToString(GetPath(), &proto_str)); + ScoreNormalizerProto proto; + CHECK(proto.ParseFromString(proto_str)); + return proto; + } + + void WriteToDisk(const ScoreNormalizerProto& proto) { + ASSERT_TRUE(base::WriteFile(GetPath(), proto.SerializeAsString())); + } + + void Wait() { task_environment_.RunUntilIdle(); } + + ScoreNormalizerProto* get_proto(ScoreNormalizer& normalizer) { + return normalizer.proto_.get(); + } + + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::MainThreadType::UI, + base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED, + base::test::TaskEnvironment::TimeSource::MOCK_TIME}; + base::ScopedTempDir temp_dir_; +}; + +// A dummy test to ensure that the score normalizer doesn't crash on +// initialization. +TEST_F(ScoreNormalizerTest, Initialize) { + ScoreNormalizer normalizer(GetPath(), TestingParams()); + Wait(); + SUCCEED(); +} + +TEST_F(ScoreNormalizerTest, StateClearedOnVersionChange) { + { + ScoreNormalizerProto proto; + proto.set_parameter_version(1); + WriteToDisk(proto); + } + + { + ScoreNormalizer normalizer(GetPath(), TestingParams()); + Wait(); + EXPECT_EQ(get_proto(normalizer)->parameter_version(), 4); + // TODO(crbug.com/1199206): Check that state is reset once it's added to the + // proto. + } +} + +} // namespace app_list
diff --git a/chrome/browser/ui/ui_features.cc b/chrome/browser/ui/ui_features.cc index 20a4b4ea..c320680 100644 --- a/chrome/browser/ui/ui_features.cc +++ b/chrome/browser/ui/ui_features.cc
@@ -65,11 +65,6 @@ const base::Feature kForceSignInReauth{"ForceSignInReauth", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables updated tabstrip animations, required for a scrollable tabstrip. -// https://crbug.com/958173 -const base::Feature kNewTabstripAnimation{"NewTabstripAnimation", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables a more prominent active tab title in dark mode to aid with // accessibility. const base::Feature kProminentDarkModeActiveTabTitle{
diff --git a/chrome/browser/ui/ui_features.h b/chrome/browser/ui/ui_features.h index 4655c91a..0350f77 100644 --- a/chrome/browser/ui/ui_features.h +++ b/chrome/browser/ui/ui_features.h
@@ -51,8 +51,6 @@ extern const base::Feature kForceSignInReauth; -extern const base::Feature kNewTabstripAnimation; - extern const base::Feature kProminentDarkModeActiveTabTitle; extern const base::Feature kReadLaterNewBadgePromo;
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_tab_list.cc b/chrome/browser/ui/views/desktop_capture/desktop_media_tab_list.cc index 9f8b2075..49d3b32 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_tab_list.cc +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_tab_list.cc
@@ -233,6 +233,9 @@ views::CreateSolidBackground(gfx::kGoogleGrey300)); empty_preview_label->SetPreferredSize(desktopcapture::kPreviewSize); empty_preview_label->SetSize(desktopcapture::kPreviewSize); + // Tell the label the background colour it's over. This just forces the text + // colour to one that's readable, notably in dark mode. + empty_preview_label->SetBackgroundColor(gfx::kGoogleGrey300); empty_preview_ = preview_wrapper->AddChildView(std::move(empty_preview_label));
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 5600a77..9659a04 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -182,6 +182,7 @@ #include "chrome/browser/ash/scanning/chrome_scanning_app_delegate.h" #include "chrome/browser/ash/scanning/scan_service.h" #include "chrome/browser/ash/scanning/scan_service_factory.h" +#include "chrome/browser/ash/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/ash/web_applications/chrome_camera_app_ui_delegate.h" #include "chrome/browser/ash/web_applications/chrome_file_manager_ui_delegate.h" #include "chrome/browser/ash/web_applications/help_app/help_app_ui_delegate.h" @@ -189,7 +190,6 @@ #include "chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.h" #include "chrome/browser/chromeos/eche_app/eche_app_manager_factory.h" #include "chrome/browser/chromeos/net/network_health/network_health_service.h" -#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/feedback/feedback_dialog_utils.h" #include "chrome/browser/nearby_sharing/nearby_sharing_service_factory.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h"
diff --git a/chrome/browser/ui/webui/chromeos/multidevice_internals/multidevice_internals_phone_hub_handler.cc b/chrome/browser/ui/webui/chromeos/multidevice_internals/multidevice_internals_phone_hub_handler.cc index a6981256..31d105c 100644 --- a/chrome/browser/ui/webui/chromeos/multidevice_internals/multidevice_internals_phone_hub_handler.cc +++ b/chrome/browser/ui/webui/chromeos/multidevice_internals/multidevice_internals_phone_hub_handler.cc
@@ -7,7 +7,7 @@ #include "ash/public/cpp/system_tray.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/components/phonehub/camera_roll_item.h" @@ -321,7 +321,7 @@ PA_LOG(VERBOSE) << "Setting real Phone Hub Manager"; Profile* profile = Profile::FromWebUI(web_ui()); chromeos::phonehub::PhoneHubManager* phone_hub_manager = - chromeos::phonehub::PhoneHubManagerFactory::GetForProfile(profile); + phonehub::PhoneHubManagerFactory::GetForProfile(profile); ash::SystemTray::Get()->SetPhoneHubManager(phone_hub_manager); RemoveObservers();
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc index de2211d..79ab0d6 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc
@@ -9,8 +9,8 @@ #include "chrome/browser/ash/android_sms/android_sms_service_factory.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h"
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc index 84ebb6bcb..7958314 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc
@@ -12,8 +12,8 @@ #include "chrome/browser/ash/android_sms/android_sms_service_factory.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 7d4f612..91db8b04 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -105,9 +105,9 @@ #include "chrome/browser/ash/android_sms/android_sms_app_manager.h" #include "chrome/browser/ash/android_sms/android_sms_service_factory.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" +#include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/browser_process_platform_part.h" -#include "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ui/webui/certificate_provisioning_ui_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h" @@ -411,7 +411,7 @@ ash::android_sms::AndroidSmsServiceFactory::GetForBrowserContext( profile); chromeos::phonehub::PhoneHubManager* phone_hub_manager = - chromeos::phonehub::PhoneHubManagerFactory::GetForProfile(profile); + ash::phonehub::PhoneHubManagerFactory::GetForProfile(profile); web_ui()->AddMessageHandler(std::make_unique< chromeos::settings::MultideviceHandler>( profile->GetPrefs(),
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 35138b9..352cef8d 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1632441416-7a8329d97839093c9a4def992490e7bcafb28549.profdata +chrome-linux-main-1632484244-b596124b24723501d208c93eae2bd86fceb5db6b.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 4da8b7b..04869957 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1632441416-cd8ce074cd62eabeea1ffbbb446738b9102d6a29.profdata +chrome-mac-main-1632484244-7b936c615165e58a3acdb61a4d274e36657917d2.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index dfffa0aa..e33aa02 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1632441416-a73451890a0e4bd9b30405b06c3d585120e1168b.profdata +chrome-win32-main-1632484244-927ce715b3082525ce9c6a042c2b5628ef50ef1f.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 766ff51..6897be6 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1632441416-b736a7d5146599d1778a5da93020a143b20da207.profdata +chrome-win64-main-1632484244-4af798eca3c92ac32465eedd990f94b44353fb7b.profdata
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index a788437..713a47d 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -768,8 +768,14 @@ "PredictivePrefetchingAllowedOnAllConnectionTypes", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kPrefixWebAppWindowsWithAppName{ - "PrefixWebAppWindowsWithAppName", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kPrefixWebAppWindowsWithAppName { + "PrefixWebAppWindowsWithAppName", +#if BUILDFLAG(IS_CHROMEOS_ASH) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; // Allows Chrome to do preconnect when prerender fails. const base::Feature kPrerenderFallbackToPreconnect{
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 10136d81..2e0b6e0 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -626,6 +626,9 @@ // Forces the update menu badge to show. const char kForceShowUpdateMenuBadge[] = "force-show-update-menu-badge"; +// Forces signin FRE flow. +const char kForceEnableSigninFRE[] = "force-enable-signin-fre"; + // Forces the update menu type to a specific type. const char kForceUpdateMenuType[] = "force-update-menu-type";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 0f76cd5..28c01af 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -189,6 +189,7 @@ extern const char kForceEnableNightMode[]; extern const char kForceShowUpdateMenuBadge[]; extern const char kForceShowUpdateMenuItemCustomSummary[]; +extern const char kForceEnableSigninFRE[]; extern const char kForceUpdateMenuType[]; extern const char kMarketUrlForTesting[]; #endif // defined(OS_ANDROID)
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index e685591..25ef59b 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -1737,6 +1737,11 @@ // This is only applicable for Android. const char kShowMissingSdCardErrorAndroid[] = "download.show_missing_sd_card_error_android"; + +// Boolean which specifies whether the user has turned on incognito +// reauthentication setting for Android. +const char kIncognitoReauthenticationForAndroid[] = + "incognito.incognito_reauthentication"; #endif // String which specifies where to save html files to by default.
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 7cf29b2..7009660f 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -585,6 +585,7 @@ extern const char kPromptForDownloadAndroid[]; extern const char kDownloadLaterPromptStatus[]; extern const char kShowMissingSdCardErrorAndroid[]; +extern const char kIncognitoReauthenticationForAndroid[]; #endif extern const char kSaveFileDefaultDirectory[];
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 844931f6..9bf1071 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -6400,6 +6400,7 @@ "../browser/ui/app_list/search/omnibox_result_unittest.cc", "../browser/ui/app_list/search/ranking/mrfu_cache_unittest.cc", "../browser/ui/app_list/search/ranking/persistent_proto_unittest.cc", + "../browser/ui/app_list/search/ranking/score_normalizer_unittest.cc", "../browser/ui/app_list/search/search_controller_unittest.cc", "../browser/ui/app_list/search/search_result_ranker/app_launch_event_logger_unittest.cc", "../browser/ui/app_list/search/search_result_ranker/app_launch_predictor_test_util.h",
diff --git a/chrome/test/chromedriver/element_util.cc b/chrome/test/chromedriver/element_util.cc index dbf8f6c..3afe481 100644 --- a/chrome/test/chromedriver/element_util.cc +++ b/chrome/test/chromedriver/element_util.cc
@@ -29,6 +29,26 @@ const char kElementKey[] = "ELEMENT"; const char kElementKeyW3C[] = "element-6066-11e4-a52e-4f735466cecf"; const char kShadowRootKey[] = "shadow-6066-11e4-a52e-4f735466cecf"; +const char kFindSubFrameScript[] = + "function findSubFrame(frame_id) {" + " const findSubFrameDeep = function(nodes, id) {" + " let r = null;" + " for (let i = 0, el; (el = nodes[i]) && !r; ++i) {" + " if ((el.tagName === 'IFRAME') " + " && el.getAttribute('cd_frame_id_') === id) {" + " r = el;" + " } else if (el.shadowRoot) {" + " r = findSubFrameDeep(el.shadowRoot.querySelectorAll('*'), id);" + " }" + " }" + " return r;" + " };" + " const xpath = \"//*[@cd_frame_id_ ='\" + frame_id + \"']\";" + " const r = document.evaluate(xpath, document, null," + " XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;" + " return r || findSubFrameDeep(document.querySelectorAll('*'), " + "frame_id);" + "}"; bool ParseFromValue(base::Value* value, WebPoint* point) { if (!value->is_dict()) @@ -877,19 +897,14 @@ center, clickable_element_id, ®ion_offset); if (status.IsError()) return status; - const char kFindSubFrameScript[] = - "function(xpath) {" - " return document.evaluate(xpath, document, null," - " XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;" - "}"; + // If the element is in a frame, go up the frame chain (from the innermost // frame up to the top-level window) and scroll each frame relative to its // parent frame, so that the region becomes visible in the parent frame. for (auto rit = session->frames.rbegin(); rit != session->frames.rend(); ++rit) { base::ListValue args; - args.Append(base::StringPrintf("//*[@cd_frame_id_ = '%s']", - rit->chromedriver_frame_id.c_str())); + args.Append(rit->chromedriver_frame_id.c_str()); std::unique_ptr<base::Value> result; status = web_view->CallFunction( rit->parent_frame_id, kFindSubFrameScript, args, &result); @@ -934,16 +949,11 @@ ¢er_location); if (status.IsError()) return status; - const char kFindSubFrameScript[] = - "function(xpath) {" - " return document.evaluate(xpath, document, null," - " XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;" - "}"; + for (auto rit = session->frames.rbegin(); rit != session->frames.rend(); ++rit) { base::ListValue args; - args.Append(base::StringPrintf("//*[@cd_frame_id_ = '%s']", - rit->chromedriver_frame_id.c_str())); + args.Append(rit->chromedriver_frame_id.c_str()); std::unique_ptr<base::Value> result; status = web_view->CallFunction(rit->parent_frame_id, kFindSubFrameScript, args, &result);
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 61c8b19..fc2f8277 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -3124,6 +3124,43 @@ is_desktop, self._driver.capabilities['webauthn:extension:largeBlob']) + def testCanClickInIframesInShadow(self): + """Test that you can interact with a iframe within a shadow element. + See https://bugs.chromium.org/p/chromedriver/issues/detail?id=3445 + """ + self._driver.SetTimeouts({'implicit': 2000}) + self._driver.Load(self.GetHttpUrlForFile( + '/chromedriver/shadow_iframe.html')) + frame = self._driver.ExecuteScript( + '''return document.querySelector("#shadow") + .shadowRoot.querySelector("iframe")''') + self._driver.SwitchToFrame(frame) + message = self._driver.FindElement('css selector', '#message') + self.assertTrue('clicked' not in message.GetText()) + button = self._driver.FindElement('tag name', 'button') + button.Click() + message = self._driver.FindElement('css selector', '#message.result') + self.assertTrue('clicked' in message.GetText()) + + def testCanClickInIframesInShadowScrolled(self): + """Test that you can interact with a scrolled iframe + within a scrolled shadow element. + See https://bugs.chromium.org/p/chromedriver/issues/detail?id=3445 + """ + self._driver.SetTimeouts({'implicit': 2000}) + self._driver.Load(self.GetHttpUrlForFile( + '/chromedriver/shadow_iframe.html')) + frame = self._driver.ExecuteScript( + '''return document.querySelector("#shadow_scroll") + .shadowRoot.querySelector("iframe")''') + self._driver.SwitchToFrame(frame) + message = self._driver.FindElement('css selector', '#message') + self.assertTrue('clicked' not in message.GetText()) + button = self._driver.FindElement('tag name', 'button') + button.Click() + message = self._driver.FindElement('css selector', '#message.result') + self.assertTrue('clicked' in message.GetText()) + class ChromeDriverBackgroundTest(ChromeDriverBaseTestWithWebServer): def setUp(self): self._driver1 = self.CreateDriver()
diff --git a/chrome/test/data/chromedriver/shadow_iframe.html b/chrome/test/data/chromedriver/shadow_iframe.html new file mode 100644 index 0000000..6e6d91b0e --- /dev/null +++ b/chrome/test/data/chromedriver/shadow_iframe.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8"> + <title>Test click in inframe inside shadow element</title> + <style> + #light { margin-bottom: 1000px; }; + </style> + <script> + function addIframe(parent, scroll) { + const iframe = document.createElement('iframe'); + iframe.src = './shadow_iframe_component.html' + + ((scroll) ? '?scroll=true' : ''); + parent.appendChild(iframe); + } + function load() { + const shadow = document.getElementById('shadow').attachShadow({ mode: 'open' }); + const shadow_scroll = document.getElementById('shadow_scroll').attachShadow({ mode: 'open' }); + const light = document.getElementById('light'); + addIframe(shadow, false); + addIframe(light, false); + addIframe(light_scroll, true); + addIframe(shadow_scroll, true); + } + </script> +</head> + +<body onload="load()"> + <div id="shadow"></div> + <div id="light"></div> + <div id="light_scroll"></div> + <div id="shadow_scroll"></div> +</body> + +</html>
diff --git a/chrome/test/data/chromedriver/shadow_iframe_component.html b/chrome/test/data/chromedriver/shadow_iframe_component.html new file mode 100644 index 0000000..9921f5be --- /dev/null +++ b/chrome/test/data/chromedriver/shadow_iframe_component.html
@@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8"> + <title>Inner iframe</title> + <style> + .scrolled { margin-top: 400px; }; + </style> + <script> + function print(msg) { + document.getElementById('message').innerHTML = msg; + document.getElementById('message').classList.add('result'); + } + window.onload = function() { + if (window.location.href.includes('scroll=true')) { + document.getElementById('b').classList.add('scrolled'); + } + } + </script> +</head> +<body> + <button id="b" onclick='print("clicked");'>Some button</button> + <div id="message"> + </div> +</body> +</html>
diff --git a/chrome/test/data/extensions/content_verifier/missing_verified_contents/README.txt b/chrome/test/data/extensions/content_verifier/missing_verified_contents/README.txt deleted file mode 100644 index ab5a0cb7..0000000 --- a/chrome/test/data/extensions/content_verifier/missing_verified_contents/README.txt +++ /dev/null
@@ -1,3 +0,0 @@ -The files in this directory came from -extensions/test/data/content_hash_fetcher/missing_verified_contents. Refer to -README.txt of above directory for more details.
diff --git a/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/manifest.json b/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/manifest.json deleted file mode 100644 index ad7600b..0000000 --- a/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/manifest.json +++ /dev/null
@@ -1,14 +0,0 @@ -{ -"update_url": "https://clients2.google.com/service/update2/crx", - - "name": "Hello Wikipedia Content Script", - "description": "Inserts 'hello world' on wikipedia pages", - "version": "0.8", - "manifest_version": 2, - "content_scripts": [ - { - "matches": ["*://*.wikipedia.org/*"], - "js": ["script.js"] - } - ] -}
diff --git a/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/script.js b/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/script.js deleted file mode 100644 index 63974fe1..0000000 --- a/chrome/test/data/extensions/content_verifier/missing_verified_contents/source/script.js +++ /dev/null
@@ -1,6 +0,0 @@ - -// trivial change for version 0.8 - -var hello = document.createElement("div"); -hello.innerText = "hello world"; -document.body.insertBefore(hello, document.body.firstChild);
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index c156ffdf..f60e4b3 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -10107,23 +10107,7 @@ ] }, "CloudPolicyOverridesPlatformPolicy": { - "os": [ - "win", - "linux", - "mac" - ], - "policy_pref_mapping_tests": [ - { - "policies": { - "CloudPolicyOverridesPlatformPolicy": false - }, - "prefs": { - "policy.cloud_override": { - "location": "local_state" - } - } - } - ] + "reason_for_missing_test": "This policy has no pref as it is only directly read by the policy system." }, "CloudUserPolicyOverridesCloudMachinePolicy": { "reason_for_missing_test": "This policy has no pref as it is only directly read by the policy system."
diff --git a/chrome/test/data/webui/chromeos/diagnostics/network_list_test.js b/chrome/test/data/webui/chromeos/diagnostics/network_list_test.js index e8cdf99..dc3f4a6 100644 --- a/chrome/test/data/webui/chromeos/diagnostics/network_list_test.js +++ b/chrome/test/data/webui/chromeos/diagnostics/network_list_test.js
@@ -175,14 +175,9 @@ // guid as it's the currently active guid. const wifiInfoElement = dx_utils.getWifiInfoElement( networkCardElements[0].$$('network-info')); - const cellularInfoElement = dx_utils.getCellularInfoElement( - networkCardElements[1].$$('network-info')); dx_utils.assertTextContains( wifiInfoElement.$$('#ssid').value, fakeWifiNetwork.typeProperties.wifi.ssid); - dx_utils.assertTextContains( - cellularInfoElement.$$('#iccid').value, - fakeCellularNetwork.typeProperties.cellular.iccid); assertEquals( getConnectivityCard().activeGuid,
diff --git a/chrome/test/data/webui/settings/BUILD.gn b/chrome/test/data/webui/settings/BUILD.gn index 997670c..999b21c 100644 --- a/chrome/test/data/webui/settings/BUILD.gn +++ b/chrome/test/data/webui/settings/BUILD.gn
@@ -146,22 +146,6 @@ #":zoom_levels_tests", ] - - if (!is_chromeos_ash) { - deps += [ - ":fake_language_settings_private", - ":test_languages_browser_proxy", - ] - } -} - -js_library("fake_language_settings_private") { - deps = [ - "..:chai_assert", - "..:fake_chrome_event.m", - "..:test_browser_proxy", - "//ui/webui/resources/js:cr.m", - ] } js_library("fake_input_method_private") { @@ -204,16 +188,6 @@ externs_list = [ "$externs_path/mocha-2.5.js" ] } -js_library("test_languages_browser_proxy") { - deps = [ - ":fake_input_method_private", - ":fake_language_settings_private", - "..:test_browser_proxy", - "//chrome/browser/resources/settings:lazy_load", - "//ui/webui/resources/js:cr.m", - ] -} - js_library("test_lifetime_browser_proxy") { deps = [ "..:test_browser_proxy",
diff --git a/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js b/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js index 1d021e1..3b1feed 100644 --- a/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js +++ b/chrome/test/data/webui/settings/languages_page_metrics_test_browser.js
@@ -4,7 +4,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {LanguageHelper, LanguagesBrowserProxyImpl, LanguageSettingsActionType, LanguageSettingsMetricsProxyImpl, LanguageSettingsPageImpressionType, SettingsLanguagesSubpageElement} from 'chrome://settings/lazy_load.js'; +import {LanguagesBrowserProxyImpl, LanguageSettingsActionType, LanguageSettingsMetricsProxyImpl, LanguageSettingsPageImpressionType, SettingsLanguagesSubpageElement} from 'chrome://settings/lazy_load.js'; import {CrSettingsPrefs} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from '../chai_assert.js';
diff --git a/chrome/test/data/webui/settings/test_languages_browser_proxy.js b/chrome/test/data/webui/settings/test_languages_browser_proxy.js index 738fe29d..083f02f2 100644 --- a/chrome/test/data/webui/settings/test_languages_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_languages_browser_proxy.js
@@ -3,12 +3,10 @@ // found in the LICENSE file. // clang-format off -import {isChromeOS, isWindows} from 'chrome://resources/js/cr.m.js'; -import {LanguagesBrowserProxy} from 'chrome://settings/lazy_load.js'; +import {isWindows} from 'chrome://resources/js/cr.m.js'; import {TestBrowserProxy} from '../test_browser_proxy.js'; -import {FakeInputMethodPrivate} from './fake_input_method_private.js'; import {FakeLanguageSettingsPrivate} from './fake_language_settings_private.js'; // clang-format on @@ -16,7 +14,7 @@ export class TestLanguagesBrowserProxy extends TestBrowserProxy { constructor() { const methodNames = []; - if (isChromeOS || isWindows) { + if (isWindows) { methodNames.push('getProspectiveUILanguage', 'setProspectiveUILanguage'); } @@ -24,10 +22,6 @@ /** @private {!LanguageSettingsPrivate} */ this.languageSettingsPrivate_ = new FakeLanguageSettingsPrivate(); - - /** @private {!InputMethodPrivate} */ - this.inputMethodPrivate_ = - /** @type{!InputMethodPrivate} */ (new FakeInputMethodPrivate()); } /** @override */ @@ -41,7 +35,7 @@ } } -if (isChromeOS || isWindows) { +if (isWindows) { /** @override */ TestLanguagesBrowserProxy.prototype.getProspectiveUILanguage = function() { this.methodCalled('getProspectiveUILanguage'); @@ -54,10 +48,3 @@ this.methodCalled('setProspectiveUILanguage', language); }; } - -if (isChromeOS) { - /** @override */ - TestLanguagesBrowserProxy.prototype.getInputMethodPrivate = function() { - return this.inputMethodPrivate_; - }; -}
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index fc88c23..6c34cb0 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -14237.0.0 \ No newline at end of file +14238.0.0 \ No newline at end of file
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index 9afe83ab..02a1a902 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -1067,6 +1067,9 @@ <message name="IDS_NETWORK_DIAGNOSTICS_VISIT_SETTINGS_TO_CONFIGURE_LINK_TEXT" desc="Help text that directs users to settings to configure their network."> Visit settings to configure </message> + <message name="IDS_NETWORK_DIAGNOSTICS_MISSING_NAME_SERVERS_TEXT" desc="The text shown when no name servers are configured."> + No name servers are configured + </message> <!-- Input diagnostics --> <message name="IDS_INPUT_DIAGNOSTICS_RUN_TEST" desc="Text for the button that runs a test for a specific input device">
diff --git a/chromeos/chromeos_strings_grd/IDS_NETWORK_DIAGNOSTICS_MISSING_NAME_SERVERS_TEXT.png.sha1 b/chromeos/chromeos_strings_grd/IDS_NETWORK_DIAGNOSTICS_MISSING_NAME_SERVERS_TEXT.png.sha1 new file mode 100644 index 0000000..e88da440 --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_NETWORK_DIAGNOSTICS_MISSING_NAME_SERVERS_TEXT.png.sha1
@@ -0,0 +1 @@ +73746946099c4c974852e63234501effa4f798f1 \ No newline at end of file
diff --git a/chromeos/components/camera_app_ui/resources/css/mode/video.css b/chromeos/components/camera_app_ui/resources/css/mode/video.css index 16caef0..2c30a545 100644 --- a/chromeos/components/camera_app_ui/resources/css/mode/video.css +++ b/chromeos/components/camera_app_ui/resources/css/mode/video.css
@@ -25,6 +25,10 @@ animation-fill-mode: forwards; } +body.recording-gif:not(.shutter-progressing) #shutter-progress-bar>circle { + animation-play-state: paused; +} + #shutter-progress-bar { --bar-width: 4px; --inner-perimeter: calc((var(--outer-radius) - var(--bar-width)) * 2 * 3.1416);
diff --git a/chromeos/components/camera_app_ui/resources/js/state.js b/chromeos/components/camera_app_ui/resources/js/state.js index 83f112aa..5e4f5f60 100644 --- a/chromeos/components/camera_app_ui/resources/js/state.js +++ b/chromeos/components/camera_app_ui/resources/js/state.js
@@ -59,11 +59,12 @@ REVIEW_RESULT: 'review-result', REVIEW_VIDEO_RESULT: 'review-video-result', SAVE_METADATA: 'save-metadata', + SCREEN_OFF_AUTO: 'screen-off-auto', SHOULD_HANDLE_INTENT_RESULT: 'should-handle-intent-result', SHOW_METADATA: 'show-metadata', SHOW_SCAN_DOCUMENT_OPTIONS: 'show-scan-document-options', SHOW_SCAN_MODE: 'show-scan-mode', - SCREEN_OFF_AUTO: 'screen-off-auto', + SHUTTER_PROGRESSING: 'shutter-progressing', STREAMING: 'streaming', SUSPEND: 'suspend', TABLET: 'tablet',
diff --git a/chromeos/components/camera_app_ui/resources/js/views/camera/mode/video.js b/chromeos/components/camera_app_ui/resources/js/views/camera/mode/video.js index 906ab23..00522a6a 100644 --- a/chromeos/components/camera_app_ui/resources/js/views/camera/mode/video.js +++ b/chromeos/components/camera_app_ui/resources/js/views/camera/mode/video.js
@@ -528,15 +528,19 @@ this.recordingType_ = this.getToggledRecordOption_(); if (this.recordingType_ === RecordType.GIF) { state.set(state.State.RECORDING_GIF, true); + state.set(state.State.SHUTTER_PROGRESSING, true); this.gifRecordTime_.start({resume: false}); const gifSaver = await this.captureGif_(); + + state.set(state.State.SHUTTER_PROGRESSING, false); + this.gifRecordTime_.stop({pause: false}); + state.set(PerfEvent.GIF_CAPTURE_POST_PROCESSING, true); await this.handler_.handleResultGif(gifSaver); state.set(PerfEvent.GIF_CAPTURE_POST_PROCESSING, false); state.set(state.State.RECORDING_GIF, false); - this.gifRecordTime_.stop({pause: false}); } else { this.recordTime_.start({resume: false}); let /** ?VideoSaver */ videoSaver = null;
diff --git a/chromeos/components/eche_app_ui/eche_notification_click_handler.cc b/chromeos/components/eche_app_ui/eche_notification_click_handler.cc index da592bd..1b42bc6 100644 --- a/chromeos/components/eche_app_ui/eche_notification_click_handler.cc +++ b/chromeos/components/eche_app_ui/eche_notification_click_handler.cc
@@ -39,7 +39,8 @@ const phonehub::Notification::AppMetadata& app_metadata) { if (launch_app_helper_->IsAppLaunchAllowed()) { launch_app_helper_->LaunchEcheApp(notification_id, - app_metadata.package_name); + app_metadata.package_name, + app_metadata.visible_app_name); } else { launch_app_helper_->ShowNotification( /* title= */ absl::nullopt, /* message= */ absl::nullopt,
diff --git a/chromeos/components/eche_app_ui/eche_notification_click_handler_unittest.cc b/chromeos/components/eche_app_ui/eche_notification_click_handler_unittest.cc index 67795fa..eaab80bb 100644 --- a/chromeos/components/eche_app_ui/eche_notification_click_handler_unittest.cc +++ b/chromeos/components/eche_app_ui/eche_notification_click_handler_unittest.cc
@@ -80,7 +80,8 @@ } void FakeLaunchEcheAppFunction(const absl::optional<int64_t>& notification_id, - const std::string& package_name) { + const std::string& package_name, + const std::u16string& visible_name) { // Do nothing. }
diff --git a/chromeos/components/eche_app_ui/eche_notification_generator_unittest.cc b/chromeos/components/eche_app_ui/eche_notification_generator_unittest.cc index 2be3569..6139d4ffc 100644 --- a/chromeos/components/eche_app_ui/eche_notification_generator_unittest.cc +++ b/chromeos/components/eche_app_ui/eche_notification_generator_unittest.cc
@@ -69,7 +69,8 @@ } void FakeLaunchEcheAppFunction(const absl::optional<int64_t>& notification_id, - const std::string& package_name) { + const std::string& package_name, + const std::u16string& visible_name) { // Do nothing. }
diff --git a/chromeos/components/eche_app_ui/eche_recent_app_click_handler.cc b/chromeos/components/eche_app_ui/eche_recent_app_click_handler.cc index d38fb39..e9c3e4f 100644 --- a/chromeos/components/eche_app_ui/eche_recent_app_click_handler.cc +++ b/chromeos/components/eche_app_ui/eche_recent_app_click_handler.cc
@@ -48,10 +48,12 @@ } void EcheRecentAppClickHandler::OnRecentAppClicked( - const std::string& recent_app_package_name) { + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) { if (launch_app_helper_->IsAppLaunchAllowed()) { launch_app_helper_->LaunchEcheApp(/*notification_id=*/absl::nullopt, - recent_app_package_name); + recent_app_package_name, + recent_app_visible_name); } else { launch_app_helper_->ShowNotification( /* title= */ absl::nullopt, /* message= */ absl::nullopt,
diff --git a/chromeos/components/eche_app_ui/eche_recent_app_click_handler.h b/chromeos/components/eche_app_ui/eche_recent_app_click_handler.h index d55e1363..e8c23826 100644 --- a/chromeos/components/eche_app_ui/eche_recent_app_click_handler.h +++ b/chromeos/components/eche_app_ui/eche_recent_app_click_handler.h
@@ -45,7 +45,9 @@ const phonehub::Notification::AppMetadata& app_metadata) override; // phonehub::RecentAppClickObserver: - void OnRecentAppClicked(const std::string& recent_app_package_name) override; + void OnRecentAppClicked( + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) override; // FeatureStatusProvider::Observer: void OnFeatureStatusChanged() override;
diff --git a/chromeos/components/eche_app_ui/eche_recent_app_click_handler_unittest.cc b/chromeos/components/eche_app_ui/eche_recent_app_click_handler_unittest.cc index 220c3ca..c85ff60 100644 --- a/chromeos/components/eche_app_ui/eche_recent_app_click_handler_unittest.cc +++ b/chromeos/components/eche_app_ui/eche_recent_app_click_handler_unittest.cc
@@ -82,8 +82,10 @@ } void FakeLaunchEcheAppFunction(const absl::optional<int64_t>& notification_id, - const std::string& package_name) { + const std::string& package_name, + const std::u16string& visible_name) { package_name_ = package_name; + visible_name_ = visible_name; } void FakeLaunchNotificationFunction( @@ -106,8 +108,9 @@ ->recent_app_click_observer_count(); } - void RecentAppClicked(const std::string& package_name) { - handler_->OnRecentAppClicked(package_name); + void RecentAppClicked(const std::string& package_name, + const std::u16string& visible_name) { + handler_->OnRecentAppClicked(package_name, visible_name); } void HandleNotificationClick( @@ -124,6 +127,8 @@ const std::string& package_name() { return package_name_; } + const std::u16string& visible_name() { return visible_name_; } + private: phonehub::FakePhoneHubManager fake_phone_hub_manager_; base::test::ScopedFeatureList scoped_feature_list_; @@ -131,6 +136,7 @@ std::unique_ptr<LaunchAppHelper> launch_app_helper_; std::unique_ptr<EcheRecentAppClickHandler> handler_; std::string package_name_; + std::u16string visible_name_; }; TEST_F(EcheRecentAppClickHandlerTest, StatusChangeTransitions) { @@ -161,10 +167,12 @@ TEST_F(EcheRecentAppClickHandlerTest, LaunchEcheAppFunction) { const char expected_package_name[] = "com.fakeapp"; + const char16_t expected_visible_name[] = u"Fake App"; - RecentAppClicked(expected_package_name); + RecentAppClicked(expected_package_name, expected_visible_name); EXPECT_EQ(expected_package_name, package_name()); + EXPECT_EQ(expected_visible_name, visible_name()); } TEST_F(EcheRecentAppClickHandlerTest, HandleNotificationClick) {
diff --git a/chromeos/components/eche_app_ui/launch_app_helper.cc b/chromeos/components/eche_app_ui/launch_app_helper.cc index dcdd04c..402f733 100644 --- a/chromeos/components/eche_app_ui/launch_app_helper.cc +++ b/chromeos/components/eche_app_ui/launch_app_helper.cc
@@ -64,8 +64,9 @@ } void LaunchAppHelper::LaunchEcheApp(absl::optional<int64_t> notification_id, - const std::string& package_name) const { - launch_eche_app_function_.Run(notification_id, package_name); + const std::string& package_name, + const std::u16string& visible_name) const { + launch_eche_app_function_.Run(notification_id, package_name, visible_name); } void LaunchAppHelper::CloseEcheApp() const {
diff --git a/chromeos/components/eche_app_ui/launch_app_helper.h b/chromeos/components/eche_app_ui/launch_app_helper.h index 833dedd..8239fc9 100644 --- a/chromeos/components/eche_app_ui/launch_app_helper.h +++ b/chromeos/components/eche_app_ui/launch_app_helper.h
@@ -64,7 +64,8 @@ using LaunchEcheAppFunction = base::RepeatingCallback<void( const absl::optional<int64_t>& notification_id, - const std::string& package_name)>; + const std::string& package_name, + const std::u16string& visible_name)>; using CloseEcheAppFunction = base::RepeatingCallback<void()>; @@ -88,7 +89,8 @@ std::unique_ptr<NotificationInfo> info) const; void LaunchEcheApp(absl::optional<int64_t> notification_id, - const std::string& package_name) const; + const std::string& package_name, + const std::u16string& visible_name) const; void CloseEcheApp() const;
diff --git a/chromeos/components/phonehub/browser_tabs_metadata_fetcher.h b/chromeos/components/phonehub/browser_tabs_metadata_fetcher.h index 6d2b4f5..ebb41e5 100644 --- a/chromeos/components/phonehub/browser_tabs_metadata_fetcher.h +++ b/chromeos/components/phonehub/browser_tabs_metadata_fetcher.h
@@ -45,4 +45,11 @@ } // namespace phonehub } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace phonehub { +using ::chromeos::phonehub::BrowserTabsMetadataFetcher; +} +} // namespace ash + #endif // CHROMEOS_COMPONENTS_PHONEHUB_BROWSER_TABS_METADATA_FETCHER_H_
diff --git a/chromeos/components/phonehub/browser_tabs_model.h b/chromeos/components/phonehub/browser_tabs_model.h index a301eb26..58e2248 100644 --- a/chromeos/components/phonehub/browser_tabs_model.h +++ b/chromeos/components/phonehub/browser_tabs_model.h
@@ -70,4 +70,11 @@ } // namespace phonehub } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace phonehub { +using ::chromeos::phonehub::BrowserTabsModel; +} +} // namespace ash + #endif // CHROMEOS_COMPONENTS_PHONEHUB_BROWSER_TABS_MODEL_H_
diff --git a/chromeos/components/phonehub/browser_tabs_model_provider.h b/chromeos/components/phonehub/browser_tabs_model_provider.h index 6f07eab2..14c76177 100644 --- a/chromeos/components/phonehub/browser_tabs_model_provider.h +++ b/chromeos/components/phonehub/browser_tabs_model_provider.h
@@ -55,4 +55,11 @@ } // namespace phonehub } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace phonehub { +using ::chromeos::phonehub::BrowserTabsModelProvider; +} +} // namespace ash + #endif // CHROMEOS_COMPONENTS_PHONEHUB_BROWSER_TABS_MODEL_PROVIDER_H_
diff --git a/chromeos/components/phonehub/fake_recent_apps_interaction_handler.cc b/chromeos/components/phonehub/fake_recent_apps_interaction_handler.cc index e950c00c..e1120221 100644 --- a/chromeos/components/phonehub/fake_recent_apps_interaction_handler.cc +++ b/chromeos/components/phonehub/fake_recent_apps_interaction_handler.cc
@@ -14,7 +14,8 @@ FakeRecentAppsInteractionHandler::~FakeRecentAppsInteractionHandler() = default; void FakeRecentAppsInteractionHandler::NotifyRecentAppClicked( - const std::string& recent_app_package_name) { + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) { if (base::Contains(package_name_to_click_count_, recent_app_package_name)) { package_name_to_click_count_.at(recent_app_package_name)++; return;
diff --git a/chromeos/components/phonehub/fake_recent_apps_interaction_handler.h b/chromeos/components/phonehub/fake_recent_apps_interaction_handler.h index 80e5afb..c94a4c9 100644 --- a/chromeos/components/phonehub/fake_recent_apps_interaction_handler.h +++ b/chromeos/components/phonehub/fake_recent_apps_interaction_handler.h
@@ -31,7 +31,8 @@ } void NotifyRecentAppClicked( - const std::string& recent_app_package_name) override; + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) override; void AddRecentAppClickObserver(RecentAppClickObserver* observer) override; void RemoveRecentAppClickObserver(RecentAppClickObserver* observer) override; void NotifyRecentAppAddedOrUpdated(
diff --git a/chromeos/components/phonehub/phone_hub_manager.h b/chromeos/components/phonehub/phone_hub_manager.h index e859344..f8ed637 100644 --- a/chromeos/components/phonehub/phone_hub_manager.h +++ b/chromeos/components/phonehub/phone_hub_manager.h
@@ -60,4 +60,11 @@ } // namespace phonehub } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace phonehub { +using ::chromeos::phonehub::PhoneHubManager; +} +} // namespace ash + #endif // CHROMEOS_COMPONENTS_PHONEHUB_PHONE_HUB_MANAGER_H_
diff --git a/chromeos/components/phonehub/recent_app_click_observer.h b/chromeos/components/phonehub/recent_app_click_observer.h index e619313c..f945e6ba 100644 --- a/chromeos/components/phonehub/recent_app_click_observer.h +++ b/chromeos/components/phonehub/recent_app_click_observer.h
@@ -17,7 +17,8 @@ // Called when the user clicks the recent app which has an open // action in the PhoneHub. virtual void OnRecentAppClicked( - const std::string& recent_app_package_name) = 0; + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) = 0; }; } // namespace phonehub
diff --git a/chromeos/components/phonehub/recent_apps_interaction_handler.cc b/chromeos/components/phonehub/recent_apps_interaction_handler.cc index 7b003abc..98ddfa3 100644 --- a/chromeos/components/phonehub/recent_apps_interaction_handler.cc +++ b/chromeos/components/phonehub/recent_apps_interaction_handler.cc
@@ -25,9 +25,10 @@ } void RecentAppsInteractionHandler::NotifyRecentAppClicked( - const std::string& package_name) { + const std::string& package_name, + const std::u16string& visible_name) { for (auto& observer : observer_list_) - observer.OnRecentAppClicked(package_name); + observer.OnRecentAppClicked(package_name, visible_name); } void RecentAppsInteractionHandler::NotifyRecentAppAddedOrUpdated(
diff --git a/chromeos/components/phonehub/recent_apps_interaction_handler.h b/chromeos/components/phonehub/recent_apps_interaction_handler.h index 49bbd84..266f16c 100644 --- a/chromeos/components/phonehub/recent_apps_interaction_handler.h +++ b/chromeos/components/phonehub/recent_apps_interaction_handler.h
@@ -27,7 +27,8 @@ delete; virtual ~RecentAppsInteractionHandler(); - virtual void NotifyRecentAppClicked(const std::string& package_name); + virtual void NotifyRecentAppClicked(const std::string& package_name, + const std::u16string& visible_name); virtual void AddRecentAppClickObserver(RecentAppClickObserver* observer); virtual void RemoveRecentAppClickObserver(RecentAppClickObserver* observer);
diff --git a/chromeos/components/phonehub/recent_apps_interaction_handler_unittest.cc b/chromeos/components/phonehub/recent_apps_interaction_handler_unittest.cc index 943a64c1..e80bab1 100644 --- a/chromeos/components/phonehub/recent_apps_interaction_handler_unittest.cc +++ b/chromeos/components/phonehub/recent_apps_interaction_handler_unittest.cc
@@ -20,7 +20,9 @@ std::string get_package_name() { return package_name; } - void OnRecentAppClicked(const std::string& recent_app_package_name) override { + void OnRecentAppClicked( + const std::string& recent_app_package_name, + const std::u16string& recent_app_visible_name) override { package_name = recent_app_package_name; } @@ -66,7 +68,8 @@ auto expected_app_metadata = Notification::AppMetadata( expected_app_visible_name, expected_package_name, gfx::Image()); - handler().NotifyRecentAppClicked(expected_package_name); + handler().NotifyRecentAppClicked(expected_package_name, + expected_app_visible_name); EXPECT_EQ(expected_package_name, GetPackageName()); }
diff --git a/chromeos/services/nearby/public/cpp/fake_nearby_process_manager.h b/chromeos/services/nearby/public/cpp/fake_nearby_process_manager.h index 26a1cc3..705f6e5 100644 --- a/chromeos/services/nearby/public/cpp/fake_nearby_process_manager.h +++ b/chromeos/services/nearby/public/cpp/fake_nearby_process_manager.h
@@ -90,4 +90,11 @@ } // namespace nearby } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace nearby { +using ::chromeos::nearby::FakeNearbyProcessManager; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_NEARBY_PUBLIC_CPP_FAKE_NEARBY_PROCESS_MANAGER_H_
diff --git a/chromeos/services/nearby/public/cpp/mock_nearby_connections.h b/chromeos/services/nearby/public/cpp/mock_nearby_connections.h index 2bb13d0..7554a3f 100644 --- a/chromeos/services/nearby/public/cpp/mock_nearby_connections.h +++ b/chromeos/services/nearby/public/cpp/mock_nearby_connections.h
@@ -142,4 +142,11 @@ } // namespace nearby } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace nearby { +using ::chromeos::nearby::MockNearbyConnections; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_NEARBY_PUBLIC_CPP_MOCK_NEARBY_CONNECTIONS_H_
diff --git a/chromeos/services/secure_channel/public/cpp/client/nearby_connector.h b/chromeos/services/secure_channel/public/cpp/client/nearby_connector.h index 6aa8969..ff24879 100644 --- a/chromeos/services/secure_channel/public/cpp/client/nearby_connector.h +++ b/chromeos/services/secure_channel/public/cpp/client/nearby_connector.h
@@ -26,4 +26,11 @@ } // namespace secure_channel } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the migration is finished. +namespace ash { +namespace secure_channel { +using ::chromeos::secure_channel::NearbyConnector; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_SECURE_CHANNEL_PUBLIC_CPP_CLIENT_NEARBY_CONNECTOR_H_
diff --git a/chromeos/services/secure_channel/public/cpp/client/secure_channel_client_impl.h b/chromeos/services/secure_channel/public/cpp/client/secure_channel_client_impl.h index 6ae2f93..7467eec 100644 --- a/chromeos/services/secure_channel/public/cpp/client/secure_channel_client_impl.h +++ b/chromeos/services/secure_channel/public/cpp/client/secure_channel_client_impl.h
@@ -95,4 +95,12 @@ } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos +// source migration is finished. +namespace ash { +namespace secure_channel { +using ::chromeos::secure_channel::SecureChannelClientImpl; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_SECURE_CHANNEL_PUBLIC_CPP_CLIENT_SECURE_CHANNEL_CLIENT_IMPL_H_
diff --git a/chromeos/services/secure_channel/secure_channel_base.h b/chromeos/services/secure_channel/secure_channel_base.h index dd92429b..16af84a 100644 --- a/chromeos/services/secure_channel/secure_channel_base.h +++ b/chromeos/services/secure_channel/secure_channel_base.h
@@ -37,4 +37,12 @@ } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos +// source migration is finished. +namespace ash { +namespace secure_channel { +using ::chromeos::secure_channel::SecureChannelBase; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_SECURE_CHANNEL_SECURE_CHANNEL_BASE_H_
diff --git a/chromeos/services/secure_channel/secure_channel_initializer.h b/chromeos/services/secure_channel/secure_channel_initializer.h index 97f7c85..47c9f37 100644 --- a/chromeos/services/secure_channel/secure_channel_initializer.h +++ b/chromeos/services/secure_channel/secure_channel_initializer.h
@@ -110,4 +110,12 @@ } // namespace chromeos +// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos +// source migration is finished. +namespace ash { +namespace secure_channel { +using ::chromeos::secure_channel::SecureChannelInitializer; +} +} // namespace ash + #endif // CHROMEOS_SERVICES_SECURE_CHANNEL_SECURE_CHANNEL_INITIALIZER_H_
diff --git a/chromeos/utils/BUILD.gn b/chromeos/utils/BUILD.gn index 9ab4fe56..09b15f1 100644 --- a/chromeos/utils/BUILD.gn +++ b/chromeos/utils/BUILD.gn
@@ -7,6 +7,7 @@ source_set("utils") { deps = [ "//base", + "//printing:printing_base", "//skia", "//ui/gfx", ] @@ -23,6 +24,7 @@ ":utils", "//base", "//skia", + "//testing/gmock", "//testing/gtest", "//ui/gfx", "//ui/gfx:test_support",
diff --git a/chromeos/utils/DEPS b/chromeos/utils/DEPS index 87fc083b..c1bf172 100644 --- a/chromeos/utils/DEPS +++ b/chromeos/utils/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+base", + "+printing/units.h", "+third_party/skia/include", "+ui/gfx", ]
diff --git a/chromeos/utils/pdf_conversion.cc b/chromeos/utils/pdf_conversion.cc index 94ce864f..41e119aa 100644 --- a/chromeos/utils/pdf_conversion.cc +++ b/chromeos/utils/pdf_conversion.cc
@@ -6,9 +6,11 @@ #include "base/files/file_path.h" #include "base/logging.h" +#include "printing/units.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkStream.h" #include "third_party/skia/include/core/SkTypes.h" #include "third_party/skia/include/docs/SkPDFDocument.h" @@ -26,14 +28,28 @@ // Returns whether the page was successfully created. bool AddPdfPage(sk_sp<SkDocument> pdf_doc, const sk_sp<SkData>& image_data, - bool rotate) { + bool rotate, + absl::optional<int> dpi) { const sk_sp<SkImage> image = SkImage::MakeFromEncoded(image_data); if (!image) { LOG(ERROR) << "Unable to generate image from encoded image data."; return false; } - SkCanvas* page_canvas = pdf_doc->beginPage(image->width(), image->height()); + // Convert from JPG dimensions in pixels (DPI) to PDF dimensions in points + // (1/72 in). + int page_width; + int page_height; + if (dpi.has_value() && dpi.value() > 0) { + page_width = printing::ConvertUnit(image->width(), dpi.value(), + printing::kPointsPerInch); + page_height = printing::ConvertUnit(image->height(), dpi.value(), + printing::kPointsPerInch); + } else { + page_width = image->width(); + page_height = image->height(); + } + SkCanvas* page_canvas = pdf_doc->beginPage(page_width, page_height); if (!page_canvas) { LOG(ERROR) << "Unable to access PDF page canvas."; return false; @@ -45,7 +61,8 @@ page_canvas->translate(-image->width(), -image->height()); } - page_canvas->drawImage(image, /*left=*/0, /*top=*/0); + SkRect image_bounds = SkRect::MakeIWH(page_width, page_height); + page_canvas->drawImageRect(image, image_bounds, SkSamplingOptions()); pdf_doc->endPage(); return true; } @@ -54,7 +71,8 @@ bool ConvertJpgImagesToPdf(const std::vector<std::string>& jpg_images, const base::FilePath& file_path, - bool rotate_alternate_pages) { + bool rotate_alternate_pages, + absl::optional<int> dpi) { DCHECK(!file_path.empty()); SkFILEWStream pdf_outfile(file_path.value().c_str()); @@ -81,7 +99,7 @@ return false; } - if (!AddPdfPage(pdf_doc, img_data, rotate_current_page)) { + if (!AddPdfPage(pdf_doc, img_data, rotate_current_page, dpi)) { LOG(ERROR) << "Unable to add new PDF page."; return false; } @@ -113,7 +131,7 @@ return false; } - if (!AddPdfPage(pdf_doc, img_data, false)) { + if (!AddPdfPage(pdf_doc, img_data, false, absl::nullopt)) { LOG(ERROR) << "Unable to add new PDF page."; return false; }
diff --git a/chromeos/utils/pdf_conversion.h b/chromeos/utils/pdf_conversion.h index b8fc768..31363ce 100644 --- a/chromeos/utils/pdf_conversion.h +++ b/chromeos/utils/pdf_conversion.h
@@ -8,6 +8,8 @@ #include <string> #include <vector> +#include "third_party/abseil-cpp/absl/types/optional.h" + namespace base { class FilePath; } // namespace base @@ -15,11 +17,13 @@ namespace chromeos { // Converts `jpg_images` to a single PDF, and writes the PDF to `file_path`. If -// `rotate_alternate_pages` is true, every other page is rotated 180 degrees. +// `rotate_alternate_pages` is true, every other page is rotated 180 degrees. If +// the DPI is specified, use it to calculate proper page and media box size. // Returns whether the PDF was successfully saved. bool ConvertJpgImagesToPdf(const std::vector<std::string>& jpg_images, const base::FilePath& file_path, - bool rotate_alternate_pages); + bool rotate_alternate_pages, + absl::optional<int> dpi); // Converts `jpg_image` to a single PDF, and saved the result into `output`. bool ConvertJpgImageToPdf(const std::vector<uint8_t>& jpg_image,
diff --git a/chromeos/utils/pdf_conversion_unittest.cc b/chromeos/utils/pdf_conversion_unittest.cc index b0559df..12f0b1a0 100644 --- a/chromeos/utils/pdf_conversion_unittest.cc +++ b/chromeos/utils/pdf_conversion_unittest.cc
@@ -4,11 +4,13 @@ #include "chromeos/utils/pdf_conversion.h" +#include <fstream> #include <string> #include <vector> #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image.h" @@ -19,9 +21,10 @@ namespace { -// Returns a manually generated JPG image. -std::vector<uint8_t> CreateJpg() { - gfx::Image original = gfx::test::CreateImage(100, 100); +// Returns a manually generated JPG image with specified width and height in +// pixels. +std::vector<uint8_t> CreateJpg(int width, int height) { + gfx::Image original = gfx::test::CreateImage(width, height); std::vector<uint8_t> jpg_buffer; if (!gfx::JPEG1xEncodedDataFromImage(original, 80, &jpg_buffer)) { return {}; @@ -34,9 +37,9 @@ using ConvertToPdfTest = testing::Test; // Test that JPG image can be converted to pdf file successfully. -TEST_F(ConvertToPdfTest, ToFile) { +TEST_F(ConvertToPdfTest, ToFileNoDpi) { std::vector<std::string> images; - std::vector<uint8_t> bytes = CreateJpg(); + std::vector<uint8_t> bytes = CreateJpg(100, 100); images.push_back(std::string(bytes.begin(), bytes.end())); base::ScopedTempDir temp_dir; @@ -44,7 +47,8 @@ auto output_path = temp_dir.GetPath().Append("temp.pdf"); EXPECT_TRUE(ConvertJpgImagesToPdf(images, output_path, - /*rotate_alternate_pages=*/false)); + /*rotate_alternate_pages=*/false, + /*dpi=*/absl::nullopt)); EXPECT_TRUE(base::PathExists(output_path)); int64_t file_size; @@ -54,9 +58,70 @@ EXPECT_GT(file_size, 20u); } +// Test that JPG image can be converted to pdf file successfully when scanner +// DPI is specified. Higher DPI results in larger pixel counts, but should +// result in the same PDF page size. +TEST_F(ConvertToPdfTest, ToFileWithDpi) { + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + // Generate and process 100 DPI image. + std::vector<std::string> images_100; + std::vector<uint8_t> bytes_100 = CreateJpg(100, 100); + images_100.push_back(std::string(bytes_100.begin(), bytes_100.end())); + auto output_path_100 = temp_dir.GetPath().Append("temp_100.pdf"); + EXPECT_TRUE(ConvertJpgImagesToPdf(images_100, output_path_100, + /*rotate_alternate_pages=*/false, + /*dpi=*/100)); + EXPECT_TRUE(base::PathExists(output_path_100)); + + // Generate and process 200 DPI image. + std::vector<std::string> images_200; + std::vector<uint8_t> bytes_200 = CreateJpg(200, 200); + images_200.push_back(std::string(bytes_200.begin(), bytes_200.end())); + auto output_path_200 = temp_dir.GetPath().Append("temp_200.pdf"); + EXPECT_TRUE(ConvertJpgImagesToPdf(images_200, output_path_200, + /*rotate_alternate_pages=*/false, + /*dpi=*/200)); + EXPECT_TRUE(base::PathExists(output_path_200)); + + // Generate and process 300 DPI image. + std::vector<std::string> images_300; + std::vector<uint8_t> bytes_300 = CreateJpg(300, 300); + images_300.push_back(std::string(bytes_300.begin(), bytes_300.end())); + auto output_path_300 = temp_dir.GetPath().Append("temp_300.pdf"); + EXPECT_TRUE(ConvertJpgImagesToPdf(images_300, output_path_300, + /*rotate_alternate_pages=*/false, + /*dpi=*/300)); + EXPECT_TRUE(base::PathExists(output_path_300)); + + // Each file should increase in size as DPI increases. + int64_t file_size_100; + int64_t file_size_200; + int64_t file_size_300; + EXPECT_TRUE(base::GetFileSize(output_path_100, &file_size_100)); + EXPECT_TRUE(base::GetFileSize(output_path_200, &file_size_200)); + EXPECT_TRUE(base::GetFileSize(output_path_300, &file_size_300)); + EXPECT_GT(file_size_200, file_size_100); + EXPECT_GT(file_size_300, file_size_200); + + // Verify that the media box is the same size across PDFs. + const char kMediaBoxString[] = "[0 0 72 72]"; + std::string file_contents; + + EXPECT_TRUE(base::ReadFileToString(output_path_100, &file_contents)); + EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString)); + + EXPECT_TRUE(base::ReadFileToString(output_path_200, &file_contents)); + EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString)); + + EXPECT_TRUE(base::ReadFileToString(output_path_300, &file_contents)); + EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString)); +} + // Test that JPG image can be converted to pdf and saved to vector successfully. TEST_F(ConvertToPdfTest, ToVector) { - std::vector<uint8_t> jpg_buffer = CreateJpg(); + std::vector<uint8_t> jpg_buffer = CreateJpg(100, 100); ASSERT_FALSE(jpg_buffer.empty()); std::vector<uint8_t> pdf_buffer;
diff --git a/components/arc/BUILD.gn b/components/arc/BUILD.gn index 2104c0eb3..c786a4b7 100644 --- a/components/arc/BUILD.gn +++ b/components/arc/BUILD.gn
@@ -186,6 +186,7 @@ "//ui/base/ime", "//ui/base/ime/ash", "//ui/chromeos/strings", + "//ui/chromeos/styles:cros_styles_views_generator", "//ui/display/manager", "//ui/events", "//ui/events:dom_keycode_converter",
diff --git a/components/arc/compat_mode/DEPS b/components/arc/compat_mode/DEPS index b9455bf..bfebe18 100644 --- a/components/arc/compat_mode/DEPS +++ b/components/arc/compat_mode/DEPS
@@ -9,6 +9,7 @@ "+ash/wm/resize_shadow_controller.h", "+components/strings/grit/components_strings.h", "+ui/aura", + "+ui/chromeos/styles/cros_styles.h", "+ui/gfx", "+ui/strings", "+ui/views",
diff --git a/components/arc/compat_mode/resize_toggle_menu.cc b/components/arc/compat_mode/resize_toggle_menu.cc index 1c321a2..c69d53b 100644 --- a/components/arc/compat_mode/resize_toggle_menu.cc +++ b/components/arc/compat_mode/resize_toggle_menu.cc
@@ -10,6 +10,7 @@ #include "base/check.h" #include "base/notreached.h" #include "components/arc/compat_mode/overlay_dialog.h" +#include "components/arc/compat_mode/style/arc_color_provider.h" #include "components/arc/vector_icons/vector_icons.h" #include "components/strings/grit/components_strings.h" #include "ui/aura/client/aura_constants.h" @@ -119,15 +120,20 @@ const auto* theme = GetNativeTheme(); - const auto foreground_color = theme->GetSystemColor( - is_selected_ ? ui::NativeTheme::kColorId_TextOnProminentButtonColor - : ui::NativeTheme::kColorId_LabelEnabledColor); - icon_view_->SetImage(gfx::CreateVectorIcon(icon_, foreground_color)); - title_->SetEnabledColor(foreground_color); + const auto icon_color = + is_selected_ + ? GetCrOSColor(cros_styles::ColorName::kIconColorSelection) + : theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor); + icon_view_->SetImage(gfx::CreateVectorIcon(icon_, icon_color)); + + const auto text_color = + is_selected_ + ? GetCrOSColor(cros_styles::ColorName::kTextColorSelection) + : theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor); + title_->SetEnabledColor(text_color); const auto background_color = - is_selected_ ? theme->GetSystemColor( - ui::NativeTheme::kColorId_ProminentButtonColor) + is_selected_ ? GetCrOSColor(cros_styles::ColorName::kHighlightColor) : SK_ColorTRANSPARENT; background()->SetNativeControlColor(background_color);
diff --git a/components/arc/compat_mode/style/arc_color_provider.cc b/components/arc/compat_mode/style/arc_color_provider.cc index 7fedfed..2388950 100644 --- a/components/arc/compat_mode/style/arc_color_provider.cc +++ b/components/arc/compat_mode/style/arc_color_provider.cc
@@ -39,6 +39,11 @@ : kDialogBackgroundBaseColorLight; } +SkColor GetCrOSColor(cros_styles::ColorName color_name) { + return cros_styles::ResolveColor(color_name, IsDarkModeEnabled(), + /*use_debug_colors=*/false); +} + bool IsDarkModeEnabled() { auto* provider = ash::ColorProvider::Get(); // |provider| may return null in unit testing
diff --git a/components/arc/compat_mode/style/arc_color_provider.h b/components/arc/compat_mode/style/arc_color_provider.h index 3b4edb6c..3d0dbe8 100644 --- a/components/arc/compat_mode/style/arc_color_provider.h +++ b/components/arc/compat_mode/style/arc_color_provider.h
@@ -6,6 +6,7 @@ #define COMPONENTS_ARC_COMPAT_MODE_STYLE_ARC_COLOR_PROVIDER_H_ #include "ash/public/cpp/style/color_provider.h" +#include "ui/chromeos/styles/cros_styles.h" namespace arc { @@ -21,6 +22,9 @@ // Get dialog background base color SkColor GetDialogBackgroundBaseColor(); +// Get color from cros_styles based on the current semantics (dark/light mode). +SkColor GetCrOSColor(cros_styles::ColorName color_name); + // Determine if dark mode is enabled bool IsDarkModeEnabled();
diff --git a/components/autofill/core/browser/autofill_merge_unittest.cc b/components/autofill/core/browser/autofill_merge_unittest.cc index 67fe8d0..e629010b 100644 --- a/components/autofill/core/browser/autofill_merge_unittest.cc +++ b/components/autofill/core/browser/autofill_merge_unittest.cc
@@ -99,11 +99,11 @@ // Serializes the |profiles| into a string. std::string SerializeProfiles(const std::vector<AutofillProfile*>& profiles) { std::string result; - for (size_t i = 0; i < profiles.size(); ++i) { + for (auto* profile : profiles) { result += kProfileSeparator; result += "\n"; for (const ServerFieldType& type : kProfileFieldTypes) { - std::u16string value = profiles[i]->GetRawInfo(type); + std::u16string value = profile->GetRawInfo(type); result += AutofillType::ServerFieldTypeToString(type); result += kFieldSeparator; if (!value.empty()) { @@ -141,7 +141,7 @@ PersonalDataManagerMock::PersonalDataManagerMock() : PersonalDataManager("en-US", "US") {} -PersonalDataManagerMock::~PersonalDataManagerMock() {} +PersonalDataManagerMock::~PersonalDataManagerMock() = default; void PersonalDataManagerMock::Reset() { profiles_.clear(); @@ -292,12 +292,17 @@ // Import the profile. std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> unused_imported_upi_id; + std::vector<FormDataImporter::AddressProfileImportCandidate> + address_profile_import_candidates; form_data_importer_->ImportFormData(form_structure, true, // address autofill enabled, true, // credit card autofill enabled false, // should return local card &imported_credit_card, + address_profile_import_candidates, &unused_imported_upi_id); + form_data_importer_->ProcessAddressProfileImportCandidates( + address_profile_import_candidates, true); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(unused_imported_upi_id.has_value());
diff --git a/components/autofill/core/browser/form_data_importer.cc b/components/autofill/core/browser/form_data_importer.cc index 39f3503..5ea9dc6 100644 --- a/components/autofill/core/browser/form_data_importer.cc +++ b/components/autofill/core/browser/form_data_importer.cc
@@ -257,7 +257,7 @@ app_locale_(app_locale) { } -FormDataImporter::~FormDataImporter() {} +FormDataImporter::~FormDataImporter() = default; void FormDataImporter::ImportFormData(const FormStructure& submitted_form, bool profile_autofill_enabled, @@ -265,6 +265,8 @@ std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> detected_upi_id; + std::vector<AddressProfileImportCandidate> address_profile_import_candidates; + bool is_credit_card_upstream_enabled = credit_card_save_manager_->IsCreditCardUploadEnabled(); // ImportFormData will set the |imported_credit_card_record_type_|. If the @@ -274,11 +276,28 @@ ImportFormData(submitted_form, profile_autofill_enabled, credit_card_autofill_enabled, /*should_return_local_card=*/is_credit_card_upstream_enabled, - &imported_credit_card, &detected_upi_id); + &imported_credit_card, address_profile_import_candidates, + &detected_upi_id); - ProcessCreditCardImportCandidate( + // Create a vector of address profile import candidates. + // This is used to make preliminarily imported profiles available + // to the credit card import logic. + std::vector<AutofillProfile> preliminary_imported_address_profiles; + for (const auto& candidate : address_profile_import_candidates) { + if (candidate.all_requirements_fulfilled) + preliminary_imported_address_profiles.push_back(candidate.profile); + } + credit_card_save_manager_->SetPreliminarilyImportedAutofillProfile( + preliminary_imported_address_profiles); + + bool cc_prompt_potentially_shown = ProcessCreditCardImportCandidate( submitted_form, std::move(imported_credit_card), detected_upi_id, credit_card_autofill_enabled, is_credit_card_upstream_enabled); + + // If a prompt for credit cards is potentially shown, do not allow for a + // second address profile import dialog. + ProcessAddressProfileImportCandidates(address_profile_import_candidates, + !cc_prompt_potentially_shown); } CreditCard FormDataImporter::ExtractCreditCardFromForm( @@ -365,6 +384,8 @@ bool credit_card_autofill_enabled, bool should_return_local_card, std::unique_ptr<CreditCard>* imported_credit_card, + std::vector<AddressProfileImportCandidate>& + address_profile_import_candidates, absl::optional<std::string>* imported_upi_id) { // We try the same |form| for both credit card and address import/update. // - ImportCreditCard may update an existing card, or fill @@ -386,9 +407,8 @@ // Only import addresses if enabled. if (profile_autofill_enabled && !base::FeatureList::IsEnabled(features::kAutofillDisableAddressImport)) { - address_import = ImportAddressProfiles( - submitted_form, - /*allow_save_prompts=*/imported_credit_card->get() == nullptr); + address_import = ImportAddressProfiles(submitted_form, + address_profile_import_candidates); } if (cc_import || address_import || imported_upi_id->has_value()) @@ -398,8 +418,9 @@ return false; } -bool FormDataImporter::ImportAddressProfiles(const FormStructure& form, - bool allow_save_prompts) { +bool FormDataImporter::ImportAddressProfiles( + const FormStructure& form, + std::vector<AddressProfileImportCandidate>& import_candidates) { // Create a buffer to collect logging output for the autofill-internals. LogBuffer import_log_buffer; import_log_buffer << LoggingScope::kAddressProfileFormImport; @@ -433,9 +454,8 @@ << section << CTag{}; // Try to import an address profile from the form fields of this section. // Only allow for a prompt if no other complete profile was found so far. - if (ImportAddressProfileForSection( - form, section, allow_save_prompts && num_complete_profiles == 0, - &import_log_buffer)) + if (ImportAddressProfileForSection(form, section, import_candidates, + &import_log_buffer)) num_complete_profiles++; // And close the div of the section import log. import_log_buffer << CTag{"div"}; @@ -447,7 +467,7 @@ AutofillMetrics::AddressProfileImportStatusMetric::REGULAR_IMPORT); } else if (sections.size() > 1) { // Try to import by combining all sections. - if (ImportAddressProfileForSection(form, "", allow_save_prompts, + if (ImportAddressProfileForSection(form, "", import_candidates, &import_log_buffer)) { num_complete_profiles++; AutofillMetrics::LogAddressFormImportStatustMetric( @@ -474,7 +494,7 @@ bool FormDataImporter::ImportAddressProfileForSection( const FormStructure& form, const std::string& section, - bool allow_save_prompts, + std::vector<AddressProfileImportCandidate>& import_candidates, LogBuffer* import_log_buffer) { // The candidate for profile import. There are many ways for the candidate to // be rejected (see everywhere this function returns false). @@ -653,7 +673,7 @@ app_locale_, import_log_buffer); // Do not import a profile if any of the requirements is violated. - bool all_fullfilled = + bool all_fulfilled = !(has_multiple_distinct_email_addresses || has_invalid_field_types || has_invalid_country || has_invalid_phone_number || is_invalid_learnable_profile); @@ -683,8 +703,8 @@ : AddressImportRequirement::COUNTRY_VALID_REQUIREMENT_FULFILLED); AutofillMetrics::LogAddressFormImportRequirementMetric( - all_fullfilled ? AddressImportRequirement::OVERALL_REQUIREMENT_FULFILLED - : AddressImportRequirement::OVERALL_REQUIREMENT_VIOLATED); + all_fulfilled ? AddressImportRequirement::OVERALL_REQUIREMENT_FULFILLED + : AddressImportRequirement::OVERALL_REQUIREMENT_VIOLATED); bool candidate_has_structured_data = base::FeatureList::IsEnabled( @@ -694,30 +714,56 @@ // If the profile does not fulfill import requirements but contains the // structured address or name information, it is eligible for silently // updating the existing profiles. - if (!all_fullfilled && !candidate_has_structured_data) { + if (!all_fulfilled && !candidate_has_structured_data) return false; - } if (!candidate_profile.FinalizeAfterImport()) return false; - // Restrict the import to silent updates meaning that no prompt will be shown - // in case the import requirements are not fulfilled or if save prompts are - // not allowed in case they are enabled at all. - bool only_silent_updates = - !all_fullfilled || - (!allow_save_prompts && base::FeatureList::IsEnabled( - features::kAutofillAddressProfileSavePrompt)); - // At this stage, the saving of the profile can only be omitted by the // incognito mode but the import is not triggered if the browser is in the // incognito mode. DCHECK(!personal_data_manager_->IsOffTheRecord()); - address_profile_save_manager_->ImportProfileFromForm( - candidate_profile, app_locale_, form.source_url(), - /*allow_only_silent_updates=*/only_silent_updates); - return !only_silent_updates; + import_candidates.push_back(AddressProfileImportCandidate{ + candidate_profile, form.source_url(), all_fulfilled}); + + // Return true if a compelete importable profile was found. + return all_fulfilled; +} + +bool FormDataImporter::ProcessAddressProfileImportCandidates( + const std::vector<AddressProfileImportCandidate>& import_candidates, + bool allow_prompt) { + // At this point, no credit card prompt was shown. Initiate the import of + // addresses is possible. + int imported_profiles = 0; + if (allow_prompt || !base::FeatureList::IsEnabled( + features::kAutofillAddressProfileSavePrompt)) { + for (const auto& candidate : import_candidates) { + // First try to import a single complete profile. + if (!candidate.all_requirements_fulfilled) + continue; + address_profile_save_manager_->ImportProfileFromForm( + candidate.profile, app_locale_, candidate.url, + /*allow_only_silent_updates=*/false); + // Limit the number of importable profiles to 2. + if (++imported_profiles >= 2) + return true; + } + } + // If a profile was already imported, do not try to use partial profiles for + // silent updates. + if (imported_profiles > 0) + return true; + // Otherwise try again but restrict the import to silent updates. + for (const auto& candidate : import_candidates) { + // First try to import a single complete profile. + address_profile_save_manager_->ImportProfileFromForm( + candidate.profile, app_locale_, candidate.url, + /*allow_only_silent_updates=*/true); + } + return false; } bool FormDataImporter::ProcessCreditCardImportCandidate(
diff --git a/components/autofill/core/browser/form_data_importer.h b/components/autofill/core/browser/form_data_importer.h index ce758c0..9b0f00a 100644 --- a/components/autofill/core/browser/form_data_importer.h +++ b/components/autofill/core/browser/form_data_importer.h
@@ -44,6 +44,7 @@ // The imported card is not currently stored with the browser. NEW_CARD, }; + // The parameters should outlive the FormDataImporter. FormDataImporter(AutofillClient* client, payments::PaymentsClient* payments_client, @@ -99,6 +100,20 @@ #endif // #if !defined(OS_ANDROID) && !defined(OS_IOS) private: + // Defines a candidate for address profile import. + struct AddressProfileImportCandidate { + // The profile that was extracted from the form. + AutofillProfile profile; + // The URL the profile was extracted from. + GURL url; + // Indicates if all import requirements have been fulfilled. + bool all_requirements_fulfilled; + AddressProfileImportCandidate(AddressProfileImportCandidate&& other) = + default; + AddressProfileImportCandidate& operator=( + AddressProfileImportCandidate&& other) = default; + }; + // Scans the given |form| for importable Autofill data. If the form includes // sufficient address data for a new profile, it is immediately imported. If // the form includes sufficient credit card data for a new credit card and @@ -116,25 +131,27 @@ bool credit_card_autofill_enabled, bool should_return_local_card, std::unique_ptr<CreditCard>* imported_credit_card, + std::vector<AddressProfileImportCandidate>& + address_profile_import_candidates, absl::optional<std::string>* imported_upi_id); // Go through the |form| fields and attempt to extract and import valid // address profiles. Returns true on extraction success of at least one // profile. There are many reasons that extraction may fail (see - // implementation). |allow_save_prompts| indicates if a dialog to import a new - // address can be shown. The function returns true if at least one complete + // implementation). The function returns true if at least one complete // address profile was found. - bool ImportAddressProfiles(const FormStructure& form, - bool allow_save_prompts); + bool ImportAddressProfiles( + const FormStructure& form, + std::vector<AddressProfileImportCandidate>& import_candidates); // Helper method for ImportAddressProfiles which only considers the fields for // a specified |section|. If |section| is the empty string, the import is - // performed on the union of all sections. |allow_save_prompts| indicates if - // a dialog to import a new address can be shown. - bool ImportAddressProfileForSection(const FormStructure& form, - const std::string& section, - bool allow_save_prompts, - LogBuffer* import_log_buffer); + // performed on the union of all sections. + bool ImportAddressProfileForSection( + const FormStructure& form, + const std::string& section, + std::vector<AddressProfileImportCandidate>& import_candidates, + LogBuffer* import_log_buffer); // Go through the |form| fields and attempt to extract a new credit card in // |imported_credit_card|, or update an existing card. @@ -158,6 +175,14 @@ bool credit_card_autofill_enabled, bool is_credit_card_upstream_enabled); + // Processes the address profile import candidates. + // |import_candidates| contains the addresses extracted from the form. + // |allow_prompt| denotes if a prompt can be shown. + // Returns true if the import of a complete profile is initiated. + bool ProcessAddressProfileImportCandidates( + const std::vector<AddressProfileImportCandidate>& import_candidates, + bool allow_prompt = true); + // Extracts credit card from the form structure. |hasDuplicateFieldType| will // be set as true if there are duplicated field types in the form. CreditCard ExtractCreditCardFromForm(const FormStructure& form,
diff --git a/components/autofill/core/browser/form_data_importer_unittest.cc b/components/autofill/core/browser/form_data_importer_unittest.cc index 32125d4..73f1cd6c 100644 --- a/components/autofill/core/browser/form_data_importer_unittest.cc +++ b/components/autofill/core/browser/form_data_importer_unittest.cc
@@ -402,15 +402,29 @@ const FormStructure& form, bool skip_waiting_on_pdm = false, bool allow_save_prompts = true) { + // This parameter has no effect unless save prompts for addresses are + // enabled. + allow_save_prompts = + allow_save_prompts || !base::FeatureList::IsEnabled( + features::kAutofillAddressProfileSavePrompt); + + std::vector<FormDataImporter::AddressProfileImportCandidate> + address_profile_import_candidates; + + EXPECT_EQ(extraction_successful, + form_data_importer_->ImportAddressProfiles( + form, address_profile_import_candidates)); + if (!extraction_successful) { - EXPECT_FALSE( - form_data_importer_->ImportAddressProfiles(form, allow_save_prompts)); + EXPECT_FALSE(form_data_importer_->ProcessAddressProfileImportCandidates( + address_profile_import_candidates, allow_save_prompts)); return; } if (skip_waiting_on_pdm) { - EXPECT_TRUE( - form_data_importer_->ImportAddressProfiles(form, allow_save_prompts)); + EXPECT_EQ(form_data_importer_->ProcessAddressProfileImportCandidates( + address_profile_import_candidates, allow_save_prompts), + allow_save_prompts); return; } @@ -418,8 +432,9 @@ EXPECT_CALL(personal_data_observer_, OnPersonalDataFinishedProfileTasks()) .WillOnce(QuitMessageLoop(&run_loop)); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(1); - EXPECT_TRUE( - form_data_importer_->ImportAddressProfiles(form, allow_save_prompts)); + EXPECT_EQ(form_data_importer_->ProcessAddressProfileImportCandidates( + address_profile_import_candidates, allow_save_prompts), + allow_save_prompts); run_loop.Run(); } @@ -436,6 +451,30 @@ } } + // Convenience wrapper that calls |FormDataImporter::ImportFormData()| and + // subsequetly processes the candidates for address profile import. + // Returns the result of |FormDataImporter::ImportFormData()|. + bool ImportFormDataAndProcessAddressCandidates( + const FormStructure& form, + bool profile_autofill_enabled, + bool credit_card_autofill_enabled, + bool should_return_local_card, + std::unique_ptr<CreditCard>* imported_credit_card, + absl::optional<std::string>* imported_upi_id) { + std::vector<FormDataImporter::AddressProfileImportCandidate> + address_profile_import_candidates; + + bool result = form_data_importer_->ImportFormData( + form, profile_autofill_enabled, credit_card_autofill_enabled, + should_return_local_card, imported_credit_card, + address_profile_import_candidates, imported_upi_id); + + form_data_importer_->ProcessAddressProfileImportCandidates( + address_profile_import_candidates); + + return result; + } + void ImportAddressProfilesAndVerifyExpectation( const FormStructure& form, const std::vector<AutofillProfile>& expected_profiles) { @@ -885,7 +924,7 @@ std::unique_ptr<FormStructure> form_structure = ConstructDefaultProfileFormStructure(); - ImportAddressProfiles(/*extraction_successful=*/false, *form_structure, + ImportAddressProfiles(/*extraction_successful=*/true, *form_structure, /*skip_waiting_on_pdm=*/true, /*allow_save_prompts=*/false); VerifyExpectationForImportedAddressProfiles({}); @@ -2570,7 +2609,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2593,7 +2632,7 @@ FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure2, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card2, @@ -2633,7 +2672,7 @@ FormStructure form_structure3(form3); form_structure3.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card3; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure3, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/false, /*should_return_local_card=*/true, &imported_credit_card3, @@ -2658,7 +2697,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2697,7 +2736,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2736,7 +2775,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2774,7 +2813,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2799,7 +2838,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2826,7 +2865,7 @@ std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2853,7 +2892,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2896,7 +2935,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -2945,7 +2984,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3034,7 +3073,7 @@ .Times(testing::AnyNumber()); absl::optional<std::string> imported_upi_id; // Still returns true because the credit card import was successful. - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3150,7 +3189,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/false, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3208,7 +3247,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/false, @@ -3270,7 +3309,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/false, /*credit_card_autofill_enabled=*/false, @@ -3327,7 +3366,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3367,7 +3406,7 @@ std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; // Still returns true because the credit card import was successful. - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3402,7 +3441,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/true, &imported_credit_card, @@ -3451,7 +3490,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3496,7 +3535,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3545,7 +3584,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3591,7 +3630,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3638,7 +3677,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3684,7 +3723,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3733,7 +3772,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, @@ -3783,7 +3822,7 @@ form_structure.DetermineHeuristicTypes(nullptr, nullptr); std::unique_ptr<CreditCard> imported_credit_card; absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/true, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3809,7 +3848,7 @@ std::unique_ptr<CreditCard> imported_credit_card; // Discarded. absl::optional<std::string> imported_upi_id; - EXPECT_TRUE(form_data_importer_->ImportFormData( + EXPECT_TRUE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/false, /*credit_card_autofill_enabled=*/true, /*should_return_local_card=*/false, &imported_credit_card, @@ -3834,7 +3873,7 @@ std::unique_ptr<CreditCard> imported_credit_card; // Discarded. absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/false, /*credit_card_autofill_enabled=*/false, /*should_return_local_card=*/false, &imported_credit_card, @@ -3858,7 +3897,7 @@ std::unique_ptr<CreditCard> imported_credit_card; // Discarded. absl::optional<std::string> imported_upi_id; - EXPECT_FALSE(form_data_importer_->ImportFormData( + EXPECT_FALSE(ImportFormDataAndProcessAddressCandidates( form_structure, /*profile_autofill_enabled=*/false, /*credit_card_autofill_enabled=*/false, /*should_return_local_card=*/false, &imported_credit_card,
diff --git a/components/autofill_assistant/browser/fake_starter_platform_delegate.cc b/components/autofill_assistant/browser/fake_starter_platform_delegate.cc index ce2c50b..58ab956 100644 --- a/components/autofill_assistant/browser/fake_starter_platform_delegate.cc +++ b/components/autofill_assistant/browser/fake_starter_platform_delegate.cc
@@ -106,4 +106,8 @@ return is_custom_tab_; } +bool FakeStarterPlatformDelegate::GetIsTabCreatedByGSA() const { + return is_tab_created_by_gsa_; +} + } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/fake_starter_platform_delegate.h b/components/autofill_assistant/browser/fake_starter_platform_delegate.h index b2c9bc7..eb078ef 100644 --- a/components/autofill_assistant/browser/fake_starter_platform_delegate.h +++ b/components/autofill_assistant/browser/fake_starter_platform_delegate.h
@@ -49,6 +49,7 @@ void SetProactiveHelpSettingEnabled(bool enabled) override; bool GetMakeSearchesAndBrowsingBetterEnabled() const override; bool GetIsCustomTab() const override; + bool GetIsTabCreatedByGSA() const override; // Intentionally public to give tests direct access. std::unique_ptr<TriggerScriptCoordinator::UiDelegate> @@ -69,6 +70,7 @@ bool proactive_help_enabled_ = true; bool msbb_enabled_ = true; bool is_custom_tab_ = true; + bool is_tab_created_by_gsa_ = true; base::OnceCallback<void( GURL url, std::unique_ptr<TriggerContext> trigger_context,
diff --git a/components/autofill_assistant/browser/starter.cc b/components/autofill_assistant/browser/starter.cc index 332bb03..b3cd1ea8 100644 --- a/components/autofill_assistant/browser/starter.cc +++ b/components/autofill_assistant/browser/starter.cc
@@ -369,7 +369,7 @@ fetch_trigger_scripts_on_navigation_ = ((base::FeatureList::IsEnabled( features::kAutofillAssistantInCCTTriggering) && - is_custom_tab_) || + is_custom_tab_ && platform_delegate_->GetIsTabCreatedByGSA()) || (base::FeatureList::IsEnabled( features::kAutofillAssistantInTabTriggering) && !is_custom_tab_)) &&
diff --git a/components/autofill_assistant/browser/starter_platform_delegate.h b/components/autofill_assistant/browser/starter_platform_delegate.h index 4a06c56b..b80d9d6c 100644 --- a/components/autofill_assistant/browser/starter_platform_delegate.h +++ b/components/autofill_assistant/browser/starter_platform_delegate.h
@@ -86,6 +86,8 @@ virtual bool GetMakeSearchesAndBrowsingBetterEnabled() const = 0; // Returns whether this is a custom tab or not. virtual bool GetIsCustomTab() const = 0; + // Returns whether the tab was created by GSA or not. + virtual bool GetIsTabCreatedByGSA() const = 0; }; } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/starter_unittest.cc b/components/autofill_assistant/browser/starter_unittest.cc index 3b84bb0..afc3d6c 100644 --- a/components/autofill_assistant/browser/starter_unittest.cc +++ b/components/autofill_assistant/browser/starter_unittest.cc
@@ -1111,6 +1111,21 @@ EXPECT_THAT(GetUkmInChromeTriggering(ukm_recorder_), IsEmpty()); } +TEST_F(StarterTest, DoNotStartImplicitlyForNonAgaCct) { + SetupPlatformDelegateForReturningUser(); + fake_platform_delegate_.is_tab_created_by_gsa_ = false; + auto scoped_feature_list = std::make_unique<base::test::ScopedFeatureList>(); + scoped_feature_list->InitAndEnableFeature( + features::kAutofillAssistantInCCTTriggering); + starter_->CheckSettings(); + + EXPECT_CALL(*mock_trigger_script_service_request_sender_, OnSendRequest) + .Times(0); + SimulateNavigateToUrl(GURL("https://www.some-website.com/cart")); + task_environment()->RunUntilIdle(); + EXPECT_THAT(GetUkmInChromeTriggering(ukm_recorder_), IsEmpty()); +} + TEST_F(StarterTest, ImplicitStartupOnCurrentUrlAfterSettingEnabled) { SetupPlatformDelegateForReturningUser(); fake_platform_delegate_.proactive_help_enabled_ = false;
diff --git a/components/content_settings/browser/content_settings_manager_impl.cc b/components/content_settings/browser/content_settings_manager_impl.cc index b694be6..bb210d17 100644 --- a/components/content_settings/browser/content_settings_manager_impl.cc +++ b/components/content_settings/browser/content_settings_manager_impl.cc
@@ -10,6 +10,7 @@ #include "components/content_settings/core/browser/cookie_settings.h" #include "components/page_load_metrics/browser/metrics_web_contents_observer.h" #include "components/page_load_metrics/browser/page_load_metrics_observer.h" +#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -124,6 +125,17 @@ settings->OnContentBlocked(type); } +// We may or may not be on the UI thread depending on whether the +// NavigationThreadingOptimizations feature is enabled. +// TODO(https://crbug.com/1187753): Clean this up once the feature is +// shipped and the code path is removed. +void RunOrPostTaskOnUI(const base::Location& location, base::OnceClosure task) { + if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) + std::move(task).Run(); + else + content::GetUIThreadTaskRunner({})->PostTask(location, std::move(task)); +} + } // namespace ContentSettingsManagerImpl::~ContentSettingsManagerImpl() = default; @@ -177,8 +189,8 @@ return; } - content::RunOrPostTaskOnThread( - FROM_HERE, content::BrowserThread::UI, + RunOrPostTaskOnUI( + FROM_HERE, base::BindOnce(&NotifyStorageAccess, render_process_id_, render_frame_id, storage_type, url, top_frame_origin, allowed)); @@ -188,10 +200,9 @@ void ContentSettingsManagerImpl::OnContentBlocked(int32_t render_frame_id, ContentSettingsType type) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - content::RunOrPostTaskOnThread( - FROM_HERE, content::BrowserThread::UI, - base::BindOnce(&OnContentBlockedOnUI, render_process_id_, render_frame_id, - type)); + RunOrPostTaskOnUI(FROM_HERE, + base::BindOnce(&OnContentBlockedOnUI, render_process_id_, + render_frame_id, type)); } ContentSettingsManagerImpl::ContentSettingsManagerImpl(
diff --git a/components/download/internal/common/download_utils.cc b/components/download/internal/common/download_utils.cc index 6addf413..fe123144 100644 --- a/components/download/internal/common/download_utils.cc +++ b/components/download/internal/common/download_utils.cc
@@ -55,7 +55,11 @@ const int kDefaultOverwrittenDownloadExpiredTimeInDays = 90; // Default buffer size in bytes to write to the download file. +#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) +const int kDefaultDownloadFileBufferSize = 524288; // Desktop uses 512 KB. +#else const int kDefaultDownloadFileBufferSize = 4096; +#endif #if defined(OS_ANDROID) // Default maximum length of a downloaded file name on Android.
diff --git a/components/download/public/common/download_features.cc b/components/download/public/common/download_features.cc index 26b30ae..d5c2493f 100644 --- a/components/download/public/common/download_features.cc +++ b/components/download/public/common/download_features.cc
@@ -71,7 +71,13 @@ "DeleteOverwrittenDownloads", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAllowFileBufferSizeControl{ - "AllowFileBufferSizeControl", base::FEATURE_DISABLED_BY_DEFAULT}; + "AllowFileBufferSizeControl", +#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; } // namespace features
diff --git a/components/enterprise/browser/reporting/policy_info.cc b/components/enterprise/browser/reporting/policy_info.cc index 1b03b3bb..cc7ed94 100644 --- a/components/enterprise/browser/reporting/policy_info.cc +++ b/components/enterprise/browser/reporting/policy_info.cc
@@ -59,8 +59,8 @@ Policy_PolicySource_SOURCE_DEVICE_LOCAL_ACCOUNT_OVERRIDE_DEPRECATED; case policy::POLICY_SOURCE_PLATFORM: return em::Policy_PolicySource_SOURCE_PLATFORM; - case policy::POLICY_SOURCE_PRIORITY_CLOUD: - return em::Policy_PolicySource_SOURCE_PRIORITY_CLOUD; + case policy::POLICY_SOURCE_PRIORITY_CLOUD_DEPRECATED: + return em::Policy_PolicySource_SOURCE_PRIORITY_CLOUD_DEPRECATED; case policy::POLICY_SOURCE_MERGED: return em::Policy_PolicySource_SOURCE_MERGED; case policy::POLICY_SOURCE_CLOUD_FROM_ASH:
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 f4ae1b77..82bf7faa 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
@@ -873,6 +873,35 @@ } /** + * If an intent is targeting other browser-like apps, but this app can handle the target URL, + * then we should just handle the navigation in this app and avoid launching other browsers. + */ + private boolean shouldHandleNonSelfWebIntent(boolean hasSpecializedHandler, + boolean isIntentWithSupportedProtocol, Intent targetIntent) { + // We allow specialized handlers to receive web intents. + if (hasSpecializedHandler) return false; + if (!isIntentWithSupportedProtocol) return false; + + // Note that up until at least Android S, an empty action will match any intent filter + // with with an action specified. + if (!TextUtils.isEmpty(targetIntent.getAction()) + && !targetIntent.getAction().equals(Intent.ACTION_VIEW)) { + return false; + } + + // We currently allow websites to do things like open CCTs... + if (targetIntent.getPackage() != null + && targetIntent.getPackage().equals( + ContextUtils.getApplicationContext().getPackageName())) { + return false; + } + + RecordHistogram.recordBooleanHistogram("Android.Intent.WebIntentToOtherBrowser", true); + if (DEBUG) Log.i(TAG, "Intent to browser app."); + return true; + } + + /** * Current URL has at least one specialized handler available. For navigations * within the same host, keep the navigation inside the browser unless the set of * available apps to handle the new navigation is different. http://crbug.com/463138 @@ -1203,7 +1232,12 @@ return OverrideUrlLoadingResult.forNoOverride(); } + GURL intentDataUrl = new GURL(targetIntent.getDataString()); boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(params.getUrl()); + // intent: URLs are considered an external protocol, but may still contain a Data URI that + // this app does support, and may still end up launching this app. + boolean isIntentWithSupportedProtocol = UrlUtilities.hasIntentScheme(params.getUrl()) + && UrlUtilities.isAcceptedScheme(intentDataUrl); if (isInternalPdfDownload(isExternalProtocol, params)) { return OverrideUrlLoadingResult.forNoOverride(); @@ -1290,6 +1324,12 @@ } return fallBackToHandlingInApp(); } + if (shouldHandleNonSelfWebIntent( + hasSpecializedHandler, isIntentWithSupportedProtocol, targetIntent)) { + // We could consider using the fallback URL here, but loading the URL the site was + // trying to load in a browser seems like the better choice. + return clobberCurrentTab(intentDataUrl, params.getReferrerUrl()); + } // From this point on we should only have intents that this app can't handle, or intents for // apps with specialized handlers. @@ -1313,7 +1353,7 @@ assert intentResolutionMatches(debugIntent, targetIntent); if (params.isIncognito()) { - return handleIncognitoIntent(params, targetIntent, resolvingInfos.get(), + return handleIncognitoIntent(params, targetIntent, intentDataUrl, resolvingInfos.get(), browserFallbackUrl, shouldProxyForInstantApps); } @@ -1334,17 +1374,16 @@ } private OverrideUrlLoadingResult handleIncognitoIntent(ExternalNavigationParams params, - Intent targetIntent, List<ResolveInfo> resolvingInfos, GURL browserFallbackUrl, - boolean shouldProxyForInstantApps) { + Intent targetIntent, GURL intentDataUrl, List<ResolveInfo> resolvingInfos, + GURL browserFallbackUrl, boolean shouldProxyForInstantApps) { boolean intentTargetedToApp = mDelegate.willAppHandleIntent(targetIntent); GURL fallbackUrl = browserFallbackUrl; // If we can handle the intent, then fall back to handling the target URL instead of // the fallbackUrl if the user decides not to leave incognito. if (resolveInfoContainsSelf(resolvingInfos)) { - GURL targetUrl = UrlUtilities.hasIntentScheme(params.getUrl()) - ? new GURL(targetIntent.getDataString()) - : params.getUrl(); + GURL targetUrl = + UrlUtilities.hasIntentScheme(params.getUrl()) ? intentDataUrl : params.getUrl(); // Make sure the browser can handle this URL, in case the Intent targeted a // non-browser component for this app. if (UrlUtilities.isAcceptedScheme(targetUrl)) fallbackUrl = targetUrl;
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 5af25a65a..21118f34 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
@@ -89,6 +89,7 @@ private static final boolean HANDLES_INSTANT_APP_LAUNCHING_INTERNALLY = true; private static final boolean INTENT_STARTED_TASK = true; + private static final String SELF_PACKAGE_NAME = "test.app.name"; private static final String INTENT_APP_PACKAGE_NAME = "com.imdb.mobile"; private static final String YOUTUBE_URL = "http://youtube.com/"; private static final String YOUTUBE_MOBILE_URL = "http://m.youtube.com"; @@ -123,14 +124,14 @@ "intent:///name/nm0000158#Intent;scheme=imdb;package=com.imdb.mobile;S." + ExternalNavigationHandler.EXTRA_MARKET_REFERRER + "=" + ENCODED_MARKET_REFERRER + ";end"; - private static final String INTENT_URL_FOR_CHROME_CUSTOM_TABS = "intent://example.com#Intent;" - + "package=org.chromium.chrome;" + private static final String INTENT_URL_FOR_SELF_CUSTOM_TABS = "intent://example.com#Intent;" + + "package=" + SELF_PACKAGE_NAME + ";" + "action=android.intent.action.VIEW;" + "scheme=http;" + "S.android.support.customtabs.extra.SESSION=;" + "end;"; - private static final String INTENT_URL_FOR_CHROME = "intent://example.com#Intent;" - + "package=org.chromium.chrome;" + private static final String INTENT_URL_FOR_SELF = "intent://example.com#Intent;" + + "package=" + SELF_PACKAGE_NAME + ";" + "action=android.intent.action.VIEW;" + "scheme=http;" + "S." + ExternalNavigationHandler.EXTRA_BROWSER_FALLBACK_URL + "=" @@ -761,7 +762,7 @@ public void testCCTIntentUriDoesNotFireCCTAndLoadInChrome_InIncognito() throws Exception { mUrlHandler.mResolveInfoContainsSelf = true; mDelegate.setCanLoadUrlInTab(false); - checkUrl(INTENT_URL_FOR_CHROME_CUSTOM_TABS) + checkUrl(INTENT_URL_FOR_SELF_CUSTOM_TABS) .withIsIncognito(true) .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB, IGNORE); Assert.assertNull(mDelegate.startActivityIntent); @@ -771,7 +772,7 @@ @Test @SmallTest public void testCCTIntentUriFiresCCT_InRegular() throws Exception { - checkUrl(INTENT_URL_FOR_CHROME_CUSTOM_TABS) + checkUrl(INTENT_URL_FOR_SELF_CUSTOM_TABS) .withIsIncognito(false) .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, START_OTHER_ACTIVITY); @@ -783,14 +784,14 @@ public void testChromeIntentUriDoesNotFireAndLoadsInChrome_InIncognito() throws Exception { mUrlHandler.mResolveInfoContainsSelf = true; mDelegate.setCanLoadUrlInTab(false); - checkUrl(INTENT_URL_FOR_CHROME) + checkUrl(INTENT_URL_FOR_SELF) .withIsIncognito(true) .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB, IGNORE); Assert.assertNull(mDelegate.startActivityIntent); Assert.assertEquals("http://example.com/", mUrlHandler.mNewUrlAfterClobbering); mUrlHandler.mResolveInfoContainsSelf = false; - checkUrl(INTENT_URL_FOR_CHROME) + checkUrl(INTENT_URL_FOR_SELF) .withIsIncognito(true) .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB, IGNORE); Assert.assertNull(mDelegate.startActivityIntent); @@ -2276,6 +2277,19 @@ mUrlHandler.canExternalAppHandleUrl(new GURL(indexOutOfBoundsException))); } + @Test + @SmallTest + public void testIntentToOtherBrowser() { + // This will create a non-specialized ResolveInfo for the target package. + mDelegate.setCanResolveActivityForExternalSchemes(true); + + String intent = "intent://example.com#Intent;scheme=https;package=com.other.browser;end"; + + checkUrl(intent) + .withPageTransition(PageTransition.LINK) + .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB, IGNORE); + } + private static List<ResolveInfo> makeResolveInfos(ResolveInfo... infos) { return Arrays.asList(infos); } @@ -2905,7 +2919,7 @@ @Override public String getPackageName() { - return "test.app.name"; + return SELF_PACKAGE_NAME; } @Override
diff --git a/components/gcm_driver/crypto/BUILD.gn b/components/gcm_driver/crypto/BUILD.gn index 8b5656e..e4f6e45 100644 --- a/components/gcm_driver/crypto/BUILD.gn +++ b/components/gcm_driver/crypto/BUILD.gn
@@ -31,6 +31,7 @@ "//crypto", "//crypto:platform", "//net", + "//third_party/leveldatabase", "//third_party/protobuf:protobuf_lite", ] }
diff --git a/components/gcm_driver/crypto/gcm_key_store.cc b/components/gcm_driver/crypto/gcm_key_store.cc index 9cb0146..dd4d066 100644 --- a/components/gcm_driver/crypto/gcm_key_store.cc +++ b/components/gcm_driver/crypto/gcm_key_store.cc
@@ -19,6 +19,7 @@ #include "components/leveldb_proto/public/proto_database_provider.h" #include "components/leveldb_proto/public/shared_proto_database_client_list.h" #include "crypto/random.h" +#include "third_party/leveldatabase/env_chromium.h" namespace gcm { @@ -31,6 +32,9 @@ // authentication secret. Must be at least 16 bytes. const size_t kAuthSecretBytes = 16; +// Size cap for the leveldb log file before compression. +const size_t kDatabaseWriteBufferSizeBytes = 16 * 1024; + std::string DatabaseKey(const std::string& app_id, const std::string& authorized_entity) { DCHECK_EQ(std::string::npos, app_id.find(',')); @@ -41,6 +45,14 @@ : app_id + ',' + authorized_entity; } +leveldb_env::Options CreateLevelDbOptions() { + leveldb_env::Options options; + options.create_if_missing = true; + options.max_open_files = 0; // Use minimum. + options.write_buffer_size = kDatabaseWriteBufferSizeBytes; + return options; +} + } // namespace enum class GCMKeyStore::State { @@ -292,7 +304,7 @@ blocking_task_runner_); database_->Init( - leveldb_proto::CreateSimpleOptions(), + CreateLevelDbOptions(), base::BindOnce(&GCMKeyStore::DidInitialize, weak_factory_.GetWeakPtr())); }
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index a62574f8..a133e2a 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -363,8 +363,6 @@ break; } } - UMA_HISTOGRAM_COUNTS_1000("PasswordManager.NumFormManagersCleared", - form_managers_.size()); form_managers_.clear(); TryToFindPredictionsToPossibleUsernameData();
diff --git a/components/policy/core/browser/browser_policy_connector.cc b/components/policy/core/browser/browser_policy_connector.cc index 2f914ef..00ed00f 100644 --- a/components/policy/core/browser/browser_policy_connector.cc +++ b/components/policy/core/browser/browser_policy_connector.cc
@@ -204,8 +204,6 @@ CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs); registry->RegisterBooleanPref( policy_prefs::kCloudManagementEnrollmentMandatory, false); - registry->RegisterBooleanPref( - policy_prefs::kCloudPolicyOverridesPlatformPolicy, false); } } // namespace policy
diff --git a/components/policy/core/browser/policy_pref_mapping_test.cc b/components/policy/core/browser/policy_pref_mapping_test.cc index 7bfba9b..200c3d2 100644 --- a/components/policy/core/browser/policy_pref_mapping_test.cc +++ b/components/policy/core/browser/policy_pref_mapping_test.cc
@@ -453,8 +453,6 @@ settings.source = POLICY_SOURCE_DEVICE_LOCAL_ACCOUNT_OVERRIDE_DEPRECATED; else if (*source == "platform") settings.source = POLICY_SOURCE_PLATFORM; - else if (*source == "priority_cloud") - settings.source = POLICY_SOURCE_PRIORITY_CLOUD; else if (*source == "merged") settings.source = POLICY_SOURCE_MERGED; else if (*source == "cloud_from_ash")
diff --git a/components/policy/core/common/features.cc b/components/policy/core/common/features.cc index b3a7a45..f354daf 100644 --- a/components/policy/core/common/features.cc +++ b/components/policy/core/common/features.cc
@@ -27,7 +27,7 @@ const base::Feature kUploadBrowserDeviceIdentifier{ "UploadBrowserDeviceIdentifier", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kCRDForManagedUserSessions{ +const base::Feature kCrdForManagedUserSessions{ "CRDForManagedUserSessions", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kLoginEventReporting{"LoginEventReporting",
diff --git a/components/policy/core/common/features.h b/components/policy/core/common/features.h index 45e93ed..c061d6e0 100644 --- a/components/policy/core/common/features.h +++ b/components/policy/core/common/features.h
@@ -35,7 +35,7 @@ POLICY_EXPORT extern const base::Feature kUploadBrowserDeviceIdentifier; // Enable Chrome Remote Desktop for Managed Guest Sessions and affiliated users. -POLICY_EXPORT extern const base::Feature kCRDForManagedUserSessions; +POLICY_EXPORT extern const base::Feature kCrdForManagedUserSessions; // Enable reporting Login events to the reporting connector when the Password // Manager detects that the user logged in to a web page.
diff --git a/components/policy/core/common/policy_map.cc b/components/policy/core/common/policy_map.cc index 284b99e3..016825c 100644 --- a/components/policy/core/common/policy_map.cc +++ b/components/policy/core/common/policy_map.cc
@@ -87,7 +87,7 @@ : POLICY_PRIORITY_BROWSER_CLOUD_USER_RAISED; } return POLICY_PRIORITY_BROWSER_CLOUD_USER; - case POLICY_SOURCE_PRIORITY_CLOUD: + case POLICY_SOURCE_PRIORITY_CLOUD_DEPRECATED: return POLICY_PRIORITY_BROWSER_CLOUD_MACHINE_RAISED; case POLICY_SOURCE_PLATFORM: return scope == POLICY_SCOPE_MACHINE
diff --git a/components/policy/core/common/policy_pref_names.cc b/components/policy/core/common/policy_pref_names.cc index 8d3f0f6c..99e3a3d 100644 --- a/components/policy/core/common/policy_pref_names.cc +++ b/components/policy/core/common/policy_pref_names.cc
@@ -39,10 +39,6 @@ const char kCloudManagementEnrollmentMandatory[] = "policy.cloud_management_enrollment_mandatory"; -// Boolean that specifies whether the cloud policy will override conflicting -// machine policy. -const char kCloudPolicyOverridesPlatformPolicy[] = "policy.cloud_override"; - // Integer that sets the minimal limit on the data size in the clipboard to be // checked against Data Leak Prevention rules. const char kDlpClipboardCheckSizeLimit[] =
diff --git a/components/policy/core/common/policy_pref_names.h b/components/policy/core/common/policy_pref_names.h index b245565..ba4f3a5 100644 --- a/components/policy/core/common/policy_pref_names.h +++ b/components/policy/core/common/policy_pref_names.h
@@ -12,7 +12,6 @@ namespace policy_prefs { POLICY_EXPORT extern const char kCloudManagementEnrollmentMandatory[]; -POLICY_EXPORT extern const char kCloudPolicyOverridesPlatformPolicy[]; POLICY_EXPORT extern const char kDlpClipboardCheckSizeLimit[]; POLICY_EXPORT extern const char kDlpReportingEnabled[]; POLICY_EXPORT extern const char kDlpRulesList[];
diff --git a/components/policy/core/common/policy_types.h b/components/policy/core/common/policy_types.h index 98daa8c..60cf114d 100644 --- a/components/policy/core/common/policy_types.h +++ b/components/policy/core/common/policy_types.h
@@ -53,8 +53,9 @@ // The policy was set by a platform source. POLICY_SOURCE_PLATFORM, - // The policy was set by a cloud source that has higher priority. - POLICY_SOURCE_PRIORITY_CLOUD, + // The policy was set by a cloud source that has higher priroity. + // TODO(crbug.com/1249611): Remove deprecated policy source. + POLICY_SOURCE_PRIORITY_CLOUD_DEPRECATED, // The policy coming from multiple sources and its value has been merged. POLICY_SOURCE_MERGED,
diff --git a/components/policy/proto/device_management_backend.proto b/components/policy/proto/device_management_backend.proto index 868350fd..7449de09 100644 --- a/components/policy/proto/device_management_backend.proto +++ b/components/policy/proto/device_management_backend.proto
@@ -1870,7 +1870,7 @@ // A policy is set by Google's cloud management tool but has higher // priority. - SOURCE_PRIORITY_CLOUD = 6; + SOURCE_PRIORITY_CLOUD_DEPRECATED = 6; // A policy is set by multiple sources and value has been merged. SOURCE_MERGED = 7;
diff --git a/components/sync/driver/sync_user_settings_impl.cc b/components/sync/driver/sync_user_settings_impl.cc index c2c4cf99..abdf2097 100644 --- a/components/sync/driver/sync_user_settings_impl.cc +++ b/components/sync/driver/sync_user_settings_impl.cc
@@ -114,16 +114,12 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) bool SyncUserSettingsImpl::IsSyncAllOsTypesEnabled() const { - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - DCHECK(chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()); + DCHECK(chromeos::features::IsSyncSettingsCategorizationEnabled()); return prefs_->IsSyncAllOsTypesEnabled(); } UserSelectableOsTypeSet SyncUserSettingsImpl::GetSelectedOsTypes() const { - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - DCHECK(chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()); + DCHECK(chromeos::features::IsSyncSettingsCategorizationEnabled()); UserSelectableOsTypeSet types = prefs_->GetSelectedOsTypes(); types.RetainAll(GetRegisteredSelectableOsTypes()); return types; @@ -131,9 +127,7 @@ void SyncUserSettingsImpl::SetSelectedOsTypes(bool sync_all_os_types, UserSelectableOsTypeSet types) { - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - DCHECK(chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()); + DCHECK(chromeos::features::IsSyncSettingsCategorizationEnabled()); UserSelectableOsTypeSet registered_types = GetRegisteredSelectableOsTypes(); DCHECK(registered_types.HasAll(types)); prefs_->SetSelectedOsTypes(sync_all_os_types, registered_types, types); @@ -141,9 +135,7 @@ UserSelectableOsTypeSet SyncUserSettingsImpl::GetRegisteredSelectableOsTypes() const { - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - DCHECK(chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()); + DCHECK(chromeos::features::IsSyncSettingsCategorizationEnabled()); UserSelectableOsTypeSet registered_types; for (UserSelectableOsType type : UserSelectableOsTypeSet::All()) { if (registered_model_types_.Has( @@ -155,9 +147,7 @@ } bool SyncUserSettingsImpl::IsOsSyncFeatureEnabled() const { - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - DCHECK(chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()); + DCHECK(chromeos::features::IsSyncSettingsCategorizationEnabled()); return prefs_->IsOsSyncFeatureEnabled(); } @@ -250,9 +240,7 @@ ModelTypeSet types = ResolvePreferredTypes(GetSelectedTypes()); types.PutAll(AlwaysPreferredUserTypes()); #if BUILDFLAG(IS_CHROMEOS_ASH) - // TODO(https://crbug.com/1227417): Remove SplitSettingsSync from this check. - if (chromeos::features::IsSplitSettingsSyncEnabled() || - chromeos::features::IsSyncSettingsCategorizationEnabled()) { + if (chromeos::features::IsSyncSettingsCategorizationEnabled()) { types.PutAll(ResolvePreferredOsTypes(GetSelectedOsTypes())); } #endif
diff --git a/components/viz/common/resources/resource_format_utils.cc b/components/viz/common/resources/resource_format_utils.cc index 498e51a..2b52ef9 100644 --- a/components/viz/common/resources/resource_format_utils.cc +++ b/components/viz/common/resources/resource_format_utils.cc
@@ -53,12 +53,14 @@ case YUV_420_BIPLANAR: return kRGB_888x_SkColorType; - // Use kN32_SkColorType if there is no corresponding SkColorType. case RED_8: - return kGray_8_SkColorType; - case LUMINANCE_F16: + return kAlpha_8_SkColorType; case R16_EXT: + return kA16_unorm_SkColorType; case RG16_EXT: + return kR16G16_unorm_SkColorType; + // Use kN32_SkColorType if there is no corresponding SkColorType. + case LUMINANCE_F16: case BGR_565: return kN32_SkColorType; case RG_88:
diff --git a/components/web_package/web_bundle_parser.cc b/components/web_package/web_bundle_parser.cc index 75677249..a0257e8 100644 --- a/components/web_package/web_bundle_parser.cc +++ b/components/web_package/web_bundle_parser.cc
@@ -278,11 +278,13 @@ DISALLOW_COPY_AND_ASSIGN(InputReader); }; -GURL ParseExchangeURL(base::StringPiece str) { +GURL ParseExchangeURL(base::StringPiece str, const GURL& base_url) { + DCHECK(base_url.is_empty() || base_url.is_valid()); + if (!base::IsStringUTF8(str)) return GURL(); - GURL url(str); + GURL url = base_url.is_valid() ? base_url.Resolve(str) : GURL(str); if (!url.is_valid()) return GURL(); @@ -318,8 +320,12 @@ : WebBundleParser::SharedBundleDataSource::Observer { public: MetadataParser(scoped_refptr<SharedBundleDataSource> data_source, + const GURL& base_url, ParseMetadataCallback callback) - : data_source_(data_source), callback_(std::move(callback)) { + : data_source_(data_source), + base_url_(base_url), + callback_(std::move(callback)) { + DCHECK(base_url_.is_empty() || base_url_.is_valid()); data_source_->AddObserver(this); } @@ -455,7 +461,7 @@ // TODO(crbug.com/966753): Revisit URL requirements here once // https://github.com/WICG/webpackage/issues/469 is resolved. - GURL primary_url = ParseExchangeURL(*primary_url_string); + GURL primary_url = ParseExchangeURL(*primary_url_string, base_url_); if (!primary_url.is_valid()) { RunErrorCallbackAndDestroy("Cannot parse primary URL."); return; @@ -698,7 +704,7 @@ const std::string& url = item.first.GetString(); const cbor::Value::ArrayValue& responses_array = item.second.GetArray(); - GURL parsed_url = ParseExchangeURL(url); + GURL parsed_url = ParseExchangeURL(url, base_url_); if (!parsed_url.is_valid()) { RunErrorCallbackAndDestroy("Index section: exchange URL is not valid."); @@ -792,7 +798,7 @@ RunErrorCallbackAndDestroy("Manifest section must be a string."); return false; } - GURL parsed_url = ParseExchangeURL(section_value.GetString()); + GURL parsed_url = ParseExchangeURL(section_value.GetString(), base_url_); if (!parsed_url.is_valid()) { RunErrorCallbackAndDestroy("Manifest URL is not a valid exchange URL."); @@ -945,7 +951,8 @@ RunErrorCallbackAndDestroy("Primary section must be a string."); return false; } - GURL parsed_url = ParseExchangeURL(section_value.GetString()); + + GURL parsed_url = ParseExchangeURL(section_value.GetString(), base_url_); if (!parsed_url.is_valid()) { RunErrorCallbackAndDestroy("Primary URL is not a valid exchange URL."); @@ -1020,6 +1027,7 @@ } // TODO(crbug.com/966753): Revisit this once requirements for validity URL // are speced. + // TODO(crbug.com/1247939): Consider supporting relative validity URL. GURL validity_url(validity_url_value->GetString()); if (!validity_url.is_valid()) { RunErrorCallbackAndDestroy("Cannot parse validity-url."); @@ -1070,7 +1078,9 @@ const std::string& url = item.first.GetString(); const cbor::Value::ArrayValue& value_array = item.second.GetArray(); - GURL parsed_url = ParseExchangeURL(url); + // TODO(crbug.com/1247939): Consider supporting relative URL in the + // signature section. + GURL parsed_url = ParseExchangeURL(url, /*base_url=*/GURL()); if (!parsed_url.is_valid()) { RunErrorCallbackAndDestroy("subset-hashes: exchange URL is not valid."); return nullptr; @@ -1141,6 +1151,7 @@ } scoped_refptr<SharedBundleDataSource> data_source_; + const GURL base_url_; ParseMetadataCallback callback_; GURL primary_url_; SectionOffsets section_offsets_; @@ -1354,10 +1365,13 @@ WebBundleParser::WebBundleParser( mojo::PendingReceiver<mojom::WebBundleParser> receiver, - mojo::PendingRemote<mojom::BundleDataSource> data_source) + mojo::PendingRemote<mojom::BundleDataSource> data_source, + const GURL& base_url) : receiver_(this, std::move(receiver)), - data_source_(base::MakeRefCounted<SharedBundleDataSource>( - std::move(data_source))) { + data_source_( + base::MakeRefCounted<SharedBundleDataSource>(std::move(data_source))), + base_url_(base_url) { + DCHECK(base_url_.is_empty() || base_url_.is_valid()); receiver_.set_disconnect_handler(base::BindOnce( &base::DeletePointer<WebBundleParser>, base::Unretained(this))); } @@ -1366,7 +1380,7 @@ void WebBundleParser::ParseMetadata(ParseMetadataCallback callback) { MetadataParser* parser = - new MetadataParser(data_source_, std::move(callback)); + new MetadataParser(data_source_, base_url_, std::move(callback)); parser->Start(); }
diff --git a/components/web_package/web_bundle_parser.h b/components/web_package/web_bundle_parser.h index 4804495..bc9d432e 100644 --- a/components/web_package/web_bundle_parser.h +++ b/components/web_package/web_bundle_parser.h
@@ -11,13 +11,15 @@ #include "components/web_package/mojom/web_bundle_parser.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" +#include "url/gurl.h" namespace web_package { class WebBundleParser : public mojom::WebBundleParser { public: WebBundleParser(mojo::PendingReceiver<mojom::WebBundleParser> receiver, - mojo::PendingRemote<mojom::BundleDataSource> data_source); + mojo::PendingRemote<mojom::BundleDataSource> data_source, + const GURL& base_url); WebBundleParser(const WebBundleParser&) = delete; WebBundleParser& operator=(const WebBundleParser&) = delete; @@ -64,6 +66,7 @@ mojo::Receiver<mojom::WebBundleParser> receiver_; scoped_refptr<SharedBundleDataSource> data_source_; + const GURL base_url_; }; } // namespace web_package
diff --git a/components/web_package/web_bundle_parser_factory.cc b/components/web_package/web_bundle_parser_factory.cc index 8079508f..d9d929d6 100644 --- a/components/web_package/web_bundle_parser_factory.cc +++ b/components/web_package/web_bundle_parser_factory.cc
@@ -69,8 +69,11 @@ void WebBundleParserFactory::GetParserForDataSource( mojo::PendingReceiver<mojom::WebBundleParser> receiver, mojo::PendingRemote<mojom::BundleDataSource> data_source) { + // TODO(crbug.com/1247939): WebBundleParserFactory doesn't support |base_url|. + // For features::kWebBundlesFromNetwork should support |base_url|. auto parser = std::make_unique<WebBundleParser>(std::move(receiver), - std::move(data_source)); + std::move(data_source), + /*base_url=*/GURL()); // |parser| will be destructed on remote mojo ends' disconnection. parser.release();
diff --git a/components/web_package/web_bundle_parser_unittest.cc b/components/web_package/web_bundle_parser_unittest.cc index 14300e9..fa2ebd4 100644 --- a/components/web_package/web_bundle_parser_unittest.cc +++ b/components/web_package/web_bundle_parser_unittest.cc
@@ -73,13 +73,14 @@ using ParseBundleResult = std::pair<mojom::BundleMetadataPtr, mojom::BundleMetadataParseErrorPtr>; -ParseBundleResult ParseBundle(TestDataSource* data_source) { +ParseBundleResult ParseBundle(TestDataSource* data_source, + const GURL& base_url = GURL()) { mojo::PendingRemote<mojom::BundleDataSource> source_remote; data_source->AddReceiver(source_remote.InitWithNewPipeAndPassReceiver()); mojo::PendingRemote<mojom::WebBundleParser> parser_remote; WebBundleParser parser_impl(parser_remote.InitWithNewPipeAndPassReceiver(), - std::move(source_remote)); + std::move(source_remote), base_url); mojom::WebBundleParser& parser = parser_impl; base::RunLoop run_loop; @@ -121,13 +122,14 @@ mojom::BundleResponsePtr ParseResponse( TestDataSource* data_source, - const mojom::BundleResponseLocationPtr& location) { + const mojom::BundleResponseLocationPtr& location, + const GURL& base_url = GURL()) { mojo::PendingRemote<mojom::BundleDataSource> source_remote; data_source->AddReceiver(source_remote.InitWithNewPipeAndPassReceiver()); mojo::PendingRemote<mojom::WebBundleParser> parser_remote; WebBundleParser parser_impl(parser_remote.InitWithNewPipeAndPassReceiver(), - std::move(source_remote)); + std::move(source_remote), base_url); mojom::WebBundleParser& parser = parser_impl; base::RunLoop run_loop; @@ -797,6 +799,37 @@ EXPECT_TRUE(metadata->primary_url.is_empty()); } +TEST_F(WebBundleParserTest, RelativeURL) { + constexpr BundleVersion kVersions[] = {BundleVersion::kB1, + BundleVersion::kB2}; + for (const auto& version : kVersions) { + test::WebBundleBuilder builder("path/to/primary_url", "path/to/manifest", + version); + builder.AddExchange("path/to/file.txt", + {{":status", "200"}, {"content-type", "text/plain"}}, + "payload"); + TestDataSource data_source(builder.CreateBundle()); + + const GURL base_url("https://test.example.com/dir/test.wbn"); + mojom::BundleMetadataPtr metadata = + ParseBundle(&data_source, base_url).first; + EXPECT_EQ(metadata->primary_url, + "https://test.example.com/dir/path/to/primary_url"); + EXPECT_EQ(metadata->manifest_url, + "https://test.example.com/dir/path/to/manifest"); + ASSERT_TRUE(metadata); + ASSERT_EQ(metadata->requests.size(), 1u); + auto location = FindResponse( + metadata, GURL("https://test.example.com/dir/path/to/file.txt")); + ASSERT_TRUE(location); + auto response = ParseResponse(&data_source, location, base_url); + ASSERT_TRUE(response); + EXPECT_EQ(response->response_code, 200); + EXPECT_EQ(response->response_headers.size(), 1u); + EXPECT_EQ(response->response_headers["content-type"], "text/plain"); + EXPECT_EQ(data_source.GetPayload(response), "payload"); + } +} // TODO(crbug.com/969596): Add a test case that loads a wbn file with variants, // once gen-bundle supports variants.
diff --git a/content/browser/accessibility/accessibility_tools_utils_mac.h b/content/browser/accessibility/accessibility_tools_utils_mac.h index ad15f4f9..5182a95 100644 --- a/content/browser/accessibility/accessibility_tools_utils_mac.h +++ b/content/browser/accessibility/accessibility_tools_utils_mac.h
@@ -9,6 +9,7 @@ #include "base/callback_forward.h" #include "content/common/content_export.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/accessibility/platform/inspect/ax_inspect.h" using ui::AXTreeSelector; @@ -55,6 +56,13 @@ id parameter); // +// Performs the given selector on the given node and returns the result. If +// the node does not conform to the NSAccessibility protocol or the selector is +// not found, then returns nullopt. +CONTENT_EXPORT absl::optional<id> PerformSelector(const id node, + const std::string& selector); + +// // Returns true if an attribute value can be changed on a given node // (either AXUIElement or BrowserAccessibilityCocoa). //
diff --git a/content/browser/accessibility/accessibility_tools_utils_mac.mm b/content/browser/accessibility/accessibility_tools_utils_mac.mm index ef437de8..d27bd72 100644 --- a/content/browser/accessibility/accessibility_tools_utils_mac.mm +++ b/content/browser/accessibility/accessibility_tools_utils_mac.mm
@@ -174,6 +174,18 @@ return nil; } +absl::optional<id> PerformSelector(const id node, + const std::string& selector_string) { + if (![node conformsToProtocol:@protocol(NSAccessibility)]) + return absl::nullopt; + + SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(selector_string)); + + if ([node respondsToSelector:selector]) + return [node performSelector:selector]; + return absl::nullopt; +} + bool IsAttributeSettable(const id node, NSString* attribute) { if (IsBrowserAccessibilityCocoa(node)) return [node accessibilityIsAttributeSettable:attribute];
diff --git a/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm b/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm index 4ce4b7e..37d54fb8 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm +++ b/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm
@@ -235,6 +235,16 @@ } } + // Invoke any methods that are declared in the NSAccessibility protocol. Note + // that they all start with the prefix "accessibility...", ignore all + // other selectors the object may respond. + if (base::StartsWith(property_node.name_or_value, "accessibility")) { + auto optional_id = PerformSelector(target, property_node.name_or_value); + if (optional_id) { + return OptionalNSObject(*optional_id); + } + } + // Unmatched attribute. No error for a tree dump calls because the tree dump // sets generic property filters not depending on a node, so we can be called // for an attribute not supported by the node.
diff --git a/content/browser/accessibility/dump_accessibility_node_browsertest.cc b/content/browser/accessibility/dump_accessibility_node_browsertest.cc index 14054bf..e1dd49b 100644 --- a/content/browser/accessibility/dump_accessibility_node_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_node_browsertest.cc
@@ -92,6 +92,9 @@ public: std::vector<ui::AXPropertyFilter> DefaultFilters() const override { std::vector<AXPropertyFilter> property_filters; + if (GetParam() == AXInspectFactory::kMac) + return property_filters; + property_filters.emplace_back("name*", AXPropertyFilter::ALLOW_EMPTY); property_filters.emplace_back("description*", AXPropertyFilter::ALLOW_EMPTY);
diff --git a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc index d8d0827..d8045e83 100644 --- a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc
@@ -126,6 +126,16 @@ RunTest(html_file, "accessibility/mac/textmarker"); } + + void RunMacMethodsTest(const base::FilePath::CharType* file_path) { + base::FilePath test_path = GetTestFilePath("accessibility", "mac/methods"); + { + base::ScopedAllowBlockingForTesting allow_blocking; + ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName(); + } + base::FilePath html_file = test_path.Append(base::FilePath(file_path)); + RunTest(html_file, "accessibility/mac/methods"); + } }; std::vector<ui::AXPropertyFilter> DumpAccessibilityScriptTest::DefaultFilters() @@ -197,6 +207,10 @@ FILE_PATH_LITERAL("ax-text-marker-range-for-ui-element.html")); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AccessibilityTitle) { + RunMacMethodsTest(FILE_PATH_LITERAL("title.html")); +} + #endif } // namespace content
diff --git a/content/browser/child_process_security_policy_impl.cc b/content/browser/child_process_security_policy_impl.cc index 8e36ca7..a95bfc1a2 100644 --- a/content/browser/child_process_security_policy_impl.cc +++ b/content/browser/child_process_security_policy_impl.cc
@@ -19,7 +19,6 @@ #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -162,19 +161,12 @@ return keep_alive_duration_key; } -base::debug::CrashKeyString* GetCanAccessDataShutdownDelayRefCountKey() { - static auto* shutdown_delay_key = base::debug::AllocateCrashKeyString( - "shutdown_delay_ref_count", base::debug::CrashKeySize::Size32); - return shutdown_delay_key; -} - void LogCanAccessDataForOriginCrashKeys( const std::string& expected_process_lock, const std::string& killed_process_origin_lock, const std::string& requested_origin, const std::string& failure_reason, - const std::string& keep_alive_durations, - const std::string& shutdown_delay_ref_count) { + const std::string& keep_alive_durations) { base::debug::SetCrashKeyString(GetExpectedProcessLockKey(), expected_process_lock); base::debug::SetCrashKeyString(GetKilledProcessOriginLockKey(), @@ -185,8 +177,6 @@ failure_reason); base::debug::SetCrashKeyString(GetCanAccessDataKeepAliveDurationKey(), keep_alive_durations); - base::debug::SetCrashKeyString(GetCanAccessDataShutdownDelayRefCountKey(), - shutdown_delay_ref_count); } } // namespace @@ -398,7 +388,7 @@ if (child_id_ == ChildProcessHost::kInvalidUniqueID) { LogCanAccessDataForOriginCrashKeys( "(unknown)", "(unknown)", origin.GetDebugString(), "handle_not_valid", - "no_keep_alive_durations", "no shutdown delay ref count"); + "no_keep_alive_durations"); return false; } @@ -1837,13 +1827,9 @@ // Record the duration of KeepAlive requests to include in the crash keys. std::string keep_alive_durations; - std::string shutdown_delay_ref_count; if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { - if (auto* process = static_cast<RenderProcessHostImpl*>( - RenderProcessHostImpl::FromID(child_id))) { + if (auto* process = RenderProcessHostImpl::FromID(child_id)) { keep_alive_durations = process->GetKeepAliveDurations(); - shutdown_delay_ref_count = - base::NumberToString(process->shutdown_delay_ref_count()); } } else { keep_alive_durations = "no durations available: on IO thread."; @@ -1851,10 +1837,10 @@ // Returning false here will result in a renderer kill. Set some crash // keys that will help understand the circumstances of that kill. - LogCanAccessDataForOriginCrashKeys( - expected_process_lock.ToString(), - GetKilledProcessOriginLock(security_state), url.GetOrigin().spec(), - failure_reason, keep_alive_durations, shutdown_delay_ref_count); + LogCanAccessDataForOriginCrashKeys(expected_process_lock.ToString(), + GetKilledProcessOriginLock(security_state), + url.GetOrigin().spec(), failure_reason, + keep_alive_durations); return false; }
diff --git a/content/browser/client_hints/client_hints.cc b/content/browser/client_hints/client_hints.cc index b7fca8a..fe95e6a6 100644 --- a/content/browser/client_hints/client_hints.cc +++ b/content/browser/client_hints/client_hints.cc
@@ -695,7 +695,7 @@ // If possible, logic should be added above so that the request headers for // the newly added client hint can be added to the request. static_assert( - network::mojom::WebClientHintsType::kViewportHeight == + network::mojom::WebClientHintsType::kViewportWidth == network::mojom::WebClientHintsType::kMaxValue, "Consider adding client hint request headers from the browser process");
diff --git a/content/browser/devtools/devtools_instrumentation.cc b/content/browser/devtools/devtools_instrumentation.cc index ea51232..b508f6d9 100644 --- a/content/browser/devtools/devtools_instrumentation.cc +++ b/content/browser/devtools/devtools_instrumentation.cc
@@ -33,6 +33,7 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_package/signed_exchange_envelope.h" #include "content/public/browser/browser_context.h" +#include "devtools_instrumentation.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "net/base/load_flags.h" @@ -1217,6 +1218,61 @@ } } +protocol::Audits::GenericIssueErrorType GenericIssueErrorTypeToProtocol( + blink::mojom::GenericIssueErrorType error_type) { + switch (error_type) { + case (blink::mojom::GenericIssueErrorType:: + kCrossOriginPortalPostMessageError): + return protocol::Audits::GenericIssueErrorTypeEnum:: + CrossOriginPortalPostMessageError; + } +} + +namespace { +struct GenericIssueInfo { + GenericIssueInfo() = default; + ~GenericIssueInfo() = default; + GenericIssueInfo(const GenericIssueInfo& info) = default; + + blink::mojom::GenericIssueErrorType error_type; + absl::optional<std::string> frame_id; +}; + +void BuildAndReportGenericIssue(RenderFrameHostImpl* render_frame_host_impl, + const GenericIssueInfo& issue_info) { + auto generic_issue_details = + protocol::Audits::GenericIssueDetails::Create() + .SetErrorType(GenericIssueErrorTypeToProtocol(issue_info.error_type)) + .Build(); + + if (issue_info.frame_id) { + generic_issue_details->SetFrameId(*issue_info.frame_id); + } + + auto issue = + protocol::Audits::InspectorIssue::Create() + .SetCode(protocol::Audits::InspectorIssueCodeEnum::GenericIssue) + .SetDetails( + protocol::Audits::InspectorIssueDetails::Create() + .SetGenericIssueDetails(std::move(generic_issue_details)) + .Build()) + .Build(); + + ReportBrowserInitiatedIssue(render_frame_host_impl, issue.get()); +} +} // namespace + +void DidRejectCrossOriginPortalMessage( + RenderFrameHostImpl* render_frame_host_impl) { + GenericIssueInfo issue_info; + issue_info.error_type = + blink::mojom::GenericIssueErrorType::kCrossOriginPortalPostMessageError; + issue_info.frame_id = + render_frame_host_impl->GetDevToolsFrameToken().ToString(); + + BuildAndReportGenericIssue(render_frame_host_impl, issue_info); +} + } // namespace devtools_instrumentation } // namespace content
diff --git a/content/browser/devtools/devtools_instrumentation.h b/content/browser/devtools/devtools_instrumentation.h index d279815..6aa16d2 100644 --- a/content/browser/devtools/devtools_instrumentation.h +++ b/content/browser/devtools/devtools_instrumentation.h
@@ -278,6 +278,9 @@ BrowserContext* browser_context, network::mojom::NetworkContextParams* network_context_params); +void DidRejectCrossOriginPortalMessage( + RenderFrameHostImpl* render_frame_host_impl); + } // namespace devtools_instrumentation } // namespace content
diff --git a/content/browser/field_trial_synchronizer.cc b/content/browser/field_trial_synchronizer.cc index 0af9ed30..deddf1b 100644 --- a/content/browser/field_trial_synchronizer.cc +++ b/content/browser/field_trial_synchronizer.cc
@@ -71,9 +71,13 @@ void FieldTrialSynchronizer::OnFieldTrialGroupFinalized( const std::string& field_trial_name, const std::string& group_name) { - RunOrPostTaskOnThread(FROM_HERE, BrowserThread::UI, - base::BindOnce(&NotifyAllRenderersOfFieldTrial, - field_trial_name, group_name)); + if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { + NotifyAllRenderersOfFieldTrial(field_trial_name, group_name); + } else { + GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, base::BindOnce(&NotifyAllRenderersOfFieldTrial, + field_trial_name, group_name)); + } } // static
diff --git a/content/browser/generic_sensor/sensor_provider_proxy_impl.h b/content/browser/generic_sensor/sensor_provider_proxy_impl.h index 4cd27db4..98ff72aa9 100644 --- a/content/browser/generic_sensor/sensor_provider_proxy_impl.h +++ b/content/browser/generic_sensor/sensor_provider_proxy_impl.h
@@ -52,10 +52,13 @@ blink::mojom::PermissionStatus); void OnConnectionError(); + // Callbacks from |receiver_set_| are passed to |sensor_provider_| and so + // the ReceiverSet should be destroyed first so that the callbacks are + // invalidated before being discarded. + mojo::Remote<device::mojom::SensorProvider> sensor_provider_; mojo::ReceiverSet<device::mojom::SensorProvider> receiver_set_; PermissionControllerImpl* permission_controller_; RenderFrameHost* render_frame_host_; - mojo::Remote<device::mojom::SensorProvider> sensor_provider_; base::WeakPtrFactory<SensorProviderProxyImpl> weak_factory_{this}; };
diff --git a/content/browser/generic_sensor/sensor_provider_proxy_impl_unittest.cc b/content/browser/generic_sensor/sensor_provider_proxy_impl_unittest.cc new file mode 100644 index 0000000..ec2bc78 --- /dev/null +++ b/content/browser/generic_sensor/sensor_provider_proxy_impl_unittest.cc
@@ -0,0 +1,138 @@ +// 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. + +#include <memory> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/test/bind.h" +#include "content/browser/generic_sensor/sensor_provider_proxy_impl.h" +#include "content/public/test/mock_permission_manager.h" +#include "content/public/test/test_browser_context.h" +#include "content/test/test_render_view_host.h" +#include "content/test/test_web_contents.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "services/device/public/cpp/test/fake_sensor_and_provider.h" +#include "services/device/public/mojom/sensor.mojom.h" +#include "services/device/public/mojom/sensor_provider.mojom.h" + +namespace content { + +namespace { + +// MockPermissionManager with a RequestPermission() implementation that always +// grants PermissionType::SENSORS requests. +class TestPermissionManager : public MockPermissionManager { + public: + void RequestPermission( + PermissionType permission, + RenderFrameHost* render_frame_host, + const GURL& requesting_origin, + bool user_gesture, + base::OnceCallback<void(blink::mojom::PermissionStatus)> callback) + override { + ASSERT_EQ(permission, PermissionType::SENSORS); + std::move(callback).Run(blink::mojom::PermissionStatus::GRANTED); + } +}; + +class SensorProviderProxyImplTest : public RenderViewHostImplTestHarness { + public: + SensorProviderProxyImplTest() = default; + ~SensorProviderProxyImplTest() override = default; + + SensorProviderProxyImplTest(const SensorProviderProxyImplTest&) = delete; + SensorProviderProxyImplTest& operator=(const SensorProviderProxyImplTest&) = + delete; + + void SetUp() override { + RenderViewHostImplTestHarness::SetUp(); + + std::unique_ptr<TestPermissionManager> mock_permission_manager( + new testing::NiceMock<TestPermissionManager>()); + static_cast<TestBrowserContext*>(browser_context()) + ->SetPermissionControllerDelegate(std::move(mock_permission_manager)); + + fake_sensor_provider_ = std::make_unique<device::FakeSensorProvider>(); + SensorProviderProxyImpl::OverrideSensorProviderBinderForTesting( + base::BindRepeating( + &SensorProviderProxyImplTest::BindSensorProviderReceiver, + base::Unretained(this))); + } + + void TearDown() override { + RenderViewHostImplTestHarness::TearDown(); + + SensorProviderProxyImpl::OverrideSensorProviderBinderForTesting( + base::NullCallback()); + fake_sensor_provider_.reset(); + } + + protected: + void set_fake_sensor_provider( + std::unique_ptr<device::FakeSensorProvider> fake_sensor_provider) { + DCHECK(!fake_sensor_provider_->is_bound()); + fake_sensor_provider_ = std::move(fake_sensor_provider); + } + + private: + void BindSensorProviderReceiver( + mojo::PendingReceiver<device::mojom::SensorProvider> receiver) { + fake_sensor_provider_->Bind(std::move(receiver)); + } + + std::unique_ptr<device::FakeSensorProvider> fake_sensor_provider_; +}; + +} // namespace + +// Allows callers to run a custom callback before running +// FakeSensorProvider::GetSensor(). +class InterceptingFakeSensorProvider : public device::FakeSensorProvider { + public: + explicit InterceptingFakeSensorProvider( + base::OnceClosure interception_callback) + : interception_callback_(std::move(interception_callback)) {} + + void GetSensor(device::mojom::SensorType type, + GetSensorCallback callback) override { + std::move(interception_callback_).Run(); + device::FakeSensorProvider::GetSensor(type, std::move(callback)); + } + + private: + base::OnceClosure interception_callback_; +}; + +// Test for https://crbug.com/1240814: destroying SensorProviderProxyImplTest +// between calling device::mojom::SensorProvider::GetSensor() and it running the +// callback does not crash. +TEST_F(SensorProviderProxyImplTest, DestructionOrderWithOngoingCallback) { + auto intercepting_fake_sensor_provider = + std::make_unique<InterceptingFakeSensorProvider>( + base::BindLambdaForTesting([&]() { + // Delete the current WebContents and consequently trigger + // SensorProviderProxyImpl's destruction before + // FakeSensorProvider::GetSensor() is invoked and handles the + // GetSensorCallback it receives. + DeleteContents(); + })); + set_fake_sensor_provider(std::move(intercepting_fake_sensor_provider)); + + mojo::Remote<device::mojom::SensorProvider> provider; + contents()->GetMainFrame()->GetSensorProvider( + provider.BindNewPipeAndPassReceiver()); + + base::RunLoop run_loop; + provider.set_disconnect_handler(run_loop.QuitClosure()); + provider->GetSensor(device::mojom::SensorType::ACCELEROMETER, + base::BindOnce([](device::mojom::SensorCreationResult, + device::mojom::SensorInitParamsPtr) { + ADD_FAILURE() + << "Reached GetSensor() callback unexpectedly"; + })); + run_loop.Run(); +} + +} // namespace content
diff --git a/content/browser/portal/portal.cc b/content/browser/portal/portal.cc index 6d61b6e6..9260c64 100644 --- a/content/browser/portal/portal.cc +++ b/content/browser/portal/portal.cc
@@ -353,6 +353,9 @@ owner_render_frame_host()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, kCrossOriginPostMessageError); + + devtools_instrumentation::DidRejectCrossOriginPortalMessage( + owner_render_frame_host()); return; } portal_contents_->GetMainFrame()->ForwardMessageFromHost( @@ -362,9 +365,12 @@ void Portal::PostMessageToHost(blink::TransferableMessage message) { DCHECK(GetPortalContents()); if (!IsSameOrigin()) { - portal_contents_->GetMainFrame()->AddMessageToConsole( + GetPortalContents()->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, kCrossOriginPostMessageError); + + devtools_instrumentation::DidRejectCrossOriginPortalMessage( + GetPortalContents()->GetMainFrame()); return; } client().ForwardMessageFromGuest(
diff --git a/content/browser/push_messaging/push_messaging_router.cc b/content/browser/push_messaging/push_messaging_router.cc index 87f49c4db..663861cb 100644 --- a/content/browser/push_messaging/push_messaging_router.cc +++ b/content/browser/push_messaging/push_messaging_router.cc
@@ -35,8 +35,7 @@ PushMessagingRouter::PushEventCallback deliver_message_callback, blink::mojom::PushEventStatus push_event_status) { DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - // Use PostTask() instead of RunOrPostTaskOnThread() to ensure the callback - // is called asynchronously. + // PostTask() to ensure the callback is called asynchronously. GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(deliver_message_callback), push_event_status)); @@ -109,12 +108,10 @@ service_worker_context->storage_partition() ->GetDevToolsBackgroundServicesContext()); - RunOrPostTaskOnThread( - FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), - base::BindOnce(&FindServiceWorkerRegistration, event_type, - std::move(service_worker_context), - std::move(devtools_context), url::Origin::Create(origin), - service_worker_registration_id, std::move(callback))); + FindServiceWorkerRegistration( + event_type, std::move(service_worker_context), + std::move(devtools_context), url::Origin::Create(origin), + service_worker_registration_id, std::move(callback)); } } // namespace
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 5669655e..30916df 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -683,7 +683,6 @@ size_t keep_alive_ref_count() const { return keep_alive_ref_count_; } size_t worker_ref_count() const { return worker_ref_count_; } - size_t shutdown_delay_ref_count() const { return shutdown_delay_ref_count_; } // Allows overriding the URLLoaderFactory creation via CreateURLLoaderFactory. // Passing a null callback will restore the default behavior.
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index bb52ccd..bc4ea94 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -1507,7 +1507,7 @@ return GetTextInputManager() && GetTextInputManager()->should_do_learning(); } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool RenderWidgetHostViewAura::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index 9020fa2..fc00a95 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -236,7 +236,7 @@ ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override;
diff --git a/content/browser/worker_host/shared_worker_host.cc b/content/browser/worker_host/shared_worker_host.cc index 447b3e4..750b1dd3 100644 --- a/content/browser/worker_host/shared_worker_host.cc +++ b/content/browser/worker_host/shared_worker_host.cc
@@ -320,13 +320,8 @@ // request endpoint was sent, it can be used, so add it to // ServiceWorkerObjectHost. if (service_worker_remote_object.is_valid()) { - RunOrPostTaskOnThread( - FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), - base::BindOnce( - &ServiceWorkerObjectHost::AddRemoteObjectPtrAndUpdateState, - controller_service_worker_object_host, - std::move(service_worker_remote_object), - service_worker_sent_state)); + controller_service_worker_object_host->AddRemoteObjectPtrAndUpdateState( + std::move(service_worker_remote_object), service_worker_sent_state); } // Monitor the lifetime of the worker.
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index bfe324c..11a8c77 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -83,7 +83,6 @@ "browser_ppapi_host.h", "browser_task_traits.cc", "browser_task_traits.h", - "browser_thread.cc", "browser_thread.h", "browser_url_handler.h", "browsing_data_filter_builder.h",
diff --git a/content/public/browser/browser_thread.cc b/content/public/browser/browser_thread.cc deleted file mode 100644 index db01160..0000000 --- a/content/public/browser/browser_thread.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/public/browser/browser_thread.h" - -#include <utility> - -#include "base/callback.h" -#include "base/location.h" -#include "content/public/browser/browser_task_traits.h" - -namespace content { - -void RunOrPostTaskOnThread(const base::Location& location, - BrowserThread::ID thread_id, - base::OnceClosure task) { - if (BrowserThread::CurrentlyOn(thread_id)) { - std::move(task).Run(); - return; - } - BrowserThread::GetTaskRunnerForThread(thread_id)->PostTask(location, - std::move(task)); -} - -} // namespace content
diff --git a/content/public/browser/browser_thread.h b/content/public/browser/browser_thread.h index 57a4486..d62fee9bf 100644 --- a/content/public/browser/browser_thread.h +++ b/content/public/browser/browser_thread.h
@@ -213,15 +213,6 @@ DISALLOW_COPY_AND_ASSIGN(BrowserThread); }; -// Runs |task| on the thread specified by |thread_id| if already on that thread, -// otherwise posts a task to that thread. -// -// This is intended to be a temporary helper function for the IO/UI thread -// simplification effort. -CONTENT_EXPORT void RunOrPostTaskOnThread(const base::Location& location, - BrowserThread::ID thread_id, - base::OnceClosure task); - } // namespace content #endif // CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_H_
diff --git a/content/public/browser/web_contents_media_capture_id.cc b/content/public/browser/web_contents_media_capture_id.cc index 349e54a..97b1197d 100644 --- a/content/public/browser/web_contents_media_capture_id.cc +++ b/content/public/browser/web_contents_media_capture_id.cc
@@ -11,7 +11,6 @@ #include "base/strings/string_util.h" namespace { -constexpr char kWebContentsCaptureScheme[] = "web-contents-media-stream://"; constexpr char kDisableLocalEchoFlag[] = "local_echo=false"; constexpr char kOptionStart = '?'; constexpr char kOptionSeparator = '&'; @@ -19,7 +18,7 @@ bool ExtractTabCaptureTarget(const std::string& device_id_param, int* render_process_id, int* main_render_frame_id) { - const std::string device_scheme = kWebContentsCaptureScheme; + const std::string device_scheme = content::kWebContentsCaptureScheme; if (!base::StartsWith(device_id_param, device_scheme, base::CompareCase::SENSITIVE)) return false; @@ -75,6 +74,8 @@ namespace content { +const char kWebContentsCaptureScheme[] = "web-contents-media-stream://"; + bool WebContentsMediaCaptureId::operator<( const WebContentsMediaCaptureId& other) const { return std::tie(render_process_id, main_render_frame_id, disable_local_echo) <
diff --git a/content/public/browser/web_contents_media_capture_id.h b/content/public/browser/web_contents_media_capture_id.h index ca79fb0e..7937cfb 100644 --- a/content/public/browser/web_contents_media_capture_id.h +++ b/content/public/browser/web_contents_media_capture_id.h
@@ -12,6 +12,8 @@ namespace content { +extern const char CONTENT_EXPORT kWebContentsCaptureScheme[]; + struct CONTENT_EXPORT WebContentsMediaCaptureId { public: WebContentsMediaCaptureId() = default;
diff --git a/content/public/test/service_worker_host_interceptor.cc b/content/public/test/service_worker_host_interceptor.cc index ff3fbf6..0efc6d2 100644 --- a/content/public/test/service_worker_host_interceptor.cc +++ b/content/public/test/service_worker_host_interceptor.cc
@@ -26,21 +26,13 @@ BrowserContext* browser_context, const GURL& scope, int* service_worker_process_id_out) { - base::RunLoop run_loop; + DCHECK_CURRENTLY_ON(BrowserThread::UI); scoped_refptr<ServiceWorkerContextWrapper> context = static_cast<ServiceWorkerContextWrapper*>( browser_context->GetDefaultStoragePartition() ->GetServiceWorkerContext()); - BrowserThread::ID run_done_thread; - bool is_known_thread = - BrowserThread::GetCurrentThreadIdentifier(&run_done_thread); - DCHECK(is_known_thread); - RunOrPostTaskOnThread( - FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), - base::BindOnce(&ServiceWorkerHostInterceptor:: - FindRegistrationOnServiceWorkerCoreThread, - base::Unretained(this), context, scope, run_done_thread, - run_loop.QuitClosure())); + base::RunLoop run_loop; + FindRegistration(context, scope, run_loop.QuitClosure()); run_loop.Run(); *service_worker_process_id_out = service_worker_process_id_; return status_; @@ -65,20 +57,17 @@ } } -void ServiceWorkerHostInterceptor::FindRegistrationOnServiceWorkerCoreThread( +void ServiceWorkerHostInterceptor::FindRegistration( scoped_refptr<ServiceWorkerContextWrapper> context, const GURL& scope, - BrowserThread::ID run_done_thread, base::OnceClosure done) { context->FindRegistrationForScope( scope, blink::StorageKey(url::Origin::Create(scope)), - base::BindOnce(&ServiceWorkerHostInterceptor:: - OnFoundRegistrationOnServiceWorkerCoreThread, - base::Unretained(this), run_done_thread, std::move(done))); + base::BindOnce(&ServiceWorkerHostInterceptor::OnFoundRegistration, + base::Unretained(this), std::move(done))); } -void ServiceWorkerHostInterceptor::OnFoundRegistrationOnServiceWorkerCoreThread( - BrowserThread::ID run_done_thread, +void ServiceWorkerHostInterceptor::OnFoundRegistration( base::OnceClosure done, blink::ServiceWorkerStatusCode status, scoped_refptr<ServiceWorkerRegistration> registration) { @@ -89,7 +78,7 @@ forwarding_interface_ = service_worker_version_->service_worker_host_receiver_for_testing() .SwapImplForTesting(this); - RunOrPostTaskOnThread(FROM_HERE, run_done_thread, std::move(done)); + std::move(done).Run(); } } // namespace content
diff --git a/content/public/test/service_worker_host_interceptor.h b/content/public/test/service_worker_host_interceptor.h index 3223846..654ea936 100644 --- a/content/public/test/service_worker_host_interceptor.h +++ b/content/public/test/service_worker_host_interceptor.h
@@ -61,14 +61,11 @@ const GURL& url, OpenPaymentHandlerWindowCallback callback) override; - void FindRegistrationOnServiceWorkerCoreThread( - scoped_refptr<ServiceWorkerContextWrapper> context, - const GURL& scope, - BrowserThread::ID run_done_thread, - base::OnceClosure done); + void FindRegistration(scoped_refptr<ServiceWorkerContextWrapper> context, + const GURL& scope, + base::OnceClosure done); - void OnFoundRegistrationOnServiceWorkerCoreThread( - BrowserThread::ID run_done_thread, + void OnFoundRegistration( base::OnceClosure done, blink::ServiceWorkerStatusCode status, scoped_refptr<ServiceWorkerRegistration> registration);
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 221c7dd..339ce58 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1960,6 +1960,7 @@ "../browser/file_system_access/file_system_access_manager_impl_unittest.cc", "../browser/file_system_access/file_system_chooser_unittest.cc", "../browser/font_access/font_access_manager_impl_unittest.cc", + "../browser/generic_sensor/sensor_provider_proxy_impl_unittest.cc", "../browser/geolocation/geolocation_service_impl_unittest.cc", "../browser/gpu/gpu_data_manager_impl_private_unittest.cc", "../browser/gpu/gpu_data_manager_testing_arrays_and_structs_autogen.h",
diff --git a/content/test/data/accessibility/mac/methods/title-expected-mac.txt b/content/test/data/accessibility/mac/methods/title-expected-mac.txt new file mode 100644 index 0000000..4a44355c --- /dev/null +++ b/content/test/data/accessibility/mac/methods/title-expected-mac.txt
@@ -0,0 +1 @@ +button.accessibilityTitle='Press Me'
diff --git a/content/test/data/accessibility/mac/methods/title.html b/content/test/data/accessibility/mac/methods/title.html new file mode 100644 index 0000000..8345d50b --- /dev/null +++ b/content/test/data/accessibility/mac/methods/title.html
@@ -0,0 +1,10 @@ +<!-- +@MAC-SCRIPT: + button.accessibilityTitle +--> +<!DOCTYPE html> +<html> +<body> +<button id="button">Press Me</button> +</body> +</html>
diff --git a/docs/enterprise/policy_pref_mapping_test.md b/docs/enterprise/policy_pref_mapping_test.md index d5fc2c3..2d91d25 100644 --- a/docs/enterprise/policy_pref_mapping_test.md +++ b/docs/enterprise/policy_pref_mapping_test.md
@@ -195,8 +195,8 @@ the policies set in `policies`) and the value is a dictionary with `scope` (possible values are [`user`, `machine`], defaults to `user`) and `source` (possible values are [`enterprise_default`, `command_line`, `cloud`, -`active_directory`, `local_account_override`, `platform`, `priority_cloud`, -`merged`, `cloud_from_ash`], defaults to `cloud`). +`active_directory`, `local_account_override`, `platform`, `merged`, +`cloud_from_ash`], defaults to `cloud`). Each `PolicyPrefMappingTest` can also have a `required_preprocessor_macros`, which defines a list of required preprocessor macros for the test to run. @@ -265,7 +265,7 @@ "policies_settings": { "${policy_name_1}": { "scope": string, // optional, one of [user, machine], defaults to "user" - "source": string, // optional, one of [enterprise_default, command_line, cloud, active_directory, local_account_override, platform, priority_cloud, merged, cloud_from_ash], defaults to "cloud" + "source": string, // optional, one of [enterprise_default, command_line, cloud, active_directory, local_account_override, platform, merged, cloud_from_ash], defaults to "cloud" }, ... // 0...N policies }, // optional
diff --git a/extensions/renderer/activity_log_converter_strategy.cc b/extensions/renderer/activity_log_converter_strategy.cc index c7ed62c..08089133 100644 --- a/extensions/renderer/activity_log_converter_strategy.cc +++ b/extensions/renderer/activity_log_converter_strategy.cc
@@ -7,7 +7,13 @@ #include <memory> #include "base/values.h" -#include "v8/include/v8.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-value.h" namespace extensions {
diff --git a/extensions/renderer/activity_log_converter_strategy.h b/extensions/renderer/activity_log_converter_strategy.h index b5d7e7fd..9944305 100644 --- a/extensions/renderer/activity_log_converter_strategy.h +++ b/extensions/renderer/activity_log_converter_strategy.h
@@ -8,7 +8,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "content/public/renderer/v8_value_converter.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/api_activity_logger.cc b/extensions/renderer/api_activity_logger.cc index 22b23f3..da55e93 100644 --- a/extensions/renderer/api_activity_logger.cc +++ b/extensions/renderer/api_activity_logger.cc
@@ -19,6 +19,10 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/worker_script_context_set.h" #include "extensions/renderer/worker_thread_util.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/api_activity_logger.h b/extensions/renderer/api_activity_logger.h index 084acf1..9f1975bc 100644 --- a/extensions/renderer/api_activity_logger.h +++ b/extensions/renderer/api_activity_logger.h
@@ -12,7 +12,7 @@ #include "base/macros.h" #include "extensions/renderer/ipc_message_sender.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace base { class ListValue;
diff --git a/extensions/renderer/api_definitions_natives.cc b/extensions/renderer/api_definitions_natives.cc index 8ce5032..59bf97a6 100644 --- a/extensions/renderer/api_definitions_natives.cc +++ b/extensions/renderer/api_definitions_natives.cc
@@ -9,6 +9,8 @@ #include "extensions/common/features/feature_provider.h" #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/script_context.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-function-callback.h" namespace extensions {
diff --git a/extensions/renderer/api_definitions_natives.h b/extensions/renderer/api_definitions_natives.h index c5084bf..d40b60f 100644 --- a/extensions/renderer/api_definitions_natives.h +++ b/extensions/renderer/api_definitions_natives.h
@@ -7,7 +7,7 @@ #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class Dispatcher;
diff --git a/extensions/renderer/app_window_custom_bindings.cc b/extensions/renderer/app_window_custom_bindings.cc index ed2658a3..5b17c71 100644 --- a/extensions/renderer/app_window_custom_bindings.cc +++ b/extensions/renderer/app_window_custom_bindings.cc
@@ -18,7 +18,10 @@ #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_view.h" #include "ui/base/resource/resource_bundle.h" -#include "v8/include/v8.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/app_window_custom_bindings.h b/extensions/renderer/app_window_custom_bindings.h index c595938..13d4b69 100644 --- a/extensions/renderer/app_window_custom_bindings.h +++ b/extensions/renderer/app_window_custom_bindings.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/binding_generating_native_handler.cc b/extensions/renderer/binding_generating_native_handler.cc index 2561cda..7f59b31 100644 --- a/extensions/renderer/binding_generating_native_handler.cc +++ b/extensions/renderer/binding_generating_native_handler.cc
@@ -10,6 +10,9 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/v8_helpers.h" #include "gin/data_object_builder.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-microtask-queue.h" namespace extensions {
diff --git a/extensions/renderer/binding_generating_native_handler.h b/extensions/renderer/binding_generating_native_handler.h index b49f81d..798be65d 100644 --- a/extensions/renderer/binding_generating_native_handler.h +++ b/extensions/renderer/binding_generating_native_handler.h
@@ -9,6 +9,7 @@ #include "base/compiler_specific.h" #include "extensions/renderer/native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/blob_native_handler.cc b/extensions/renderer/blob_native_handler.cc index a13bf061..2bcbca4 100644 --- a/extensions/renderer/blob_native_handler.cc +++ b/extensions/renderer/blob_native_handler.cc
@@ -8,6 +8,8 @@ #include "extensions/renderer/script_context.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/web/web_blob.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-primitive.h" namespace {
diff --git a/extensions/renderer/blob_native_handler.h b/extensions/renderer/blob_native_handler.h index 342a9f35..0886d49 100644 --- a/extensions/renderer/blob_native_handler.h +++ b/extensions/renderer/blob_native_handler.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_RENDERER_BLOB_NATIVE_HANDLER_H_ #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/chrome_setting.cc b/extensions/renderer/chrome_setting.cc index c12edc5..e49f1bf4 100644 --- a/extensions/renderer/chrome_setting.cc +++ b/extensions/renderer/chrome_setting.cc
@@ -16,6 +16,7 @@ #include "gin/arguments.h" #include "gin/handle.h" #include "gin/object_template_builder.h" +#include "v8/include/v8-object.h" namespace extensions {
diff --git a/extensions/renderer/chrome_setting.h b/extensions/renderer/chrome_setting.h index 28d1898..0fd097d 100644 --- a/extensions/renderer/chrome_setting.h +++ b/extensions/renderer/chrome_setting.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "extensions/renderer/bindings/argument_spec.h" #include "gin/wrappable.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace base { class DictionaryValue;
diff --git a/extensions/renderer/console.cc b/extensions/renderer/console.cc index 5f61b506..413c065 100644 --- a/extensions/renderer/console.cc +++ b/extensions/renderer/console.cc
@@ -18,6 +18,9 @@ #include "gin/converter.h" #include "gin/per_isolate_data.h" #include "third_party/blink/public/web/web_console_message.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" namespace extensions { namespace console {
diff --git a/extensions/renderer/console.h b/extensions/renderer/console.h index b62bc1dd..4dec549e 100644 --- a/extensions/renderer/console.h +++ b/extensions/renderer/console.h
@@ -8,7 +8,7 @@ #include <string> #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/content_setting.cc b/extensions/renderer/content_setting.cc index f8e8b4f..ec87f989 100644 --- a/extensions/renderer/content_setting.cc +++ b/extensions/renderer/content_setting.cc
@@ -22,6 +22,7 @@ #include "gin/handle.h" #include "gin/object_template_builder.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" +#include "v8/include/v8-object.h" namespace extensions {
diff --git a/extensions/renderer/content_setting.h b/extensions/renderer/content_setting.h index 4769adfa9..b15b22b8 100644 --- a/extensions/renderer/content_setting.h +++ b/extensions/renderer/content_setting.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "extensions/renderer/bindings/argument_spec.h" #include "gin/wrappable.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace base { class DictionaryValue;
diff --git a/extensions/renderer/declarative_content_hooks_delegate.cc b/extensions/renderer/declarative_content_hooks_delegate.cc index 7ee6948b..2b9e213 100644 --- a/extensions/renderer/declarative_content_hooks_delegate.cc +++ b/extensions/renderer/declarative_content_hooks_delegate.cc
@@ -13,6 +13,16 @@ #include "gin/converter.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_selector.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-external.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" +#include "v8/include/v8-value.h" namespace extensions {
diff --git a/extensions/renderer/declarative_content_hooks_delegate.h b/extensions/renderer/declarative_content_hooks_delegate.h index 47a8528..85eefa5 100644 --- a/extensions/renderer/declarative_content_hooks_delegate.h +++ b/extensions/renderer/declarative_content_hooks_delegate.h
@@ -12,7 +12,7 @@ #include "base/callback.h" #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class APITypeReferenceMap;
diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index 9a32f5e0..ecbf692 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc
@@ -115,7 +115,10 @@ #include "third_party/blink/public/web/web_view.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" using blink::WebDocument; using blink::WebSecurityPolicy;
diff --git a/extensions/renderer/dispatcher.h b/extensions/renderer/dispatcher.h index 233089b..b891943 100644 --- a/extensions/renderer/dispatcher.h +++ b/extensions/renderer/dispatcher.h
@@ -36,7 +36,7 @@ #include "extensions/renderer/v8_schema_registry.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "third_party/blink/public/platform/web_string.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" class ChromeRenderViewTest; class GURL;
diff --git a/extensions/renderer/dom_activity_logger.cc b/extensions/renderer/dom_activity_logger.cc index 4a11f168..38d62764 100644 --- a/extensions/renderer/dom_activity_logger.cc +++ b/extensions/renderer/dom_activity_logger.cc
@@ -14,6 +14,7 @@ #include "extensions/renderer/activity_log_converter_strategy.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" +#include "v8/include/v8-isolate.h" using blink::WebString; using blink::WebURL;
diff --git a/extensions/renderer/dom_activity_logger.h b/extensions/renderer/dom_activity_logger.h index 0c232593..0727e5a 100644 --- a/extensions/renderer/dom_activity_logger.h +++ b/extensions/renderer/dom_activity_logger.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "extensions/common/dom_action_types.h" #include "third_party/blink/public/web/web_dom_activity_logger.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace base { class ListValue;
diff --git a/extensions/renderer/dom_hooks_delegate.cc b/extensions/renderer/dom_hooks_delegate.cc index 72c3005..bca89c9 100644 --- a/extensions/renderer/dom_hooks_delegate.cc +++ b/extensions/renderer/dom_hooks_delegate.cc
@@ -10,6 +10,8 @@ #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/script_context.h" #include "third_party/blink/public/web/web_element.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/dom_hooks_delegate.h b/extensions/renderer/dom_hooks_delegate.h index de7245fc..5b917cd 100644 --- a/extensions/renderer/dom_hooks_delegate.h +++ b/extensions/renderer/dom_hooks_delegate.h
@@ -8,7 +8,7 @@ #include <string> #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/extension_frame_helper.cc b/extensions/renderer/extension_frame_helper.cc index 599c20c..9abb420e 100644 --- a/extensions/renderer/extension_frame_helper.cc +++ b/extensions/renderer/extension_frame_helper.cc
@@ -34,6 +34,11 @@ #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_settings.h" #include "third_party/blink/public/web/web_view.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/extension_frame_helper.h b/extensions/renderer/extension_frame_helper.h index 24e7e14..018d648 100644 --- a/extensions/renderer/extension_frame_helper.h +++ b/extensions/renderer/extension_frame_helper.h
@@ -20,7 +20,7 @@ #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" struct ExtensionMsg_ExternalConnectionInfo; struct ExtensionMsg_TabConnectionInfo;
diff --git a/extensions/renderer/extension_interaction_provider.h b/extensions/renderer/extension_interaction_provider.h index 8ddd6db..59b931bb 100644 --- a/extensions/renderer/extension_interaction_provider.h +++ b/extensions/renderer/extension_interaction_provider.h
@@ -8,7 +8,7 @@ #include "extensions/renderer/bindings/interaction_provider.h" #include "base/macros.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/extension_js_runner.cc b/extensions/renderer/extension_js_runner.cc index 7d3adf4..1fa10a9f 100644 --- a/extensions/renderer/extension_js_runner.cc +++ b/extensions/renderer/extension_js_runner.cc
@@ -9,6 +9,9 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_injection_callback.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-microtask-queue.h" namespace extensions {
diff --git a/extensions/renderer/extension_js_runner.h b/extensions/renderer/extension_js_runner.h index 3af099f..7bc27eb 100644 --- a/extensions/renderer/extension_js_runner.h +++ b/extensions/renderer/extension_js_runner.h
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "extensions/renderer/bindings/js_runner.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/file_system_natives.cc b/extensions/renderer/file_system_natives.cc index 8a549f7..a761474 100644 --- a/extensions/renderer/file_system_natives.cc +++ b/extensions/renderer/file_system_natives.cc
@@ -16,6 +16,8 @@ #include "third_party/blink/public/web/web_dom_file_system.h" #include "third_party/blink/public/web/web_local_frame.h" #include "url/origin.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/file_system_natives.h b/extensions/renderer/file_system_natives.h index 4cec86a9..06b81e0 100644 --- a/extensions/renderer/file_system_natives.h +++ b/extensions/renderer/file_system_natives.h
@@ -8,6 +8,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/gc_callback.h b/extensions/renderer/gc_callback.h index 1d6bd55..6c3e6117 100644 --- a/extensions/renderer/gc_callback.h +++ b/extensions/renderer/gc_callback.h
@@ -10,7 +10,8 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-persistent-handle.h" namespace extensions {
diff --git a/extensions/renderer/get_script_context.h b/extensions/renderer/get_script_context.h index 2dd8e9d4..dfe265a 100644 --- a/extensions/renderer/get_script_context.h +++ b/extensions/renderer/get_script_context.h
@@ -5,7 +5,7 @@ #ifndef EXTENSIONS_RENDERER_GET_SCRIPT_CONTEXT_H_ #define EXTENSIONS_RENDERER_GET_SCRIPT_CONTEXT_H_ -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/gin_port.cc b/extensions/renderer/gin_port.cc index f658468e..a7dd9a0 100644 --- a/extensions/renderer/gin_port.cc +++ b/extensions/renderer/gin_port.cc
@@ -16,6 +16,9 @@ #include "gin/arguments.h" #include "gin/converter.h" #include "gin/object_template_builder.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/gin_port.h b/extensions/renderer/gin_port.h index 9282d6b..77a4af1 100644 --- a/extensions/renderer/gin_port.h +++ b/extensions/renderer/gin_port.h
@@ -14,7 +14,7 @@ #include "extensions/renderer/bindings/api_binding_util.h" #include "gin/wrappable.h" #include "third_party/abseil-cpp/absl/types/optional.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace gin { class Arguments;
diff --git a/extensions/renderer/i18n_hooks_delegate.cc b/extensions/renderer/i18n_hooks_delegate.cc index 3831af1..87e8892 100644 --- a/extensions/renderer/i18n_hooks_delegate.cc +++ b/extensions/renderer/i18n_hooks_delegate.cc
@@ -22,6 +22,12 @@ #include "gin/converter.h" #include "gin/data_object_builder.h" #include "third_party/cld_3/src/src/nnet_language_identifier.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/i18n_hooks_delegate.h b/extensions/renderer/i18n_hooks_delegate.h index 376c2b2..4b6e6093 100644 --- a/extensions/renderer/i18n_hooks_delegate.h +++ b/extensions/renderer/i18n_hooks_delegate.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/id_generator_custom_bindings.cc b/extensions/renderer/id_generator_custom_bindings.cc index af8070f..341978d 100644 --- a/extensions/renderer/id_generator_custom_bindings.cc +++ b/extensions/renderer/id_generator_custom_bindings.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/callback.h" +#include "v8/include/v8-function-callback.h" namespace extensions {
diff --git a/extensions/renderer/id_generator_custom_bindings.h b/extensions/renderer/id_generator_custom_bindings.h index cbe4520..b67d7483 100644 --- a/extensions/renderer/id_generator_custom_bindings.h +++ b/extensions/renderer/id_generator_custom_bindings.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_RENDERER_ID_GENERATOR_CUSTOM_BINDINGS_H_ #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/lazy_background_page_native_handler.h b/extensions/renderer/lazy_background_page_native_handler.h index 30dfd863..ccb5b4b 100644 --- a/extensions/renderer/lazy_background_page_native_handler.h +++ b/extensions/renderer/lazy_background_page_native_handler.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_RENDERER_LAZY_BACKGROUND_PAGE_NATIVE_HANDLER_H_ #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/logging_native_handler.cc b/extensions/renderer/logging_native_handler.cc index 9fe7eb5b..06755d5 100644 --- a/extensions/renderer/logging_native_handler.cc +++ b/extensions/renderer/logging_native_handler.cc
@@ -7,6 +7,8 @@ #include "base/bind.h" #include "base/logging.h" #include "extensions/renderer/script_context.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/logging_native_handler.h b/extensions/renderer/logging_native_handler.h index 499170c..2438bc75 100644 --- a/extensions/renderer/logging_native_handler.h +++ b/extensions/renderer/logging_native_handler.h
@@ -8,6 +8,7 @@ #include <string> #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/messaging_bindings.cc b/extensions/renderer/messaging_bindings.cc index 8f21fb2e..3f08aa9 100644 --- a/extensions/renderer/messaging_bindings.cc +++ b/extensions/renderer/messaging_bindings.cc
@@ -11,7 +11,9 @@ #include "base/callback_helpers.h" #include "extensions/renderer/gc_callback.h" #include "extensions/renderer/script_context.h" -#include "v8/include/v8.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-object.h" namespace extensions {
diff --git a/extensions/renderer/messaging_bindings.h b/extensions/renderer/messaging_bindings.h index 8d1657a..79d73e6 100644 --- a/extensions/renderer/messaging_bindings.h +++ b/extensions/renderer/messaging_bindings.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/messaging_util.cc b/extensions/renderer/messaging_util.cc index f6bf874..7b21012 100644 --- a/extensions/renderer/messaging_util.cc +++ b/extensions/renderer/messaging_util.cc
@@ -20,6 +20,11 @@ #include "gin/converter.h" #include "gin/dictionary.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-json.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions { namespace messaging_util {
diff --git a/extensions/renderer/messaging_util.h b/extensions/renderer/messaging_util.h index 7a381b4..8c30d8d0 100644 --- a/extensions/renderer/messaging_util.h +++ b/extensions/renderer/messaging_util.h
@@ -8,7 +8,7 @@ #include <memory> #include <string> -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace blink { class WebLocalFrame;
diff --git a/extensions/renderer/module_system.cc b/extensions/renderer/module_system.cc index f86145c..1255b81 100644 --- a/extensions/renderer/module_system.cc +++ b/extensions/renderer/module_system.cc
@@ -25,6 +25,15 @@ #include "gin/converter.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_v8_features.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-external.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-message.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-script.h" namespace extensions {
diff --git a/extensions/renderer/module_system.h b/extensions/renderer/module_system.h index 34bc4cd..4aee5ce 100644 --- a/extensions/renderer/module_system.h +++ b/extensions/renderer/module_system.h
@@ -17,7 +17,9 @@ #include "extensions/renderer/native_handler.h" #include "extensions/renderer/object_backed_native_handler.h" #include "extensions/renderer/script_injection_callback.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-persistent-handle.h" namespace extensions {
diff --git a/extensions/renderer/module_system_test.cc b/extensions/renderer/module_system_test.cc index 67d9e0c4..19a9515d 100644 --- a/extensions/renderer/module_system_test.cc +++ b/extensions/renderer/module_system_test.cc
@@ -34,6 +34,13 @@ #include "extensions/renderer/utils_native_handler.h" #include "gin/converter.h" #include "ui/base/resource/resource_bundle.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-microtask-queue.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-statistics.h" namespace extensions { namespace {
diff --git a/extensions/renderer/module_system_test.h b/extensions/renderer/module_system_test.h index 223a758..1045856 100644 --- a/extensions/renderer/module_system_test.h +++ b/extensions/renderer/module_system_test.h
@@ -16,7 +16,7 @@ #include "extensions/renderer/test_extensions_renderer_client.h" #include "gin/public/context_holder.h" #include "testing/gtest/include/gtest/gtest.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class Extension;
diff --git a/extensions/renderer/native_extension_bindings_system.cc b/extensions/renderer/native_extension_bindings_system.cc index 15196ca4..9ce46f6c 100644 --- a/extensions/renderer/native_extension_bindings_system.cc +++ b/extensions/renderer/native_extension_bindings_system.cc
@@ -55,6 +55,11 @@ #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_origin_trials.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" namespace extensions {
diff --git a/extensions/renderer/native_extension_bindings_system.h b/extensions/renderer/native_extension_bindings_system.h index 4a92997f..0b4503b 100644 --- a/extensions/renderer/native_extension_bindings_system.h +++ b/extensions/renderer/native_extension_bindings_system.h
@@ -14,7 +14,8 @@ #include "extensions/renderer/bindings/event_emitter.h" #include "extensions/renderer/feature_cache.h" #include "extensions/renderer/native_renderer_messaging_service.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-persistent-handle.h" namespace extensions { class IPCMessageSender;
diff --git a/extensions/renderer/native_extension_bindings_system_test_base.h b/extensions/renderer/native_extension_bindings_system_test_base.h index c017cc2d..4848667 100644 --- a/extensions/renderer/native_extension_bindings_system_test_base.h +++ b/extensions/renderer/native_extension_bindings_system_test_base.h
@@ -23,6 +23,7 @@ #include "extensions/renderer/test_extensions_renderer_client.h" #include "mojo/public/cpp/bindings/struct_ptr.h" #include "testing/gmock/include/gmock/gmock.h" +#include "v8/include/v8-forward.h" struct ExtensionHostMsg_APIActionOrEvent_Params;
diff --git a/extensions/renderer/native_handler.h b/extensions/renderer/native_handler.h index 601040b5..8429f43 100644 --- a/extensions/renderer/native_handler.h +++ b/extensions/renderer/native_handler.h
@@ -6,7 +6,7 @@ #define EXTENSIONS_RENDERER_NATIVE_HANDLER_H_ #include "base/macros.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/native_renderer_messaging_service.cc b/extensions/renderer/native_renderer_messaging_service.cc index 99928664..b79c49844 100644 --- a/extensions/renderer/native_renderer_messaging_service.cc +++ b/extensions/renderer/native_renderer_messaging_service.cc
@@ -41,7 +41,8 @@ #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_scoped_window_focus_allowed_indicator.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-persistent-handle.h" using blink::mojom::UserActivationNotificationType;
diff --git a/extensions/renderer/native_renderer_messaging_service.h b/extensions/renderer/native_renderer_messaging_service.h index 22c4bf28..cfdbee8 100644 --- a/extensions/renderer/native_renderer_messaging_service.h +++ b/extensions/renderer/native_renderer_messaging_service.h
@@ -12,6 +12,7 @@ #include "extensions/renderer/gin_port.h" #include "extensions/renderer/one_time_message_handler.h" #include "gin/handle.h" +#include "v8/include/v8-forward.h" struct ExtensionMsg_ExternalConnectionInfo; struct ExtensionMsg_TabConnectionInfo;
diff --git a/extensions/renderer/object_backed_native_handler.cc b/extensions/renderer/object_backed_native_handler.cc index c403df5..9655d82 100644 --- a/extensions/renderer/object_backed_native_handler.cc +++ b/extensions/renderer/object_backed_native_handler.cc
@@ -16,7 +16,14 @@ #include "extensions/renderer/script_context_set.h" #include "extensions/renderer/v8_helpers.h" #include "third_party/blink/public/web/web_local_frame.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-external.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" +#include "v8/include/v8-value.h" namespace extensions {
diff --git a/extensions/renderer/object_backed_native_handler.h b/extensions/renderer/object_backed_native_handler.h index e59cb0e..2f7c4ad 100644 --- a/extensions/renderer/object_backed_native_handler.h +++ b/extensions/renderer/object_backed_native_handler.h
@@ -11,8 +11,8 @@ #include "base/bind.h" #include "base/macros.h" #include "extensions/renderer/native_handler.h" +#include "v8/include/v8-forward.h" #include "v8/include/v8-util.h" -#include "v8/include/v8.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/one_time_message_handler.cc b/extensions/renderer/one_time_message_handler.cc index 32950b5..7bd539b7 100644 --- a/extensions/renderer/one_time_message_handler.cc +++ b/extensions/renderer/one_time_message_handler.cc
@@ -29,6 +29,15 @@ #include "gin/handle.h" #include "gin/per_context_data.h" #include "ipc/ipc_message.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-external.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-persistent-handle.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/one_time_message_handler.h b/extensions/renderer/one_time_message_handler.h index ef4166e..355f99b 100644 --- a/extensions/renderer/one_time_message_handler.h +++ b/extensions/renderer/one_time_message_handler.h
@@ -9,7 +9,7 @@ #include <string> #include "base/memory/weak_ptr.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace gin { class Arguments;
diff --git a/extensions/renderer/render_frame_observer_natives.cc b/extensions/renderer/render_frame_observer_natives.cc index 9a1aef60..f4b14db 100644 --- a/extensions/renderer/render_frame_observer_natives.cc +++ b/extensions/renderer/render_frame_observer_natives.cc
@@ -16,6 +16,9 @@ #include "content/public/renderer/render_frame_observer.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/script_context.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/render_frame_observer_natives.h b/extensions/renderer/render_frame_observer_natives.h index 6ef6ed0c..9991fc7 100644 --- a/extensions/renderer/render_frame_observer_natives.h +++ b/extensions/renderer/render_frame_observer_natives.h
@@ -8,6 +8,8 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-persistent-handle.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/resource_bundle_source_map.cc b/extensions/renderer/resource_bundle_source_map.cc index b81b628..103c9597 100644 --- a/extensions/renderer/resource_bundle_source_map.cc +++ b/extensions/renderer/resource_bundle_source_map.cc
@@ -10,6 +10,7 @@ #include "extensions/renderer/static_v8_external_one_byte_string_resource.h" #include "third_party/zlib/google/compression_utils.h" #include "ui/base/resource/resource_bundle.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/resource_bundle_source_map.h b/extensions/renderer/resource_bundle_source_map.h index a66f40f8..4e368c5 100644 --- a/extensions/renderer/resource_bundle_source_map.h +++ b/extensions/renderer/resource_bundle_source_map.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "extensions/renderer/source_map.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace ui { class ResourceBundle;
diff --git a/extensions/renderer/runtime_custom_bindings.cc b/extensions/renderer/runtime_custom_bindings.cc index dffa571..b1e51f6 100644 --- a/extensions/renderer/runtime_custom_bindings.cc +++ b/extensions/renderer/runtime_custom_bindings.cc
@@ -14,6 +14,9 @@ #include "extensions/common/view_type_util.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/script_context.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/runtime_custom_bindings.h b/extensions/renderer/runtime_custom_bindings.h index f1ecd0b..69f45b8 100644 --- a/extensions/renderer/runtime_custom_bindings.h +++ b/extensions/renderer/runtime_custom_bindings.h
@@ -7,7 +7,7 @@ #include "base/compiler_specific.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/runtime_hooks_delegate.cc b/extensions/renderer/runtime_hooks_delegate.cc index d82805b..b75d29e 100644 --- a/extensions/renderer/runtime_hooks_delegate.cc +++ b/extensions/renderer/runtime_hooks_delegate.cc
@@ -24,6 +24,12 @@ #include "extensions/renderer/script_context.h" #include "gin/converter.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" namespace extensions {
diff --git a/extensions/renderer/runtime_hooks_delegate.h b/extensions/renderer/runtime_hooks_delegate.h index dd60ae0..3101e8b6 100644 --- a/extensions/renderer/runtime_hooks_delegate.h +++ b/extensions/renderer/runtime_hooks_delegate.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class NativeRendererMessagingService;
diff --git a/extensions/renderer/safe_builtins.cc b/extensions/renderer/safe_builtins.cc index 86d8795..3cd525bc 100644 --- a/extensions/renderer/safe_builtins.cc +++ b/extensions/renderer/safe_builtins.cc
@@ -9,6 +9,16 @@ #include "base/strings/stringprintf.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/v8_helpers.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-extension.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-microtask-queue.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive-object.h" +#include "v8/include/v8-primitive.h" +#include "v8/include/v8-template.h" namespace extensions {
diff --git a/extensions/renderer/safe_builtins.h b/extensions/renderer/safe_builtins.h index 0cf6ea8..928d499e 100644 --- a/extensions/renderer/safe_builtins.h +++ b/extensions/renderer/safe_builtins.h
@@ -8,7 +8,7 @@ #include <memory> #include "base/macros.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/script_context.cc b/extensions/renderer/script_context.cc index 6ffc155..0a22a51 100644 --- a/extensions/renderer/script_context.cc +++ b/extensions/renderer/script_context.cc
@@ -29,7 +29,12 @@ #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_document_loader.h" #include "third_party/blink/public/web/web_local_frame.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-debug.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-microtask-queue.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/script_context.h b/extensions/renderer/script_context.h index d9353882..2d93cc90 100644 --- a/extensions/renderer/script_context.h +++ b/extensions/renderer/script_context.h
@@ -23,7 +23,10 @@ #include "extensions/renderer/safe_builtins.h" #include "extensions/renderer/script_injection_callback.h" #include "url/gurl.h" -#include "v8/include/v8.h" +#include "v8-exception.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-script.h" namespace blink { class WebDocumentLoader;
diff --git a/extensions/renderer/script_context_set.cc b/extensions/renderer/script_context_set.cc index 31390cf3..13d9557 100644 --- a/extensions/renderer/script_context_set.cc +++ b/extensions/renderer/script_context_set.cc
@@ -17,7 +17,8 @@ #include "third_party/blink/public/web/blink.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" -#include "v8/include/v8.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" namespace extensions {
diff --git a/extensions/renderer/script_context_set.h b/extensions/renderer/script_context_set.h index 50e5e38..00bb0fe 100644 --- a/extensions/renderer/script_context_set.h +++ b/extensions/renderer/script_context_set.h
@@ -18,8 +18,7 @@ #include "extensions/renderer/renderer_extension_registry.h" #include "extensions/renderer/script_context_set_iterable.h" #include "url/gurl.h" -#include "v8/include/v8.h" - +#include "v8/include/v8-forward.h" class GURL; namespace blink {
diff --git a/extensions/renderer/script_injection.h b/extensions/renderer/script_injection.h index ac8aee7..c5a5d6f 100644 --- a/extensions/renderer/script_injection.h +++ b/extensions/renderer/script_injection.h
@@ -20,16 +20,12 @@ #include "extensions/renderer/script_injector.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "v8/include/v8-forward.h" namespace content { class RenderFrame; } -namespace v8 { -class Value; -template <class T> class Local; -} - namespace extensions { struct ScriptsRunInfo;
diff --git a/extensions/renderer/script_injection_callback.h b/extensions/renderer/script_injection_callback.h index b71c5d84..ded433d6 100644 --- a/extensions/renderer/script_injection_callback.h +++ b/extensions/renderer/script_injection_callback.h
@@ -10,7 +10,7 @@ #include "base/callback.h" #include "base/macros.h" #include "third_party/blink/public/web/web_script_execution_callback.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/set_icon_natives.cc b/extensions/renderer/set_icon_natives.cc index 7af1f5f..ccc5f13 100644 --- a/extensions/renderer/set_icon_natives.cc +++ b/extensions/renderer/set_icon_natives.cc
@@ -18,6 +18,12 @@ #include "skia/public/mojom/bitmap.mojom.h" #include "third_party/blink/public/web/web_array_buffer_converter.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" // TODO(devlin): Looks like there are lots of opportunities to use gin helpers // like gin::Dictionary and gin::DataObjectBuilder here.
diff --git a/extensions/renderer/set_icon_natives.h b/extensions/renderer/set_icon_natives.h index 7d17f15d..70c5cd435 100644 --- a/extensions/renderer/set_icon_natives.h +++ b/extensions/renderer/set_icon_natives.h
@@ -7,7 +7,7 @@ #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/source_map.h b/extensions/renderer/source_map.h index 6833181..f4e8dd1 100644 --- a/extensions/renderer/source_map.h +++ b/extensions/renderer/source_map.h
@@ -7,7 +7,7 @@ #include <string> -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/static_v8_external_one_byte_string_resource.h b/extensions/renderer/static_v8_external_one_byte_string_resource.h index 3f569585..1dde15a 100644 --- a/extensions/renderer/static_v8_external_one_byte_string_resource.h +++ b/extensions/renderer/static_v8_external_one_byte_string_resource.h
@@ -9,7 +9,7 @@ #include "base/compiler_specific.h" #include "base/strings/string_piece.h" -#include "v8/include/v8.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/storage_area.cc b/extensions/renderer/storage_area.cc index 2da46247..89ff6c8 100644 --- a/extensions/renderer/storage_area.cc +++ b/extensions/renderer/storage_area.cc
@@ -17,6 +17,8 @@ #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/storage_area.h b/extensions/renderer/storage_area.h index 1b10d7e..6d27b42 100644 --- a/extensions/renderer/storage_area.h +++ b/extensions/renderer/storage_area.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "base/strings/string_piece.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace base { class ListValue;
diff --git a/extensions/renderer/string_source_map.h b/extensions/renderer/string_source_map.h index c3b6857..d70c13f 100644 --- a/extensions/renderer/string_source_map.h +++ b/extensions/renderer/string_source_map.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "extensions/renderer/source_map.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/test_native_handler.cc b/extensions/renderer/test_native_handler.cc index 0df3eab..12c896d 100644 --- a/extensions/renderer/test_native_handler.cc +++ b/extensions/renderer/test_native_handler.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "extensions/renderer/wake_event_page.h" +#include "v8/include/v8-function.h" namespace extensions {
diff --git a/extensions/renderer/test_native_handler.h b/extensions/renderer/test_native_handler.h index 86d18d2..8460f56d 100644 --- a/extensions/renderer/test_native_handler.h +++ b/extensions/renderer/test_native_handler.h
@@ -8,7 +8,8 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" +#include "v8/include/v8-function-callback.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/test_v8_extension_configuration.cc b/extensions/renderer/test_v8_extension_configuration.cc index 6123a86..879ae80 100644 --- a/extensions/renderer/test_v8_extension_configuration.cc +++ b/extensions/renderer/test_v8_extension_configuration.cc
@@ -9,7 +9,8 @@ #include "base/lazy_instance.h" #include "extensions/renderer/safe_builtins.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-extension.h" namespace extensions {
diff --git a/extensions/renderer/user_gestures_native_handler.cc b/extensions/renderer/user_gestures_native_handler.cc index 88e04ca..407879a50 100644 --- a/extensions/renderer/user_gestures_native_handler.cc +++ b/extensions/renderer/user_gestures_native_handler.cc
@@ -9,6 +9,9 @@ #include "extensions/renderer/script_context.h" #include "third_party/blink/public/mojom/frame/user_activation_notification_type.mojom.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/user_gestures_native_handler.h b/extensions/renderer/user_gestures_native_handler.h index b9209b7..148bc5b 100644 --- a/extensions/renderer/user_gestures_native_handler.h +++ b/extensions/renderer/user_gestures_native_handler.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_RENDERER_USER_GESTURES_NATIVE_HANDLER_H_ #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/utils_native_handler.h b/extensions/renderer/utils_native_handler.h index 9045560..54de921 100644 --- a/extensions/renderer/utils_native_handler.h +++ b/extensions/renderer/utils_native_handler.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions { class ScriptContext;
diff --git a/extensions/renderer/v8_context_native_handler.cc b/extensions/renderer/v8_context_native_handler.cc index ac3b850..c0a39b6b 100644 --- a/extensions/renderer/v8_context_native_handler.cc +++ b/extensions/renderer/v8_context_native_handler.cc
@@ -9,6 +9,9 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_context_set.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/v8_context_native_handler.h b/extensions/renderer/v8_context_native_handler.h index 1a519d7..2d256423 100644 --- a/extensions/renderer/v8_context_native_handler.h +++ b/extensions/renderer/v8_context_native_handler.h
@@ -6,6 +6,7 @@ #define EXTENSIONS_RENDERER_V8_CONTEXT_NATIVE_HANDLER_H_ #include "extensions/renderer/object_backed_native_handler.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/v8_helpers.h b/extensions/renderer/v8_helpers.h index e9ced93d..8fd8c04 100644 --- a/extensions/renderer/v8_helpers.h +++ b/extensions/renderer/v8_helpers.h
@@ -9,7 +9,9 @@ #include <string.h> #include "base/strings/string_number_conversions.h" -#include "v8/include/v8.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-primitive.h" namespace extensions { namespace v8_helpers {
diff --git a/extensions/renderer/v8_schema_registry.cc b/extensions/renderer/v8_schema_registry.cc index 843c92e..59cc2fc8 100644 --- a/extensions/renderer/v8_schema_registry.cc +++ b/extensions/renderer/v8_schema_registry.cc
@@ -18,6 +18,13 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/static_v8_external_one_byte_string_resource.h" #include "extensions/renderer/v8_helpers.h" +#include "v8/include/v8-container.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-function-callback.h" +#include "v8/include/v8-isolate.h" +#include "v8/include/v8-json.h" +#include "v8/include/v8-object.h" +#include "v8/include/v8-value.h" using content::V8ValueConverter;
diff --git a/extensions/renderer/v8_schema_registry.h b/extensions/renderer/v8_schema_registry.h index 6ccdf63..0dc624cb 100644 --- a/extensions/renderer/v8_schema_registry.h +++ b/extensions/renderer/v8_schema_registry.h
@@ -12,8 +12,8 @@ #include "base/macros.h" #include "gin/public/context_holder.h" +#include "v8/include/v8-forward.h" #include "v8/include/v8-util.h" -#include "v8/include/v8.h" namespace extensions { class NativeHandler;
diff --git a/extensions/renderer/wake_event_page.cc b/extensions/renderer/wake_event_page.cc index e108dea..a685cc6f 100644 --- a/extensions/renderer/wake_event_page.cc +++ b/extensions/renderer/wake_event_page.cc
@@ -21,6 +21,10 @@ #include "extensions/renderer/v8_helpers.h" #include "ipc/ipc_message.h" #include "ipc/ipc_message_macros.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-persistent-handle.h" +#include "v8/include/v8-primitive.h" namespace extensions {
diff --git a/extensions/renderer/wake_event_page.h b/extensions/renderer/wake_event_page.h index 5d6de04e..85c1d4fb8 100644 --- a/extensions/renderer/wake_event_page.h +++ b/extensions/renderer/wake_event_page.h
@@ -16,7 +16,7 @@ #include "base/synchronization/lock.h" #include "content/public/renderer/render_thread_observer.h" #include "ipc/ipc_sync_message_filter.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace content { class RenderThread;
diff --git a/extensions/renderer/web_request_hooks.cc b/extensions/renderer/web_request_hooks.cc index 7c9bbd4..90bdc55 100644 --- a/extensions/renderer/web_request_hooks.cc +++ b/extensions/renderer/web_request_hooks.cc
@@ -16,6 +16,10 @@ #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_context_set.h" #include "gin/converter.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-exception.h" +#include "v8/include/v8-function.h" +#include "v8/include/v8-object.h" namespace extensions {
diff --git a/extensions/renderer/web_request_hooks.h b/extensions/renderer/web_request_hooks.h index afe55e3..c90bd2f 100644 --- a/extensions/renderer/web_request_hooks.h +++ b/extensions/renderer/web_request_hooks.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/extensions/renderer/worker_script_context_set.cc b/extensions/renderer/worker_script_context_set.cc index 06aaee27..4a3e237 100644 --- a/extensions/renderer/worker_script_context_set.cc +++ b/extensions/renderer/worker_script_context_set.cc
@@ -10,6 +10,7 @@ #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/worker_thread_util.h" +#include "v8/include/v8-context.h" namespace extensions {
diff --git a/extensions/renderer/worker_script_context_set.h b/extensions/renderer/worker_script_context_set.h index e73b360..ec51ab5d 100644 --- a/extensions/renderer/worker_script_context_set.h +++ b/extensions/renderer/worker_script_context_set.h
@@ -14,7 +14,7 @@ #include "content/public/renderer/worker_thread.h" #include "extensions/renderer/script_context_set_iterable.h" #include "url/gurl.h" -#include "v8/include/v8.h" +#include "v8/include/v8-forward.h" namespace extensions {
diff --git a/fuchsia/base/mem_buffer_util.h b/fuchsia/base/mem_buffer_util.h index 04d7598..a567024 100644 --- a/fuchsia/base/mem_buffer_util.h +++ b/fuchsia/base/mem_buffer_util.h
@@ -12,6 +12,9 @@ #include "base/files/file.h" #include "base/strings/utf_string_conversions.h" +// These functions are deprecated. New code should use the definitions in +// base/fuchsia/mem_buffer_util.h; see https://crbug.com/1120731. + namespace cr_fuchsia { // TODO(crbug.com/1156780): Replace bool returns with absl::optional.
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_raw_draw.cc b/gpu/command_buffer/service/shared_image_backing_factory_raw_draw.cc index 27383e53..4912941 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_raw_draw.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_raw_draw.cc
@@ -432,7 +432,7 @@ return false; } - if (!is_pixel_used) { + if (is_pixel_used) { return false; }
diff --git a/gpu/config/gpu_finch_features.cc b/gpu/config/gpu_finch_features.cc index 66369c4..d4b99fe3 100644 --- a/gpu/config/gpu_finch_features.cc +++ b/gpu/config/gpu_finch_features.cc
@@ -210,7 +210,7 @@ const base::Feature kWebGPUService{"WebGPUService", base::FEATURE_DISABLED_BY_DEFAULT}; // Enable raw draw for tiles. -const base::Feature kRawDraw{"RawDraw", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kRawDraw{"RawDraw", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_ANDROID)
diff --git a/ios/chrome/browser/BUILD.gn b/ios/chrome/browser/BUILD.gn index 7545e7d..9b6954d2 100644 --- a/ios/chrome/browser/BUILD.gn +++ b/ios/chrome/browser/BUILD.gn
@@ -193,6 +193,7 @@ "//components/component_updater", "//components/content_settings/core/browser", "//components/content_settings/core/common", + "//components/crash/core/common:crash_key_lib", "//components/crash/core/common:reporter_running_ios", "//components/flags_ui", "//components/gcm_driver",
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc index a31a5e6..637a120a 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc +++ b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc
@@ -17,7 +17,6 @@ #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" -#include "components/password_manager/core/browser/password_store.h" #include "components/prefs/pref_service.h" #include "components/signin/ios/browser/active_state_manager.h" #include "components/signin/public/identity_manager/identity_manager.h"
diff --git a/ios/chrome/browser/browsing_data/browsing_data_counter_wrapper.cc b/ios/chrome/browser/browsing_data/browsing_data_counter_wrapper.cc index 7c6e27cf..c6c584b 100644 --- a/ios/chrome/browser/browsing_data/browsing_data_counter_wrapper.cc +++ b/ios/chrome/browser/browsing_data/browsing_data_counter_wrapper.cc
@@ -13,7 +13,7 @@ #include "components/browsing_data/core/counters/passwords_counter.h" #include "components/browsing_data/core/pref_names.h" #include "components/keyed_service/core/service_access_type.h" -#include "components/password_manager/core/browser/password_store.h" +#include "components/password_manager/core/browser/password_store_interface.h" #include "components/prefs/pref_service.h" #include "components/sync/driver/sync_service.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" @@ -47,7 +47,7 @@ if (pref_name == browsing_data::prefs::kDeletePasswords) { return std::make_unique<browsing_data::PasswordsCounter>( - IOSChromePasswordStoreFactory::GetForBrowserState( + IOSChromePasswordStoreFactory::GetInterfaceForBrowserState( browser_state, ServiceAccessType::EXPLICIT_ACCESS), /*account_store=*/nullptr, SyncServiceFactory::GetForBrowserState(browser_state));
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index b82c416..aad6fafd 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -212,35 +212,6 @@ base::size(kDefaultBrowserFullscreenPromoExperimentRemindMeLater), nullptr}}; -const FeatureEntry::FeatureParam - kDefaultPromoNonModalShortTimeoutWithInstructions[] = { - {kDefaultPromoNonModalTimeoutParam, "15"}, - {kDefaultPromoNonModalInstructionsParam, "true"}}; -const FeatureEntry::FeatureParam - kDefaultPromoNonModalLongTimeoutWithInstructions[] = { - {kDefaultPromoNonModalTimeoutParam, "45"}, - {kDefaultPromoNonModalInstructionsParam, "true"}}; -const FeatureEntry::FeatureParam - kDefaultPromoNonModalShortTimeoutWithoutInstructions[] = { - {kDefaultPromoNonModalTimeoutParam, "15"}}; -const FeatureEntry::FeatureParam - kDefaultPromoNonModalLongTimeoutWithoutInstructions[] = { - {kDefaultPromoNonModalTimeoutParam, "45"}}; -const FeatureEntry::FeatureVariation kDefaultPromoNonModalVariations[] = { - {"Short timeout, with instructions", - kDefaultPromoNonModalShortTimeoutWithInstructions, - base::size(kDefaultPromoNonModalShortTimeoutWithInstructions), nullptr}, - {"Long timeout, with instructions", - kDefaultPromoNonModalLongTimeoutWithInstructions, - base::size(kDefaultPromoNonModalLongTimeoutWithInstructions), nullptr}, - {"Short timeout, without instructions", - kDefaultPromoNonModalShortTimeoutWithoutInstructions, - base::size(kDefaultPromoNonModalShortTimeoutWithoutInstructions), nullptr}, - {"Long timeout, without instructions", - kDefaultPromoNonModalLongTimeoutWithoutInstructions, - base::size(kDefaultPromoNonModalLongTimeoutWithoutInstructions), nullptr}, -}; - const FeatureEntry::FeatureParam kDiscoverFeedInNtpEnableNativeUI[] = { {kDiscoverFeedIsNativeUIEnabled, "true"}}; const FeatureEntry::FeatureVariation kDiscoverFeedInNtpVariations[] = { @@ -641,13 +612,6 @@ flags_ui::kOsIos, FEATURE_VALUE_TYPE( password_manager::features::kFillingAcrossAffiliatedWebsites)}, - {"default-browser-promo-non-modal", - flag_descriptions::kDefaultPromoNonModalName, - flag_descriptions::kDefaultPromoNonModalDescription, flags_ui::kOsIos, - FEATURE_WITH_PARAMS_VALUE_TYPE( - kDefaultPromoNonModal, - kDefaultPromoNonModalVariations, - "IOSDefaultBrowserNonModalPromoExperiment")}, {"autofill-parse-merchant-promo-code-fields", flag_descriptions::kAutofillParseMerchantPromoCodeFieldsName, flag_descriptions::kAutofillParseMerchantPromoCodeFieldsDescription, @@ -757,13 +721,13 @@ flag_descriptions::kSendTabToSelfManageDevicesLinkDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(send_tab_to_self::kSendTabToSelfManageDevicesLink)}, - { - "new-overflow-menu", - flag_descriptions::kNewOverflowMenuName, - flag_descriptions::kNewOverflowMenuDescription, - flags_ui::kOsIos, - FEATURE_VALUE_TYPE(kNewOverflowMenu), - }}; + {"new-overflow-menu", flag_descriptions::kNewOverflowMenuName, + flag_descriptions::kNewOverflowMenuDescription, flags_ui::kOsIos, + FEATURE_VALUE_TYPE(kNewOverflowMenu)}, + {"enable-new-download-api", flag_descriptions::kEnableNewDownloadAPIName, + flag_descriptions::kEnableNewDownloadAPIDescription, flags_ui::kOsIos, + FEATURE_VALUE_TYPE(web::features::kEnableNewDownloadAPI)}, +}; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) { return false;
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index 31f0e98c..4eb2e35 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -99,10 +99,6 @@ "rather than crashing. If enabled, DCHECKs will crash the calling process."; #endif // defined(DCHECK_IS_CONFIGURABLE) -const char kDefaultPromoNonModalName[] = "Default Browser Non-Modal Promo"; -const char kDefaultPromoNonModalDescription[] = - "When enabled non-modal default browser promos can be triggered."; - const char kUseDefaultUserAgentInWebClientName[] = "[Refactoring] Let the client choose default mode"; const char kUseDefaultUserAgentInWebClientDescription[] = @@ -489,6 +485,10 @@ const char kWalletServiceUseSandboxDescription[] = "Uses the sandbox service for Google Payments API calls."; +const char kEnableNewDownloadAPIName[] = "Enable new download API"; +const char kEnableNewDownloadAPIDescription[] = + "Enable new download API (restricted to iOS 15.0+)."; + const char kWebPageDefaultZoomFromDynamicTypeName[] = "Use dynamic type size for default text zoom level"; const char kWebPageDefaultZoomFromDynamicTypeDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index eedcd6b..310d01e 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -92,10 +92,6 @@ extern const char kDcheckIsFatalDescription[]; #endif // defined(DCHECK_IS_CONFIGURABLE) -// Title and description for the flag to show non modal default browser promos. -extern const char kDefaultPromoNonModalName[]; -extern const char kDefaultPromoNonModalDescription[]; - // Title and description for the flag to have the web client choosing the // default user agent. extern const char kUseDefaultUserAgentInWebClientName[]; @@ -425,6 +421,10 @@ extern const char kWalletServiceUseSandboxName[]; extern const char kWalletServiceUseSandboxDescription[]; +// Title and description for the flag to enable the new download API. +extern const char kEnableNewDownloadAPIName[]; +extern const char kEnableNewDownloadAPIDescription[]; + // Title and description for the flag to tie the default text zoom level to // the dynamic type setting. extern const char kWebPageDefaultZoomFromDynamicTypeName[];
diff --git a/ios/chrome/browser/ios_chrome_main_parts.mm b/ios/chrome/browser/ios_chrome_main_parts.mm index 66769ce..d82bee5 100644 --- a/ios/chrome/browser/ios_chrome_main_parts.mm +++ b/ios/chrome/browser/ios_chrome_main_parts.mm
@@ -21,6 +21,7 @@ #include "base/time/default_tick_clock.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/crash/core/common/crash_key.h" #include "components/crash/core/common/reporter_running_ios.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "components/heap_profiling/in_process/heap_profiler_controller.h" @@ -174,10 +175,10 @@ DCHECK_EQ(application_context_.get(), GetApplicationContext()); // Check the first run state early; this must be done before IO is disallowed - // so that later calls can use the cached value. (The return value is ignored - // because this is only to trigger the internal lookup and caching for later - // use.) - FirstRun::IsChromeFirstRun(); + // so that later calls can use the cached value. + static crash_reporter::CrashKeyString<4> key("first-run"); + if (FirstRun::IsChromeFirstRun()) + key.Set("yes"); // Convert freeform experimental settings into switches before initializing // local state, in case any of the settings affect policy.
diff --git a/ios/chrome/browser/reading_list/reading_list_download_service.cc b/ios/chrome/browser/reading_list/reading_list_download_service.cc index 1637a70b..19e7c800 100644 --- a/ios/chrome/browser/reading_list/reading_list_download_service.cc +++ b/ios/chrome/browser/reading_list/reading_list_download_service.cc
@@ -285,10 +285,11 @@ STATUS_MAX); break; } - case URLDownloader::ERROR: { + case URLDownloader::ERROR: + case URLDownloader::PERMANENT_ERROR: { const ReadingListEntry* entry = reading_list_model_->GetEntryByURL(url); // Add this failure to the total failure count. - if (entry && + if (entry && real_success_value == URLDownloader::ERROR && entry->FailedDownloadCounter() + 1 < kNumberOfFailsBeforeStop) { reading_list_model_->SetEntryDistilledState( url, ReadingListEntry::WILL_RETRY);
diff --git a/ios/chrome/browser/reading_list/url_downloader.cc b/ios/chrome/browser/reading_list/url_downloader.cc index 8326814..fb549d1 100644 --- a/ios/chrome/browser/reading_list/url_downloader.cc +++ b/ios/chrome/browser/reading_list/url_downloader.cc
@@ -14,6 +14,7 @@ #include "base/files/file_util.h" #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -58,6 +59,17 @@ " }" "}, false);" "</script>"; + +// The maximum size for the distilled page. +// Note that the sum of the size of the resources will be used for this check, +// so the total size of the page after processing can be slightly more than +// this. +const int kMaximumTotalPageSize = 10 * 1024 * 1024; + +// The maximum size for a single raw image. If a bigger image is found, the +// page distillation is canceled (page will only be available online). +const int kMaximumImageSize = 1024 * 1024; + } // namespace // URLDownloader @@ -317,6 +329,22 @@ const std::vector<dom_distiller::DistillerViewerInterface::ImageInfo>& images, const std::string& html) { + int total_size = html.size(); + for (size_t i = 0; i < images.size(); i++) { + if (images[i].data.size() > kMaximumImageSize) { + UMA_HISTOGRAM_MEMORY_KB("IOS.ReadingList.ImageTooLargeFailure", + images[i].data.size() / 1024); + return PERMANENT_ERROR; + } + // Image will be base64 encoded. + total_size += 4 * images[i].data.size() / 3; + } + if (total_size > kMaximumTotalPageSize) { + UMA_HISTOGRAM_MEMORY_KB("IOS.ReadingList.PageTooLargeFailure", + total_size / 1024); + return PERMANENT_ERROR; + } + if (CreateOfflineURLDirectory(url)) { return SaveHTMLForURL(ReplaceImagesInHTML(url, html, images), url) ? DOWNLOAD_SUCCESS
diff --git a/ios/chrome/browser/reading_list/url_downloader.h b/ios/chrome/browser/reading_list/url_downloader.h index 4266ef3..c26000a 100644 --- a/ios/chrome/browser/reading_list/url_downloader.h +++ b/ios/chrome/browser/reading_list/url_downloader.h
@@ -53,6 +53,9 @@ // The URL could not be downloaded because of an error. Client may want to // try again later. ERROR, + // The URL could not be downloaded because of an error. Client should not + // try again. + PERMANENT_ERROR, }; // A completion callback that takes a GURL and a bool indicating the
diff --git a/ios/chrome/browser/safe_browsing/safe_browsing_query_manager.mm b/ios/chrome/browser/safe_browsing/safe_browsing_query_manager.mm index e6d9d3b..a498a0c 100644 --- a/ios/chrome/browser/safe_browsing/safe_browsing_query_manager.mm +++ b/ios/chrome/browser/safe_browsing/safe_browsing_query_manager.mm
@@ -78,18 +78,19 @@ const UnsafeResource& resource) { bool is_main_frame = resource.request_destination == network::mojom::RequestDestination::kDocument; - auto it = std::find_if(results_.begin(), results_.end(), - [&resource, &is_main_frame](const auto& pair) { - return pair.first.url == resource.url && - is_main_frame == pair.first.IsMainFrame() && - !pair.second.resource; - }); - if (it == results_.end()) - return; - - UnsafeResource resource_copy = resource; - resource_copy.callback = base::DoNothing(); - it->second.resource = resource; + // Responses to repeated queries can arrive in arbitrary order, not + // necessarily in the same order as the queries are made. This means + // that when there are repeated pending queries (e.g., when a page has + // multiple iframes with the same URL), it is not possible to determine + // which of these queries will receive a response first. As a result, + // |resource| must be stored with every corresponding query, not just the + // first. + for (auto& pair : results_) { + if (pair.first.url == resource.url && + is_main_frame == pair.first.IsMainFrame() && !pair.second.resource) { + pair.second.resource = resource; + } + } } #pragma mark Private
diff --git a/ios/chrome/browser/safe_browsing/safe_browsing_query_manager_unittest.mm b/ios/chrome/browser/safe_browsing/safe_browsing_query_manager_unittest.mm index 4ba9bf0..12a2097 100644 --- a/ios/chrome/browser/safe_browsing/safe_browsing_query_manager_unittest.mm +++ b/ios/chrome/browser/safe_browsing/safe_browsing_query_manager_unittest.mm
@@ -159,6 +159,31 @@ base::RunLoop().RunUntilIdle(); } +// Tests that StoreUnsafeResource associates the UnsafeResource with all +// queries that match the UnsafeResource's URL. +TEST_P(SafeBrowsingQueryManagerTest, StoreUnsafeResourceMultipleQueries) { + GURL url("http://" + FakeSafeBrowsingService::kUnsafeHost); + EXPECT_CALL(observer_, SafeBrowsingQueryFinished(manager(), _, _)) + .Times(2) + .WillRepeatedly(VerifyQueryFinished(url, http_method_, + navigation_item_id_, + /*is_url_safe=*/false)); + + // Start two URL check queries for the unsafe URL and run the runloop until + // the results are received. Only call StoreUnsafeResource once, rather than + // once for each query. + manager()->StartQuery( + SafeBrowsingQueryManager::Query(url, http_method_, navigation_item_id_)); + manager()->StartQuery( + SafeBrowsingQueryManager::Query(url, http_method_, navigation_item_id_)); + UnsafeResource resource; + resource.url = url; + resource.threat_type = safe_browsing::SB_THREAT_TYPE_URL_PHISHING; + resource.request_destination = GetParam(); + manager()->StoreUnsafeResource(resource); + base::RunLoop().RunUntilIdle(); +} + // Tests observer callbacks for manager destruction. TEST_P(SafeBrowsingQueryManagerTest, ManagerDestruction) { web_state_ = nullptr;
diff --git a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_egtest.mm b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_egtest.mm index 261a401..5c6da52 100644 --- a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_egtest.mm +++ b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_egtest.mm
@@ -58,12 +58,6 @@ @implementation NonModalEGTest -- (AppLaunchConfiguration)appConfigurationForTestCase { - AppLaunchConfiguration config; - config.features_enabled.push_back(kDefaultPromoNonModal); - return config; -} - - (void)setUp { [super setUp]; [ChromeEarlGreyAppInterface clearDefaultBrowserPromoData];
diff --git a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler.mm b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler.mm index 31955bdf..d61590d 100644 --- a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler.mm +++ b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler.mm
@@ -39,6 +39,9 @@ // Number of times to show the promo to a user. const int kPromoShownTimesLimit = 2; +// Timeout before the promo is dismissed. +const double kPromoTimeout = 45; + bool PromoCanBeDisplayed() { return !IsChromeLikelyDefaultBrowser() && !UserInPromoCooldown() && UserInteractionWithNonModalPromoCount() < kPromoShownTimesLimit; @@ -191,17 +194,10 @@ self.promoShownTime = base::TimeTicks(); LogUserInteractionWithNonModalPromo(); - if (NonModalPromosInstructionsEnabled()) { - id<ApplicationSettingsCommands> handler = - HandlerForProtocol(self.dispatcher, ApplicationSettingsCommands); - [handler showDefaultBrowserSettingsFromViewController:nil]; - } else { - NSURL* settingsURL = - [NSURL URLWithString:UIApplicationOpenSettingsURLString]; - [[UIApplication sharedApplication] openURL:settingsURL - options:{} - completionHandler:nil]; - } + NSURL* settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; + [[UIApplication sharedApplication] openURL:settingsURL + options:@{} + completionHandler:nil]; } - (void)logUserDismissedPromo { @@ -404,8 +400,7 @@ __weak __typeof(self) weakSelf = self; _dismissPromoTimer = std::make_unique<base::OneShotTimer>(); _dismissPromoTimer->Start( - FROM_HERE, base::TimeDelta::FromSeconds(NonModalPromosTimeout()), - base::BindOnce(^{ + FROM_HERE, base::TimeDelta::FromSeconds(kPromoTimeout), base::BindOnce(^{ [weakSelf dismissPromoTimerFinished]; })); }
diff --git a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler_unittest.mm b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler_unittest.mm index 3f334da..369512fa 100644 --- a/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler_unittest.mm +++ b/ios/chrome/browser/ui/default_promo/default_browser_promo_non_modal_scheduler_unittest.mm
@@ -48,13 +48,6 @@ DefaultBrowserPromoNonModalSchedulerTest() : web_state_list_(&web_state_list_delegate_) {} void SetUp() override { - // Turn on instructions because that is easier to unittest. - const std::map<std::string, std::string> feature_params = { - {"instructions_enabled", "true"}, - }; - feature_list_.InitAndEnableFeatureWithParameters(kDefaultPromoNonModal, - feature_params); - TestChromeBrowserState::Builder test_cbs_builder; std::unique_ptr<TestChromeBrowserState> chrome_browser_state = test_cbs_builder.Build(); @@ -88,7 +81,16 @@ scheduler_ = [[DefaultBrowserPromoNonModalScheduler alloc] init]; scheduler_.browser = browser_.get(); scheduler_.dispatcher = browser_->GetCommandDispatcher(); + + // Stub application so the settings panel doesn't actually open. + application_ = OCMClassMock([UIApplication class]); + OCMStub([application_ sharedApplication]).andReturn(application_); } + + ~DefaultBrowserPromoNonModalSchedulerTest() override { + [application_ stopMocking]; + } + void TearDown() override { ClearUserDefaults(); OverlayPresenter::FromBrowser(browser_.get(), @@ -119,6 +121,7 @@ FakeOverlayPresentationContext overlay_presentation_context_; id promo_commands_handler_; DefaultBrowserPromoNonModalScheduler* scheduler_; + id application_ = nil; }; // Tests that the omnibox paste event triggers the promo to show. @@ -221,7 +224,7 @@ // promo. [[promo_commands_handler_ expect] dismissDefaultBrowserNonModalPromoAnimated:YES]; - task_env_.FastForwardBy(base::TimeDelta::FromSeconds(15)); + task_env_.FastForwardBy(base::TimeDelta::FromSeconds(60)); [promo_commands_handler_ verify]; // Check that NSUserDefaults has been updated. @@ -248,15 +251,13 @@ [promo_commands_handler_ verify]; - id settings_commands_handler = - OCMStrictProtocolMock(@protocol(ApplicationSettingsCommands)); - [browser_->GetCommandDispatcher() - startDispatchingToTarget:settings_commands_handler - forProtocol:@protocol(ApplicationSettingsCommands)]; - [[settings_commands_handler expect] - showDefaultBrowserSettingsFromViewController:nil]; + [[application_ expect] + openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] + options:@{} + completionHandler:nil]; [scheduler_ logUserPerformedPromoAction]; - [settings_commands_handler verify]; + + [application_ verify]; // Check that NSUserDefaults has been updated. EXPECT_EQ(UserInteractionWithNonModalPromoCount(), 1);
diff --git a/ios/chrome/browser/ui/default_promo/default_browser_utils.h b/ios/chrome/browser/ui/default_promo/default_browser_utils.h index 636994e..69c8816 100644 --- a/ios/chrome/browser/ui/default_promo/default_browser_utils.h +++ b/ios/chrome/browser/ui/default_promo/default_browser_utils.h
@@ -36,12 +36,6 @@ // The feature parameter to activate the remind me later button. extern const char kDefaultBrowserFullscreenPromoExperimentRemindMeGroupParam[]; -// Indicates the timeout duration for the non-modal promo. -extern const char kDefaultPromoNonModalTimeoutParam[]; - -// Indicates if the instructions for the non-modal promo are enabled. -extern const char kDefaultPromoNonModalInstructionsParam[]; - // Logs the timestamp of user activity that is deemed to be an indication of // a user that would likely benefit from having Chrome set as their default // browser. Before logging the current activity, this method will also clear all @@ -73,12 +67,6 @@ // Returns true if non modals default browser promos are enabled. bool NonModalPromosEnabled(); -// Returns the timeout for non modals. -double NonModalPromosTimeout(); - -// Returns true if instructions for non modals should be shown. -bool NonModalPromosInstructionsEnabled(); - // Returns true if the user has interacted with the Fullscreen Promo previously. // Returns false otherwise. bool HasUserInteractedWithFullscreenPromoBefore();
diff --git a/ios/chrome/browser/ui/default_promo/default_browser_utils.mm b/ios/chrome/browser/ui/default_promo/default_browser_utils.mm index eaae900a..5002275 100644 --- a/ios/chrome/browser/ui/default_promo/default_browser_utils.mm +++ b/ios/chrome/browser/ui/default_promo/default_browser_utils.mm
@@ -133,10 +133,6 @@ NSString* const kLastHTTPURLOpenTime = @"lastHTTPURLOpenTime"; -const char kDefaultPromoNonModalTimeoutParam[] = "timeout"; - -const char kDefaultPromoNonModalInstructionsParam[] = "instructions_enabled"; - const char kDefaultBrowserFullscreenPromoExperimentRemindMeGroupParam[] = "show_remind_me_later"; @@ -192,18 +188,7 @@ bool NonModalPromosEnabled() { // Default browser isn't enabled until iOS 14.0.1, regardless of flag state. - return base::ios::IsRunningOnOrLater(14, 0, 1) && - base::FeatureList::IsEnabled(kDefaultPromoNonModal); -} - -double NonModalPromosTimeout() { - return base::GetFieldTrialParamByFeatureAsDouble( - kDefaultPromoNonModal, kDefaultPromoNonModalTimeoutParam, 15); -} - -bool NonModalPromosInstructionsEnabled() { - return base::GetFieldTrialParamByFeatureAsBool( - kDefaultPromoNonModal, kDefaultPromoNonModalInstructionsParam, false); + return base::ios::IsRunningOnOrLater(14, 0, 1); } bool HasUserInteractedWithFullscreenPromoBefore() {
diff --git a/ios/chrome/browser/ui/settings/language/BUILD.gn b/ios/chrome/browser/ui/settings/language/BUILD.gn index c3a2d28..09b5c57c 100644 --- a/ios/chrome/browser/ui/settings/language/BUILD.gn +++ b/ios/chrome/browser/ui/settings/language/BUILD.gn
@@ -42,6 +42,7 @@ "language_settings_table_view_controller.mm", ] deps = [ + "//components/password_manager/core/common", "//components/prefs", "//components/translate/core/browser:translate_pref_names", "//ios/chrome/app/strings:ios_strings_grit",
diff --git a/ios/chrome/browser/ui/settings/language/language_settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/language/language_settings_table_view_controller.mm index a42e7b5..3ae9857e 100644 --- a/ios/chrome/browser/ui/settings/language/language_settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/language/language_settings_table_view_controller.mm
@@ -10,6 +10,7 @@ #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/notreached.h" +#include "components/password_manager/core/common/password_manager_features.h" #include "components/prefs/pref_service.h" #include "components/translate/core/browser/translate_pref_names.h" #include "ios/chrome/browser/application_context.h" @@ -111,7 +112,13 @@ [super viewDidLoad]; self.title = l10n_util::GetNSString(IDS_IOS_LANGUAGE_SETTINGS_TITLE); - self.shouldHideDoneButton = YES; + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + self.shouldDisableDoneButtonOnEdit = YES; + self.shouldShowDeleteButtonInToolbar = NO; + } else { + self.shouldHideDoneButton = YES; + } self.tableView.accessibilityIdentifier = kLanguageSettingsTableViewAccessibilityIdentifier; @@ -119,6 +126,14 @@ [self updateUIForEditState]; } +- (void)viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + self.navigationController.toolbarHidden = NO; + } +} + #pragma mark - ChromeTableViewController - (void)loadModel { @@ -169,7 +184,8 @@ #pragma mark - SettingsRootTableViewController - (BOOL)shouldShowEditButton { - return YES; + return !base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings); } - (BOOL)editButtonEnabled { @@ -177,6 +193,16 @@ sectionIdentifier:SectionIdentifierLanguages]; } +- (BOOL)shouldHideToolbar { + return !base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings); +} + +- (BOOL)shouldShowEditDoneButton { + return !base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings); +} + - (void)updateUIForEditState { [super updateUIForEditState]; @@ -190,11 +216,20 @@ if (_translateSwitchItem) { [self setTranslateSwitchItemEnabled:!self.isEditing]; } + + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + [self updatedToolbarForEditState]; + } } #pragma mark - SettingsControllerProtocol - (void)reportDismissalUserAction { + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + return; + } // Language Settings screen does not have Done button. NOTREACHED(); }
diff --git a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm index 17a6ec60..116039c 100644 --- a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm
@@ -11,6 +11,7 @@ #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/sys_string_conversions.h" +#include "components/password_manager/core/common/password_manager_features.h" #include "components/search_engines/template_url_service.h" #include "components/search_engines/template_url_service_observer.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" @@ -93,6 +94,10 @@ _faviconLoader = IOSChromeFaviconLoaderFactory::GetForBrowserState(browserState); [self setTitle:l10n_util::GetNSString(IDS_IOS_SEARCH_ENGINE_SETTING_TITLE)]; + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + self.shouldDisableDoneButtonOnEdit = YES; + } [self updateUIForEditState]; } return self; @@ -175,6 +180,14 @@ [self loadModel]; } +- (void)viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + self.navigationController.toolbarHidden = NO; + } +} + - (void)setEditing:(BOOL)editing animated:(BOOL)animated { if (editing) { base::RecordAction( @@ -247,11 +260,21 @@ // Hide toolbar for non-editing mode or when no items are selected. - (BOOL)shouldHideToolbar { + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + return NO; + } return !self.editing || self.tableView.indexPathsForSelectedRows.count == 0; } - (BOOL)shouldShowEditButton { - return YES; + return !base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings); +} + +- (BOOL)shouldShowEditDoneButton { + return !base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings); } - (BOOL)editButtonEnabled { @@ -261,6 +284,14 @@ sectionIdentifier:SectionIdentifierSecondList]; } +- (void)updateUIForEditState { + [super updateUIForEditState]; + if (base::FeatureList::IsEnabled( + password_manager::features::kSupportForAddPasswordsInSettings)) { + [self updatedToolbarForEditState]; + } +} + #pragma mark - UITableViewDelegate - (void)tableView:(UITableView*)tableView @@ -269,6 +300,7 @@ // Keep selection in editing mode. if (self.editing) { + self.deleteButton.enabled = YES; return; } @@ -340,6 +372,16 @@ self.updatingBackend = NO; } +- (void)tableView:(UITableView*)tableView + didDeselectRowAtIndexPath:(NSIndexPath*)indexPath { + [super tableView:tableView didDeselectRowAtIndexPath:indexPath]; + if (!self.tableView.editing) + return; + + if (self.tableView.indexPathsForSelectedRows.count == 0) + self.deleteButton.enabled = NO; +} + #pragma mark - UITableViewDataSource - (UITableViewCell*)tableView:(UITableView*)tableView
diff --git a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h index 9c2818c..af4d1e5 100644 --- a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h +++ b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h
@@ -37,6 +37,10 @@ // toolbar(bottom left). Default is NO. @property(nonatomic, assign) BOOL shouldShowAddButtonInToolbar; +// Whether this table view controller should show the "Delete" button in the +// toolbar(bottom left). Default is YES. Set in |viewDidLoad|. +@property(nonatomic, assign) BOOL shouldShowDeleteButtonInToolbar; + // Updates the edit or done button to reflect editing state. If the // tableView is not in edit mode (and thus showing the 'Done' button) it is // using shouldHideDoneButton to know if it should display the edit button.
diff --git a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm index c413764..84b3878 100644 --- a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm
@@ -108,7 +108,7 @@ action:nil]; UIBarButtonItem* toolbarLeftButton = nil; - if (self.tableView.editing) { + if (self.tableView.editing && self.shouldShowDeleteButtonInToolbar) { toolbarLeftButton = self.deleteButton; } else if (self.shouldShowAddButtonInToolbar) { toolbarLeftButton = self.addButtonInToolbar; @@ -192,6 +192,7 @@ UINavigationItemLargeTitleDisplayModeNever; self.backButtonItem = self.navigationItem.leftBarButtonItem; + self.shouldShowDeleteButtonInToolbar = YES; } - (void)viewWillAppear:(BOOL)animated {
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm index a71b18d2..cadcdcc 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm
@@ -683,9 +683,9 @@ self.leadingEdgeNavigationEnabled = YES; // If the next page is an NTP, enable trailing edge swipe. - std::vector<web::NavigationItem*> fordwardItems = + std::vector<web::NavigationItem*> forwardItems = webState->GetNavigationManager()->GetForwardItems(); - if (fordwardItems.size() > 0 && UseNativeSwipe(fordwardItems[0])) + if (forwardItems.size() > 0 && UseNativeSwipe(forwardItems[0])) self.trailingEdgeNavigationEnabled = YES; }
diff --git a/ios/chrome/browser/ui/ui_feature_flags.cc b/ios/chrome/browser/ui/ui_feature_flags.cc index 71ba4e5..c495bd2 100644 --- a/ios/chrome/browser/ui/ui_feature_flags.cc +++ b/ios/chrome/browser/ui/ui_feature_flags.cc
@@ -43,9 +43,6 @@ "DefaultBrowserFullscreenPromoExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kDefaultPromoNonModal{"DefaultPromoNonModal", - base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kIOSNewOmniboxImplementation{ "kIOSNewOmniboxImplementation", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/ui/ui_feature_flags.h b/ios/chrome/browser/ui/ui_feature_flags.h index ccc08036..7c5da3f 100644 --- a/ios/chrome/browser/ui/ui_feature_flags.h +++ b/ios/chrome/browser/ui/ui_feature_flags.h
@@ -48,9 +48,6 @@ // Feature flag that experiments with the default browser fullscreen promo UI. extern const base::Feature kDefaultBrowserFullscreenPromoExperiment; -// Feature flag that enables non-modal default browser promos. -extern const base::Feature kDefaultPromoNonModal; - // Feature flag that swaps the omnibox textfield implementation. extern const base::Feature kIOSNewOmniboxImplementation;
diff --git a/ios/web/common/features.h b/ios/web/common/features.h index 3c227eda..0428153 100644 --- a/ios/web/common/features.h +++ b/ios/web/common/features.h
@@ -64,6 +64,17 @@ // Disables the screenshots of non-HTML pages on iOS15. extern const base::Feature kDisableNonHTMLScreenshotOnIOS15; +// Feature flag that enable Shared Highlighting color change in iOS. +extern const base::Feature kIOSSharedHighlightingColorChange; + +// Feature flag that enables creating pending item on POST form submission. +// Also, for GET form submissions with same page navigation, retains the +// transition type of new navigation item. +extern const base::Feature kCreatePendingItemForPostFormSubmission; + +// Enable the new download API if available. +extern const base::Feature kEnableNewDownloadAPI; + // When true, for each navigation, the default user agent is chosen by the // WebClient GetDefaultUserAgent() method. If it is false, the mobile version // is requested by default. @@ -79,13 +90,8 @@ // When true, screenshots of non-HTML (e.g. PDF) pages should be taken. bool ShouldTakeScreenshotOnNonHTMLContent(); -// Feature flag that enable Shared Highlighting color change in iOS. -extern const base::Feature kIOSSharedHighlightingColorChange; - -// Feature flag that enables creating pending item on POST form submission. -// Also, for GET form submissions with same page navigation, retains the -// transition type of new navigation item. -extern const base::Feature kCreatePendingItemForPostFormSubmission; +// When true, the new download API should be used. +bool IsNewDownloadAPIEnabled(); } // namespace features } // namespace web
diff --git a/ios/web/common/features.mm b/ios/web/common/features.mm index 44c8cd4..527f3e8 100644 --- a/ios/web/common/features.mm +++ b/ios/web/common/features.mm
@@ -55,6 +55,16 @@ const base::Feature kDisableNonHTMLScreenshotOnIOS15{ "DisableNonHTMLScreenshotOnIOS15", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kIOSSharedHighlightingColorChange{ + "IOSSharedHighlightingColorChange", base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kCreatePendingItemForPostFormSubmission{ + "CreatePendingItemForPostFormSubmission", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kEnableNewDownloadAPI{"EnableNewDownloadAPI", + base::FEATURE_DISABLED_BY_DEFAULT}; + bool UseWebClientDefaultUserAgent() { return base::FeatureList::IsEnabled(kUseDefaultUserAgentInWebClient); } @@ -75,12 +85,12 @@ return true; } -const base::Feature kIOSSharedHighlightingColorChange{ - "IOSSharedHighlightingColorChange", base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kCreatePendingItemForPostFormSubmission{ - "CreatePendingItemForPostFormSubmission", - base::FEATURE_DISABLED_BY_DEFAULT}; +bool IsNewDownloadAPIEnabled() { + if (@available(iOS 15, *)) { + return base::FeatureList::IsEnabled(kEnableNewDownloadAPI); + } + return false; +} } // namespace features } // namespace web
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 8da49a09..bf9bf3a 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -481,9 +481,6 @@ [self updatePendingNavigationInfoFromNavigationResponse:WKResponse HTTPHeaders:headers]; - web::WebStatePolicyDecider::PolicyDecision policyDecision = - web::WebStatePolicyDecider::PolicyDecision::Allow(); - __weak CRWPendingNavigationInfo* weakPendingNavigationInfo = self.pendingNavigationInfo; auto callback = base::BindOnce(
diff --git a/media/audio/mac/audio_manager_mac.cc b/media/audio/mac/audio_manager_mac.cc index 49f2e70..e6bdfaea 100644 --- a/media/audio/mac/audio_manager_mac.cc +++ b/media/audio/mac/audio_manager_mac.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/containers/flat_set.h" #include "base/mac/mac_logging.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" @@ -670,10 +671,12 @@ std::vector<AudioObjectID> related_device_ids = core_audio_mac::GetRelatedDeviceIDs(input_device_id); - std::vector<AudioObjectID> related_output_device_ids; + // Defined as a set as device IDs might be duplicated in + // GetRelatedDeviceIDs(). + base::flat_set<AudioObjectID> related_output_device_ids; for (AudioObjectID device_id : related_device_ids) { if (core_audio_mac::GetNumStreams(device_id, false /* is_input */) > 0) - related_output_device_ids.push_back(device_id); + related_output_device_ids.insert(device_id); } // Return the device ID if there is only one associated device. @@ -682,7 +685,7 @@ // to an endpoint, so we cannot randomly pick a device. if (related_output_device_ids.size() == 1) { absl::optional<std::string> related_unique_id = - core_audio_mac::GetDeviceUniqueID(related_output_device_ids[0]); + core_audio_mac::GetDeviceUniqueID(*related_output_device_ids.begin()); if (related_unique_id) return std::move(*related_unique_id); }
diff --git a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.cc b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.cc index ed1bbd9..4df4d6e 100644 --- a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.cc +++ b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.cc
@@ -209,9 +209,7 @@ H264VaapiVideoEncoderDelegate::H264VaapiVideoEncoderDelegate( scoped_refptr<VaapiWrapper> vaapi_wrapper, base::RepeatingClosure error_cb) - : VaapiVideoEncoderDelegate(std::move(vaapi_wrapper), error_cb), - packed_sps_(new H264BitstreamBuffer()), - packed_pps_(new H264BitstreamBuffer()) {} + : VaapiVideoEncoderDelegate(std::move(vaapi_wrapper), error_cb) {} H264VaapiVideoEncoderDelegate::~H264VaapiVideoEncoderDelegate() { // H264VaapiVideoEncoderDelegate can be destroyed on any thread. @@ -324,13 +322,32 @@ curr_params_.max_num_ref_frames = std::min(kMaxNumReferenceFrames, curr_params_.max_ref_pic_list0_size); - if (!UpdateRates(GetDefaultVideoBitrateAllocation(config), initial_framerate)) + bool submit_packed_sps = false; + bool submit_packed_pps = false; + bool submit_packed_slice = false; + if (!vaapi_wrapper_->GetSupportedPackedHeaders( + config.output_profile, submit_packed_sps, submit_packed_pps, + submit_packed_slice)) { + DVLOGF(1) << "Failed getting supported packed headers"; return false; + } + + // Submit packed headers only if packed SPS, PPS and slice header all are + // supported. + submit_packed_headers_ = + submit_packed_sps && submit_packed_pps && submit_packed_slice; + if (submit_packed_headers_) { + packed_sps_ = base::MakeRefCounted<H264BitstreamBuffer>(); + packed_pps_ = base::MakeRefCounted<H264BitstreamBuffer>(); + } else { + DVLOGF(2) << "Packed headers are not submitted to a driver"; + } UpdateSPS(); UpdatePPS(); - return true; + return UpdateRates(GetDefaultVideoBitrateAllocation(config), + initial_framerate); } gfx::Size H264VaapiVideoEncoderDelegate::GetCodedSize() const { @@ -416,7 +433,7 @@ return false; } - if (pic->type == H264SliceHeader::kISlice) { + if (pic->type == H264SliceHeader::kISlice && submit_packed_headers_) { // We always generate SPS and PPS with I(DR) frame. This will help for Seek // operation on the generated stream. if (!SubmitPackedHeaders(encode_job, packed_sps_, packed_pps_)) { @@ -584,7 +601,8 @@ current_sps_.time_offset_length = H264SPS::kDefaultTimeOffsetLength; current_sps_.low_delay_hrd_flag = false; - GeneratePackedSPS(); + if (submit_packed_headers_) + GeneratePackedSPS(); encoding_parameters_changed_ = true; } @@ -610,12 +628,15 @@ current_pps_.transform_8x8_mode_flag = (current_sps_.profile_idc == H264SPS::kProfileIDCHigh); - GeneratePackedPPS(); + if (submit_packed_headers_) + GeneratePackedPPS(); encoding_parameters_changed_ = true; } void H264VaapiVideoEncoderDelegate::GeneratePackedSPS() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(submit_packed_headers_); + DCHECK(packed_sps_); packed_sps_->Reset(); @@ -731,6 +752,8 @@ void H264VaapiVideoEncoderDelegate::GeneratePackedPPS() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(submit_packed_headers_); + DCHECK(packed_pps_); packed_pps_->Reset(); @@ -1020,23 +1043,6 @@ base::Unretained(this), VAEncPictureParameterBufferType, MakeRefCountedBytes(&pic_param, sizeof(pic_param)))); - scoped_refptr<H264BitstreamBuffer> packed_slice_header = - GeneratePackedSliceHeader(pic_param, slice_param, *pic); - VAEncPackedHeaderParameterBuffer packed_slice_param_buffer; - packed_slice_param_buffer.type = VAEncPackedHeaderSlice; - packed_slice_param_buffer.bit_length = packed_slice_header->BitsInBuffer(); - packed_slice_param_buffer.has_emulation_bytes = 0; - - // Submit packed slice header. - job->AddSetupCallback(base::BindOnce( - &VaapiVideoEncoderDelegate::SubmitBuffer, base::Unretained(this), - VAEncPackedHeaderParameterBufferType, - MakeRefCountedBytes(&packed_slice_param_buffer, - sizeof(packed_slice_param_buffer)))); - job->AddSetupCallback( - base::BindOnce(&H264VaapiVideoEncoderDelegate::SubmitH264BitstreamBuffer, - base::Unretained(this), packed_slice_header)); - job->AddSetupCallback( base::BindOnce(&VaapiVideoEncoderDelegate::SubmitBuffer, base::Unretained(this), VAEncSliceParameterBufferType, @@ -1057,6 +1063,26 @@ base::Unretained(this), VAEncMiscParameterTypeHRD, MakeRefCountedBytes(&hrd_param, sizeof(hrd_param)))); + if (!submit_packed_headers_) + return true; + + scoped_refptr<H264BitstreamBuffer> packed_slice_header = + GeneratePackedSliceHeader(pic_param, slice_param, *pic); + VAEncPackedHeaderParameterBuffer packed_slice_param_buffer; + packed_slice_param_buffer.type = VAEncPackedHeaderSlice; + packed_slice_param_buffer.bit_length = packed_slice_header->BitsInBuffer(); + packed_slice_param_buffer.has_emulation_bytes = 0; + + // Submit packed slice header. + job->AddSetupCallback(base::BindOnce( + &VaapiVideoEncoderDelegate::SubmitBuffer, base::Unretained(this), + VAEncPackedHeaderParameterBufferType, + MakeRefCountedBytes(&packed_slice_param_buffer, + sizeof(packed_slice_param_buffer)))); + job->AddSetupCallback( + base::BindOnce(&H264VaapiVideoEncoderDelegate::SubmitH264BitstreamBuffer, + base::Unretained(this), packed_slice_header)); + return true; } @@ -1073,6 +1099,9 @@ scoped_refptr<H264BitstreamBuffer> packed_sps, scoped_refptr<H264BitstreamBuffer> packed_pps) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(submit_packed_headers_); + DCHECK(packed_sps); + DCHECK(packed_pps); // Submit SPS. VAEncPackedHeaderParameterBuffer par_buffer = {}; @@ -1101,7 +1130,6 @@ job->AddSetupCallback( base::BindOnce(&H264VaapiVideoEncoderDelegate::SubmitH264BitstreamBuffer, base::Unretained(this), packed_pps)); - return true; }
diff --git a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.h b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.h index 4661b32..fe1c4cf 100644 --- a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.h +++ b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate.h
@@ -124,6 +124,7 @@ scoped_refptr<H264BitstreamBuffer> packed_sps_; H264PPS current_pps_; scoped_refptr<H264BitstreamBuffer> packed_pps_; + bool submit_packed_headers_; // Current encoding parameters being used. EncodeParams curr_params_;
diff --git a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate_unittest.cc b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate_unittest.cc index cbb9bee..a8a3199 100644 --- a/media/gpu/vaapi/h264_vaapi_video_encoder_delegate_unittest.cc +++ b/media/gpu/vaapi/h264_vaapi_video_encoder_delegate_unittest.cc
@@ -79,6 +79,16 @@ public: MockVaapiWrapper() : VaapiWrapper(kEncodeConstantBitrate) {} + bool GetSupportedPackedHeaders(VideoCodecProfile profile, + bool& packed_sps, + bool& packed_pps, + bool& packed_slice) override { + packed_sps = true; + packed_pps = true; + packed_slice = true; + return true; + } + protected: ~MockVaapiWrapper() override = default; };
diff --git a/media/gpu/vaapi/vaapi_wrapper.cc b/media/gpu/vaapi/vaapi_wrapper.cc index da9831d91..e0012e2 100644 --- a/media/gpu/vaapi/vaapi_wrapper.cc +++ b/media/gpu/vaapi/vaapi_wrapper.cc
@@ -2711,6 +2711,25 @@ return true; } +bool VaapiWrapper::GetSupportedPackedHeaders(VideoCodecProfile profile, + bool& packed_sps, + bool& packed_pps, + bool& packed_slice) { + const VAProfile va_profile = + ProfileToVAProfile(profile, CodecMode::kEncodeConstantBitrate); + VAConfigAttrib attrib{}; + attrib.type = VAConfigAttribEncPackedHeaders; + base::AutoLock auto_lock(*va_lock_); + const VAStatus va_res = vaGetConfigAttributes(va_display_, va_profile, + va_entrypoint_, &attrib, 1); + VA_SUCCESS_OR_RETURN(va_res, VaapiFunctions::kVAGetConfigAttributes, false); + packed_sps = attrib.value & VA_ENC_PACKED_HEADER_SEQUENCE; + packed_pps = attrib.value & VA_ENC_PACKED_HEADER_PICTURE; + packed_slice = attrib.value & VA_ENC_PACKED_HEADER_SLICE; + + return true; +} + bool VaapiWrapper::IsRotationSupported() { base::AutoLock auto_lock(*va_lock_); VAProcPipelineCaps pipeline_caps;
diff --git a/media/gpu/vaapi/vaapi_wrapper.h b/media/gpu/vaapi/vaapi_wrapper.h index 88ffcd0..0dea294 100644 --- a/media/gpu/vaapi/vaapi_wrapper.h +++ b/media/gpu/vaapi/vaapi_wrapper.h
@@ -484,6 +484,15 @@ size_t* max_ref_frames) WARN_UNUSED_RESULT; + // Gets packed headers are supported for encoding. This is called for + // H264 encoding. |packed_sps|, |packed_pps| and |packed_slice| stands for + // whether packed slice parameter set, packed picture parameter set and packed + // slice header is supported, respectively. + virtual bool GetSupportedPackedHeaders(VideoCodecProfile profile, + bool& packed_sps, + bool& packed_pps, + bool& packed_slice) WARN_UNUSED_RESULT; + // Checks if the driver supports frame rotation. bool IsRotationSupported();
diff --git a/media/webrtc/helpers.cc b/media/webrtc/helpers.cc index 7c584ad..1973967bc 100644 --- a/media/webrtc/helpers.cc +++ b/media/webrtc/helpers.cc
@@ -178,7 +178,7 @@ ConfigAgc1AnalogForClippingControlExperiment(agc1_analog_config); } - // Hybrid AGC experiment. + // Hybrid AGC feature. const bool use_hybrid_agc = base::FeatureList::IsEnabled(::features::kWebRtcHybridAgc); auto& agc2_config = apm_config.gain_controller2;
diff --git a/media/webrtc/helpers_unittests.cc b/media/webrtc/helpers_unittests.cc index 835da91..b5d64af 100644 --- a/media/webrtc/helpers_unittests.cc +++ b/media/webrtc/helpers_unittests.cc
@@ -25,9 +25,8 @@ } // Verify that the default settings in AudioProcessingSettings are applied -// correctly by CreateWebRtcAudioProcessingModule(). -TEST(CreateWebRtcAudioProcessingModuleTest, - CheckDefaultAudioProcessingSettings) { +// correctly by `CreateWebRtcAudioProcessingModule()`. +TEST(CreateWebRtcAudioProcessingModuleTest, CheckDefaultAudioProcessingConfig) { auto config = CreateApmGetConfig(/*settings=*/{}); EXPECT_TRUE(config.pipeline.multi_channel_render); @@ -37,8 +36,11 @@ EXPECT_FALSE(config.pre_amplifier.enabled); EXPECT_TRUE(config.echo_canceller.enabled); EXPECT_TRUE(config.gain_controller1.enabled); - EXPECT_TRUE(config.gain_controller1.analog_gain_controller.enabled); +#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) + EXPECT_TRUE(config.gain_controller2.enabled); +#else EXPECT_FALSE(config.gain_controller2.enabled); +#endif EXPECT_TRUE(config.noise_suppression.enabled); EXPECT_EQ(config.noise_suppression.level, webrtc::AudioProcessing::Config::NoiseSuppression::kHigh); @@ -65,7 +67,7 @@ EXPECT_EQ(config.gain_controller1.mode, Mode::kFixedDigital); #else EXPECT_EQ(config.gain_controller1.mode, Mode::kAdaptiveAnalog); -#endif // defined(OS_ANDROID) +#endif const auto& agc1_analog_config = config.gain_controller1.analog_gain_controller; @@ -91,7 +93,17 @@ // TODO(bugs.webrtc.org/7909): Uncomment below once fixed. // #endif + // Check that either AGC1 digital or AGC2 digital is used based on the + // platforms where the Hybrid AGC is enabled by default. +#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) + EXPECT_FALSE(agc1_analog_config.enable_digital_adaptive); + EXPECT_TRUE(config.gain_controller2.enabled); + EXPECT_TRUE(config.gain_controller2.adaptive_digital.enabled); +#else + // AGC1 Digital. + EXPECT_TRUE(agc1_analog_config.enable_digital_adaptive); EXPECT_FALSE(config.gain_controller2.enabled); +#endif } // When `automatic_gain_control` and `experimental_automatic_gain_control` are @@ -103,12 +115,14 @@ /*settings=*/{.automatic_gain_control = false, .experimental_automatic_gain_control = false}); #if BUILDFLAG(IS_CHROMECAST) + // Override the default config since on Chromecast AGC1 is explicitly + // disabled. auto expected_config = kDefaultApmConfig.gain_controller1; expected_config.analog_gain_controller.enabled = false; EXPECT_EQ(config.gain_controller1, expected_config); #else EXPECT_EQ(config.gain_controller1, kDefaultApmConfig.gain_controller1); -#endif // !BUILDFLAG(IS_CHROMECAST) +#endif } TEST(CreateWebRtcAudioProcessingModuleTest, @@ -119,25 +133,6 @@ EXPECT_EQ(config.gain_controller2, kDefaultApmConfig.gain_controller2); } -// When `automatic_gain_control` and `experimental_automatic_gain_control` are -// false and the Hybrid AGC experiment is enabled, the default AGC1 -// configuration is used, but on Chromecast AGC1 Analog is explicitly disabled. -TEST(CreateWebRtcAudioProcessingModuleTest, - Agc1ConfigUnchangedIfAgcSettingsDisabledAndHybridAgcEnabled) { - ::base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature(features::kWebRtcAnalogAgcClippingControl); - auto config = CreateApmGetConfig( - /*settings=*/{.automatic_gain_control = false, - .experimental_automatic_gain_control = false}); -#if BUILDFLAG(IS_CHROMECAST) - auto expected_config = kDefaultApmConfig.gain_controller1; - expected_config.analog_gain_controller.enabled = false; - EXPECT_EQ(config.gain_controller1, expected_config); -#else - EXPECT_EQ(config.gain_controller1, kDefaultApmConfig.gain_controller1); -#endif // !BUILDFLAG(IS_CHROMECAST) -} - TEST(CreateWebRtcAudioProcessingModuleTest, Agc2ConfigUnchangedIfAgcSettingsDisabledAndHybridAgcEnabled) { ::base::test::ScopedFeatureList feature_list; @@ -165,7 +160,7 @@ EXPECT_TRUE(config.gain_controller1.enabled); EXPECT_FALSE(config.gain_controller1.analog_gain_controller.enabled); } -#else // BUILDFLAG(IS_CHROMECAST) +#else // !BUILDFLAG(IS_CHROMECAST) // Checks that setting `experimental_automatic_gain_control` to false does not // disable the analog controller. // TODO(bugs.webrtc.org/7909): Remove once fixed. @@ -209,17 +204,6 @@ } #endif // !(defined(OS_ANDROID) || defined(OS_IOS)) -TEST(CreateWebRtcAudioProcessingModuleTest, EnableAgcAndExperimentalAgc) { - auto config = CreateApmGetConfig( - /*settings=*/{.automatic_gain_control = true, - .experimental_automatic_gain_control = true}); - EXPECT_TRUE(config.gain_controller1.enabled); - EXPECT_TRUE(config.gain_controller1.analog_gain_controller.enabled); - EXPECT_FALSE(config.gain_controller1.analog_gain_controller.clipping_predictor - .enabled); - EXPECT_FALSE(config.gain_controller2.enabled); -} - TEST(CreateWebRtcAudioProcessingModuleTest, EnableAgc1AnalogClippingControl) { ::base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeatureWithParameters( @@ -346,7 +330,7 @@ } TEST(CreateWebRtcAudioProcessingModuleTest, - CannotEnableHybridAgcWhenAgcIsDisabled) { + HybridAgcDisabledWhenAgcIsDisabled) { ::base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kWebRtcHybridAgc); auto config = @@ -356,7 +340,7 @@ } TEST(CreateWebRtcAudioProcessingModuleTest, - CannotEnableHybridAgcWhenExperimentalAgcIsDisabled) { + HybridAgcDisabledWhenExperimentalAgcIsDisabled) { ::base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kWebRtcHybridAgc); auto config = CreateApmGetConfig(
diff --git a/media/webrtc/webrtc_features.cc b/media/webrtc/webrtc_features.cc index 51272988..97458577 100644 --- a/media/webrtc/webrtc_features.cc +++ b/media/webrtc/webrtc_features.cc
@@ -8,6 +8,15 @@ #include "build/build_config.h" namespace features { +namespace { +#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) +constexpr base::FeatureState kWebRtcHybridAgcState = + base::FEATURE_ENABLED_BY_DEFAULT; +#else +constexpr base::FeatureState kWebRtcHybridAgcState = + base::FEATURE_DISABLED_BY_DEFAULT; +#endif +} // namespace // When enabled we will tell WebRTC that we want to use the // Windows.Graphics.Capture API based DesktopCapturer, if it is available. @@ -25,10 +34,9 @@ const base::Feature kWebRtcAllow48kHzProcessingOnArm{ "WebRtcAllow48kHzProcessingOnArm", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables the WebRTC Agc2 digital adaptation with WebRTC Agc1 analog -// adaptation. Feature for http://crbug.com/873650. Is sent to WebRTC. -const base::Feature kWebRtcHybridAgc{"WebRtcHybridAgc", - base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables the WebRTC Hybrid AGC configuration - i.e., AGC1 analog and AGC2 +// digital (see http://crbug.com/1231085). +const base::Feature kWebRtcHybridAgc{"WebRtcHybridAgc", kWebRtcHybridAgcState}; // Enables and configures the clipping control in the WebRTC analog AGC. const base::Feature kWebRtcAnalogAgcClippingControl{
diff --git a/net/base/features.cc b/net/base/features.cc index b9dcac5..2701fee79 100644 --- a/net/base/features.cc +++ b/net/base/features.cc
@@ -202,9 +202,6 @@ const base::Feature kTLSLegacyCryptoFallbackForMetrics{ "TLSLegacyCryptoFallbackForMetrics", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kUseLookalikesForNavigationSuggestions{ - "UseLookalikesForNavigationSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kReportPoorConnectivity{"ReportPoorConnectivity", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/net/base/features.h b/net/base/features.h index 26cd4eb..e516e675 100644 --- a/net/base/features.h +++ b/net/base/features.h
@@ -303,10 +303,6 @@ // those algorithms. If disabled, the algorithms will always be offered. NET_EXPORT extern const base::Feature kTLSLegacyCryptoFallbackForMetrics; -// When enabled, DNS_PROBE_FINISHED_NXDOMAIN error pages may show -// locally-generated suggestions to visit similar domains. -NET_EXPORT extern const base::Feature kUseLookalikesForNavigationSuggestions; - // When enabled, the Network Quality Estimator (NQE) will notify the operating // system whenever it detects that the current default network may have // significantly degraded connectivity. Currently only effective on Android.
diff --git a/services/device/public/cpp/test/fake_sensor_and_provider.cc b/services/device/public/cpp/test/fake_sensor_and_provider.cc index 4cf21f8..b15c3a7 100644 --- a/services/device/public/cpp/test/fake_sensor_and_provider.cc +++ b/services/device/public/cpp/test/fake_sensor_and_provider.cc
@@ -198,6 +198,10 @@ receivers_.Add(this, std::move(receiver)); } +bool FakeSensorProvider::is_bound() const { + return !receivers_.empty(); +} + void FakeSensorProvider::SetAmbientLightSensorData(double value) { ambient_light_sensor_reading_.als.timestamp = (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
diff --git a/services/device/public/cpp/test/fake_sensor_and_provider.h b/services/device/public/cpp/test/fake_sensor_and_provider.h index 55e1975..aefb1c4 100644 --- a/services/device/public/cpp/test/fake_sensor_and_provider.h +++ b/services/device/public/cpp/test/fake_sensor_and_provider.h
@@ -68,6 +68,7 @@ void GetSensor(mojom::SensorType type, GetSensorCallback callback) override; void Bind(mojo::PendingReceiver<mojom::SensorProvider> receiver); + bool is_bound() const; void set_ambient_light_sensor_is_available( bool ambient_light_sensor_is_available) {
diff --git a/services/network/public/cpp/client_hints.cc b/services/network/public/cpp/client_hints.cc index f3def88..6ce5a2a 100644 --- a/services/network/public/cpp/client_hints.cc +++ b/services/network/public/cpp/client_hints.cc
@@ -43,6 +43,12 @@ {network::mojom::WebClientHintsType::kUAReduced, "sec-ch-ua-reduced"}, {network::mojom::WebClientHintsType::kViewportHeight, "sec-ch-viewport-height"}, + {network::mojom::WebClientHintsType::kDeviceMemory, + "sec-ch-device-memory"}, + {network::mojom::WebClientHintsType::kDpr, "sec-ch-dpr"}, + {network::mojom::WebClientHintsType::kResourceWidth, "sec-ch-width"}, + {network::mojom::WebClientHintsType::kViewportWidth, + "sec-ch-viewport-width"}, }; }
diff --git a/services/network/public/cpp/cors/cors.cc b/services/network/public/cpp/cors/cors.cc index 1edb83c..7e9683d 100644 --- a/services/network/public/cpp/cors/cors.cc +++ b/services/network/public/cpp/cors/cors.cc
@@ -310,12 +310,10 @@ "intervention", "content-type", "save-data", - // The Device Memory header field is a number that indicates the client’s - // device memory i.e. approximate amount of ram in GiB. The header value - // must satisfy ABNF 1*DIGIT [ "." 1*DIGIT ] - // See - // https://w3c.github.io/device-memory/#sec-device-memory-client-hint-header - // for more details. + + // These four were deprecated and replaced by variants with a `sec-ch-` + // prefix to conform with the proposal: + // https://wicg.github.io/client-hints-infrastructure/ "device-memory", "dpr", "width", @@ -353,6 +351,17 @@ // // https://wicg.github.io/user-preference-media-features-headers/#sec-ch-prefers-color-scheme "sec-ch-prefers-color-scheme", + + // The Device Memory header field is a number that indicates the client’s + // device memory i.e. approximate amount of ram in GiB. The header value + // must satisfy ABNF 1*DIGIT [ "." 1*DIGIT ] + // See + // https://w3c.github.io/device-memory/#sec-device-memory-client-hint-header + // for more details. + "sec-ch-device-memory", + "sec-ch-dpr", + "sec-ch-width", + "sec-ch-viewport-width", }; if (std::find(std::begin(safe_names), std::end(safe_names), lower_name) == std::end(safe_names))
diff --git a/services/network/public/cpp/url_loader_completion_status.cc b/services/network/public/cpp/url_loader_completion_status.cc index 45eea53..b84d6d2 100644 --- a/services/network/public/cpp/url_loader_completion_status.cc +++ b/services/network/public/cpp/url_loader_completion_status.cc
@@ -4,6 +4,7 @@ #include "services/network/public/cpp/url_loader_completion_status.h" +#include "base/trace_event/trace_event.h" #include "net/base/net_errors.h" namespace network { @@ -45,4 +46,14 @@ should_collapse_initiator == rhs.should_collapse_initiator; } +void URLLoaderCompletionStatus::WriteIntoTrace( + perfetto::TracedValue context) const { + auto dict = std::move(context).WriteDictionary(); + dict.Add("error_code", error_code); + dict.Add("extended_error_code", extended_error_code); + dict.Add("encoded_data_length", encoded_data_length); + dict.Add("encoded_body_length", encoded_body_length); + dict.Add("decoded_body_length", decoded_body_length); +} + } // namespace network
diff --git a/services/network/public/cpp/url_loader_completion_status.h b/services/network/public/cpp/url_loader_completion_status.h index 5cd5fc7..9db1bba5 100644 --- a/services/network/public/cpp/url_loader_completion_status.h +++ b/services/network/public/cpp/url_loader_completion_status.h
@@ -18,6 +18,7 @@ #include "services/network/public/mojom/cors.mojom-shared.h" #include "services/network/public/mojom/trust_tokens.mojom-shared.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/perfetto/include/perfetto/tracing/traced_value_forward.h" namespace network { @@ -103,6 +104,9 @@ // Whether the initiator of this request should be collapsed. bool should_collapse_initiator = false; + + // Write a representation of this struct into a trace. + void WriteIntoTrace(perfetto::TracedValue context) const; }; } // namespace network
diff --git a/services/network/public/mojom/web_client_hints_types.mojom b/services/network/public/mojom/web_client_hints_types.mojom index 34dbcc3..5a4a97b 100644 --- a/services/network/public/mojom/web_client_hints_types.mojom +++ b/services/network/public/mojom/web_client_hints_types.mojom
@@ -39,6 +39,10 @@ // header contains the reduced user agent string. kUAReduced = 17, kViewportHeight = 18, + kDeviceMemory = 19, // The `sec-ch-` variant of kDeviceMemory_DEPRECATED + kDpr = 20, // The `sec-ch-` variant of kDpr_DEPRECATED + kResourceWidth = 21, // The `sec-ch-` variant of kResourceWidth_DEPRECATED + kViewportWidth = 22, // The `sec-ch-` variant of kViewportWidth_DEPRECATED // Warning: Before adding a new client hint, read the warning at the top. };
diff --git a/services/network/web_bundle/web_bundle_url_loader_factory.cc b/services/network/web_bundle/web_bundle_url_loader_factory.cc index 8c0af18..a6f8d634 100644 --- a/services/network/web_bundle/web_bundle_url_loader_factory.cc +++ b/services/network/web_bundle/web_bundle_url_loader_factory.cc
@@ -541,7 +541,7 @@ weak_ptr_factory_.GetWeakPtr())); // WebBundleParser will self-destruct on remote mojo ends' disconnection. new web_package::WebBundleParser(parser_.BindNewPipeAndPassReceiver(), - std::move(data_source)); + std::move(data_source), bundle_url_); parser_->ParseMetadata( base::BindOnce(&WebBundleURLLoaderFactory::OnMetadataParsed,
diff --git a/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter b/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter index 15b45da..2b5ab5a 100644 --- a/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter +++ b/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter
@@ -2,4 +2,5 @@ # If you need to disable a tests for version skew, use # linux-lacros.lacros_chrome_browsertests.skew.filter. +# TODO(crbug.com/1252114) Flaky. Re-enable the test. -LacrosExtensionAppsControllerTest.LaunchPinnedApp
diff --git a/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter b/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter index c9cdf8a1..2ce5b8ab 100644 --- a/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter +++ b/testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter
@@ -2,3 +2,6 @@ # # If you want to disable a test only for version skew testing, # you should add the test here, not in the source code. + +# TODO(crbug.com/1252114) Flaky. Re-enable the test. +-LacrosExtensionAppsControllerTest.LaunchPinnedApp
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 6cdf9e7c..470d241 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -170,27 +170,6 @@ ] } ], - "AndroidInProductHelpContextualSearchPromoteLongpress": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "PromoteLongpressExperiment", - "params": { - "availability": "any", - "event_trigger": "name:longpress_bubble_shown;comparator:<6;window:90;storage:90", - "event_used": "name:contextual_search_panel_opened_after_longpress;comparator:==0;window:365;storage:365", - "session_rate": "<1" - }, - "enable_features": [ - "IPH_ContextualSearchTappedButShouldLongpress" - ] - } - ] - } - ], "AndroidInProductHelpContextualSearchPromotePanelOpen": [ { "platforms": [ @@ -1367,24 +1346,6 @@ ] } ], - "BackgroundSync": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "RelyOnAndroidNetworkDetection", - "params": { - "rely_on_android_network_detection": "true" - }, - "enable_features": [ - "BackgroundSync" - ] - } - ] - } - ], "BackgroundThreadPool": [ { "platforms": [ @@ -3378,27 +3339,6 @@ ] } ], - "EphemeralTab": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "Enabled", - "params": { - "availability": "any", - "event_trigger": "name:ephemeral_tab_triggered;comparator:<2;window:90;storage:90", - "event_used": "name:ephemeral_tab_used;comparator:==0;window:90;storage:90", - "session_rate": "any" - }, - "enable_features": [ - "IPH_EphemeralTab" - ] - } - ] - } - ], "ExperimentalAccessibilityLabels": [ { "platforms": [ @@ -4104,53 +4044,6 @@ ] } ], - "IOSDefaultBrowserNonModalPromoExperiment": [ - { - "platforms": [ - "ios" - ], - "experiments": [ - { - "name": "ShortTimeout", - "params": { - "timeout": "15" - }, - "enable_features": [ - "DefaultPromoNonModal" - ] - }, - { - "name": "ShortTimeoutInstructions", - "params": { - "instructions_enabled": "true", - "timeout": "15" - }, - "enable_features": [ - "DefaultPromoNonModal" - ] - }, - { - "name": "LongTimeout", - "params": { - "timeout": "45" - }, - "enable_features": [ - "DefaultPromoNonModal" - ] - }, - { - "name": "LongTimeoutInstructions", - "params": { - "instructions_enabled": "true", - "timeout": "45" - }, - "enable_features": [ - "DefaultPromoNonModal" - ] - } - ] - } - ], "IOSDiscoverNoticeCardAutoDismiss": [ { "platforms": [ @@ -6082,27 +5975,6 @@ ] } ], - "PaymentRequestAlwaysAllowJustInTimePaymentApp": [ - { - "platforms": [ - "android", - "android_weblayer", - "chromeos", - "chromeos_lacros", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "AlwaysAllowJustInTimePaymentApp" - ] - } - ] - } - ], "PdfUnseasoned": [ { "platforms": [ @@ -6970,33 +6842,6 @@ ] } ], - "RenderDocument": [ - { - "platforms": [ - "android", - "android_webview", - "chromeos", - "chromeos_lacros", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "EnableForCrashedFrame", - "params": { - "level": "crashed-frame" - }, - "enable_features": [ - "RenderDocument" - ], - "disable_features": [ - "SkipEarlyCommitPendingForCrashedFrame" - ] - } - ] - } - ], "ReportAllJavaScriptFrameworks": [ { "platforms": [ @@ -7502,26 +7347,6 @@ ] } ], - "SharedClipboard": [ - { - "platforms": [ - "android", - "chromeos", - "chromeos_lacros", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "SharedClipboardUI" - ] - } - ] - } - ], "SharedHighlightingClankV2": [ { "platforms": [ @@ -7593,31 +7418,6 @@ ] } ], - "SharingFilterDevices": [ - { - "platforms": [ - "android", - "android_weblayer", - "chromeos", - "chromeos_lacros", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled_strict", - "params": { - "SharingPulseDeltaAndroidHours": "0", - "SharingPulseDeltaDesktopHours": "0" - }, - "enable_features": [ - "SharingMatchPulseInterval" - ] - } - ] - } - ], "SharingHubLinkToggle": [ { "platforms": [ @@ -7874,8 +7674,7 @@ "chromeos", "linux", "mac", - "windows", - "ios" + "windows" ], "experiments": [ {
diff --git a/third_party/blink/common/client_hints/client_hints.cc b/third_party/blink/common/client_hints/client_hints.cc index c304e26..89167fe1 100644 --- a/third_party/blink/common/client_hints/client_hints.cc +++ b/third_party/blink/common/client_hints/client_hints.cc
@@ -25,8 +25,7 @@ ClientHintToPolicyFeatureMap MakeClientHintToPolicyFeatureMap() { return { // Legacy Hints that are sent cross-origin regardless of Permissions - // Policy - // when kAllowClientHintsToThirdParty is enabled. + // Policy when kAllowClientHintsToThirdParty is enabled. {network::mojom::WebClientHintsType::kDeviceMemory_DEPRECATED, mojom::PermissionsPolicyFeature::kClientHintDeviceMemory}, {network::mojom::WebClientHintsType::kDpr_DEPRECATED, @@ -64,6 +63,14 @@ mojom::PermissionsPolicyFeature::kClientHintUAReduced}, {network::mojom::WebClientHintsType::kViewportHeight, mojom::PermissionsPolicyFeature::kClientHintViewportHeight}, + {network::mojom::WebClientHintsType::kDeviceMemory, + mojom::PermissionsPolicyFeature::kClientHintDeviceMemory}, + {network::mojom::WebClientHintsType::kDpr, + mojom::PermissionsPolicyFeature::kClientHintDPR}, + {network::mojom::WebClientHintsType::kResourceWidth, + mojom::PermissionsPolicyFeature::kClientHintWidth}, + {network::mojom::WebClientHintsType::kViewportWidth, + mojom::PermissionsPolicyFeature::kClientHintViewportWidth}, }; }
diff --git a/third_party/blink/common/client_hints/client_hints_unittest.cc b/third_party/blink/common/client_hints/client_hints_unittest.cc index 6bbfd7a1..faea933f 100644 --- a/third_party/blink/common/client_hints/client_hints_unittest.cc +++ b/third_party/blink/common/client_hints/client_hints_unittest.cc
@@ -25,12 +25,14 @@ features::kAllowClientHintsToThirdParty); std::vector<std::string> removed_headers; FindClientHintsToRemove(nullptr, GURL(), &removed_headers); - EXPECT_THAT(removed_headers, - UnorderedElementsAre( - "rtt", "downlink", "ect", "sec-ch-ua-arch", "sec-ch-ua-model", - "sec-ch-ua-full-version", "sec-ch-ua-platform-version", - "sec-ch-prefers-color-scheme", "sec-ch-ua-bitness", - "sec-ch-ua-reduced", "sec-ch-viewport-height")); + EXPECT_THAT( + removed_headers, + UnorderedElementsAre( + "rtt", "downlink", "ect", "sec-ch-ua-arch", "sec-ch-ua-model", + "sec-ch-ua-full-version", "sec-ch-ua-platform-version", + "sec-ch-prefers-color-scheme", "sec-ch-ua-bitness", + "sec-ch-ua-reduced", "sec-ch-viewport-height", "sec-ch-device-memory", + "sec-ch-dpr", "sec-ch-width", "sec-ch-viewport-width")); } // Checks that the removed header list includes legacy headers but not the @@ -47,6 +49,8 @@ "device-memory", "dpr", "width", "viewport-width", "rtt", "downlink", "ect", "sec-ch-ua-arch", "sec-ch-ua-model", "sec-ch-ua-full-version", "sec-ch-ua-platform-version", "sec-ch-prefers-color-scheme", - "sec-ch-ua-bitness", "sec-ch-ua-reduced", "sec-ch-viewport-height")); + "sec-ch-ua-bitness", "sec-ch-ua-reduced", "sec-ch-viewport-height", + "sec-ch-device-memory", "sec-ch-dpr", "sec-ch-width", + "sec-ch-viewport-width")); } } // namespace blink
diff --git a/third_party/blink/common/client_hints/enabled_client_hints.cc b/third_party/blink/common/client_hints/enabled_client_hints.cc index 56c9352..4eb1c056 100644 --- a/third_party/blink/common/client_hints/enabled_client_hints.cc +++ b/third_party/blink/common/client_hints/enabled_client_hints.cc
@@ -41,6 +41,22 @@ features::kViewportHeightClientHintHeader)) return true; break; + case WebClientHintsType::kDeviceMemory: + if (!base::FeatureList::IsEnabled(features::kClientHintsDeviceMemory)) + return true; + break; + case WebClientHintsType::kDpr: + if (!base::FeatureList::IsEnabled(features::kClientHintsDPR)) + return true; + break; + case WebClientHintsType::kResourceWidth: + if (!base::FeatureList::IsEnabled(features::kClientHintsResourceWidth)) + return true; + break; + case WebClientHintsType::kViewportWidth: + if (!base::FeatureList::IsEnabled(features::kClientHintsViewportWidth)) + return true; + break; default: break; }
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 6c3eff4..7da929e8 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -1034,5 +1034,20 @@ const base::Feature kForceMajorVersion100InUserAgent{ "ForceMajorVersion100InUserAgent", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enable `sec-ch-device-memory` client hint. +const base::Feature kClientHintsDeviceMemory{"ClientHintsDeviceMemory", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enable `sec-ch-dpr` client hint. +const base::Feature kClientHintsDPR{"ClientHintsDPR", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enable `sec-ch-width` client hint. +const base::Feature kClientHintsResourceWidth{ + "ClientHintsResourceWidth", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enable `sec-ch-viewport-width` client hint. +const base::Feature kClientHintsViewportWidth{ + "ClientHintsViewportWidth", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace features } // namespace blink
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 7ba3ce4..b7f8bae 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -472,6 +472,11 @@ // fix any issues as we approach a 3-digit major version number. BLINK_COMMON_EXPORT extern const base::Feature kForceMajorVersion100InUserAgent; +BLINK_COMMON_EXPORT extern const base::Feature kClientHintsDeviceMemory; +BLINK_COMMON_EXPORT extern const base::Feature kClientHintsDPR; +BLINK_COMMON_EXPORT extern const base::Feature kClientHintsResourceWidth; +BLINK_COMMON_EXPORT extern const base::Feature kClientHintsViewportWidth; + } // namespace features } // namespace blink
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index 4e90b6d..973a78c 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -776,6 +776,17 @@ string targetOrigin boolean isWarning + type GenericIssueErrorType extends string + enum + CrossOriginPortalPostMessageError + + # Depending on the concrete errorType, different properties are set. + type GenericIssueDetails extends object + properties + # Issues with the same errorType are aggregated in the frontend. + GenericIssueErrorType errorType + optional Page.FrameId frameId + # A unique identifier for the type of issue. Each type may use one of the # optional fields in InspectorIssueDetails to convey more specific # information about the kind of issue. @@ -794,6 +805,7 @@ QuirksModeIssue NavigatorUserAgentIssue WasmCrossOriginModuleSharingIssue + GenericIssue # This struct holds a list of optional fields with additional information # specific to the kind of issue. When adding a new issue code, please also @@ -813,6 +825,7 @@ optional QuirksModeIssueDetails quirksModeIssueDetails optional NavigatorUserAgentIssueDetails navigatorUserAgentIssueDetails optional WasmCrossOriginModuleSharingIssueDetails wasmCrossOriginModuleSharingIssue + optional GenericIssueDetails genericIssueDetails # A unique id for a DevTools inspector issue. Allows other entities (e.g. # exceptions, CDP message, console messages, etc.) to reference an issue.
diff --git a/third_party/blink/public/mojom/devtools/inspector_issue.mojom b/third_party/blink/public/mojom/devtools/inspector_issue.mojom index 9da98504..1a8517bb 100644 --- a/third_party/blink/public/mojom/devtools/inspector_issue.mojom +++ b/third_party/blink/public/mojom/devtools/inspector_issue.mojom
@@ -21,6 +21,7 @@ kTrustedWebActivityIssue, kHeavyAdIssue, kLowTextContrastIssue, + kGenericIssue, }; // Information about a cookie that is affected by an issue. @@ -173,6 +174,15 @@ string font_weight; }; +enum GenericIssueErrorType { + kCrossOriginPortalPostMessageError, +}; + +struct GenericIssueDetails { + GenericIssueErrorType error_type; + string? frame_id; +}; + // A collection of optional fields that may store additional data depending // on the issue code. struct InspectorIssueDetails { @@ -184,6 +194,7 @@ TrustedWebActivityIssueDetails? twa_issue_details; HeavyAdIssueDetails? heavy_ad_issue_details; LowTextContrastIssue? low_text_contrast_details; + GenericIssueDetails? generic_issue_details; mojo_base.mojom.UnguessableToken? issue_id; };
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index f1129d5..aef6bee 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -3353,6 +3353,10 @@ kCoepRequireCorpSharedWorker = 4043, kCoepCredentiallessSharedWorker = 4044, kPaymentRequestBasicCard = 4045, + kClientHintsDeviceMemory = 4046, + kClientHintsDPR = 4047, + kClientHintsResourceWidth = 4048, + kClientHintsViewportWidth = 4049, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 2fd22b1..625e828 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -3197,47 +3197,43 @@ } if (RuntimeEnabledFeatures::HighlightInheritanceEnabled() && new_style) { + const StyleHighlightData* parent_highlights = + parent_style ? parent_style->HighlightData().get() : nullptr; + if (new_style->HasPseudoElementStyle(kPseudoIdSelection)) { - scoped_refptr<StyleHighlightData> highlights = - new_style->MutableHighlightData(); + StyleHighlightData& highlights = new_style->MutableHighlightData(); const ComputedStyle* highlight_parent = - parent_style ? parent_style->HighlightData()->Selection().get() - : nullptr; + parent_highlights ? parent_highlights->Selection().get() : nullptr; StyleRequest style_request{kPseudoIdSelection, highlight_parent}; - highlights->SetSelection( + highlights.SetSelection( StyleForPseudoElement(style_recalc_context, style_request)); } if (new_style->HasPseudoElementStyle(kPseudoIdTargetText)) { - scoped_refptr<StyleHighlightData> highlights = - new_style->MutableHighlightData(); + StyleHighlightData& highlights = new_style->MutableHighlightData(); const ComputedStyle* highlight_parent = - parent_style ? parent_style->HighlightData()->TargetText().get() - : nullptr; + parent_highlights ? parent_highlights->TargetText().get() : nullptr; StyleRequest style_request{kPseudoIdTargetText, highlight_parent}; - highlights->SetTargetText( + highlights.SetTargetText( StyleForPseudoElement(style_recalc_context, style_request)); } if (new_style->HasPseudoElementStyle(kPseudoIdSpellingError)) { - scoped_refptr<StyleHighlightData> highlights = - new_style->MutableHighlightData(); + StyleHighlightData& highlights = new_style->MutableHighlightData(); const ComputedStyle* highlight_parent = - parent_style ? parent_style->HighlightData()->SpellingError().get() - : nullptr; + parent_highlights ? parent_highlights->SpellingError().get() + : nullptr; StyleRequest style_request{kPseudoIdSpellingError, highlight_parent}; - highlights->SetSpellingError( + highlights.SetSpellingError( StyleForPseudoElement(style_recalc_context, style_request)); } if (new_style->HasPseudoElementStyle(kPseudoIdGrammarError)) { - scoped_refptr<StyleHighlightData> highlights = - new_style->MutableHighlightData(); + StyleHighlightData& highlights = new_style->MutableHighlightData(); const ComputedStyle* highlight_parent = - parent_style ? parent_style->HighlightData()->GrammarError().get() - : nullptr; + parent_highlights ? parent_highlights->GrammarError().get() : nullptr; StyleRequest style_request{kPseudoIdGrammarError, highlight_parent}; - highlights->SetGrammarError( + highlights.SetGrammarError( StyleForPseudoElement(style_recalc_context, style_request)); }
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index b60de59..318d791 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -3132,7 +3132,7 @@ } paint_artifact_compositor_->SetPrefersLCDText( - page->GetSettings().GetPreferCompositingToLCDTextEnabled()); + !page->GetSettings().GetPreferCompositingToLCDTextEnabled()); SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(), LocalFrameUkmAggregator::kCompositingCommit);
diff --git a/third_party/blink/renderer/core/inspector/inspector_issue_conversion.cc b/third_party/blink/renderer/core/inspector/inspector_issue_conversion.cc index 782b405..b52a3f9 100644 --- a/third_party/blink/renderer/core/inspector/inspector_issue_conversion.cc +++ b/third_party/blink/renderer/core/inspector/inspector_issue_conversion.cc
@@ -60,6 +60,9 @@ return ""; case mojom::blink::InspectorIssueCode::kLowTextContrastIssue: return protocol::Audits::InspectorIssueCodeEnum::LowTextContrastIssue; + case mojom::blink::InspectorIssueCode::kGenericIssue: + NOTREACHED(); + return ""; } }
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index 765d7b0..d75e72a 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -4269,7 +4269,8 @@ } const ComputedStyle* LayoutObject::GetSelectionStyle() const { - if (RuntimeEnabledFeatures::HighlightInheritanceEnabled()) { + if (RuntimeEnabledFeatures::HighlightInheritanceEnabled() && + StyleRef().HighlightData()) { return StyleRef().HighlightData()->Selection().get(); } return GetCachedPseudoElementStyle(kPseudoIdSelection);
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc index 5008844..cf74107 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc
@@ -1061,13 +1061,17 @@ LayoutUnit NGInlineLayoutStateStack::ComputeAlignmentBaselineShift( const NGInlineBoxState* box) { - const FontMetrics& metrics = box->font->PrimaryFont()->GetFontMetrics(); - LayoutUnit result = metrics.FixedAscent(box->style->GetFontBaseline()) - - metrics.FixedAscent(box->alignment_type); + LayoutUnit result; + if (const auto* font_data = box->font->PrimaryFont()) { + const FontMetrics& metrics = font_data->GetFontMetrics(); + result = metrics.FixedAscent(box->style->GetFontBaseline()) - + metrics.FixedAscent(box->alignment_type); + } - if (box != stack_.begin()) { - const FontMetrics& parent_metrics = - box[-1].font->PrimaryFont()->GetFontMetrics(); + if (box == stack_.begin()) + return result; + if (const auto* font_data = box[-1].font->PrimaryFont()) { + const FontMetrics& parent_metrics = font_data->GetFontMetrics(); result -= parent_metrics.FixedAscent(box[-1].style->GetFontBaseline()) - parent_metrics.FixedAscent(box[-1].alignment_type); }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc index 9380751b..2c279fe 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc
@@ -1025,7 +1025,14 @@ wtf_size_t size = index_list.size(); unsigned glyph_start = offset_; for (wtf_size_t i = 0; i < size; ++i) { - DCHECK_EQ(glyph_start, index_list[i]); +#if DCHECK_IS_ON() + // The first glyph index can be greater than StartIndex() if the leading + // part of the string was not mapped to any glyphs. + if (i == 0) + DCHECK_LE(glyph_start, index_list[0]); + else + DCHECK_EQ(glyph_start, index_list[i]); +#endif unsigned glyph_end = i + 1 < size ? index_list[i + 1] : shape.EndIndex(); StringView text_view(Text()); bool should_split = i == size - 1;
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc index f56e6ab..9b1dc5f 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc
@@ -923,6 +923,30 @@ }); } +// crbug.com/1251960 +TEST_F(NGLineBreakerTest, SplitTextIntoSegementsCrash) { + RuntimeEnabledFeaturesTestHelpers::ScopedSVGTextNG svg_text_ng(true); + NGInlineNode node = CreateInlineNode(R"HTML(<!DOCTYPE html> + <svg viewBox="0 0 800 600"> + <text id="container" x="50 100 150">̓▅̓▅<!-- + -->̓▅</text> + </svg>)HTML"); + BreakLines( + node, LayoutUnit::Max(), + [](const NGLineBreaker& line_breaker, const NGLineInfo& line_info) { + Vector<const NGInlineItemResult*> text_results; + for (const auto& result : line_info.Results()) { + if (result.item->Type() == NGInlineItem::kText) + text_results.push_back(&result); + } + EXPECT_EQ(4u, text_results.size()); + EXPECT_EQ(1u, text_results[0]->Length()); // U+0343 + EXPECT_EQ(1u, text_results[1]->Length()); // U+2585 + EXPECT_EQ(2u, text_results[2]->Length()); // U+0343 U+2585 + EXPECT_EQ(2u, text_results[3]->Length()); // U+0343 U+2585 + }); +} + // crbug.com/1214232 TEST_F(NGLineBreakerTest, GetOverhangCrash) { NGInlineNode node = CreateInlineNode(
diff --git a/third_party/blink/renderer/core/loader/frame_client_hints_preferences_context.cc b/third_party/blink/renderer/core/loader/frame_client_hints_preferences_context.cc index 072e319..e2223f9 100644 --- a/third_party/blink/renderer/core/loader/frame_client_hints_preferences_context.cc +++ b/third_party/blink/renderer/core/loader/frame_client_hints_preferences_context.cc
@@ -59,6 +59,13 @@ WebFeature::kClientHintsUAReduced}, {network::mojom::WebClientHintsType::kViewportHeight, WebFeature::kClientHintsViewportHeight}, + {network::mojom::WebClientHintsType::kDeviceMemory, + WebFeature::kClientHintsDeviceMemory}, + {network::mojom::WebClientHintsType::kDpr, WebFeature::kClientHintsDPR}, + {network::mojom::WebClientHintsType::kResourceWidth, + WebFeature::kClientHintsResourceWidth}, + {network::mojom::WebClientHintsType::kViewportWidth, + WebFeature::kClientHintsViewportWidth}, }; }
diff --git a/third_party/blink/renderer/core/paint/highlight_painting_utils.cc b/third_party/blink/renderer/core/paint/highlight_painting_utils.cc index 4dd902f4..822e954 100644 --- a/third_party/blink/renderer/core/paint/highlight_painting_utils.cc +++ b/third_party/blink/renderer/core/paint/highlight_painting_utils.cc
@@ -183,7 +183,6 @@ // Returns highlight styles for the given node, inheriting through the “tree” of // highlight pseudo styles mirroring the originating element tree. None of the // returned styles are influenced by originating elements or pseudo-elements. -// TODO(crbug.com/1024156): return const ComputedStyle& when dropping old impl? scoped_refptr<const ComputedStyle> HighlightPseudoStyle( Node* node, const ComputedStyle& style, @@ -194,6 +193,9 @@ pseudo_argument); } + if (!style.HighlightData()) + return nullptr; + switch (pseudo) { case kPseudoIdSelection: return style.HighlightData()->Selection();
diff --git a/third_party/blink/renderer/core/style/applied_text_decoration.cc b/third_party/blink/renderer/core/style/applied_text_decoration.cc index be0b4ec..6a5fba5 100644 --- a/third_party/blink/renderer/core/style/applied_text_decoration.cc +++ b/third_party/blink/renderer/core/style/applied_text_decoration.cc
@@ -4,8 +4,28 @@ #include "third_party/blink/renderer/core/style/applied_text_decoration.h" +#include <memory> +#include "third_party/blink/renderer/core/style/data_equivalency.h" +#include "third_party/blink/renderer/core/style/svg_paint.h" + namespace blink { +struct AppliedTextDecoration::TextDecorationSvgPaints { + const SVGPaint fill; + const SVGPaint stroke; + + TextDecorationSvgPaints(const SVGPaint& fill_arg, const SVGPaint& stroke_arg) + : fill(fill_arg), stroke(stroke_arg) {} + + bool operator==(const TextDecorationSvgPaints& other) const { + return fill == other.fill && stroke == other.stroke; + } + + bool operator!=(const TextDecorationSvgPaints& other) const { + return !(*this == other); + } +}; + AppliedTextDecoration::AppliedTextDecoration(TextDecoration line, ETextDecorationStyle style, Color color, @@ -18,9 +38,44 @@ thickness_(thickness), underline_offset_(underline_offset) {} +AppliedTextDecoration::AppliedTextDecoration(const AppliedTextDecoration& other) + : lines_(other.lines_), + style_(other.style_), + color_(other.color_), + thickness_(other.thickness_), + underline_offset_(other.underline_offset_), + svg_paints_(other.svg_paints_ ? std::make_unique<TextDecorationSvgPaints>( + *other.svg_paints_) + : nullptr) {} + +AppliedTextDecoration::~AppliedTextDecoration() = default; + +AppliedTextDecoration& AppliedTextDecoration::operator=( + const AppliedTextDecoration& other) { + lines_ = other.lines_; + style_ = other.style_; + color_ = other.color_; + thickness_ = other.thickness_; + underline_offset_ = other.underline_offset_; + svg_paints_.reset(); + if (other.svg_paints_) + svg_paints_ = std::make_unique<TextDecorationSvgPaints>(*other.svg_paints_); + return *this; +} + bool AppliedTextDecoration::operator==(const AppliedTextDecoration& o) const { + if (!DataEquivalent(svg_paints_, o.svg_paints_)) + return false; return color_ == o.color_ && lines_ == o.lines_ && style_ == o.style_ && thickness_ == o.thickness_ && underline_offset_ == o.underline_offset_; } +const SVGPaint& AppliedTextDecoration::Fill() const { + return svg_paints_->fill; +} + +const SVGPaint& AppliedTextDecoration::Stroke() const { + return svg_paints_->stroke; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/style/applied_text_decoration.h b/third_party/blink/renderer/core/style/applied_text_decoration.h index 66da48d..3f13d968 100644 --- a/third_party/blink/renderer/core/style/applied_text_decoration.h +++ b/third_party/blink/renderer/core/style/applied_text_decoration.h
@@ -13,7 +13,9 @@ namespace blink { -class AppliedTextDecoration { +struct SVGPaint; + +class CORE_EXPORT AppliedTextDecoration { DISALLOW_NEW(); public: @@ -22,13 +24,22 @@ Color, TextDecorationThickness, Length); + AppliedTextDecoration(const AppliedTextDecoration& other); + ~AppliedTextDecoration(); + AppliedTextDecoration& operator=(const AppliedTextDecoration& other); TextDecoration Lines() const { return static_cast<TextDecoration>(lines_); } ETextDecorationStyle Style() const { return static_cast<ETextDecorationStyle>(style_); } + // GetColor() should not be used for SVG elements. Use Fill() and + // Stroke() instead. Color GetColor() const { return color_; } void SetColor(Color color) { color_ = color; } + // Fill() and Stroke() should not be used for non-SVG elements. Use + // GetColor() instead. + const SVGPaint& Fill() const; + const SVGPaint& Stroke() const; TextDecorationThickness Thickness() const { return thickness_; } Length UnderlineOffset() const { return underline_offset_; } @@ -44,6 +55,10 @@ Color color_; TextDecorationThickness thickness_; Length underline_offset_; + + struct TextDecorationSvgPaints; + // svg_paints_ is not null if and only if this instance is for an SVG element. + std::unique_ptr<TextDecorationSvgPaints> svg_paints_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/style/computed_style.cc b/third_party/blink/renderer/core/style/computed_style.cc index b7fe29c..4aaff104 100644 --- a/third_party/blink/renderer/core/style/computed_style.cc +++ b/third_party/blink/renderer/core/style/computed_style.cc
@@ -152,11 +152,7 @@ } scoped_refptr<ComputedStyle> ComputedStyle::CreateInitialStyleSingleton() { - auto result = base::MakeRefCounted<ComputedStyle>(PassKey()); - - result->SetHighlightDataInternal(StyleHighlightData::Create(PassKey())); - - return result; + return base::MakeRefCounted<ComputedStyle>(PassKey()); } Vector<AtomicString>* ComputedStyle::GetVariableNamesCache() const { @@ -193,13 +189,6 @@ ALWAYS_INLINE ComputedStyle::ComputedStyle(PassKey key, const ComputedStyle& o) : ComputedStyle(o) {} -scoped_refptr<ComputedStyle> ComputedStyle::Create(PkStyleHighlightData) { - return base::AdoptRef(new ComputedStyle); -} -scoped_refptr<ComputedStyle> ComputedStyle::Copy(PkStyleHighlightData) const { - return base::AdoptRef(new ComputedStyle(PassKey(), *this)); -} - static bool PseudoElementStylesEqual(const ComputedStyle& old_style, const ComputedStyle& new_style) { if (!old_style.HasAnyPseudoElementStyles() && @@ -619,15 +608,13 @@ return nullptr; } -const scoped_refptr<StyleHighlightData>& ComputedStyle::HighlightData() const { - return HighlightDataInternal(); -} - -scoped_refptr<StyleHighlightData> ComputedStyle::MutableHighlightData() { - // TODO(crbug.com/1024156): why does this never end up cloning when done - // under a !HasOneRef condition (à la DataRef::Access)? - SetHighlightDataInternal(HighlightData()->Copy(PassKey())); - return HighlightData(); +StyleHighlightData& ComputedStyle::MutableHighlightData() { + scoped_refptr<StyleHighlightData>& data = MutableHighlightDataInternal(); + if (!data) + data = StyleHighlightData::Create(); + else if (!data->HasOneRef()) + data = data->Copy(); + return *data; } bool ComputedStyle::InheritedEqual(const ComputedStyle& other) const {
diff --git a/third_party/blink/renderer/core/style/computed_style.h b/third_party/blink/renderer/core/style/computed_style.h index 8b3a03a0..ab2e30e3 100644 --- a/third_party/blink/renderer/core/style/computed_style.h +++ b/third_party/blink/renderer/core/style/computed_style.h
@@ -298,12 +298,9 @@ public: using PassKey = base::PassKey<ComputedStyle>; - using PkStyleHighlightData = base::PassKey<StyleHighlightData>; ALWAYS_INLINE ComputedStyle(PassKey, const ComputedStyle&); ALWAYS_INLINE explicit ComputedStyle(PassKey); - static scoped_refptr<ComputedStyle> Create(PkStyleHighlightData); - scoped_refptr<ComputedStyle> Copy(PkStyleHighlightData) const; // Create the per-document/context singleton that is used for shallow-copying // into new instances. @@ -419,8 +416,7 @@ return this; } - const scoped_refptr<StyleHighlightData>& HighlightData() const; - scoped_refptr<StyleHighlightData> MutableHighlightData(); + StyleHighlightData& MutableHighlightData(); /** * ComputedStyle properties
diff --git a/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 b/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 index b9b4d1a..b60c53ec 100644 --- a/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 +++ b/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
@@ -502,7 +502,7 @@ default_value: "nullptr", wrapper_pointer_name: "scoped_refptr", field_group: "*", - computed_style_custom_functions: ["getter", "setter"], + computed_style_custom_functions: ["setter"], }, { name: "InitialData",
diff --git a/third_party/blink/renderer/core/style/style_highlight_data.cc b/third_party/blink/renderer/core/style/style_highlight_data.cc index 4fd7cdf3..dbc7f3d7 100644 --- a/third_party/blink/renderer/core/style/style_highlight_data.cc +++ b/third_party/blink/renderer/core/style/style_highlight_data.cc
@@ -8,27 +8,14 @@ namespace blink { -StyleHighlightData::StyleHighlightData(PkComputedStyle) - : StyleHighlightData() {} -StyleHighlightData::StyleHighlightData(PkComputedStyle, - const StyleHighlightData& other) - : StyleHighlightData(other) {} -scoped_refptr<StyleHighlightData> StyleHighlightData::Create(PkComputedStyle) { +scoped_refptr<StyleHighlightData> StyleHighlightData::Create() { return base::AdoptRef(new StyleHighlightData); } -scoped_refptr<StyleHighlightData> StyleHighlightData::Copy( - PkComputedStyle) const { +scoped_refptr<StyleHighlightData> StyleHighlightData::Copy() const { return base::AdoptRef(new StyleHighlightData(*this)); } -StyleHighlightData::StyleHighlightData() { - // Call the internal ctor, *not* CreateInitialStyleSingleton or similar, to - // avoid an infinite tree of StyleHighlightData under each highlight style. - selection_ = ComputedStyle::Create(PassKey()); - target_text_ = ComputedStyle::Create(PassKey()); - spelling_error_ = ComputedStyle::Create(PassKey()); - grammar_error_ = ComputedStyle::Create(PassKey()); -} +StyleHighlightData::StyleHighlightData() = default; StyleHighlightData::StyleHighlightData(const StyleHighlightData& other) // TODO(crbug.com/1024156): init field for ::highlight() @@ -44,19 +31,23 @@ grammar_error_ == other.grammar_error_; } -const scoped_refptr<ComputedStyle>& StyleHighlightData::Selection() const { +const scoped_refptr<const ComputedStyle>& StyleHighlightData::Selection() + const { return selection_; } -const scoped_refptr<ComputedStyle>& StyleHighlightData::TargetText() const { +const scoped_refptr<const ComputedStyle>& StyleHighlightData::TargetText() + const { return target_text_; } -const scoped_refptr<ComputedStyle>& StyleHighlightData::SpellingError() const { +const scoped_refptr<const ComputedStyle>& StyleHighlightData::SpellingError() + const { return spelling_error_; } -const scoped_refptr<ComputedStyle>& StyleHighlightData::GrammarError() const { +const scoped_refptr<const ComputedStyle>& StyleHighlightData::GrammarError() + const { return grammar_error_; }
diff --git a/third_party/blink/renderer/core/style/style_highlight_data.h b/third_party/blink/renderer/core/style/style_highlight_data.h index a9c493c..a894c89 100644 --- a/third_party/blink/renderer/core/style/style_highlight_data.h +++ b/third_party/blink/renderer/core/style/style_highlight_data.h
@@ -20,25 +20,20 @@ class CORE_EXPORT StyleHighlightData final : public RefCounted<StyleHighlightData> { public: - using PassKey = base::PassKey<StyleHighlightData>; - using PkComputedStyle = base::PassKey<ComputedStyle>; - StyleHighlightData(StyleHighlightData&& other) = delete; StyleHighlightData& operator=(const StyleHighlightData& other) = delete; StyleHighlightData& operator=(StyleHighlightData&& other) = delete; - explicit StyleHighlightData(PkComputedStyle); - StyleHighlightData(PkComputedStyle, const StyleHighlightData& other); - static scoped_refptr<StyleHighlightData> Create(PkComputedStyle); - scoped_refptr<StyleHighlightData> Copy(PkComputedStyle) const; + static scoped_refptr<StyleHighlightData> Create(); + scoped_refptr<StyleHighlightData> Copy() const; bool operator==(const StyleHighlightData&) const; // TODO(crbug.com/1024156): add methods for ::highlight() - const scoped_refptr<ComputedStyle>& Selection() const; - const scoped_refptr<ComputedStyle>& TargetText() const; - const scoped_refptr<ComputedStyle>& SpellingError() const; - const scoped_refptr<ComputedStyle>& GrammarError() const; + const scoped_refptr<const ComputedStyle>& Selection() const; + const scoped_refptr<const ComputedStyle>& TargetText() const; + const scoped_refptr<const ComputedStyle>& SpellingError() const; + const scoped_refptr<const ComputedStyle>& GrammarError() const; void SetSelection(scoped_refptr<ComputedStyle>&&); void SetTargetText(scoped_refptr<ComputedStyle>&&); void SetSpellingError(scoped_refptr<ComputedStyle>&&); @@ -49,10 +44,10 @@ StyleHighlightData(const StyleHighlightData& other); // TODO(crbug.com/1024156): add field for ::highlight() - scoped_refptr<ComputedStyle> selection_; - scoped_refptr<ComputedStyle> target_text_; - scoped_refptr<ComputedStyle> spelling_error_; - scoped_refptr<ComputedStyle> grammar_error_; + scoped_refptr<const ComputedStyle> selection_; + scoped_refptr<const ComputedStyle> target_text_; + scoped_refptr<const ComputedStyle> spelling_error_; + scoped_refptr<const ComputedStyle> grammar_error_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/webtransport/web_transport_close_info.idl b/third_party/blink/renderer/modules/webtransport/web_transport_close_info.idl index b419141..6a90c69 100644 --- a/third_party/blink/renderer/modules/webtransport/web_transport_close_info.idl +++ b/third_party/blink/renderer/modules/webtransport/web_transport_close_info.idl
@@ -5,6 +5,6 @@ // https://wicg.github.io/web-transport/#dictdef-webtransportcloseinfo dictionary WebTransportCloseInfo { - unsigned short errorCode = 0; - DOMString reason = ""; + unsigned long closeCode; + DOMString reason; };
diff --git a/third_party/blink/renderer/modules/webtransport/web_transport_test.cc b/third_party/blink/renderer/modules/webtransport/web_transport_test.cc index 8673d62..1a4ff8f 100644 --- a/third_party/blink/renderer/modules/webtransport/web_transport_test.cc +++ b/third_party/blink/renderer/modules/webtransport/web_transport_test.cc
@@ -568,7 +568,7 @@ web_transport->closed()); WebTransportCloseInfo close_info; - close_info.setErrorCode(42); + close_info.setCloseCode(42); close_info.setReason("because"); web_transport->close(&close_info); @@ -585,6 +585,44 @@ web_transport->close(nullptr); } +TEST_F(WebTransportTest, CloseWithNull) { + V8TestingScope scope; + auto* web_transport = + CreateAndConnectSuccessfully(scope, "https://example.com"); + ScriptPromiseTester ready_tester(scope.GetScriptState(), + web_transport->ready()); + ScriptPromiseTester closed_tester(scope.GetScriptState(), + web_transport->closed()); + + web_transport->close(nullptr); + + test::RunPendingTasks(); + + EXPECT_FALSE(web_transport->HasPendingActivity()); + EXPECT_TRUE(ready_tester.IsFulfilled()); + EXPECT_TRUE(closed_tester.IsFulfilled()); + + // TODO(yhirano): Make sure Close() is called. +} + +TEST_F(WebTransportTest, CloseWithReasonOnly) { + V8TestingScope scope; + auto* web_transport = + CreateAndConnectSuccessfully(scope, "https://example.com"); + ScriptPromiseTester ready_tester(scope.GetScriptState(), + web_transport->ready()); + ScriptPromiseTester closed_tester(scope.GetScriptState(), + web_transport->closed()); + + WebTransportCloseInfo close_info; + close_info.setReason("because"); + web_transport->close(&close_info); + + test::RunPendingTasks(); + + // TODO(yhirano): Make sure Close() is called. +} + // A live connection will be kept alive even if there is no explicit reference. // When the underlying connection is shut down, the connection will be swept. TEST_F(WebTransportTest, GarbageCollection) { @@ -1701,7 +1739,7 @@ ScriptPromiseTester tester(script_state, web_transport->closed()); absl::optional<WebTransportCloseInfo> input_close_info(absl::in_place); - input_close_info->setErrorCode(99); + input_close_info->setCloseCode(99); input_close_info->setReason("reason"); web_transport->OnClosed(input_close_info); @@ -1714,9 +1752,9 @@ ASSERT_TRUE(value.IsObject()); WebTransportCloseInfo* close_info = WebTransportCloseInfo::Create( isolate, value.V8Value(), ASSERT_NO_EXCEPTION); - EXPECT_TRUE(close_info->hasErrorCode()); + EXPECT_TRUE(close_info->hasCloseCode()); EXPECT_TRUE(close_info->hasReason()); - EXPECT_EQ(close_info->errorCode(), 99); + EXPECT_EQ(close_info->closeCode(), 99u); EXPECT_EQ(close_info->reason(), "reason"); } @@ -1740,9 +1778,8 @@ ASSERT_TRUE(value.IsObject()); WebTransportCloseInfo* close_info = WebTransportCloseInfo::Create( isolate, value.V8Value(), ASSERT_NO_EXCEPTION); - // TODO(yhirano): `close_info` should be empty but actually not because of the - // IDL definition for WebTransportCloseInfo. Fix that. - DCHECK(close_info); + EXPECT_FALSE(close_info->hasCloseCode()); + EXPECT_FALSE(close_info->hasReason()); } } // namespace
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc index 2477fee..06d25bb5 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
@@ -87,7 +87,7 @@ // Delay constructing the compositor until after the feature is set. paint_artifact_compositor_ = std::make_unique<PaintArtifactCompositor>( scroll_callbacks_.GetWeakPtr()); - // Prefer compositing to lcd-text by default for tests. + // Prefer lcd-text by default for tests. paint_artifact_compositor_->SetPrefersLCDText(true); // Uses a LayerTreeHostClient that will make a LayerTreeFrameSink to allow
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 417b6854d..d6774ee 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1817,7 +1817,7 @@ }, { name: "PriorityHints", - origin_trial_feature_name: "PriorityHints", + origin_trial_feature_name: "PriorityHintsAPI", status: "experimental", }, { @@ -1962,7 +1962,7 @@ }, { name: "ScriptElementSupports", - status: "experimental", + status: "stable", }, { name: "ScrollbarGutter",
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 2e4565f6..54302cf 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -2847,10 +2847,15 @@ crbug.com/626703 virtual/plz-dedicated-worker/external/wpt/service-workers/service-worker/worker-interception.https.html [ Pass ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 [ Linux ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Crash ] +crbug.com/626703 [ Mac10.15 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Crash ] +crbug.com/626703 external/wpt/css/css-transforms/transform-fixed-bg-005.html [ Failure ] +crbug.com/626703 virtual/backface-visibility-interop/external/wpt/css/css-transforms/transform-fixed-bg-005.html [ Failure ] +crbug.com/626703 virtual/transform-interop-disabled/external/wpt/css/css-transforms/transform-fixed-bg-005.html [ Failure ] crbug.com/626703 [ Linux ] external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] -crbug.com/626703 [ Mac10.14 ] external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] +crbug.com/626703 [ Mac ] external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] crbug.com/626703 [ Linux ] virtual/synchronous_html_parser/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] -crbug.com/626703 [ Mac10.14 ] virtual/synchronous_html_parser/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] +crbug.com/626703 [ Mac ] virtual/synchronous_html_parser/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html [ Timeout ] crbug.com/626703 [ Linux ] virtual/coep-for-shared-worker/external/wpt/html/cross-origin-embedder-policy/reporting-subresource-corp.https.html [ Skip Timeout ] crbug.com/626703 [ Mac11.0 ] virtual/coep-for-shared-worker/external/wpt/html/cross-origin-embedder-policy/reporting-subresource-corp.https.html [ Skip Timeout ] crbug.com/626703 [ Linux ] external/wpt/css/css-flexbox/dynamic-isize-change-002.html [ Crash ] @@ -4232,6 +4237,8 @@ crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-network-error.https.tentative.html [ Skip ] crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-not-found.https.tentative.html [ Skip ] crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-path-restriction.https.tentative.html [ Skip ] +crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle-cors.https.tentative.sub.html [ Skip ] +crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle.https.tentative.html [ Skip ] crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-relative-url.https.tentative.html [ Skip ] crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-relative-url-with-base.https.tentative.html [ Skip ] crbug.com/1245166 external/wpt/web-bundle/subresource-loading/script-request-destination.https.tentative.html [ Skip ] @@ -4644,11 +4651,6 @@ #Sheriff 2018-10-23 crbug.com/898378 [ Mac10.13 ] fast/scroll-behavior/smooth-scroll/keyboard-scroll.html [ Timeout ] -# Sheriff 2018-10-26 -### See crbug.com/891427 comment near the top of this file: -####crbug.com/899087 [ Linux ] virtual/android/fullscreen/full-screen-iframe-allowed-video.html [ Failure Pass ] - - # Sheriff 2018-10-29 crbug.com/766357 [ Win ] virtual/threaded-prefer-compositing/fast/scrolling/wheel-and-touch-scroll-use-count.html [ Failure Pass ] @@ -6662,7 +6664,13 @@ # Sheriff 2021-07-29 crbug.com/626703 http/tests/security/cross-frame-access-put.html [ Failure Pass ] -crbug.com/626703 virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Fuchsia ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Mac10.12 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Mac10.13 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Mac10.14 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Mac11-arm64 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Mac11.0 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] +crbug.com/626703 [ Win ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-start-delay.https.html [ Failure Pass ] crbug.com/626703 virtual/oopr-canvas2d/fast/canvas/canvas-composite-canvas.html [ Failure Pass ] # Sheriff 2021-07-30
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 688eba8..6617e6c 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -64,6 +64,7 @@ { "prefix": "prefer_compositing_to_lcd_text", "bases": ["compositing/overflow", + "compositing/squashing/keep-lcd-text.html", "scrollbars"], "args": ["--enable-prefer-compositing-to-lcd-text"] },
diff --git a/third_party/blink/web_tests/compositing/squashing/keep-lcd-text-expected.txt b/third_party/blink/web_tests/compositing/squashing/keep-lcd-text-expected.txt new file mode 100644 index 0000000..47f9e1c --- /dev/null +++ b/third_party/blink/web_tests/compositing/squashing/keep-lcd-text-expected.txt
@@ -0,0 +1,21 @@ +{ + "layers": [ + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='composited'", + "bounds": [300, 300], + "drawsContent": false + }, + { + "name": "Squashing Layer (first squashed layer: LayoutNGBlockFlow (positioned) DIV id='non-opaque')", + "bounds": [220, 270], + "backgroundColor": "#FFFF00" + } + ] +} +
diff --git a/third_party/blink/web_tests/compositing/squashing/keep-lcd-text.html b/third_party/blink/web_tests/compositing/squashing/keep-lcd-text.html new file mode 100644 index 0000000..402e6d89 --- /dev/null +++ b/third_party/blink/web_tests/compositing/squashing/keep-lcd-text.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<body style="margin: 0"> +<div id="composited" style="position: absolute; will-change: transform; width: 300px; height: 300px"></div> +<div id="non-opaque" style="position: absolute; width: 200px; height: 100px; padding: 10px">NON-OPAQUE</div> +<div id="opaque" style="position: absolute; top: 50px; width: 200px; height: 200px; padding: 10px; background: yellow">OPAQUE</div> +<script> +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.setCustomTextOutput(internals.layerTreeAsText(document)); +} +</script> +</body>
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index ffccb82..bbc69ad0 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -2554,35 +2554,35 @@ }, "display-override-member": { "display-override-member-media-feature-browser-manual.tentative.html": [ - "8bc5b11896a5483d8c9b7db943b13e1ae6a6298c", + "d13d0986ad0c6d7aa193c0f8e26f193941ae98e7", [ null, {} ] ], "display-override-member-media-feature-fullscreen-manual.tentative.html": [ - "b3cc4d396a6f5b1cac2385f6b4edba09d0238670", + "0b9923f8bd4ded2fb7af6cd8fff4e24fc3b10cd9", [ null, {} ] ], "display-override-member-media-feature-minimal-ui-manual.tentative.html": [ - "1b69b2d469ba7cb8634a66454a4c46919efe378f", + "5b9d63977d3e1a7d681101c7cb8bd0aeb5adb50f", [ null, {} ] ], "display-override-member-media-feature-standalone-manual.tentative.html": [ - "bccba1f90e559ac820478d7f84eea70e668e2710", + "db1ed389294fae0f56858f978fee83009daf07e4", [ null, {} ] ], "display-override-member-media-feature-standalone-overrides-browser-manual.tentative.html": [ - "e91ea4e331423fa91647717bdad899ba3dfdffc2", + "d42feb3fe2f9bf66f2227d03c5392e3f255aac44", [ null, {} @@ -166755,7 +166755,7 @@ ] ], "transform-fixed-bg-001.html": [ - "39a6baa2d14a462464e365fcc4d7cb97a4314233", + "5198d09cc36d4071e6ac20374b091762674781ae", [ null, [ @@ -166768,7 +166768,7 @@ ] ], "transform-fixed-bg-002.html": [ - "a1a34d7d83189bc166cbd62ed627dede39a37329", + "37b4975dc27a4060564000c3f13ee5ffc54ffdc4", [ null, [ @@ -166781,7 +166781,7 @@ ] ], "transform-fixed-bg-003.html": [ - "e00266a7124a03d92d726431b2fdbd10474405b8", + "8b03f3d6d47c3d72dbcf5d29cfdc1b4075e3bd48", [ null, [ @@ -166794,7 +166794,7 @@ ] ], "transform-fixed-bg-004.html": [ - "8ca1a8cb5ff038fa70678679df753e27754ec128", + "2e180b84c525489df060b635781612245516a25a", [ null, [ @@ -166807,7 +166807,7 @@ ] ], "transform-fixed-bg-005.html": [ - "ac1f5b0943c8d4689fbc29260c6f23d7f720b450", + "c4cd1c264292e99210c391c42925cbecb336f855", [ null, [ @@ -166820,7 +166820,7 @@ ] ], "transform-fixed-bg-006.html": [ - "4668e3c85c5484164bada59366bd1c5e7bc789f1", + "e5ca7d5285eaf1877ee5e466a3c3ab97126614f1", [ null, [ @@ -166833,7 +166833,7 @@ ] ], "transform-fixed-bg-007.html": [ - "ade998ba83a9ea409f6a5bee39e8ecc276dbc1cb", + "be6e9f77b9fb130004cbdbb30c6ccdcc18d04fd6", [ null, [ @@ -214577,46 +214577,60 @@ } }, "display-override-member": { - "display-override-member-media-feature-browser.webmanifest": [ - "f65c7de9add9031d190d1179c046daf70f42128e", + "display-override-member-media-feature-service-worker.js": [ + "eec0d9972d00be2dd853bbd6ca952883f7ffe054", [] ], - "display-override-member-media-feature-browser.webmanifest.headers": [ - "2bab061d43ab9e533b0160ca506231939886cd89", - [] - ], - "display-override-member-media-feature-fullscreen.webmanifest": [ - "c43856c8a2104d1a2bf88a2c005090ab5a8d0844", - [] - ], - "display-override-member-media-feature-fullscreen.webmanifest.headers": [ - "2bab061d43ab9e533b0160ca506231939886cd89", - [] - ], - "display-override-member-media-feature-minimal-ui.webmanifest": [ - "68fcc760ca454496b7527009c744969024f321cb", - [] - ], - "display-override-member-media-feature-minimal-ui.webmanifest.headers": [ - "2bab061d43ab9e533b0160ca506231939886cd89", - [] - ], - "display-override-member-media-feature-standalone-overrides-browser.webmanifest": [ - "0f33e3b82c032de5a41a283ce08d07cef7881d6f", - [] - ], - "display-override-member-media-feature-standalone-overrides-browser.webmanifest.headers": [ - "2bab061d43ab9e533b0160ca506231939886cd89", - [] - ], - "display-override-member-media-feature-standalone.webmanifest": [ - "c6f4b66b6f9378cea5dace0af6ce5802ec007b24", - [] - ], - "display-override-member-media-feature-standalone.webmanifest.headers": [ - "2bab061d43ab9e533b0160ca506231939886cd89", - [] - ] + "resources": { + "display-override-member-media-feature-browser.webmanifest": [ + "a384f6f2c89560484acb9300cc0e2358da304b92", + [] + ], + "display-override-member-media-feature-browser.webmanifest.headers": [ + "2bab061d43ab9e533b0160ca506231939886cd89", + [] + ], + "display-override-member-media-feature-fullscreen.webmanifest": [ + "70cad0a0ca1ba567fac11d406079e8df69210d6c", + [] + ], + "display-override-member-media-feature-fullscreen.webmanifest.headers": [ + "2bab061d43ab9e533b0160ca506231939886cd89", + [] + ], + "display-override-member-media-feature-manual.js": [ + "eca350245fd5c338884c0f43ac1dc1460f6d528f", + [] + ], + "display-override-member-media-feature-minimal-ui.webmanifest": [ + "474f58526b7a4b6a28ef2d2fd893919eec3ca931", + [] + ], + "display-override-member-media-feature-minimal-ui.webmanifest.headers": [ + "2bab061d43ab9e533b0160ca506231939886cd89", + [] + ], + "display-override-member-media-feature-standalone-overrides-browser.webmanifest": [ + "dcdd293ab7a46079178c53faf4c7642ef0d185cc", + [] + ], + "display-override-member-media-feature-standalone-overrides-browser.webmanifest.headers": [ + "2bab061d43ab9e533b0160ca506231939886cd89", + [] + ], + "display-override-member-media-feature-standalone.webmanifest": [ + "dfd6b77a25bfd01dac44b6fa974b4946e097f41f", + [] + ], + "display-override-member-media-feature-standalone.webmanifest.headers": [ + "2bab061d43ab9e533b0160ca506231939886cd89", + [] + ], + "icon.png": [ + "637cc8daf463d1fcebe14cadb7d5eae90a5b67fe", + [] + ] + } }, "file_handlers-member": { "file_handlers-member-service-worker.js": [ @@ -253536,7 +253550,7 @@ [] ], "transform-fixed-bg-ref.html": [ - "ba46b847a34aa1f7dde3b46c457e7292d4c7a016", + "fa579319dcf4a519bdb3d88155f5897b23a153f8", [] ], "transform-generated-001-notref.html": [ @@ -284906,19 +284920,19 @@ ] }, "webtransport-h3.sub.any-expected.txt": [ - "c581aa017641fc0d8a19863f3bb59d701375cb3e", + "6b34f70cf89a9c4f45443f4982cda7aaf3f2630a", [] ], "webtransport-h3.sub.any.serviceworker-expected.txt": [ - "c581aa017641fc0d8a19863f3bb59d701375cb3e", + "6b34f70cf89a9c4f45443f4982cda7aaf3f2630a", [] ], "webtransport-h3.sub.any.sharedworker-expected.txt": [ - "c581aa017641fc0d8a19863f3bb59d701375cb3e", + "6b34f70cf89a9c4f45443f4982cda7aaf3f2630a", [] ], "webtransport-h3.sub.any.worker-expected.txt": [ - "c581aa017641fc0d8a19863f3bb59d701375cb3e", + "6b34f70cf89a9c4f45443f4982cda7aaf3f2630a", [] ] }, @@ -299980,7 +299994,7 @@ ] }, "generate-test-wbns.sh": [ - "c92fae0b83d7c70326929992980f7b2984f613ff", + "9e2383577b348ed2245105309974eede04bf4438", [] ], "location": { @@ -300041,6 +300055,10 @@ ] } }, + "relative-url.har": [ + "e42e85fd1f94c35f8a597c16f97d07d3347425b5", + [] + ], "static-element": { "out-of-scope": { "script.js": [ @@ -300190,6 +300208,14 @@ "66381aaaf416c034eb09eafb1cab0dd80afbf0aa", [] ], + "relative-url.wbn": [ + "13924fdb994f970ed941dcfdf4ac1d4454a20a96", + [] + ], + "relative-url.wbn.sub.headers": [ + "ce4780f454082d39cfe793a5724bc79db864b9bd", + [] + ], "static-element": { "out-of-scope": { "script.js": [ @@ -300286,6 +300312,14 @@ "d55aca3fdfba4d15c86ab3459578f33c848debed", [] ], + "relative-url-in-web-bundle-cors-test.js": [ + "60450d072ac11b8fb19a76124bcef8246abf7674", + [] + ], + "relative-url-in-web-bundle-test.js": [ + "ba0d4a1effd7c8b9b95de398a7a67d47bac64ac2", + [] + ], "relative-url-test.js": [ "fa78a4a16204573f3be2a58205902b59c8c2486b", [] @@ -495792,6 +495826,20 @@ {} ] ], + "link-relative-url-in-web-bundle-cors.https.tentative.sub.html": [ + "340a65a150cf208b8a8282f287c97f32b2459fb2", + [ + null, + {} + ] + ], + "link-relative-url-in-web-bundle.https.tentative.html": [ + "460c48a21f866af1afae3ba6445366fa46b14ce3", + [ + null, + {} + ] + ], "link-relative-url-with-base.https.tentative.html": [ "07ba9159e9b5008fc3f4dce6178bb55bcf0142e0", [ @@ -495904,6 +495952,20 @@ {} ] ], + "script-relative-url-in-web-bundle-cors.https.tentative.sub.html": [ + "40114c7c5999a8499d017f8598f8cd6ea9603485", + [ + null, + {} + ] + ], + "script-relative-url-in-web-bundle.https.tentative.html": [ + "37a896b4828b97c56e7d7cd4c9d4c3cb63483c92", + [ + null, + {} + ] + ], "script-relative-url-with-base.https.tentative.html": [ "5732a0935ec6a20a76a531688084ee1ba016eafe", [ @@ -516513,7 +516575,7 @@ ] ], "constructor.any.js": [ - "1aef6fe18d7854bdc7a35b3513a14a516fe3140e", + "4312eb32857b621e7d855bbe1998d7e8d53906f7", [ "webtransport/constructor.any.html", {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004-ref.html b/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004-ref.html new file mode 100644 index 0000000..f9bf83f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004-ref.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<title>Initial custom property values in div::selection rule</title> +<link rel="help" href="https://drafts.csswg.org/css-pseudo-4/#highlight-cascade"> +<script src="support/selections.js"></script> +<style> + div::selection { + background-color: green; + } +</style> +<div>PASS if background-color is green when selected</div> +<script> + selectNodeContents(document.querySelector("div")); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004.html b/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004.html new file mode 100644 index 0000000..eb18109 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-pseudo/highlight-cascade-004.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<title>Initial custom property values in div::selection rule</title> +<link rel="help" href="https://drafts.csswg.org/css-pseudo-4/#highlight-cascade"> +<link rel="match" href="highlight-cascade-004-ref.html"> +<meta name="assert" value="This test verifies that the initial value given in a custom property registration is respected, when the property is referenced in ::selection styles but no value is defined. The initial value is not the guaranteed-invalid value, so the fallback value in var() is not used."> +<script src="support/selections.js"></script> +<style> + @property --bg { + syntax: "<color>"; + inherits: false; + initial-value: green; + } + div::selection { + background-color: var(--bg, red); + } +</style> +<div>PASS if background-color is green when selected</div> +<script> + selectNodeContents(document.querySelector("div")); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-001.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-001.html index 39a6baa2..5198d09 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-001.html
@@ -3,13 +3,15 @@ <head> <title>CSS Test (Transforms): Fixed Background</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> - <meta name="assert" content='"Fixed backgrounds are affected by any - transform specified for the root element, and not by any other transforms." - Thus if we have a div that's 100px square aligned at the top left of - the page, giving it a fixed background and translating it 50px down and - right should be the same as giving it a non-fixed background that's - translated 50px down and right.'> + <meta name="assert" content='"Fixed backgrounds on the root element are + affected by any transform specified for that element. For all other + elements that are effected by a transform (i.e. have a transform applied + to them, or to any of their ancestor elements), a value of fixed for the + background-attachment property is treated as if it had a value of + scroll."'> <meta name="flags" content="svg"> <link rel="match" href="transform-fixed-bg-ref.html"> <style>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-002.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-002.html index a1a34d7d8..37b4975 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-002.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-002.html
@@ -3,12 +3,16 @@ <head> <title>CSS Test (Transforms): Fixed Background (with scrolling)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> - <meta name="assert" content='"Fixed backgrounds are affected by any - transform specified for the root element, and not by any other transforms." + <meta name="assert" content='"Fixed backgrounds on the root element are + affected by any transform specified for that element. For all other + elements that are effected by a transform (i.e. have a transform applied + to them, or to any of their ancestor elements), a value of fixed for the + background-attachment property is treated as if it had a value of scroll." Here we translate the div 150px down instead of 50px, and also scroll down - 100px. This should be the same as the previous test because the background - image is 100px square.'> + 100px. This should be the same as the previous test.'> <meta name="flags" content="svg dom"> <link rel="match" href="transform-fixed-bg-ref.html"> <style>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-003.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-003.html index e00266a..8b03f3d6 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-003.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-003.html
@@ -3,6 +3,8 @@ <head> <title>CSS Test (Transforms): Fixed Background (with rotation)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> <meta name="assert" content='This is the same as transform-fixed-bg-001, except that we also test that a rotation on a non-root element doesn't @@ -14,7 +16,7 @@ margin: 0; } div { - background: url(support/transform-triangle-left.svg) fixed; + background: url(support/transform-triangle-down.svg) fixed; width: 100px; height: 100px; transform: translate(50px, 50px) rotate(90deg);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-004.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-004.html index 8ca1a8c..2e180b84 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-004.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-004.html
@@ -3,6 +3,8 @@ <head> <title>CSS Test (Transforms): Fixed Background (with rotation and scrolling)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> <meta name="assert" content='This is the same as transform-fixed-bg-002, except that we also test that a rotation on a non-root element doesn't @@ -16,7 +18,7 @@ overflow: hidden; } div { - background: url(support/transform-triangle-left.svg) fixed; + background: url(support/transform-triangle-down.svg) fixed; width: 100px; height: 100px; transform: translate(50px, 150px) rotate(90deg);
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-005.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-005.html index ac1f5b0..c4cd1c26 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-005.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-005.html
@@ -3,9 +3,16 @@ <head> <title>CSS Test (Transforms): Fixed Background (no-op transform)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> - <meta name="assert" content='This affects that adding a no-op transform to - an element with a fixed background doesn't affect rendering.'> + <meta name="assert" content='"Fixed backgrounds on the root element are + affected by any transform specified for that element. For all other + elements that are effected by a transform (i.e. have a transform applied + to them, or to any of their ancestor elements), a value of fixed for the + background-attachment property is treated as if it had a value of scroll." + This tests that adding a no-op transform to an element with a fixed + background doesn't change rendering from scroll background.'> <meta name="flags" content="svg"> <link rel="match" href="transform-fixed-bg-ref.html"> <style>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-006.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-006.html index 4668e3c8..e5ca7d5 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-006.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-006.html
@@ -3,10 +3,17 @@ <head> <title>CSS Test (Transforms): Fixed Background (transform of intermediate)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> - <meta name="assert" content='This tests that adding a rotation to a - non-root element doesn't affect rendering of fixed backgrounds on its - descendants.'> + <meta name="assert" content='"Fixed backgrounds on the root element are + affected by any transform specified for that element. For all other + elements that are effected by a transform (i.e. have a transform applied + to them, or to any of their ancestor elements), a value of fixed for the + background-attachment property is treated as if it had a value of scroll." + This tests that adding a rotation to a non-root element doesn't + change rendering of fixed backgrounds on its descendants relative to what + they would be if background-attachment: scroll.'> <meta name="flags" content="svg"> <link rel="match" href="transform-fixed-bg-ref.html"> <style> @@ -17,7 +24,7 @@ overflow: hidden; } div { - background: url(support/transform-triangle-left.svg) fixed; + background: url(support/transform-triangle-down.svg) fixed; width: 100px; height: 100px; position: relative;
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-007.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-007.html index ade998b..be6e9f7 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-007.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-007.html
@@ -3,10 +3,17 @@ <head> <title>CSS Test (Transforms): Fixed Background (transform on root)</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-rendering"> - <meta name="assert" content='This tests that a transform on the root - element *does* affect the rendering of fixed backgrounds on its - descendants.'> + <meta name="assert" content='"Fixed backgrounds on the root element are + affected by any transform specified for that element. For all other + elements that are effected by a transform (i.e. have a transform applied + to them, or to any of their ancestor elements), a value of fixed for the + background-attachment property is treated as if it had a value of scroll." + This tests that a transform on the root element still leads fixed + backgrounds on descendants to act as though they were scrolled + backgrounds.'> <meta name="flags" content="svg"> <link rel="match" href="transform-fixed-bg-ref.html"> <style>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-ref.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-ref.html index ba46b847..fa57931 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform-fixed-bg-ref.html
@@ -3,12 +3,14 @@ <head> <title>CSS Reftest Reference</title> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="author" title="L. David Baron" href="https://dbaron.org/"> + <link rel="author" title="Google" href="http://www.google.com/"> <style> body { margin: 0; } div { - background: url(support/transform-triangle-left.svg) 50px 50px; + background: url(support/transform-triangle-left.svg); width: 100px; height: 100px; position: relative;
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh b/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh index c92fae0..9e23835 100755 --- a/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/generate-test-wbns.sh
@@ -95,3 +95,9 @@ -har non-utf8-query-encoding.har \ -primaryURL $wpt_test_origin/web-bundle/resources/wbn/static-element/resources/script.js?x=%A4%A2 \ -o wbn/non-utf8-query-encoding.wbn + +gen-bundle \ + -version b2 \ + -har relative-url.har \ + -o wbn/relative-url.wbn +
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/relative-url.har b/third_party/blink/web_tests/external/wpt/web-bundle/resources/relative-url.har new file mode 100644 index 0000000..e42e85f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/relative-url.har
@@ -0,0 +1,139 @@ +{ + "log": { + "entries": [ + { + "request": { + "method": "GET", + "url": "relative-url-file.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('relative-url-file.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "//web-platform.test:8444/web-bundle/resources/wbn/relative-url/start-with-double-slash.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('start-with-double-slash.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "//www1.web-platform.test:8444/web-bundle/resources/wbn/relative-url/start-with-double-slash-cors.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('start-with-double-slash-cors.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "/web-bundle/resources/wbn/relative-url/start-with-slash.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('start-with-slash.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "relative-url/subdirectory-path.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('subdirectory-path.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "../wbn/starts-with-two-dots.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('starts-with-two-dots.js');" + } + } + }, + { + "request": { + "method": "GET", + "url": "../starts-with-two-dots-out-of-scope.js", + "headers": [] + }, + "response": { + "status": 200, + "headers": [ + { + "name": "Content-type", + "value": "text/javascript" + } + ], + "content": { + "text": "scriptLoaded('starts-with-two-dots-out-of-scope.js');" + } + } + } + ] + } +} \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn new file mode 100644 index 0000000..13924fdb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn.sub.headers b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn.sub.headers new file mode 100644 index 0000000..ce4780f4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/resources/wbn/relative-url.wbn.sub.headers
@@ -0,0 +1,3 @@ +Content-Type: application/webbundle +X-Content-Type-Options: nosniff +Access-Control-Allow-Origin: https://{{domains[]}}:{{ports[https][0]}}
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle-cors.https.tentative.sub.html b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle-cors.https.tentative.sub.html new file mode 100644 index 0000000..340a65a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle-cors.https.tentative.sub.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<title>Relative Url in cross origin web bundle</title> +<link rel="help" href="https://github.com/WICG/webpackage/blob/main/explainers/subresource-loading.md" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/test-helpers.js"></script> + +<body> + <link + rel="webbundle" + href="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url.wbn" + resources=" + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url-file.js + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-double-slash-cors.js + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-slash.js + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/subdirectory-path.js + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/starts-with-two-dots.js + //{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/starts-with-two-dots-out-of-scope.js + " /> + <script> + const loaded_scripts = []; + function scriptLoaded(file) { + loaded_scripts.push(file); + } + const failed_scripts = []; + function scriptFailed(file) { + failed_scripts.push(file); + } + </script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url-file.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-double-slash-cors.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-slash.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/subdirectory-path.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/starts-with-two-dots.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/starts-with-two-dots-out-of-scope.js" + onerror="scriptFailed('starts-with-two-dots-out-of-scope.js')"></script> + + <script src="resources/relative-url-in-web-bundle-cors-test.js"></script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle.https.tentative.html b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle.https.tentative.html new file mode 100644 index 0000000..460c48a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/link-relative-url-in-web-bundle.https.tentative.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<title>Relative Url in web bundle</title> +<link rel="help" href="https://github.com/WICG/webpackage/blob/main/explainers/subresource-loading.md" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/test-helpers.js"></script> + +<body> + <link + rel="webbundle" + href="../resources/wbn/relative-url.wbn" + resources=" + ../resources/wbn/relative-url-file.js + ../resources/wbn/relative-url/start-with-double-slash.js + ../resources/wbn/relative-url/start-with-slash.js + ../resources/wbn/relative-url/subdirectory-path.js + ../resources/wbn/starts-with-two-dots.js + ../resources/starts-with-two-dots-out-of-scope.js + " /> + <script> + const loaded_scripts = []; + function scriptLoaded(file) { + loaded_scripts.push(file); + } + const failed_scripts = []; + function scriptFailed(file) { + failed_scripts.push(file); + } + </script> + <script src="../resources/wbn/relative-url-file.js"></script> + <script src="../resources/wbn/relative-url/start-with-double-slash.js"></script> + <script src="../resources/wbn/relative-url/start-with-slash.js"></script> + <script src="../resources/wbn/relative-url/subdirectory-path.js"></script> + <script src="../resources/wbn/starts-with-two-dots.js"></script> + <script src="../resources/starts-with-two-dots-out-of-scope.js" + onerror="scriptFailed('starts-with-two-dots-out-of-scope.js')"></script> + + <script src="resources/relative-url-in-web-bundle-test.js"></script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-cors-test.js b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-cors-test.js new file mode 100644 index 0000000..60450d0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-cors-test.js
@@ -0,0 +1,17 @@ +promise_test(async (t) => { + assert_array_equals( + loaded_scripts, + [ + 'relative-url-file.js', + 'start-with-double-slash-cors.js', + 'start-with-slash.js', + 'subdirectory-path.js', + 'starts-with-two-dots.js', + ]); + assert_array_equals( + failed_scripts, + [ + 'starts-with-two-dots-out-of-scope.js', + ]); +}, +'Relative Url in web bundle.');
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-test.js b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-test.js new file mode 100644 index 0000000..ba0d4a1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/resources/relative-url-in-web-bundle-test.js
@@ -0,0 +1,17 @@ +promise_test(async (t) => { + assert_array_equals( + loaded_scripts, + [ + 'relative-url-file.js', + 'start-with-double-slash.js', + 'start-with-slash.js', + 'subdirectory-path.js', + 'starts-with-two-dots.js', + ]); + assert_array_equals( + failed_scripts, + [ + 'starts-with-two-dots-out-of-scope.js', + ]); +}, +'Relative Url in web bundle.');
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle-cors.https.tentative.sub.html b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle-cors.https.tentative.sub.html new file mode 100644 index 0000000..40114c7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle-cors.https.tentative.sub.html
@@ -0,0 +1,41 @@ +<!DOCTYPE html> +<title>Relative Url in cross origin web bundle</title> +<link rel="help" href="https://github.com/WICG/webpackage/blob/main/explainers/subresource-loading.md" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/test-helpers.js"></script> + +<body> + <script type="webbundle"> + { + "source": "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url.wbn", + "resources": [ + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url-file.js", + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-double-slash-cors.js", + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-slash.js", + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/subdirectory-path.js", + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/starts-with-two-dots.js", + "//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/starts-with-two-dots-out-of-scope.js" + ] + } + </script> + <script> + const loaded_scripts = []; + function scriptLoaded(file) { + loaded_scripts.push(file); + } + const failed_scripts = []; + function scriptFailed(file) { + failed_scripts.push(file); + } + </script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url-file.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-double-slash-cors.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/start-with-slash.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/relative-url/subdirectory-path.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/wbn/starts-with-two-dots.js"></script> + <script src="//{{domains[www1]}}:{{ports[https][0]}}/web-bundle/resources/starts-with-two-dots-out-of-scope.js" + onerror="scriptFailed('starts-with-two-dots-out-of-scope.js')"></script> + + <script src="resources/relative-url-in-web-bundle-cors-test.js"></script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle.https.tentative.html b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle.https.tentative.html new file mode 100644 index 0000000..37a896b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-bundle/subresource-loading/script-relative-url-in-web-bundle.https.tentative.html
@@ -0,0 +1,41 @@ +<!DOCTYPE html> +<title>Relative Url in web bundle</title> +<link rel="help" href="https://github.com/WICG/webpackage/blob/main/explainers/subresource-loading.md" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/test-helpers.js"></script> + +<body> + <script type="webbundle"> + { + "source": "../resources/wbn/relative-url.wbn", + "resources": [ + "../resources/wbn/relative-url-file.js", + "../resources/wbn/relative-url/start-with-double-slash.js", + "../resources/wbn/relative-url/start-with-slash.js", + "../resources/wbn/relative-url/subdirectory-path.js", + "../resources/wbn/starts-with-two-dots.js", + "../resources/starts-with-two-dots-out-of-scope.js" + ] + } + </script> + <script> + const loaded_scripts = []; + function scriptLoaded(file) { + loaded_scripts.push(file); + } + const failed_scripts = []; + function scriptFailed(file) { + failed_scripts.push(file); + } + </script> + <script src="../resources/wbn/relative-url-file.js"></script> + <script src="../resources/wbn/relative-url/start-with-double-slash.js"></script> + <script src="../resources/wbn/relative-url/start-with-slash.js"></script> + <script src="../resources/wbn/relative-url/subdirectory-path.js"></script> + <script src="../resources/wbn/starts-with-two-dots.js"></script> + <script src="../resources/starts-with-two-dots-out-of-scope.js" + onerror="scriptFailed('starts-with-two-dots-out-of-scope.js')"></script> + + <script src="resources/relative-url-in-web-bundle-test.js"></script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/webtransport/constructor.any.js b/third_party/blink/web_tests/external/wpt/webtransport/constructor.any.js index 1aef6fe..4312eb3 100644 --- a/third_party/blink/web_tests/external/wpt/webtransport/constructor.any.js +++ b/third_party/blink/web_tests/external/wpt/webtransport/constructor.any.js
@@ -20,10 +20,17 @@ }, `WebTransport constructor should reject URL '${url}'`); } -promise_test(t => { +promise_test(async t => { const wt = new WebTransport(`https://${HOST}:0/`); - return Promise.all([ - promise_rejects_js(t, TypeError, wt.ready, 'ready promise should be rejected'), - promise_rejects_js(t, TypeError, wt.closed, 'closed promise should be rejected'), - ]); + + // Sadly we cannot use promise_rejects_dom as the error constructor is + // WebTransportError rather than DOMException. + // We get a possible error, and then make sure wt.ready is rejected with it. + const e = await wt.ready.catch(e => e); + + await promise_rejects_exactly(t, e, wt.ready, 'ready should be rejected'); + await promise_rejects_exactly(t, e, wt.closed, 'closed should be rejected'); + assert_true(e instanceof WebTransportError); + assert_equals(e.source, 'session', 'source'); + assert_equals(e.streamErrorCode, null, 'streamErrorCode'); }, 'Connection to port 0 should fail');
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/reflections/reflection-in-composited-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/reflections/reflection-in-composited-expected.png index 62838e1a..3fdd1a9 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/reflections/reflection-in-composited-expected.png +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/reflections/reflection-in-composited-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/squashing/keep-lcd-text-expected.txt b/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/squashing/keep-lcd-text-expected.txt new file mode 100644 index 0000000..c335659 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/compositing/squashing/keep-lcd-text-expected.txt
@@ -0,0 +1,28 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='composited'", + "bounds": [300, 300], + "contentsOpaqueForText": true, + "drawsContent": false + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='non-opaque'", + "bounds": [220, 120] + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='opaque'", + "position": [0, 50], + "bounds": [220, 220], + "contentsOpaque": true, + "backgroundColor": "#FFFF00" + } + ] +} +
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-collapsed-border-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-collapsed-border-expected.png new file mode 100644 index 0000000..3d756aab --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-collapsed-border-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-expected.png new file mode 100644 index 0000000..3d756aab --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/fast/table/backgr_layers-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/prefer_compositing_to_lcd_text/compositing/squashing/keep-lcd-text-expected.txt b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/prefer_compositing_to_lcd_text/compositing/squashing/keep-lcd-text-expected.txt new file mode 100644 index 0000000..f27ae9e --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/prefer_compositing_to_lcd_text/compositing/squashing/keep-lcd-text-expected.txt
@@ -0,0 +1,22 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='composited'", + "bounds": [300, 300], + "contentsOpaqueForText": true, + "drawsContent": false + }, + { + "name": "LayoutNGBlockFlow (positioned) DIV id='non-opaque'", + "bounds": [220, 270], + "backgroundColor": "#FFFF00" + } + ] +} +
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/compositing/squashing/keep-lcd-text-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/compositing/squashing/keep-lcd-text-expected.txt new file mode 100644 index 0000000..2519132 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/compositing/squashing/keep-lcd-text-expected.txt
@@ -0,0 +1,21 @@ +{ + "layers": [ + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutBlockFlow (positioned) DIV id='composited'", + "bounds": [300, 300], + "drawsContent": false + }, + { + "name": "Squashing Layer (first squashed layer: LayoutBlockFlow (positioned) DIV id='non-opaque')", + "bounds": [220, 270], + "backgroundColor": "#FFFF00" + } + ] +} +
diff --git a/third_party/blink/web_tests/platform/linux/virtual/android/fullscreen/full-screen-iframe-allowed-video-expected.png b/third_party/blink/web_tests/platform/linux/virtual/android/fullscreen/full-screen-iframe-allowed-video-expected.png index bea834b7f..3bf2470 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/android/fullscreen/full-screen-iframe-allowed-video-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/android/fullscreen/full-screen-iframe-allowed-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/README.md b/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/README.md new file mode 100644 index 0000000..ef5dde96 --- /dev/null +++ b/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/README.md
@@ -0,0 +1 @@ +These suites run the tests with --enable-prefer-compositing-to-lcd-text.
diff --git a/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/compositing/overflow/README.txt b/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/compositing/overflow/README.txt deleted file mode 100644 index 044763d..0000000 --- a/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/compositing/overflow/README.txt +++ /dev/null
@@ -1,3 +0,0 @@ -# This suite runs the tests in LayoutTests/compositing/overflow/ with -# --enable-accelerated-overflow-scroll. -# See the virtual_test_suites() method in tools/blinkpy/web_tests/port/base.py.
diff --git a/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/scrollbars/README.txt b/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/scrollbars/README.txt deleted file mode 100644 index 19ab3cc9..0000000 --- a/third_party/blink/web_tests/virtual/prefer_compositing_to_lcd_text/scrollbars/README.txt +++ /dev/null
@@ -1,2 +0,0 @@ -# This suite runs the tests in LayoutTests/scrollbars/ with --enable-accelerated-overflow-scroll. -# See the virtual_test_suites() method in tools/blinkpy/web_tests/port/base.py.
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index 399c4527..e6f91c599 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -3560,6 +3560,7 @@ method constructor setter cite interface HTMLScriptElement : HTMLElement + static method supports attribute @@toStringTag getter async getter charset
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index 7d87cd7..0cafbe1f 100644 --- a/third_party/freetype/README.chromium +++ b/third_party/freetype/README.chromium
@@ -1,7 +1,7 @@ Name: FreeType URL: http://www.freetype.org/ -Version: VER-2-11-0-93-g6d19b29fb -Revision: 6d19b29fbcd48bdfeb3ae10d26460137f65ebac8 +Version: VER-2-11-0-94-ga29e02005 +Revision: a29e020059ca6f73a212ec76af94b22a694ad765 CPEPrefix: cpe:/a:freetype:freetype:2.10.4 License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses"
diff --git a/tools/memory/partition_allocator/pa_tcache_inspect.cc b/tools/memory/partition_allocator/pa_tcache_inspect.cc index 81812e3..de97864 100644 --- a/tools/memory/partition_allocator/pa_tcache_inspect.cc +++ b/tools/memory/partition_allocator/pa_tcache_inspect.cc
@@ -505,6 +505,9 @@ std::memory_order_relaxed) / 1024 << "kiB"; + std::cout << "\nEmpty Slot Spans Dirty Size = " + << TS_UNCHECKED_READ(root->empty_slot_spans_dirty_bytes) / 1024 + << "kiB"; } } // namespace tools
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 8bb2ef8..0128075 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -34657,6 +34657,10 @@ <int value="4043" label="CoepRequireCorpSharedWorker"/> <int value="4044" label="CoepCredentiallessSharedWorker"/> <int value="4045" label="PaymentRequestBasicCard"/> + <int value="4046" label="ClientHintsDeviceMemory"/> + <int value="4047" label="ClientHintsDPR"/> + <int value="4048" label="ClientHintsResourceWidth"/> + <int value="4049" label="ClientHintsViewportWidth"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -85280,6 +85284,16 @@ </int> </enum> +<enum name="V8CagedMemoryAllocationOutcome"> + <int value="0" label="kSuccess">Allocation succeeded inside the cage.</int> + <int value="1" label="kOutsideCage"> + Allocation failed inside the cage but succeeded outside of it. + </int> + <int value="2" label="kFailure"> + Allocation failed inside and outside of the cage. + </int> +</enum> + <enum name="V8CodeCacheRejectReason"> <int value="1" label="MAGIC_NUMBER_MISMATCH"> Reject due to magic number mismatch
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index 8ce1cea..a9be8cf 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -1553,6 +1553,16 @@ </summary> </histogram> +<histogram name="Android.Intent.WebIntentToOtherBrowser" enum="Boolean" + expires_after="M98"> + <owner>mthiesse@chromium.org</owner> + <owner>yfriedman@chromium.org</owner> + <summary> + When a site attempts to navigate to a supported URL with an intent URL that + targets other browser-like apps. + </summary> +</histogram> + <histogram name="Android.IsLastSharedAppInfoRetrieved" enum="BooleanIsLastSharedAppInfoRetrieved" expires_after="M77"> <owner>tedchoc@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/ios/histograms.xml b/tools/metrics/histograms/metadata/ios/histograms.xml index be54ea9..df9145d8 100644 --- a/tools/metrics/histograms/metadata/ios/histograms.xml +++ b/tools/metrics/histograms/metadata/ios/histograms.xml
@@ -965,6 +965,16 @@ </summary> </histogram> +<histogram name="IOS.ReadingList.ImageTooLargeFailure" units="KB" + expires_after="2022-06-11"> + <owner>olivierrobin@chromium.org</owner> + <owner>justincohen@chromium.org</owner> + <summary> + Distillation of the page failed because an image was too big (>1MB). + Recorded on distillation attempt. + </summary> +</histogram> + <histogram name="IOS.ReadingList.Javascript.ExecutionTime" units="ms" expires_after="2022-06-11"> <owner>thegreenfrog@chromium.org</owner> @@ -1012,6 +1022,16 @@ </summary> </histogram> +<histogram name="IOS.ReadingList.PageTooLargeFailure" units="KB" + expires_after="2022-06-11"> + <owner>olivierrobin@chromium.org</owner> + <owner>justincohen@chromium.org</owner> + <summary> + Distillation of the page failed because the page was too big (>10MB). + Recorded on distillation attempt. + </summary> +</histogram> + <histogram name="IOS.Reauth.Password.Autofill" enum="ReauthenticationEvent" expires_after="2022-02-20"> <owner>javierrobles@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/password/histograms.xml b/tools/metrics/histograms/metadata/password/histograms.xml index 504d9f1..ddeaee9 100644 --- a/tools/metrics/histograms/metadata/password/histograms.xml +++ b/tools/metrics/histograms/metadata/password/histograms.xml
@@ -876,7 +876,7 @@ </histogram> <histogram name="PasswordManager.AutoSigninFirstRunDialog" - enum="AutoSigninFirstRun" expires_after="2021-10-31"> + enum="AutoSigninFirstRun" expires_after="2022-04-30"> <owner>vasilii@chromium.org</owner> <owner>kazinova@google.com</owner> <summary> @@ -1916,6 +1916,9 @@ <histogram name="PasswordManager.NumFormManagersCleared" units="count" expires_after="2021-09-19"> + <obsolete> + Removed in M96. + </obsolete> <owner>vasilii@chromium.org</owner> <owner>kazinova@google.com</owner> <summary> @@ -2422,7 +2425,7 @@ </histogram> <histogram name="PasswordManager.TimeBetweenStoreAndServer" units="ms" - expires_after="2021-10-25"> + expires_after="2022-04-25"> <owner>kazinova@google.com</owner> <owner>battre@chromium.org</owner> <summary> @@ -2433,7 +2436,7 @@ </histogram> <histogram base="true" name="PasswordManager.TimesPasswordUsed" - units="PasswordUses" expires_after="2021-10-28"> + units="PasswordUses" expires_after="2022-04-28"> <owner>kazinova@google.com</owner> <owner>battre@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/v8/histograms.xml b/tools/metrics/histograms/metadata/v8/histograms.xml index 4b24b62..b7056f2 100644 --- a/tools/metrics/histograms/metadata/v8/histograms.xml +++ b/tools/metrics/histograms/metadata/v8/histograms.xml
@@ -40,6 +40,17 @@ <summary>Array buffer sizes for which V8 failed to allocate memory.</summary> </histogram> +<histogram name="V8.CagedMemoryAllocationOutcome" + enum="V8CagedMemoryAllocationOutcome" expires_after="2022-09-30"> + <owner>saelo@chromium.org</owner> + <owner>ishell@chromium.org</owner> + <summary> + The outcome of attempts to allocate memory pages inside the virtual memory + cage. Recorded at each allocation attempt, such as when allocating WASM + memory buffers, but only if the virtual memory cage is active. + </summary> +</histogram> + <histogram name="V8.CodeCacheRejectReason" enum="V8CodeCacheRejectReason" expires_after="M77"> <owner>yangguo@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/web_rtc/histograms.xml b/tools/metrics/histograms/metadata/web_rtc/histograms.xml index 13c2966..dc39d23 100644 --- a/tools/metrics/histograms/metadata/web_rtc/histograms.xml +++ b/tools/metrics/histograms/metadata/web_rtc/histograms.xml
@@ -143,6 +143,17 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.Agc.ClippingPredictor.Precision" units="%" + expires_after="2021-12-31"> + <owner>silen@chromium.org</owner> + <owner>alessiob@chromium.org</owner> + <summary> + Logs the precision for the clipping predictor used in AgcManagerDirect. A + log call is made every 30 seconds during an active WebRTC call using the + analog gain controller and the clipping predictor feature. + </summary> +</histogram> + <histogram name="WebRTC.Audio.Agc.ClippingPredictor.PredictionInterval" units="frames" expires_after="2021-12-31"> <owner>alessiob@chromium.org</owner> @@ -156,6 +167,17 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.Agc.ClippingPredictor.Recall" units="%" + expires_after="2021-12-31"> + <owner>silen@chromium.org</owner> + <owner>alessiob@chromium.org</owner> + <summary> + Logs the recall for the clipping predictor used in AgcManagerDirect. A log + call is made every 30 seconds during an active WebRTC call using the analog + gain controller and the clipping predictor feature. + </summary> +</histogram> + <histogram name="WebRTC.Audio.Agc.DigitalGainApplied" units="dB" expires_after="2021-12-31"> <owner>alessiob@chromium.org</owner>
diff --git a/tools/typescript/definitions/language_settings_private.d.ts b/tools/typescript/definitions/language_settings_private.d.ts index e71976b1..77393d1 100644 --- a/tools/typescript/definitions/language_settings_private.d.ts +++ b/tools/typescript/definitions/language_settings_private.d.ts
@@ -80,12 +80,12 @@ export function removeInputMethod(inputMethodId: string): void; export function retryDownloadDictionary(languageCode: string): void; - export const onSpellcheckDictionariesChanged: ChromeEvent< - Array<SpellcheckDictionaryStatus>>; + export const onSpellcheckDictionariesChanged: + ChromeEvent<(statuses: Array<SpellcheckDictionaryStatus>) => void>; export const onCustomDictionaryChanged: ChromeEvent<(added: Array<string>, removed: Array<string>) => void>; - export const onInputMethodAdded: ChromeEvent<string>; - export const onInputMethodRemoved: ChromeEvent<string>; + export const onInputMethodAdded: ChromeEvent<(id: string) => void>; + export const onInputMethodRemoved: ChromeEvent<(id: string) => void>; } } }
diff --git a/ui/base/ime/dummy_text_input_client.cc b/ui/base/ime/dummy_text_input_client.cc index f8bff81..9ec46a6 100644 --- a/ui/base/ime/dummy_text_input_client.cc +++ b/ui/base/ime/dummy_text_input_client.cc
@@ -155,7 +155,7 @@ return false; } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool DummyTextInputClient::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
diff --git a/ui/base/ime/dummy_text_input_client.h b/ui/base/ime/dummy_text_input_client.h index 58e0c97..42c3ddfb 100644 --- a/ui/base/ime/dummy_text_input_client.h +++ b/ui/base/ime/dummy_text_input_client.h
@@ -64,7 +64,7 @@ ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override;
diff --git a/ui/base/ime/fake_text_input_client.cc b/ui/base/ime/fake_text_input_client.cc index ea2f388..7b782548 100644 --- a/ui/base/ime/fake_text_input_client.cc +++ b/ui/base/ime/fake_text_input_client.cc
@@ -160,7 +160,7 @@ return false; } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool FakeTextInputClient::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
diff --git a/ui/base/ime/fake_text_input_client.h b/ui/base/ime/fake_text_input_client.h index b87dde1..6150e16 100644 --- a/ui/base/ime/fake_text_input_client.h +++ b/ui/base/ime/fake_text_input_client.h
@@ -70,7 +70,7 @@ void SetTextEditCommandForNextKeyEvent(TextEditCommand command) override; ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override;
diff --git a/ui/base/ime/text_input_client.h b/ui/base/ime/text_input_client.h index 9442dfe..0c73492 100644 --- a/ui/base/ime/text_input_client.h +++ b/ui/base/ime/text_input_client.h
@@ -237,7 +237,7 @@ // fields that are considered 'private' (e.g. in incognito tabs). virtual bool ShouldDoLearning() = 0; -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) // Start composition over a given UTF-16 code range from existing text. This // should only be used for composition scenario when IME wants to start // composition on existing text. Returns whether the operation was successful.
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 ecc2b88..ae3649a 100644 --- a/ui/file_manager/file_manager/foreground/css/file_manager.css +++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -697,16 +697,6 @@ -webkit-mask-image: url(../images/files/ui/search.svg); } -.dialog-header.files-ng #share-menu-button > .icon { - -webkit-mask-image: url(../images/files/ui/share_ng.svg); - height: 48px; - margin-inline-end: -7px; - margin-inline-start: -7px; - margin-top: -7px; - position: absolute; - width: 48px; -} - .dialog-header.files-ng #sharesheet-button > .icon { -webkit-mask-image: url(../images/files/ui/share_ng.svg); } @@ -2293,23 +2283,15 @@ opacity: 0; } -#share-menu cr-menu-item, #tasks-menu cr-menu-item:not(.change-default) { background-position: left 10px center; padding-inline-start: 32px; } -html[dir='rtl'] #share-menu cr-menu-item, html[dir='rtl'] #tasks-menu cr-menu-item:not(.change-default) { background-position: right 10px center; } -#share-menu cr-menu-item[command='#share'] { - background-image: -webkit-image-set( - url(../images/files/ui/person_add.png) 1x, - url(../images/files/ui/2x/person_add.png) 2x); -} - #action-bar { display: flex; flex: none;
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 d012ea5..bd63df7d 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
@@ -14,7 +14,6 @@ import {FileType} from '../../common/js/file_type.js'; import {EntryList} from '../../common/js/files_app_entry_types.js'; import {metrics} from '../../common/js/metrics.js'; -import {ProgressCenterItem, ProgressItemState} from '../../common/js/progress_center_common.js'; import {TrashEntry} from '../../common/js/trash.js'; import {str, strf, util} from '../../common/js/util.js'; import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; @@ -71,7 +70,6 @@ */ CommandUtil.SharingActionElementId = { CONTEXT_MENU: 'file-list', - SHARE_BUTTON: 'share-menu-button', SHARE_SHEET: 'sharesheet-button', }; @@ -87,8 +85,6 @@ switch (id) { case CommandUtil.SharingActionElementId.CONTEXT_MENU: return FileTasks.SharingActionSourceForUMA.CONTEXT_MENU; - case CommandUtil.SharingActionElementId.SHARE_BUTTON: - return FileTasks.SharingActionSourceForUMA.SHARE_BUTTON; case CommandUtil.SharingActionElementId.SHARE_SHEET: return FileTasks.SharingActionSourceForUMA.SHARE_SHEET; default: {
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.m.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.m.js index e667a622..99c550e5 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.m.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.m.js
@@ -23,10 +23,6 @@ expected: FileTasks.SharingActionSourceForUMA.CONTEXT_MENU, }, { - event: {target: {id: CommandUtil.SharingActionElementId.SHARE_BUTTON}}, - expected: FileTasks.SharingActionSourceForUMA.SHARE_BUTTON, - }, - { event: {target: {id: CommandUtil.SharingActionElementId.SHARE_SHEET}}, expected: FileTasks.SharingActionSourceForUMA.SHARE_SHEET, },
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks.js b/ui/file_manager/file_manager/foreground/js/file_tasks.js index deddc47..39b3a4fc 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks.js +++ b/ui/file_manager/file_manager/foreground/js/file_tasks.js
@@ -3,8 +3,6 @@ // found in the LICENSE file. import {assert} from 'chrome://resources/js/assert.m.js'; -import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {AsyncUtil} from '../../common/js/async_util.js'; @@ -30,8 +28,6 @@ import {DefaultTaskDialog} from './ui/default_task_dialog.js'; import {FileManagerUI} from './ui/file_manager_ui.js'; import {FilesConfirmDialog} from './ui/files_confirm_dialog.js'; -import {FilesMenuItem} from './ui/files_menu.js'; -import {MultiMenuButton} from './ui/multi_menu_button.js'; /** * Represents a collection of available tasks to execute for a specific list @@ -971,15 +967,13 @@ } /** - * Displays the list of tasks in a open task picker combobutton and a share - * options menu. + * Displays the list of tasks in a open task picker combobutton.. * * @param {!ComboButton} openCombobutton The open task picker * combobutton. - * @param {!MultiMenuButton} shareMenuButton Button for share options. * @public */ - display(openCombobutton, shareMenuButton) { + display(openCombobutton) { const openTasks = []; const otherTasks = []; for (const task of this.tasks_) { @@ -990,7 +984,6 @@ } } this.updateOpenComboButton_(openCombobutton, openTasks); - this.updateShareMenuButton_(shareMenuButton, otherTasks); } /** @@ -1044,39 +1037,6 @@ } /** - * Setup a menu button for sharing options based on the given tasks. - * @param {!MultiMenuButton} shareMenuButton - * @param {!Array<!chrome.fileManagerPrivate.FileTask>} tasks - */ - updateShareMenuButton_(shareMenuButton, tasks) { - const driveShareCommand = - shareMenuButton.menu.querySelector('cr-menu-item[command="#share"]'); - const driveShareCommandSeparator = - shareMenuButton.menu.querySelector('#drive-share-separator'); - - // Update share command. - driveShareCommand.command.canExecuteChange( - this.ui_.listContainer.currentList); - - // Hide share icon for New Folder creation. See https://crbug.com/571355. - shareMenuButton.hidden = true; - - // Show the separator if Drive share command is enabled and there is at - // least one other share actions. - driveShareCommandSeparator.hidden = - driveShareCommand.disabled || tasks.length == 0; - - // Clear menu items except for drive share menu and a separator for it. - // As querySelectorAll() returns live NodeList, we need to copy elements to - // Array object to modify DOM in the for loop. - const itemsToRemove = [].slice.call(shareMenuButton.menu.querySelectorAll( - 'cr-menu-item:not([command="#share"])')); - for (const item of itemsToRemove) { - item.parentNode.removeChild(item); - } - } - - /** * Creates sorted array of available task descriptions such as title and icon. * * @param {!Array<!chrome.fileManagerPrivate.FileTask>} tasks Tasks to create
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.m.js b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.m.js index a77bf265..53cc3e35 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.m.js +++ b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.m.js
@@ -19,7 +19,6 @@ import {VolumeManager} from '../../externs/volume_manager.js'; import {FilesPasswordDialog} from '../elements/files_password_dialog.js'; -import {constants} from './constants.js'; import {DirectoryModel} from './directory_model.js'; import {FileTasks} from './file_tasks.js'; import {FileTransferController} from './file_transfer_controller.js'; @@ -636,18 +635,6 @@ [FileTasks.SharingActionSourceForUMA.CONTEXT_MENU]); assertArrayEquals(countMap.get('Share.FileCount'), [3]); assertArrayEquals(enumMap.get('Share.FileType'), ['.log', '.doc', 'other']); - - FileTasks.recordSharingActionUMA_( - FileTasks.SharingActionSourceForUMA.SHARE_BUTTON, [ - MockFileEntry.create(mockFileSystem, '/test.log'), - ]); - assertArrayEquals(enumMap.get('Share.ActionSource'), [ - FileTasks.SharingActionSourceForUMA.CONTEXT_MENU, - FileTasks.SharingActionSourceForUMA.SHARE_BUTTON, - ]); - assertArrayEquals(countMap.get('Share.FileCount'), [3, 1]); - assertArrayEquals( - enumMap.get('Share.FileType'), ['.log', '.doc', 'other', '.log']); } /**
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller.js b/ui/file_manager/file_manager/foreground/js/task_controller.js index 4897a05..df9e9ac 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller.js
@@ -7,7 +7,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {DialogType} from '../../common/js/dialog_type.js'; -import {str, strf, util} from '../../common/js/util.js'; +import {strf, util} from '../../common/js/util.js'; import {Crostini} from '../../externs/background/crostini.js'; import {ProgressCenter} from '../../externs/background/progress_center.js'; import {VolumeManager} from '../../externs/volume_manager.js'; @@ -166,8 +166,6 @@ ui.taskMenuButton.addEventListener( 'select', this.onTaskItemClicked_.bind(this)); - ui.shareMenuButton.menu.addEventListener( - 'activate', this.onTaskItemClicked_.bind(this)); this.selectionHandler_.addEventListener( FileSelectionHandler.EventType.CHANGE, this.onSelectionChanged_.bind(this)); @@ -274,8 +272,7 @@ this.tasks_ = null; this.getFileTasks() .then(tasks => { - tasks.display( - this.ui_.taskMenuButton, this.ui_.shareMenuButton); + tasks.display(this.ui_.taskMenuButton); }) .catch(error => { if (error) { @@ -379,7 +376,7 @@ (selection.directoryCount > 0 || selection.fileCount > 0)) { this.getFileTasks() .then(tasks => { - tasks.display(this.ui_.taskMenuButton, this.ui_.shareMenuButton); + tasks.display(this.ui_.taskMenuButton); this.updateContextMenuTaskItems_( tasks.getOpenTaskItems(), tasks.getNonOpenTaskItems()); }) @@ -390,7 +387,6 @@ }); } else { this.ui_.taskMenuButton.hidden = true; - this.ui_.shareMenuButton.hidden = true; } }
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller_unittest.m.js b/ui/file_manager/file_manager/foreground/js/task_controller_unittest.m.js index 6aed8fbd..9b7e83aa 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller_unittest.m.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller_unittest.m.js
@@ -108,13 +108,9 @@ }), /** @type {!FileManagerUI} */ ({ taskMenuButton: document.createElement('button'), - shareMenuButton: { - menu: document.createElement('div'), - }, fileContextMenu: { defaultActionMenuItem: document.createElement('div'), }, - shareSubMenu: document.createElement('div'), speakA11yMessage: text => {}, }), new MockMetadataModel({}),
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js index 07645bde..6e6458a 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js
@@ -332,23 +332,6 @@ }; /** - * The menu button for share options - * @type {!MultiMenuButton} - * @const - */ - this.shareMenuButton = - util.queryDecoratedElement('#share-menu-button', MultiMenuButton); - const shareMenuButtonToggleRipple = - /** @type {!FilesToggleRippleElement} */ ( - queryRequiredElement('files-toggle-ripple', this.shareMenuButton)); - this.shareMenuButton.addEventListener('menushow', () => { - shareMenuButtonToggleRipple.activated = true; - }); - this.shareMenuButton.addEventListener('menuhide', () => { - shareMenuButtonToggleRipple.activated = false; - }); - - /** * Banners in the file list. * @type {Banners|BannerController} */
diff --git a/ui/file_manager/file_manager/main.html b/ui/file_manager/file_manager/main.html index 5b8cf06..8d76bc2e 100644 --- a/ui/file_manager/file_manager/main.html +++ b/ui/file_manager/file_manager/main.html
@@ -188,7 +188,7 @@ <cr-menu-item command="#open-with" visibleif="full-page" class="hide-on-toolbar" sub-menu="#tasks-menu" hidden></cr-menu-item> <cr-menu-item command="#more-actions" - visibleif="full-page" class="hide-on-toolbar" sub-menu="#share-menu" hidden></cr-menu-item> + visibleif="full-page" class="hide-on-toolbar" hidden></cr-menu-item> <cr-menu-item command="#invoke-sharesheet" visibleif="full-page" class="hide-on-toolbar"> $i18n{SHARE_BUTTON_TOOLTIP} @@ -320,17 +320,6 @@ menu-item-selector="cr-menu-item, hr"> </cr-menu> - <cr-menu id="share-menu" class="chrome-menu files-menu" - aria-label="$i18n{MORE_ACTIONS_BUTTON_LABEL}" - menu-item-selector="cr-menu-item, hr"> - <cr-menu-item command="#share"></cr-menu-item> - <cr-menu-item command="#share-with-linux"></cr-menu-item> - <cr-menu-item command="#manage-linux-sharing"></cr-menu-item> - <cr-menu-item command="#share-with-plugin-vm"></cr-menu-item> - <cr-menu-item command="#manage-plugin-vm-sharing"></cr-menu-item> - <hr id="drive-share-separator"> - </cr-menu> - <cr-menu id="providers-menu" class="chrome-menu files-menu has-icon-start" menu-item-selector="cr-menu-item, hr"> @@ -407,14 +396,6 @@ tabindex="0" hidden aria-label="$i18n{TASKS_BUTTON_LABEL}"> </button> - <button id="share-menu-button" class="icon-button menu-button" tabindex="0" hidden - menu="#share-menu" - aria-label="$i18n{SHARE_BUTTON_TOOLTIP}" - aria-activedescendant="share-menu" - has-tooltip> - <files-toggle-ripple></files-toggle-ripple> - <div class="icon"></div> - </button> <cr-button id="sharesheet-button" class="icon-button menu-button" tabindex="0" hidden aria-label="$i18n{SHARESHEET_BUTTON_LABEL}" visibleif="full-page"
diff --git a/ui/file_manager/integration_tests/file_manager/share_and_manage_dialog.js b/ui/file_manager/integration_tests/file_manager/share_and_manage_dialog.js index fdae80e..7802b1d 100644 --- a/ui/file_manager/integration_tests/file_manager/share_and_manage_dialog.js +++ b/ui/file_manager/integration_tests/file_manager/share_and_manage_dialog.js
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {addEntries, ENTRIES, EntryType, getCaller, pending, repeatUntil, RootPath, sendTestMessage, TestEntryInfo} from '../test_util.js'; +import {RootPath} from '../test_util.js'; import {testcase} from '../testcase.js'; -import {expandTreeItem, IGNORE_APP_ERRORS, mountCrostini, navigateWithDirectoryTree, openNewWindow, remoteCall, setupAndWaitUntilReady} from './background.js'; +import {remoteCall, setupAndWaitUntilReady} from './background.js'; import {BASIC_DRIVE_ENTRY_SET, SHARED_DRIVE_ENTRY_SET} from './test_data.js'; /** @@ -36,33 +36,19 @@ !!await remoteCall.callRemoteTestUtil('selectFile', appId, [path]), 'selectFile failed'); - // Wait for the entry to be selected. - await remoteCall.waitForElement(appId, '.table-row[selected]'); - - // Wait for the share button to appear. - chrome.test.assertTrue(!!await remoteCall.waitForElement( - appId, '#share-menu-button:not([disabled])')); - - // Click the share button to open share menu. - chrome.test.assertTrue(!!await remoteCall.callRemoteTestUtil( - 'fakeMouseClick', appId, ['#share-menu-button'])); - - // Check: the "Share with others" menu item should be shown enabled. - const shareMenuItem = - '#share-menu:not([hidden]) [command="#share"]:not([disabled])'; + // Right-click to show the context menu. chrome.test.assertTrue( - !!await remoteCall.waitForElement(appId, shareMenuItem)); + !!await remoteCall.waitAndRightClick(appId, '.table-row[selected]')); - // Click the "Share with others" menu item. - const shareWithOthers = '#share-menu [command="#share"]:not([disabled])'; + // Wait and click on the visible and enabled menu item. + const shareMenuItem = '#file-context-menu:not([hidden]) ' + + ' [command="#share"]:not([hidden]):not([disabled])'; chrome.test.assertTrue( - !!await remoteCall.callRemoteTestUtil( - 'fakeMouseClick', appId, [shareWithOthers]), - 'fakeMouseClick failed'); + !!await remoteCall.waitAndClickElement(appId, shareMenuItem)); - // Wait for the share menu to disappear. + // Wait for the context menu to disappear. chrome.test.assertTrue( - !!await remoteCall.waitForElement(appId, '#share-menu[hidden]')); + !!await remoteCall.waitForElement(appId, '#file-context-menu[hidden]')); // Wait for the browser window to appear and navigate to the expected URL. chrome.test.assertEq(
diff --git a/ui/ozone/platform/wayland/host/wayland_screen.cc b/ui/ozone/platform/wayland/host/wayland_screen.cc index 6a5347b..022b970e 100644 --- a/ui/ozone/platform/wayland/host/wayland_screen.cc +++ b/ui/ozone/platform/wayland/host/wayland_screen.cc
@@ -58,22 +58,6 @@ return display::Display::ROTATE_0; } -wl_output_transform RotationToWaylandTransform( - display::Display::Rotation rotation) { - switch (rotation) { - case display::Display::ROTATE_0: - return WL_OUTPUT_TRANSFORM_NORMAL; - case display::Display::ROTATE_90: - return WL_OUTPUT_TRANSFORM_90; - case display::Display::ROTATE_180: - return WL_OUTPUT_TRANSFORM_180; - case display::Display::ROTATE_270: - return WL_OUTPUT_TRANSFORM_270; - } - NOTREACHED(); - return WL_OUTPUT_TRANSFORM_NORMAL; -} - } // namespace WaylandScreen::WaylandScreen(WaylandConnection* connection) @@ -153,8 +137,7 @@ int32_t transform) { display::Display changed_display(output_id); if (!display::Display::HasForceDeviceScaleFactor()) { - changed_display.SetScaleAndBounds(scale_factor + additional_scale_, - new_bounds); + changed_display.SetScaleAndBounds(scale_factor, new_bounds); } else { changed_display.set_bounds(new_bounds); changed_display.set_work_area(new_bounds); @@ -378,25 +361,4 @@ return values; } -void WaylandScreen::SetDeviceScaleFactor(float scale) { - // If the device scale factor is forced, ignore the one provided as it's - // already set. - if (display::Display::HasForceDeviceScaleFactor()) - return; - - // See comment near the additional_scale_ in the header file. - float whole = 0; - additional_scale_ = std::modf(scale, &whole); - for (const auto& display : display_list_.displays()) { - // display::bounds returns bounds in dip while OnOutputAddedOrUpdated - // expects them to be in px. Translate using current scale factor of the - // display. - OnOutputAddedOrUpdated(display.id(), - gfx::ScaleToEnclosedRect( - display.bounds(), display.device_scale_factor()), - display.device_scale_factor(), - RotationToWaylandTransform(display.rotation())); - } -} - } // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_screen.h b/ui/ozone/platform/wayland/host/wayland_screen.h index de2f3087..6cf8b1a0 100644 --- a/ui/ozone/platform/wayland/host/wayland_screen.h +++ b/ui/ozone/platform/wayland/host/wayland_screen.h
@@ -71,7 +71,6 @@ void RemoveObserver(display::DisplayObserver* observer) override; std::vector<base::Value> GetGpuExtraInfo( const gfx::GpuExtraInfo& gpu_extra_info) override; - void SetDeviceScaleFactor(float scale) override; private: void AddOrUpdateDisplay(uint32_t output_id, @@ -93,15 +92,6 @@ org_gnome_mutter_idle_monitor_; #endif - // Fractional part of additional scale. By default, GNOME also provides scale - // factor for Wayland, but it uses the biggest scale factor if multiple - // displays are available. In contrast, wl_output.scale sends scale factor for - // each of the displays and we adapt accordingly. However, wl_output.scale - // doesn't send fractional parts, while GNOME does send that when "Large text" - // feature is enabled. Thus, store only this decimal part and updates displays - // accordingly. - float additional_scale_ = 0.f; - wl::Object<zwp_idle_inhibitor_v1> idle_inhibitor_; base::WeakPtrFactory<WaylandScreen> weak_factory_;
diff --git a/ui/ozone/platform/wayland/host/wayland_screen_unittest.cc b/ui/ozone/platform/wayland/host/wayland_screen_unittest.cc index 5cdc578..b2f23a67 100644 --- a/ui/ozone/platform/wayland/host/wayland_screen_unittest.cc +++ b/ui/ozone/platform/wayland/host/wayland_screen_unittest.cc
@@ -764,43 +764,6 @@ display::Display::ResetForceDeviceScaleFactorForTesting(); } -// Tests that WaylandScreen updates list of displays with additional fractional -// scale by taking only decimal part of it and updating the displays using their -// existing scale + fractional part. This fractional part comes from GNOME's -// accessibility feature called "Large Text". -TEST_P(WaylandScreenTest, SetAdditionalScale) { - TestDisplayObserver observer; - platform_screen_->AddObserver(&observer); - - const display::Display primary_display = - platform_screen_->GetPrimaryDisplay(); - - wl::TestOutput* output2 = server_.CreateAndInitializeOutput(); - - Sync(); - - // Place it on the right side of the primary display. - const gfx::Rect output2_rect = - gfx::Rect(primary_display.bounds().width(), 0, 1024, 768); - output2->SetRect(output2_rect); - output2->Flush(); - - Sync(); - - const std::vector<float> scales = {0.2, 0.7, 1.3, 1.6, 1.8, 2.3, 2.9, 3.5}; - // Pretend GNOME updates scale and sets fractional scale (Large Text feature). - for (auto scale : scales) { - platform_screen_->SetDeviceScaleFactor(scale); - for (auto& display : platform_screen_->GetAllDisplays()) { - float whole = 0; - // WaylandScreen will get decimal part and use the integer part provided - // by wl_output. - float expected_scale = std::modf(scale, &whole) + 1.f; - EXPECT_EQ(expected_scale, display.device_scale_factor()); - } - } -} - namespace { class LazilyConfiguredScreenTest
diff --git a/ui/platform_window/x11/BUILD.gn b/ui/platform_window/x11/BUILD.gn index 72bce1f..7939317 100644 --- a/ui/platform_window/x11/BUILD.gn +++ b/ui/platform_window/x11/BUILD.gn
@@ -61,6 +61,7 @@ sources = [ "test/device_data_manager_x11_unittest.cc", "test/events_x_unittest.cc", + "test/x11_drag_drop_client_unittest.cc", "test/x11_event_translation_unittest.cc", "test/x11_window_unittest.cc", ] @@ -76,6 +77,7 @@ "//testing/gtest", "//ui/base", "//ui/base:features", + "//ui/base/dragdrop:types", "//ui/base/x", "//ui/base/x:test_support", "//ui/events:test_support",
diff --git a/ui/views/widget/desktop_aura/x11_drag_drop_client_unittest.cc b/ui/platform_window/x11/test/x11_drag_drop_client_unittest.cc similarity index 80% rename from ui/views/widget/desktop_aura/x11_drag_drop_client_unittest.cc rename to ui/platform_window/x11/test/x11_drag_drop_client_unittest.cc index 6866cb6..61604c9b 100644 --- a/ui/views/widget/desktop_aura/x11_drag_drop_client_unittest.cc +++ b/ui/platform_window/x11/test/x11_drag_drop_client_unittest.cc
@@ -17,33 +17,34 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" -#include "ui/aura/client/drag_drop_client.h" -#include "ui/aura/client/drag_drop_delegate.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/cursor/cursor_loader.h" -#include "ui/base/cursor/mojom/cursor_type.mojom.h" -#include "ui/base/cursor/platform_cursor.h" +#include "testing/gtest/include/gtest/gtest.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h" #include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/base/dragdrop/os_exchange_data_provider_factory_ozone.h" +#include "ui/base/dragdrop/os_exchange_data_provider_x11.h" #include "ui/base/x/x11_cursor.h" #include "ui/base/x/x11_move_loop.h" #include "ui/base/x/x11_move_loop_delegate.h" #include "ui/base/x/x11_os_exchange_data_provider.h" #include "ui/base/x/x11_util.h" #include "ui/events/event_utils.h" +#include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h" -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/widget/widget.h" +#include "ui/platform_window/platform_window_init_properties.h" +#include "ui/platform_window/x11/x11_window.h" -namespace views { +#if BUILDFLAG(IS_CHROMEOS_ASH) +#include "ui/base/dragdrop/os_exchange_data_provider_non_backed.h" +#else +#include "ui/base/dragdrop/os_exchange_data_provider_x11.h" +#endif + +namespace ui { namespace { using ::ui::mojom::DragOperation; @@ -81,26 +82,26 @@ std::vector<x11::ClientMessageEvent> events_; }; -// An implementation of ui::X11MoveLoop where RunMoveLoop() always starts the +// An implementation of X11MoveLoop where RunMoveLoop() always starts the // move loop. -class TestMoveLoop : public ui::X11MoveLoop { +class TestMoveLoop : public X11MoveLoop { public: - explicit TestMoveLoop(ui::X11MoveLoopDelegate* delegate); + explicit TestMoveLoop(X11MoveLoopDelegate* delegate); ~TestMoveLoop() override; // Returns true if the move loop is running. bool IsRunning() const; - // ui::X11MoveLoop: + // X11MoveLoop: bool RunMoveLoop(bool can_grab_pointer, - scoped_refptr<ui::X11Cursor> old_cursor, - scoped_refptr<ui::X11Cursor> new_cursor) override; - void UpdateCursor(scoped_refptr<ui::X11Cursor> cursor) override; + scoped_refptr<X11Cursor> old_cursor, + scoped_refptr<X11Cursor> new_cursor) override; + void UpdateCursor(scoped_refptr<X11Cursor> cursor) override; void EndMoveLoop() override; private: // Not owned. - ui::X11MoveLoopDelegate* delegate_; + X11MoveLoopDelegate* delegate_; // Ends the move loop. base::OnceClosure quit_closure_; @@ -109,12 +110,11 @@ }; // Implementation of XDragDropClient which short circuits FindWindowFor(). -class SimpleTestDragDropClient : public aura::client::DragDropClient, - public ui::XDragDropClient, - public ui::XDragDropClient::Delegate, - public ui::X11MoveLoopDelegate { +class SimpleTestDragDropClient : public XDragDropClient, + public XDragDropClient::Delegate, + public X11MoveLoopDelegate { public: - explicit SimpleTestDragDropClient(aura::Window*); + explicit SimpleTestDragDropClient(X11Window* window); SimpleTestDragDropClient(const SimpleTestDragDropClient&) = delete; SimpleTestDragDropClient& operator=(const SimpleTestDragDropClient&) = delete; @@ -127,21 +127,15 @@ // Returns true if the move loop is running. bool IsMoveLoopRunning(); - // aura::client::DragDropClient: - DragOperation StartDragAndDrop(std::unique_ptr<ui::OSExchangeData> data, - aura::Window* root_window, - aura::Window* source_window, - const gfx::Point& screen_location, + // Starts the move loop. + DragOperation StartDragAndDrop(std::unique_ptr<OSExchangeData> data, + X11Window* source_window, int allowed_operations, - ui::mojom::DragEventSource source) override; - void DragCancel() override; - bool IsDragDropInProgress() override; - void AddObserver(aura::client::DragDropClientObserver* observer) override; - void RemoveObserver(aura::client::DragDropClientObserver* observer) override; + mojom::DragEventSource source); private: - // ui::XDragDropClient::Delegate: - std::unique_ptr<ui::XTopmostWindowFinder> CreateWindowFinder() override; + // XDragDropClient::Delegate: + std::unique_ptr<XTopmostWindowFinder> CreateWindowFinder() override; int UpdateDrag(const gfx::Point& screen_point) override; void UpdateCursor(DragOperation negotiated_operation) override; void OnBeginForeignDrag(x11::Window window) override; @@ -153,15 +147,14 @@ // XDragDropClient: x11::Window FindWindowFor(const gfx::Point& screen_point) override; - // ui::X11MoveLoopDelegate: + // X11MoveLoopDelegate: void OnMouseMovement(const gfx::Point& screen_point, int flags, base::TimeTicks event_time) override; void OnMouseReleased() override; void OnMoveLoopEnded() override; - std::unique_ptr<ui::X11MoveLoop> CreateMoveLoop( - ui::X11MoveLoopDelegate* delegate); + std::unique_ptr<X11MoveLoop> CreateMoveLoop(X11MoveLoopDelegate* delegate); // The x11::Window of the window which is simulated to be the topmost window. x11::Window target_window_ = x11::Window::None; @@ -181,7 +174,7 @@ static constexpr int kMouseMoveX = 100; static constexpr int kMouseMoveY = 200; - explicit TestDragDropClient(aura::Window* window); + explicit TestDragDropClient(X11Window* window); TestDragDropClient(const TestDragDropClient&) = delete; TestDragDropClient& operator=(const TestDragDropClient&) = delete; @@ -260,7 +253,7 @@ /////////////////////////////////////////////////////////////////////////////// // TestMoveLoop -TestMoveLoop::TestMoveLoop(ui::X11MoveLoopDelegate* delegate) +TestMoveLoop::TestMoveLoop(X11MoveLoopDelegate* delegate) : delegate_(delegate) {} TestMoveLoop::~TestMoveLoop() = default; @@ -270,8 +263,8 @@ } bool TestMoveLoop::RunMoveLoop(bool can_grab_pointer, - scoped_refptr<ui::X11Cursor> old_cursor, - scoped_refptr<ui::X11Cursor> new_cursor) { + scoped_refptr<X11Cursor> old_cursor, + scoped_refptr<X11Cursor> new_cursor) { is_running_ = true; base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); @@ -279,7 +272,7 @@ return true; } -void TestMoveLoop::UpdateCursor(scoped_refptr<ui::X11Cursor> cursor) {} +void TestMoveLoop::UpdateCursor(scoped_refptr<X11Cursor> cursor) {} void TestMoveLoop::EndMoveLoop() { if (is_running_) { @@ -292,11 +285,8 @@ /////////////////////////////////////////////////////////////////////////////// // SimpleTestDragDropClient -SimpleTestDragDropClient::SimpleTestDragDropClient(aura::Window* window) - : ui::XDragDropClient( - this, - static_cast<x11::Window>(window->GetHost()->GetAcceleratedWidget())) { -} +SimpleTestDragDropClient::SimpleTestDragDropClient(X11Window* window) + : XDragDropClient(this, static_cast<x11::Window>(window->GetWidget())) {} SimpleTestDragDropClient::~SimpleTestDragDropClient() = default; @@ -308,53 +298,34 @@ return loop_->IsRunning(); } -std::unique_ptr<ui::X11MoveLoop> SimpleTestDragDropClient::CreateMoveLoop( - ui::X11MoveLoopDelegate* delegate) { +std::unique_ptr<X11MoveLoop> SimpleTestDragDropClient::CreateMoveLoop( + X11MoveLoopDelegate* delegate) { loop_ = new TestMoveLoop(delegate); return base::WrapUnique(loop_); } DragOperation SimpleTestDragDropClient::StartDragAndDrop( - std::unique_ptr<ui::OSExchangeData> data, - aura::Window* root_window, - aura::Window* source_window, - const gfx::Point& screen_location, + std::unique_ptr<OSExchangeData> data, + X11Window* source_window, int allowed_operations, - ui::mojom::DragEventSource source) { + mojom::DragEventSource source) { InitDrag(allowed_operations, data.get()); auto loop = CreateMoveLoop(this); - // Windows has a specific method, DoDragDrop(), which performs the entire - // drag. We have to emulate this, so we spin off a nested runloop which will - // track all cursor movement and reroute events to a specific handler. - ui::CursorLoader cursor_loader; - ui::Cursor grabbing = ui::mojom::CursorType::kGrabbing; - cursor_loader.SetPlatformCursor(&grabbing); - auto last_cursor = source_window->GetHost()->last_cursor(); - loop_->RunMoveLoop(!source_window->HasCapture(), - ui::X11Cursor::FromPlatformCursor(last_cursor.platform()), - ui::X11Cursor::FromPlatformCursor(grabbing.platform())); + // Cursors are not set. Thus, pass nothing. + loop_->RunMoveLoop(!source_window->HasCapture(), {}, {}); auto resulting_operation = negotiated_operation(); CleanupDrag(); return resulting_operation; } -void SimpleTestDragDropClient::DragCancel() {} -bool SimpleTestDragDropClient::IsDragDropInProgress() { - return false; -} -void SimpleTestDragDropClient::AddObserver( - aura::client::DragDropClientObserver* observer) {} -void SimpleTestDragDropClient::RemoveObserver( - aura::client::DragDropClientObserver* observer) {} - int SimpleTestDragDropClient::UpdateDrag(const gfx::Point& screen_point) { return 0; } -std::unique_ptr<ui::XTopmostWindowFinder> +std::unique_ptr<XTopmostWindowFinder> SimpleTestDragDropClient::CreateWindowFinder() { return {}; } @@ -393,11 +364,9 @@ /////////////////////////////////////////////////////////////////////////////// // TestDragDropClient -TestDragDropClient::TestDragDropClient(aura::Window* window) +TestDragDropClient::TestDragDropClient(X11Window* window) : SimpleTestDragDropClient(window), - source_window_( - static_cast<x11::Window>(window->GetHost()->GetAcceleratedWidget())) { -} + source_window_(static_cast<x11::Window>(window->GetWidget())) {} TestDragDropClient::~TestDragDropClient() = default; @@ -451,8 +420,8 @@ void TestDragDropClient::SetTopmostXWindowAndMoveMouse(x11::Window window) { SetTopmostXWindow(window); - HandleMouseMovement(gfx::Point(kMouseMoveX, kMouseMoveY), ui::EF_NONE, - ui::EventTimeForNow()); + HandleMouseMovement(gfx::Point(kMouseMoveX, kMouseMoveY), EF_NONE, + EventTimeForNow()); } void TestDragDropClient::SendXClientEvent( @@ -463,11 +432,54 @@ it->second->RecordEvent(event); } +class TestPlatformWindowDelegate : public PlatformWindowDelegate { + public: + TestPlatformWindowDelegate() = default; + TestPlatformWindowDelegate(const TestPlatformWindowDelegate&) = delete; + TestPlatformWindowDelegate& operator=(const TestPlatformWindowDelegate&) = + delete; + ~TestPlatformWindowDelegate() override = default; + + // PlatformWindowDelegate: + void OnBoundsChanged( + const PlatformWindowDelegate::BoundsChange& change) override {} + void OnDamageRect(const gfx::Rect& damaged_region) override {} + void DispatchEvent(Event* event) override {} + void OnCloseRequest() override {} + void OnClosed() override {} + void OnWindowStateChanged(PlatformWindowState old_state, + PlatformWindowState new_state) override {} + void OnLostCapture() override {} + void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) override {} + void OnWillDestroyAcceleratedWidget() override {} + void OnAcceleratedWidgetDestroyed() override {} + void OnActivationChanged(bool active) override {} + void OnMouseEnter() override {} + SkPath GetWindowMaskForWindowShapeInPixels() override { return {}; } +}; + +class TestOSExchangeDataProvideFactory + : public OSExchangeDataProviderFactoryOzone { + public: + TestOSExchangeDataProvideFactory() { SetInstance(this); } + ~TestOSExchangeDataProvideFactory() override = default; + + std::unique_ptr<OSExchangeDataProvider> CreateProvider() override { +#if BUILDFLAG(IS_CHROMEOS_ASH) + return std::make_unique<OSExchangeDataProviderNonBacked>(); +#else + return std::make_unique<OSExchangeDataProviderX11>(); +#endif + } +}; + } // namespace -class X11DragDropClientTest : public ViewsTestBase { +class X11DragDropClientTest : public testing::Test { public: - X11DragDropClientTest() = default; + X11DragDropClientTest() + : task_env_(std::make_unique<base::test::TaskEnvironment>( + base::test::TaskEnvironment::MainThreadType::UI)) {} X11DragDropClientTest(const X11DragDropClientTest&) = delete; X11DragDropClientTest& operator=(const X11DragDropClientTest&) = delete; @@ -475,7 +487,7 @@ ~X11DragDropClientTest() override = default; DragOperation StartDragAndDrop() { - auto data(std::make_unique<ui::OSExchangeData>()); + auto data(std::make_unique<OSExchangeData>()); data->SetString(u"Test"); SkBitmap drag_bitmap; drag_bitmap.allocN32Pixels(10, 10); @@ -483,46 +495,43 @@ gfx::ImageSkia drag_image(gfx::ImageSkia::CreateFrom1xBitmap(drag_bitmap)); data->provider().SetDragImage(drag_image, gfx::Vector2d()); - return client_->StartDragAndDrop( - std::move(data), widget_->GetNativeWindow()->GetRootWindow(), - widget_->GetNativeWindow(), gfx::Point(), ui::DragDropTypes::DRAG_COPY, - ui::mojom::DragEventSource::kMouse); + return client_->StartDragAndDrop(std::move(data), window_.get(), + DragDropTypes::DRAG_COPY, + mojom::DragEventSource::kMouse); } - // ViewsTestBase: + // testing::Test: void SetUp() override { - set_native_widget_type(NativeWidgetType::kDesktop); + auto* connection = x11::Connection::Get(); + event_source_ = std::make_unique<X11EventSource>(connection); - ViewsTestBase::SetUp(); - // TODO(crbug.com/1096425): Once non-Ozone X11 is deprecated, re-work this. - if (features::IsUsingOzonePlatform()) - GTEST_SKIP(); + PlatformWindowInitProperties init_params(gfx::Rect(100, 100)); + init_params.type = PlatformWindowType::kWindow; + window_ = std::make_unique<X11Window>(&delegate_); + window_->Initialize(std::move(init_params)); + window_->Show(false); - // Create widget to initiate the drags. - widget_ = std::make_unique<Widget>(); - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(100, 100); - widget_->Init(std::move(params)); - widget_->Show(); - - client_ = std::make_unique<TestDragDropClient>(widget_->GetNativeWindow()); - // client_->Init(); + client_ = std::make_unique<TestDragDropClient>(window_.get()); } void TearDown() override { client_.reset(); - widget_.reset(); - ViewsTestBase::TearDown(); + window_.reset(); } TestDragDropClient* client() { return client_.get(); } private: + std::unique_ptr<base::test::TaskEnvironment> task_env_; + std::unique_ptr<X11EventSource> event_source_; + std::unique_ptr<TestDragDropClient> client_; - // The widget used to initiate drags. - std::unique_ptr<Widget> widget_; + TestOSExchangeDataProvideFactory data_exchange_provider_factory_; + TestPlatformWindowDelegate delegate_; + + // The window used to initiate drags. + std::unique_ptr<X11Window> window_; }; namespace { @@ -832,4 +841,4 @@ EXPECT_EQ(DragOperation::kNone, result); } -} // namespace views +} // namespace ui
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index 47b8a4f..df68074 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -1364,13 +1364,6 @@ "widget/desktop_aura/desktop_native_widget_aura_unittest.cc", "widget/desktop_widget_unittest.cc", ] - if (use_x11) { - sources += [ "widget/desktop_aura/x11_drag_drop_client_unittest.cc" ] - deps += [ - "//ui/base/x", - "//ui/base/x:test_support", - ] - } if (is_linux || is_chromeos || is_fuchsia) { sources += [ "widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc",
diff --git a/ui/views/controls/prefix_selector.cc b/ui/views/controls/prefix_selector.cc index 106d00f..a124aca 100644 --- a/ui/views/controls/prefix_selector.cc +++ b/ui/views/controls/prefix_selector.cc
@@ -171,7 +171,7 @@ return false; } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool PrefixSelector::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
diff --git a/ui/views/controls/prefix_selector.h b/ui/views/controls/prefix_selector.h index 5d0d925..8e770dd 100644 --- a/ui/views/controls/prefix_selector.h +++ b/ui/views/controls/prefix_selector.h
@@ -81,7 +81,7 @@ ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override;
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index 634c627..4e29f7c 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -1732,7 +1732,7 @@ return false; } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) // TODO(https://crbug.com/952355): Implement this method to support Korean IME // reconversion feature on native text fields (e.g. find bar). bool Textfield::SetCompositionFromExistingText(
diff --git a/ui/views/controls/textfield/textfield.h b/ui/views/controls/textfield/textfield.h index 81f66500..302512b1 100644 --- a/ui/views/controls/textfield/textfield.h +++ b/ui/views/controls/textfield/textfield.h
@@ -442,7 +442,7 @@ // Set whether the text should be used to improve typing suggestions. void SetShouldDoLearning(bool value) { should_do_learning_ = value; } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override;
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 185d42c..9a8a5a4 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -3075,7 +3075,7 @@ EXPECT_EQ(composed_text_length, static_cast<uint32_t>(0)); } -#if defined(OS_WIN) || defined(OS_CHROMEOS) +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) // SetCompositionFromExistingText is only available on Windows and Chrome OS. TEST_F(TextfieldTest, SetCompositionFromExistingTextTest) { InitTextfield();
diff --git a/url/OWNERS b/url/OWNERS index 2ecc933..7a82807 100644 --- a/url/OWNERS +++ b/url/OWNERS
@@ -3,4 +3,5 @@ csharrison@chromium.org dcheng@chromium.org mkwst@chromium.org +timothygu@chromium.org # NOTE: keep this in sync with lsc-owners-override@chromium.org owners
diff --git a/weblayer/BUILD.gn b/weblayer/BUILD.gn index 0be435c5..58cdb5d 100644 --- a/weblayer/BUILD.gn +++ b/weblayer/BUILD.gn
@@ -84,6 +84,7 @@ output_locales = locales source_patterns = [ "${root_gen_dir}/components/strings/components_locale_settings_", + "${root_gen_dir}/device/bluetooth/strings/bluetooth_strings_", "${root_gen_dir}/weblayer/components_chromium_strings_", "${root_gen_dir}/weblayer/components_strings_", ] @@ -91,6 +92,7 @@ ":generate_components_chromium_strings", ":generate_components_strings", "//components/strings:components_locale_settings", + "//device/bluetooth/strings", ] output_dir = "$root_out_dir/weblayer/locales" }
diff --git a/weblayer/app/content_main_delegate_impl.cc b/weblayer/app/content_main_delegate_impl.cc index bfb25c4..0a94f43 100644 --- a/weblayer/app/content_main_delegate_impl.cc +++ b/weblayer/app/content_main_delegate_impl.cc
@@ -198,10 +198,6 @@ #endif }; - // TODO(crbug.com/1057770): make Background Fetch work with WebLayer. - if (!BackgroundFetchDelegateFactory::IsEnabled()) - disabled_features.push_back(::features::kBackgroundFetch); - #if defined(OS_ANDROID) if (base::android::BuildInfo::GetInstance()->sdk_int() >= base::android::SDK_VERSION_OREO) {
diff --git a/weblayer/browser/android/javatests/BUILD.gn b/weblayer/browser/android/javatests/BUILD.gn index 81a33e7..82f31eea 100644 --- a/weblayer/browser/android/javatests/BUILD.gn +++ b/weblayer/browser/android/javatests/BUILD.gn
@@ -57,6 +57,7 @@ "//net/android:net_java_test_support", "//third_party/android_deps:android_support_v4_java", "//third_party/android_deps:espresso_java", + "//third_party/android_sdk:android_support_chromium_java", "//third_party/android_support_test_runner:rules_java", "//third_party/android_support_test_runner:runner_java", "//third_party/androidx:androidx_activity_activity_java",
diff --git a/weblayer/browser/android/javatests/skew/expectations.txt b/weblayer/browser/android/javatests/skew/expectations.txt index c509a94..3efaede 100644 --- a/weblayer/browser/android/javatests/skew/expectations.txt +++ b/weblayer/browser/android/javatests/skew/expectations.txt
@@ -5,7 +5,7 @@ # with versions less than or equal to $VERSION of the implementation. # # These lines are not comments! They define the set of known tags and other information. -# tags: [ client_lte_91 client_lte_94 ] +# tags: [ client_lte_91 client_lte_94 client_lte_95 ] # 'all' disables the test from any skew test. # tags: [ all ] # results: [ Skip ] @@ -36,7 +36,26 @@ crbug.com/1248183 [ all ] org.chromium.weblayer.test.TabTest#testRotationDoesntChangeVisibility [ Skip ] crbug.com/1248187 [ all ] org.chromium.weblayer.test.FindInPageTest#testHideOnNewTab [ Skip ] - +# Chrome changes broke some test infrastructure, so tests are only artificially +# broken - the behavior under test has not changed. +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentAfterRedirectInBackgroundTabLaunchedWhenBackgroundLaunchesAllowed [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentAfterRedirectLaunched [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentInNewTabLaunchedOnLinkClick [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentInSameTabLaunchedOnLinkClick [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentNavigationParamSetOnIntentLaunchViaLinkClick [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentNavigationParamSetOnNavigationsToIntents [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentViaOnLoadLaunched [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithFallbackUrlAfterRedirectLaunched [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBackgroundTabLaunchedWhenBackgroundLaunchesAllowed [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBrowserStartupInIncognitoBlockedWhenBackgroundLaunchesAllowedAndUserForbids [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBrowserStartupInIncognitoLaunchedWhenBackgroundLaunchesAllowedAndUserConsents [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBrowserStartupInIncognitoWithEmbedderPresentingWarningDialogBlockedWhenBackgroundLaunchesAllowedAndUserForbids [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBrowserStartupInIncognitoWithEmbedderPresentingWarningDialogLaunchedWhenBackgroundLaunchesAllowedAndUserConsents [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectInBrowserStartupLaunchedWhenBackgroundLaunchesAllowed [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testExternalIntentWithNoRedirectLaunched [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testUserClicksLinkToPageWithExternalIntentLaunchedViaOnLoad [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.ExternalNavigationTest#testUserDecidingExternalIntentNavigationParamSetOnNavigationsToIntentsInIncognito [ Skip ] +crbug.com/1249962 [ client_lte_95 ] org.chromium.weblayer.test.NavigationTest#testIsKnownProtocol [ Skip ] # Bulk disable to get bot green. crbug.com/1191751 [ all ] org.chromium.weblayer.test.InputTypesTest* [ Skip ]
diff --git a/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/ExternalNavigationTest.java b/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/ExternalNavigationTest.java index 8d9df69..0900568 100644 --- a/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/ExternalNavigationTest.java +++ b/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/ExternalNavigationTest.java
@@ -12,11 +12,11 @@ import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; -import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.support.test.InstrumentationRegistry; import androidx.annotation.NonNull; import androidx.test.filters.SmallTest; @@ -49,17 +49,6 @@ public InstrumentationActivityTestRule mActivityTestRule = new InstrumentationActivityTestRule(); - /** - * A dummy activity that claims to handle "weblayer://weblayertest". - */ - public static class DummyActivityForSpecialScheme extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - finish(); - } - } - private static final boolean EXPECT_NAVIGATION_COMPLETION = true; private static final boolean EXPECT_NAVIGATION_FAILURE = false; private static final boolean RESULTS_IN_EXTERNAL_INTENT = true; @@ -77,20 +66,21 @@ // The package is not specified in the intent that gets created when navigating to the special // scheme. private static final String INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_PACKAGE = null; - private static final String INTENT_TO_CHROME_DATA_CONTENT = + private static final String INTENT_TO_SELF_DATA_CONTENT = "play.google.com/store/apps/details?id=com.facebook.katana/"; - private static final String INTENT_TO_CHROME_SCHEME = "https"; - private static final String INTENT_TO_CHROME_DATA_STRING = - INTENT_TO_CHROME_SCHEME + "://" + INTENT_TO_CHROME_DATA_CONTENT; - private static final String INTENT_TO_CHROME_ACTION = "android.intent.action.VIEW"; - private static final String INTENT_TO_CHROME_PACKAGE = "com.android.chrome"; + private static final String INTENT_TO_SELF_SCHEME = "https"; + private static final String INTENT_TO_SELF_DATA_STRING = + INTENT_TO_SELF_SCHEME + "://" + INTENT_TO_SELF_DATA_CONTENT; + private static final String INTENT_TO_SELF_ACTION = "android.intent.action.VIEW"; + private static final String INTENT_TO_SELF_PACKAGE = + InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageName(); - // An intent that opens Chrome to view a specified URL. Note that the "end" is left off to allow - // appending extras when constructing URLs. - private static final String INTENT_TO_CHROME = "intent://" + INTENT_TO_CHROME_DATA_CONTENT - + "#Intent;scheme=" + INTENT_TO_CHROME_SCHEME + ";action=" + INTENT_TO_CHROME_ACTION - + ";package=" + INTENT_TO_CHROME_PACKAGE + ";"; - private static final String INTENT_TO_CHROME_URL = INTENT_TO_CHROME + "end"; + // An intent that opens the test app to view a specified URL. Note that the "end" is left off to + // allow appending extras when constructing URLs. + private static final String INTENT_TO_SELF = "intent://" + INTENT_TO_SELF_DATA_CONTENT + + "#Intent;scheme=" + INTENT_TO_SELF_SCHEME + ";action=" + INTENT_TO_SELF_ACTION + + ";package=" + INTENT_TO_SELF_PACKAGE + ";"; + private static final String INTENT_TO_SELF_URL = INTENT_TO_SELF + "end"; // An intent URL that gets rejected as malformed. private static final String MALFORMED_INTENT_URL = "intent://garbage;end"; @@ -100,33 +90,33 @@ private static final String NON_RESOLVABLE_INTENT = "intent://dummy.com/#Intent;scheme=https;action=android.intent.action.VIEW;package=com.missing.app;"; - private static final String LINK_WITH_INTENT_TO_CHROME_IN_SAME_TAB_FILE = - "link_with_intent_to_chrome_in_same_tab.html"; - private static final String LINK_WITH_INTENT_TO_CHROME_IN_NEW_TAB_FILE = - "link_with_intent_to_chrome_in_new_tab.html"; + private static final String LINK_WITH_INTENT_TO_SELF_IN_SAME_TAB_FILE = + "link_with_intent_to_package_in_same_tab.html#" + INTENT_TO_SELF_PACKAGE; + private static final String LINK_WITH_INTENT_TO_SELF_IN_NEW_TAB_FILE = + "link_with_intent_to_package_in_new_tab.html#" + INTENT_TO_SELF_PACKAGE; private static final String PAGE_THAT_INTENTS_TO_CHROME_ON_LOAD_FILE = - "page_that_intents_to_chrome_on_load.html"; + "page_that_intents_to_package_on_load.html#" + INTENT_TO_SELF_PACKAGE; private static final String LINK_TO_PAGE_THAT_INTENTS_TO_CHROME_ON_LOAD_FILE = - "link_to_page_that_intents_to_chrome_on_load.html"; + "link_to_page_that_intents_to_package_on_load.html#" + INTENT_TO_SELF_PACKAGE; // The test server handles "echo" with a response containing "Echo" :). private final String mTestServerSiteUrl = mActivityTestRule.getTestServer().getURL("/echo"); private final String mTestServerSiteFallbackUrlExtra = "S.browser_fallback_url=" + android.net.Uri.encode(mTestServerSiteUrl) + ";"; - private final String mIntentToChromeWithFallbackUrl = - INTENT_TO_CHROME + mTestServerSiteFallbackUrlExtra + "end"; + private final String mIntentToSelfWithFallbackUrl = + INTENT_TO_SELF + mTestServerSiteFallbackUrlExtra + "end"; private final String mNonResolvableIntentWithFallbackUrl = NON_RESOLVABLE_INTENT + mTestServerSiteFallbackUrlExtra + "end"; private final String mRedirectToCustomSchemeUrlWithDefaultExternalHandler = mActivityTestRule.getTestServer().getURL( "/server-redirect?" + CUSTOM_SCHEME_URL_WITH_DEFAULT_EXTERNAL_HANDLER); - private final String mRedirectToIntentToChromeURL = - mActivityTestRule.getTestServer().getURL("/server-redirect?" + INTENT_TO_CHROME_URL); + private final String mRedirectToIntentToSelfURL = + mActivityTestRule.getTestServer().getURL("/server-redirect?" + INTENT_TO_SELF_URL); private final String mNonResolvableIntentWithFallbackUrlThatLaunchesIntent = NON_RESOLVABLE_INTENT + "S.browser_fallback_url=" - + android.net.Uri.encode(mRedirectToIntentToChromeURL) + ";end"; + + android.net.Uri.encode(mRedirectToIntentToSelfURL) + ";end"; private class IntentInterceptor implements InstrumentationActivity.IntentInterceptor { public Intent mLastIntent; @@ -276,10 +266,10 @@ // Navigate directly to an intent in the background and verify that the intent is not // launched. - NavigationWaiter waiter = new NavigationWaiter(INTENT_TO_CHROME_URL, backgroundTab, + NavigationWaiter waiter = new NavigationWaiter(INTENT_TO_SELF_URL, backgroundTab, /*expectFailure=*/true, /*waitForPaint=*/false); TestThreadUtils.runOnUiThreadBlocking(() -> { - backgroundTab.getNavigationController().navigate(Uri.parse(INTENT_TO_CHROME_URL)); + backgroundTab.getNavigationController().navigate(Uri.parse(INTENT_TO_SELF_URL)); }); waiter.waitForNavigation(); @@ -321,7 +311,7 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); backgroundTab.getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_SELF_URL), navigateParamsBuilder.build()); }); intentInterceptor.waitForIntent(); @@ -330,9 +320,9 @@ // navigation in the background tab. Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); int numNavigationsInBackgroundTab = TestThreadUtils.runOnUiThreadBlocking( () -> { return backgroundTab.getNavigationController().getNavigationListSize(); }); @@ -357,11 +347,10 @@ // Perform a navigation that redirects to an intent in the background and verify that the // intent is not launched. - NavigationWaiter waiter = new NavigationWaiter(INTENT_TO_CHROME_URL, backgroundTab, + NavigationWaiter waiter = new NavigationWaiter(INTENT_TO_SELF_URL, backgroundTab, /*expectFailure=*/true, /*waitForPaint=*/false); TestThreadUtils.runOnUiThreadBlocking(() -> { - backgroundTab.getNavigationController().navigate( - Uri.parse(mRedirectToIntentToChromeURL)); + backgroundTab.getNavigationController().navigate(Uri.parse(mRedirectToIntentToSelfURL)); }); waiter.waitForNavigation(); @@ -403,7 +392,7 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); backgroundTab.getNavigationController().navigate( - Uri.parse(mRedirectToIntentToChromeURL), navigateParamsBuilder.build()); + Uri.parse(mRedirectToIntentToSelfURL), navigateParamsBuilder.build()); }); intentInterceptor.waitForIntent(); @@ -412,9 +401,9 @@ // navigation in the background tab. Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); int numNavigationsInBackgroundTab = TestThreadUtils.runOnUiThreadBlocking( () -> { return backgroundTab.getNavigationController().getNavigationListSize(); }); @@ -434,7 +423,7 @@ NavigationCallback navigationCallback = new NavigationCallback() { @Override public void onNavigationFailed(Navigation navigation) { - if (navigation.getUri().toString().equals(INTENT_TO_CHROME_URL)) { + if (navigation.getUri().toString().equals(INTENT_TO_SELF_URL)) { onNavigationFailedCallbackHelper.notifyCalled(); } } @@ -451,7 +440,7 @@ browser.getActiveTab().getNavigationController().registerNavigationCallback( navigationCallback); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL)); + Uri.parse(INTENT_TO_SELF_URL)); } }); @@ -508,7 +497,7 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_SELF_URL), navigateParamsBuilder.build()); } }); @@ -518,9 +507,9 @@ intentInterceptor.waitForIntent(); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); // ...the tab created for the initial navigation should be closed... onTabRemovedCallbackHelper.waitForFirst(); @@ -548,7 +537,7 @@ NavigationCallback navigationCallback = new NavigationCallback() { @Override public void onNavigationFailed(Navigation navigation) { - if (navigation.getUri().toString().equals(INTENT_TO_CHROME_URL)) { + if (navigation.getUri().toString().equals(INTENT_TO_SELF_URL)) { onNavigationFailedCallbackHelper.notifyCalled(); } } @@ -564,7 +553,7 @@ browser.getActiveTab().getNavigationController().registerNavigationCallback( navigationCallback); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL)); + Uri.parse(INTENT_TO_SELF_URL)); } }); @@ -626,7 +615,7 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_SELF_URL), navigateParamsBuilder.build()); } }); @@ -645,9 +634,9 @@ intentInterceptor.waitForIntent(); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); // ...the tab created for the initial navigation should be closed... onTabRemovedCallbackHelper.waitForFirst(); @@ -680,11 +669,13 @@ @Override public void onNavigationStarted(Navigation navigation) { // There should be no additional navigations after the initial one. - Assert.assertEquals(INTENT_TO_CHROME_URL, navigation.getUri().toString()); + Assert.assertEquals(INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING, + navigation.getUri().toString()); } @Override public void onNavigationFailed(Navigation navigation) { - if (navigation.getUri().toString().equals(INTENT_TO_CHROME_URL)) { + if (navigation.getUri().toString().equals( + INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING)) { onNavigationToIntentFailedCallbackHelper.notifyCalled(); } } @@ -703,7 +694,8 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING), + navigateParamsBuilder.build()); } }); @@ -775,7 +767,7 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_SELF_URL), navigateParamsBuilder.build()); } }); @@ -798,9 +790,9 @@ intentInterceptor.waitForIntent(); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); // ...the tab created for the initial navigation should be closed... onTabRemovedCallbackHelper.waitForFirst(); @@ -833,11 +825,13 @@ @Override public void onNavigationStarted(Navigation navigation) { // There should be no additional navigations after the initial one. - Assert.assertEquals(INTENT_TO_CHROME_URL, navigation.getUri().toString()); + Assert.assertEquals(INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING, + navigation.getUri().toString()); } @Override public void onNavigationFailed(Navigation navigation) { - if (navigation.getUri().toString().equals(INTENT_TO_CHROME_URL)) { + if (navigation.getUri().toString().equals( + INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING)) { onNavigationToIntentFailedCallbackHelper.notifyCalled(); } } @@ -860,7 +854,8 @@ NavigateParams.Builder navigateParamsBuilder = new NavigateParams.Builder(); navigateParamsBuilder.allowIntentLaunchesInBackground(); browser.getActiveTab().getNavigationController().navigate( - Uri.parse(INTENT_TO_CHROME_URL), navigateParamsBuilder.build()); + Uri.parse(INTENT_TO_DUMMY_ACTIVITY_FOR_SPECIAL_SCHEME_DATA_STRING), + navigateParamsBuilder.build()); } }); @@ -913,7 +908,7 @@ Tab tab = mActivityTestRule.getActivity().getTab(); TestThreadUtils.runOnUiThreadBlocking( - () -> { tab.getNavigationController().navigate(Uri.parse(INTENT_TO_CHROME_URL)); }); + () -> { tab.getNavigationController().navigate(Uri.parse(INTENT_TO_SELF_URL)); }); intentInterceptor.waitForIntent(); @@ -921,9 +916,9 @@ Assert.assertEquals(ABOUT_BLANK_URL, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -957,12 +952,12 @@ IntentInterceptor intentInterceptor = new IntentInterceptor(); activity.setIntentInterceptor(intentInterceptor); - navigateAndCheckExternalIntentParams(INTENT_TO_CHROME_URL, EXPECT_NAVIGATION_FAILURE, + navigateAndCheckExternalIntentParams(INTENT_TO_SELF_URL, EXPECT_NAVIGATION_FAILURE, RESULTS_IN_EXTERNAL_INTENT, DOESNT_RESULT_IN_USER_DECIDING_EXTERNAL_INTENT); - navigateAndCheckExternalIntentParams(mIntentToChromeWithFallbackUrl, + navigateAndCheckExternalIntentParams(mIntentToSelfWithFallbackUrl, EXPECT_NAVIGATION_FAILURE, RESULTS_IN_EXTERNAL_INTENT, DOESNT_RESULT_IN_USER_DECIDING_EXTERNAL_INTENT); - navigateAndCheckExternalIntentParams(mRedirectToIntentToChromeURL, INTENT_TO_CHROME_URL, + navigateAndCheckExternalIntentParams(mRedirectToIntentToSelfURL, INTENT_TO_SELF_URL, EXPECT_NAVIGATION_FAILURE, RESULTS_IN_EXTERNAL_INTENT, DOESNT_RESULT_IN_USER_DECIDING_EXTERNAL_INTENT); navigateAndCheckExternalIntentParams(mRedirectToCustomSchemeUrlWithDefaultExternalHandler, @@ -994,7 +989,7 @@ extras.putBoolean(InstrumentationActivity.EXTRA_IS_INCOGNITO, true); mActivityTestRule.launchShellWithUrl(ABOUT_BLANK_URL, extras); - navigateAndCheckExternalIntentParams(INTENT_TO_CHROME_URL, EXPECT_NAVIGATION_FAILURE, + navigateAndCheckExternalIntentParams(INTENT_TO_SELF_URL, EXPECT_NAVIGATION_FAILURE, DOESNT_RESULT_IN_EXTERNAL_INTENT, RESULTS_IN_USER_DECIDING_EXTERNAL_INTENT); } @@ -1017,7 +1012,7 @@ NavigationCallback navigationCallback = new NavigationCallback() { @Override public void onNavigationFailed(Navigation navigation) { - Assert.assertEquals(INTENT_TO_CHROME_URL, navigation.getUri().toString()); + Assert.assertEquals(INTENT_TO_SELF_URL, navigation.getUri().toString()); Assert.assertEquals(true, navigation.wasIntentLaunched()); Assert.assertEquals(false, navigation.isUserDecidingIntentLaunch()); @@ -1030,7 +1025,7 @@ // Navigate to a URL that has a link to an intent, click on the link, and verify via the // callback that the navigation to the intent fails with the expected state set. - String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_CHROME_IN_SAME_TAB_FILE); + String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_SELF_IN_SAME_TAB_FILE); mActivityTestRule.navigateAndWait(url); mActivityTestRule.executeScriptSync( "document.onclick = function() {document.getElementById('link').click()}", @@ -1059,7 +1054,7 @@ Tab tab = mActivityTestRule.getActivity().getTab(); TestThreadUtils.runOnUiThreadBlocking(() -> { - tab.getNavigationController().navigate(Uri.parse(mRedirectToIntentToChromeURL)); + tab.getNavigationController().navigate(Uri.parse(mRedirectToIntentToSelfURL)); }); intentInterceptor.waitForIntent(); @@ -1068,9 +1063,9 @@ Assert.assertEquals(ABOUT_BLANK_URL, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -1118,7 +1113,7 @@ IntentInterceptor intentInterceptor = new IntentInterceptor(); activity.setIntentInterceptor(intentInterceptor); - String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_CHROME_IN_SAME_TAB_FILE); + String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_SELF_IN_SAME_TAB_FILE); mActivityTestRule.navigateAndWait(url); @@ -1134,9 +1129,9 @@ Assert.assertEquals(url, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -1153,7 +1148,7 @@ IntentInterceptor intentInterceptor = new IntentInterceptor(); activity.setIntentInterceptor(intentInterceptor); - String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_CHROME_IN_NEW_TAB_FILE); + String url = mActivityTestRule.getTestDataURL(LINK_WITH_INTENT_TO_SELF_IN_NEW_TAB_FILE); mActivityTestRule.navigateAndWait(url); @@ -1191,9 +1186,9 @@ intentInterceptor.waitForIntent(); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); // (3) And finally the new tab should be closed. onTabRemovedCallbackHelper.waitForFirst(); @@ -1224,7 +1219,7 @@ activity.setIntentInterceptor(intentInterceptor); String url = mActivityTestRule.getTestServer().getURL( - "/server-redirect?" + mIntentToChromeWithFallbackUrl); + "/server-redirect?" + mIntentToSelfWithFallbackUrl); Tab tab = mActivityTestRule.getActivity().getTab(); TestThreadUtils.runOnUiThreadBlocking( @@ -1236,9 +1231,9 @@ Assert.assertEquals(ABOUT_BLANK_URL, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -1324,7 +1319,7 @@ () -> { tab.getNavigationController().navigate(Uri.parse(url)); }); NavigationWaiter waiter = new NavigationWaiter( - INTENT_TO_CHROME_URL, tab, /*expectFailure=*/true, /*waitForPaint=*/false); + INTENT_TO_SELF_URL, tab, /*expectFailure=*/true, /*waitForPaint=*/false); waiter.waitForNavigation(); Assert.assertNull(intentInterceptor.mLastIntent); @@ -1365,9 +1360,9 @@ Assert.assertEquals(initialUrl, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -1416,9 +1411,9 @@ Assert.assertEquals(url, mActivityTestRule.getCurrentDisplayUrl()); Intent intent = intentInterceptor.mLastIntent; Assert.assertNotNull(intent); - Assert.assertEquals(INTENT_TO_CHROME_PACKAGE, intent.getPackage()); - Assert.assertEquals(INTENT_TO_CHROME_ACTION, intent.getAction()); - Assert.assertEquals(INTENT_TO_CHROME_DATA_STRING, intent.getDataString()); + Assert.assertEquals(INTENT_TO_SELF_PACKAGE, intent.getPackage()); + Assert.assertEquals(INTENT_TO_SELF_ACTION, intent.getAction()); + Assert.assertEquals(INTENT_TO_SELF_DATA_STRING, intent.getDataString()); } /** @@ -1442,7 +1437,7 @@ }); NavigationWaiter waiter = new NavigationWaiter( - INTENT_TO_CHROME_URL, tab, /*expectFailure=*/true, /*waitForPaint=*/false); + INTENT_TO_SELF_URL, tab, /*expectFailure=*/true, /*waitForPaint=*/false); waiter.waitForNavigation(); Assert.assertNull(intentInterceptor.mLastIntent);
diff --git a/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/NavigationTest.java b/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/NavigationTest.java index 86317ab7..8d01e771 100644 --- a/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/NavigationTest.java +++ b/weblayer/browser/android/javatests/src/org/chromium/weblayer/test/NavigationTest.java
@@ -84,9 +84,10 @@ // A URL with a custom scheme/host that is handled by WebLayer Shell. private static final String CUSTOM_SCHEME_URL_WITH_DEFAULT_EXTERNAL_HANDLER = "weblayer://weblayertest/intent"; - // An intent that opens Chrome to view a specified URL. - private static final String INTENT_TO_CHROME_URL = - "intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=com.android.chrome;end"; + // An intent that sends an url with a custom scheme that is handled by WebLayer Shell. + private static final String INTENT_TO_CUSTOM_SCHEME_URL = + "intent://weblayertest/intent#Intent;scheme=weblayer;" + + "action=android.intent.action.VIEW;end"; // An IntentInterceptor that simply drops intents to ensure that intent launches don't interfere // with running of tests. @@ -762,7 +763,7 @@ assertEquals(true, mCallback.onCompletedCallback.isKnownProtocol()); // Test external protocol cases. - mActivityTestRule.navigateAndWaitForFailure(activity.getTab(), INTENT_TO_CHROME_URL, + mActivityTestRule.navigateAndWaitForFailure(activity.getTab(), INTENT_TO_CUSTOM_SCHEME_URL, /*waitForPaint=*/false); assertEquals(false, mCallback.onStartedCallback.isKnownProtocol()); assertEquals(false, mCallback.onFailedCallback.isKnownProtocol());
diff --git a/weblayer/browser/background_fetch/background_fetch_delegate_factory.cc b/weblayer/browser/background_fetch/background_fetch_delegate_factory.cc index c7077d371..b9d2ac3b 100644 --- a/weblayer/browser/background_fetch/background_fetch_delegate_factory.cc +++ b/weblayer/browser/background_fetch/background_fetch_delegate_factory.cc
@@ -19,18 +19,6 @@ namespace weblayer { // static -bool BackgroundFetchDelegateFactory::IsEnabled() { -#if defined(OS_ANDROID) - static bool enabled = GetApplicationMetadataAsBoolean( - "org.chromium.weblayer.ENABLE_BACKGROUND_FETCH", - /*defaultValue=*/false); - return enabled; -#else - return true; -#endif -} - -// static BackgroundFetchDelegateImpl* BackgroundFetchDelegateFactory::GetForBrowserContext( content::BrowserContext* context) {
diff --git a/weblayer/browser/background_fetch/background_fetch_delegate_factory.h b/weblayer/browser/background_fetch/background_fetch_delegate_factory.h index c8702cf..79b1b68 100644 --- a/weblayer/browser/background_fetch/background_fetch_delegate_factory.h +++ b/weblayer/browser/background_fetch/background_fetch_delegate_factory.h
@@ -16,9 +16,6 @@ class BackgroundFetchDelegateFactory : public BrowserContextKeyedServiceFactory { public: - // Returns whether the Background Fetch API should be enabled. - static bool IsEnabled(); - static BackgroundFetchDelegateImpl* GetForBrowserContext( content::BrowserContext* context); static BackgroundFetchDelegateFactory* GetInstance();
diff --git a/weblayer/browser/content_browser_client_impl.cc b/weblayer/browser/content_browser_client_impl.cc index b7203d5..e4510517 100644 --- a/weblayer/browser/content_browser_client_impl.cc +++ b/weblayer/browser/content_browser_client_impl.cc
@@ -128,6 +128,7 @@ #include "components/embedder_support/android/metrics/android_metrics_service_client.h" #include "components/media_router/browser/presentation/presentation_service_delegate_impl.h" // nogncheck #include "components/navigation_interception/intercept_navigation_delegate.h" +#include "components/permissions/bluetooth_delegate_impl.h" #include "components/safe_browsing/core/browser/realtime/policy_engine.h" // nogncheck #include "components/safe_browsing/core/browser/realtime/url_lookup_service.h" // nogncheck #include "components/safe_browsing/core/common/safe_browsing_prefs.h" @@ -139,6 +140,7 @@ #include "weblayer/browser/android/metrics/weblayer_metrics_navigation_throttle.h" #include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h" #include "weblayer/browser/android_descriptors.h" +#include "weblayer/browser/bluetooth/weblayer_bluetooth_delegate_impl_client.h" #include "weblayer/browser/browser_context_impl.h" #include "weblayer/browser/devtools_manager_delegate_android.h" #include "weblayer/browser/http_auth_handler_impl.h" @@ -1175,6 +1177,14 @@ return true; } +content::BluetoothDelegate* ContentBrowserClientImpl::GetBluetoothDelegate() { + if (!bluetooth_delegate_) { + bluetooth_delegate_ = std::make_unique<permissions::BluetoothDelegateImpl>( + std::make_unique<WebLayerBluetoothDelegateImplClient>()); + } + return bluetooth_delegate_.get(); +} + #endif // OS_ANDROID content::SpeechRecognitionManagerDelegate*
diff --git a/weblayer/browser/content_browser_client_impl.h b/weblayer/browser/content_browser_client_impl.h index f092448..4f7ed021 100644 --- a/weblayer/browser/content_browser_client_impl.h +++ b/weblayer/browser/content_browser_client_impl.h
@@ -28,6 +28,10 @@ class SiteForCookies; } // namespace net +namespace permissions { +class BluetoothDelegateImpl; +} + namespace weblayer { class FeatureListCreator; @@ -214,6 +218,7 @@ std::unique_ptr<content::TtsEnvironmentAndroid> CreateTtsEnvironmentAndroid() override; bool ShouldObserveContainerViewLocationForDialogOverlays() override; + content::BluetoothDelegate* GetBluetoothDelegate() override; #endif // OS_ANDROID content::SpeechRecognitionManagerDelegate* CreateSpeechRecognitionManagerDelegate() override; @@ -232,6 +237,8 @@ #if defined(OS_ANDROID) SafeBrowsingService* GetSafeBrowsingService(); + + std::unique_ptr<permissions::BluetoothDelegateImpl> bluetooth_delegate_; #endif MainParams* params_;
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java index 6717c9d..967dab2 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java
@@ -14,7 +14,6 @@ import org.chromium.base.Callback; import org.chromium.base.Function; import org.chromium.base.PackageManagerUtils; -import org.chromium.components.embedder_support.util.UrlUtilities; import org.chromium.components.external_intents.ExternalNavigationDelegate; import org.chromium.components.external_intents.ExternalNavigationDelegate.StartActivityIfNeededResult; import org.chromium.components.external_intents.ExternalNavigationParams; @@ -78,17 +77,7 @@ assert !proxy : "|proxy| should be true only for instant apps, which WebLayer doesn't handle"; - boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(intent.toUri(0)); - boolean hasDefaultHandler = hasDefaultHandler(intent); - - // Match CCT's custom behavior of keeping http(s) URLs with no default handler in the app. - // TODO(blundell): If/when CCT eliminates its special handling of this case, eliminate it - // from WebLayer as well. - if (!isExternalProtocol && !hasDefaultHandler) { - return StartActivityIfNeededResult.HANDLED_WITHOUT_ACTIVITY_START; - } - - // Otherwise defer to ExternalNavigationHandler's default logic. + // Defer to ExternalNavigationHandler's default logic. return StartActivityIfNeededResult.DID_NOT_HANDLE; }
diff --git a/weblayer/browser/tab_impl.cc b/weblayer/browser/tab_impl.cc index 638f225..fdd9c38 100644 --- a/weblayer/browser/tab_impl.cc +++ b/weblayer/browser/tab_impl.cc
@@ -594,6 +594,16 @@ return std::make_unique<FaviconFetcherImpl>(web_contents_.get(), delegate); } +void TabImpl::SetTranslateTargetLanguage( + const std::string& translate_target_lang) { + translate::TranslateManager* translate_manager = + TranslateClientImpl::FromWebContents(web_contents()) + ->GetTranslateManager(); + translate_manager->SetPredefinedTargetLanguage( + translate_target_lang, + /*should_auto_translate=*/true); +} + #if !defined(OS_ANDROID) void TabImpl::AttachToView(views::WebView* web_view) { web_view->SetWebContents(web_contents_.get()); @@ -862,10 +872,7 @@ void TabImpl::SetTranslateTargetLanguage( JNIEnv* env, const base::android::JavaParamRef<jstring>& translate_target_lang) { - translate::TranslateManager* translate_manager = - TranslateClientImpl::FromWebContents(web_contents()) - ->GetTranslateManager(); - translate_manager->SetPredefinedTargetLanguage( + SetTranslateTargetLanguage( base::android::ConvertJavaStringToUTF8(env, translate_target_lang)); }
diff --git a/weblayer/browser/tab_impl.h b/weblayer/browser/tab_impl.h index 1b9e02f..43462d1 100644 --- a/weblayer/browser/tab_impl.h +++ b/weblayer/browser/tab_impl.h
@@ -230,6 +230,8 @@ const std::u16string& js_object_name) override; std::unique_ptr<FaviconFetcher> CreateFaviconFetcher( FaviconFetcherDelegate* delegate) override; + void SetTranslateTargetLanguage( + const std::string& translate_target_lang) override; #if !defined(OS_ANDROID) void AttachToView(views::WebView* web_view) override; #endif
diff --git a/weblayer/browser/translate_browsertest.cc b/weblayer/browser/translate_browsertest.cc index 6dea4d9..3d2ce9b 100644 --- a/weblayer/browser/translate_browsertest.cc +++ b/weblayer/browser/translate_browsertest.cc
@@ -553,6 +553,136 @@ #endif #if defined(OS_ANDROID) +// Test that translation occurs when a target language is set. +IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, + TranslationViaPredefinedTargetLanguage) { + auto* tab = static_cast<TabImpl*>(shell()->tab()); + auto* web_contents = tab->web_contents(); + auto* infobar_manager = + infobars::ContentInfoBarManager::FromWebContents(web_contents); + + SetTranslateScript(kTestValidScript); + + TranslateClientImpl* translate_client = GetTranslateClient(shell()); + + TestInfoBarManagerObserver infobar_observer; + infobar_manager->AddObserver(&infobar_observer); + + base::RunLoop run_loop; + infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure()); + + tab->SetTranslateTargetLanguage("ru"); + + // Navigate to a page in French and wait for the infobar to be added and + // autotranslation to occur. + ResetPageTranslationWaiter(); + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page.html")), shell()); + + run_loop.Run(); + + page_translation_waiter_->Wait(); + + EXPECT_EQ("fr", translate_client->GetLanguageState().source_language()); + EXPECT_FALSE(translate_client->GetLanguageState().translation_error()); + EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult()); + EXPECT_EQ("ru", translate_client->GetLanguageState().current_language()); + + // The translate infobar should still be present. + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + infobar_manager->RemoveObserver(&infobar_observer); +} +#endif + +#if defined(OS_ANDROID) +// Test that the infobar appears on pages in the user's locale iff a target +// language is set. +IN_PROC_BROWSER_TEST_F( + TranslateBrowserTest, + InfoBarAppearsForDefaultLanguageWhenPredefinedTargetLanguageIsSet) { + auto* tab = static_cast<TabImpl*>(shell()->tab()); + auto* web_contents = tab->web_contents(); + auto* infobar_manager = + infobars::ContentInfoBarManager::FromWebContents(web_contents); + + SetTranslateScript(kTestValidScript); + + TestInfoBarManagerObserver infobar_observer; + infobar_manager->AddObserver(&infobar_observer); + + // Navigate to a page in English: the infobar should not appear. + ResetPageTranslationWaiter(); + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/english_page.html")), shell()); + + // NOTE: There is no notification to wait for for the event of the infobar not + // showing. However, in practice the infobar is added synchronously, so if it + // were to be shown, this check would fail. + EXPECT_EQ(0u, infobar_manager->infobar_count()); + + // Set a target language, navigate again, and verify that the infobar now + // appears. + tab->SetTranslateTargetLanguage("ru"); + + base::RunLoop run_loop; + infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure()); + + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/english_page.html")), shell()); + + run_loop.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + infobar_manager->RemoveObserver(&infobar_observer); +} +#endif + +#if defined(OS_ANDROID) +// Test that when a predefined target language is set, the infobar does not +// appear on pages in that language. +IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, + InfoBarDoesNotAppearForPageInPredefinedTargetLanguage) { + auto* tab = static_cast<TabImpl*>(shell()->tab()); + auto* web_contents = tab->web_contents(); + auto* infobar_manager = + infobars::ContentInfoBarManager::FromWebContents(web_contents); + + SetTranslateScript(kTestValidScript); + + TestInfoBarManagerObserver infobar_observer; + infobar_manager->AddObserver(&infobar_observer); + + base::RunLoop run_loop; + infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure()); + + // Navigate to a page in French: the infobar should appear. + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page.html")), shell()); + + run_loop.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + // Set the target language to French. + tab->SetTranslateTargetLanguage("fr"); + + // Navigate again to a page in French: the infobar should not appear. + ResetPageTranslationWaiter(); + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page.html")), shell()); + + // NOTE: There is no notification to wait for for the event of the infobar not + // showing. However, in practice the infobar is added synchronously, so if it + // were to be shown, this check would fail. + EXPECT_EQ(0u, infobar_manager->infobar_count()); + + infobar_manager->RemoveObserver(&infobar_observer); +} +#endif + +#if defined(OS_ANDROID) // Test that the translation infobar stays present when the "never translate // language" item is clicked. Note that this behavior is intentionally different // from that of Chrome, where the infobar is removed in this case and a snackbar @@ -624,6 +754,61 @@ infobar_manager->RemoveObserver(&infobar_observer); } +#if defined(OS_ANDROID) +// Test that the infobar shows when a predefined target language is set even if +// the source language is in the "never translate" set. +IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, + PredefinedTargetLanguageOverridesLanguageBlocklist) { + auto* tab = static_cast<TabImpl*>(shell()->tab()); + auto* web_contents = tab->web_contents(); + auto* infobar_manager = + infobars::ContentInfoBarManager::FromWebContents(web_contents); + + SetTranslateScript(kTestValidScript); + + TranslateClientImpl* translate_client = GetTranslateClient(shell()); + + TestInfoBarManagerObserver infobar_observer; + infobar_manager->AddObserver(&infobar_observer); + + base::RunLoop run_loop; + infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure()); + + tab->SetTranslateTargetLanguage("ru"); + + // Navigate to a page in French and wait for the infobar to be added. + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page.html")), shell()); + + run_loop.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + auto* infobar = + static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0)); + TranslateTestBridge::ClickOverflowMenuItem( + infobar, + TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_LANGUAGE); + + // Since a predefined target language is set, the infobar should still be + // shown on a new navigation to a page in French even though it's blocklisted. + ResetLanguageDeterminationWaiter(); + base::RunLoop run_loop2; + infobar_observer.set_on_infobar_added_callback(run_loop2.QuitClosure()); + + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page2.html")), shell()); + language_determination_waiter_->Wait(); + EXPECT_EQ("fr", translate_client->GetLanguageState().source_language()); + + run_loop2.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + infobar_manager->RemoveObserver(&infobar_observer); +} +#endif + // Test that the translation infobar stays present when the "never translate // site" item is clicked. Note that this behavior is intentionally different // from that of Chrome, where the infobar is removed in this case and a snackbar @@ -686,6 +871,74 @@ infobar_manager->RemoveObserver(&infobar_observer); } +#if defined(OS_ANDROID) +// Test that the infobar shows when a predefined target language is set even if +// the site is in the "never translate" set. +IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, + PredefinedTargetLanguageOverridesSiteBlocklist) { + auto* tab = static_cast<TabImpl*>(shell()->tab()); + auto* web_contents = tab->web_contents(); + auto* infobar_manager = + infobars::ContentInfoBarManager::FromWebContents(web_contents); + + SetTranslateScript(kTestValidScript); + + TranslateClientImpl* translate_client = GetTranslateClient(shell()); + + TestInfoBarManagerObserver infobar_observer; + infobar_manager->AddObserver(&infobar_observer); + + base::RunLoop run_loop; + infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure()); + + tab->SetTranslateTargetLanguage("ru"); + + // Navigate and wait for the infobar to be added. + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page.html")), shell()); + + run_loop.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + // Blocklist the site. + auto* infobar = + static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0)); + TranslateTestBridge::ClickOverflowMenuItem( + infobar, TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_SITE); + + // Since a predefined target language is set, the infobar should still be + // shown on new navigations to this site even though the site is blocklisted. + ResetLanguageDeterminationWaiter(); + base::RunLoop run_loop2; + infobar_observer.set_on_infobar_added_callback(run_loop2.QuitClosure()); + + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/french_page2.html")), shell()); + language_determination_waiter_->Wait(); + EXPECT_EQ("fr", translate_client->GetLanguageState().source_language()); + + run_loop2.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + ResetLanguageDeterminationWaiter(); + base::RunLoop run_loop3; + infobar_observer.set_on_infobar_added_callback(run_loop3.QuitClosure()); + + NavigateAndWaitForCompletion( + GURL(embedded_test_server()->GetURL("/german_page.html")), shell()); + language_determination_waiter_->Wait(); + EXPECT_EQ("de", translate_client->GetLanguageState().source_language()); + + run_loop3.Run(); + + EXPECT_EQ(1u, infobar_manager->infobar_count()); + + infobar_manager->RemoveObserver(&infobar_observer); +} +#endif + // Parameterized to run tests on the "never translate language" and "never // translate site" menu items. class NeverTranslateMenuItemTranslateBrowserTest
diff --git a/weblayer/grit_strings_allowlist.txt b/weblayer/grit_strings_allowlist.txt index 9bcb3b82..6912e39 100644 --- a/weblayer/grit_strings_allowlist.txt +++ b/weblayer/grit_strings_allowlist.txt
@@ -13,6 +13,19 @@ IDS_BEFORERELOAD_MESSAGEBOX_TITLE IDS_BEFOREUNLOAD_APP_MESSAGEBOX_TITLE IDS_BEFOREUNLOAD_MESSAGEBOX_TITLE +IDS_BLUETOOTH_DEVICE_AUDIO +IDS_BLUETOOTH_DEVICE_CAR_AUDIO +IDS_BLUETOOTH_DEVICE_COMPUTER +IDS_BLUETOOTH_DEVICE_GAMEPAD +IDS_BLUETOOTH_DEVICE_JOYSTICK +IDS_BLUETOOTH_DEVICE_KEYBOARD +IDS_BLUETOOTH_DEVICE_KEYBOARD_MOUSE_COMBO +IDS_BLUETOOTH_DEVICE_MODEM +IDS_BLUETOOTH_DEVICE_MOUSE +IDS_BLUETOOTH_DEVICE_PHONE +IDS_BLUETOOTH_DEVICE_TABLET +IDS_BLUETOOTH_DEVICE_UNKNOWN +IDS_BLUETOOTH_DEVICE_VIDEO IDS_CANCEL IDS_CAPTIVE_PORTAL_BUTTON_OPEN_LOGIN_PAGE IDS_CAPTIVE_PORTAL_HEADING_WIFI
diff --git a/weblayer/public/java/AndroidManifest.xml b/weblayer/public/java/AndroidManifest.xml index 574dcf6..3d9617d 100644 --- a/weblayer/public/java/AndroidManifest.xml +++ b/weblayer/public/java/AndroidManifest.xml
@@ -12,6 +12,18 @@ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> + + <uses-permission-sdk-23 android:name="android.permission.BLUETOOTH"/> + <uses-permission-sdk-23 android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/> + <uses-permission-sdk-23 android:name="android.permission.BLUETOOTH_CONNECT"/> + <!-- + Bluetooth scanning is used to implement the Web Bluetooth API, which is + not intended to allow sites to derive location and so can accept a + filtered view of devices. + --> + <uses-permission-sdk-23 android:name="android.permission.BLUETOOTH_SCAN" + android:usesPermissionFlags="neverForLocation"/> + <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.INTERNET"/>
diff --git a/weblayer/public/java/org/chromium/weblayer/Tab.java b/weblayer/public/java/org/chromium/weblayer/Tab.java index 599eaf9..237b37d 100644 --- a/weblayer/public/java/org/chromium/weblayer/Tab.java +++ b/weblayer/public/java/org/chromium/weblayer/Tab.java
@@ -214,8 +214,13 @@ * Tab, the target language will be |targetLanguage|. Notes: * - |targetLanguage| should be specified as the language code (e.g., "de" for German). * - Passing an empty string causes behavior to revert to default. - * - Even with the target language specified, the translate UI will not trigger for pages in the - * user's locale. + * - Specifying a non-empty target language will also result in the following behaviors (all of + * which are intentional as part of the semantics of having a target language): + * - Translation is initiated automatically (note that the infobar UI is present) + * - Translation occurs even for languages/sites that the user has blocklisted + * - Translation occurs even for pages in the user's default locale + * - Translation does *not* occur nor is the infobar UI shown for pages in the specified + * target language */ public void setTranslateTargetLanguage(@NonNull String targetLanguage) { ThreadCheck.ensureOnUiThread();
diff --git a/weblayer/public/tab.h b/weblayer/public/tab.h index 1037bd0..704be91e 100644 --- a/weblayer/public/tab.h +++ b/weblayer/public/tab.h
@@ -124,6 +124,24 @@ virtual std::unique_ptr<FaviconFetcher> CreateFaviconFetcher( FaviconFetcherDelegate* delegate) = 0; + // Sets the target language for translation such that whenever the translate + // UI shows in this Tab, the target language will be |targetLanguage|. Notes: + // - |targetLanguage| should be specified as the language code (e.g., "de" for + // German). + // - Passing an empty string causes behavior to revert to default. + // - Specifying a non-empty target language will also result in the following + // behaviors (all of which are intentional as part of the semantics of + // having a target language): + // - Translation is initiated automatically (note that the infobar UI is + // present) + // - Translation occurs even for languages/sites that the user has + // blocklisted + // - Translation occurs even for pages in the user's default locale + // - Translation does *not* occur nor is the infobar UI shown for pages in + // the specified target language + virtual void SetTranslateTargetLanguage( + const std::string& translate_target_lang) = 0; + #if !defined(OS_ANDROID) // TODO: this isn't a stable API, so use it now for expediency in the C++ API, // but if we ever want to have backward or forward compatibility in C++ this
diff --git a/weblayer/shell/android/shell_apk/AndroidManifest.xml b/weblayer/shell/android/shell_apk/AndroidManifest.xml index b7a5d8a9..35457b3 100644 --- a/weblayer/shell/android/shell_apk/AndroidManifest.xml +++ b/weblayer/shell/android/shell_apk/AndroidManifest.xml
@@ -48,18 +48,26 @@ android:theme="@android:style/Theme.Holo.Light.NoActionBar"> </activity> <activity android:name="org.chromium.weblayer.test.ExternalNavigationTest$DummyActivityForSpecialScheme" - android:exported="true" > - <intent-filter> - <action android:name="android.intent.action.VIEW" /> - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.BROWSABLE" /> - <data android:host="weblayertest" android:scheme="weblayer" /> - </intent-filter> - </activity> + android:exported="true" > + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + <data android:host="weblayertest" android:scheme="weblayer" /> + </intent-filter> + </activity> - <!-- Enable BGF, which is still in development. Don't enable this in production apps. --> - <meta-data - android:name="org.chromium.weblayer.ENABLE_BACKGROUND_FETCH" android:value="true"/> + <activity android:name="org.chromium.weblayer.test.ExternalNavigationTest$DummyActivity" + android:exported="true" > + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="http" /> + <data android:scheme="https" /> + <data android:scheme="about" /> + <category android:name="android.intent.category.BROWSABLE" /> + </intent-filter> + </activity> <!-- Enable ADB logging of js logs (console.log). This is disabled by default because some websites log PII. -->
diff --git a/weblayer/test/data/link_to_page_that_intents_to_chrome_on_load.html b/weblayer/test/data/link_to_page_that_intents_to_chrome_on_load.html deleted file mode 100644 index d5e024b..0000000 --- a/weblayer/test/data/link_to_page_that_intents_to_chrome_on_load.html +++ /dev/null
@@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta name="viewport" - content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> -</head> -<body> - <a id='link' href='/weblayer/test/data/page_that_intents_to_chrome_on_load.html'> - Click to go to page that intents to Chrome on load -</a> -</body> -</html>
diff --git a/weblayer/test/data/link_to_page_that_intents_to_package_on_load.html b/weblayer/test/data/link_to_page_that_intents_to_package_on_load.html new file mode 100644 index 0000000..e31ef486 --- /dev/null +++ b/weblayer/test/data/link_to_page_that_intents_to_package_on_load.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" + content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> +</head> +<body> + <a id='link'> + <script type="text/javascript"> + document.getElementById('link').href = '/weblayer/test/data/page_that_intents_to_package_on_load.html' + window.location.hash; + </script> + Click to go to page that intents to the package specified in the URL hash on load +</a> +</body> +</html>
diff --git a/weblayer/test/data/link_with_intent_to_chrome_in_new_tab.html b/weblayer/test/data/link_with_intent_to_chrome_in_new_tab.html deleted file mode 100644 index 44994a17..0000000 --- a/weblayer/test/data/link_with_intent_to_chrome_in_new_tab.html +++ /dev/null
@@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta name="viewport" - content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> -</head> -<body> - <a id='link' target='_blank' href='intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=com.android.chrome;end'> - Click to intent to production Chrome in a new tab -</a> -</body> -</html>
diff --git a/weblayer/test/data/link_with_intent_to_chrome_in_same_tab.html b/weblayer/test/data/link_with_intent_to_chrome_in_same_tab.html deleted file mode 100644 index e442dc92..0000000 --- a/weblayer/test/data/link_with_intent_to_chrome_in_same_tab.html +++ /dev/null
@@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta name="viewport" - content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> -</head> -<body> - <a id='link' href='intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=com.android.chrome;end'> - Click to intent to production Chrome in this tab -</a> -</body> -</html>
diff --git a/weblayer/test/data/link_with_intent_to_package_in_new_tab.html b/weblayer/test/data/link_with_intent_to_package_in_new_tab.html new file mode 100644 index 0000000..5fc9711 --- /dev/null +++ b/weblayer/test/data/link_with_intent_to_package_in_new_tab.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" + content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> +</head> +<body> + <a id='link' target='_blank'> + Click to intent to the package specified in the URL hash in a new tab + </a> + <script type="text/javascript"> + document.getElementById('link').href = 'intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=' + window.location.href.split('#')[1] + ';end'; + </script> +</body> +</html>
diff --git a/weblayer/test/data/link_with_intent_to_package_in_same_tab.html b/weblayer/test/data/link_with_intent_to_package_in_same_tab.html new file mode 100644 index 0000000..0a9a240 --- /dev/null +++ b/weblayer/test/data/link_with_intent_to_package_in_same_tab.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" + content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> +</head> +<body> + <a id='link'> + Click to intent to the package specified in the URL hash in this tab + </a> + <script type="text/javascript"> + document.getElementById('link').href = 'intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=' + window.location.href.split('#')[1] + ';end'; + </script> +</body> +</html>
diff --git a/weblayer/test/data/page_that_intents_to_chrome_on_load.html b/weblayer/test/data/page_that_intents_to_chrome_on_load.html deleted file mode 100644 index 253dfbe..0000000 --- a/weblayer/test/data/page_that_intents_to_chrome_on_load.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta name="viewport" - content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> -</head> -<body> - <a id='link' href='intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=com.android.chrome;end'> - Click to intent to production Chrome in this tab -</a> -<script> - window.addEventListener("load", function() { - document.getElementById("link").click(); - }, false); -</script> -</body> -</html>
diff --git a/weblayer/test/data/page_that_intents_to_package_on_load.html b/weblayer/test/data/page_that_intents_to_package_on_load.html new file mode 100644 index 0000000..4875c03 --- /dev/null +++ b/weblayer/test/data/page_that_intents_to_package_on_load.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" + content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> +</head> +<body> + <a id='link'> + Click to intent to the package specified in the URL hash in this tab + </a> +<script> + document.getElementById('link').href = 'intent://play.google.com/store/apps/details?id=com.facebook.katana/#Intent;scheme=https;action=android.intent.action.VIEW;package=' + window.location.href.split('#')[1] + ';end'; + window.addEventListener("load", function() { + document.getElementById("link").click(); + }, false); +</script> +</body> +</html>